From 3f57327a1201c3140ff784a1a045c873711e8525 Mon Sep 17 00:00:00 2001 From: Flavio Renzi Date: Sat, 28 Nov 2026 23:41:16 +0100 Subject: [PATCH] Search PDF passages locally with optional embedding models Add shared extraction, exact/semantic/hybrid retrieval, verified optional model downloads and independent indexes in a lazy Electron utility process. Provide reader sidebar controls, model settings, indexing and passage navigation. Include retrieval tests, stable smoke setup, benchmark tooling, architecture and usage documentation, packaging and third-party notices. Keep local launcher changes outside this commit. --- .github/workflows/ci.yml | 1 + README.md | 10 + THIRD_PARTY_NOTICES.md | 18 + build/third-party/GPL-3.0.txt | 674 +++++++++++++ build/third-party/LGPL-3.0.txt | 165 +++ build/third-party/onnxruntime-LICENSE.txt | 21 + build/third-party/sqlite-vec-LICENSE-MIT.txt | 21 + docs/retrieval-benchmarks.md | 90 ++ docs/semantic-search.md | 119 +++ electron/main.cjs | 1 + electron/preload.cjs | 13 + electron/retrieval.cjs | 47 + electron/retrieval/download.cjs | 56 ++ electron/retrieval/models.json | 227 +++++ electron/retrieval/provider.cjs | 60 ++ electron/retrieval/store.cjs | 121 +++ electron/retrieval/text.cjs | 64 ++ electron/retrieval/worker.cjs | 256 +++++ package-lock.json | 998 ++++++++++++++++++- package.json | 30 +- scripts/benchmark-retrieval.mjs | 82 ++ scripts/screenshots.mjs | 2 +- scripts/smoke-retrieval.mjs | 235 +++++ scripts/smoke-test.mjs | 11 +- scripts/test-retrieval.cjs | 135 +++ src/AdvancedSearch.tsx | 168 ++++ src/App.tsx | 76 +- src/Dialogs.tsx | 1 + src/EmbeddingModels.tsx | 68 ++ src/SearchBar.tsx | 86 +- src/SearchResults.test.tsx | 4 +- src/SearchResults.tsx | 6 +- src/SettingsDialog.tsx | 9 +- src/desktop.d.ts | 1 + src/icons.tsx | 1 + src/retrieval.ts | 86 ++ src/styles.css | 67 +- 37 files changed, 3860 insertions(+), 170 deletions(-) create mode 100644 build/third-party/GPL-3.0.txt create mode 100644 build/third-party/LGPL-3.0.txt create mode 100644 build/third-party/onnxruntime-LICENSE.txt create mode 100644 build/third-party/sqlite-vec-LICENSE-MIT.txt create mode 100644 docs/retrieval-benchmarks.md create mode 100644 docs/semantic-search.md create mode 100644 electron/retrieval.cjs create mode 100644 electron/retrieval/download.cjs create mode 100644 electron/retrieval/models.json create mode 100644 electron/retrieval/provider.cjs create mode 100644 electron/retrieval/store.cjs create mode 100644 electron/retrieval/text.cjs create mode 100644 electron/retrieval/worker.cjs create mode 100644 scripts/benchmark-retrieval.mjs create mode 100644 scripts/smoke-retrieval.mjs create mode 100644 scripts/test-retrieval.cjs create mode 100644 src/AdvancedSearch.tsx create mode 100644 src/EmbeddingModels.tsx create mode 100644 src/retrieval.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 19e8f51..f4804d6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,6 +29,7 @@ jobs: - run: npm audit --audit-level=high - run: npm test - run: npm run test:chat-math + - run: npm run test:retrieval - run: npm run test:thumbnails - run: node --test scripts/test-word-files.cjs scripts/test-network-security.cjs scripts/test-release-build.mjs scripts/test-claude-path.cjs scripts/test-agy.cjs - run: node --test scripts/test-link-history.mjs scripts/test-text-direction.mjs diff --git a/README.md b/README.md index ef72e35..5f7769a 100644 --- a/README.md +++ b/README.md @@ -372,3 +372,13 @@ privately, see [SECURITY.md](SECURITY.md). [MIT](LICENSE). Folio includes third-party software under its own licenses; see [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). + +### Local semantic search (source build) + +The Semantic search toolbar icon (Ctrl+Shift+F) opens a dedicated sidebar for +local Exact, Semantic and Hybrid passage search. +Install an optional embedding model in Settings → Semantic Search, then index +the PDF. Indexes persist independently of annotations and reuse shared text when +models change. No model or inference service is needed for normal reading/find. +See [architecture and limitations](docs/semantic-search.md) and the +[synthetic benchmark report](docs/retrieval-benchmarks.md). diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index fe3b8b1..7a7641d 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -27,6 +27,9 @@ they cover, and Electron's and Chromium's licenses are in the app's installation | [Electron](https://www.electronjs.org) | MIT | GitHub Inc., OpenJS Foundation and contributors | | Chromium (bundled with Electron) | BSD-3-Clause and others | The Chromium Authors | | [electron-updater](https://github.com/electron-userland/electron-builder) and its dependencies | MIT, ISC, BlueOak-1.0.0, Python-2.0 | electron-builder contributors and others | +| [Transformers.js](https://github.com/huggingface/transformers.js) and ONNX Runtime (optional local inference) | Apache-2.0, MIT | Hugging Face and Microsoft | +| [sharp](https://sharp.pixelplumbing.com) and its dynamically linked libvips distribution | Apache-2.0, LGPL-3.0-or-later and the dependency licenses listed in the bundled `@img/sharp-libvips-*/README.md` | sharp and libvips contributors | +| [sqlite-vec](https://github.com/asg017/sqlite-vec) (local vector retrieval) | MIT, Apache-2.0 | Alex Garcia | | [mammoth](https://github.com/mwilliamson/mammoth.js) (Word document conversion) and its dependencies | BSD-2-Clause, MIT, ISC, Zlib, Python-2.0; JSZip under MIT (of MIT OR GPL-3.0-or-later) | Michael Williamson and others | The sample document (`public/sample.pdf`) was written for Folio and is covered by Folio's MIT License. @@ -78,3 +81,18 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +## Downloaded embedding models + +Models are optional downloads, not bundled weights. The pinned model registry lists +source revisions, file digests and licenses. BGE Small EN v1.5 is MIT licensed; +all-MiniLM-L6-v2 is Apache-2.0 licensed. EmbeddingGemma uses the Gemma terms (explicit acceptance is required before download); +Qwen3 uses Apache-2.0. No ReadAny source +code is included. Backend dependency license texts ship inside their packages. + +Native inference/vector license texts are also in `licenses/backend/`. Libvips +and its dependencies are dynamically linked and unpacked beside the application, +so these libraries can be replaced. Corresponding source and build configuration: +https://github.com/lovell/sharp-libvips (distribution 1.3.4; bundled versions are +listed in each platform package’s `versions.json`). LGPL and GPL license texts +for these library terms are included; Folio’s own code remains MIT. diff --git a/build/third-party/GPL-3.0.txt b/build/third-party/GPL-3.0.txt new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/build/third-party/GPL-3.0.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/build/third-party/LGPL-3.0.txt b/build/third-party/LGPL-3.0.txt new file mode 100644 index 0000000..0a04128 --- /dev/null +++ b/build/third-party/LGPL-3.0.txt @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser 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 +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/build/third-party/onnxruntime-LICENSE.txt b/build/third-party/onnxruntime-LICENSE.txt new file mode 100644 index 0000000..48bc6bb --- /dev/null +++ b/build/third-party/onnxruntime-LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/build/third-party/sqlite-vec-LICENSE-MIT.txt b/build/third-party/sqlite-vec-LICENSE-MIT.txt new file mode 100644 index 0000000..9c106bc --- /dev/null +++ b/build/third-party/sqlite-vec-LICENSE-MIT.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Alex Garcia + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/docs/retrieval-benchmarks.md b/docs/retrieval-benchmarks.md new file mode 100644 index 0000000..1fad4e0 --- /dev/null +++ b/docs/retrieval-benchmarks.md @@ -0,0 +1,90 @@ +# Local retrieval validation + +Linux x86_64, AMD Ryzen 7 7735HS, 29 GiB RAM, Node 24.20.0 and +Electron 45.2.1. Measurements are local observations, not performance guarantees. +No production document or query was sent to an external inference service. + +## Reproducible commands + +``` +npm run test:retrieval +npm run build +npm run smoke:retrieval +FOLIO_TEST_MODELS=1 npm run smoke:retrieval +``` + +The last command explicitly installs BGE and MiniLM in a temporary test profile, +verifies CPU inference/retrieval, uses offline mode, and deletes the profile. +`FOLIO_TEST_ALL_MODELS=1` also exercises enabled larger catalog entries. +`FOLIO_KEEP_TEST_PROFILE=1` retains test assets and prints the directory. +`FOLIO_MODEL_FIXTURE=/path/to/test/profile/retrieval/models` reuses already downloaded +models. These flags never point at the user's installed Folio profile. + +``` +FOLIO_MODEL_FIXTURE=/path/to/test/models npm run benchmark:retrieval +FOLIO_MODEL_FIXTURE=/path/to/test/models FOLIO_BENCHMARK_PAGES=7000 npm run benchmark:retrieval +``` + +The benchmark emits JSON under `release/`, excluded from Git. It opens the generated +PDF in the reader and indexes that same PDF through the utility process. Relevance +labels are manually assigned for five technical queries (DMA recovery, I2C enable, +software reset, watchdog timeout, PCIe BAR mapping). The four relevant pages are +followed by mechanical-assembly distractor pages. This intentionally simple dataset +checks retrieval mechanics, not general relevance quality or complex PDF layout. + +## 7,000-page synthetic baseline + +Measured after adding per-model embedding checkpoints. Default indexing: two CPU +threads, four passages per batch; measured semantic query runs use one CPU thread. +The PDF is 1.89 MB with one short passage per page. No images, scans or complex tables. +The large document was open throughout indexing. + +| Mode/model | Index duration | First query | Warm mean | +| --- | ---: | ---: | ---: | +| Exact, no model | 11.80 s shared extraction | 8.75 ms | 7.61 ms | +| BGE semantic | 35.83 s embeddings only | 157.11 ms | 30.53 ms | +| BGE hybrid | same index | 27.86 ms | 23.76 ms | +| MiniLM semantic | 23.27 s embeddings only | 132.16 ms | 17.34 ms | +| MiniLM hybrid | same index | 17.79 ms | 17.79 ms | + +Semantic first-query measurements include reloading the model after disposing its +session; filesystem caches may be warm. Hybrid reuses the loaded session. +Recall@5, Recall@10, MRR@10 and nDCG@10 were 1.0 for every mode on this small +five-query label set. This is not evidence of equivalent quality on real manuals. + +Opening the document took 7.59 s. Peak search-process working set was 357 MiB; +peak sum of all Electron working sets was 1,457 MiB (shared pages can be counted +more than once). Database plus WAL occupied 33.3 MB, excluding model weights and +original PDF. Across 40 samples, reader input-to-navigation averaged 35.82 ms (30.39–54.44 ms). +These measure scripted input/Enter handling, not display-frame latency. + +An earlier run without embedding checkpoints took 86.72 s for BGE and 72.01 s for +MiniLM. Profiling the work exposed repeated scans of already embedded chunks; +persisted per-model chunk cursors now bound that work without changing extraction. + +## Provisional targets and remaining measurements + +On this hardware, target warm retrieval below 250 ms, reader input below 100 ms, +and a search utility working set below 1 GiB for small CPU embedding models. +These provisional targets must be reassessed on dense real documentation. Model +download time depends on the network and is not characterized here. + +Real 7,000–10,000-page technical manuals, multiple columns, long register tables, +image-heavy documents and OCR-backed indexing still need their own corpus and +reviewed relevance labels. Windows/macOS binaries and Linux installers require +platform execution beyond the local Linux ASAR harness; no release was published. + +## Final package checks + +Linux `.deb` (193 MiB) and AppImage (239 MiB) were generated locally with +publication disabled. The final ASAR inside the Linux output passed the hidden +Electron test with all four installed models, Italian-to-English retrieval, +passage highlighting, and pause/cancel/restart/resume over a 1,000-page fixture. +The installer scripts were inspected through Debian package metadata; they were +not executed and the existing installed Folio was not replaced. + +The original baseline run stopped in the OCR selection fixture; an untouched +`0590fac` checkout also failed there. After rebasing onto `16f8da3` and making the +smoke's desktop viewport and bookmark starting page explicit, the full +`npm run smoke` passes on Linux, including OCR, printing and retrieval. +The benchmark measurements above were not rerun as part of that smoke validation. diff --git a/docs/semantic-search.md b/docs/semantic-search.md new file mode 100644 index 0000000..0b12626 --- /dev/null +++ b/docs/semantic-search.md @@ -0,0 +1,119 @@ +# Local retrieval architecture + +Audit baseline: `0590fac`, Folio 1.16.1. + +The React reader in `src/App.tsx` owns a pdf.js `PDFDocumentProxy`. `SearchBar` +and `SearchResults` use `PDFFindController` and its event bus. Preserve this path, +including Ctrl+F and match highlighting. `src/pdf.ts` configures pdf.js assets and +disables XFA. `recent.contentKey` hashes every byte with SHA-256; IndexedDB owns +annotations, bookmarks, reading position and recent PDFs. Retrieval uses a separate +database and never writes these stores. Password-protected PDFs must not leave +plaintext search indexes on disk. + +`electron/main.cjs` authenticates IPC senders, `preload.cjs` exposes explicit +capabilities to the sandboxed renderer. Follow that boundary. Existing AI in +`electron/ai.cjs` handles remote generation/authentication; local retrieval neither +imports it nor requires its configuration. `convert.cjs` already demonstrates +Electron utility-process isolation. CI builds and runs hidden Electron smoke tests +on Linux, macOS and Windows. Electron Builder packages `dist` and `electron`; +backend PDF assets and native inference/vector libraries need explicit packaging. + +## Implementation sequence + +1. Persistent shared extraction, page-local chunks and FTS5; transactional page + checkpoints, content identity verification, exact retrieval tests. +2. Lazy utility-process ONNX provider, model-specific formatting, separate vector + indexes, RRF hybrid retrieval and cancellation. +3. Explicit verified model installation and settings; extend the existing search + panel with advanced results and page navigation. +4. Resume/partial coverage/resource limits, hidden integration tests and benchmark + tooling. Record measurements and platform validation separately from targets. + +## Invariants + +Opening PDFs, navigation, annotations, bookmarks and existing find require no +retrieval process, embedding runtime, installed model or network. Only an explicit +index/search/settings action starts retrieval; ONNX is dynamically imported only +when an installed model is explicitly used. Downloads require Install. + +Extraction and chunking belong to the document content hash plus extraction and +chunking configuration version. They are independent of embedding models. Every +model/revision/configuration owns its own vector table and completion checkpoints. +Switching a model reuses extracted pages and shared chunks; it never deletes other +indexes. Changed bytes produce a different document identity, even under the same +filename; moved identical bytes reuse the index. No local query or document text +is transmitted to a provider. + +## Using the feature + +Open **Semantic search** from its toolbar icon or Ctrl+Shift+F (⌘⇧F on macOS). +It uses a dedicated sidebar beside the PDF. Ctrl+F opens basic find in the same +sidebar space, with a fixed query field and scrollable matching pages. Basic find, +semantic search, Ask AI and version history share one right-hand panel. +Both shortcuts use selected PDF text as the query, including when a search panel +is already open. +Exact uses the local persistent FTS5 index; Semantic and Hybrid use the selected +installed model. **Manage embedding models** opens Settings → Semantic Search. +Choose Install explicitly, accept Gemma's terms if applicable, and build the index. +Typing hides the initial configuration and searches after a short debounce. The +query field stays anchored at the bottom while results scroll above it. Search +options restores the configuration without clearing the query; clearing the query +also restores it. +Models remain optional. The normal find bar continues working while indexing. + +Shared extraction is keyed by the full PDF content identity and extraction/chunking +versions. Starting another model's index sends no PDF bytes when shared extraction +is complete. Pages and chunks are never reconstructed for a model switch. +Token estimates define shared chunks; the actual model tokenizer checks inference +limits and splits overlong inputs without truncating the original passage. Split +embeddings are normalized and averaged. Vectors are never mixed across revisions, +quantization variants or embedding configurations. Per-model chunk checkpoints +avoid repeatedly scanning the completed prefix of a large embedding index. + +The utility process serializes inference/storage batches, prioritizes foreground +search requests, bounds the RPC queue, and supports query cancellation and +pause/cancel/resume of indexing. A cancelled index retains committed pages and +vectors. A restart changes interrupted jobs to paused. A page is committed only +after extraction completes and cancellation is checked. Downloads retain partial +files, validate resumed ranges and every SHA-256, and rename the verified model +directory only after a local embedding/retrieval smoke test. Runtime model loading +uses local files only regardless of the download offline setting. + +The backend lives in `electron/retrieval/`; `electron/retrieval.cjs` is its authenticated +IPC entry point. `src/retrieval.ts` defines provenance, embedding, retrieval and +future generation contracts. `AdvancedSearch` and `EmbeddingModels` supply the UI. +The database is `retrieval/search.sqlite` under Electron's per-user data directory; +models and resumable downloads live beside it. This is separate from IndexedDB +annotations/bookmarks and from the installed application directory. + +## Validated scope and remaining work + +- BGE Small EN v1.5 (`q8`), MiniLM (`q8`), EmbeddingGemma (`q4`) and Qwen3 (`q8`) + passed real loading, dimensionality, basic retrieval and offline checks in the + Linux Electron app and its built ASAR. Italian queries against English passages + are checked for Gemma and Qwen. Gemma `q8` terminated the utility process (exit + 133) locally; it is not offered. The exact cause is not established. +- Normal startup/open/find never launch retrieval. ONNX is dynamically imported + only for an explicit semantic operation or installation verification. +- The default hidden smoke requires no downloads. Opt-in model tests exercise + installation, offline retrieval, switching without resending PDF bytes, result + highlighting/navigation, partial indexes, cancel/pause/resume and restart. +- Search currently covers the open document. Other PDFs' indexes remain stored, + but a cross-document library search/open workflow is not implemented. +- Inference uses CPU only. Threads and indexing batch size are configurable; + GPU acceleration and a hard per-process memory budget are not implemented. +- Extraction reads PDF text only. Image-only scans require a searchable text layer; + the reader's transient OCR output is not indexed by this backend. Password-protected + documents are excluded to preserve Folio's existing no-plaintext-persistence rule. +- Source provenance includes content hash, page and original extracted-text offsets. + Coordinates and automatic section-heading detection are not provided. Clicking a + passage navigates and uses the existing find controller to highlight its opening. +- No chat or generation provider is added. Generation interfaces are future contracts. +- Real complex manuals and Windows/macOS execution remain outstanding. See + [retrieval-benchmarks.md](retrieval-benchmarks.md) for measured synthetic results. + +After rebasing onto `16f8da3`, the full `npm run smoke` passes on Linux, +including OCR, printing and retrieval. The smoke uses an explicit desktop viewport +and selects page 1 before checking that bookmarking another page does not navigate. +The earlier OCR fixture failures describe the original `0590fac` baseline, not +this validation. Windows/macOS execution remains outstanding. diff --git a/electron/main.cjs b/electron/main.cjs index d8f36fd..0df6b53 100644 --- a/electron/main.cjs +++ b/electron/main.cjs @@ -597,6 +597,7 @@ if (!app.requestSingleInstanceLock()) { ai.register(handle, (channel, payload) => win?.webContents.send(channel, payload), { confirmLocal: (url, addresses) => confirmLocalAddress(url, addresses) }); registerPrinting(handle, () => win); + require("./retrieval.cjs").register(handle); handle("folio:ready", () => { rendererReady = true; diff --git a/electron/preload.cjs b/electron/preload.cjs index 81d5350..5d70ea0 100644 --- a/electron/preload.cjs +++ b/electron/preload.cjs @@ -63,6 +63,19 @@ contextBridge.exposeInMainWorld("folioDesktop", { checkForUpdates: () => ipcRenderer.send("folio:check-update"), getAutoUpdateEnabled: () => ipcRenderer.invoke("folio:auto-update-setting"), setAutoUpdateEnabled: (enabled) => ipcRenderer.invoke("folio:set-auto-update-setting", enabled), + retrieval: { + catalog: () => ipcRenderer.invoke("folio:retrieval-catalog"), + configure: settings => ipcRenderer.invoke("folio:retrieval-configure", settings), + install: (model, acceptLicense) => ipcRenderer.invoke("folio:retrieval-install", { model, acceptLicense }), + cancelDownload: model => ipcRenderer.invoke("folio:retrieval-cancelDownload", { model }), + uninstall: model => ipcRenderer.invoke("folio:retrieval-uninstall", { model }), + status: (documentId, model) => ipcRenderer.invoke("folio:retrieval-status", { documentId, model }), + index: request => ipcRenderer.invoke("folio:retrieval-index", request), + pause: documentId => ipcRenderer.invoke("folio:retrieval-pause", { documentId }), + cancelIndex: documentId => ipcRenderer.invoke("folio:retrieval-cancelIndex", { documentId }), + search: request => ipcRenderer.invoke("folio:retrieval-search", request), + cancel: id => ipcRenderer.invoke("folio:retrieval-cancel", { id }), + }, ai: { status: () => ipcRenderer.invoke("folio:ai-status"), signInChatGPT: () => ipcRenderer.invoke("folio:ai-chatgpt-signin"), diff --git a/electron/retrieval.cjs b/electron/retrieval.cjs new file mode 100644 index 0000000..e5d25bb --- /dev/null +++ b/electron/retrieval.cjs @@ -0,0 +1,47 @@ +const path = require('node:path'); +const { app, utilityProcess } = require('electron'); +let worker, starting, serial = 0; +const pending = new Map(); +function call(method, args) { + if (pending.size >= 32) return Promise.reject(new Error('Search queue is full. Try again shortly.')); + const id = ++serial; + return new Promise((resolve, reject) => { pending.set(id, { resolve, reject }); worker.postMessage({ id, method, args }); }); +} +function start() { + if (starting) return starting; + worker = utilityProcess.fork(path.join(__dirname, 'retrieval/worker.cjs'), [], { serviceName: 'Folio local search', stdio: 'pipe' }); + worker.stderr?.on('data', chunk => console.error('[local search]', String(chunk).trim())); + worker.on('message', message => { + const entry = pending.get(message.id); + if (!entry) return; + pending.delete(message.id); + if (message.error) entry.reject(new Error(message.error)); else entry.resolve(message.result); + }); + worker.on('exit', code => { + for (const entry of pending.values()) entry.reject(new Error(`Local search stopped (exit ${code}). Retry to resume.`)); + pending.clear(); worker = null; starting = null; + }); + starting = call('init', { root: path.join(app.getPath('userData'), 'retrieval') }); + return starting; +} +function validate(method, args) { + if (!args || typeof args !== 'object') throw new Error('Invalid search request.'); + const documentMethods = ['status', 'index', 'pause', 'cancelIndex', 'search']; + if (documentMethods.includes(method) && (typeof args.documentId !== 'string' || !/^sha256(?:-full)?:[a-f0-9]{64}:\d{1,10}$/.test(args.documentId))) throw new Error('Invalid document identity.'); + if (args.model !== undefined && (typeof args.model !== 'string' || args.model.length > 100)) throw new Error('Invalid model.'); + if (method === 'index' && ((args.data !== undefined && (!(args.data instanceof Uint8Array) || args.data.length > 300 * 1024 * 1024)) || typeof args.name !== 'string' || args.name.length > 1024)) throw new Error('Invalid document.'); + if (method === 'search' && (!['exact', 'semantic', 'hybrid'].includes(args.mode) || typeof args.query !== 'string' || args.query.length > 4096 || !Number.isInteger(args.limit) || args.limit < 1 || args.limit > 100 || args.scope !== 'document' || (args.phrase !== undefined && typeof args.phrase !== 'boolean'))) throw new Error('Invalid query.'); + if (['search', 'cancel'].includes(method) && (typeof args.id !== 'string' || args.id.length > 100)) throw new Error('Invalid search identifier.'); +} +function register(handle) { + // Keep capabilities explicit; never expose arbitrary worker commands or filesystem paths. + for (const method of ['catalog', 'configure', 'install', 'cancelDownload', 'uninstall', 'status', 'index', 'pause', 'cancelIndex', 'search', 'cancel']) { + handle('folio:retrieval-' + method, async (_event, args = {}) => { + validate(method, args); + await start(); + return call(method, args); + }); + } + app.on('before-quit', () => worker?.kill()); +} +module.exports = { register }; diff --git a/electron/retrieval/download.cjs b/electron/retrieval/download.cjs new file mode 100644 index 0000000..36fd268 --- /dev/null +++ b/electron/retrieval/download.cjs @@ -0,0 +1,56 @@ +const fs = require('node:fs'); +const path = require('node:path'); +const crypto = require('node:crypto'); +const { Readable } = require('node:stream'); +const { pipeline } = require('node:stream/promises'); + +async function digest(file) { + const hash = crypto.createHash('sha256'); + for await (const block of fs.createReadStream(file)) hash.update(block); + return hash.digest('hex'); +} +async function valid(file, spec) { + try { return (await fs.promises.stat(file)).size === spec.bytes && await digest(file) === spec.sha256; } + catch { return false; } +} +async function fetchPinned(url, options, fetchFile = fetch) { + for (let i = 0; i < 8; i++) { + const target = new URL(url); + if (target.protocol !== 'https:' || !['huggingface.co', 'hf.co', 'xethub.hf.co'].some(host => target.hostname === host || target.hostname.endsWith('.' + host))) throw new Error('Untrusted model download location.'); + const response = await fetchFile(target, { ...options, redirect: 'manual' }); + if (![301, 302, 303, 307, 308].includes(response.status)) return response; + await response.body?.cancel(); + url = new URL(response.headers.get('location'), target).href; + } + throw new Error('Too many model download redirects.'); +} +async function downloadFile(model, spec, target, signal, progress, fetchFile) { + await fs.promises.mkdir(path.dirname(target), { recursive: true, mode: 0o700 }); + if (await valid(target, spec)) { progress(spec.bytes); return; } + const partial = target + '.part'; + let offset = (await fs.promises.stat(partial).catch(() => ({ size: 0 }))).size; + if (offset > spec.bytes) { await fs.promises.rm(partial, { force: true }); offset = 0; } + if (offset < spec.bytes) { + const response = await fetchPinned(`https://huggingface.co/${model.repo}/resolve/${model.revision}/${spec.name}`, { + headers: offset ? { Range: `bytes=${offset}-` } : {}, signal: AbortSignal.any([signal, AbortSignal.timeout(30 * 60_000)]), + credentials: 'omit', referrerPolicy: 'no-referrer', + }, fetchFile); + if (![200, 206].includes(response.status) || !response.body) throw new Error(`Download failed (${response.status}).`); + if (response.status === 206) { + if (response.headers.get('content-range') !== `bytes ${offset}-${spec.bytes - 1}/${spec.bytes}`) { await response.body.cancel(); throw new Error('Invalid resumed download range.'); } + } else offset = 0; + let received = offset; + const source = Readable.fromWeb(response.body); + source.on('data', chunk => { received += chunk.length; if (received > spec.bytes) source.destroy(new Error('Unexpected model file size.')); else progress(received); }); + await pipeline(source, fs.createWriteStream(partial, { flags: offset ? 'a' : 'w', mode: 0o600 }), { signal }); + } + if (!await valid(partial, spec)) { + await fs.promises.rm(partial, { force: true }); + throw new Error('Model checksum verification failed. Retry the download.'); + } + await fs.promises.rename(partial, target); +} +async function verifyModel(model, directory) { + for (const spec of model.files) if (!await valid(path.join(directory, spec.name), spec)) throw new Error('Model files are missing or changed. Reinstall this model.'); +} +module.exports = { digest, valid, downloadFile, verifyModel }; diff --git a/electron/retrieval/models.json b/electron/retrieval/models.json new file mode 100644 index 0000000..f0d3e8d --- /dev/null +++ b/electron/retrieval/models.json @@ -0,0 +1,227 @@ +[ + { + "id": "bge-small-en-v1.5", + "repo": "onnx-community/bge-small-en-v1.5-ONNX", + "revision": "4a9a46c7b88fa408e650a571a1800243f26309bd", + "name": "BGE Small EN v1.5", + "dimension": 384, + "maxTokens": 512, + "pooling": "cls", + "normalize": true, + "queryPrefix": "Represent this sentence for searching relevant passages: ", + "documentPrefix": "", + "languages": [ + "en" + ], + "dtype": "q8", + "devices": [ + "cpu" + ], + "license": "mit", + "files": [ + { + "name": "config.json", + "bytes": 867, + "sha256": "26ad1d93a1ba37422fc25472191cfa230010631fa6a01f9d9f81fa13df2d0917" + }, + { + "name": "onnx/model_quantized.onnx", + "bytes": 413666, + "sha256": "4d46eaef91aaa13133a32aafba250a05265c220d1e526797fb55359bfb5a953a" + }, + { + "name": "onnx/model_quantized.onnx_data", + "bytes": 33393408, + "sha256": "bf3c4475ba4cac85907418ef34a48dbdfcf628ee91c85415ca6b0c3e70a94cbb" + }, + { + "name": "special_tokens_map.json", + "bytes": 695, + "sha256": "5d5b662e421ea9fac075174bb0688ee0d9431699900b90662acd44b2a350503a" + }, + { + "name": "tokenizer.json", + "bytes": 533603, + "sha256": "ea77de727ef7fd34d177b83b4b1f1d3bb8884c95c90b6554a0adb0b3b65350a9" + }, + { + "name": "tokenizer_config.json", + "bytes": 1271, + "sha256": "eebe14d184cfbd65f6a11d2a5ff39385c4044c8a670a89acf1a13331e04faa60" + } + ], + "enabled": true, + "description": "Fast CPU search for English technical documents.", + "validation": "linux-x64-asar", + "externalData": true, + "key": "bge-small-en-v1.5@4a9a46c7b88fa408e650a571a1800243f26309bd:q8:v1", + "memoryHint": "Allow roughly 0.5 GB RAM." + }, + { + "id": "all-MiniLM-L6-v2", + "repo": "Xenova/all-MiniLM-L6-v2", + "revision": "751bff37182d3f1213fa05d7196b954e230abad9", + "name": "all-MiniLM-L6-v2", + "dimension": 384, + "maxTokens": 256, + "pooling": "mean", + "normalize": true, + "queryPrefix": "", + "documentPrefix": "", + "languages": [ + "en" + ], + "dtype": "q8", + "devices": [ + "cpu" + ], + "license": "apache-2.0", + "files": [ + { + "name": "config.json", + "bytes": 650, + "sha256": "7135149f7cffa1a573466c6e4d8423ed73b62fd2332c575bf738a0d033f70df7" + }, + { + "name": "onnx/model_quantized.onnx", + "bytes": 22972370, + "sha256": "afdb6f1a0e45b715d0bb9b11772f032c399babd23bfc31fed1c170afc848bdb1" + }, + { + "name": "special_tokens_map.json", + "bytes": 125, + "sha256": "b6d346be366a7d1d48332dbc9fdf3bf8960b5d879522b7799ddba59e76237ee3" + }, + { + "name": "tokenizer.json", + "bytes": 711661, + "sha256": "da0e79933b9ed51798a3ae27893d3c5fa4a201126cef75586296df9b4d2c62a0" + }, + { + "name": "tokenizer_config.json", + "bytes": 366, + "sha256": "9261e7d79b44c8195c1cada2b453e55b00aeb81e907a6664974b4d7776172ab3" + } + ], + "enabled": true, + "description": "Lightweight English baseline.", + "validation": "linux-x64-asar", + "externalData": false, + "key": "all-MiniLM-L6-v2@751bff37182d3f1213fa05d7196b954e230abad9:q8:v1", + "memoryHint": "Allow roughly 0.5 GB RAM." + }, + { + "id": "embeddinggemma-300m", + "repo": "onnx-community/embeddinggemma-300m-ONNX", + "revision": "5090578d9565bb06545b4552f76e6bc2c93e4a66", + "name": "EmbeddingGemma 300M", + "dimension": 768, + "maxTokens": 2048, + "pooling": "model", + "normalize": true, + "queryPrefix": "task: search result | query: ", + "documentPrefix": "title: none | text: ", + "languages": [ + "multilingual" + ], + "dtype": "q4", + "devices": [ + "cpu" + ], + "license": "gemma", + "files": [ + { + "name": "config.json", + "bytes": 1765, + "sha256": "6e1f06404b7163e0325ed2ea3e6781cde50f4a50b31780a95ad0d30e8404d77b" + }, + { + "name": "special_tokens_map.json", + "bytes": 662, + "sha256": "2f7b0adf4fb469770bb1490e3e35df87b1dc578246c5e7e6fc76ecf33213a397" + }, + { + "name": "tokenizer.json", + "bytes": 20323312, + "sha256": "4dda02faaf32bc91031dc8c88457ac272b00c1016cc679757d1c441b248b9c47" + }, + { + "name": "tokenizer_config.json", + "bytes": 1156830, + "sha256": "3ca953eea6c3c9fcda9cf3df22949ff18b216f7c74bd6459230f3f1013953f3a" + }, + { + "name": "onnx/model_q4.onnx", + "bytes": 519322, + "sha256": "ad1dfee81a70f7944b9b9d1cc6e48075b832881cf33fab2f2b248be78f3f0043" + }, + { + "name": "onnx/model_q4.onnx_data", + "bytes": 196725760, + "sha256": "599962c3143b040de2dd05e5975be3e9091dd067cacc6a8f7186e3203bab9e02" + } + ], + "enabled": true, + "description": "Multilingual retrieval, including Italian queries and English documents.", + "validation": "linux-x64-asar", + "externalData": true, + "key": "embeddinggemma-300m@5090578d9565bb06545b4552f76e6bc2c93e4a66:q4:v1", + "output": "sentence_embedding", + "requiresLicenseAcceptance": true, + "licenseUrl": "https://ai.google.dev/gemma/terms", + "memoryHint": "Allow roughly 1\u20132 GB RAM; CPU indexing is slower." + }, + { + "id": "qwen3-embedding-0.6b", + "repo": "onnx-community/Qwen3-Embedding-0.6B-ONNX", + "revision": "c25a394dd583836952667c12f008335071b3f43d", + "name": "Qwen3 Embedding 0.6B", + "dimension": 1024, + "maxTokens": 32768, + "pooling": "last_token", + "normalize": true, + "queryPrefix": "Instruct: Given a web search query, retrieve relevant passages that answer the query\nQuery:", + "documentPrefix": "", + "languages": [ + "multilingual" + ], + "dtype": "q8", + "devices": [ + "cpu" + ], + "license": "apache-2.0", + "files": [ + { + "name": "config.json", + "bytes": 1576, + "sha256": "66a10929782f3c9a3cd5dec90e2a95c60e05736134a63cd54479eeae80bed175" + }, + { + "name": "onnx/model_quantized.onnx", + "bytes": 613527631, + "sha256": "87cd124e0ef1fd1f223ebc283efccbaeac386d0b08344701c46975d0657b591f" + }, + { + "name": "special_tokens_map.json", + "bytes": 613, + "sha256": "76862e765266b85aa9459767e33cbaf13970f327a0e88d1c65846c2ddd3a1ecd" + }, + { + "name": "tokenizer.json", + "bytes": 11423705, + "sha256": "def76fb086971c7867b829c23a26261e38d9d74e02139253b38aeb9df8b4b50a" + }, + { + "name": "tokenizer_config.json", + "bytes": 9731, + "sha256": "977648852447cb6587327ff3205b0a84cf2fc9f05621d6c8e88a497caafab2e1" + } + ], + "enabled": true, + "description": "Advanced multilingual retrieval. Requires more memory and CPU time.", + "validation": "linux-x64-asar", + "externalData": false, + "key": "qwen3-embedding-0.6b@c25a394dd583836952667c12f008335071b3f43d:q8:v1", + "memoryHint": "Allow roughly 1\u20132 GB RAM; CPU indexing is slower." + } +] diff --git a/electron/retrieval/provider.cjs b/electron/retrieval/provider.cjs new file mode 100644 index 0000000..7655496 --- /dev/null +++ b/electron/retrieval/provider.cjs @@ -0,0 +1,60 @@ +const path = require('node:path'); +function normalized(values, dimension) { + if (values.length !== dimension || !values.every(Number.isFinite)) throw new Error('Invalid embedding dimensions or values.'); + const norm = Math.hypot(...values); + if (!norm) throw new Error('Empty embedding.'); + return Float32Array.from(values, value => value / norm); +} +function format(model, text, query) { return (query ? model.queryPrefix : model.documentPrefix) + text; } + +class LocalOnnxEmbeddingProvider { + id = 'local-onnx'; + async load(model, directory, threads = 2) { + await this.dispose(); + // Importing this module alone must never initialize an AI runtime. + const { pipeline, env, AutoModel, AutoTokenizer } = await import('@huggingface/transformers'); + env.allowRemoteModels = false; + env.allowLocalModels = true; + env.useBrowserCache = false; + env.useFSCache = false; + this.model = model; + const location = path.join(directory, model.id); + const options = { + local_files_only: true, dtype: model.dtype, device: 'cpu', + use_external_data_format: model.externalData, + session_options: { intraOpNumThreads: threads, interOpNumThreads: 1 }, + }; + if (model.output) { + this.runtime = await AutoModel.from_pretrained(location, options); + const tokenizer = await AutoTokenizer.from_pretrained(location, { local_files_only: true }); + this.pipeline = { tokenizer, dispose: () => this.runtime.dispose() }; + } else this.pipeline = await pipeline('feature-extraction', location, options); + } + async embed(text, query, signal) { + signal?.throwIfAborted(); + const input = format(this.model, text, query); + const tokens = await this.pipeline.tokenizer(input, { truncation: false }); + if (tokens.input_ids.size > this.model.maxTokens) { + // Shared chunks never depend on the selected model. Split overlong model inputs + // with its real tokenizer, then average normalized pieces rather than truncating. + if (text.length < 2) throw new Error('Model prompt exceeds its token limit.'); + let middle = Math.floor(text.length / 2); + const boundary = text.lastIndexOf(' ', middle); + if (boundary > text.length / 4) middle = boundary; + const a = await this.embed(text.slice(0, middle), query, signal); + const b = await this.embed(text.slice(middle), query, signal); + return normalized(a.map((v, i) => v + b[i]), this.model.dimension); + } + const result = this.model.output ? (await this.runtime(tokens))[this.model.output] : await this.pipeline(input, { pooling: this.model.pooling, normalize: this.model.normalize, truncation: true, max_length: this.model.maxTokens }); + signal?.throwIfAborted(); + return normalized(result.data, this.model.dimension); + } + async embedDocuments(texts, signal) { + const result = []; + for (const text of texts) result.push(await this.embed(text, false, signal)); + return result; + } + embedQuery(query, signal) { return this.embed(query, true, signal); } + async dispose() { if (this.pipeline) await this.pipeline.dispose(); else if (this.runtime) await this.runtime.dispose(); this.pipeline = null; this.runtime = null; } +} +module.exports = { LocalOnnxEmbeddingProvider, normalized, format }; diff --git a/electron/retrieval/store.cjs b/electron/retrieval/store.cjs new file mode 100644 index 0000000..78faf93 --- /dev/null +++ b/electron/retrieval/store.cjs @@ -0,0 +1,121 @@ +const { DatabaseSync } = require('node:sqlite'); +const { EXTRACTION_VERSION, CHUNK_VERSION, chunks, normalize, ftsQuery, fuse } = require('./text.cjs'); + +class Store { + constructor(filename) { + this.db = new DatabaseSync(filename, { allowExtension: true }); + const extension = require('sqlite-vec').getLoadablePath().replace('app.asar' + require('node:path').sep, 'app.asar.unpacked' + require('node:path').sep); + this.db.loadExtension(extension); + this.db.enableLoadExtension(false); + this.db.exec('PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;'); + const version = this.db.prepare('PRAGMA user_version').get().user_version; + if (version > 2) { this.db.close(); throw new Error('Search index was created by a newer Folio.'); } + this.db.exec(` + CREATE TABLE IF NOT EXISTS documents(id TEXT PRIMARY KEY, name TEXT NOT NULL, total INTEGER NOT NULL, extraction INTEGER NOT NULL, chunking INTEGER NOT NULL); + CREATE TABLE IF NOT EXISTS pages(document_id TEXT REFERENCES documents(id) ON DELETE CASCADE, number INTEGER, text TEXT NOT NULL, normalized TEXT NOT NULL, PRIMARY KEY(document_id, number)); + CREATE TABLE IF NOT EXISTS chunks(id INTEGER PRIMARY KEY, document_id TEXT REFERENCES documents(id) ON DELETE CASCADE, page INTEGER NOT NULL, start INTEGER NOT NULL, end INTEGER NOT NULL, text TEXT NOT NULL); + CREATE INDEX IF NOT EXISTS chunks_document ON chunks(document_id, page); + CREATE INDEX IF NOT EXISTS chunks_embedding_order ON chunks(document_id, id); + CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(text, content='chunks', content_rowid='id', tokenize="unicode61 tokenchars '_'"); + CREATE TRIGGER IF NOT EXISTS chunks_insert AFTER INSERT ON chunks BEGIN INSERT INTO chunks_fts(rowid,text) VALUES(new.id,new.text); END; + CREATE TRIGGER IF NOT EXISTS chunks_delete AFTER DELETE ON chunks BEGIN INSERT INTO chunks_fts(chunks_fts,rowid,text) VALUES('delete',old.id,old.text); END; + CREATE TABLE IF NOT EXISTS embedding_models(id TEXT PRIMARY KEY, dimension INTEGER NOT NULL); + CREATE TABLE IF NOT EXISTS embedding_indexes(document_id TEXT REFERENCES documents(id) ON DELETE CASCADE, model TEXT NOT NULL, last_chunk INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(document_id,model)); + CREATE TABLE IF NOT EXISTS indexing_jobs(document_id TEXT PRIMARY KEY REFERENCES documents(id) ON DELETE CASCADE, state TEXT NOT NULL, error TEXT); + CREATE TABLE IF NOT EXISTS settings(key TEXT PRIMARY KEY, value TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS model_downloads(model TEXT PRIMARY KEY, state TEXT NOT NULL, bytes INTEGER NOT NULL DEFAULT 0); + + `); + this.transaction(() => { + if (!this.db.prepare('PRAGMA table_info(embedding_indexes)').all().some(column => column.name === 'last_chunk')) this.db.exec('ALTER TABLE embedding_indexes ADD COLUMN last_chunk INTEGER NOT NULL DEFAULT 0'); + this.db.exec('PRAGMA user_version=2'); + }); + this.db.prepare("UPDATE indexing_jobs SET state='paused' WHERE state='indexing'").run(); + } + transaction(fn) { + this.db.exec('BEGIN IMMEDIATE'); + try { const result = fn(); this.db.exec('COMMIT'); return result; } + catch (error) { this.db.exec('ROLLBACK'); throw error; } + } + document(id, name, total) { + this.transaction(() => { + const old = this.db.prepare('SELECT * FROM documents WHERE id=?').get(id); + if (old && (old.extraction !== EXTRACTION_VERSION || old.chunking !== CHUNK_VERSION)) { + for (const row of this.db.prepare('SELECT id FROM chunks WHERE document_id=?').all(id)) { + for (const model of this.db.prepare('SELECT id FROM embedding_models').all()) this.db.prepare(`DELETE FROM ${this.table(model.id)} WHERE rowid=?`).run(BigInt(row.id)); + } + this.db.prepare('DELETE FROM documents WHERE id=?').run(id); + } + this.db.prepare('INSERT INTO documents VALUES(?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name').run(id, name, total, EXTRACTION_VERSION, CHUNK_VERSION); + }); + } + page(id, number, text) { + this.transaction(() => { + if (this.db.prepare('SELECT 1 FROM pages WHERE document_id=? AND number=?').get(id, number)) return; + this.db.prepare('INSERT INTO pages VALUES(?,?,?,?)').run(id, number, text, normalize(text)); + const insert = this.db.prepare('INSERT INTO chunks(document_id,page,start,end,text) VALUES(?,?,?,?,?)'); + for (const chunk of chunks(text)) insert.run(id, number, chunk.start, chunk.end, chunk.text); + }); + } + table(model) { return 'vec_' + require('node:crypto').createHash('sha256').update(model).digest('hex').slice(0, 24); } + model(model) { + const table = this.table(model.key); + this.db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${table} USING vec0(embedding float[${model.dimension}], document_id text partition key)`); + this.db.prepare('INSERT OR IGNORE INTO embedding_models VALUES(?,?)').run(model.key, model.dimension); + return table; + } + missing(id, model, limit = 8) { + const table = this.model(model); + const checkpoint = this.db.prepare('SELECT last_chunk FROM embedding_indexes WHERE document_id=? AND model=?').get(id, model.key)?.last_chunk || 0; + return this.db.prepare(`SELECT c.id,c.text FROM chunks c LEFT JOIN ${table} v ON v.rowid=c.id WHERE c.document_id=? AND c.id>? AND v.rowid IS NULL ORDER BY c.id LIMIT ?`).all(id, checkpoint, limit); + } + embeddings(id, model, rows, vectors) { + const table = this.model(model); + this.transaction(() => { + const insert = this.db.prepare(`INSERT INTO ${table}(rowid,embedding,document_id) VALUES(?,?,?)`); + rows.forEach((row, i) => insert.run(BigInt(row.id), vectors[i], id)); + this.db.prepare('INSERT INTO embedding_indexes(document_id,model,last_chunk) VALUES(?,?,?) ON CONFLICT(document_id,model) DO UPDATE SET last_chunk=excluded.last_chunk').run(id, model.key, Math.max(...rows.map(row => row.id))); + }); + } + status(id, model) { + const document = this.db.prepare('SELECT * FROM documents WHERE id=?').get(id); + const pages = this.db.prepare('SELECT count(*) AS n FROM pages WHERE document_id=?').get(id).n; + const count = this.db.prepare('SELECT count(*) AS n FROM chunks WHERE document_id=?').get(id).n; + const job = this.db.prepare('SELECT * FROM indexing_jobs WHERE document_id=?').get(id); + let embedded = 0; + if (model && this.db.prepare('SELECT 1 FROM embedding_models WHERE id=?').get(model.key)) { + embedded = this.db.prepare(`SELECT count(*) AS n FROM ${this.table(model.key)} WHERE document_id=?`).get(id).n; + } + return { pages, needsExtraction: !document || document.extraction !== EXTRACTION_VERSION || document.chunking !== CHUNK_VERSION || pages < document.total, total: document?.total || 0, chunks: count, embedded, state: job?.state || 'unavailable', error: job?.error || '' }; + } + job(id, state, error = '') { + this.db.prepare('INSERT INTO indexing_jobs VALUES(?,?,?) ON CONFLICT(document_id) DO UPDATE SET state=excluded.state,error=excluded.error').run(id, state, error); + } + setting(key, value) { + if (value !== undefined) this.db.prepare('INSERT OR REPLACE INTO settings VALUES(?,?)').run(key, JSON.stringify(value)); + return JSON.parse(this.db.prepare('SELECT value FROM settings WHERE key=?').get(key)?.value || 'null'); + } + search({ documentId, query, mode, limit = 20, scope = 'document', phrase = false }, model, vector) { + const match = phrase ? `"${query.replaceAll('"', '""')}"` : ftsQuery(query); + const candidates = Math.min(500, limit * 5); + const lexical = !match || mode === 'semantic' ? [] : this.db.prepare(`SELECT c.id,c.document_id AS documentId,d.name,c.page,c.start,c.end,c.text,bm25(chunks_fts) AS rank + FROM chunks_fts JOIN chunks c ON c.id=chunks_fts.rowid JOIN documents d ON d.id=c.document_id + WHERE chunks_fts MATCH ? ${scope === 'document' ? 'AND c.document_id=?' : ''} ORDER BY rank LIMIT ?`) + .all(...[match, ...(scope === 'document' ? [documentId] : []), candidates]); + // Literal identifiers and phrases take precedence over bag-of-words candidates. + lexical.sort((a, b) => Number(b.text.toLowerCase().includes(query.toLowerCase())) - Number(a.text.toLowerCase().includes(query.toLowerCase())) || a.rank - b.rank); + let semantic = []; + if (vector) { + const table = this.model(model); + semantic = this.db.prepare(`SELECT c.id,c.document_id AS documentId,d.name,c.page,c.start,c.end,c.text,v.distance FROM + (SELECT rowid,distance FROM ${table} WHERE embedding MATCH ? AND k=? ${scope === 'document' ? 'AND document_id=?' : ''}) v + JOIN chunks c ON c.id=v.rowid JOIN documents d ON d.id=c.document_id ORDER BY v.distance`) + .all(...[vector, BigInt(candidates), ...(scope === 'document' ? [documentId] : [])]); + } + const results = fuse(mode === 'exact' ? [lexical] : mode === 'semantic' ? [semantic] : [lexical, semantic], limit); + if (mode === 'hybrid' && /^(?:0x[0-9a-f]+|[a-z0-9]*_[a-z0-9_]+)$/i.test(query)) results.sort((a, b) => Number(b.text.toLowerCase().includes(query.toLowerCase())) - Number(a.text.toLowerCase().includes(query.toLowerCase())) || b.score - a.score); + return results; + } + close() { this.db.close(); } +} +module.exports = { Store }; diff --git a/electron/retrieval/text.cjs b/electron/retrieval/text.cjs new file mode 100644 index 0000000..968ac10 --- /dev/null +++ b/electron/retrieval/text.cjs @@ -0,0 +1,64 @@ +const crypto = require('node:crypto'); +const EXTRACTION_VERSION = 1; +const CHUNK_VERSION = 1; +const CHUNK_TOKENS = 400; +const OVERLAP_TOKENS = 60; + +function fingerprint(bytes) { + return `${bytes.length <= 2 * 1024 * 1024 ? 'sha256:' : 'sha256-full:'}${crypto.createHash('sha256').update(bytes).digest('hex')}:${bytes.length}`; +} + +function pageText(items) { + // Keep item boundaries and line breaks: never merge register names in adjacent cells. + return items.filter(item => typeof item.str === 'string').map(item => item.str + (item.hasEOL ? '\n' : ' ')).join('').trim(); +} + +function normalize(text) { return text.normalize('NFC').replace(/[\t\r ]+/g, ' '); } + +function chunks(text, budget = CHUNK_TOKENS, overlap = OVERLAP_TOKENS) { + if (!Number.isInteger(budget) || budget < 8 || overlap < 0 || overlap >= budget) throw new Error('Invalid chunk limits.'); + // Model-independent token estimate; inference enforces each model's actual tokenizer limit. + const units = [...text.matchAll(/[\p{L}\p{N}_]{1,64}|[^\s\p{L}\p{N}_]/gu)].map(m => ({ start: m.index, end: m.index + m[0].length, + cost: Math.max(1, Math.ceil(m[0].length / 4)) })); + const result = []; + for (let first = 0; first < units.length;) { + let end = first, count = 0; + while (end < units.length && (count + units[end].cost <= budget || end === first)) count += units[end++].cost; + // Prefer a paragraph break near the end, without losing any text. + if (end < units.length) { + for (let i = end - 1; i > first + (end - first) * .7; i--) { + if (text.slice(units[i - 1].end, units[i].start).includes('\n\n')) { end = i; break; } + } + } + const start = units[first].start, finish = units[end - 1].end; + result.push({ start, end: finish, text: text.slice(start, finish) }); + if (end === units.length) break; + let next = end, shared = 0; + while (next > first + 1 && shared + units[next - 1].cost <= overlap) shared += units[--next].cost; + first = Math.max(first + 1, next); + } + return result; +} + +function ftsQuery(query) { + const terms = query.match(/[\p{L}\p{N}_]+/gu) || []; + return [...new Set(terms)].slice(0, 48).map(term => `"${term}"`).join(' OR '); +} + +function fuse(lists, limit) { + const merged = new Map(); + for (const list of lists) list.forEach((row, rank) => { + const found = merged.get(row.id) || { ...row, score: 0 }; + found.score += 1 / (60 + rank + 1); + merged.set(row.id, found); + }); + const output = []; + for (const row of [...merged.values()].sort((a, b) => b.score - a.score || a.id - b.id)) { + if (output.some(other => other.documentId === row.documentId && other.page === row.page && + Math.max(0, Math.min(other.end, row.end) - Math.max(other.start, row.start)) > Math.min(other.end - other.start, row.end - row.start) * .3)) continue; + output.push(row); + if (output.length >= limit) break; + } + return output; +} +module.exports = { EXTRACTION_VERSION, CHUNK_VERSION, chunks, pageText, normalize, fingerprint, ftsQuery, fuse }; diff --git a/electron/retrieval/worker.cjs b/electron/retrieval/worker.cjs new file mode 100644 index 0000000..4f4e954 --- /dev/null +++ b/electron/retrieval/worker.cjs @@ -0,0 +1,256 @@ +const fs = require('node:fs'); +const path = require('node:path'); +const { pathToFileURL } = require('node:url'); +const { Store } = require('./store.cjs'); +const { fingerprint, pageText } = require('./text.cjs'); +const { downloadFile, verifyModel } = require('./download.cjs'); +const catalog = require('./models.json'); +const { LocalOnnxEmbeddingProvider } = require('./provider.cjs'); +let store, root, settings, provider, loaded, activeJob, activeDownload; +const cancellations = new Map(); +const downloads = new Map(); +const failures = new Map(); +const queue = []; +let busy = false; +function exclusive(fn, priority = false) { + return new Promise((resolve, reject) => { + const task = { fn, resolve, reject }; + if (priority) queue.unshift(task); else queue.push(task); + void drain(); + }); +} +async function drain() { + if (busy) return; + busy = true; + while (queue.length) { + const task = queue.shift(); + try { task.resolve(await task.fn()); } catch (error) { task.reject(error); } + } + busy = false; +} +function modelById(id, enabled = true) { + const model = catalog.find(model => model.id === id); + if (!model || (enabled && !model.enabled)) throw new Error('This model is not validated for installation.'); + return model; +} +function modelRoot(model) { return path.join(root, 'models', model.id); } +function ready(model) { + try { + const marker = JSON.parse(fs.readFileSync(path.join(modelRoot(model), 'ready.json'), 'utf8')); + return marker.key === model.key && model.files.every(file => fs.statSync(path.join(modelRoot(model), file.name)).size === file.bytes); + } catch { return false; } +} +async function load(model) { + if (!ready(model)) throw new Error('Install the selected embedding model in Settings → Semantic Search.'); + if (loaded === model.key) return provider; + await verifyModel(model, modelRoot(model)); + provider ||= new LocalOnnxEmbeddingProvider(); + loaded = null; + await provider.load(model, path.join(root, 'models'), settings.threads); + loaded = model.key; + return provider; +} +async function extract(job, request) { + const bytes = request.data instanceof Uint8Array ? request.data : new Uint8Array(request.data); + request.data = null; + if (bytes.byteLength > 300 * 1024 * 1024 || fingerprint(bytes) !== request.documentId) throw new Error('Document identity does not match its contents.'); + // No PDF JavaScript or remote resources. Import only after an explicit indexing action. + globalThis.pdfjsWorker ||= await import('pdfjs-dist/legacy/build/pdf.worker.mjs'); + const pdfjs = await import('pdfjs-dist/legacy/build/pdf.mjs'); + const assetRoot = path.resolve(__dirname, '../..', 'dist/pdfjs'); + const task = pdfjs.getDocument({ data: bytes, enableXfa: false, isEvalSupported: false, useSystemFonts: false, + cMapUrl: pathToFileURL(path.join(assetRoot, 'cmaps') + path.sep).href, cMapPacked: true, + standardFontDataUrl: pathToFileURL(path.join(assetRoot, 'standard_fonts') + path.sep).href, + useWorkerFetch: false, + BinaryDataFactory: class { + async fetch({ kind, filename }) { + const directories = { cMapUrl: 'cmaps', standardFontDataUrl: 'standard_fonts', wasmUrl: 'wasm' }; + if (!directories[kind] || typeof filename !== 'string' || filename !== path.basename(filename)) throw new Error('Invalid PDF resource.'); + return new Uint8Array(await fs.promises.readFile(path.join(assetRoot, directories[kind], filename))); + } + } }); + const abort = () => { void task.destroy().catch(() => {}); }; + job.controller.signal.addEventListener('abort', abort, { once: true }); + try { + const pdf = await task.promise; + if (pdf.numPages > 10000) throw new Error('PDF exceeds 10,000 pages.'); + store.document(request.documentId, request.name, pdf.numPages); + store.job(request.documentId, 'indexing'); + for (let pageNumber = 1; pageNumber <= pdf.numPages; pageNumber++) { + job.controller.signal.throwIfAborted(); + if (store.db.prepare('SELECT 1 FROM pages WHERE document_id=? AND number=?').get(request.documentId, pageNumber)) continue; + await exclusive(async () => { + job.controller.signal.throwIfAborted(); + const page = await pdf.getPage(pageNumber); + try { + const content = await page.getTextContent({ disableNormalization: true }); + job.controller.signal.throwIfAborted(); + store.page(request.documentId, pageNumber, pageText(content.items)); + } finally { page.cleanup(); } + }); + await new Promise(resolve => setImmediate(resolve)); + } + } finally { job.controller.signal.removeEventListener('abort', abort); await task.destroy(); } +} +async function index(job, request) { + try { + const old = store.status(request.documentId); + // Completed extraction is shared across every embedding model, including after restart. + if (!old.total || old.pages !== old.total || !store.db.prepare('SELECT 1 FROM documents WHERE id=? AND extraction=? AND chunking=?').get(request.documentId, require('./text.cjs').EXTRACTION_VERSION, require('./text.cjs').CHUNK_VERSION)) await extract(job, request); + else store.job(request.documentId, 'indexing'); + request.data = null; + if (request.model) { + const model = modelById(request.model); + for (;;) { + job.controller.signal.throwIfAborted(); + const count = await exclusive(async () => { + job.controller.signal.throwIfAborted(); + const rows = store.missing(request.documentId, model, settings.batchSize); + if (!rows.length) return 0; + const runtime = await load(model); + const vectors = await runtime.embedDocuments(rows.map(row => row.text), job.controller.signal); + store.embeddings(request.documentId, model, rows, vectors); + return rows.length; + }); + if (!count) break; + await new Promise(resolve => setImmediate(resolve)); + } + } + store.job(request.documentId, 'complete'); + } catch (error) { + if (store.status(request.documentId).total) store.job(request.documentId, job.controller.signal.aborted ? (job.cancelled ? 'cancelled' : 'paused') : 'failed', job.controller.signal.aborted ? '' : String(error.message)); + else failures.set(request.documentId, { state: job.controller.signal.aborted ? (job.cancelled ? 'cancelled' : 'paused') : 'failed', error: job.controller.signal.aborted ? '' : String(error.message) }); + } finally { request.data = null; if (activeJob === job) activeJob = null; } +} +async function install(model) { + const controller = new AbortController(); + activeDownload = { model: model.id, controller }; + const progress = { state: 'downloading', downloaded: 0, error: '' }; + downloads.set(model.id, progress); + const staging = path.join(root, 'downloads', model.id, model.id); + try { + let finished = 0, persistedAt = 0; + for (const file of model.files) { + await downloadFile(model, file, path.join(staging, file.name), controller.signal, current => { + progress.downloaded = finished + current; + if (Date.now() - persistedAt > 250) { + store.db.prepare('INSERT OR REPLACE INTO model_downloads VALUES(?,?,?)').run(model.id, 'downloading', progress.downloaded); + persistedAt = Date.now(); + } + }); + finished += file.bytes; + } + progress.state = 'verifying'; + await exclusive(async () => { + controller.signal.throwIfAborted(); + await verifyModel(model, staging); + const test = new LocalOnnxEmbeddingProvider(); + try { + await test.load(model, path.dirname(staging), settings.threads); + const docs = await test.embedDocuments(['The watchdog timeout resets the processor.', 'An Ethernet DMA timeout requires resetting the DMA controller.'], controller.signal); + const query = await test.embedQuery('How do I recover an Ethernet DMA timeout?', controller.signal); + const similarity = vector => vector.reduce((sum, value, i) => sum + value * query[i], 0); + if (!(similarity(docs[1]) > similarity(docs[0]))) throw new Error('Model retrieval verification failed.'); + } finally { await test.dispose(); } + controller.signal.throwIfAborted(); + const allowed = new Set(model.files.map(file => file.name)); + for (const file of await fs.promises.readdir(staging, { recursive: true, withFileTypes: true })) { + if (!file.isFile()) continue; + const filename = path.join(file.parentPath, file.name); + if (!allowed.has(path.relative(staging, filename).split(path.sep).join('/'))) await fs.promises.rm(filename); + } + await fs.promises.writeFile(path.join(staging, 'ready.json'), JSON.stringify({ key: model.key }), { mode: 0o600 }); + await fs.promises.mkdir(path.dirname(modelRoot(model)), { recursive: true, mode: 0o700 }); + // Reinstalling invalidates the loaded session, never its persisted indexes. + if (loaded === model.key) { await provider.dispose(); loaded = null; } + await fs.promises.rm(modelRoot(model), { recursive: true, force: true }); + await fs.promises.rename(staging, modelRoot(model)); + }); + progress.state = 'ready'; + store.db.prepare('INSERT OR REPLACE INTO model_downloads VALUES(?,?,?)').run(model.id, 'ready', progress.downloaded); + } catch (error) { + progress.state = controller.signal.aborted ? 'paused' : 'failed'; + progress.error = controller.signal.aborted ? '' : String(error.message); + store.db.prepare('INSERT OR REPLACE INTO model_downloads VALUES(?,?,?)').run(model.id, progress.state, progress.downloaded); + } finally { activeDownload = null; } +} + +async function dispatch(method, args) { + if (method === 'init') { + root = args.root; + fs.mkdirSync(root, { recursive: true, mode: 0o700 }); + store = new Store(path.join(root, 'search.sqlite')); + settings = store.setting('settings') || { activeModel: catalog[0].id, offline: false, threads: 2, batchSize: 4 }; + return true; + } + if (method === 'catalog') return { models: catalog.map(model => { + const saved = store.db.prepare('SELECT * FROM model_downloads WHERE model=?').get(model.id); + const state = downloads.get(model.id) || { state: saved?.state === 'downloading' ? 'paused' : saved?.state || 'not installed', downloaded: saved?.bytes || 0 }; + return { ...model, ...state, state: ready(model) ? 'ready' : state.state === 'ready' ? 'failed' : state.state }; + }), settings }; + if (method === 'configure') { + modelById(args.activeModel); + if (typeof args.offline !== 'boolean' || !Number.isInteger(args.threads) || args.threads < 1 || args.threads > 8 || !Number.isInteger(args.batchSize) || args.batchSize < 1 || args.batchSize > 16) throw new Error('Invalid search resource settings.'); + if (args.offline) activeDownload?.controller.abort(); + await exclusive(async () => { if (loaded && args.threads !== settings.threads) { await provider.dispose(); loaded = null; } settings = { activeModel: args.activeModel, offline: args.offline, threads: args.threads, batchSize: args.batchSize }; store.setting('settings', settings); }); + return; + } + if (method === 'install') { + if (settings.offline) throw new Error('Turn off offline mode before downloading a model.'); + if (activeDownload) throw new Error('Another model download is in progress.'); + if (activeJob) throw new Error('Pause indexing before installing another model.'); + const model = modelById(args.model); + if (model.requiresLicenseAcceptance && args.acceptLicense !== true) throw new Error('Review and accept this model’s license terms before installing it.'); + if (model.requiresLicenseAcceptance) store.setting('license:' + model.key, { accepted: Date.now(), url: model.licenseUrl }); + void install(model); + return; + } + if (method === 'cancelDownload') { if (activeDownload?.model === args.model) activeDownload.controller.abort(); return; } + if (method === 'uninstall') { + const model = modelById(args.model); + if (activeDownload || activeJob) throw new Error('Pause indexing and model downloads first.'); + return exclusive(async () => { + if (loaded === model.key) { await provider.dispose(); loaded = null; } + await fs.promises.rm(modelRoot(model), { recursive: true, force: true }); + downloads.delete(model.id); + store.db.prepare('DELETE FROM model_downloads WHERE model=?').run(model.id); + }); + } + if (method === 'status') { + const result = store.status(args.documentId, args.model ? modelById(args.model) : null); + if (failures.has(args.documentId)) return { ...result, ...failures.get(args.documentId) }; + if (activeJob?.id === args.documentId && !result.total) return { ...result, state: 'indexing' }; + return result; + } + if (method === 'index') { + if (activeJob) throw new Error('Another document is being indexed. Pause it first.'); + if (args.model && !ready(modelById(args.model))) throw new Error('Install the selected embedding model first.'); + failures.delete(args.documentId); + const job = { id: args.documentId, controller: new AbortController() }; + activeJob = job; + void index(job, args); + return; + } + if (method === 'pause') { if (activeJob?.id === args.documentId) activeJob.controller.abort(); return; } + if (method === 'cancelIndex') { if (activeJob?.id === args.documentId) { activeJob.cancelled = true; activeJob.controller.abort(); } return; } + if (method === 'cancel') { cancellations.get(args.id)?.abort(); return; } + if (method === 'search') { + const controller = new AbortController(); + cancellations.set(args.id, controller); + try { + return await exclusive(async () => { + controller.signal.throwIfAborted(); + const model = args.mode === 'exact' ? null : modelById(args.model || settings.activeModel); + const vector = model ? await (await load(model)).embedQuery(args.query, controller.signal) : null; + const results = store.search(args, model, vector); + controller.signal.throwIfAborted(); + return results; + }, true); + } finally { cancellations.delete(args.id); } + } + throw new Error('Unknown retrieval method.'); +} +process.parentPort.on('message', async ({ data: { id, method, args } }) => { + try { process.parentPort.postMessage({ id, result: await dispatch(method, args) }); } + catch (error) { process.parentPort.postMessage({ id, error: String(error.message || error).slice(0, 2048) }); } +}); diff --git a/package-lock.json b/package-lock.json index d239a90..65de9b7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,9 +9,12 @@ "version": "1.16.1", "license": "MIT", "dependencies": { + "@huggingface/transformers": "4.3.2", "electron-updater": "^6.8.11", "jszip": "^3.10.2", - "mammoth": "^1.13.0" + "mammoth": "^1.13.0", + "pdfjs-dist": "6.5.438", + "sqlite-vec": "0.1.9" }, "devDependencies": { "@embedpdf/pdfium": "2.15.1", @@ -33,7 +36,6 @@ "katex": "^0.19.1", "mdast-util-from-markdown": "^2.1.0", "pdf-lib": "1.17.1", - "pdfjs-dist": "^6.5.438", "playwright-core": "^1.65.0", "react": "^19.3.1", "react-dom": "^19.3.1", @@ -562,6 +564,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@exodus/bytes": { "version": "1.16.0", "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", @@ -569,15 +581,591 @@ "dev": true, "license": "MIT", "engines": { - "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, + "node_modules/@huggingface/jinja": { + "version": "0.5.11", + "resolved": "https://registry.npmjs.org/@huggingface/jinja/-/jinja-0.5.11.tgz", + "integrity": "sha512-YzEzwM5oQf4r0vs7ifWQ+yuVR1YkAHrjERQ+a8WRsStHHp4NRBg+NesjiFc+X2AFUpRvvrIeHDS1xFy9jY/IjQ==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@huggingface/tokenizers": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@huggingface/tokenizers/-/tokenizers-0.2.0.tgz", + "integrity": "sha512-LidMHe1FpcSYH4vcSjXooda34pC0M8m1gmDOv7SQi6Iv+ib1zX7J3sHBCC9/3FPCkn2k1b55FneVqMRxrr99pg==", + "license": "Apache-2.0" + }, + "node_modules/@huggingface/transformers": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@huggingface/transformers/-/transformers-4.3.2.tgz", + "integrity": "sha512-V3+dqf3iWlRYJ9I9GreM3zGQd0lAXnnoPeddmkOQYWAEE4l/+Fi6p7tx/qVUJlKQgLXGim2W76rTOzz+eC0i7g==", + "license": "Apache-2.0", + "dependencies": { + "@huggingface/jinja": "^0.5.10", + "@huggingface/tokenizers": "^0.2.0", + "onnxruntime-node": "1.30.0", + "onnxruntime-web": "1.31.0-dev.20260914-8d85527a0", + "sharp": "^0.35.4" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", + "cpu": [ + "riscv64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", + "cpu": [ + "riscv64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" }, - "peerDependencies": { - "@noble/hashes": "^1.8.0 || ^2.0.0" + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" }, - "peerDependenciesMeta": { - "@noble/hashes": { - "optional": true - } + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, "node_modules/@isaacs/fs-minipass": { @@ -659,7 +1247,6 @@ "version": "1.0.13", "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-1.0.13.tgz", "integrity": "sha512-b87ugZpQ5ViwqVBkjervxpwa0GmJPsKHLBNoZN6GpjWeHzTbDUGryriq+2DYW2XbB+xCqSIINQysC0/I87nPbw==", - "dev": true, "license": "MIT", "optional": true, "workspaces": [ @@ -693,7 +1280,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -714,7 +1300,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -735,7 +1320,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -756,7 +1340,6 @@ "cpu": [ "arm" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -777,7 +1360,6 @@ "cpu": [ "arm64" ], - "dev": true, "libc": [ "glibc" ], @@ -801,7 +1383,6 @@ "cpu": [ "arm64" ], - "dev": true, "libc": [ "musl" ], @@ -825,7 +1406,6 @@ "cpu": [ "riscv64" ], - "dev": true, "libc": [ "glibc" ], @@ -849,7 +1429,6 @@ "cpu": [ "x64" ], - "dev": true, "libc": [ "glibc" ], @@ -873,7 +1452,6 @@ "cpu": [ "x64" ], - "dev": true, "libc": [ "musl" ], @@ -897,7 +1475,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -918,7 +1495,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -1040,6 +1616,63 @@ "node": ">=14.18.0" } }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", + "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", + "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", + "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz", + "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==", + "license": "BSD-3-Clause" + }, "node_modules/@rolldown/binding-android-arm-eabi": { "version": "1.2.16", "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.16.tgz", @@ -1504,7 +2137,6 @@ "version": "24.19.2", "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz", "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==", - "dev": true, "license": "MIT", "dependencies": { "undici-types": ">=7.24.0 <7.24.7" @@ -2056,6 +2688,15 @@ "node": "^20.17.0 || >=22.9.0" } }, + "node_modules/adm-zip": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.6.1.tgz", + "integrity": "sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ==", + "license": "MIT", + "engines": { + "node": ">=14.0" + } + }, "node_modules/agent-base": { "version": "7.1.4", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", @@ -2958,9 +3599,7 @@ "version": "1.1.4", "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", - "dev": true, "license": "MIT", - "optional": true, "dependencies": { "es-define-property": "^1.0.0", "es-errors": "^1.3.0", @@ -2977,9 +3616,7 @@ "version": "1.2.1", "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", - "dev": true, "license": "MIT", - "optional": true, "dependencies": { "define-data-property": "^1.0.1", "has-property-descriptors": "^1.0.0", @@ -3023,7 +3660,6 @@ "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "dev": true, "license": "Apache-2.0", "engines": { "node": ">=8" @@ -3409,7 +4045,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -3419,7 +4054,6 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -3483,9 +4117,7 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "dev": true, "license": "MIT", - "optional": true, "engines": { "node": ">=10" }, @@ -3630,6 +4262,12 @@ "node": ">=10" } }, + "node_modules/flatbuffers": { + "version": "25.9.23", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.9.23.tgz", + "integrity": "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==", + "license": "Apache-2.0" + }, "node_modules/form-data": { "version": "4.0.6", "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", @@ -3834,9 +4472,7 @@ "version": "1.0.4", "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", - "dev": true, "license": "MIT", - "optional": true, "dependencies": { "define-properties": "^1.2.1", "gopd": "^1.0.1" @@ -3852,7 +4488,6 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -3893,6 +4528,12 @@ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", "license": "ISC" }, + "node_modules/guid-typescript": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/guid-typescript/-/guid-typescript-1.0.9.tgz", + "integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==", + "license": "ISC" + }, "node_modules/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", @@ -3907,9 +4548,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", - "dev": true, "license": "MIT", - "optional": true, "dependencies": { "es-define-property": "^1.0.0" }, @@ -4927,6 +5566,12 @@ "deprecated": "This package is deprecated. Use require('node:util').isDeepStrictEqual instead.", "license": "MIT" }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, "node_modules/longest-streak": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz", @@ -6081,9 +6726,7 @@ "version": "1.1.1", "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", - "dev": true, "license": "MIT", - "optional": true, "engines": { "node": ">= 0.4" } @@ -6112,6 +6755,106 @@ "wrappy": "1" } }, + "node_modules/onnxruntime-common": { + "version": "1.30.0", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.30.0.tgz", + "integrity": "sha512-7fdVWjAID1dVhH/G8qK3APARunV4VkBFoCQAP7qp4Wkab0mrorvmc+sqiT+mKXOzDqdjN5j+/Z9nb4gzNPWcyA==", + "license": "MIT" + }, + "node_modules/onnxruntime-node": { + "version": "1.30.0", + "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.30.0.tgz", + "integrity": "sha512-twhs1C2C/BFkz1yc5OY0KIU2GUq6DURO7hD4bx5Q2Qy3nAMJwRXW8xU3NVczE29VA9lolLOYepoD8fjTGOfIqw==", + "hasInstallScript": true, + "license": "MIT", + "os": [ + "win32", + "darwin", + "linux" + ], + "dependencies": { + "adm-zip": "^0.6.0", + "global-agent": "^4.1.3", + "onnxruntime-common": "1.30.0" + } + }, + "node_modules/onnxruntime-node/node_modules/global-agent": { + "version": "4.1.7", + "resolved": "https://registry.npmjs.org/global-agent/-/global-agent-4.1.7.tgz", + "integrity": "sha512-pxaZqdsMwPA4i7TuRKpDUONm2xGRjvYdRoidCQz7VleUKVuUfh/4p5Q3QDTGrpAE5Kz5TxxcZ+uqEgTkoKRNtg==", + "license": "BSD-3-Clause", + "dependencies": { + "globalthis": "^1.0.2", + "matcher": "^4.0.0", + "semver": "^7.3.5", + "serialize-error": "^8.1.0" + }, + "engines": { + "node": ">=10.0" + } + }, + "node_modules/onnxruntime-node/node_modules/matcher": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/matcher/-/matcher-4.0.0.tgz", + "integrity": "sha512-S6x5wmcDmsDRRU/c2dkccDwQPXoFczc5+HpQ2lON8pnvHlnvHAHj5WlLVvw6n6vNyHuVugYrFohYxbS+pvFpKQ==", + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/onnxruntime-node/node_modules/serialize-error": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-8.1.0.tgz", + "integrity": "sha512-3NnuWfM6vBYoy5gZFvHiYsVbafvI9vZv/+jlIigFn4oP4zjNPK3LhcY0xSCgeb1a5L8jO71Mit9LlNoi2UfDDQ==", + "license": "MIT", + "dependencies": { + "type-fest": "^0.20.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/onnxruntime-node/node_modules/type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/onnxruntime-web": { + "version": "1.31.0-dev.20260914-8d85527a0", + "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.31.0-dev.20260914-8d85527a0.tgz", + "integrity": "sha512-Iy7rtadoBgxS/LLvDr3QW38DB1PNXRnr0GJMcL0TAt7c9qjgVQl83UlGCVyeAnK2InpmW8Uc3PL8XIuqtDeF6g==", + "license": "MIT", + "dependencies": { + "flatbuffers": "^25.1.24", + "guid-typescript": "^1.0.9", + "long": "^5.2.3", + "onnxruntime-common": "1.31.0-dev.20260911-2a43ec07e", + "platform": "^1.3.6", + "protobufjs": "^7.2.4" + } + }, + "node_modules/onnxruntime-web/node_modules/onnxruntime-common": { + "version": "1.31.0-dev.20260911-2a43ec07e", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.31.0-dev.20260911-2a43ec07e.tgz", + "integrity": "sha512-gBuF6U32YErKIAt+yD7DeGBpjRxhJ1uJwako6ygjokSZULDU6Pd+KWComX8Tumk1hYVHRxjPj7mdMnD0ryAPOw==", + "license": "MIT" + }, "node_modules/opencollective-postinstall": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/opencollective-postinstall/-/opencollective-postinstall-2.0.3.tgz", @@ -6251,7 +6994,6 @@ "version": "6.5.438", "resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.5.438.tgz", "integrity": "sha512-vg8Pw1x+AFKy4AMDvhuWl5cOYV8d698UoEANoFFhc79hqXDnZQqnOXoxw3HG907WHOg1JYOvLhP756boddFxpA==", - "dev": true, "license": "Apache-2.0", "engines": { "node": ">=22.13.0 || >=24" @@ -6316,6 +7058,12 @@ "node": ">=16.0.0" } }, + "node_modules/platform": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz", + "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==", + "license": "MIT" + }, "node_modules/playwright-core": { "version": "1.65.0", "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.0.tgz", @@ -6466,6 +7214,29 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/protobufjs": { + "version": "7.6.6", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz", + "integrity": "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.5", + "@protobufjs/eventemitter": "^1.1.1", + "@protobufjs/fetch": "^1.1.1", + "@protobufjs/float": "^1.0.2", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.1", + "@types/node": ">=13.7.0", + "long": "^5.3.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/pump": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", @@ -6879,7 +7650,6 @@ "version": "7.8.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", - "dev": true, "license": "ISC", "bin": { "semver": "bin/semver.js" @@ -6919,6 +7689,55 @@ "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==", "license": "MIT" }, + "node_modules/sharp": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -7019,6 +7838,84 @@ "license": "BSD-3-Clause", "optional": true }, + "node_modules/sqlite-vec": { + "version": "0.1.9", + "resolved": "https://registry.npmjs.org/sqlite-vec/-/sqlite-vec-0.1.9.tgz", + "integrity": "sha512-L7XJWRIBNvR9O5+vh1FQ+IGkh/3D2AzVksW5gdtk28m78Hy8skFD0pqReKH1Yp0/BUKRGcffgKvyO/EON5JXpA==", + "license": "MIT OR Apache", + "optionalDependencies": { + "sqlite-vec-darwin-arm64": "0.1.9", + "sqlite-vec-darwin-x64": "0.1.9", + "sqlite-vec-linux-arm64": "0.1.9", + "sqlite-vec-linux-x64": "0.1.9", + "sqlite-vec-windows-x64": "0.1.9" + } + }, + "node_modules/sqlite-vec-darwin-arm64": { + "version": "0.1.9", + "resolved": "https://registry.npmjs.org/sqlite-vec-darwin-arm64/-/sqlite-vec-darwin-arm64-0.1.9.tgz", + "integrity": "sha512-jSsZpE42OfBkGL/ItyJTVCUwl6o6Ka3U5rc4j+UBDIQzC1ulSSKMEhQLthsOnF/MdAf1MuAkYhkdKmmcjaIZQg==", + "cpu": [ + "arm64" + ], + "license": "MIT OR Apache", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/sqlite-vec-darwin-x64": { + "version": "0.1.9", + "resolved": "https://registry.npmjs.org/sqlite-vec-darwin-x64/-/sqlite-vec-darwin-x64-0.1.9.tgz", + "integrity": "sha512-KDlVyqQT7pnOhU1ymB9gs7dMbSoVmKHitT+k1/xkjarcX8bBqPxWrGlK/R+C5WmWkfvWwyq5FfXfiBYCBs6PlA==", + "cpu": [ + "x64" + ], + "license": "MIT OR Apache", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/sqlite-vec-linux-arm64": { + "version": "0.1.9", + "resolved": "https://registry.npmjs.org/sqlite-vec-linux-arm64/-/sqlite-vec-linux-arm64-0.1.9.tgz", + "integrity": "sha512-5wXVJ9c9kR4CHm/wVqXb/R+XUHTdpZ4nWbPHlS+gc9qQFVHs92Km4bPnCKX4rtcPMzvNis+SIzMJR1SCEwpuUw==", + "cpu": [ + "arm64" + ], + "license": "MIT OR Apache", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/sqlite-vec-linux-x64": { + "version": "0.1.9", + "resolved": "https://registry.npmjs.org/sqlite-vec-linux-x64/-/sqlite-vec-linux-x64-0.1.9.tgz", + "integrity": "sha512-w3tCH8xK2finW8fQJ/m8uqKodXUZ9KAuAar2UIhz4BHILfpE0WM/MTGCRfa7RjYbrYim5Luk3guvMOGI7T7JQA==", + "cpu": [ + "x64" + ], + "license": "MIT OR Apache", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/sqlite-vec-windows-x64": { + "version": "0.1.9", + "resolved": "https://registry.npmjs.org/sqlite-vec-windows-x64/-/sqlite-vec-windows-x64-0.1.9.tgz", + "integrity": "sha512-y3gEIyy/17bq2QFPQOWLE68TYWcRZkBQVA2XLrTPHNTOp55xJi/BBBmOm40tVMDMjtP+Elpk6UBUXdaq+46b0Q==", + "cpu": [ + "x64" + ], + "license": "MIT OR Apache", + "optional": true, + "os": [ + "win32" + ] + }, "node_modules/stackback": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", @@ -7043,15 +7940,6 @@ "dev": true, "license": "MIT" }, - "node_modules/string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "license": "MIT", - "dependencies": { - "safe-buffer": "~5.1.0" - } - }, "node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", @@ -7067,6 +7955,15 @@ "node": ">=8" } }, + "node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, "node_modules/stringify-entities": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", @@ -7393,7 +8290,7 @@ "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "dev": true, + "devOptional": true, "license": "0BSD" }, "node_modules/type-fest": { @@ -7465,7 +8362,6 @@ "version": "7.24.6", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", - "dev": true, "license": "MIT" }, "node_modules/unified": { diff --git a/package.json b/package.json index c6e974c..1b1e535 100644 --- a/package.json +++ b/package.json @@ -15,16 +15,22 @@ "release": "node scripts/release.mjs", "dist:mac": "npm run build && electron-builder --mac --publish never", "dist:linux": "npm run build && electron-builder --linux --publish never", - "smoke": "node scripts/smoke-test.mjs && node scripts/test-print.mjs && node scripts/smoke-print.mjs && node scripts/smoke-print-resolution.mjs", + "smoke": "node scripts/smoke-test.mjs && node scripts/test-print.mjs && node scripts/smoke-print.mjs && node scripts/smoke-print-resolution.mjs && npm run smoke:retrieval", "test": "vitest run", "test:reader-security": "node scripts/test-reader-security.mjs && node scripts/test-url-client-certificates.mjs", "test:chat-math": "node scripts/test-chat-math.mjs", - "test:thumbnails": "node scripts/test-thumbnails.mjs" + "test:thumbnails": "node scripts/test-thumbnails.mjs", + "test:retrieval": "node --test scripts/test-retrieval.cjs", + "smoke:retrieval": "node scripts/smoke-retrieval.mjs", + "benchmark:retrieval": "node scripts/benchmark-retrieval.mjs" }, "dependencies": { + "@huggingface/transformers": "4.3.2", "electron-updater": "^6.8.11", "jszip": "^3.10.2", - "mammoth": "^1.13.0" + "mammoth": "^1.13.0", + "pdfjs-dist": "6.5.438", + "sqlite-vec": "0.1.9" }, "devDependencies": { "@embedpdf/pdfium": "2.15.1", @@ -46,7 +52,6 @@ "katex": "^0.19.1", "mdast-util-from-markdown": "^2.1.0", "pdf-lib": "1.17.1", - "pdfjs-dist": "^6.5.438", "playwright-core": "^1.65.0", "react": "^19.3.1", "react-dom": "^19.3.1", @@ -81,7 +86,9 @@ "dist/**/*", "electron/**/*", "package.json", - "!node_modules/mammoth/mammoth.browser*.js" + "!node_modules/mammoth/mammoth.browser*.js", + "!node_modules/onnxruntime-node/bin/**/libonnxruntime_providers_cuda.so", + "!node_modules/onnxruntime-node/bin/**/libonnxruntime_providers_tensorrt.so" ], "win": { "target": [ @@ -131,6 +138,10 @@ { "from": "dist/.vite/license.md", "to": "licenses/THIRD_PARTY_LICENSES.md" + }, + { + "from": "build/third-party", + "to": "licenses/backend" } ], "electronFuses": { @@ -206,7 +217,14 @@ "artifactName": "Folio-linux-amd64.deb", "afterInstall": "build/linux/after-install.tpl", "afterRemove": "build/linux/after-remove.tpl" - } + }, + "asarUnpack": [ + "node_modules/sqlite-vec*/**/*", + "node_modules/onnxruntime-node/**/*", + "node_modules/@napi-rs/**/*", + "node_modules/@img/**/*", + "node_modules/sharp/**/*" + ] }, "repository": { "type": "git", diff --git a/scripts/benchmark-retrieval.mjs b/scripts/benchmark-retrieval.mjs new file mode 100644 index 0000000..6aa5daf --- /dev/null +++ b/scripts/benchmark-retrieval.mjs @@ -0,0 +1,82 @@ +// Deterministic retrieval fixture; pass FOLIO_BENCHMARK_PAGES=7000 for a large synthetic PDF. +// Real manuals require separately reviewed relevance labels; this fixture is not a quality claim for them. +import assert from 'node:assert/strict'; +import { _electron as electron } from 'playwright-core'; +import { PDFDocument, StandardFonts } from 'pdf-lib'; +import { mkdtempSync, mkdirSync, cpSync, rmSync, writeFileSync, statSync } from 'node:fs'; +import { tmpdir, cpus } from 'node:os'; +import path from 'node:path'; +import { createRequire } from 'node:module'; +import { performance } from 'node:perf_hooks'; +import { electronPath } from './electron-path.mjs'; +import { readerPage } from './reader-page.mjs'; +const require=createRequire(import.meta.url); +const {fingerprint}=require('../electron/retrieval/text.cjs'); +const temp=mkdtempSync(path.join(tmpdir(),'folio-benchmark-')); +const profile=path.join(temp,'profile');mkdirSync(path.join(profile,'retrieval'),{recursive:true}); +if(process.env.FOLIO_MODEL_FIXTURE)cpSync(process.env.FOLIO_MODEL_FIXTURE,path.join(profile,'retrieval/models'),{recursive:true}); +const doc=await PDFDocument.create();const font=await doc.embedFont(StandardFonts.Helvetica); +const texts=[ + 'I2C_CR2 enables the I2C peripheral. Address 0x30AD0000. Set the peripheral enable bit.', + 'Recover from an Ethernet DMA timeout by resetting the DMA controller. CONFIG_FEC FEC_ENET_MII.', + 'A watchdog timeout triggers a software reset of the processor. Configure the reset controller for a software reset.', + 'The PCIe BAR register configures the memory mapping of peripheral address regions.', +]; +const pages=Number(process.env.FOLIO_BENCHMARK_PAGES||texts.length); +for(let i=0;irelevant.includes(r.page)); + const recall=k=>new Set(found.slice(0,k).filter(r=>relevant.includes(r.page)).map(r=>r.page)).size/relevant.length; + const dcg=found.slice(0,10).reduce((s,r,i)=>s+(relevant.includes(r.page)?1/Math.log2(i+2):0),0); + const ideal=relevant.slice(0,10).reduce((s,_,i)=>s+1/Math.log2(i+2),0); + return {recall5:recall(5),recall10:recall(10),mrr10:first<0||first>=10?0:1/(first+1),ndcg10:dcg/ideal}; +} +const env={...process.env,FOLIO_TEST_USER_DATA:profile,FOLIO_TEST_HIDDEN:'1'};delete env.ELECTRON_RUN_AS_NODE; +const app=await electron.launch({executablePath:electronPath(env),args:[path.resolve(import.meta.dirname,'..'),'--mute-audio'],env}); +const report={dataset:'synthetic technical passages; manually assigned page labels',pages,bytes:data.length,cpu:cpus()[0].model,models:[],readerResponseMs:[],peakWorkingSetMB:0,peakTotalWorkingSetMB:0}; +const memory=setInterval(async()=>{ + try{const sizes=await app.evaluate(({app})=>{const metrics=app.getAppMetrics();return {worker:Math.max(0,...metrics.filter(p=>p.name==='Folio local search').map(p=>p.memory.workingSetSize/1024)),total:metrics.reduce((s,p)=>s+p.memory.workingSetSize/1024,0)};});report.peakWorkingSetMB=Math.max(report.peakWorkingSetMB,sizes.worker);report.peakTotalWorkingSetMB=Math.max(report.peakTotalWorkingSetMB,sizes.total);}catch{} +},200); +try{ + const page=readerPage(await app.firstWindow());await page.getByRole('button',{name:/Try a sample/}).waitFor(); + const opened=performance.now(); + await app.evaluate(({BrowserWindow},bytes)=>BrowserWindow.getAllWindows()[0].webContents.send('folio:open-file',{name:'benchmark.pdf',data:Buffer.from(bytes)}),[...data]); + await page.locator('.textLayer span:not(.markedContent)').first().waitFor();report.openMs=performance.now()-opened; + const catalog=await page.evaluate(()=>window.folioDesktop.retrieval.catalog()); + for(const model of [null,...catalog.models.filter(m=>m.state==='ready'&&m.enabled)]){ + await page.evaluate(s=>window.folioDesktop.retrieval.configure(s),catalog.settings); + const start=performance.now(); + await page.evaluate(({documentId,bytes,model})=>window.folioDesktop.retrieval.index({documentId,name:'benchmark.pdf',data:new Uint8Array(bytes),model}),{documentId,bytes:[...data],model:model?.id}); + let sample=0; + for(;;){ + const status=await page.evaluate(({documentId,model})=>window.folioDesktop.retrieval.status(documentId,model),{documentId,model:model?.id}); + if(status.state==='failed')throw new Error(status.error); + if(status.state==='complete')break; + if(sample++%10===0){const tick=performance.now();const n=sample%2?2:1;await page.getByRole('textbox',{name:'Page number',exact:true}).fill(String(n));await page.getByRole('textbox',{name:'Page number',exact:true}).press('Enter');report.readerResponseMs.push(performance.now()-tick);} + await new Promise(r=>setTimeout(r,100)); + } + const indexMs=performance.now()-start; + for(const mode of model?['semantic','hybrid']:['exact']){ + const runs=[]; + if(model && mode==='semantic')await page.evaluate(s=>window.folioDesktop.retrieval.configure(s),{...catalog.settings,threads:1}); + for(let iteration=0;iteration<2;iteration++)for(const label of labels){ + const before=performance.now(); + const results=await page.evaluate(req=>window.folioDesktop.retrieval.search(req),{id:crypto.randomUUID(),documentId,model:model?.id,mode,query:label.query,scope:'document',limit:10}); + runs.push({query:label.query,iteration,latencyMs:performance.now()-before,...metrics(results,label.pages)}); + } + const mean=field=>runs.reduce((s,r)=>s+r[field],0)/runs.length; + report.models.push({model:model?.id||'none',mode,indexMs,recall5:mean('recall5'),recall10:mean('recall10'),mrr10:mean('mrr10'),ndcg10:mean('ndcg10'),firstQueryMs:runs[0].latencyMs,warmMeanMs:runs.slice(5).reduce((s,r)=>s+r.latencyMs,0)/5}); + } + } + report.databaseBytes=['search.sqlite','search.sqlite-wal'].reduce((sum,name)=>sum+(statSync(path.join(profile,'retrieval',name),{throwIfNoEntry:false})?.size||0),0); + const output=process.env.FOLIO_BENCHMARK_REPORT||path.resolve('release/retrieval-benchmark.json');mkdirSync(path.dirname(output),{recursive:true});writeFileSync(output,JSON.stringify(report,null,2)+'\n');console.log(JSON.stringify(report,null,2)); + assert.equal(report.models[0].mode,'exact'); +}finally{clearInterval(memory);await app.close();rmSync(temp,{recursive:true,force:true});} diff --git a/scripts/screenshots.mjs b/scripts/screenshots.mjs index 2b25f87..ef57bc3 100644 --- a/scripts/screenshots.mjs +++ b/scripts/screenshots.mjs @@ -75,7 +75,7 @@ try { await theme("dark"); await page.keyboard.press("ControlOrMeta+f"); - await page.getByLabel("Find in document").fill("lighthouse"); + await page.getByRole("textbox", { name: "Find in document", exact: true }).fill("lighthouse"); await page.keyboard.press("Enter"); await shot("search"); } finally { diff --git a/scripts/smoke-retrieval.mjs b/scripts/smoke-retrieval.mjs new file mode 100644 index 0000000..9be923b --- /dev/null +++ b/scripts/smoke-retrieval.mjs @@ -0,0 +1,235 @@ +import assert from 'node:assert/strict'; +import { _electron as electron } from 'playwright-core'; +import { PDFDocument, StandardFonts } from 'pdf-lib'; +import { mkdtempSync, writeFileSync, rmSync, cpSync, mkdirSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { createRequire } from 'node:module'; +import { electronPath } from './electron-path.mjs'; +import { readerPage } from './reader-page.mjs'; +const require = createRequire(import.meta.url); +const { fingerprint } = require('../electron/retrieval/text.cjs'); +const temp = mkdtempSync(path.join(tmpdir(), 'folio-search-smoke-')); +const profile = path.join(temp, 'profile'); +if (process.env.FOLIO_MODEL_FIXTURE) { + mkdirSync(path.join(profile, 'retrieval'), { recursive: true }); + cpSync(process.env.FOLIO_MODEL_FIXTURE, path.join(profile, 'retrieval/models'), { recursive: true }); +} +if (process.env.FOLIO_DOWNLOAD_FIXTURE) { + mkdirSync(path.join(profile, 'retrieval'), { recursive: true }); + cpSync(process.env.FOLIO_DOWNLOAD_FIXTURE, path.join(profile, 'retrieval/downloads'), { recursive: true }); +} +const doc = await PDFDocument.create(); +const font = await doc.embedFont(StandardFonts.Courier); +const passages = [ + 'The I2C_CR2 register enables the I2C peripheral at 0x30AD0000.', + 'Recover from an Ethernet DMA timeout by resetting the DMA controller. CONFIG_FEC FEC_ENET_MII', + 'A watchdog timeout triggers a software reset of the processor.', + 'The PCIe BAR register configures the memory mapping for the peripheral.', +]; +for (const text of passages) doc.addPage([800, 600]).drawText(text, { x: 20, y: 500, font, size: 10 }); +const data = await doc.save(); +const file = path.join(temp, 'technical.pdf');writeFileSync(file, data); +const documentId = fingerprint(data); +const env = { ...process.env, FOLIO_TEST_USER_DATA: profile, FOLIO_TEST_HIDDEN: '1' }; +delete env.ELECTRON_RUN_AS_NODE; +const executablePath = electronPath(env); +let app; +async function launch() { + app = await electron.launch({executablePath,args:[process.env.FOLIO_TEST_ASAR || path.resolve(import.meta.dirname,'..'),'--mute-audio',...(process.platform==='linux' && process.getuid?.()===0?['--no-sandbox']:[])],env,timeout:60000}); + app.process().stderr.on('data', data => { if (String(data).includes('[local search]') || process.env.FOLIO_TEST_VERBOSE === '1') process.stderr.write(data); }); + return readerPage(await app.firstWindow()); +} +async function selectPdfText(page,text) { + await page.evaluate(text=>{ + const walker=document.createTreeWalker(document.querySelector('.pdfViewer'),NodeFilter.SHOW_TEXT); + let node; + while(node=walker.nextNode()) { + if(!node.parentElement.closest('.textLayer'))continue; + const offset=node.textContent.indexOf(text); + if(offset<0)continue; + const range=document.createRange();range.setStart(node,offset);range.setEnd(node,offset+text.length); + const selection=window.getSelection();selection.removeAllRanges();selection.addRange(range);return; + } + throw new Error('PDF text not found: '+text); + },text); +} +async function until(fn, predicate, timeout=30000) { + const deadline=Date.now()+timeout; + for(;;) { const result=await fn(); if(predicate(result))return result; if(Date.now()>deadline)throw new Error('Timed out: '+JSON.stringify(result)); await new Promise(r=>setTimeout(r,100)); } +} +try { + let page = await launch(); + await page.getByRole('button',{name:/Try a sample/}).waitFor(); + assert.equal(await app.evaluate(({app})=>app.getAppMetrics().filter(p=>p.name==='Folio local search').length),0,'startup must not start retrieval'); + await app.evaluate(({BrowserWindow},bytes)=>BrowserWindow.getAllWindows()[0].webContents.send('folio:open-file',{name:'technical.pdf',data:Buffer.from(bytes)}),[...data]); + await page.locator('.textLayer span').first().waitFor(); + assert.equal(await app.evaluate(({app})=>app.getAppMetrics().filter(p=>p.name==='Folio local search').length),0,'opening a PDF must not start retrieval'); + await selectPdfText(page,'I2C_CR2'); + await page.keyboard.press(process.platform==='darwin'?'Meta+f':'Control+f'); + assert.equal(await page.getByRole('textbox',{name:'Find in document'}).inputValue(),'I2C_CR2'); + await page.locator('.search-result-list button').first().waitFor(); + assert.equal(await app.evaluate(({app})=>app.getAppMetrics().filter(p=>p.name==='Folio local search').length),0,'normal find must not start retrieval'); + const basicPanel=page.getByRole('complementary',{name:'Find in document',exact:true}); + await basicPanel.waitFor(); + assert.ok(await basicPanel.evaluate(el=>!el.closest('main')),'basic find is a sidebar beside the reader'); + const basicField=page.getByRole('textbox',{name:'Find in document'}); + await basicField.fill('THE'); + await basicPanel.getByTitle('Match case',{exact:true}).click(); + await until(()=>basicPanel.locator('.search-status').innerText(),text=>text==='No results'); + await basicPanel.getByTitle('Match case',{exact:true}).click(); + await until(()=>basicPanel.locator('.search-result-list button').count(),n=>n===4); + const match=await basicPanel.locator('.search-status').innerText(); + await basicField.press('Enter'); + await until(()=>basicPanel.locator('.search-status').innerText(),text=>text!==match&&/of/.test(text)); + await basicField.press('Shift+Enter'); + await until(()=>basicPanel.locator('.search-status').innerText(),text=>text===match); + await basicPanel.getByTitle('Whole words',{exact:true}).click(); + assert.equal(await basicPanel.getByTitle('Whole words',{exact:true}).getAttribute('aria-pressed'),'true'); + const basicBounds=await app.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows()[0].getBounds()); + await app.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows()[0].setSize(1100,500)); + const basicResults=basicPanel.getByRole('region',{name:'Search results'}); + await until(()=>basicResults.evaluate(el=>el.scrollHeight>el.clientHeight),value=>value); + const basicPosition=await basicField.boundingBox(); + await basicResults.evaluate(el=>{el.scrollTop=el.scrollHeight;}); + assert.ok(Math.abs((await basicField.boundingBox()).y-basicPosition.y)<2,'basic search input stays fixed while results scroll'); + await app.evaluate(({BrowserWindow},bounds)=>BrowserWindow.getAllWindows()[0].setSize(bounds.width,bounds.height),basicBounds); + await until(()=>basicPanel.locator('.search-result-list button').count(),n=>n===4); + mkdirSync(path.resolve('release/smoke'),{recursive:true}); + await page.screenshot({path:path.resolve('release/smoke/basic-search-sidebar.png')}); + console.log('ok basic find sidebar, case/word options, Enter navigation and fixed query field'); + await selectPdfText(page,'0x30AD0000'); + await page.keyboard.press(process.platform==='darwin'?'Meta+f':'Control+f'); + await until(()=>page.getByRole('textbox',{name:'Find in document'}).inputValue(),q=>q==='0x30AD0000'); + console.log('ok zero-AI startup, PDF rendering and normal find with selected text'); + await selectPdfText(page,'I2C_CR2'); + await page.keyboard.press(process.platform==='darwin'?'Meta+Shift+f':'Control+Shift+f'); + const panel=page.getByRole('complementary',{name:'Semantic search',exact:true}); + await panel.waitFor(); + assert.equal(await page.getByRole('textbox',{name:'Find in document'}).count(),0); + assert.ok(await page.getByRole('searchbox',{name:'Search passages'}).evaluate(el=>el===document.activeElement)); + assert.equal(await page.getByRole('searchbox',{name:'Search passages'}).inputValue(),'I2C_CR2'); + await page.getByRole('searchbox',{name:'Search passages'}).fill(''); + await page.getByRole('combobox',{name:'Search mode'}).selectOption('exact'); + + await page.getByRole('button',{name:'Index document',exact:true}).click(); + await until(()=>page.evaluate(id=>window.folioDesktop.retrieval.status(id),documentId),s=>{if(s.state==='failed')throw new Error(s.error);return s.state==='complete';}); + const field=page.getByRole('searchbox',{name:'Search passages'}); + const shots=path.resolve('release/smoke');mkdirSync(shots,{recursive:true}); + await page.screenshot({path:path.join(shots,'semantic-search-options.png')}); + const beforeTyping=await field.boundingBox(); + await field.fill('CONFIG_FEC'); + await page.getByRole('button',{name:'Locate passage on page 2'}).click(); + await until(()=>page.getByRole('textbox',{name:'Page number',exact:true}).inputValue(),v=>v==='2'); + await page.locator('.page[data-page-number="2"] .textLayer .highlight').first().waitFor(); + assert.equal(await page.getByRole('combobox',{name:'Search mode'}).count(),0,'typing hides the configuration'); + const afterTyping=await field.boundingBox(); + assert.ok(Math.abs(afterTyping.y-beforeTyping.y)<2,'the search field stays fixed at the bottom'); + await page.screenshot({path:path.join(shots,'semantic-search-results.png')}); + const bounds=await app.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows()[0].getBounds()); + await app.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows()[0].setSize(1100,500)); + await field.fill('the'); + await until(()=>panel.locator('.semantic-results button').count(),n=>n===4); + const body=panel.locator('.semantic-body'); + assert.ok(await body.evaluate(el=>el.scrollHeight>el.clientHeight),'results scroll inside the sidebar'); + const beforeScroll=await field.boundingBox(); + await body.evaluate(el=>{el.scrollTop=el.scrollHeight;}); + assert.ok(Math.abs((await field.boundingBox()).y-beforeScroll.y)<2,'scrolling results does not move the query field'); + await app.evaluate(({BrowserWindow},bounds)=>BrowserWindow.getAllWindows()[0].setSize(bounds.width,bounds.height),bounds); + await selectPdfText(page,'FEC_ENET_MII'); + await page.keyboard.press(process.platform==='darwin'?'Meta+Shift+f':'Control+Shift+f'); + await until(()=>field.inputValue(),q=>q==='FEC_ENET_MII'); + await page.getByRole('button',{name:'Locate passage on page 2'}).waitFor(); + console.log('ok selected PDF text pre-fills both shortcuts, including already-open panels'); + await page.getByRole('button',{name:'Search options',exact:true}).click(); + await page.getByRole('combobox',{name:'Search mode'}).waitFor(); + assert.equal(await field.inputValue(),'FEC_ENET_MII','opening options preserves the query'); + await field.fill(''); + await page.getByRole('combobox',{name:'Search mode'}).waitFor(); + await page.getByRole('button',{name:'Close semantic search',exact:true}).click(); + await page.getByRole('button',{name:/Semantic search \(/}).click(); + await panel.waitFor(); + await page.getByRole('button',{name:'Ask AI',exact:true}).click(); + assert.equal(await panel.count(),0,'the two right panels share the same space'); + await page.keyboard.press(process.platform==='darwin'?'Meta+Shift+f':'Control+Shift+f'); + await panel.waitFor(); + assert.equal(await page.getByRole('complementary',{name:'Ask AI',exact:true}).count(),0); + await field.fill('temporary query'); + await field.press('Escape'); + assert.equal(await panel.count(),0); + await page.keyboard.press(process.platform==='darwin'?'Meta+f':'Control+f'); + await page.getByRole('textbox',{name:'Find in document'}).waitFor(); + assert.equal(await panel.count(),0,'normal find stays independent'); + await page.keyboard.press(process.platform==='darwin'?'Meta+Shift+f':'Control+Shift+f'); + await panel.waitFor(); + await field.fill(''); + console.log('ok dedicated icon/shortcut, fixed composer, automatic results and configuration visibility'); + console.log('ok persistent FTS5 extraction, identifier search and page navigation'); + const status=await page.evaluate(id=>window.folioDesktop.retrieval.status(id),documentId); + assert.equal(status.pages,4); + if(process.env.FOLIO_TEST_MODELS==='1') { + await page.getByRole('button',{name:'Manage embedding models'}).click(); + const settings=page.getByRole('dialog',{name:'Settings'}); + for(const [id,name] of [['bge-small-en-v1.5','BGE Small EN v1.5'],['all-MiniLM-L6-v2','all-MiniLM-L6-v2'],...(process.env.FOLIO_TEST_ALL_MODELS === '1' ? [['embeddinggemma-300m','EmbeddingGemma 300M'],['qwen3-embedding-0.6b','Qwen3 Embedding 0.6B']] : [])]) { + const card=settings.locator('.embedding-model').filter({hasText:name}); + if (await card.getByRole('checkbox').count()) await card.getByRole('checkbox').check(); + if (await card.getByRole('button',{name:'Install',exact:true}).count()) await card.getByRole('button',{name:'Install',exact:true}).click(); + await until(()=>page.evaluate(()=>window.folioDesktop.retrieval.catalog()),c=>{ + const m=c.models.find(m=>m.id===id); + if(m.state==='failed')throw new Error(m.error); + return m.state==='ready'; + },600000); + await page.evaluate(async({id,documentId})=>window.folioDesktop.retrieval.index({documentId,name:'technical.pdf',model:id}),{id,documentId}); + await until(()=>page.evaluate(({documentId,id})=>window.folioDesktop.retrieval.status(documentId,id),{documentId,id}),s=>{ + if(s.state==='failed')throw new Error(s.error); + return s.state==='complete'&&s.embedded===s.chunks; + },180000); + assert.equal((await page.evaluate(id=>window.folioDesktop.retrieval.status(id),documentId)).pages,4); + const config=await page.evaluate(()=>window.folioDesktop.retrieval.catalog()); + await page.evaluate(s=>window.folioDesktop.retrieval.configure(s),{...config.settings,offline:true}); + for(const mode of ['semantic','hybrid']) { + const results=await page.evaluate(({documentId,id,mode})=>window.folioDesktop.retrieval.search({id:crypto.randomUUID(),documentId,model:id,mode,scope:'document',limit:5,query:'How to recover from an Ethernet DMA timeout?'}),{documentId,id,mode}); + assert.equal(results[0].page,2,`${name} ${mode}`); + } + if (['embeddinggemma-300m','qwen3-embedding-0.6b'].includes(id)) { + const found = await page.evaluate(({documentId,id})=>window.folioDesktop.retrieval.search({id:crypto.randomUUID(),documentId,model:id,mode:'semantic',scope:'document',limit:5,query:'Come recuperare dopo un timeout del DMA Ethernet?'}),{documentId,id}); + assert.equal(found[0].page,2,'Italian queries against English passages'); + } + await page.evaluate(s=>window.folioDesktop.retrieval.configure(s),{...config.settings,offline:false}); + console.log('ok verified model installation and offline retrieval:',name); + } + await settings.getByRole('button',{name:'Close',exact:true}).click(); + await page.getByRole('combobox',{name:'Search mode'}).selectOption('semantic'); + await page.getByRole('combobox',{name:'Embedding model'}).selectOption('bge-small-en-v1.5'); + await page.getByRole('searchbox',{name:'Search passages'}).fill('How do I recover an Ethernet DMA timeout?'); + await page.getByRole('searchbox',{name:'Search passages'}).press('Enter'); + await page.getByRole('button',{name:'Locate passage on page 2'}).first().click(); + assert.equal(await page.getByRole('textbox',{name:'Page number',exact:true}).inputValue(),'2'); + console.log('ok semantic search UI refreshes after model installation'); + } + const largeDoc=await PDFDocument.create();const largeFont=await largeDoc.embedFont(StandardFonts.Helvetica); + for(let i=0;i<1000;i++)largeDoc.addPage().drawText(`Persistent register table CONFIG_FEC page ${i+1}`,{x:20,y:700,font:largeFont,size:10}); + const largeBytes=await largeDoc.save(),largeId=fingerprint(largeBytes); + await page.evaluate(({documentId,bytes})=>window.folioDesktop.retrieval.index({documentId,name:'resume.pdf',data:new Uint8Array(bytes)}),{documentId:largeId,bytes:[...largeBytes]}); + await until(()=>page.evaluate(id=>window.folioDesktop.retrieval.status(id),largeId),s=>s.pages>0); + await page.evaluate(id=>window.folioDesktop.retrieval.pause(id),largeId); + const paused=await until(()=>page.evaluate(id=>window.folioDesktop.retrieval.status(id),largeId),s=>s.state==='paused'); + assert.ok(paused.pages>0 && paused.pages<1000); + const partial=await page.evaluate(documentId=>window.folioDesktop.retrieval.search({id:crypto.randomUUID(),documentId,query:'CONFIG_FEC',mode:'exact',limit:5,scope:'document'}),largeId); + assert.ok(partial.length>0); + console.log('ok pause and partial-index search'); + await app.close();app=null; + page=await launch(); + await page.waitForFunction(() => !!window.folioDesktop?.retrieval); + const resumed=await page.evaluate(id=>window.folioDesktop.retrieval.status(id),documentId); + assert.equal(resumed.pages,4);assert.equal(resumed.chunks,status.chunks); + console.log('ok indexes survive application restart'); + const checkpoint=await page.evaluate(id=>window.folioDesktop.retrieval.status(id),largeId);assert.equal(checkpoint.pages,paused.pages); + await page.evaluate(({documentId,bytes})=>window.folioDesktop.retrieval.index({documentId,name:'resume.pdf',data:new Uint8Array(bytes)}),{documentId:largeId,bytes:[...largeBytes]}); + await page.evaluate(id=>window.folioDesktop.retrieval.cancelIndex(id),largeId); + await until(()=>page.evaluate(id=>window.folioDesktop.retrieval.status(id),largeId),s=>s.state==='cancelled'); + await page.evaluate(({documentId,bytes})=>window.folioDesktop.retrieval.index({documentId,name:'resume.pdf',data:new Uint8Array(bytes)}),{documentId:largeId,bytes:[...largeBytes]}); + const completed=await until(()=>page.evaluate(id=>window.folioDesktop.retrieval.status(id),largeId),s=>s.state==='complete'); + assert.equal(completed.pages,1000);assert.equal(completed.chunks,1000); + console.log('ok resume after restart without duplicate pages or chunks'); +} finally { if(app)await app.close(); if(process.env.FOLIO_KEEP_TEST_PROFILE==='1')console.log('Profile:',profile);else rmSync(temp,{recursive:true,force:true}); } diff --git a/scripts/smoke-test.mjs b/scripts/smoke-test.mjs index ca9ca45..9ddee14 100644 --- a/scripts/smoke-test.mjs +++ b/scripts/smoke-test.mjs @@ -69,6 +69,8 @@ async function checkStaysHidden() { } try { const page = readerPage(await app.firstWindow()); + // Keep desktop checks independent of the host display; the narrow layout is tested separately below. + await page.window.setViewportSize({ width: 1360, height: 900 }); assert.ok(await app.evaluate(({ app }) => app.commandLine.hasSwitch("mute-audio"))); page.on("pageerror", (error) => { console.error(error.stack ?? String(error)); @@ -115,11 +117,11 @@ try { // The list of matching pages quotes each page's first match. The words it marks are the ones searched for, // also when the match sits many lines down the page. (Text with ligatures is checked at the end.) await page.getByRole("button", { name: /^Search/ }).click(); - await page.getByLabel("Find in document").fill("highlight"); + await page.getByRole("textbox", { name: "Find in document", exact: true }).fill("highlight"); const quoted = page.locator(".search-result-list mark"); await quoted.nth(2).waitFor(); assert.deepEqual((await quoted.allTextContents()).map((text) => text.toLowerCase()), ["highlight", "highlight", "highlight"]); - await page.getByLabel("Find in document").press("Escape"); + await page.getByRole("textbox", { name: "Find in document", exact: true }).press("Escape"); console.log("ok search results mark the words that were searched for"); // A dialog keeps the keyboard: the reader's one-key shortcuts don't act on the document behind it. @@ -163,6 +165,9 @@ try { const sidebarWasOpen = await sidebarToggle.getAttribute("aria-pressed") === "true"; if (!sidebarWasOpen) await sidebarToggle.click(); await page.getByRole("tab", { name: "Pages" }).click(); + // Earlier search checks may leave another page active; bookmarking must keep page 1 selected. + await page.getByRole("button", { name: "Page 1", exact: true }).click(); + await page.waitForFunction(() => document.querySelector('input[aria-label="Page number"]').value === "1"); const bookmark = page.getByRole("button", { name: "Bookmark page 2", exact: true }); await bookmark.click(); assert.equal(await bookmark.getAttribute("aria-pressed"), "true"); @@ -1273,7 +1278,7 @@ try { await page.window.waitForFunction(() => document.title.startsWith("Ligatures.pdf")); await page.locator(".textLayer span:not(.markedContent)").first().waitFor(); await page.getByRole("button", { name: /^Search/ }).click(); - await page.getByLabel("Find in document").fill("zebra"); + await page.getByRole("textbox", { name: "Find in document", exact: true }).fill("zebra"); await quoted.first().waitFor(); assert.deepEqual(await quoted.allTextContents(), ["zebra"]); console.log("ok search results mark the right words in text with ligatures"); diff --git a/scripts/test-retrieval.cjs b/scripts/test-retrieval.cjs new file mode 100644 index 0000000..d000196 --- /dev/null +++ b/scripts/test-retrieval.cjs @@ -0,0 +1,135 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { Store } = require('../electron/retrieval/store.cjs'); +const { chunks, pageText, fingerprint, fuse } = require('../electron/retrieval/text.cjs'); +const { format, normalized } = require('../electron/retrieval/provider.cjs'); +const { downloadFile, valid } = require('../electron/retrieval/download.cjs'); +const catalog = require('../electron/retrieval/models.json'); +const { createHash } = require('node:crypto'); +const id = fingerprint(Buffer.from('document')); +const model = { key: 'test@immutable:3', dimension: 3 }; +function fixture(t) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'folio-retrieval-')); + const db = new Store(path.join(dir, 'test.sqlite')); + t.after(() => { db.close(); fs.rmSync(dir, { recursive: true, force: true }); }); + db.document(id, 'manual.pdf', 2); + return db; +} +test('page extraction keeps cell identifiers separate and preserves EOL', () => { + assert.equal(pageText([{str:'I2C_CR2',hasEOL:false},{str:'0x30AD0000',hasEOL:true},{type:'marker'},{str:'CONFIG_FEC'}]), 'I2C_CR2 0x30AD0000\nCONFIG_FEC'); +}); +test('chunk offsets, overlap and full coverage, including punctuation/tables', () => { + const text = Array.from({length:2000}, (_,i) => `register_${i}\t0x30AD0000\n`).join(''); + const result = chunks(text, 100, 20); + assert.ok(result.length > 10); + assert.equal(result[0].start, 0); + assert.equal(result.at(-1).end, text.trimEnd().length); + result.forEach((chunk,i) => { + assert.equal(chunk.text, text.slice(chunk.start,chunk.end)); + if(i) { assert.ok(chunk.start > result[i-1].start); assert.ok(chunk.start < result[i-1].end); } + }); +}); +test('fingerprints distinguish modifications and ignore filenames', () => { + assert.equal(fingerprint(Buffer.from('a')),fingerprint(Buffer.from('a'))); + assert.notEqual(fingerprint(Buffer.from('a')),fingerprint(Buffer.from('b'))); +}); +test('FTS5 preserves register identifiers, hex and phrases with hostile query syntax', t => { + const db=fixture(t); + db.page(id,1,'I2C_CR2 0x30AD0000 CONFIG_FEC DMA_SxCR FEC_ENET_MII software reset'); + for(const query of ['I2C_CR2','0x30AD0000','CONFIG_FEC','DMA_SxCR','FEC_ENET_MII','software reset','" OR * :']) { + const result=db.search({documentId:id,query,mode:'exact',limit:10}); + assert.equal(result.length,query==='" OR * :' ? 0 : 1); + } + assert.equal(db.search({documentId:id,query:'software reset',mode:'exact',phrase:true}).length,1); +}); +test('page transactions are idempotent and resume without duplication', t => { + const db=fixture(t); + db.page(id,1,'watchdog timeout'); db.page(id,1,'should never replace'); + assert.equal(db.status(id).pages,1); + assert.equal(db.search({documentId:id,query:'watchdog',mode:'exact'}).length,1); + db.page(id,2,'DMA timeout'); + assert.equal(db.status(id).pages,2); +}); +test('independent lazy model indexes reuse shared pages and chunks', t => { + const db=fixture(t); db.page(id,1,'I2C_CR2 enables I2C'); + assert.equal(db.db.prepare('SELECT count(*) n FROM embedding_models').get().n,0); + const first=db.missing(id,model); + db.embeddings(id,model,first,[new Float32Array([1,0,0])]); + const second={key:'other@revision:3',dimension:3}; + assert.equal(db.missing(id,model).length,0); + assert.equal(db.missing(id,second).length,first.length); + assert.equal(db.status(id).pages,1); + assert.equal(db.status(id,model).embedded,1); + assert.equal(db.status(id,second).embedded,0); + const found=db.search({documentId:id,query:'I2C',mode:'hybrid',limit:5},model,new Float32Array([1,0,0])); + assert.equal(found[0].page,1); +}); +test('content/config changes invalidate shared extraction and its vectors transactionally', t => { + const db=fixture(t);db.page(id,1,'original'); + db.embeddings(id,model,db.missing(id,model),[new Float32Array([1,0,0])]); + db.db.prepare('UPDATE documents SET chunking=0 WHERE id=?').run(id); + db.document(id,'moved.pdf',2); + assert.equal(db.status(id,model).pages,0); + assert.equal(db.status(id,model).embedded,0); +}); +test('RRF deduplicates overlapping passages without merging pages', () => { + const rows=[{id:1,documentId:id,page:1,start:0,end:100},{id:2,documentId:id,page:1,start:50,end:150},{id:3,documentId:id,page:2,start:0,end:100}]; + assert.deepEqual(fuse([rows,rows],10).map(r=>r.id),[1,3]); +}); +test('model formatting and dimensionality are model-specific', () => { + assert.ok(format(catalog[0],'I2C',true).startsWith('Represent this sentence')); + assert.equal(format(catalog[0],'I2C',false),'I2C'); + assert.equal(format(catalog[1],'I2C',true),'I2C'); + assert.deepEqual([...normalized([3,4],2)],[Math.fround(.6),Math.fround(.8)]); + assert.throws(()=>normalized([1],2));assert.throws(()=>normalized([NaN,0],2)); +}); +test('downloads resume exact ranges, validate checksums and reject corruption', async t => { + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'folio-download-')); + t.after(()=>fs.rmSync(dir,{recursive:true,force:true})); + const data=Buffer.from('verified model'); + const spec={name:'config.json',bytes:data.length,sha256:createHash('sha256').update(data).digest('hex')}; + const target=path.join(dir,'config.json');fs.writeFileSync(target+'.part',data.subarray(0,4)); + const fake=async (_url,options)=>{ + assert.equal(options.headers.Range,'bytes=4-'); + return new Response(data.subarray(4),{status:206,headers:{'Content-Range':`bytes 4-${data.length-1}/${data.length}`}}); + }; + await downloadFile(catalog[0],spec,target,new AbortController().signal,()=>{},fake); + assert.ok(await valid(target,spec)); + fs.unlinkSync(target); + await assert.rejects(downloadFile(catalog[0],spec,target,new AbortController().signal,()=>{},async()=>new Response(Buffer.alloc(data.length))),/checksum/); + assert.equal(fs.existsSync(target),false); +}); +test('database restart preserves shared pages, vectors and a paused job checkpoint', t => { + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'folio-restart-')); + t.after(()=>fs.rmSync(dir,{recursive:true,force:true})); + const file=path.join(dir,'index.sqlite'); + let db=new Store(file);db.document(id,'manual.pdf',2);db.page(id,1,'watchdog timeout'); + db.embeddings(id,model,db.missing(id,model),[new Float32Array([1,0,0])]);db.job(id,'indexing');db.close(); + db=new Store(file); + try{ + assert.equal(db.status(id,model).state,'paused');assert.equal(db.status(id,model).embedded,1); + db.document(id,'renamed.pdf',2);assert.equal(db.status(id).pages,1); + db.page(id,2,'software reset');assert.equal(db.missing(id,model).length,1); + assert.equal(db.search({documentId:id,query:'watchdog',mode:'exact'})[0].name,'renamed.pdf'); + }finally{db.close();} +}); +test('future schema versions fail without destroying the database', t => { + const db=fixture(t);db.db.exec('PRAGMA user_version=999'); + assert.throws(()=>new Store(db.db.prepare('PRAGMA database_list').get().file),/newer Folio/); +}); +test('download cancellation preserves partial bytes for retry', async t => { + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'folio-abort-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true})); + const data=Buffer.from('partial file data');const spec={name:'config.json',bytes:data.length,sha256:createHash('sha256').update(data).digest('hex')}; + const target=path.join(dir,spec.name),controller=new AbortController(); + await assert.rejects(downloadFile(catalog[0],spec,target,controller.signal,()=>controller.abort(),async()=>new Response(new ReadableStream({start(c){c.enqueue(data.subarray(0,5));}})))); + assert.equal(fs.existsSync(target),false); +}); +test('invalid range responses never become verified files', async t => { + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'folio-range-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true})); + const target=path.join(dir,'config.json');fs.writeFileSync(target+'.part','part'); + await assert.rejects(downloadFile(catalog[0],{name:'config.json',bytes:10,sha256:'invalid'},target,new AbortController().signal,()=>{},async()=>new Response('bad',{status:206,headers:{'Content-Range':'bytes 0-2/3'}})),/range/); + assert.equal(fs.existsSync(target),false); +}); diff --git a/src/AdvancedSearch.tsx b/src/AdvancedSearch.tsx new file mode 100644 index 0000000..0dd26c7 --- /dev/null +++ b/src/AdvancedSearch.tsx @@ -0,0 +1,168 @@ +import { useEffect, useRef, useState } from "react"; +import { Icon } from "./icons"; +import type { PDFDocumentProxy } from "./pdf"; +import type { EmbeddingModelConfig, IndexStatus, SearchMode, SearchResult } from "./retrieval"; + +function Excerpt({ text, query }: { text: string; query: string }) { + const terms = query.match(/[\p{L}\p{N}_]+/gu) || []; + const pattern = terms.map(term => term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"); + if (!pattern) return <>{text}; + const regex = new RegExp(`(${pattern})`, "giu"); + return <>{text.split(regex).map((part, i) => i % 2 ? {part} : part)}; +} + +export function AdvancedSearch({ documentId, name, pdf, protectedDocument, onSelect, onClose, onSettings, queryRequest }: { + queryRequest?: { text: string } | null; + documentId: string; + name: string; + pdf: PDFDocumentProxy; + protectedDocument: boolean; + onSelect: (result: SearchResult) => void; + onClose: () => void; + onSettings: () => void; +}) { + const api = window.folioDesktop!.retrieval; + const [mode, setMode] = useState("semantic"); + const [models, setModels] = useState([]); + const [model, setModel] = useState(""); + const [query, setQuery] = useState(queryRequest?.text ?? ""); + const [limit, setLimit] = useState(20); + const [phrase, setPhrase] = useState(false); + const [optionsOpen, setOptionsOpen] = useState(false); + const [searched, setSearched] = useState(false); + const [status, setStatus] = useState(); + const [results, setResults] = useState([]); + const [busy, setBusy] = useState(false); + const [starting, setStarting] = useState(false); + const [error, setError] = useState(""); + const request = useRef(""); + const queryInput = useRef(null); + const debounce = useRef(0); + useEffect(() => { + let active = true; + void api.catalog().then(value => { if (active) { setModels(value.models); setModel(value.settings.activeModel); } }).catch(e => { if (active) setError(String(e)); }); + return () => { active = false; window.clearTimeout(debounce.current); if (request.current) void api.cancel(request.current).catch(() => {}); request.current = ""; }; + }, [api]); + useEffect(() => { + let active = true, pending = false; + const refresh = async () => { + if (pending) return; + pending = true; + try { + const [value, catalog] = await Promise.all([api.status(documentId, mode === "exact" ? undefined : model || undefined), api.catalog()]); + if (active) { setStatus(value); setModels(catalog.models); } + } + catch (e) { if (active) setError(String(e)); } + finally { pending = false; } + }; + void refresh(); + const timer = window.setInterval(() => void refresh(), 1000); + return () => { active = false; window.clearInterval(timer); }; + }, [api, documentId, model, mode]); + const cancel = () => { + window.clearTimeout(debounce.current); + if (request.current) void api.cancel(request.current).catch(() => {}); + request.current = ""; setBusy(false); + }; + const invalidate = () => { cancel(); setResults([]); setError(""); setSearched(false); }; + useEffect(() => { + if (!queryRequest) return; + invalidate(); + setOptionsOpen(false); + setQuery(queryRequest.text); + queryInput.current?.focus(); + }, [queryRequest]); + const search = async () => { + cancel(); + const id = crypto.randomUUID(); request.current = id; + setBusy(true); setResults([]); setError(""); setSearched(false); + try { + const found = await api.search({ id, documentId, query, mode, model, limit, scope: "document", phrase }); + // Render in small groups so long result lists don't delay reader input. + for (let i = 0; i < Math.max(1, found.length); i += 10) { + if (request.current !== id) return; + setResults(found.slice(0, i + 10)); + await new Promise(resolve => window.setTimeout(resolve, 0)); + } + if (request.current === id) setSearched(true); + } catch (e) { if (request.current === id) setError(String(e)); } + finally { if (request.current === id) { setBusy(false); request.current = ""; } } + }; + const index = async () => { + setStarting(true); setError(""); + try { await api.index({ documentId, name, data: status?.needsExtraction === false ? undefined : await pdf.getData(), model: mode === "exact" ? undefined : model }); } + catch (e) { setError(String(e)); } + finally { setStarting(false); } + }; + const selected = models.find(entry => entry.id === model); + const needsModel = mode !== "exact" && selected?.state !== "ready"; + const hasQuery = !!query.trim(); + const configuring = !hasQuery || optionsOpen; + const canSearch = !protectedDocument && !needsModel && !!status?.pages && (mode === "exact" || !!status.embedded); + useEffect(() => { + if (!hasQuery || !canSearch) return; + debounce.current = window.setTimeout(() => void search(), 350); + return () => window.clearTimeout(debounce.current); + // Search captures the current query/options; status polling must not repeat inference. + }, [query, mode, model, limit, phrase, canSearch]); + + return ; +} diff --git a/src/App.tsx b/src/App.tsx index c3829eb..45500d1 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -18,6 +18,7 @@ import { readSetting, writeSetting } from "./preferences"; import { DocumentTabBar } from "./DocumentTabBar"; import { trackTitlebar } from "./titlebar"; import type { DocumentTabs, OpenSource } from "./documentTabs"; +import { AdvancedSearch } from "./AdvancedSearch"; import { SearchResults } from "./SearchResults"; import { Icon, type IconName } from "./icons"; import { Welcome } from "./Welcome"; @@ -213,6 +214,9 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs const [rotation, setRotation] = useState(0); const [sidebar, setSidebar] = useState(() => readSetting("folio:sidebar") !== "0" && window.innerWidth > 760); const [searchOpen, setSearchOpen] = useState(false); + const [advancedSearch, setAdvancedSearch] = useState(false); + const [searchQuery, setSearchQuery] = useState<{ text: string } | null>(null); + const [semanticQuery, setSemanticQuery] = useState<{ text: string } | null>(null); const [find, setFind] = useState({ current: 0, total: 0, state: null }); const [theme, setTheme] = useState(document.documentElement.dataset.theme || "light"); const [spread, setSpread] = useState(() => readSetting("folio:spread") === "1"); @@ -273,7 +277,7 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs const [printCopy, setPrintCopy] = useState<{ pdf: PDFDocumentProxy; bytes: Uint8Array; page: number; name: string } | null>(null); const preparingPrint = useRef(false); useEffect(() => () => { if (printCopy) void printCopy.pdf.loadingTask.destroy(); }, [printCopy]); - const [dialog, setDialog] = useState<"info" | "shortcuts" | "about" | "url" | "settings" | "ai-settings" | "changelog" | "upgrade" | null>( + const [dialog, setDialog] = useState<"info" | "shortcuts" | "about" | "url" | "settings" | "ai-settings" | "semantic-settings" | "changelog" | "upgrade" | null>( upgradeNotes.length ? "upgrade" : null); // A pasted or dropped link waits in Open from URL, so the user sees where it goes before Folio contacts it. const [linkDraft, setLinkDraft] = useState(""); @@ -581,6 +585,7 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs setTool("select"); setPending(null); setSearchOpen(false); + setAdvancedSearch(false); setFind({ current: 0, total: 0, state: null }); document.title = `${name} — Folio`; @@ -960,7 +965,9 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs const askAbout = (text: string, pageNumber: number) => { setAiContext({ text, page: pageNumber }); + closeSearch(); setAiOpen(true); + setAdvancedSearch(false); setHistoryOpen(false); document.getSelection()?.removeAllRanges(); }; @@ -980,7 +987,7 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs }; let timer = window.setTimeout(refit, 280); return () => window.clearTimeout(timer); - }, [aiOpen, sidebar, sidebarTab, focus]); + }, [aiOpen, advancedSearch, searchOpen, historyOpen, sidebar, sidebarTab, focus]); useEffect(() => { const stage = container?.parentElement; if (!stage) return; @@ -1323,10 +1330,12 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs && (e.key.toLowerCase() === "z" || e.key.toLowerCase() === "y")) { e.preventDefault(); busRef.current?.dispatch("editingaction", { source: null, name: e.shiftKey || e.key.toLowerCase() === "y" ? "redo" : "undo" }); - } else if (mod && e.key.toLowerCase() === "f") { + } else if (mod && e.shiftKey && !e.altKey && e.key.toLowerCase() === "f") { e.preventDefault(); - setSearchOpen(true); - requestAnimationFrame(() => document.getElementById("folio-search")?.focus()); + if (window.folioDesktop?.retrieval) openSemanticSearch(true); + } else if (mod && !e.shiftKey && e.key.toLowerCase() === "f") { + e.preventDefault(); + openFind(true); } else if (mod && e.key.toLowerCase() === "s") { e.preventDefault(); download(); @@ -1359,7 +1368,8 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs } else if (e.key === "Escape") { if (highlightMenu) setHighlightMenu(null); else if (noteBox) setNoteBox(null); - else if (searchOpen) setSearchOpen(false); + else if (searchOpen) closeSearch(); + else if (advancedSearch) setAdvancedSearch(false); else if (contentRef.current?.deselect()) return; else if (Number(viewerRef.current?.annotationEditorMode) === AnnotationEditorType.STAMP) { viewerRef.current!.annotationEditorMode = { mode: AnnotationEditorType.NONE }; @@ -1481,6 +1491,30 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs busRef.current!.dispatch("findbarclose", { source: null }); }; + const openFind = (useSelection = false) => { + const selected = useSelection ? window.getSelection()?.toString().trim() : ""; + if (selected) setSearchQuery({ text: selected }); + else if (!searchOpen) setSearchQuery(null); + setAdvancedSearch(false); + setAiOpen(false); + setHistoryOpen(false); + if (focus) void toggleFocus(); + setSearchOpen(true); + requestAnimationFrame(() => document.getElementById("folio-search")?.focus()); + }; + + const openSemanticSearch = (useSelection = false) => { + const selected = useSelection ? window.getSelection()?.toString().trim() : ""; + if (selected) setSemanticQuery({ text: selected.slice(0, 4096) }); + else if (!advancedSearch) setSemanticQuery(null); + closeSearch(); + setAiOpen(false); + setHistoryOpen(false); + if (focus) void toggleFocus(); + setAdvancedSearch(true); + requestAnimationFrame(() => document.getElementById("folio-semantic-search")?.focus()); + }; + return (
{doc && ( <> - { setHistoryOpen(false); setAiOpen(!aiOpen); }} /> - (searchOpen ? closeSearch() : setSearchOpen(true))} /> + { closeSearch(); setHistoryOpen(false); setAdvancedSearch(false); setAiOpen(!aiOpen); }} /> + {window.folioDesktop?.retrieval && advancedSearch ? setAdvancedSearch(false) : openSemanticSearch()} />} + { + if (searchOpen) closeSearch(); else openFind(); + }} /> )} void tabs.close(tabKey) }, { kind: "divider" }, { kind: "action", icon: "download", label: "Save a copy", shortcut: keys("Ctrl S"), onSelect: download }, - { kind: "action", icon: "history", label: "Version history", onSelect: () => { setAiOpen(false); setHistoryOpen(true); } }, + { kind: "action", icon: "history", label: "Version history", onSelect: () => { closeSearch(); setAiOpen(false); setAdvancedSearch(false); setHistoryOpen(true); } }, { kind: "action", icon: "print", label: "Print", shortcut: keys("Ctrl P"), onSelect: print }, { kind: "action", icon: "info", label: "Document info", onSelect: () => setDialog("info") }, { kind: "action", icon: "search", label: "Recognize text", onSelect: () => pageOcrRef.current?.retry() }, @@ -1634,12 +1672,7 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs }} apply={async (bytes, change) => docRef.current === doc && !!await openBytes(doc.name, bytes, undefined, opening.current!.signal, undefined, { doc, change })} />} {doc &&
{textStatus}{textStatus?.startsWith("Text unavailable") && }
} - {doc && searchOpen && ( - <> - - - - )} + {doc && !contentEditing && PALETTE[tool] && (
@@ -1780,6 +1813,9 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs )} + {doc && searchOpen && !focus && + + } {doc && historyOpen && !focus && !keptOrganized || keptOrganized.has(mark.page)), organized)} @@ -1787,6 +1823,14 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs onOpen={(v, blob) => tabs.open([{ kind: "blob", name: v.name, blob }])} onDownload={(v, blob) => saveBlob(blob, v.name.replace(/\.pdf$/i, "") + ` (v${v.number}).pdf`)} onClose={() => setHistoryOpen(false)} />} + {doc && advancedSearch && window.folioDesktop?.retrieval && !focus && setAdvancedSearch(false)} onSettings={() => setDialog("semantic-settings")} + onSelect={result => { + goTo(result.page); + const phrase = result.text.split("\n")[0].trim().slice(0, 100); + if (phrase) runFind(phrase, {}); + }} />} {doc && aiOpen && !focus && ( { printPdfBytes(printCopy.bytes); setPrintCopy(null); }} onClose={() => setPrintCopy(null)} />} {dialog === "shortcuts" && setDialog(null)} />} {dialog === "about" && setDialog(null)} />} - {(dialog === "settings" || dialog === "ai-settings") && { setScanLanguages(next); diff --git a/src/Dialogs.tsx b/src/Dialogs.tsx index 76f7d34..5e0f974 100644 --- a/src/Dialogs.tsx +++ b/src/Dialogs.tsx @@ -130,6 +130,7 @@ const SHORTCUTS: [string, string][] = [ ["Write a note on the selection", "N"], ["Remove a clicked highlight", "Delete"], ["Find", "Ctrl F"], + ["Semantic search", "Ctrl Shift F"], ["Save / download", "Ctrl S"], ["Print", "Ctrl P"], ["Zoom in / out", "Ctrl + / −"], diff --git a/src/EmbeddingModels.tsx b/src/EmbeddingModels.tsx new file mode 100644 index 0000000..4d98541 --- /dev/null +++ b/src/EmbeddingModels.tsx @@ -0,0 +1,68 @@ +import { useEffect, useState } from "react"; +import type { EmbeddingModelConfig, SearchSettings } from "./retrieval"; + +export function EmbeddingModels() { + const api = window.folioDesktop?.retrieval; + const [models, setModels] = useState([]); + const [settings, setSettings] = useState(); + const [error, setError] = useState(""); + const [busy, setBusy] = useState(false); + const [accepted, setAccepted] = useState>({}); + useEffect(() => { + if (!api) return; + let active = true, pending = false; + const refresh = async () => { + if (pending) return; + pending = true; + try { + const result = await api.catalog(); + if (active) { setModels(result.models); setSettings(result.settings); } + } catch (error) { if (active) setError(String(error)); } + finally { pending = false; } + }; + void refresh(); + const timer = window.setInterval(() => void refresh(), 1000); + return () => { active = false; window.clearInterval(timer); }; + }, [api]); + const run = async (action: () => Promise) => { + setBusy(true); setError(""); + try { await action(); const value = await api!.catalog(); setModels(value.models); setSettings(value.settings); } + catch (error) { setError(String(error)); } + finally { setBusy(false); } + }; + if (!api) return

Local semantic search is available in the desktop app.

; + return
+

Embedding Models

+

Search runs on this device. Models download only when you choose Install. Indexes are kept when you switch or uninstall models.

+ {settings && <> + + + + } + {models.map(model => { + const bytes = model.files.reduce((sum, file) => sum + file.bytes, 0); + const downloading = model.state === "downloading" || model.state === "verifying"; + return
+ {model.name} +

{model.description} {model.memoryHint} {model.languages.join(", ")} · {(bytes / 1048576).toFixed(1)} MB download · allow {(bytes * 2 / 1048576).toFixed(0)} MB disk plus indexes

+

Source · License: {model.license}

+ {model.enabled ? model.state : "Not yet validated"} + {downloading && } + {model.error &&

{model.error}

} + {model.requiresLicenseAcceptance && model.state !== "ready" && } +
+ {model.enabled && (model.state === "ready" ? <> + + + : downloading ? : + )} +
+
; + })} + {error &&

{error}

} +
; +} diff --git a/src/SearchBar.tsx b/src/SearchBar.tsx index 20bd428..accbf01 100644 --- a/src/SearchBar.tsx +++ b/src/SearchBar.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState, type ReactNode } from "react"; import { Icon } from "./icons"; import { keys } from "./platform"; @@ -14,18 +14,30 @@ type FindOpts = { again?: boolean; previous?: boolean; caseSensitive?: boolean; export function SearchBar({ result, recognizing, + queryRequest, onFind, onClose, + children, }: { + children: ReactNode; result: FindResult; recognizing: boolean; + queryRequest?: { text: string } | null; onFind: (q: string, o: FindOpts) => void; onClose: () => void; }) { - const [query, setQuery] = useState(""); + const [query, setQuery] = useState(queryRequest?.text ?? ""); + const input = useRef(null); const [caseSensitive, setCase] = useState(false); const [entireWord, setWord] = useState(false); + useEffect(() => { + if (!queryRequest) return; + setQuery(queryRequest.text); + input.current?.focus(); + input.current?.select(); + }, [queryRequest]); + // Search as you type, debounced so large documents stay responsive. useEffect(() => { const t = window.setTimeout(() => onFind(query, { caseSensitive, entireWord }), 160); @@ -34,49 +46,35 @@ export function SearchBar({ }, [query, caseSensitive, entireWord]); const step = (previous: boolean) => query && onFind(query, { again: true, previous, caseSensitive, entireWord }); - - const status = - !query ? "" : result.state === 3 ? "Searching…" : result.total === 0 ? "No results" : `${result.current} of ${result.total}`; + const status = !query ? "" : result.state === 3 ? "Searching…" : result.total === 0 ? "No results" : `${result.current} of ${result.total}`; return ( -
- - setQuery(e.target.value)} - onKeyDown={(e) => { - if (e.key === "Enter") { - e.preventDefault(); - step(e.shiftKey); - } else if (e.key === "Escape") { - e.preventDefault(); - onClose(); - } - }} - spellCheck={false} - /> - {status} - {query && recognizing && Results may be incomplete while text is being recognized} - - - - - - -
+ ); } diff --git a/src/SearchResults.test.tsx b/src/SearchResults.test.tsx index 394f4d9..0a5472b 100644 --- a/src/SearchResults.test.tsx +++ b/src/SearchResults.test.tsx @@ -85,7 +85,7 @@ describe("SearchResults", () => { const { pdf } = makePdf({}); await mount(pdf, { pageMatches: [], pageMatchesLength: [] }); await settle(); - expect(container.textContent).toContain("Search above to see matching pages"); + expect(container.textContent).toContain("Search below to see matching pages"); expect(heading()).toBe("Matching pages 0"); expect(rows()).toHaveLength(0); }); @@ -201,7 +201,7 @@ describe("SearchResults", () => { await act(async () => { bus.emit("find"); }); expect(rows()).toHaveLength(0); expect(heading()).toBe("Matching pages 0"); - expect(container.textContent).toContain("Search above"); + expect(container.textContent).toContain("Search below"); }); it("shows the first 100 matching pages and says so", async () => { diff --git a/src/SearchResults.tsx b/src/SearchResults.tsx index fc0aa0f..590c820 100644 --- a/src/SearchResults.tsx +++ b/src/SearchResults.tsx @@ -78,9 +78,9 @@ export function SearchResults({ pdf, controller, bus, onSelect }: { }; }, [pdf, controller, bus]); - return ; +
; } diff --git a/src/SettingsDialog.tsx b/src/SettingsDialog.tsx index c6f84fb..0db6927 100644 --- a/src/SettingsDialog.tsx +++ b/src/SettingsDialog.tsx @@ -2,6 +2,7 @@ import { clearRecognizedText } from "./recent"; import { useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from "react"; import { Modal } from "./Dialogs"; import { AGY_URL, CLAUDE_CODE_URL, PROVIDERS, savedGeminiMode, savedProvider, saveAiPreference, signInChatGPT, subscribeAiPreferences, USAGE_URL, type AiProvider } from "./ai"; +import { EmbeddingModels } from "./EmbeddingModels"; import { OpenRouterSettings } from "./OpenRouterSettings"; import { GeminiSettings } from "./GeminiSettings"; import { CustomEndpointSettings } from "./CustomEndpointSettings"; @@ -14,7 +15,7 @@ import { clearStoredData, countStoredData, onStoredDataCleared, type StoredCateg /** One place for every Folio preference. */ interface Props { - initialSection?: "General" | "Ask AI"; + initialSection?: "General" | "Ask AI" | "Semantic Search"; theme: string; onTheme: (theme: "light" | "dark") => void; night: boolean; @@ -156,7 +157,7 @@ export function SettingsDialog({ initialSection = "General", theme, onTheme, nig const ai = desktop?.ai; const [error, setError] = useState(null); const [ocrCleared, setOcrCleared] = useState(false); - const [section, setSection] = useState<"General" | "Ask AI" | "Storage">(initialSection); + const [section, setSection] = useState<"General" | "Ask AI" | "Semantic Search" | "Storage">(initialSection); // Updates const [info, setInfo] = useState> | null>(null); @@ -195,7 +196,7 @@ export function SettingsDialog({ initialSection = "General", theme, onTheme, nig
@@ -281,6 +282,8 @@ export function SettingsDialog({ initialSection = "General", theme, onTheme, nig )} + {section === "Semantic Search" && } + {section === "Storage" && <>