diff --git a/AGENTS.md b/AGENTS.md index 65453695..0fb2fe29 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,16 +74,19 @@ - To add a routing provider (e.g. Vercel): add its kind to `UPSTREAM_ROUTING`, map `ProviderRouting` in its Omniference adapter or vendor dialect, and add a `sync` function in `sources/` called from `sources::sync` - Cortecs (`CortecsDialect` in Omniference, Responses adapter): `only` becomes `allowed_providers`, `order` becomes `allowed_providers` with `provider_order: "custom"`, and Cortecs never falls back beyond that list, so web chat's "prefer" puts the model's other stored providers the user may use after the picked one (`picked_provider`); "lock" stays `only: [slug]`. Its catalog and every model's provider options come from one `/v1/models?extended=true` call in the model sync (`sync_cortecs_catalog`, `source_gateway = 'cortecs'`, `cortecs_options`, written in one transaction by `GatewayCatalogModel::replace_gateway_provider_options`); the provider-options refresh re-runs that sync. Cortecs reports EUR per 1M tokens (converted to USD with `exchange_rates`, left empty without a rate), latency in seconds (stored as ms) and uptime as a fraction (stored as percent); `ttft` and `cache_hit_rate` stay in `raw`. The admin Catalog tab stays OpenRouter-only - Provider kinds without their own Omniference adapter pass `ProviderKind::catalog_slug()` as `catalog_provider_slug`, the vendor slug Omniference uses for models.dev prices and its vendor profile (`catalog/providers/.toml`); every `ProviderConfig` OxideChat builds must set it (`profile` and `resolved_profile` stay `None`: registration resolves the profile). `MISTRAL` uses the OpenAI-compatible Chat adapter (`/v1/chat/completions`), where Omniference's `MistralDialect` applies; `CORTECS` uses the OpenAI Responses adapter (`/v1/responses`) -- `src/types/rag/` - Knowledge (RAG, HEN-22, built as stacked PRs; slices 1, 2a, 2b, 2c and 2d so far): `rag_config` (single row: reranker model and `top_n`, default connection) and `rag_connections` (where vectors live), managed under `/api/v1/admin/rag` (`admin.rag.view` / `.edit`, page `/settings/tools/knowledge`, a sub page of Tools; `/settings/knowledge-setup` redirects there); knowledge is on while the Knowledge Search builtin tool row is enabled (`RagConfig::enabled`, `Tool::builtin_enabled`), there is no separate switch, and `/api/v1/base` returns that as `rag: {enabled}` - - A connection has a `kind` (`pgvector`, `qdrant`) and a `mode` (`managed`: `OxideChat` writes, pgvector only; `read_only`: another pipeline fills it), both fixed at create. Its URL never holds a password, and a pgvector URL takes no query parameter but `sslmode` and no percent-encoded host (sqlx would read host, port, socket and key files from them past the host checks): the Postgres password or Qdrant API key is the encrypted `secret`, a new host needs it again (`RagConnection::redirects_secret`), and Qdrant keys go over https only. A managed pgvector connection without URL is the main database; `RAG_PGVECTOR_URL` replaces the address and password of the default managed connection +- `src/types/rag/` - Knowledge (RAG, HEN-22, built as stacked PRs; slices 1, 2a, 2b, 2c, 2d and 4): `rag_config` (single row: reranker model, `top_n` and optional `min_score`, default managed connection, chunking defaults `chunk_size`/`chunk_overlap_percent`; knowledge uploads have no quotas of their own and count toward the shared file limits) and `rag_connections` (where vectors live), managed under `/api/v1/admin/rag` (`admin.rag.view` / `.edit`, page `/settings/tools/knowledge`, a sub page of Tools; `/settings/knowledge-setup` redirects there); knowledge is on while the Knowledge Search builtin tool row is enabled (`RagConfig::enabled`, `Tool::builtin_enabled`), there is no separate switch, and `/api/v1/base` returns that as `rag: {enabled}` + - A connection has a `kind` (`pgvector`, `qdrant`) and a `mode` (`managed`: `OxideChat` writes, pgvector only; `read_only`: another pipeline fills it), both fixed at create. Its URL never holds a password, and a pgvector URL takes no query parameter but `sslmode` and no percent-encoded host (sqlx would read host, port, socket and key files from them past the host checks): the Postgres password or Qdrant API key is the encrypted `secret`, a new host needs it again (`RagConnection::redirects_secret`), and Qdrant keys go over https only. A managed pgvector connection without URL is the main database; `RAG_PGVECTOR_URL` replaces the address and password of the default managed connection; the first managed connection saved while no default is set becomes the default storage (`make_default_if_none`), and the add dialog (`SettingsKnowledgeConnectionsCard`) asks what to connect (OxideChat's own database, another PostgreSQL server, or an existing collection) and only then shows address and password - A managed connection's embedding model is checked with one test embedding billed to the saving admin (`probe_embedding`, `oxide_request_type = rag_setup`), which stores `vector_size`; a new model or size bumps `index_generation`. Reranker and embedding models are checked with `gateway::model_type`, and the admin model list takes `?type=embedding|reranking` for the pickers - `VectorStore` (`store.rs`) opens a connection for `health` (pgvector 0.8+ or the Qdrant version), `list_collections`, `describe` (vectors with size and distance, payload field paths, three sample records without vectors and with strings cut by `shorten`) and `search` (nearest records as payload and score, inside the view's fixed filter); addresses follow the outbound rules (`private_hosts_allowed`), read-only Postgres sessions set `default_transaction_read_only`, external pgvector pools are reused per address, secret and mode (`PG_POOLS`, an `ArcSwap` map; the host check still runs on every connect and idle connections close after a minute), and failures are `StoreError` codes (`rag.store_error.`), never the server's own text. Validation failures are `RagError`, rendered as `ValidationFailed` with `details.reason` (`rag.error.`) - pgvector tables are resolved with `to_regclass` and their columns read from `pg_attribute`; identifiers go into SQL only through `quote_ident` after that lookup, filter values only as parameters (`view::pg_filter`, which refuses unknown columns), and search sets `hnsw.iterative_scan = relaxed_order` in its transaction (pgvector below 0.8 answers `extension_too_old`). Qdrant runs over REST (`/collections/{name}`, `/points/scroll`, `/points/query`) with the view's filter as `must` conditions (`view::qdrant_filter`) - - Knowledge bases (slice 2a, `knowledge_bases.rs`, `knowledge_bases` / `knowledge_base_shares`): a view (`ExternalView`: connection, collection, optional `vector_name`, `distance`, the `embedding` model that built the collection, `fields: {text, title?, url?, section?}` as dotted payload paths, fixed `filter` of field = value conditions; pgvector compares them as JSON (`pg_filter`), so a dotted path reaches into a JSON column and `5` matches `5.0`) onto a read-only connection's collection, under `/api/v1/knowledge-bases` (page `/settings/knowledge`). Only knowledge admins (`admin.rag.edit`) create, delete, change the source and share; `check_view` checks the collection, the vector and one test embedding whose size must match (`collection_dimensions_mismatch`). A new knowledge base is shared with nobody; sharing goes through `…/assignments` with everyone, teams, roles and users, each as `viewer` or `editor` (editors change name and description; everyone is viewer only), and, while the view has no per-record access, the frontend asks for a confirmation before a share with everyone, a team or a role because source access rights are not checked. `admin.rag.view` (and `admin.rag.edit`, which includes seeing what it edits) sees every knowledge base with its source; other users see only those shared with them and never the connection or view. `POST …/{id}/search` is the test search, for bases shared with the user or by `admin.rag.edit` (`KnowledgeActor::can_search`; `admin.rag.view` alone is not enough): one query embedding billed to the user as `rag_query`, hits mapped through `ExternalView::hit` (only `http(s)` links; Qdrant Euclid and Manhattan distances are negated so higher is closer). A connection cannot be deleted while knowledge bases use it (`connection_in_use`) - - Knowledge tool (slice 2b, `retrieval.rs`): knowledge bases are attached to chats (`chat_knowledge_bases`, replaced by `StreamRequest.knowledge_base_ids`, returned as `ChatWithMessagesResponse.knowledge_base_ids`) and presets (`preset_knowledge_bases`, `SavePresetRequest.knowledge_base_ids`; only bases the saving user may search are added, ones already attached stay). `prepare_single` keeps the attached bases the user may search right now (`turn_knowledge_bases`: none while the Knowledge Search tool is off) and offers `knowledge_search` (`add_knowledge_tool`: `query`, optional `knowledge_base` name from an enum, replacing the stored spec or a user tool of the same name, which the agent also never runs while the tool is offered) only when some remain, the model does not list capabilities without `TOOLS` (a model with none, such as a self-hosted one, still gets it) and the Knowledge builtin tool is among the turn's tools (`offer_knowledge`, `Tool::enabled_builtin_among`: an enabled system tool row with `builtin_id = knowledge` named `knowledge_search`, created from its template in `useBuiltinToolTemplates` on Settings → Tools, whose row links to the knowledge setup at `/settings/tools/knowledge` and is never run through `get_builtin_executor`); like other tools it comes from the request, a preset or the admin model config, and attaching a base in the composer or the preset editor selects it; arena turns never get it. The agent runs the tool itself (`run_knowledge_tool`, never through `get_builtin_executor`; `resolve_tools` skips the row, so neither its spec nor its system prompt reaches a turn that does not offer the tool): it checks the bases again, narrows them by the model's argument, embeds the query once per distinct embedding model, searches every base in parallel (one whose store is unreachable or whose embedding model fails is listed under `unavailable`; a used-up budget fails the tool), merges with RRF (identical text once), keeps at most 3 excerpts per document and 20 candidates, reranks them with the configured reranker down to its `top_n` (else keeps 8; a failed rerank keeps the merged order) and numbers the sources `[n]` up to 16,000 characters with each excerpt cut to 4,000, wrapped with a note that they are data, not instructions. Query embedding and rerank reserve budget as `rag_query`. `KnowledgeBaseResponse.usable` marks bases shared with the viewer; the composer lists those in `ChatSettingsMenu` (`useKnowledgeStore`, `composer-knowledge-`, chip `knowledge`), the preset editor in its Knowledge tab (`SettingsPresetsKnowledgeTab`), and `ToolExecutionDisplay` shows a `knowledge_search` result as source chips. The e2e stand-in calls `knowledge_search` once when it is offered and answers from the first source + - Knowledge bases (slice 2a, `knowledge_bases.rs`, `knowledge_bases` / `knowledge_base_shares`): a view (`ExternalView`: connection, collection, optional `vector_name`, `distance`, the `embedding` model that built the collection, `fields: {text, title?, url?, section?}` as dotted payload paths, fixed `filter` of field = value conditions; pgvector compares them as JSON (`pg_filter`), so a dotted path reaches into a JSON column and `5` matches `5.0`) onto a read-only connection's collection, under `/api/v1/knowledge-bases` (page `/settings/knowledge`). Only knowledge admins (`admin.rag.edit`) create, delete, change the source and share; `check_view` checks the collection, the vector and one test embedding whose size must match (`collection_dimensions_mismatch`). A new knowledge base is shared with nobody; sharing goes through `…/assignments` with everyone, teams, roles and users, each as `viewer` or `editor` (editors change name and description; everyone is viewer only), and, while the view has no per-record access, the frontend asks for a confirmation before a share with everyone, a team or a role because source access rights are not checked. `admin.rag.view` (and `admin.rag.edit`, which includes seeing what it edits) sees every knowledge base with its source; other users see only those shared with them and never the connection or view. `POST …/{id}/search` is the test search, for bases shared with the user or by `admin.rag.edit` (`KnowledgeActor::can_search`; `admin.rag.view` alone is not enough): it runs the knowledge tool's pipeline for that one base (20 candidates, at most 3 per document, the configured reranker down to its `top_n`, else 8), query embedding and rerank billed to the user as `rag_query`, `KnowledgeHit.score` is the reranker's relevance, else the vector similarity, and none for a keyword-only match; hits are mapped through `ExternalView::hit` (only `http(s)` links; Qdrant Euclid and Manhattan distances are negated so higher is closer). A connection cannot be deleted while knowledge bases use it (`connection_in_use`) + - Knowledge tool (slice 2b, `retrieval.rs`): knowledge bases are attached to chats (`chat_knowledge_bases`, replaced by `StreamRequest.knowledge_base_ids`, returned as `ChatWithMessagesResponse.knowledge_base_ids`) and presets (`preset_knowledge_bases`, `SavePresetRequest.knowledge_base_ids`; only bases the saving user may search are added, ones already attached stay). `prepare_single` keeps the attached bases the user may search right now (`turn_knowledge_bases`: none while the Knowledge Search tool is off) and offers `knowledge_search` (`add_knowledge_tool`: `query`, optional `knowledge_base` name from an enum, replacing the stored spec or a user tool of the same name, which the agent also never runs while the tool is offered) only when some remain, the model does not list capabilities without `TOOLS` (a model with none, such as a self-hosted one, still gets it) and the Knowledge builtin tool is among the turn's tools (`offer_knowledge`, `Tool::enabled_builtin_among`: an enabled system tool row with `builtin_id = knowledge` named `knowledge_search`, created from its template in `useBuiltinToolTemplates` on Settings → Tools, whose row links to the knowledge setup at `/settings/tools/knowledge` and is never run through `get_builtin_executor`); like other tools it comes from the request, a preset or the admin model config, and attaching a base in the composer or the preset editor selects it; arena turns never get it. The agent runs the tool itself (`run_knowledge_tool`, never through `get_builtin_executor`; `resolve_tools` skips the row, so neither its spec nor its system prompt reaches a turn that does not offer the tool): it checks the bases again, narrows them by the model's argument, embeds the query once per distinct embedding model, searches every base in parallel (one whose store is unreachable or whose embedding model fails is listed under `unavailable`; a used-up budget fails the tool), merges with RRF (identical text once), keeps at most 3 excerpts per document and 20 candidates, reranks them with the configured reranker down to its `top_n`, dropping hits it scores below `rag_config.reranker_min_score` when that is set, even if none remain (else keeps 8; a failed rerank keeps the merged order) and numbers the sources `[n]` up to 16,000 characters with each excerpt cut to 4,000, wrapped with a note that they are data, not instructions. Query embedding and rerank reserve budget as `rag_query`. `KnowledgeBaseResponse.usable` marks bases shared with the viewer; the composer lists those in `ChatSettingsMenu` (`useKnowledgeStore`, `composer-knowledge-`, chip `knowledge`), the preset editor in its Knowledge tab (`SettingsPresetsKnowledgeTab`), and `ToolExecutionDisplay` shows a `knowledge_search` result as source chips. The e2e stand-in calls `knowledge_search` once when it is offered and answers from the first source - Model access (slice 2c, `model_access.rs`, `knowledge_base_model_targets` / `chat_knowledge_sources`): a knowledge base can be limited to providers, upstream provider slugs and single models (`ModelTargets`; all empty means no restriction) through `GET/PUT /api/v1/knowledge-bases/{id}/model-access` or, together with the name and source in one transaction, `SaveKnowledgeBaseRequest.model_access` (only `admin.rag.edit` writes it, since lifting it lets content reach other models; editors and `admin.rag.view` may read; audited as `knowledge_base_model_access_updated`; tab Model access, `SettingsKnowledgeModelAccess`). Upstream slugs only narrow a listed routing provider, so a list with slugs but no routing provider is refused (`upstream_needs_provider`). A deleted provider or model leaves its target row with every column NULL (`ON DELETE SET NULL`), which `ModelTargets.removed` turns into a restriction that allows nothing until the list is saved again (`ModelAccessResponse.removed_targets`). `ModelTargets::decide`: nothing is allowed while a target was deleted, otherwise the model or its provider must be listed, and a model of a routing provider (`routes_upstream`) is narrowed to the listed upstream slugs either way (`ModelAccess::Upstream`); several bases combine with `ModelAccess::and` (denial wins, upstream lists intersect, none left is a denial). The list must allow the base's embedding model outright (`embedding_model_not_allowed`, also checked when the source changes). When the knowledge tool returns sources, their bases are added to `chat_knowledge_sources` (only grows, copied to a branched chat by `KnowledgeBase::copy_chat_sources`; neither table has a foreign key on the knowledge base, so a deleted base's restriction stays on chats holding its excerpts). Chat turns, tool steps and titles carry `oxide_chat_id` (`KNOWLEDGE_CHAT_METADATA_KEY`), and `ProviderRoutingMiddleware` refuses a model those bases don't allow with 403 `knowledge_model_not_allowed` or narrows `ProviderRouting.only` to the allowed upstream providers. Requests outside the middleware check themselves with `ModelTargets::allow_outright` and treat upstream narrowing as refused: the image tool (`ToolContext.chat_id`, `chat_allows_model`) before reserving budget, the knowledge tool's query embedding (a base whose embedding model the chat's sources refuse is `unavailable`, since the query may quote earlier excerpts), and reranking, which is skipped unless every base among the candidates and in the chat allows the reranker. `prepare_single` and arena turns refuse a model the chat's sources don't allow through the turn's provider routing, after the user's routing policy narrowed it, before storing anything (`require_knowledge_access`, which returns a `KnowledgeCheck`), and `prepare_single` offers the tool only for attached bases whose upstream lists, together with the chat's sources and the bases kept before them, still leave a route (`allowed_for_model`, so the search cannot be followed by a refusal); `KnowledgeBaseResponse.allowed_model_ids` (enabled models that may see it, `None` when unrestricted) lets the composer show the others disabled - Per-record access (slice 2d, `access.rs`, `knowledge_base_access_labels`): `ExternalView.access` names the payload field that lists who may see each record (by convention `oxide_access`, preselected when the sample has it; `None`: everyone the base is shared with sees everything). Labels are plain strings from the source system and never depend on the sign-in provider: `…/access-labels` lists the labels found in the collection (`VectorStore::access_labels`: Qdrant facet, which needs a keyword payload index; pgvector `DISTINCT` over a `text[]` or JSON field) plus the mapped ones and counts `unassigned` labels, and `GET/PUT …/access-labels/assignments?label=…` (the label is a query parameter, since clients resolve a `..` path segment away; teams, roles, users; `admin.rag.edit`, audited as `knowledge_base_access_label_updated`) says who holds each. `KnowledgeBase::held_labels` loads a user's labels live from their teams, roles and ID, and `VectorStore::search` takes them and filters inside the query (Qdrant `match any`, pgvector `&&` on a `text[]` column or `?|` on a JSON array or string, never an object's keys): a label nobody holds grants nobody, a record without the field is never returned and an empty label set returns nothing. The knowledge tool and the test search both pass the searcher's labels; `KnowledgeSearchRequest.as_user` lets `admin.rag.edit` search as another user (audited as `rag_search_as` before searching) and returns `SearchAccess` (shared, labels held, unassigned) for the explanation. Tab Access is `SettingsKnowledgeAccessLabels`; team, role and user picker options load through `useAssignmentOptions` - Connect flow: `POST /api/v1/admin/rag/connections/{id}/inspect` (`admin.rag.edit`) returns `InspectResponse` (`error` or `collection: CollectionInfo`) for a collection and filter, checked like a saved view (`InspectRequest::validate`); the editor is `SettingsKnowledgeEditor` with `SettingsKnowledgeSourceForm` (steps: connection, collection, sample, fields, filter, embedding model, who may see what), `SettingsKnowledgeSharing` and `SettingsKnowledgeTestSearch`. The e2e stand-in serves a read-only Qdrant under `${MOCK_LLM_URL}/qdrant` (`handbook` with mock-embed's 3 dimensions, `wide` with 4, `intranet` whose records list `oxide_access` labels; it answers `match.any` and `facet`) + - Managed knowledge bases (slice 4, `chunker.rs`, `documents.rs`, `ingest.rs`, `src/utils/extract.rs`, `rag_documents` / `rag_chunks`): a managed knowledge base has `view = NULL`, binds to the default managed pgvector connection (`rag_config.default_connection_id`), carries a `scope` (`personal` with `settings.knowledge.edit`, `team` for team admins, `installation` for `admin.rag.edit`, `GET /api/v1/knowledge-bases/scopes`), a PostgreSQL `search_language` (`regconfig`, validated against `SEARCH_LANGUAGES`), and soft deletion (`deleted_at`); `rag_documents.knowledge_base_id` uses `ON DELETE RESTRICT` so vectors are never cascaded away, and `User::delete` marks personal KB documents `deleting` (and soft-deletes non-empty personal KBs) inside its transaction and notifies `JobState.rag_ingest_notify` + - Upload & ingest: `POST /api/v1/knowledge-bases/{id}/documents?filename=…` (25 MiB limit) checks `DocumentKind::detect` (text/code, HTML, PDF with `%PDF-`), the shared hourly upload limit and storage quota through `FileStorage::begin_store` (`RagError::RateLimited`, `RagError::StorageQuotaExceeded`), and KB model access against the connection's embedding model; it stores the file as a `files` row (`source = 'knowledge'`, `KNOWLEDGE_SOURCE`; name, type, size, original bytes in `data` and, once extracted, `text`) that the `rag_documents` row points to (`file_id`, `ON DELETE RESTRICT`; the worker deletes both after purging vectors), as `status = 'pending'` and notifies `rag_ingest_notify`. Two `rag_ingest_worker` background tasks (`src/jobs.rs`) claim jobs via `FOR UPDATE SKIP LOCKED`, extract HTML/PDF/text in a sandboxed child process (`OxideChat extract`, handled in plain `fn main()` before Tokio starts, 4 concurrent children, empty env, 30 s, 1 GiB `RLIMIT_AS` on Linux, 8 MiB text cap, PDF pages marked ``), chunk with `chunk_document` (heading hierarchy, ~15% overlap, no cross-section overlap on `#`/`##`, split Markdown tables repeat header + separator row, `doc › heading` embed prefix, SHA-256 `content_hash`), batch-embed (`embed_batch`, <=64 inputs / ~16k tokens, 2 in flight, billed as `rag_ingest`), and write L2-normalized vectors into per-connection per-generation pgvector tables `rag_vectors__g` (`halfvec(N)` + HNSW `halfvec_cosine_ops` + GIN `access`); extracted text replaces the kept bytes only if it fits the uploader's storage quota (`FileStorage::begin_extracted`, else `quota_exceeded`), failed uploads keep `files.data` for 7 days for `POST …/retry`, a claim is the row's `locked_at`, which every later write of that worker must still match (a re-queued or reaped document makes the old worker's writes no-ops), a worker touches `updated_at` every minute while it works and a document untouched for 10 min is queued again, a panic fails only its document, `#` lines are headings only in Markdown, text and HTML files (`has_headings`), and `deleting` rows purge vectors before removing Postgres rows and finished soft-deleted KBs; `Team::delete` hands a team's knowledge bases to the same path (`KnowledgeBase::delete_team_owned`), viewers list only the documents their labels grant (`RagDocument::visible_to`), `GET …/documents/{doc_id}/text` returns a document's extracted text under the same rule (`RagDocument::text`, the eye button in `SettingsKnowledgeDocuments`), document lists and text need `KnowledgeActor::can_search` or edit rights (`admin.rag.view` alone sees bases, not their documents), and a managed connection's address cannot change while documents are stored on it (`ConnectionHasDocuments`) + - Hybrid search, per-document access & re-indexing: `hybrid_search_managed` runs pgvector cosine search (`SET LOCAL hnsw.iterative_scan = relaxed_order`) alongside time-limited Postgres FTS (`websearch_to_tsquery`, 1.5 s timeout), re-checks `d.status = 'ready'` and `access` fail-closed in Postgres, and merges with RRF; per-document "Limit access" uses `GET/PUT …/documents/{doc_id}/assignments` (`team:`, `role:`, `user:` stored on `rag_documents.access`, `rag_chunks.access`, and pgvector `access`; empty clears back to `NULL` inheriting the KB). Changing a managed connection's embedding model checks KB model-access conflicts (`ConnectionModelConflict`), exposes `POST /api/v1/admin/rag/connections/{id}/reindex-estimate`, bumps `index_generation`, marks documents `pending` with `reindex_by`, blocks search with `StoreError::Reindexing` while documents are still `pending` or `processing` behind it (failed ones do not block), and drops generation tables older than the current one once those finish. Frontend adds `SettingsKnowledgeDocuments`, scope/language controls in `Editor.vue`, Mine / Shared with me / All tabs on `/settings/knowledge`, chunking settings and re-index confirmation/progress on `/settings/tools/knowledge`, and page badges on `ToolExecutionDisplay` - `src/types/presets/` - Presets (`model_presets`): a base model plus instructions, sampling (`PresetSampling`), reasoning, tools (optionally locked) and up to four starters, addressed as `presets/` - The slug is unique across all scopes, and `presets/` is a reserved namespace: providers cannot be named `presets` and model sync skips IDs starting with `presets/` (both also enforced by CHECK constraints) - Scopes: `personal` (`settings.presets.edit`), `team` (managed by team admins and installation admins, visible to members) and `installation` (`admin.presets.edit`, visible to everyone). `PresetActor` carries what a caller may manage; the scope names the owner, is set at create and never changes. On top of it a preset is shared through `PUT /api/v1/presets/{id}/assignments` (`Preset::replace_assignments`) with any number of teams and users (`model_preset_shares`) or with everyone (`model_presets.shared_with_everyone`): each team or user share holds a role (`AssignmentRole`): a `viewer` may use the preset, an `editor` may also change it (every member of an editor team; `PresetActor::can_edit`, `PresetResponse.can_edit`), and only whoever manages the owning scope may delete or share it (`PresetActor::can_manage`, `PresetResponse.can_manage`); everyone can only be a viewer, `PresetResponse.shared` marks presets the viewer does not own, a new share needs the actor to manage that team (`PresetActor::can_share_with`; users and everyone need an installation admin), and a preset that is shared or not personal may only bundle system tools. `GET /api/v1/presets/scopes` lists where a user may create presets diff --git a/Cargo.lock b/Cargo.lock index a509fba9..06b59df6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -25,6 +25,7 @@ dependencies = [ "oauth2", "omniference", "pdf-extract", + "pdf_oxide", "rand 0.10.3", "reqwest", "rust_decimal", @@ -123,6 +124,21 @@ dependencies = [ "memchr", ] +[[package]] +name = "alloc-no-stdlib" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" + +[[package]] +name = "alloc-stdlib" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" +dependencies = [ + "alloc-no-stdlib", +] + [[package]] name = "allocator-api2" version = "0.2.21" @@ -144,6 +160,56 @@ dependencies = [ "libc", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "anyhow" version = "1.0.104" @@ -225,6 +291,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "atoi_simd" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3cdb3708a128e559a30fb830e8a77a5022ee6902806925c216658652b452a44" +dependencies = [ + "debug_unsafe", + "rustversion", +] + [[package]] name = "atomic-waker" version = "1.1.2" @@ -376,6 +452,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" +dependencies = [ + "hybrid-array", +] + [[package]] name = "borsh" version = "1.8.1" @@ -400,6 +485,27 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "brotli" +version = "9.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9071f285ed78f04f37d675abaaef5de7689e2f30a216c8dc6795465d81910a13" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "6.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "664148598c930650998ef56df301329ffe7b4cdb02d49b2a3fca3bcaf2185bcb" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + [[package]] name = "bumpalo" version = "3.20.4" @@ -414,6 +520,20 @@ name = "bytemuck" version = "1.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] [[package]] name = "byteorder" @@ -421,6 +541,12 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + [[package]] name = "bytes" version = "1.12.1" @@ -454,6 +580,15 @@ dependencies = [ "cipher 0.4.4", ] +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher 0.5.2", +] + [[package]] name = "cbindgen" version = "0.29.3" @@ -593,6 +728,12 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "combine" version = "4.6.9" @@ -609,6 +750,15 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" +[[package]] +name = "constant_time_eq" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7" +dependencies = [ + "rustversion", +] + [[package]] name = "cookie" version = "0.18.2" @@ -889,6 +1039,12 @@ version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + [[package]] name = "crypto-common" version = "0.1.7" @@ -928,6 +1084,12 @@ dependencies = [ "cmov", ] +[[package]] +name = "debug_unsafe" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eed2c4702fa172d1ce21078faa7c5203e69f5394d48cc436d25928394a867a2" + [[package]] name = "debugid" version = "0.8.0" @@ -1059,6 +1221,29 @@ dependencies = [ "simdutf8", ] +[[package]] +name = "env_filter" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "288efae2d67fb0418d01f837feb55c7a9cdc4c5db38d3dee91324a1c7ec6fd31" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "env_logger" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82bdfc6e01c305a3ea46ed815b06ac0b379d7c5eac588fa4464048d731c4dcdf" +dependencies = [ + "anstream", + "anstyle", + "env_filter", + "jiff", + "log", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -1094,6 +1279,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + [[package]] name = "event-listener" version = "5.4.2" @@ -1175,12 +1369,39 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" +[[package]] +name = "fast-float2" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6e8948ce679d00a02a94739ea185595dca7118ed04feb991127e443bd3d761f" + [[package]] name = "fastrand" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fax" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70ed8646f3993cad0585c6669ffba6f7e5440a0bfb0a1f16600cae33ce7cf307" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + [[package]] name = "find-msvc-tools" version = "0.1.15" @@ -1200,7 +1421,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" dependencies = [ "crc32fast", - "miniz_oxide", + "miniz_oxide 0.9.1", "zlib-rs", ] @@ -1227,6 +1448,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "font-types" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7" +dependencies = [ + "bytemuck", +] + [[package]] name = "foreign-types" version = "0.3.2" @@ -1476,6 +1706,17 @@ dependencies = [ "tracing", ] +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + [[package]] name = "hashbrown" version = "0.16.1" @@ -1811,6 +2052,22 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png", + "tiff", + "zune-core", + "zune-jpeg", +] + [[package]] name = "include_dir" version = "0.7.4" @@ -1857,7 +2114,7 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" dependencies = [ - "block-padding", + "block-padding 0.3.3", "generic-array", ] @@ -1867,6 +2124,7 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" dependencies = [ + "block-padding 0.4.2", "hybrid-array", ] @@ -1898,6 +2156,12 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itertools" version = "0.14.0" @@ -1942,6 +2206,41 @@ dependencies = [ "cc", ] +[[package]] +name = "jiff" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "107f2e89536b6818514025f6787b0d94d819e54fe3b40365275fc753de485b3f" +dependencies = [ + "jiff-core", + "jiff-static", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff-core" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d44c923edf2bf456a982253f1a9ee1f6e89e421dffd0065d9b9a581da0def58f" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4996f71e569e3a3e32b925c28ef8f0027dc30bb1d594b33eeda409eea185f5c8" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "jni" version = "0.22.4" @@ -2001,6 +2300,15 @@ dependencies = [ "libc", ] +[[package]] +name = "jpeg-decoder" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07" +dependencies = [ + "rayon", +] + [[package]] name = "js-sys" version = "0.3.107" @@ -2012,6 +2320,18 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "kurbo" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" +dependencies = [ + "arrayvec", + "euclid 0.22.14", + "polycool", + "smallvec", +] + [[package]] name = "lazy_static" version = "1.5.1" @@ -2096,7 +2416,7 @@ checksum = "25aab26d99567469098e64a02f42679f8965c6401263eefa31d8f2dcc37a221c" dependencies = [ "aes 0.8.4", "bitflags", - "cbc", + "cbc 0.1.2", "ecb", "encoding_rs", "flate2", @@ -2112,7 +2432,7 @@ dependencies = [ "stringprep", "thiserror 2.0.21", "ttf-parser", - "weezl", + "weezl 0.1.12", ] [[package]] @@ -2233,6 +2553,16 @@ dependencies = [ "unicase", ] +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "miniz_oxide" version = "0.9.1" @@ -2254,6 +2584,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "multer" version = "3.1.0" @@ -2300,6 +2640,18 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" +[[package]] +name = "nix" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nom" version = "8.0.0" @@ -2364,11 +2716,28 @@ dependencies = [ "memchr", ] +[[package]] +name = "office_oxide" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1985d384db629099807a236b6aa07f7cc8f7d0b4e821e02b8aea7175de4e164" +dependencies = [ + "atoi_simd", + "encoding_rs", + "fast-float2", + "flate2", + "log", + "memchr", + "quick-xml", + "serde", + "serde_json", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "omniference" version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b4c0032364706e9049ef44b9a2e71b8603c6b056e68f048e7fff1a9b970a6fa" dependencies = [ "anyhow", "async-stream", @@ -2406,6 +2775,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "openssl" version = "0.10.82" @@ -2497,7 +2872,7 @@ dependencies = [ "adobe-cmap-parser", "cff-parser", "encoding_rs", - "euclid", + "euclid 0.20.14", "log", "lopdf", "postscript", @@ -2505,6 +2880,52 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "pdf_oxide" +version = "0.3.78" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95b1ecc1a60a314fbd1aea5fe8f700ec32af1efa70fef5c6879162444da3437d" +dependencies = [ + "aes 0.9.4", + "base64 0.23.1", + "bitflags", + "brotli", + "byteorder", + "bytes", + "cbc 0.2.1", + "chrono", + "encoding_rs", + "env_logger", + "fax 0.3.0", + "flate2", + "getrandom 0.4.3", + "image", + "jpeg-decoder", + "libc", + "log", + "md-5 0.11.0", + "memchr", + "nom", + "office_oxide", + "phf 0.14.0", + "quick-xml", + "regex", + "serde", + "serde_json", + "sha2 0.11.1", + "smallvec", + "stringprep", + "subsetter", + "taffy", + "thiserror 2.0.21", + "ttf-parser", + "unicode-bidi", + "unicode-linebreak", + "unicode-normalization", + "uuid", + "weezl 0.2.1", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -2547,6 +2968,7 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" dependencies = [ + "phf_macros", "phf_shared 0.14.0", "serde", ] @@ -2571,6 +2993,19 @@ dependencies = [ "phf_shared 0.14.0", ] +[[package]] +name = "phf_macros" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" +dependencies = [ + "phf_generator", + "phf_shared 0.14.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "phf_shared" version = "0.12.1" @@ -2601,6 +3036,28 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "polycool" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6" +dependencies = [ + "arrayvec", +] + [[package]] name = "polyval" version = "0.7.3" @@ -2618,6 +3075,21 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60f6ce597ecdcc9a098e7fddacb1065093a3d66446fa16c675e7e71d1b5c28e6" +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + [[package]] name = "postcard" version = "1.1.3" @@ -2770,6 +3242,28 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", + "serde", +] + [[package]] name = "quinn" version = "0.11.12" @@ -2959,6 +3453,16 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "read-fonts" +version = "0.39.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81" +dependencies = [ + "bytemuck", + "font-types", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -3470,12 +3974,31 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" +[[package]] +name = "skrifa" +version = "0.42.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564" +dependencies = [ + "bytemuck", + "read-fonts", +] + [[package]] name = "slab" version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + [[package]] name = "smallvec" version = "1.16.5" @@ -3728,6 +4251,18 @@ dependencies = [ "unicode-properties", ] +[[package]] +name = "subsetter" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38803281d1c23166c5ebcb455439a5d2afe711cc909cf88af72448c297756ad6" +dependencies = [ + "kurbo", + "rustc-hash", + "skrifa", + "write-fonts", +] + [[package]] name = "subtle" version = "2.6.1" @@ -3797,6 +4332,18 @@ dependencies = [ "libc", ] +[[package]] +name = "taffy" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "639627c87f43b9181c811f40a6296409e093a17bc761214cba3c15df74f86b99" +dependencies = [ + "arrayvec", + "serde", + "slotmap", + "smallvec", +] + [[package]] name = "target-lexicon" version = "0.13.6" @@ -3883,6 +4430,20 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax 0.2.7", + "flate2", + "half", + "quick-error", + "weezl 0.1.12", + "zune-jpeg", +] + [[package]] name = "time" version = "0.3.55" @@ -4254,6 +4815,12 @@ dependencies = [ "pom", ] +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + [[package]] name = "typenum" version = "1.20.1" @@ -4278,6 +4845,12 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-linebreak" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" + [[package]] name = "unicode-normalization" version = "0.1.26" @@ -4372,6 +4945,12 @@ dependencies = [ "utf_types", ] +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "utf_types" version = "1.0.0" @@ -4956,6 +5535,12 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" +[[package]] +name = "weezl" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4ca08e5ef825b65b056d9efbd95c8750683f0a6d0466d02e96dc2e4e360f3d2" + [[package]] name = "whoami" version = "2.1.3" @@ -5349,6 +5934,19 @@ dependencies = [ "wast 35.0.2", ] +[[package]] +name = "write-fonts" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb731d4c4d93eacc69a1ad2f270f905788a98e4a3438267bcafbe08d3431c8d8" +dependencies = [ + "font-types", + "indexmap", + "kurbo", + "log", + "read-fonts", +] + [[package]] name = "writeable" version = "0.6.4" @@ -5424,6 +6022,20 @@ name = "zeroize" version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] [[package]] name = "zerotrie" @@ -5458,6 +6070,26 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "zip" +version = "9.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce" +dependencies = [ + "constant_time_eq", + "crc32fast", + "flate2", + "getrandom 0.4.3", + "indexmap", + "libc", + "memchr", + "nix", + "typed-path", + "windows-sys 0.61.2", + "zeroize", + "zopfli", +] + [[package]] name = "zlib-rs" version = "0.6.8" @@ -5470,6 +6102,18 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + [[package]] name = "zstd" version = "0.13.5" @@ -5497,3 +6141,18 @@ dependencies = [ "cc", "pkg-config", ] + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] diff --git a/Cargo.toml b/Cargo.toml index 7b49c00f..68510319 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,97 +1,98 @@ -[package] -name = "OxideChat" -version = "0.4.1" -edition = "2024" -description = "A modern, performance and on customization focused AI chat application" -license = "Apache-2.0" -repository = "https://github.com/NxtCore/OxideChat" -readme = "README.md" -keywords = ["chat", "axum", "websocket", "postgres"] -categories = ["web-programming"] - -[dependencies] -axum = { version = "0.8.9" } -tokio = { version = "1.54", features = ["full"] } -serde = { version = "1.0", features = ["derive"] } -serde_json = "1.0" -sqlx = { version = "0.9", features = [ - "postgres", - "chrono", - "tls-native-tls", - "runtime-tokio", - "macros", - "migrate", - "uuid", - "rust_decimal", -] } -dotenv = { version = "0.15" } -argon2 = { version = "0.6" } -uuid = { version = "1.29", features = ["serde", "v4"] } -chrono = { version = "0.4", features = ["serde"] } -tower-cookies = { version = "0.11" } -arc-swap = "1.9.5" -oauth2 = { version = "5", default-features = false } -reqwest = { version = "0.13", default-features = false, features = [ - "rustls", - "json", - "multipart", - "stream", -] } -tower-http = { version = "0.7", features = ["cors"] } -omniference = { version = "0" } -aes-gcm = "0.11" -rand = "0.10" -rust_decimal = { version = "1.43.0", features = ["db-postgres", "serde"] } -futures-util = "0.3.34" -http-body = "1" -async-stream = "0.3.6" -tokio-util = "0.7.20" -extism = "1" -tracing = "0.1" -tracing-subscriber = { version = "0.3", features = ["env-filter"] } -sha2 = "0.11" -base64 = "0.23" -thiserror = "2" -async-trait = "0.1" -anyhow = "1" -infer = "0.22" -pdf-extract = "0.12" -html2text = "0.17" -libc = "0.2" - -[lints.clippy] -correctness = { level = "deny", priority = -1 } -suspicious = { level = "deny", priority = -1 } -perf = { level = "warn", priority = -1 } -style = { level = "warn", priority = -1 } -complexity = { level = "warn", priority = -1 } -must_use_candidate = "warn" -missing_errors_doc = "warn" -missing_panics_doc = "warn" -doc_markdown = "warn" -explicit_iter_loop = "warn" -explicit_into_iter_loop = "warn" -inconsistent_struct_constructor = "warn" -manual_let_else = "warn" -redundant_closure_for_method_calls = "warn" -semicolon_if_nothing_returned = "warn" -unnested_or_patterns = "warn" -unused_self = "warn" -cargo = { level = "warn", priority = -1 } -future_not_send = "warn" -fallible_impl_from = "warn" -dbg_macro = "warn" -todo = "warn" -unimplemented = "warn" -multiple_crate_versions = "allow" -too_many_lines = "warn" -cognitive_complexity = "warn" - -[lints.rust] -unsafe_code = "warn" -missing_docs = "allow" - -[dev-dependencies] -tokio = { version = "1.54", features = ["test-util"] } -tower = { version = "0.5.3", features = ["util"] } -ts-rs = { version = "12.0.1", features = ["uuid-impl", "chrono-impl", "serde-json-impl", "no-serde-warnings"] } +[package] +name = "OxideChat" +version = "0.4.1" +edition = "2024" +description = "A modern, performance and on customization focused AI chat application" +license = "Apache-2.0" +repository = "https://github.com/NxtCore/OxideChat" +readme = "README.md" +keywords = ["chat", "axum", "websocket", "postgres"] +categories = ["web-programming"] + +[dependencies] +axum = { version = "0.8.9" } +tokio = { version = "1.54", features = ["full"] } +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +sqlx = { version = "0.9", features = [ + "postgres", + "chrono", + "tls-native-tls", + "runtime-tokio", + "macros", + "migrate", + "uuid", + "rust_decimal", +] } +dotenv = { version = "0.15" } +argon2 = { version = "0.6" } +uuid = { version = "1.29", features = ["serde", "v4"] } +chrono = { version = "0.4", features = ["serde"] } +tower-cookies = { version = "0.11" } +arc-swap = "1.9.5" +oauth2 = { version = "5", default-features = false } +reqwest = { version = "0.13", default-features = false, features = [ + "rustls", + "json", + "multipart", + "stream", +] } +tower-http = { version = "0.7", features = ["cors"] } +omniference = { version = "0" } +aes-gcm = "0.11" +rand = "0.10" +rust_decimal = { version = "1.43.0", features = ["db-postgres", "serde"] } +futures-util = "0.3.34" +http-body = "1" +async-stream = "0.3.6" +tokio-util = "0.7.20" +extism = "1" +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +sha2 = "0.11" +base64 = "0.23" +thiserror = "2" +async-trait = "0.1" +anyhow = "1" +infer = "0.22" +pdf_oxide = { version = "0.3.78", default-features = false, features = ["legacy-crypto"] } +html2text = "0.17" +libc = "0.2" + +[lints.clippy] +correctness = { level = "deny", priority = -1 } +suspicious = { level = "deny", priority = -1 } +perf = { level = "warn", priority = -1 } +style = { level = "warn", priority = -1 } +complexity = { level = "warn", priority = -1 } +must_use_candidate = "warn" +missing_errors_doc = "warn" +missing_panics_doc = "warn" +doc_markdown = "warn" +explicit_iter_loop = "warn" +explicit_into_iter_loop = "warn" +inconsistent_struct_constructor = "warn" +manual_let_else = "warn" +redundant_closure_for_method_calls = "warn" +semicolon_if_nothing_returned = "warn" +unnested_or_patterns = "warn" +unused_self = "warn" +cargo = { level = "warn", priority = -1 } +future_not_send = "warn" +fallible_impl_from = "warn" +dbg_macro = "warn" +todo = "warn" +unimplemented = "warn" +multiple_crate_versions = "allow" +too_many_lines = "warn" +cognitive_complexity = "warn" + +[lints.rust] +unsafe_code = "warn" +missing_docs = "allow" + +[dev-dependencies] +pdf-extract = "0.12" +tokio = { version = "1.54", features = ["test-util"] } +tower = { version = "0.5.3", features = ["util"] } +ts-rs = { version = "12.0.1", features = ["uuid-impl", "chrono-impl", "serde-json-impl", "no-serde-warnings"] } diff --git a/e2e/tests/knowledge-setup.spec.ts b/e2e/tests/knowledge-setup.spec.ts index 9b18c107..68e14cf8 100644 --- a/e2e/tests/knowledge-setup.spec.ts +++ b/e2e/tests/knowledge-setup.spec.ts @@ -7,16 +7,14 @@ const MANAGED = 'E2E main store'; const QDRANT = 'E2E qdrant'; const KEY = 'e2e-qdrant-api-key-value'; -async function fillConnection(page: Page, fields: {name?: string; kind?: string; mode?: string; url?: string; secret?: string}) { +async function fillConnection(page: Page, fields: {name?: string; kind?: string; url?: string; secret?: string}) { if (fields.name !== undefined) await page.getByTestId('knowledge-connection-name').fill(fields.name); if (fields.kind) { + await page.getByTestId('knowledge-connection-target').click(); + await page.getByTestId('knowledge-connection-target-external').click(); await page.getByTestId('knowledge-connection-kind').click(); await page.getByRole('option', {name: fields.kind}).click(); } - if (fields.mode) { - await page.getByTestId('knowledge-connection-mode').click(); - await page.getByRole('option', {name: fields.mode}).click(); - } if (fields.url !== undefined) await page.getByTestId('knowledge-connection-url').fill(fields.url); if (fields.secret !== undefined) await page.getByTestId('knowledge-connection-secret').fill(fields.secret); } @@ -33,10 +31,13 @@ test.describe.configure({mode: 'serial'}); test.describe('knowledge setup', () => { test('an admin connects the main database as managed storage and tests it', async ({page, api, t}) => { await reset(api); + await page.goto('/settings/knowledge/new'); + await expect(page.getByTestId('knowledge-managed-unavailable')).toBeVisible(); await page.goto('/settings/tools/knowledge'); await expect(page.getByTestId('knowledge-connections-empty')).toBeVisible(); await page.getByTestId('knowledge-connection-add').click(); + await expect(page.getByTestId('knowledge-connection-url')).toBeHidden(); await fillConnection(page, {name: MANAGED}); await page.getByTestId('knowledge-connection-save').click(); await expect(page.getByTestId(`knowledge-connection-${MANAGED}`)).toContainText(t('settings.knowledge_setup.connections.main_database')); @@ -98,6 +99,8 @@ test.describe('knowledge setup', () => { }); test('the default storage is saved through the save bar', async ({page, api}) => { + expect((await api.get('/api/v1/admin/rag')).defaults.connection_id, 'the first storage became the default').toBeTruthy(); + await api.put('/api/v1/admin/rag', {reranker: {model_id: null, top_n: 6}, defaults: {connection_id: null}}); await page.goto('/settings/tools/knowledge'); await page.getByTestId('knowledge-default-connection').click(); await page.getByRole('option', {name: MANAGED}).click(); diff --git a/e2e/tests/knowledge.spec.ts b/e2e/tests/knowledge.spec.ts index 9c0dd750..17812ad6 100644 --- a/e2e/tests/knowledge.spec.ts +++ b/e2e/tests/knowledge.spec.ts @@ -79,6 +79,8 @@ test.describe('knowledge bases', () => { test('an admin maps a Qdrant collection and the test search finds its records', async ({page, t}) => { await page.goto('/settings/knowledge'); await page.getByTestId('knowledge-create').click(); + await page.getByTestId('knowledge-kind').click(); + await page.getByRole('option', {name: t('knowledge.editor.kind_external')}).click(); await page.getByTestId('knowledge-name').fill(BASE); await page.getByTestId('knowledge-tab-source').click(); diff --git a/e2e/tests/managed-knowledge.spec.ts b/e2e/tests/managed-knowledge.spec.ts new file mode 100644 index 00000000..ffa3ef3c --- /dev/null +++ b/e2e/tests/managed-knowledge.spec.ts @@ -0,0 +1,166 @@ +import {test, expect, Api} from './support/fixtures'; +import {uniqueName} from './support/gateway'; +import {AUTH_FILES, LLM, MEMBER, MOCK_LLM_KEY, MOCK_LLM_URL} from './support/constants'; + +const CONNECTION = 'E2E managed pgvector'; +const BASE = 'E2E managed handbook'; + +type Embed = {providerId: string; modelId: string; name: string}; + +async function embeddingModel(api: Api): Promise { + const provider = await api.post('/api/v1/admin/providers', { + kind: 'OPENAI_COMPAT', + name: uniqueName('ManagedEmbed'), + base_url: `${MOCK_LLM_URL}/media`, + api_key: MOCK_LLM_KEY, + }); + const sync = await api.post(`/api/v1/admin/providers/${provider.id}/sync`); + expect(sync.success, JSON.stringify(sync)).toBe(true); + const synced: {id: string; model_id: string; display_name: string}[] = await api.get(`/api/v1/admin/providers/${provider.id}/models`); + const embed = synced.find(model => model.model_id.endsWith('/mock-embed'))!; + await api.patch(`/api/v1/admin/models/${embed.id}`, {output_modalities: ['EMBEDDINGS']}); + await api.put(`/api/v1/admin/models/${embed.id}/pricing`, {pricing: {input: 10, output: 0, tiers: []}}); + return {providerId: provider.id, modelId: embed.id, name: embed.display_name}; +} + +async function knowledgeTool(api: Api): Promise<{id: string; created: boolean}> { + const existing = (await api.get('/api/v1/admin/tools')).find((tool: {name: string}) => tool.name === 'knowledge_search'); + if (existing) return {id: existing.id, created: false}; + const tool = await api.post('/api/v1/admin/tools', { + name: 'knowledge_search', + display_name: 'Knowledge Search', + source_kind: 'BUILTIN', + source_config: {builtin_id: 'knowledge'}, + functions: [{name: 'knowledge_search', input_schema: {type: 'object', properties: {query: {type: 'string'}}, required: ['query']}}], + }); + return {id: tool.id, created: true}; +} + +test.describe.configure({mode: 'serial'}); + +test.describe('managed knowledge bases', () => { + let embed: Embed; + let connectionId: string; + let baseId: string; + let createdToolId: string | null = null; + let pgvectorReady = false; + + test.beforeAll(async ({browser, baseURL}) => { + const context = await browser.newContext({baseURL, storageState: AUTH_FILES.admin}); + const api = new Api(context.request); + embed = await embeddingModel(api); + const tool = await knowledgeTool(api); + if (tool.created) createdToolId = tool.id; + const setup = await api.post('/api/v1/admin/rag/connections', { + name: CONNECTION, + kind: 'pgvector', + mode: 'managed', + url: null, + secret: null, + embedding: {model_id: embed.modelId, dimensions: null}, + }); + connectionId = setup.connections.find((item: {name: string}) => item.name === CONNECTION).id; + const health = await api.post(`/api/v1/admin/rag/connections/${connectionId}/test`); + if (!health.ok && !['extension_missing', 'extension_too_old'].includes(health.error)) throw new Error(`managed connection test failed: ${JSON.stringify(health)}`); + pgvectorReady = Boolean(health.ok); + await api.put('/api/v1/admin/rag', { + reranker: {model_id: null, top_n: 6}, + defaults: {connection_id: connectionId}, + chunking: {chunk_size: 400, overlap_percent: 15}, + }); + await context.close(); + }); + + test.afterAll(async ({browser, baseURL}) => { + const context = await browser.newContext({baseURL, storageState: AUTH_FILES.admin}); + const api = new Api(context.request); + await api.put('/api/v1/admin/rag', {reranker: {model_id: null, top_n: 6}, defaults: {connection_id: null}}); + for (const base of await api.get('/api/v1/knowledge-bases')) { + if (base.name === BASE) await api.delete(`/api/v1/knowledge-bases/${base.id}`); + } + if (connectionId) await api.request.delete(`/api/v1/admin/rag/connections/${connectionId}`); + if (createdToolId) await api.request.delete(`/api/v1/admin/tools/${createdToolId}`); + if (embed?.providerId) await api.request.delete(`/api/v1/admin/providers/${embed.providerId}`); + await context.close(); + }); + + test('uploads a document into a managed knowledge base and finds it via hybrid search', async ({page, t}) => { + test.skip(!pgvectorReady, 'pgvector 0.8+ extension is required on the database'); + + await page.goto('/settings/knowledge'); + await page.getByTestId('knowledge-create').click(); + await page.getByTestId('knowledge-name').fill(BASE); + await page.getByTestId('settings-save-bar-save').click(); + await expect(page).toHaveURL(/\/settings\/knowledge\/[0-9a-f-]{36}\?tab=documents/); + baseId = page.url().match(/knowledge\/([0-9a-f-]{36})/)![1]!; + + await page.getByTestId('knowledge-documents-input').setInputFiles({ + name: 'handbook.md', + mimeType: 'text/markdown', + buffer: Buffer.from('# Travel Policy\n\nRail tickets are booked through the internal travel desk and reimbursed within five business days.\n'), + }); + await expect(page.getByTestId('knowledge-document-handbook.md')).toBeVisible(); + await expect(page.getByTestId('knowledge-document-status-handbook.md')).toContainText(t('knowledge.documents.status.ready'), {timeout: 30_000}); + + await page.getByTestId('knowledge-document-text-handbook.md').click(); + await expect(page.getByTestId('knowledge-document-text')).toContainText('Rail tickets are booked through the internal travel desk'); + await page.keyboard.press('Escape'); + + await page.getByTestId('knowledge-tab-search').click(); + await page.getByTestId('knowledge-search-query').fill('How are rail tickets booked?'); + await page.getByTestId('knowledge-search-run').click(); + const hits = page.getByTestId('knowledge-search-hit'); + await expect(hits.first()).toContainText('Rail tickets are booked through the internal travel desk'); + }); + + test('per-document limit access hides restricted documents from other users', async ({page, browser, baseURL}) => { + test.skip(!pgvectorReady || !baseId, 'requires indexed managed base'); + + await page.request.put(`/api/v1/knowledge-bases/${baseId}/assignments`, {data: {targets: [{kind: 'everyone'}]}}); + const users = await (await page.request.get('/api/v1/admin/users', {params: {page: 1, size: 10, search: MEMBER.username}})).json(); + const member = users.items.find((user: {username: string}) => user.username === MEMBER.username); + const docs = await (await page.request.get(`/api/v1/knowledge-bases/${baseId}/documents`)).json(); + const doc = docs.find((item: {filename: string}) => item.filename === 'handbook.md'); + expect(doc).toBeTruthy(); + + const memberContext = await browser.newContext({baseURL, storageState: AUTH_FILES.member}); + try { + const before = await (await memberContext.request.post(`/api/v1/knowledge-bases/${baseId}/search`, {data: {query: 'rail tickets'}})).json(); + expect(before.hits.length).toBeGreaterThan(0); + + const admin = await (await page.request.get('/api/v1/users/@me')).json(); + const restricted = await page.request.put(`/api/v1/knowledge-bases/${baseId}/documents/${doc.id}/assignments`, { + data: {targets: [{kind: 'user', id: admin.id}]}, + }); + expect(restricted.status()).toBe(200); + + const after = await (await memberContext.request.post(`/api/v1/knowledge-bases/${baseId}/search`, {data: {query: 'rail tickets'}})).json(); + expect(after.hits).toEqual([]); + } finally { + await memberContext.close(); + } + }); + + test('attaching a managed knowledge base in chat returns cited answers', async ({page, t, seed}) => { + test.skip(!pgvectorReady || !baseId || !LLM.isMock, 'requires pgvector and local mock LLM'); + + await page.goto('/'); + await page.getByTestId('model-selector').click(); + const search = page.getByPlaceholder(t('chat.model_selector.search_models')); + await search.fill(seed.model.displayName); + await page.getByText(seed.model.displayName, {exact: true}).last().click(); + await expect(search).toBeHidden(); + + await page.getByTestId('composer-settings').click(); + await page.getByTestId(`composer-knowledge-${BASE}`).click(); + await page.keyboard.press('Escape'); + + const composer = page.locator('textarea').first(); + await composer.fill('How are rail tickets booked?'); + await composer.press('Enter'); + await expect(page).toHaveURL(/\/chats\/[0-9a-f-]{36}/); + const reply = page.locator('[data-testid="message"][data-role="assistant"]').first(); + await expect(reply).toContainText('Rail tickets are booked through the internal travel desk', {timeout: 60_000}); + await expect(page.getByTestId('knowledge-source-chip').first()).toContainText('handbook.md'); + }); +}); diff --git a/frontend/components/chat/ToolExecutionDisplay.vue b/frontend/components/chat/ToolExecutionDisplay.vue index f66ecf3d..e3b3897c 100644 --- a/frontend/components/chat/ToolExecutionDisplay.vue +++ b/frontend/components/chat/ToolExecutionDisplay.vue @@ -39,7 +39,7 @@ :class="source.url ? 'hover:bg-accent' : ''" data-testid="knowledge-source-chip" > - [{{ source.n }}] {{ source.title || source.knowledge_base }}{{ source.section ? ` › ${source.section}` : '' }} + [{{ source.n }}] {{ source.title || source.knowledge_base }}{{ source.section ? ` › ${source.section}` : '' }}{{ source.page ? ` (${store.getTranslation('knowledge.search.page', {page: String(source.page)})})` : '' }} @@ -145,7 +145,7 @@ function isValidImageProtocol(url: string): boolean { return false; } -type KnowledgeSource = {n: number; knowledge_base: string; title: string | null; section: string | null; url: string | null; text: string}; +type KnowledgeSource = {n: number; knowledge_base: string; title: string | null; section: string | null; url: string | null; text: string; page: number | null}; const knowledgeSources = computed(() => { if (props.name !== 'knowledge_search' || !props.output) return []; @@ -163,6 +163,7 @@ const knowledgeSources = computed(() => { section: text(source.section), url: url && /^https?:\/\//i.test(url) ? url : null, text: text(source.text) ?? '', + page: typeof source.page === 'number' ? source.page : null, }; }); }); diff --git a/frontend/components/settings/knowledge/ConnectionsCard.vue b/frontend/components/settings/knowledge/ConnectionsCard.vue index f6435e28..6a799e1b 100644 --- a/frontend/components/settings/knowledge/ConnectionsCard.vue +++ b/frontend/components/settings/knowledge/ConnectionsCard.vue @@ -35,7 +35,18 @@ -
+
+ {{ t('target') }} + + + + {{ t(`target_${target}`) }} + + +

{{ t('target_internal_hint') }}

+
+ +
{{ t('kind') }} @@ -46,9 +57,9 @@
-
+
{{ t('mode') }} - + {{ t('mode_managed') }} @@ -59,13 +70,13 @@

{{ t('mode_hint') }}

-
+
{{ t('url') }}

{{ editing?.url_from_env ? t('url_from_env') : t(`url_hint_${form.kind}`) }}

-
+
{{ t(`secret_${form.kind}`) }} + + + + + {{ t('reindex_confirm_title') }} + {{ reindexDescription }} + + + {{ store.getTranslation('common.cancel') }} + {{ t('reindex_confirm') }} + + +
diff --git a/frontend/components/settings/knowledge/Editor.vue b/frontend/components/settings/knowledge/Editor.vue index 6f89163d..a168a966 100644 --- a/frontend/components/settings/knowledge/Editor.vue +++ b/frontend/components/settings/knowledge/Editor.vue @@ -1,5 +1,5 @@ diff --git a/frontend/pages/settings/tools/knowledge.vue b/frontend/pages/settings/tools/knowledge.vue index 1f52e619..1b2ead0d 100644 --- a/frontend/pages/settings/tools/knowledge.vue +++ b/frontend/pages/settings/tools/knowledge.vue @@ -40,6 +40,20 @@ + + + + +
+ +
+

{{ store.getTranslation('settings.knowledge_setup.chunking_title') }}

+ + + + + +
@@ -57,20 +71,30 @@