diff --git a/README.md b/README.md index def8dbc..f8755b9 100644 --- a/README.md +++ b/README.md @@ -26,11 +26,11 @@ It began as an exploratory PDF-chat prototype. It now includes a product landing ## One conversation for the job -The product page opens with a full-screen gradient hero, followed by a concise “How it works” section and a crisp HTML/CSS preview. Team credits and deeper technical details live in the docs. **Open Mantis** opens the working chat: upload a manual, ask a question, attach a photo, and expand sources beneath the answer. **Try an example** opens that same interface with a sample conversation. Manuals live in a small drawer; there is no separate demo interface or library page. +The product page opens with a full-screen black hero with a gradient headline, followed by a concise “How it works” section and interactive examples rendered in HTML/CSS. Team credits and deeper technical details live in the docs. **Open Mantis** opens the working chat: upload a manual, ask a question, attach a photo, and expand sources beneath the answer. **Try an example** on the landing page scrolls to local examples; their source notes expand inline, and previous exchanges remain in the scrolling transcript. The full app also offers sample conversations in its own chat. The top manual picker lists uploaded documents. The left **Your chats** drawer lists saved conversations so you can reopen them; there is no separate library page. ![Mantis product page](docs/assets/product.jpg) -![Mantis chat with a connected context, inline sources, and manual upload](docs/assets/workspace.jpg) +![Mantis saved conversations in the Your chats drawer](docs/assets/workspace.jpg) ## What you can do @@ -65,7 +65,7 @@ Open the **[product page](http://127.0.0.1:8000)** or go directly to the **[work ### 1. Try the same app with an example -Choose **Try an example**, or open [`/workspace#demo`](http://127.0.0.1:8000/workspace#demo). The chat starts with a scripted spindle-overload scenario. Try the illustrative alarm-screen attachment, ask a maintenance handover question, and expand the sample source. No API key or AI calls are involved. Personal photos attached in example mode stay in the browser and are not analyzed. +Use the landing page’s sample questions and expandable notes without leaving the page. To explore examples in the full chat, choose **Try an example** there, or open [`/workspace#demo`](http://127.0.0.1:8000/workspace#demo). The chat starts with a scripted spindle-overload scenario. The landing page offers suggested questions for vibration, overheating, alarm photos, and maintenance records in one scrollable chat; each click appends another exchange. Try the illustrative alarm-screen attachment, ask a maintenance handover question, and expand the sample source. No API key or AI calls are involved. Personal photos attached in example mode stay in the browser and are not analyzed. Choose **Exit example** or upload your own manual to leave example mode. Then attach a photo or ask about the selected manual to use the real backend. Switching modes resets the conversation, so example replies never enter a live request's history. @@ -81,7 +81,7 @@ In live mode, attach one JPEG, PNG, or WebP photo (up to 8 MB and 20 megapixels) Live image handling follows the [official OpenAI image-input format](https://developers.openai.com/api/docs/guides/images-vision). The configured chat model must support image input and strict structured outputs. This request path has been tested with a fake provider; live image accuracy and provider compatibility still need validation with a valid key. -Mantis does not persist photos or conversations. The browser sends the last four successful text exchanges as follow-up context; old image bytes are not resent. Reattach a photo when it needs to be examined again. The provider's data-processing policies apply to live requests. +Mantis saves conversation text and cited passages in the workspace’s local server database. Photo files are not saved; reopened chats show a note where a personal photo was attached. The browser sends the last four successful text exchanges as follow-up context; old image bytes are not resent. Reattach a photo when it needs to be examined again. The provider's data-processing policies apply to live requests. ### 4. Verify the source @@ -97,8 +97,8 @@ Read the [architecture guide](docs/architecture.md) for retrieval behavior, conc ## Quality and current limits -- **34 Python regression tests** cover real PDF extraction with a fake provider, storage isolation, persistence, deletion, concurrency, request limits, and citation handling. -- **12 frontend regressions** cover bounded follow-up context, stale responses and reset cancellation, retry handling, mode/manual resets, current-message-only photos, and key-free examples. +- **48 Python regression tests** cover real PDF extraction with a fake provider, storage isolation, persistence, deletion, concurrency, request limits, and citation handling. +- **20 frontend regressions** cover bounded follow-up context, stale responses and reset cancellation, retry handling, mode/manual resets, current-message-only photos, and key-free examples. - **CI** runs Python/frontend tests and lint/format checks, JavaScript syntax/format checks, and an independent built-wheel smoke test for pages, assets, and the demo API. - **Browser checks** cover desktop/mobile layouts, demo citations, keyboard focus, and cancelling/reselecting a file. - **Still to evaluate:** representative industrial answer quality and live-provider behavior. Software tests are not evidence of troubleshooting accuracy. diff --git a/docs/about.md b/docs/about.md index 792a5dd..cd453cb 100644 --- a/docs/about.md +++ b/docs/about.md @@ -15,7 +15,7 @@ The engineer remains responsible for checking the actual manual and following ap - Text-based PDF upload, indexing, and a persistent manual library. - Questions scoped to one equipment manual, with a retrieval cutoff for weak matches. - Answers with validated source identifiers, page numbers, and inspectable excerpts. -- Browser-scoped workspaces, duplicate detection, and document/index deletion. +- Browser-scoped workspaces, duplicate detection, document/index deletion, and saved text conversations with restore/delete actions. - One chat for manual questions, photos, follow-ups, and inline sources. A key-free example runs in that same interface with scripted replies; personal example photos stay local. The application is a local pilot. Software regression tests cover its API and storage behavior; retrieval quality and answer correctness have not yet been evaluated on a representative set of industrial manuals. diff --git a/docs/api.md b/docs/api.md index 800c41a..f740278 100644 --- a/docs/api.md +++ b/docs/api.md @@ -43,7 +43,7 @@ curl --cookie data/dev.cookies \ Real questions use `demo: false` and the selected manual's `document_id`, returned by the upload/list endpoints. Optional `history` contains up to eight text turns (`role`: `user` or `assistant`, `content`: up to 10,000 characters). The browser sends the last four successful exchanges and resets them when the manual or mode changes. History is context, not evidence. Responses contain `answer`, `sources`, `insufficient_evidence`, and `demo`. A source contains its document identifier, name, page, and text. -Optional `image` is a base64 data URL for one valid JPEG, PNG, or WebP image up to 8 MB / 20 megapixels; animated images and remote URLs are rejected. Question request bodies are limited to 12 MB before JSON parsing. The image is sent to the provider for visible observations/transcription, which inform manual retrieval. Without a manual, an image (or follow-up history) can request observations/context collection, with `insufficient_evidence: true` and no citations. Old images are not part of text history. Photos and chat turns are not stored by Mantis. The legacy `demo: true` API still returns training-manual excerpts and rejects attached images; the app’s example conversation runs locally in the same chat UI. +Optional `image` is a base64 data URL for one valid JPEG, PNG, or WebP image up to 8 MB / 20 megapixels; animated images and remote URLs are rejected. Question request bodies are limited to 12 MB before JSON parsing. The image is sent to the provider for visible observations/transcription, which inform manual retrieval. Without a manual, an image (or follow-up history) can request observations/context collection, with `insufficient_evidence: true` and no citations. Old images are not part of text history. Photo files are not stored by Mantis; completed text exchanges and sources can be saved through the chat-history endpoints. The legacy `demo: true` API still returns training-manual excerpts and rejects attached images; the app’s example conversation runs locally in the same chat UI. For real PDF uploads, configure the provider first. Uploaded text is sent for embedding, and retrieved passages/questions, recent text history, and photo observations are sent for answer generation. Duplicate detection can reuse an existing document; a new upload can incur provider usage. @@ -63,3 +63,9 @@ For real PDF uploads, configure the provider first. Uploaded text is sent for em | 503 | Real PDF analysis requested without a configured API key | Some failures return JSON `detail`; Host validation can return plain text. Source-ID validation checks identifiers against retrieved passages and is not a claim-level correctness guarantee. + +## Saved chats + +`GET /api/chats` lists this workspace’s chat metadata; `GET /api/chats/{id}` returns its transcript. `POST /api/chats` creates a chat; `PUT /api/chats/{id}` updates it with the last returned `revision`; stale revisions or attempts to change manual/mode return 409. `DELETE /api/chats/{id}` removes the owned chat. Unknown/other-workspace chats return 404. + +Save payloads contain `document_id`, `demo`, `revision`, and `messages`. Messages must be completed alternating user/assistant pairs, each with `role`, `content`, optional source records, `demo`, `insufficient_evidence`, and `photo` (`""`, `"sample"`, or `"omitted"`). Extra fields, personal photo data, privileged roles, and oversized transcripts are rejected. Limits: 100 messages per chat, 100 chats per workspace, 1 MB per save. Deleting a manual does not delete saved conversations. diff --git a/docs/architecture.md b/docs/architecture.md index 4f4ac48..51c0c2a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -30,7 +30,7 @@ Each question specifies one manual. Retrieval embeds the question using that man The model returns a structured answer and source identifiers. The API checks that identifiers refer to retrieved passages and that a substantive answer has sources. These checks establish source identity; they do not prove that every answer claim is supported. The threshold and answer behavior need evaluation against representative manuals and questions. -The frontend supplies up to eight successful text turns for follow-up context. Retrieval includes the last two user questions and current photo observations. History and image text are treated as untrusted context, never as verified manual evidence. New chat, manual changes, and live/example transitions reset history. Photos are validated (format, bytes, pixels, animation), transcribed/described by the configured image-capable model, and used to inform retrieval. Without relevant excerpts, photos can support observations and clarification but cannot produce a source-backed diagnosis. No photos or chat turns are persisted by Mantis. +The frontend supplies up to eight successful text turns for follow-up context. Retrieval includes the last two user questions and current photo observations. History and image text are treated as untrusted context, never as verified manual evidence. New chat, manual changes, and live/example transitions reset history. Photos are validated (format, bytes, pixels, animation), transcribed/described by the configured image-capable model, and used to inform retrieval. Without relevant excerpts, photos can support observations and clarification but cannot produce a source-backed diagnosis. Conversation text and cited passages are stored in workspace-scoped SQLite chats after successful exchanges; photo bytes are not stored. Reopening a chat restores its manual/mode and last four text exchanges. Revision checks reject stale updates from another tab. Chats have a 1 MB request limit, 100-message cap, and 100-chat workspace quota. A removed manual leaves its chat readable but blocks continuation under that missing context. ## Workspace boundary @@ -44,8 +44,12 @@ The current limits are 30 manuals per workspace and 2,000 chunks per manual. Bru ## Product and frontend layout -`/` serves the product presentation; `/workspace` serves the working assistant. Both pages are packaged under `mantis/web/pages/` and use self-hosted assets. CSS lives in `mantis/web/css/`; JavaScript modules live in `mantis/web/js/`. The product page is a static presentation with a real screenshot and links into one working chat app. `/workspace#demo` loads a scripted example into that same app. `conversation.js` owns cancellation and bounded text history; `examples.js` contains the key-free scenarios; `workspace.js` binds uploads, photos, the manual drawer, and inline expandable sources. There is no parallel demo interface or full library page. +`/` serves the product presentation; `/workspace` serves the working assistant. Both pages are packaged under `mantis/web/pages/` and use self-hosted assets. CSS lives in `mantis/web/css/`; JavaScript modules live in `mantis/web/js/`. The product page is a presentation with inline scripted examples and links into one working chat app. `product-preview.js` reuses `examples.js` for the landing examples; source details expand locally without navigation. `/workspace#demo` loads a scripted example into that same app. `conversation.js` owns cancellation and bounded text history; `examples.js` contains the key-free scenarios; `workspace.js` binds uploads, photos, the manual drawer, and inline expandable sources. There is no parallel demo interface or full library page. The landing page follows the owner-supplied design reference while using the original presentation's logos, team portraits, names, and role labels. Mock telemetry, inventory records, invented performance figures, and unsupported certifications from the reference are not product data. The Python wheel includes HTML, CSS, scripts, fonts, logos, and portraits through setuptools package data. Runtime data and `.env` are resolved from the working directory, so an installed package can run outside the source checkout. + +## Frontend revisions + +`mantis/frontend.py` fingerprints the CSS/JavaScript bundle and places page assets under a shared `/static/v/{revision}/` URL prefix. Relative module and stylesheet imports inherit that prefix, so new HTML does not reuse an older cached module graph. HTML and static responses use `Cache-Control: no-cache` for revalidation; API responses remain `no-store`. The existing `/static/` paths remain supported, and Starlette still enforces the public-directory boundary. Font URLs are relative to the stylesheet. diff --git a/docs/assets/README.md b/docs/assets/README.md index 1aa3af8..43ee68f 100644 --- a/docs/assets/README.md +++ b/docs/assets/README.md @@ -3,6 +3,6 @@ - `banner.svg`: editable artwork for the GitHub README, using the existing Mantis mark and black/orange project identity. - `banner.png`: 1280 × 400 raster export, so GitHub renders the bundled Anton and Space Mono typography consistently. - `product.jpg`: screenshot of the real product landing page. -- `workspace.jpg`: screenshot of the actual unified chat in example mode, with no private manuals or credentials. +- `workspace.jpg`: screenshot of the actual Your chats drawer with a saved example conversation and no private manuals or credentials. The banner source embeds the original Mantis mark. The PNG was rendered from that SVG with resvg using `mantis/web/assets/Anton-Regular.ttf` and `mantis/web/assets/SpaceMono-Regular.ttf`. Font licenses and brand provenance are documented in [the application asset guide](../../mantis/web/assets/README.md). diff --git a/docs/assets/product.jpg b/docs/assets/product.jpg index a7f85d5..73ea37d 100644 Binary files a/docs/assets/product.jpg and b/docs/assets/product.jpg differ diff --git a/docs/assets/workspace.jpg b/docs/assets/workspace.jpg index 7367231..8226122 100644 Binary files a/docs/assets/workspace.jpg and b/docs/assets/workspace.jpg differ diff --git a/docs/configuration.md b/docs/configuration.md index 0f98cd5..836d969 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -15,7 +15,7 @@ For a new setup, copy `.env.example` to `.env` and configure the key locally. `. The default server limits are 20 MB and 300 pages per PDF, 2,000 chunks per manual, and 30 manuals per workspace. The multipart-body limiter allows a bounded envelope in addition to the file limit. -Uploaded manual text is sent to OpenAI to create embeddings. Questions, the last four successful text exchanges, and retrieved excerpts are sent for answer generation. In live mode, a current-message photo is sent for visual observations, which can inform manual retrieval; photos are limited to JPEG/PNG/WebP, 8 MB and 20 megapixels. Photos and chat history are not persisted by Mantis. The question-body cap is 12 MB. The original PDF remains in the local database. Example mode uses the same chat interface with scripted replies, makes no AI calls, and keeps attached photos local. Live photos follow the [official OpenAI image-input format](https://developers.openai.com/api/docs/guides/images-vision); configured key/model availability still needs a live-provider check. +Uploaded manual text is sent to OpenAI to create embeddings. Questions, the last four successful text exchanges, and retrieved excerpts are sent for answer generation. In live mode, a current-message photo is sent for visual observations, which can inform manual retrieval; photos are limited to JPEG/PNG/WebP, 8 MB and 20 megapixels. Chat text and sources are saved in the local SQLite database under the same browser-workspace cookie as manuals. Photo files are not persisted. Chat history is limited to 100 chats per workspace, 100 messages per chat, and 1 MB per save request. The question-body cap is 12 MB. The original PDF remains in the local database. Example mode uses the same chat interface with scripted replies, makes no AI calls, and keeps attached photos local. Live photos follow the [official OpenAI image-input format](https://developers.openai.com/api/docs/guides/images-vision); configured key/model availability still needs a live-provider check. Changing the embedding model affects new indexes. Existing manuals retain their model identifier for compatible question embeddings. A model identifier still needs to be available to the configured provider account. diff --git a/docs/running.md b/docs/running.md index 32139c7..5705fa5 100644 --- a/docs/running.md +++ b/docs/running.md @@ -65,3 +65,5 @@ After changing `.env`, restart the server. `--reload` watches source changes; do | Cookie does not persist over local HTTP | Use `MANTIS_SECURE_COOKIE=false` locally. Secure cookies require HTTPS. | See [configuration](configuration.md), [API usage](api.md), and [deployment boundaries](deployment.md). + +If an older checkout renders with overlapping controls or default browser buttons, perform one hard reload (Chrome on macOS: Command–Shift–R). Current releases use revisioned CSS/script URLs and revalidation headers so normal reloads pick up interface changes together. diff --git a/docs/verification.md b/docs/verification.md index cbd3551..7cebf80 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -1,6 +1,6 @@ # Verification record -The current implementation has **34 passing Python regression tests** and **12 frontend regression tests**, plus Python lint/format checks and frontend syntax/format checks in [GitHub Actions](../.github/workflows/checks.yml). +The current implementation has **48 passing Python regression tests** and **20 frontend regression tests**, plus Python lint/format checks and frontend syntax/format checks in [GitHub Actions](../.github/workflows/checks.yml). ## Automated coverage @@ -23,7 +23,7 @@ Tests generate their own PDFs and replace the AI provider. They require no live ## Manual browser checks -The unified app was checked at 1280px and 390px: scripted spindle and alarm-photo examples, inline source expansion, keyboard submission, and no horizontal overflow. An isolated temporary server with a fake provider exercised the actual PDF upload, active-manual selection, source-backed question and follow-up, original PDF link, live photo request path, and manual drawer. That check made no external AI calls. The landing page uses crisp HTML/CSS instead of a screenshot preview. Its gradient hero fills the first screen at 1440×900 and 390×844; the workflow and example follow below. Section anchors clear the sticky header and neither layout overflows horizontally. README images show the actual local app/example. +The unified app was checked at 1280px and 390px: scripted spindle and alarm-photo examples, inline source expansion, keyboard submission, and no horizontal overflow. An isolated temporary server with a fake provider exercised the actual PDF upload, active-manual selection, source-backed question and follow-up, original PDF link, live photo request path, and manual drawer. That check made no external AI calls. The landing page uses crisp HTML/CSS instead of a screenshot preview. Its black hero, with a gradient confined to “ON AUTOPILOT.”, fills the first screen at 1440×900 and 390×844; the workflow and example follow below. Section anchors clear the sticky header and neither layout overflows horizontally. README images show the actual local app/example. ## What this does not establish @@ -40,3 +40,17 @@ CI builds the Python wheel and runs `scripts/check_package.py` against its extra `npm test` exercises the request controller and example boundaries directly: the last four successful text exchanges, current-message-only images, stale response suppression, abort/reset behavior, retries, manual/mode context resets, and zero provider calls for examples. It does not emulate browser layout. The new API regressions verify photo validation, extraction-to-retrieval flow, bounded/role-limited history, missing-key behavior, question request limits, and rejection of fabricated citations when no manual exists. Software test success does not validate real model image-reading accuracy. + +The follow-up visual correction restores the black landing palette with gradient text only on “ON AUTOPILOT.” and removes dashboard-style chat headers. The chat follows the original recording with a narrow logo rail, compact replies, orange user messages, a bottom Send composer, a small manual-upload action, and restored sample inputs. + +Chrome previously reused an old stylesheet/module against new HTML, causing a null-element script error and an unstyled layout. After a normal reload, the corrected page rendered correctly with no application console error. CSS and JS modules now share a content-based revision URL; HTML/static responses require revalidation. Regressions cover imported-module changes, cache headers/304 responses, and versioned static-path traversal. + +Landing examples now use the same scenario data as the app. Their native source disclosures expand inline; each question appends its own answer and source notes, while earlier exchanges remain available by scrolling. The landing page’s “Try an example” action scrolls to that section rather than opening the full app. + +Final layout checks verified that the landing demo keeps all three tested exchanges (six messages) in one 480px scrollable transcript. Suggested questions sit below it. The real app starts with an upload prompt; its upload action and helper text are inside the same bottom-bar border on desktop and mobile, with no horizontal overflow or application console error. + +Saved-chat tests cover persistence, workspace isolation, deletion, revision conflicts, immutable manual/mode, request/message/chat quotas, exclusion of personal photo bytes, and restoring bounded context while invalidating an older pending reply. + +Browser checks for Your chats verified automatic save, reopening after a fresh page load, continuing a restored conversation, separate manuals/chats drawers, and mobile access without horizontal overflow or application console errors. + +Review regressions simulate Windows-normalized asset paths and a second writer immediately after a chat transaction commits. The workspace controller is also exercised with a DOM double and deferred requests: blocked manual changes/deletion during failed or pending saves, retry during a follow-up, removed-manual recovery, discard confirmation, and successful upload selection. These are state/interaction tests, not browser layout checks. diff --git a/mantis/api.py b/mantis/api.py index 3692e19..f561910 100644 --- a/mantis/api.py +++ b/mantis/api.py @@ -16,14 +16,14 @@ from dotenv import load_dotenv from fastapi import FastAPI, File, Form, HTTPException, Request, UploadFile -from fastapi.responses import FileResponse, JSONResponse, Response -from fastapi.staticfiles import StaticFiles +from fastapi.responses import JSONResponse, Response from openai import OpenAI, OpenAIError from PIL import Image, UnidentifiedImageError -from pydantic import BaseModel, Field, field_validator +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator from starlette.concurrency import run_in_threadpool from starlette.middleware.trustedhost import TrustedHostMiddleware +from mantis.frontend import FrontendFiles, render_page from mantis.middleware import UploadBodyLimitMiddleware from mantis.rag import DEMO_CHUNKS, cosine, extract_chunks, terms from mantis.store import Store, WorkspaceFullError @@ -94,6 +94,41 @@ class GeneratedAnswer(BaseModel): insufficient_evidence: bool +class SavedSource(BaseModel): + model_config = ConfigDict(extra="forbid") + document_id: str = Field(max_length=64) + name: str = Field(max_length=180) + page: int = Field(ge=1, le=300) + text: str = Field(max_length=4000) + + +class SavedMessage(BaseModel): + model_config = ConfigDict(extra="forbid") + role: Literal["user", "assistant"] + content: str = Field(min_length=1, max_length=10000) + sources: list[SavedSource] = Field(default_factory=list, max_length=5) + demo: bool = False + insufficient_evidence: bool = False + photo: Literal["", "sample", "omitted"] = "" + + +class SavedChat(BaseModel): + model_config = ConfigDict(extra="forbid") + document_id: str = Field(default="", max_length=64) + demo: bool = False + revision: int = Field(default=0, ge=0) + messages: list[SavedMessage] = Field(min_length=2, max_length=100) + + @model_validator(mode="after") + def completed_exchanges(self): + if len(self.messages) % 2 or any( + message.role != ("user" if index % 2 == 0 else "assistant") + for index, message in enumerate(self.messages) + ): + raise ValueError("Save completed user/assistant exchanges only.") + return self + + def create_app(data_dir=None): api = FastAPI(title="Mantis", version="0.2.0") store = Store( @@ -142,6 +177,10 @@ async def workspace(request: Request, call_next): ) if request.url.path.startswith("/api/"): response.headers["Cache-Control"] = "no-store" + elif request.url.path in ("/", "/workspace") or request.url.path.startswith( + "/static/" + ): + response.headers["Cache-Control"] = "no-cache" return response def provider(): @@ -153,14 +192,14 @@ def provider(): ) return OpenAI(api_key=key, timeout=45, max_retries=1) - def limit(request): + def limit(request, group=""): now = time.monotonic() # Bound memory for this single-process limiter. if len(buckets) > 5000: for key in list(buckets): if not buckets[key] or buckets[key][-1] < now - 60: del buckets[key] - bucket = buckets[request.state.workspace] + bucket = buckets[request.state.workspace + group] while bucket and bucket[0] < now - 60: bucket.popleft() if len(bucket) >= 20: @@ -201,6 +240,44 @@ def health(): "version": "0.2.0", } + @api.get("/api/chats") + def chats(request: Request): + return {"chats": store.chats(request.state.workspace)} + + @api.get("/api/chats/{identifier}") + def get_chat(identifier: str, request: Request): + result = store.chat(request.state.workspace, identifier) + if not result: + raise HTTPException(404, "Chat not found.") + return {"chat": result} + + def persist_chat(body, request, identifier=None): + limit(request, ":history") + try: + return { + "chat": store.save_chat( + request.state.workspace, body.model_dump(), identifier + ) + } + except LookupError as exc: + raise HTTPException(404, str(exc)) + except ValueError as exc: + raise HTTPException(409, str(exc)) + + @api.post("/api/chats", status_code=201) + def create_chat(body: SavedChat, request: Request): + return persist_chat(body, request) + + @api.put("/api/chats/{identifier}") + def update_chat(identifier: str, body: SavedChat, request: Request): + return persist_chat(body, request, identifier) + + @api.delete("/api/chats/{identifier}") + def delete_chat(identifier: str, request: Request): + if not store.delete_chat(request.state.workspace, identifier): + raise HTTPException(404, "Chat not found.") + return {"deleted": True} + @api.get("/api/documents") def documents(request: Request): return {"documents": store.documents(request.state.workspace)} @@ -480,11 +557,11 @@ def question(body: Question, request: Request): @api.get("/") def home(): - return FileResponse(WEB_DIR / "pages/index.html") + return render_page(WEB_DIR, "index.html") @api.get("/workspace", include_in_schema=False) def workspace_page(): - return FileResponse(WEB_DIR / "pages/workspace.html") + return render_page(WEB_DIR, "workspace.html") - api.mount("/static", StaticFiles(directory=WEB_DIR), name="static") + api.mount("/static", FrontendFiles(directory=WEB_DIR), name="static") return api diff --git a/mantis/frontend.py b/mantis/frontend.py new file mode 100644 index 0000000..18510fe --- /dev/null +++ b/mantis/frontend.py @@ -0,0 +1,32 @@ +"""Keep HTML, styles, and the complete browser module graph on one revision.""" + +import hashlib +import re + +from fastapi.responses import HTMLResponse +from fastapi.staticfiles import StaticFiles +from starlette.exceptions import HTTPException + + +def render_page(web_dir, filename): + digest = hashlib.sha256() + for path in sorted(web_dir.rglob("*")): + if path.is_file() and path.suffix in (".js", ".css"): + digest.update(path.relative_to(web_dir).as_posix().encode()) + digest.update(b"\0") + digest.update(path.read_bytes()) + revision = digest.hexdigest()[:16] + html = (web_dir / "pages" / filename).read_text(encoding="utf-8") + return HTMLResponse(html.replace("/static/", f"/static/v/{revision}/")) + + +class FrontendFiles(StaticFiles): + async def get_response(self, path, scope): + normalized = path.replace("\\", "/") + if normalized.startswith("v/"): + match = re.fullmatch(r"v/[0-9a-f]{16}/(.+)", normalized) + if not match: + raise HTTPException(404) + path = match.group(1) + # StaticFiles still enforces the public directory boundary. + return await super().get_response(path, scope) diff --git a/mantis/middleware.py b/mantis/middleware.py index 5433c53..bf01e86 100644 --- a/mantis/middleware.py +++ b/mantis/middleware.py @@ -12,17 +12,27 @@ def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): - if ( - scope["type"] != "http" - or scope["method"] != "POST" - or scope["path"] not in ("/api/documents", "/api/questions") + if scope["type"] != "http": + return await self.app(scope, receive, send) + path = scope["path"] + saved_chat = (scope["method"] == "POST" and path == "/api/chats") or ( + scope["method"] == "PUT" and path.startswith("/api/chats/") + ) + if not saved_chat and ( + scope["method"] != "POST" + or path not in ("/api/documents", "/api/questions") ): return await self.app(scope, receive, send) - # Allow a small, bounded multipart envelope in addition to the file limit. + # Bound JSON history and photos as well as the multipart envelope. maximum = ( - 12 * 1024 * 1024 - if scope["path"] == "/api/questions" - else int(os.getenv("MANTIS_MAX_UPLOAD_MB", "20")) * 1024 * 1024 + 64 * 1024 + 1024 * 1024 + if saved_chat + else ( + 12 * 1024 * 1024 + if path == "/api/questions" + else int(os.getenv("MANTIS_MAX_UPLOAD_MB", "20")) * 1024 * 1024 + + 64 * 1024 + ) ) headers = dict(scope["headers"]) length = headers.get(b"content-length") diff --git a/mantis/store.py b/mantis/store.py index 52ade2d..e28b006 100644 --- a/mantis/store.py +++ b/mantis/store.py @@ -4,6 +4,7 @@ import sqlite3 import uuid from contextlib import contextmanager +from datetime import datetime, timezone from pathlib import Path @@ -29,6 +30,11 @@ def __init__(self, path): page INTEGER NOT NULL, text TEXT NOT NULL, embedding TEXT NOT NULL); CREATE INDEX IF NOT EXISTS document_workspace ON documents(workspace); CREATE INDEX IF NOT EXISTS chunk_document ON chunks(document_id); + CREATE TABLE IF NOT EXISTS chats ( + id TEXT PRIMARY KEY, workspace TEXT NOT NULL, title TEXT NOT NULL, + document_id TEXT NOT NULL, demo INTEGER NOT NULL, messages TEXT NOT NULL, + revision INTEGER NOT NULL DEFAULT 1, updated TEXT NOT NULL); + CREATE INDEX IF NOT EXISTS chat_workspace ON chats(workspace,updated); """) @contextmanager @@ -137,3 +143,93 @@ def delete(self, workspace, identifier=None): return db.execute( "DELETE FROM documents WHERE workspace=?", (workspace,) ).rowcount + + def chats(self, workspace): + with self.connect() as db: + return [ + dict(row) + for row in db.execute( + "SELECT id,title,document_id,demo,revision,updated FROM chats WHERE workspace=? ORDER BY updated DESC,id", + (workspace,), + ) + ] + + @staticmethod + def _chat_record(row): + if not row: + return None + result = dict(row) + result.pop("workspace") + result["messages"] = json.loads(result["messages"]) + return result + + def chat(self, workspace, identifier): + with self.connect() as db: + row = db.execute( + "SELECT * FROM chats WHERE workspace=? AND id=?", + (workspace, identifier), + ).fetchone() + return self._chat_record(row) + + def save_chat(self, workspace, data, identifier=None): + title = data["messages"][0]["content"].strip().replace("\n", " ")[:80] + updated = datetime.now(timezone.utc).isoformat() + with self.connect() as db: + db.execute("BEGIN IMMEDIATE") + if identifier: + row = db.execute( + "SELECT revision,document_id,demo FROM chats WHERE workspace=? AND id=?", + (workspace, identifier), + ).fetchone() + if not row: + raise LookupError("Chat not found.") + if ( + row["document_id"] != data["document_id"] + or bool(row["demo"]) != data["demo"] + ): + raise ValueError( + "Changing manual or example mode requires a new chat." + ) + if row["revision"] != data["revision"]: + raise ValueError( + "This chat changed in another tab. Reopen it from Your chats before continuing." + ) + db.execute( + "UPDATE chats SET messages=?, revision=revision+1, updated=? WHERE workspace=? AND id=?", + (json.dumps(data["messages"]), updated, workspace, identifier), + ) + else: + if ( + db.execute( + "SELECT count(*) FROM chats WHERE workspace=?", (workspace,) + ).fetchone()[0] + >= 100 + ): + raise WorkspaceFullError( + "This workspace is limited to 100 chats. Delete a chat before saving another." + ) + identifier = uuid.uuid4().hex + db.execute( + "INSERT INTO chats(id,workspace,title,document_id,demo,messages,updated) VALUES(?,?,?,?,?,?,?)", + ( + identifier, + workspace, + title, + data["document_id"], + int(data["demo"]), + json.dumps(data["messages"]), + updated, + ), + ) + # Capture exactly the revision written here before another writer can run. + row = db.execute( + "SELECT * FROM chats WHERE workspace=? AND id=?", + (workspace, identifier), + ).fetchone() + return self._chat_record(row) + + def delete_chat(self, workspace, identifier): + with self.connect() as db: + return db.execute( + "DELETE FROM chats WHERE workspace=? AND id=?", (workspace, identifier) + ).rowcount diff --git a/mantis/web/assets/README.md b/mantis/web/assets/README.md index 7d2d3f0..d71c9bc 100644 --- a/mantis/web/assets/README.md +++ b/mantis/web/assets/README.md @@ -15,4 +15,4 @@ The product and workspace interfaces use self-hosted Inter and JetBrains Mono, w `demo-alarm.svg` is a code-drawn, illustrative alarm screen for the scripted example in the main chat. Its example labels are inspired by the user-supplied original Mantis recording; it is not a manufacturer interface or live reading. Personal example attachments are previewed locally, never uploaded or analyzed in example mode. Live-mode photos are sent to the configured provider. -The landing page preview is rendered directly in HTML/CSS, with the original brand assets. It does not use a screenshot or duplicate the app’s interactive controls. +The landing page preview is rendered directly in HTML/CSS, with the original brand assets. It does not use a screenshot. The landing examples share the app’s scripted scenario data, and their source notes expand on the same page. diff --git a/mantis/web/css/product.css b/mantis/web/css/product.css index 624fe62..8d2baae 100644 --- a/mantis/web/css/product.css +++ b/mantis/web/css/product.css @@ -1,7 +1,7 @@ @import url("./tokens.css"); :root { color-scheme: dark; - --orange: #ff8a35; + --orange: #ff781a; --muted: #9aa2b0; --mono: "JetBrains Mono", monospace; } @@ -10,7 +10,7 @@ } body { margin: 0; - background: #101114; + background: #121316; color: #f8fafc; font: 14px/1.7 Inter, @@ -23,7 +23,9 @@ a { color: inherit; text-decoration: none; } -a:focus-visible { +a:focus-visible, +button:focus-visible, +summary:focus-visible { outline: 2px solid var(--orange); outline-offset: 5px; } @@ -35,7 +37,7 @@ a:focus-visible { position: sticky; top: 0; z-index: 20; - background: #111215ed; + background: #121316ed; backdrop-filter: blur(18px); border-bottom: 1px solid #ffffff0c; } @@ -119,20 +121,9 @@ html { .hero { position: relative; overflow: hidden; - background: #0c0d10; + background: #0d0e11; text-align: center; } -.hero::before { - content: ""; - pointer-events: none; - position: absolute; - inset: 0; - background: radial-gradient( - ellipse 65% 65% at 50% -10%, - #ff79242b, - transparent 75% - ); -} .hero-inner { position: relative; min-height: calc(100svh - 88px); @@ -155,7 +146,7 @@ html { justify-content: center; gap: 10px; padding: 7px 12px; - background: #252429; + background: #232125; border: 1px solid #ffffff08; border-radius: 24px; color: #efaa76; @@ -178,8 +169,8 @@ html { margin: 0; } .hero h1 > span { - color: #ffba89; - background: linear-gradient(105deg, #ffddca 3%, #ffaf89 57%, #ffb754 100%); + color: #ffc19c; + background: linear-gradient(100deg, #f7dfd2, #ffb083 70%, #ffb95f); background-clip: text; -webkit-background-clip: text; -webkit-text-fill-color: transparent; @@ -187,12 +178,12 @@ html { .hero-description { font-size: 17px; line-height: 1.9; - color: #d4d9e1; + color: #d8c7bf; margin: 24px auto 27px; } .hero-description > span { font-size: 13px; - color: #939dab; + color: #97999f; } .hero-actions { display: flex; @@ -206,7 +197,7 @@ html { width: min(960px, 100%); padding: 22px 14px; margin-top: 40px; - background: #1b1c23; + background: #1b1c21; border: 1px solid #ffffff05; border-radius: 12px; } @@ -243,7 +234,7 @@ html { .how-section { padding: 90px 0 70px; border-bottom: 1px solid #ffffff06; - background: #111216; + background: #121316; } .section-heading { text-align: center; @@ -360,9 +351,6 @@ html { background: #090a0c; box-shadow: 0 24px 80px #0004; } -.app-preview:hover { - border-color: #ff8a3550; -} .preview-rail { display: flex; align-items: center; @@ -413,10 +401,16 @@ html { display: flex; flex-direction: column; gap: 22px; + height: 480px; + overflow-y: auto; + overscroll-behavior: contain; + scrollbar-width: thin; + scrollbar-color: #393c44 transparent; } .preview-user { align-self: flex-end; max-width: 78%; + flex-shrink: 0; } .preview-author { display: flex; @@ -437,6 +431,7 @@ html { } .preview-assistant { max-width: 78%; + flex-shrink: 0; } .tiny-mark { position: relative; @@ -460,45 +455,100 @@ html { font-size: 12px; line-height: 1.9; } -.preview-source { +.preview-answer > p, +.preview-user-bubble > p { + margin: 0; + white-space: pre-line; +} +.preview-suggestions { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 8px; + padding: 0 23px 18px; +} +.preview-suggestions button { display: flex; - justify-content: space-between; align-items: center; gap: 10px; + min-width: 0; + font: inherit; + font-size: 10px; + cursor: pointer; + text-align: left; + color: #b2bac5; + background: #17191d; + border: 1px solid #ffffff12; + padding: 12px; + min-height: 48px; + border-radius: 7px; +} +.preview-suggestions button > span:first-child { + color: #d0a27d; + font-size: 16px; +} +.preview-suggestions button > span:last-child { + margin-left: auto; + color: #939dab; +} +.preview-suggestions button:hover, +.preview-suggestions button:focus-visible { + color: #f0c8a9; + border-color: #ff8a3540; + background: #201b17; +} +.preview-source { border-top: 1px solid #ffffff10; margin-top: 15px; - padding-top: 12px; + padding-top: 10px; color: #a6c6d9; font-size: 10px; } +.preview-source summary { + cursor: pointer; + min-height: 28px; + padding: 3px 0; +} +.preview-source > p { + white-space: pre-line; + padding: 10px 0 0; + margin: 0; + font-size: 11px; + line-height: 1.9; + color: #b6c2ce; +} +.preview-source small { + display: block; + color: #8c98a6; + font-size: 9px; + margin-top: 10px; +} +.preview-photo { + display: block; + width: 250px; + max-width: 100%; + height: 150px; + object-fit: contain; + border-radius: 5px; + background: #111; + margin-bottom: 12px; +} .preview-bottom { display: flex; align-items: center; + justify-content: space-between; gap: 15px; color: #8c96a6; - padding: 12px 20px; - margin: 0 24px 20px; - background: #202228; - border: 1px solid #ffffff12; - border-radius: 9px; - font-size: 11px; + padding: 13px 23px; + border-top: 1px solid #ffffff0b; + font-size: 10px; } -.preview-bottom > span:first-child { - font-size: 24px; - color: #a6afbd; +.preview-open { + color: #ffb783; + font-size: 10px; + white-space: nowrap; } -.preview-send { - display: grid; - place-items: center; - width: 31px; - height: 31px; - font-size: 22px; - font-weight: 600; - background: var(--orange); - color: #211408; - border-radius: 5px; - margin-left: auto; - flex-shrink: 0; +[hidden] { + display: none !important; } .preview-caption { display: flex; @@ -652,6 +702,7 @@ html { font-size: 6px; } .preview-conversation { + height: 420px; padding: 21px 15px; gap: 18px; } @@ -667,10 +718,17 @@ html { .preview-source { font-size: 9px; } + .preview-suggestions { + grid-template-columns: minmax(0, 1fr); + padding: 0 14px 14px; + gap: 6px; + } + .preview-suggestions button { + font-size: 9px; + padding: 6px 8px; + } .preview-bottom { - margin: 0 12px 14px; - padding: 8px 10px; - gap: 10px; + padding: 12px 14px; font-size: 9px; } .preview-caption { diff --git a/mantis/web/css/tokens.css b/mantis/web/css/tokens.css index 11deee9..d122cbc 100644 --- a/mantis/web/css/tokens.css +++ b/mantis/web/css/tokens.css @@ -1,12 +1,12 @@ @font-face { font-family: Inter; - src: url("/static/assets/Inter-Variable.ttf") format("truetype"); + src: url("../assets/Inter-Variable.ttf") format("truetype"); font-weight: 100 900; font-display: swap; } @font-face { font-family: "JetBrains Mono"; - src: url("/static/assets/JetBrainsMono-Variable.ttf") format("truetype"); + src: url("../assets/JetBrainsMono-Variable.ttf") format("truetype"); font-weight: 100 800; font-display: swap; } diff --git a/mantis/web/css/workspace.css b/mantis/web/css/workspace.css index 683f33b..a2ec61a 100644 --- a/mantis/web/css/workspace.css +++ b/mantis/web/css/workspace.css @@ -61,7 +61,7 @@ button { .app-shell { height: 100dvh; display: grid; - grid-template-columns: 72px minmax(0, 1fr); + grid-template-columns: 56px minmax(0, 1fr); } .app-rail { display: flex; @@ -70,7 +70,7 @@ button { gap: 25px; padding: 25px 0 18px; border-right: 1px solid var(--line); - background: #101114; + background: #0c0c0c; } .brand-icon { position: relative; @@ -124,147 +124,90 @@ button { display: flex; flex-direction: column; } -.app-header { +.chat-toolbar { display: flex; - justify-content: space-between; align-items: center; + justify-content: space-between; gap: 15px; - padding: 19px 34px 16px; - border-bottom: 1px solid var(--line); + padding: 12px 28px 0; + min-height: 49px; } -.app-title { +.toolbar-context { display: flex; align-items: center; - gap: 10px; -} -.eyebrow { - font: 8px/1.7 var(--mono); - letter-spacing: 1.6px; - color: #9b9faa; - margin: 0 0 4px; -} -h1 { - font-size: 21px; - letter-spacing: -0.4px; - font-weight: 650; - margin: 0; -} -.status-dot { - display: inline-block; - vertical-align: middle; - width: 6px; - height: 6px; - background: #8f96a1; - border-radius: 50%; - margin-left: 5px; -} -.status-dot.connected { - background: #ff9b5a; + gap: 8px; + min-width: 0; } -.header-actions { +.toolbar-actions { display: flex; - gap: 10px; align-items: center; + gap: 8px; + flex-shrink: 0; +} +.eyebrow { + font: 8px/1.7 var(--mono); + letter-spacing: 1.2px; + color: #9096a1; + margin: 0 0 5px; } .primary-button, .quiet-button, -.example-button, .context-button { display: inline-flex; align-items: center; justify-content: center; - gap: 8px; - border-radius: 7px; - min-height: 37px; - padding: 8px 13px; + gap: 7px; + min-height: 32px; + padding: 6px 10px; + border-radius: 5px; + border: 1px solid #ffffff10; + background: transparent; + color: #aeb4bf; font-size: 11px; - border: 1px solid var(--line); - background: #1a1c21; } .primary-button { - color: #1b1008; - background: var(--orange); - border-color: var(--orange); - font-weight: 650; + background: #ff781a; + color: #201108; + border-color: #ff781a; + font-weight: 600; } .quiet-button { - background: transparent; - color: #b9bfca; + border-color: transparent; } .quiet-button:hover, .context-button:hover { - background: #1b1e24; -} -.primary-button:hover { - background: #ffa15c; -} -.context-bar { - display: flex; - align-items: center; - justify-content: space-between; - gap: 15px; - padding: 10px 34px; - background: #101114; - border-bottom: 1px solid #ffffff06; + background: #191919; + color: #f0c09c; } .context-button { - background: transparent; border: 0; - padding: 0; - max-width: 65%; - color: #b9bfca; + padding-left: 0; text-align: left; + max-width: 350px; + color: #7f8794; } .context-button #selected-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.context-actions { - display: flex; - align-items: center; - gap: 18px; -} -.connection-label { - font-size: 10px; - color: #8b929f; -} -.example-button { - font-size: 10px; - min-height: 30px; - padding: 5px 10px; - background: #ff8a350c; - border-color: #ff8a3526; - color: #ffb27c; - white-space: nowrap; -} .mode-banner { display: flex; align-items: center; - justify-content: center; - gap: 15px; + justify-content: flex-end; flex-wrap: wrap; - padding: 9px 20px; - background: #ff8a350b; - border-bottom: 1px solid #ff8a351a; -} -.mode-banner > span { - font: 8px var(--mono); - letter-spacing: 0.8px; - color: #ffb680; -} -.mode-banner p { - font-size: 10px; - color: #aba8a7; - margin: 0; + gap: 12px; + padding: 2px 38px 4px; + color: #88817a; + font-size: 9px; } .mode-banner button { - font-size: 10px; - border: 0; background: none; - color: #ffc090; - padding: 4px; - min-height: 28px; + border: 0; + padding: 4px 0; + min-height: 24px; + color: #c5a48b; + font-size: 9px; } .chat-scroll { flex: 1; @@ -276,53 +219,35 @@ h1 { padding: 32px 32px 18px; } .welcome { - max-width: 720px; - margin: clamp(15px, 7vh, 90px) auto 30px; + width: min(680px, 100%); + margin: clamp(15px, 10vh, 130px) auto 30px; text-align: center; } .welcome-mark { - width: 53px; - height: 63px; - margin: 0 auto 25px; -} -.welcome-mark img { - width: 136px; - left: -42px; - top: -23px; + margin: 0 auto 18px; } .welcome h2 { - font-size: clamp(27px, 3.2vw, 39px); - font-weight: 550; - letter-spacing: -1.4px; - margin: 8px 0 15px; -} -.welcome > p:not(.eyebrow) { - color: #9fa6b1; - font-size: 14px; -} -.welcome-actions { - display: flex; - justify-content: center; - gap: 10px; - margin-top: 28px; + font-size: 26px; + font-weight: 500; + letter-spacing: -0.8px; + margin: 8px 0 10px; } -.welcome-footnote { - font: 9px var(--mono) !important; - color: #6f7785 !important; - margin-top: 28px !important; +.welcome > p { + font-size: 12px; + color: #8b929e; + margin: 0 0 26px; } .mobile-brand { display: none; } #messages { - max-width: 900px; - margin: 0 auto; + width: 100%; display: flex; flex-direction: column; - gap: 26px; + gap: 25px; } .message { - max-width: min(82%, 740px); + max-width: min(70%, 680px); min-width: 0; flex-shrink: 0; } @@ -331,72 +256,72 @@ h1 { } .message.assistant { align-self: flex-start; + position: relative; + padding-left: 33px; + max-width: min(75%, 760px); } .message-header { - display: flex; - align-items: center; - gap: 5px; - font: 9px var(--mono); - letter-spacing: 0.7px; - color: #9199a7; - margin-bottom: 9px; + position: absolute; + left: 0; + top: 4px; +} +.user .message-header { + position: absolute; } .message-header img { - width: 32px; + width: 25px; height: 24px; object-fit: cover; } .message-body { - border: 1px solid #ffffff08; - background: #191b20; - color: #d5d8df; - border-radius: 3px 13px 13px; - padding: 16px 20px; + background: #161616; + border: 1px solid #ffffff04; + color: #d2d2d2; + border-radius: 8px; + padding: 14px 17px; font-size: 13px; - line-height: 1.9; + line-height: 1.8; white-space: pre-wrap; overflow-wrap: anywhere; } .user .message-body { - background: #ed7626; - border-color: #ffae6b30; - color: #170e08; - border-radius: 13px 3px 13px 13px; + background: #f07820; + color: #170f08; + border: 1px solid #ffb77722; + border-radius: 9px; } .message-photo { display: block; - max-width: 300px; - height: 190px; - max-height: 210px; - width: 100%; + width: 300px; + max-width: 100%; + height: 185px; object-fit: contain; - border-radius: 6px; - margin-bottom: 12px; - background: #0a0a0c; + background: #101010; + border-radius: 5px; + margin-bottom: 10px; } .answer-note { - color: #959daa; - font: 8px/1.8 var(--mono); - letter-spacing: 0.3px; - margin: 8px 0 0; + color: #a39c94; + font-size: 10px; + margin: 6px 0 0; } .citations { display: flex; flex-direction: column; - gap: 8px; - margin-top: 10px; + gap: 7px; + margin-top: 8px; } .source-details { - border: 1px solid #ffffff15; - background: #11161b; - border-radius: 7px; + border: 1px solid #ffffff0e; + background: #111; + border-radius: 6px; font-size: 11px; overflow: hidden; } .source-details summary { cursor: pointer; - padding: 9px 12px; - color: #a3c6da; + padding: 8px 11px; + color: #a8b9c3; overflow-wrap: anywhere; } .source-details .source-excerpt { @@ -405,128 +330,155 @@ h1 { overflow: auto; margin: 0; padding: 12px; - border-top: 1px solid #ffffff0c; - color: #bcc5cf; + border-top: 1px solid #ffffff0b; + color: #b8bec7; line-height: 1.9; } .source-details a, .source-details .source-note { display: block; - color: #9bcbe6; + color: #9ab5c4; padding: 0 12px 12px; font-size: 10px; } .source-details[open] { - border-color: #7bd0ff50; + border-color: #ffffff26; } .pending { - font: 11px var(--mono); - color: #ffb781; + font-size: 12px; + color: #cf8f58; letter-spacing: 3px; - padding: 10px 0; + padding: 6px 35px; } .composer-shell { width: 100%; - padding: 14px 32px 16px; - border-top: 1px solid #ffffff08; - background: linear-gradient(#101114, #0d0e11); + padding: 12px 32px 12px; + background: #101010; + border-top: 1px solid #ffffff05; } .composer-shell > * { - max-width: 900px; + max-width: 1040px; margin-left: auto; margin-right: auto; } +.composer-box { + border: 1px solid #ffffff0d; + border-radius: 7px; + background: #1b1b1b; + overflow: hidden; +} +.composer-box:focus-within { + border-color: #d07b3960; +} .composer { display: flex; align-items: flex-end; - gap: 12px; - border: 1px solid #ffffff18; - border-radius: 10px; - background: #202228; - padding: 9px; -} -.composer:focus-within { - border-color: #ff9b5a90; - box-shadow: 0 0 0 3px #ff781a0a; + gap: 10px; + padding: 7px; } .attach-button { border: 0; - border-right: 1px solid #ffffff15; - padding: 0 12px 0 6px; - min-height: 37px; + border-right: 1px solid #ffffff0b; background: none; - color: #b3bac7; - font-size: 25px; + color: #a19b91; + font-size: 23px; + min-height: 35px; + padding: 0 12px 0 7px; flex-shrink: 0; } .composer textarea { + flex: 1; border: 0; outline: none !important; background: none; - color: #f8fafc; resize: none; - flex: 1; - min-height: 37px; + color: #e6e6e6; + min-height: 35px; max-height: 130px; - padding: 8px 0; - font-size: 13px; - line-height: 1.65; field-sizing: content; + padding: 7px 0; + font-size: 12px; + line-height: 1.65; } .composer textarea::placeholder { - color: #8c95a3; + color: #797b7f; } .send-button { + min-width: 65px; + height: 34px; border: 0; - background: var(--orange); - color: #241407; - font-weight: 600; - font-size: 23px; - border-radius: 7px; - width: 39px; - height: 37px; + border-radius: 5px; + padding: 0 14px; + background: #f07820; + color: #211208; + font-size: 12px; + font-weight: 550; flex-shrink: 0; } -.composer-note { +.composer-meta { + display: flex; + align-items: center; + justify-content: space-between; + gap: 20px; + padding: 0 12px 7px; + margin: 0; +} +.manual-upload-action { + border: 0; + padding: 0; + min-height: 25px; + background: none; + color: #b7a08a; + white-space: nowrap; font-size: 10px; - color: #8b94a2; - margin-top: 9px; - margin-bottom: 0; +} +.manual-upload-action:hover { + color: #f3ba89; +} +.composer-note { + font-size: 11px; + line-height: 1.7; + color: #a3a9b3; + margin: 0; + text-align: right; } .suggestions { display: flex; - flex-wrap: wrap; gap: 7px; - margin-bottom: 12px; + overflow-x: auto; + scrollbar-width: thin; + margin-bottom: 10px; + padding-bottom: 2px; } .suggestions button { - border: 1px solid #ffffff15; - background: #1a1c21; - color: #b7bfcb; + flex-shrink: 0; + border: 1px solid #ffffff0f; + border-radius: 5px; + background: #181818; + color: #a8a9ae; + padding: 5px 9px; font-size: 10px; - padding: 6px 10px; - border-radius: 6px; - min-height: 32px; + min-height: 29px; } .suggestions button:hover { - border-color: #ff9b5a66; - color: #ffc090; + border-color: #d07b3944; + color: #edb88c; } .photo-tray { display: flex; align-items: center; - gap: 12px; - padding: 10px; - border: 1px solid var(--line); - border-radius: 8px; - margin-bottom: 12px; + gap: 10px; + padding: 8px; + border: 1px solid #ffffff0e; + border-radius: 6px; + margin-bottom: 10px; } .photo-tray img { - width: 52px; - height: 44px; + width: 49px; + height: 42px; object-fit: contain; - background: #222; - border-radius: 5px; + background: #171717; + border-radius: 4px; } .photo-tray div { min-width: 0; @@ -534,19 +486,19 @@ h1 { .photo-tray strong { display: block; font-size: 11px; + font-weight: 400; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .photo-tray small { display: block; - font-size: 10px; - color: #9ca4b0; + font-size: 9px; + color: #888b92; } .photo-tray button { margin-left: auto; - font-size: 21px; - padding: 2px 10px; + font-size: 22px; } dialog { background: #17191e; @@ -749,112 +701,108 @@ dialog input { .app-rail { display: none; } - .mobile-brand { - display: block; - } - .app-header { - padding: 14px 16px; - } - .app-title .eyebrow { - font-size: 6px; - letter-spacing: 1px; - } - h1 { - font-size: 18px; + .chat-toolbar { + padding: 10px 12px 2px; + min-height: 48px; + gap: 8px; } - .header-actions { - gap: 5px; + .toolbar-actions { + gap: 3px; } - .header-actions button { + .toolbar-actions button { font-size: 10px; - padding: 7px 9px; - gap: 5px; + padding: 5px 6px; } - .header-actions #new-chat span { + #new-chat span { display: none; } - .context-bar { - padding: 8px 16px; - gap: 7px; + .mobile-brand { + display: block; + width: 24px; + height: 30px; } - .connection-label { - display: none; + .mobile-brand img { + width: 62px; + left: -19px; + top: -10px; } .context-button { - max-width: 60%; + max-width: 150px; font-size: 10px; - min-height: 30px; - } - .example-button { - font-size: 9px; - padding: 4px 7px; + gap: 4px; } .mode-banner { - justify-content: flex-start; - gap: 2px 10px; - padding: 8px 16px; - } - .mode-banner p { - font-size: 9px; + padding: 0 18px 4px; + gap: 10px; + font-size: 8px; } .mode-banner button { - margin-left: auto; - font-size: 9px; + font-size: 8px; } .chat-scroll { - padding: 23px 16px 16px; + padding: 20px 13px 16px; } .welcome { margin: 5vh auto 25px; } .welcome h2 { - font-size: 28px; - letter-spacing: -1px; + font-size: 23px; } - .welcome > p:not(.eyebrow) { - font-size: 12px; - } - .welcome-actions { - gap: 7px; + .welcome > p { + font-size: 11px; + max-width: 280px; + margin: 0 auto 22px; } - .welcome-actions button { - font-size: 10px; + .message { + max-width: 87%; } - .welcome-footnote { - font-size: 8px !important; + .message.assistant { + max-width: 96%; + padding-left: 25px; } - .message { - max-width: 94%; + .message-header img { + width: 20px; + height: 21px; } .message-body { + padding: 12px 13px; font-size: 12px; - padding: 13px 15px; } .message-photo { - max-height: 170px; + height: 155px; } .composer-shell { - padding: 12px 12px 14px; + padding: 10px 10px 9px; } .composer { - gap: 8px; - padding: 7px; + gap: 7px; + padding: 6px; } .composer textarea { - font-size: 12px; + font-size: 11px; + } + .send-button { + min-width: 52px; + padding: 0 9px; + font-size: 11px; + } + .composer-meta { + gap: 8px; + padding: 0 10px 7px; + flex-wrap: wrap; } .composer-note { - font-size: 9px; + font-size: 10px; + max-width: 220px; } - .suggestions { - gap: 5px; + .manual-upload-action { + font-size: 9px; } .suggestions button { font-size: 9px; - padding: 5px 7px; } .photo-tray small { - font-size: 9px; + font-size: 8px; } dialog { padding: 20px; @@ -865,3 +813,34 @@ dialog input { scroll-behavior: auto !important; } } + +.rail-button svg { + width: 20px; + height: 20px; + fill: none; + stroke: currentColor; + stroke-width: 1.7; +} +.chats-dialog { + margin: 0 auto 0 0; +} +.mobile-chats { + display: none; +} +.photo-history-note { + font-size: 10px; + color: inherit; + opacity: 0.7; + margin: 0 0 9px; +} +#retry-save { + color: #ffc18b; +} +@media (max-width: 700px) { + .mobile-chats { + display: inline-flex; + } + .context-button { + max-width: 120px; + } +} diff --git a/mantis/web/js/chat-history.js b/mantis/web/js/chat-history.js new file mode 100644 index 0000000..a313fe7 --- /dev/null +++ b/mantis/web/js/chat-history.js @@ -0,0 +1,24 @@ +/** Whitelist saved transcript data; personal photo bytes never enter history. */ +export function archiveExchange(question, result, photo) { + return [ + { + role: "user", + content: question, + photo: photo ? (photo.sample ? "sample" : "omitted") : "", + }, + { + role: "assistant", + content: result.answer, + demo: Boolean(result.demo), + insufficient_evidence: Boolean(result.insufficient_evidence), + sources: (result.sources || []).map( + ({ document_id, name, page, text }) => ({ + document_id, + name, + page, + text, + }), + ), + }, + ]; +} diff --git a/mantis/web/js/conversation.js b/mantis/web/js/conversation.js index 8c09cec..ae47705 100644 --- a/mantis/web/js/conversation.js +++ b/mantis/web/js/conversation.js @@ -19,6 +19,14 @@ export function createConversation({ request }) { turns = []; busy = false; }, + restore(messages) { + generation += 1; + controller?.abort(); + turns = messages + .slice(-8) + .map(({ role, content }) => ({ role, content })); + busy = false; + }, async send({ question, documentId = "", diff --git a/mantis/web/js/examples.js b/mantis/web/js/examples.js index 20ec295..4b5aed9 100644 --- a/mantis/web/js/examples.js +++ b/mantis/web/js/examples.js @@ -1,4 +1,6 @@ export const DEMO_PROMPTS = { + vibration: "What should I check for excessive vibration?", + overheating: "What should I check for overheating?", spindle: "My CNC machine reports “spindle overload” and sounds louder than usual. What should I check first?", alarm: @@ -15,13 +17,19 @@ export function demoReply(question, attachmentKind = null) { if (attachmentKind === "sample") { return "This prepared example lists three alarm labels:\n\n01 / PLC 121 — Machine off\n02 / PLC 122 — Door / safety device\n03 / Battery voltage range\n\nWhat machine model and controller is this? Code meanings vary by equipment. Record the exact messages and when they appeared, then compare them with the matching manual before planning checks."; } + if (/overheat/i.test(question)) { + return "Overheating — illustrative training example.\n\nRecord the operating load, cooling conditions, and recent lubrication or maintenance history. Compare these observations with the actual manufacturer’s documentation.\n\nWhat machine model is this, and what exact temperature or alarm was recorded? This example does not specify operating limits or equipment service procedures."; + } + if (/vibrat/i.test(question) && !/spindle|overload/i.test(question)) { + return "Excessive vibration — illustrative training example.\n\nRecord when the vibration started, the operating conditions, and any recent setup changes. The matching manual is needed to identify approved checks and limits.\n\nDo you have the equipment model or an alarm message to include in the handover?"; + } if (/record|handover|handing|technician|log|zabele/i.test(question)) { return "Here’s a sample handover note to build on:\n\n• Equipment model and controller\n• Exact alarm code and message\n• Time of the event and operating conditions\n• Any unusual noise, vibration, or heat\n• Recent tool changes or maintenance\n• A photo of the screen, if your site permits it\n\nInclude what happened before the alarm. The maintenance team can then compare it with the correct manual and decide the next safe step."; } if (/spindle|overload|noise|vibrat|vreten|preoptere/i.test(question)) { return "Let’s start with the context, before assuming a cause.\n\nAn overload message and a change in sound are useful observations, but they don’t identify a fault on their own. Follow the site’s stop and isolation procedures if abnormal operation is suspected.\n\nFor the maintenance handover, capture:\n01 / The exact alarm and machine model\n02 / When the sound changed\n03 / The operation and tool in use\n04 / Any recent setup or maintenance changes\n\nDo you also have a photo of the alarm screen? You can try the sample photo below."; } - return "This is a scripted interaction preview, so I can’t diagnose that issue or search your manuals here.\n\nTry “Spindle overload”, “Try an alarm photo”, or “What should I record?” to explore the prepared conversation.\n\nTo ask questions about your own PDF manual, open the maintenance workspace. Live manual answers require a configured API key; switch out of the example to use live photo analysis with a configured AI service."; + return "This is a scripted interaction preview, so I can’t diagnose that issue or search your manuals here.\n\nTry “Spindle overload”, “Try an alarm photo”, or “What should I record?” to explore the prepared conversation.\n\nChoose “Upload your own manual” below to ask about your equipment documentation. Live manual answers require a configured API key; switch out of the example to use live photo analysis with a configured AI service."; } export function attachmentError(file) { @@ -36,13 +44,23 @@ export function attachmentError(file) { export function exampleResponse(question, kind = null) { const answer = demoReply(question, kind); const sources = - !kind && /spindle|overload|record|handover|vibrat/i.test(question) + !kind && /spindle|overload|record|handover|vibrat|overheat/i.test(question) ? [ { - name: "Illustrative CNC handover notes", + name: /overheat|vibrat/i.test(question) + ? "Illustrative training notes" + : "Illustrative CNC handover notes", document_id: "demo", - page: 1, - text: "Record the equipment model and controller, exact alarm message, operating conditions, unusual noise or vibration, and recent tool or maintenance changes. Compare observations with the correct manufacturer documentation. This is example material, not an equipment service procedure.", + page: /overheat/i.test(question) + ? 7 + : /vibrat/i.test(question) + ? 4 + : 1, + text: /overheat/i.test(question) + ? "Overheating — illustrative training notes. Record operating load, cooling conditions, lubrication and maintenance history, machine model, and the exact temperature or alarm. Compare observations with the actual manufacturer documentation. No operating limits or service procedures are specified here." + : /vibrat/i.test(question) + ? "Vibration — illustrative training notes. Record the equipment model, when vibration began, operating conditions, recent setup changes, and exact alarm messages. Use the matching manufacturer manual for approved checks and limits." + : "Record the equipment model and controller, exact alarm message, operating conditions, unusual noise or vibration, and recent tool or maintenance changes. Compare observations with the correct manufacturer documentation. This is example material, not an equipment service procedure.", }, ] : []; diff --git a/mantis/web/js/product-preview.js b/mantis/web/js/product-preview.js new file mode 100644 index 0000000..50e865b --- /dev/null +++ b/mantis/web/js/product-preview.js @@ -0,0 +1,57 @@ +import { DEMO_PROMPTS, exampleResponse } from "./examples.js"; + +const thread = document.getElementById("preview-thread"); +function node(tag, className, text) { + const item = document.createElement(tag); + if (className) item.className = className; + if (text !== undefined) item.textContent = text; + return item; +} +function addExample(key) { + const result = exampleResponse( + DEMO_PROMPTS[key], + key === "alarm" ? "sample" : null, + ); + const user = node("article", "preview-user"); + const userBubble = node("div", "preview-user-bubble"); + if (key === "alarm") { + const photo = node("img", "preview-photo"); + photo.src = "/static/assets/demo-alarm.svg"; + photo.alt = "Illustrative CNC alarm screen"; + userBubble.append(photo); + } + userBubble.append(node("p", "", DEMO_PROMPTS[key])); + user.append(node("span", "preview-author", "YOU"), userBubble); + + const assistant = node("article", "preview-assistant"); + const author = node("span", "preview-author"); + const mark = node("span", "tiny-mark"); + const logo = node("img"); + logo.src = "/static/assets/mantis-mark.png"; + logo.alt = ""; + mark.append(logo); + author.append(mark, node("span", "", "MANTIS")); + const bubble = node("div", "preview-answer"); + bubble.append(node("p", "", result.answer)); + for (const passage of result.sources) { + const details = node("details", "preview-source"); + details.append( + node("summary", "", `${passage.name} · p. ${passage.page}`), + node("p", "", passage.text), + node( + "small", + "", + "Illustrative example · not an equipment service procedure.", + ), + ); + bubble.append(details); + } + assistant.append(author, bubble); + // A single transcript: keep earlier questions, replies, and their own sources. + thread.append(user, assistant); + thread.scrollTop = thread.scrollHeight; +} +document.querySelectorAll("[data-example]").forEach((button) => { + button.addEventListener("click", () => addExample(button.dataset.example)); +}); +addExample("spindle"); diff --git a/mantis/web/js/workspace.js b/mantis/web/js/workspace.js index 8c36e07..0228c58 100644 --- a/mantis/web/js/workspace.js +++ b/mantis/web/js/workspace.js @@ -1,444 +1,733 @@ import { api } from "./api.js"; +import { archiveExchange } from "./chat-history.js"; import { attachmentError, DEMO_PROMPTS } from "./examples.js"; import { createConversation } from "./conversation.js"; -const $ = (id) => document.getElementById(id); -const chat = createConversation({ request: api }); -const state = { - documents: [], - selected: "", - demo: false, - configured: false, - uploading: false, - file: null, - photo: null, - photoGeneration: 0, - chatGeneration: 0, -}; -let toastTimer; -function element(tag, className, text) { - const node = document.createElement(tag); - if (className) node.className = className; - if (text !== undefined) node.textContent = text; - return node; -} -function toast(message) { - $("toast").textContent = message; - $("toast").hidden = false; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { - $("toast").hidden = true; - }, 6500); -} -function scrollChat() { - $("chat-scroll").scrollTop = $("chat-scroll").scrollHeight; -} -function lock() { - $("send-button").disabled = chat.busy || state.uploading; - $("attach-photo").disabled = state.uploading; - document.querySelectorAll("[data-prompt]").forEach((button) => { - button.disabled = chat.busy || state.uploading; - }); -} -function clearPhoto() { - state.photoGeneration += 1; - state.photo = null; - $("photo-tray").hidden = true; - $("photo-preview").removeAttribute("src"); - $("photo-input").value = ""; -} -function updateMode() { - const doc = state.documents.find((item) => item.id === state.selected); - $("selected-label").textContent = state.demo - ? "Sample CNC scenario" - : doc - ? doc.equipment || doc.name - : "Connect a manual"; - $("mode-banner").hidden = !state.demo; - $("suggestions").hidden = !state.demo; - $("demo-button").textContent = state.demo - ? "Exit example ↗" - : "Try an example ↗"; - $("photo-note").textContent = state.demo - ? "Local preview only · not analyzed in this example" - : "Sent to OpenAI when you send this message."; - $("composer-note").textContent = state.demo - ? "Scripted example · no AI calls. Attachments stay in your browser." - : !state.configured - ? "AI service isn’t configured. Try the example, or set OPENAI_API_KEY on the server." +export function mountWorkspace({ + root, + request, + confirmAction = (message) => root.defaultView.confirm(message), + schedule = setTimeout, + cancel = clearTimeout, +}) { + const location = root.defaultView.location; + const history = root.defaultView.history; + const confirm = confirmAction; + const $ = (id) => root.getElementById(id); + const chat = createConversation({ request }); + const state = { + documents: [], + chats: [], + transcript: [], + chatId: "", + chatRevision: 0, + saving: false, + unsaved: false, + missingManual: false, + selected: "", + demo: false, + configured: false, + uploading: false, + file: null, + photo: null, + photoGeneration: 0, + chatGeneration: 0, + }; + let toastTimer; + let historyRequest = 0; + function element(tag, className, text) { + const node = root.createElement(tag); + if (className) node.className = className; + if (text !== undefined) node.textContent = text; + return node; + } + function toast(message) { + $("toast").textContent = message; + $("toast").hidden = false; + cancel(toastTimer); + toastTimer = schedule(() => { + $("toast").hidden = true; + }, 6500); + } + function scrollChat() { + $("chat-scroll").scrollTop = $("chat-scroll").scrollHeight; + } + function lock() { + $("send-button").disabled = chat.busy || state.uploading || state.saving; + $("new-chat").disabled = state.uploading || state.saving; + $("retry-save").disabled = chat.busy || state.uploading || state.saving; + $("attach-photo").disabled = state.uploading; + root.querySelectorAll("[data-prompt]").forEach((button) => { + button.disabled = chat.busy || state.uploading || state.saving; + }); + } + function clearPhoto() { + state.photoGeneration += 1; + state.photo = null; + $("photo-tray").hidden = true; + $("photo-preview").removeAttribute("src"); + $("photo-input").value = ""; + } + function updateMode() { + const doc = state.documents.find((item) => item.id === state.selected); + $("selected-label").textContent = state.demo + ? "Example conversation" : doc - ? "Answers use this manual and recent text context. Verify citations. Photos are sent to OpenAI." - : "Attach a photo for observations, or upload a manual for source-backed answers. Sent to OpenAI."; -} -function resetChat() { - chat.reset(); - state.chatGeneration += 1; - $("messages").replaceChildren(); - $("welcome").hidden = false; - $("question").value = ""; - clearPhoto(); - lock(); -} -function choose(id, demo = false) { - if (state.uploading) return; - state.selected = id; - state.demo = demo; - const url = new URL(location.href); - url.hash = demo ? "demo" : ""; - history.replaceState(null, "", url); - resetChat(); - updateMode(); - renderDocuments(); - if ($("manuals-dialog").open) $("manuals-dialog").close(); -} -function addMessage(role, text, { result = null, photo = null } = {}) { - const node = element("article", "message " + role); - const header = element( - "div", - "message-header", - role === "user" ? "YOU" : "MANTIS", - ); - if (role === "assistant") { - const mark = element("img"); - mark.src = "/static/assets/mantis-mark.png"; - mark.alt = ""; - header.prepend(mark); + ? doc.equipment || doc.name + : "Your manuals"; + $("welcome-title").textContent = state.demo + ? "Choose a sample question below" + : doc + ? "Ask about your manual" + : "Upload a manual to start"; + $("upload-welcome").hidden = state.demo || Boolean(doc); + $("mode-banner").hidden = !state.demo; + $("suggestions").hidden = !state.demo; + $("demo-button").textContent = state.demo + ? "Exit example" + : "Try an example"; + $("photo-note").textContent = state.demo + ? "Local preview only · not analyzed in this example" + : "Sent to OpenAI when you send this message."; + $("composer-note").textContent = state.demo + ? "Scripted examples · no AI calls." + : !state.configured + ? "Live answers need a configured AI service. Try an example." + : doc + ? "Verify sources. Photos are sent to OpenAI." + : "Photos and questions are sent to OpenAI."; + if (state.missingManual) + $("composer-note").textContent = + "This chat’s manual was removed. Start a new chat or select another manual."; + } + function resetChat() { + chat.reset(); + state.transcript = []; + state.chatId = ""; + state.chatRevision = 0; + state.unsaved = false; + state.missingManual = false; + if ( + state.selected && + !state.documents.some((doc) => doc.id === state.selected) + ) + state.selected = ""; + $("retry-save").hidden = true; + state.chatGeneration += 1; + $("messages").replaceChildren(); + $("welcome").hidden = false; + $("question").value = ""; + clearPhoto(); + lock(); + updateMode(); } - const body = element("div", "message-body"); - if (photo) { - const image = element("img", "message-photo"); - image.src = photo.url; - image.alt = photo.sample - ? "Illustrative CNC alarm screen" - : "Attached equipment photo"; - body.append(image); + function choose(id, demo = false) { + if (state.uploading || state.saving) return false; + if (state.unsaved) { + toast("Use Retry save or start a new chat before changing manuals."); + return false; + } + state.selected = id; + state.demo = demo; + const url = new URL(location.href); + url.hash = demo ? "demo" : ""; + history.replaceState(null, "", url); + resetChat(); + updateMode(); + renderDocuments(); + if ($("manuals-dialog").open) $("manuals-dialog").close(); + return true; } - body.append(element("span", "", text)); - node.append(header, body); - if (result) { - if (result.demo || result.insufficient_evidence) - node.append( + function addMessage(role, text, { result = null, photo = null } = {}) { + const node = element("article", "message " + role); + const header = element("div", "message-header"); + header.append( + element("span", "sr-only", role === "user" ? "You" : "Mantis"), + ); + if (role === "assistant") { + const mark = element("img"); + mark.src = "/static/assets/mantis-mark.png"; + mark.alt = ""; + header.prepend(mark); + } + const body = element("div", "message-body"); + if (photo?.omitted) + body.append( element( "p", - "answer-note", - result.demo - ? "SCRIPTED EXAMPLE · ILLUSTRATIVE MATERIAL" - : "LIMITED MANUAL EVIDENCE · OBSERVATIONS ARE NOT A DIAGNOSIS", + "photo-history-note", + "Photo was attached · file not saved", ), ); - const citations = element("div", "citations"); - for (const source of result.sources || []) { - const detail = element("details", "source-details"); - detail.append( - element("summary", "", `${source.name} · p. ${source.page}`), - element("p", "source-excerpt", source.text), - ); - if (source.document_id !== "demo") { - const link = element( - "a", - "", - `Open original PDF · page ${source.page} ↗`, - ); - link.href = `/api/documents/${encodeURIComponent(source.document_id)}/file#page=${source.page}`; - link.target = "_blank"; - link.rel = "noopener"; - detail.append(link); - } else - detail.append( + else if (photo) { + const image = element("img", "message-photo"); + image.src = photo.url; + image.alt = photo.sample + ? "Illustrative CNC alarm screen" + : "Attached equipment photo"; + body.append(image); + } + body.append(element("span", "", text)); + node.append(header, body); + if (result) { + if (result.demo || result.insufficient_evidence) + node.append( element( "p", - "source-note", - "Illustrative example · not a service procedure", + "answer-note", + result.demo + ? "SCRIPTED EXAMPLE · ILLUSTRATIVE MATERIAL" + : "LIMITED MANUAL EVIDENCE · OBSERVATIONS ARE NOT A DIAGNOSIS", ), ); - citations.append(detail); + const citations = element("div", "citations"); + for (const source of result.sources || []) { + const detail = element("details", "source-details"); + detail.append( + element("summary", "", `${source.name} · p. ${source.page}`), + element("p", "source-excerpt", source.text), + ); + if (source.document_id !== "demo") { + const link = element( + "a", + "", + `Open original PDF · page ${source.page} ↗`, + ); + link.href = `/api/documents/${encodeURIComponent(source.document_id)}/file#page=${source.page}`; + link.target = "_blank"; + link.rel = "noopener"; + detail.append(link); + } else + detail.append( + element( + "p", + "source-note", + "Illustrative example · not a service procedure", + ), + ); + citations.append(detail); + } + node.append(citations); } - node.append(citations); + $("messages").append(node); + scrollChat(); + return node; } - $("messages").append(node); - scrollChat(); - return node; -} -function startExample() { - if (state.uploading) return; - choose("", true); - $("welcome").hidden = true; - addMessage( - "assistant", - "Hi, I’m Mantis. Let’s put the machine’s symptoms into context. This example follows a CNC maintenance conversation—try the spindle question, then the alarm photo.", - { result: { demo: true, sources: [] } }, - ); - $("question").value = DEMO_PROMPTS.spindle; - ask(); -} -async function ask(event, samplePhoto = false) { - event?.preventDefault(); - if (chat.busy || state.uploading) return; - const photo = samplePhoto - ? { sample: true, url: "/static/assets/demo-alarm.svg" } - : state.photo; - const question = - $("question").value.trim() || - (photo ? "Can you help me understand this equipment photo?" : ""); - if (question.length < 3) - return toast("Enter a question with at least three characters."); - if (!state.demo && !state.configured) - return toast( - "Set OPENAI_API_KEY on the server for live answers, or choose Try an example.", + function startExample(prompt = "spindle") { + if (state.uploading || state.saving || state.unsaved) return; + if (!choose("", true)) return; + $("welcome").hidden = true; + $("question").value = DEMO_PROMPTS[prompt]; + ask(null, prompt === "alarm"); + } + async function ask(event, samplePhoto = false) { + event?.preventDefault(); + if (chat.busy || state.uploading || state.saving) return; + if (state.missingManual) + return toast( + "This chat’s manual was removed. Select another manual to start a new conversation.", + ); + if (state.transcript.length >= 100) + return toast( + "This chat has reached 50 exchanges. Start a new chat to continue.", + ); + const photo = samplePhoto + ? { sample: true, url: "/static/assets/demo-alarm.svg" } + : state.photo; + const question = + $("question").value.trim() || + (photo ? "Can you help me understand this equipment photo?" : ""); + if (question.length < 3) + return toast("Enter a question with at least three characters."); + if (!state.demo && !state.configured) + return toast( + "Set OPENAI_API_KEY on the server for live answers, or choose Try an example.", + ); + if (!state.demo && !state.selected && !photo && !chat.history.length) + return toast("Upload a manual or attach a photo to start."); + const generation = state.chatGeneration; + $("welcome").hidden = true; + const sent = addMessage("user", question, { photo }); + $("question").value = ""; + clearPhoto(); + const pending = element( + "div", + "pending", + state.demo ? "•••" : "Reading context…", ); - if (!state.demo && !state.selected && !photo && !chat.history.length) - return toast("Upload a manual or attach a photo to start."); - const generation = state.chatGeneration; - $("welcome").hidden = true; - const sent = addMessage("user", question, { photo }); - $("question").value = ""; - clearPhoto(); - const pending = element( - "div", - "pending", - state.demo ? "•••" : "Reading context…", - ); - $("messages").append(pending); - scrollChat(); - try { - const promise = chat.send({ - question, - documentId: state.selected, - demo: state.demo, - image: photo && !photo.sample ? photo.url : null, - sample: Boolean(photo?.sample), - }); - lock(); - const result = await promise; - if (generation !== state.chatGeneration || !result) return; - pending.remove(); - addMessage("assistant", result.answer, { result }); - } catch (error) { - if (generation !== state.chatGeneration) return; - pending.remove(); - sent.remove(); - $("question").value = question; - if (photo && !photo.sample) { - state.photo = photo; - renderPhoto(); + $("messages").append(pending); + scrollChat(); + try { + const promise = chat.send({ + question, + documentId: state.selected, + demo: state.demo, + image: photo && !photo.sample ? photo.url : null, + sample: Boolean(photo?.sample), + }); + lock(); + const result = await promise; + if (generation !== state.chatGeneration || !result) return; + pending.remove(); + addMessage("assistant", result.answer, { result }); + state.transcript.push(...archiveExchange(question, result, photo)); + await saveActiveChat(); + } catch (error) { + if (generation !== state.chatGeneration) return; + pending.remove(); + sent.remove(); + $("question").value = question; + if (photo && !photo.sample) { + state.photo = photo; + renderPhoto(); + } + toast(error.message + " Your draft is ready to retry."); + } finally { + if (generation === state.chatGeneration) lock(); } - toast(error.message + " Your draft is ready to retry."); - } finally { - if (generation === state.chatGeneration) lock(); } -} -function renderPhoto() { - $("photo-preview").src = state.photo.url; - $("photo-name").textContent = state.photo.name; - $("photo-tray").hidden = false; -} -async function stagePhoto(file) { - if (!file) return; - const error = attachmentError(file); - if (error) return toast(error); - const generation = ++state.photoGeneration; - try { - const url = await new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onload = () => resolve(reader.result); - reader.onerror = () => reject(new Error("This photo could not be read.")); - reader.readAsDataURL(file); - }); - if (generation !== state.photoGeneration) return; - state.photo = { url, name: file.name }; - renderPhoto(); - $("question").focus(); - } catch (error) { - toast(error.message); + function renderPhoto() { + $("photo-preview").src = state.photo.url; + $("photo-name").textContent = state.photo.name; + $("photo-tray").hidden = false; } -} -function renderDocuments() { - $("manual-count").textContent = state.documents.length; - const list = $("manual-list"); - list.replaceChildren(); - const search = $("manual-search").value.toLowerCase(); - const docs = state.documents.filter((doc) => - `${doc.name} ${doc.equipment}`.toLowerCase().includes(search), - ); - if (!docs.length) - list.append( - element( - "p", - "manual-empty", - search - ? "No matching manuals." - : "Your manuals will appear here. Upload a PDF to connect your equipment knowledge.", - ), - ); - for (const doc of docs) { - const row = element( - "div", - "manual-row" + (doc.id === state.selected ? " selected" : ""), - ); - const select = element("button", "manual-choose"); - select.append( - element("strong", "", doc.name), - element( - "small", - "", - `${doc.equipment || "Equipment manual"} · ${doc.pages} ${doc.pages === 1 ? "page" : "pages"}`, - ), + async function stagePhoto(file) { + if (!file) return; + const error = attachmentError(file); + if (error) return toast(error); + const generation = ++state.photoGeneration; + try { + const url = await new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(reader.result); + reader.onerror = () => + reject(new Error("This photo could not be read.")); + reader.readAsDataURL(file); + }); + if (generation !== state.photoGeneration) return; + state.photo = { url, name: file.name }; + renderPhoto(); + $("question").focus(); + } catch (error) { + toast(error.message); + } + } + function renderDocuments() { + $("manual-count").textContent = state.documents.length; + const list = $("manual-list"); + list.replaceChildren(); + const search = $("manual-search").value.toLowerCase(); + const docs = state.documents.filter((doc) => + `${doc.name} ${doc.equipment}`.toLowerCase().includes(search), ); - select.addEventListener("click", () => choose(doc.id)); - const remove = element("button", "manual-delete", "Delete"); - remove.setAttribute("aria-label", `Delete ${doc.name}`); - remove.addEventListener("click", async () => { - if (chat.busy || state.uploading) - return toast("Wait for the current request to finish."); - if (!confirm(`Delete “${doc.name}” and its searchable passages?`)) return; - remove.disabled = true; - try { - await api(`/documents/${encodeURIComponent(doc.id)}`, { - method: "DELETE", - }); - if (state.selected === doc.id) choose(""); - await refresh(); - toast("Manual and its index deleted."); - } catch (error) { - toast(error.message); - remove.disabled = false; + if (!docs.length) + list.append( + element( + "p", + "manual-empty", + search + ? "No matching manuals." + : "Your manuals will appear here. Upload a PDF to connect your equipment knowledge.", + ), + ); + for (const doc of docs) { + const row = element( + "div", + "manual-row" + (doc.id === state.selected ? " selected" : ""), + ); + const select = element("button", "manual-choose"); + select.append( + element("strong", "", doc.name), + element( + "small", + "", + `${doc.equipment || "Equipment manual"} · ${doc.pages} ${doc.pages === 1 ? "page" : "pages"}`, + ), + ); + select.addEventListener("click", () => choose(doc.id)); + const remove = element("button", "manual-delete", "Delete"); + remove.setAttribute("aria-label", `Delete ${doc.name}`); + remove.addEventListener("click", async () => { + if (chat.busy || state.uploading || state.saving || state.unsaved) + return toast( + "Save or discard the current conversation before deleting a manual.", + ); + if (!confirm(`Delete “${doc.name}” and its searchable passages?`)) + return; + remove.disabled = true; + try { + await request(`/documents/${encodeURIComponent(doc.id)}`, { + method: "DELETE", + }); + if (state.selected === doc.id && !choose("")) { + state.missingManual = true; + } + await refresh(); + toast("Manual and its index deleted."); + } catch (error) { + toast(error.message); + remove.disabled = false; + } + }); + row.append(select, remove); + list.append(row); + } + } + async function refresh() { + state.documents = (await request("/documents")).documents; + if ( + state.selected && + !state.documents.some((doc) => doc.id === state.selected) + ) { + // Keep an existing transcript tied to its original manual until it is reset. + if ( + state.transcript.length || + state.chatId || + state.saving || + state.unsaved + ) + state.missingManual = true; + else state.selected = ""; + } + renderDocuments(); + updateMode(); + } + function pickManual() { + if (state.uploading || chat.busy || state.saving || state.unsaved) + return toast( + "Save or discard the current conversation before uploading a manual.", + ); + $("file-input").click(); + } + function stageManual(file) { + if (!file) return; + if (state.uploading || chat.busy || state.saving || state.unsaved) + return toast( + "Save or discard the current conversation before uploading a manual.", + ); + if (!file.name.toLowerCase().endsWith(".pdf")) + return toast("Choose a PDF manual."); + if (file.size > 20 * 1024 * 1024) + return toast("Choose a PDF smaller than 20 MB."); + if ($("manuals-dialog").open) $("manuals-dialog").close(); + state.file = file; + $("upload-filename").textContent = file.name; + $("equipment").value = ""; + $("upload-progress").textContent = state.configured + ? "" + : "AI indexing needs OPENAI_API_KEY configured on the server."; + $("upload-dialog").showModal(); + } + async function upload(event) { + event.preventDefault(); + if ( + !state.file || + state.uploading || + chat.busy || + state.saving || + state.unsaved + ) + return; + state.uploading = true; + lock(); + $("confirm-upload").disabled = true; + $("close-upload").disabled = true; + $("upload-progress").textContent = "Reading and indexing the manual…"; + const data = new FormData(); + data.append("file", state.file); + data.append("equipment", $("equipment").value.trim()); + try { + const result = await request("/documents", { + method: "POST", + body: data, + }); + await refresh(); + state.uploading = false; + if (!choose(result.document.id)) { + $("upload-progress").textContent = + "Manual uploaded, but this conversation was kept. Select it from Your manuals after saving or discarding this chat."; + return; } - }); - row.append(select, remove); - list.append(row); + $("upload-dialog").close(); + toast( + result.duplicate + ? "Manual already connected. Ready to ask." + : "Manual connected. Ask your first question.", + ); + } catch (error) { + $("upload-progress").textContent = error.message; + } finally { + state.uploading = false; + lock(); + $("confirm-upload").disabled = false; + $("close-upload").disabled = false; + $("file-input").value = ""; + } } -} -async function refresh() { - state.documents = (await api("/documents")).documents; - if ( - state.selected && - !state.documents.some((doc) => doc.id === state.selected) - ) - state.selected = ""; - renderDocuments(); - updateMode(); -} -function pickManual() { - if (state.uploading || chat.busy) - return toast("Wait for the current request to finish."); - $("file-input").click(); -} -function stageManual(file) { - if (!file) return; - if (!file.name.toLowerCase().endsWith(".pdf")) - return toast("Choose a PDF manual."); - if (file.size > 20 * 1024 * 1024) - return toast("Choose a PDF smaller than 20 MB."); - if ($("manuals-dialog").open) $("manuals-dialog").close(); - state.file = file; - $("upload-filename").textContent = file.name; - $("equipment").value = ""; - $("upload-progress").textContent = state.configured - ? "" - : "AI indexing needs OPENAI_API_KEY configured on the server."; - $("upload-dialog").showModal(); -} -async function upload(event) { - event.preventDefault(); - if (!state.file || state.uploading || chat.busy) return; - state.uploading = true; - lock(); - $("confirm-upload").disabled = true; - $("close-upload").disabled = true; - $("upload-progress").textContent = "Reading and indexing the manual…"; - const data = new FormData(); - data.append("file", state.file); - data.append("equipment", $("equipment").value.trim()); - try { - const result = await api("/documents", { method: "POST", body: data }); - await refresh(); - state.uploading = false; - choose(result.document.id); - $("upload-dialog").close(); - toast( - result.duplicate - ? "Manual already connected. Ready to ask." - : "Manual connected. Ask your first question.", - ); - } catch (error) { - $("upload-progress").textContent = error.message; - } finally { - state.uploading = false; + async function saveActiveChat() { + if ( + !state.transcript.length || + chat.busy || + state.uploading || + state.saving + ) + return; + state.saving = true; lock(); - $("confirm-upload").disabled = false; - $("close-upload").disabled = false; - $("file-input").value = ""; + const generation = state.chatGeneration; + try { + const response = await request( + state.chatId ? `/chats/${encodeURIComponent(state.chatId)}` : "/chats", + { + method: state.chatId ? "PUT" : "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + document_id: state.selected, + demo: state.demo, + revision: state.chatRevision, + messages: state.transcript, + }), + }, + ); + if (generation !== state.chatGeneration) return; + state.chatId = response.chat.id; + state.chatRevision = response.chat.revision; + state.unsaved = false; + $("retry-save").hidden = true; + } catch (error) { + if (generation === state.chatGeneration) { + state.unsaved = true; + $("retry-save").hidden = false; + toast(`Chat could not be saved: ${error.message} Use Retry save.`); + } + } finally { + state.saving = false; + lock(); + } } -} -$("question-form").addEventListener("submit", ask); -$("question").addEventListener("keydown", (event) => { - if (event.key === "Enter" && !event.shiftKey && !event.isComposing) { - event.preventDefault(); - ask(); + function newChat() { + if (state.uploading || state.saving) return; + if ( + state.unsaved && + !confirm( + "This conversation has unsaved messages. Discard them and start a new chat?", + ) + ) + return false; + resetChat(); + if ($("chats-dialog").open) $("chats-dialog").close(); + return true; } -}); -$("new-chat").addEventListener("click", () => { - if (!state.uploading) resetChat(); -}); -$("demo-button").addEventListener("click", () => - state.demo ? choose("") : startExample(), -); -$("example-welcome").addEventListener("click", startExample); -$("exit-demo").addEventListener("click", () => { - choose(""); - $("manuals-dialog").showModal(); -}); -document.querySelectorAll("[data-prompt]").forEach((button) => - button.addEventListener("click", () => { - $("question").value = DEMO_PROMPTS[button.dataset.prompt]; - ask(null, button.dataset.prompt === "alarm"); - }), -); -["manuals-rail", "manuals-button"].forEach((id) => - $(id).addEventListener("click", () => $("manuals-dialog").showModal()), -); -$("close-manuals").addEventListener("click", () => $("manuals-dialog").close()); -$("manual-search").addEventListener("input", renderDocuments); -["upload-header", "upload-welcome", "upload-drawer"].forEach((id) => - $(id).addEventListener("click", pickManual), -); -$("file-input").addEventListener("change", (event) => { - const file = event.target.files[0]; - event.target.value = ""; - stageManual(file); -}); -$("upload-form").addEventListener("submit", upload); -$("close-upload").addEventListener("click", () => $("upload-dialog").close()); -$("upload-dialog").addEventListener("cancel", (event) => { - if (state.uploading) event.preventDefault(); -}); -$("attach-photo").addEventListener("click", () => $("photo-input").click()); -$("photo-input").addEventListener("change", (event) => { - const file = event.target.files[0]; - event.target.value = ""; - stagePhoto(file); -}); -$("remove-photo").addEventListener("click", clearPhoto); -$("help-button").addEventListener("click", () => $("help-dialog").showModal()); -$("close-help").addEventListener("click", () => $("help-dialog").close()); -window.addEventListener("pagehide", resetChat); -(async () => { - try { - const health = await api("/health"); - state.configured = health.configured; - $("connection-dot").classList.toggle("connected", health.configured); - $("connection-label").textContent = health.configured - ? "AI service configured" - : "Example ready · AI not configured"; - await refresh(); - if (location.hash === "#demo") startExample(); - } catch (error) { - $("connection-label").textContent = "Server unavailable"; - toast(error.message); + async function openSavedChat(id) { + if (state.uploading || state.saving) + return toast("Wait for the current chat to finish saving."); + const discardUnsaved = state.unsaved; + if ( + discardUnsaved && + !confirm( + "This chat has unsaved messages. Reopen the saved conversation and discard those unsaved changes?", + ) + ) + return; + const current = ++historyRequest; + const generation = state.chatGeneration; + try { + const { chat: saved } = await request(`/chats/${encodeURIComponent(id)}`); + if (current !== historyRequest || generation !== state.chatGeneration) + return; + if (state.saving || state.uploading || (state.unsaved && !discardUnsaved)) + return toast("Wait for this chat to finish saving before switching."); + state.unsaved = false; + if (!choose(saved.document_id, Boolean(saved.demo))) return; + state.selected = saved.document_id; + state.chatId = saved.id; + state.chatRevision = saved.revision; + state.transcript = saved.messages; + chat.restore(saved.messages); + for (const message of saved.messages) { + const photo = + message.photo === "sample" + ? { sample: true, url: "/static/assets/demo-alarm.svg" } + : message.photo === "omitted" + ? { omitted: true } + : null; + addMessage(message.role, message.content, { + photo, + result: + message.role === "assistant" + ? { ...message, answer: message.content } + : null, + }); + } + $("welcome").hidden = true; + state.missingManual = + !saved.demo && + Boolean(saved.document_id) && + !state.documents.some((doc) => doc.id === saved.document_id); + if (state.missingManual) + $("composer-note").textContent = + "This chat’s manual was removed. Choose another manual to start a new chat."; + $("chats-dialog").close(); + } catch (error) { + toast(error.message); + } } -})(); + async function loadChats() { + $("chat-list").replaceChildren( + element("p", "manual-empty", "Loading chats…"), + ); + try { + state.chats = (await request("/chats")).chats; + const list = $("chat-list"); + list.replaceChildren(); + if (!state.chats.length) + list.append( + element( + "p", + "manual-empty", + "Your conversations will appear here after an answer.", + ), + ); + for (const saved of state.chats) { + const row = element( + "div", + "manual-row" + (saved.id === state.chatId ? " selected" : ""), + ); + const open = element("button", "manual-choose"); + const doc = state.documents.find( + (item) => item.id === saved.document_id, + ); + open.append( + element("strong", "", saved.title), + element( + "small", + "", + `${saved.demo ? "Example" : doc?.equipment || doc?.name || "Conversation"} · ${new Date(saved.updated).toLocaleDateString()}`, + ), + ); + open.addEventListener("click", () => openSavedChat(saved.id)); + const remove = element("button", "manual-delete", "Delete"); + remove.setAttribute("aria-label", `Delete chat ${saved.title}`); + remove.addEventListener("click", async () => { + if (chat.busy || state.saving || state.uploading) + return toast("Wait for the current request to finish."); + if (!confirm(`Delete the saved chat “${saved.title}”?`)) return; + remove.disabled = true; + try { + await request(`/chats/${encodeURIComponent(saved.id)}`, { + method: "DELETE", + }); + if (state.chatId === saved.id) resetChat(); + await loadChats(); + } catch (error) { + toast(error.message); + remove.disabled = false; + } + }); + row.append(open, remove); + list.append(row); + } + } catch (error) { + $("chat-list").replaceChildren( + element("p", "manual-empty", error.message), + ); + } + } + ["chats-rail", "chats-mobile"].forEach((id) => + $(id).addEventListener("click", () => { + $("chats-dialog").showModal(); + loadChats(); + }), + ); + $("close-chats").addEventListener("click", () => $("chats-dialog").close()); + $("drawer-new-chat").addEventListener("click", newChat); + $("retry-save").addEventListener("click", saveActiveChat); + $("question-form").addEventListener("submit", ask); + $("question").addEventListener("keydown", (event) => { + if (event.key === "Enter" && !event.shiftKey && !event.isComposing) { + event.preventDefault(); + ask(); + } + }); + $("new-chat").addEventListener("click", newChat); + $("demo-button").addEventListener("click", () => + state.demo ? choose("") : startExample(), + ); + $("exit-demo").addEventListener("click", () => { + if (choose("")) $("manuals-dialog").showModal(); + }); + root.querySelectorAll("[data-prompt]").forEach((button) => + button.addEventListener("click", () => { + $("question").value = DEMO_PROMPTS[button.dataset.prompt]; + ask(null, button.dataset.prompt === "alarm"); + }), + ); + $("manuals-button").addEventListener("click", () => + $("manuals-dialog").showModal(), + ); + $("close-manuals").addEventListener("click", () => + $("manuals-dialog").close(), + ); + $("manual-search").addEventListener("input", renderDocuments); + ["upload-header", "upload-welcome", "upload-drawer"].forEach((id) => + $(id).addEventListener("click", pickManual), + ); + $("file-input").addEventListener("change", (event) => { + const file = event.target.files[0]; + event.target.value = ""; + stageManual(file); + }); + $("upload-form").addEventListener("submit", upload); + $("close-upload").addEventListener("click", () => $("upload-dialog").close()); + $("upload-dialog").addEventListener("cancel", (event) => { + if (state.uploading) event.preventDefault(); + }); + $("attach-photo").addEventListener("click", () => $("photo-input").click()); + $("photo-input").addEventListener("change", (event) => { + const file = event.target.files[0]; + event.target.value = ""; + stagePhoto(file); + }); + $("remove-photo").addEventListener("click", clearPhoto); + $("help-button").addEventListener("click", () => + $("help-dialog").showModal(), + ); + $("close-help").addEventListener("click", () => $("help-dialog").close()); + root.defaultView.addEventListener("pagehide", resetChat); + const ready = (async () => { + try { + const health = await request("/health"); + state.configured = health.configured; + $("connection-dot").classList.toggle("connected", health.configured); + $("connection-label").textContent = health.configured + ? "AI service configured" + : "Example ready · AI not configured"; + await refresh(); + if (location.hash === "#demo") startExample(); + } catch (error) { + $("connection-label").textContent = "Server unavailable"; + toast(error.message); + } + })(); -$("help-drawer").addEventListener("click", () => { - $("manuals-dialog").close(); - $("help-dialog").showModal(); -}); + $("help-drawer").addEventListener("click", () => { + $("manuals-dialog").close(); + $("help-dialog").showModal(); + }); + + return { + ready, + choose, + newChat, + refresh, + ask, + upload, + saveActiveChat, + openSavedChat, + get state() { + return { ...state, transcript: [...state.transcript] }; + }, + }; +} +if (typeof document !== "undefined") + mountWorkspace({ root: document, request: api }); diff --git a/mantis/web/pages/index.html b/mantis/web/pages/index.html index 5e259bc..31bf3fc 100644 --- a/mantis/web/pages/index.html +++ b/mantis/web/pages/index.html @@ -11,6 +11,7 @@ Mantis — Your maintenance co-pilot + @@ -50,7 +51,7 @@

MAINTENANCE
ON AUTOPILOT.

Open Mantis Try an example
@@ -132,11 +133,7 @@

question and the supporting information together.

- +
- - +

- A preview of the flow. Try the example in the same app you’ll use - for your own equipment. + Explore these examples here. Click the source notes to expand them + on this page.

- Try it yourself ↗ + Use your own manual ↗

Examples work without a key. Live manual answers and photo analysis diff --git a/mantis/web/pages/workspace.html b/mantis/web/pages/workspace.html index 0d46a0b..476b924 100644 --- a/mantis/web/pages/workspace.html +++ b/mantis/web/pages/workspace.html @@ -22,12 +22,14 @@ /> -

- + Connecting…
-
- -
- Connecting… -
-
-

THE NEXT STEP STARTS WITH CONTEXT

-

What are we working on?

-

- Describe the symptom. Show the alarm.
Bring the right manual - into the conversation. -

-
- -
-

- PDF manuals · equipment photos · page-level sources -

+

Upload a manual to start

+
What are we working on?

× -
- - - -
-

- Add a PDF manual or a photo to get started. Live answers require an - API key. -

+
+
+ + + +
+
+ +

+ Live answers require an API key. +

+
+
@@ -180,6 +180,31 @@

What are we working on?

accept="image/jpeg,image/png,image/webp" hidden /> + +
+
+

PICK UP WHERE YOU LEFT OFF

+

Your chats

+
+ +
+ +

+ Previous conversations from this browser workspace. +

+
+

+ Conversation text and sources are saved on this server. Photo files are + not saved. Deleting a manual does not delete its chats; delete those + here if needed. +

+

Manuals are stored on this server, scoped to your browser cookie. - Clearing cookies loses access. Conversations and photos aren’t saved by - Mantis. + Clearing cookies loses access. Conversation text is saved on this + server; photo files are not saved.

@@ -268,8 +293,9 @@

One conversation. Better context.

Recent text turns provide follow-up context. Photos are analyzed only when attached to the current message; attach them again if needed. - Photos and conversations aren’t saved by Mantis. AI service processing - policies still apply. + Conversation text and sources are saved in Your chats on this server. + Photo files are not saved; only the text observations remain. AI service + processing policies still apply.

Try an example uses scripted replies and a clearly labeled sample alarm diff --git a/scripts/check_package.py b/scripts/check_package.py index 14722d6..3c274b8 100644 --- a/scripts/check_package.py +++ b/scripts/check_package.py @@ -40,7 +40,9 @@ def main(): "/static/js/api.js", "/static/js/workspace.js", "/static/js/conversation.js", + "/static/js/chat-history.js", "/static/js/examples.js", + "/static/js/product-preview.js", "/static/assets/mantis-mark.png", "/static/assets/demo-alarm.svg", "/static/assets/Inter-Variable.ttf", @@ -55,7 +57,26 @@ def main(): ) assert result.status_code == 200 assert result.json()["sources"] - print("Built wheel serves both pages, local assets, and the demo API.") + saved = client.post( + "/api/chats", + json={ + "demo": True, + "messages": [ + {"role": "user", "content": "Example question"}, + { + "role": "assistant", + "content": "Example answer", + "demo": True, + }, + ], + }, + ) + assert saved.status_code == 201 + identifier = saved.json()["chat"]["id"] + assert client.get(f"/api/chats/{identifier}").status_code == 200 + print( + "Built wheel serves both pages, local assets, demo API, and chat history." + ) if __name__ == "__main__": diff --git a/tests/frontend/conversation.test.mjs b/tests/frontend/conversation.test.mjs index 73f2a0d..912078f 100644 --- a/tests/frontend/conversation.test.mjs +++ b/tests/frontend/conversation.test.mjs @@ -1,5 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; +import { archiveExchange } from "../../mantis/web/js/chat-history.js"; import { createConversation } from "../../mantis/web/js/conversation.js"; import { attachmentError, @@ -179,3 +180,64 @@ test("repeated send while busy does not duplicate the provider call", async () = await first; assert.equal(count, 1); }); + +test("restored sample questions have matching illustrative answers and sources", () => { + const hot = exampleResponse("What should I check for overheating?"); + assert.match(hot.answer, /Overheating/); + assert.match(hot.sources[0].text, /cooling/); + assert.equal(hot.sources[0].page, 7); + const vibration = exampleResponse( + "What should I check for excessive vibration?", + ); + assert.match(vibration.answer, /Excessive vibration/); + assert.doesNotMatch(vibration.answer, /overload message/); + assert.equal(vibration.sources[0].page, 4); +}); + +test("saved exchanges omit personal photo bytes and unrecognized source fields", () => { + const messages = archiveExchange( + "Read this", + { + answer: "Visible alarm", + demo: false, + insufficient_evidence: true, + sources: [ + { + document_id: "one", + name: "Manual", + page: 1, + text: "Evidence", + image: "private", + }, + ], + }, + { url: "data:image/png;base64,private" }, + ); + assert.equal(messages[0].photo, "omitted"); + assert.equal(JSON.stringify(messages).includes("private"), false); + assert.equal(messages[1].sources[0].text, "Evidence"); +}); + +test("reopening a chat restores bounded context and invalidates an old reply", async () => { + const pending = deferred(); + const calls = []; + const chat = createConversation({ + request: async (_, options) => { + calls.push(JSON.parse(options.body)); + return calls.length === 1 ? pending.promise : answer("new"); + }, + }); + const old = chat.send({ question: "old pending" }); + const transcript = Array.from({ length: 12 }, (_, index) => ({ + role: index % 2 ? "assistant" : "user", + content: `saved ${index}`, + sources: [], + })); + chat.restore(transcript); + pending.resolve(answer("old reply")); + assert.equal(await old, null); + assert.equal(chat.history.length, 8); + await chat.send({ question: "follow up", documentId: "restored-manual" }); + assert.equal(calls[1].history[0].content, "saved 4"); + assert.equal(calls[1].document_id, "restored-manual"); +}); diff --git a/tests/frontend/workspace.test.mjs b/tests/frontend/workspace.test.mjs new file mode 100644 index 0000000..eb62e3e --- /dev/null +++ b/tests/frontend/workspace.test.mjs @@ -0,0 +1,233 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import { mountWorkspace } from "../../mantis/web/js/workspace.js"; + +class Element { + children = []; + handlers = {}; + attributes = {}; + value = ""; + hidden = false; + disabled = false; + open = false; + classList = { toggle() {} }; + append(...nodes) { + this.children.push(...nodes); + } + prepend(...nodes) { + this.children.unshift(...nodes); + } + replaceChildren(...nodes) { + this.children = nodes; + } + remove() {} + setAttribute(key, value) { + this.attributes[key] = value; + } + removeAttribute(key) { + delete this.attributes[key]; + } + addEventListener(key, fn) { + this.handlers[key] = fn; + } + showModal() { + this.open = true; + } + close() { + this.open = false; + } + focus() {} + click() { + if (!this.disabled) return this.handlers.click?.(); + } +} +const manual = { id: "manual", name: "manual.pdf", equipment: "CNC", pages: 1 }; +const result = { answer: "Answer", sources: [] }; +function deferred() { + let resolve; + const promise = new Promise((r) => { + resolve = r; + }); + return { promise, resolve }; +} +async function setup( + handler = () => undefined, + documents = [manual], + confirmAction = () => true, +) { + const html = readFileSync( + new URL("../../mantis/web/pages/workspace.html", import.meta.url), + "utf8", + ); + const nodes = Object.fromEntries( + [...html.matchAll(/id="([^"]+)"/g)].map(([, id]) => [id, new Element()]), + ); + const calls = []; + const root = { + getElementById: (id) => nodes[id], + createElement: () => new Element(), + querySelectorAll: () => [], + defaultView: { + location: { href: "http://localhost/workspace", hash: "" }, + history: { replaceState() {} }, + addEventListener() {}, + }, + }; + const app = mountWorkspace({ + root, + confirmAction, + schedule: () => 0, + cancel() {}, + request: async (path, options = {}) => { + calls.push({ path, ...options }); + const override = handler(path, options); + if (override !== undefined) return override; + if (path === "/health") return { configured: true }; + if (path === "/documents") return { documents }; + if (path === "/questions") return result; + if (path.startsWith("/chats")) + return { chat: { id: "chat", revision: 1 } }; + throw new Error(`Unexpected ${path}`); + }, + }); + await app.ready; + return { app, nodes, calls, documents }; +} +async function ask(ctx) { + ctx.nodes.question.value = "What should I record?"; + await ctx.app.ask(); +} +function deleteButton(nodes) { + return nodes["manual-list"].children[0].children[1]; +} + +test("manual deletion and upload switches are blocked during pending or failed saves", async () => { + const save = deferred(); + const ctx = await setup((path) => + path === "/chats" ? save.promise : undefined, + ); + ctx.app.choose(manual.id); + const asking = ask(ctx); + // Let the answer start its save. + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); + assert.equal(ctx.app.state.saving, true); + await deleteButton(ctx.nodes).click(); + assert.equal(ctx.app.choose("", true), false); + save.resolve(Promise.reject(new Error("Save failed"))); + await asking; + assert.equal(ctx.app.state.unsaved, true); + await deleteButton(ctx.nodes).click(); + await ctx.nodes["exit-demo"].click(); + ctx.nodes["file-input"].handlers.change({ + target: { files: [new File(["PDF"], "new.pdf")], value: "" }, + }); + assert.equal(ctx.nodes["upload-dialog"].open, false); + assert.equal(ctx.nodes["manuals-dialog"].open, false); + assert.equal(ctx.app.state.selected, manual.id); + assert.equal( + ctx.calls.some((c) => c.method === "DELETE"), + false, + ); + assert.equal(ctx.nodes.toast.textContent.includes("Manual connected"), false); +}); + +test("retry cannot race a follow-up answer and the complete transcript is saved", async () => { + const answer = deferred(); + let questions = 0; + let saves = 0; + const ctx = await setup((path) => { + if (path === "/questions" && ++questions === 2) return answer.promise; + if (path === "/chats" && ++saves === 1) + return Promise.reject(new Error("offline")); + }); + ctx.app.choose(manual.id); + await ask(ctx); + assert.equal(ctx.app.state.unsaved, true); + const asking = ask(ctx); + assert.equal(ctx.nodes["retry-save"].disabled, true); + await ctx.app.saveActiveChat(); + assert.equal(saves, 1); + answer.resolve(result); + await asking; + const writes = ctx.calls.filter((c) => c.path === "/chats"); + assert.equal(JSON.parse(writes.at(-1).body).messages.length, 4); + assert.equal(ctx.app.state.unsaved, false); +}); + +test("removed manual stays attached to old chat but New chat clears unavailable selection", async () => { + const saved = { + id: "saved", + revision: 3, + document_id: "removed", + demo: false, + messages: [ + { role: "user", content: "Question" }, + { role: "assistant", content: "Answer", sources: [] }, + ], + }; + const ctx = await setup( + (path) => (path === "/chats/saved" ? { chat: saved } : undefined), + [], + ); + await ctx.app.openSavedChat("saved"); + assert.equal(ctx.app.state.selected, "removed"); + assert.equal(ctx.app.state.missingManual, true); + await ask(ctx); + assert.equal( + ctx.calls.some((c) => c.path === "/questions"), + false, + ); + ctx.app.newChat(); + assert.equal(ctx.app.state.selected, ""); + assert.equal(ctx.app.state.missingManual, false); +}); + +test("refresh preserves unsaved manual context and discard confirmation recovers permanent save failures", async () => { + let discard = false; + const ctx = await setup( + (path) => + path === "/chats" + ? Promise.reject(new Error("413 transcript too large")) + : undefined, + [manual], + () => discard, + ); + ctx.app.choose(manual.id); + await ask(ctx); + ctx.documents.splice(0); + await ctx.app.refresh(); + assert.equal(ctx.app.state.selected, manual.id); + assert.equal(ctx.app.state.missingManual, true); + assert.equal(ctx.app.newChat(), false); + assert.equal(ctx.app.state.transcript.length, 2); + discard = true; + assert.equal(ctx.app.newChat(), true); + assert.equal(ctx.app.state.transcript.length, 0); + assert.equal(ctx.app.state.unsaved, false); + assert.equal(ctx.app.state.selected, ""); +}); + +test("successful upload selects the uploaded manual and New chat retains a valid manual", async () => { + const docs = [manual]; + const uploaded = { ...manual, id: "new", name: "new.pdf" }; + const ctx = await setup((path, options) => { + if (path === "/documents" && options.method === "POST") { + docs.push(uploaded); + return { document: uploaded }; + } + }, docs); + ctx.app.choose("", true); + ctx.nodes["file-input"].handlers.change({ + target: { files: [new File(["PDF"], "new.pdf")], value: "" }, + }); + await ctx.app.upload({ preventDefault() {} }); + assert.equal(ctx.app.state.selected, "new"); + assert.equal(ctx.app.state.demo, false); + assert.equal(ctx.nodes["upload-dialog"].open, false); + assert.match(ctx.nodes.toast.textContent, /Manual connected/); + ctx.app.newChat(); + assert.equal(ctx.app.state.selected, "new"); +}); diff --git a/tests/test_app.py b/tests/test_app.py index 5f16848..15a9a60 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -639,3 +639,171 @@ def test_demo_api_rejects_photo_analysis(clients, provider): ) assert result.status_code == 422 assert provider[0].chats == [] + + +def test_page_and_assets_revalidate_including_not_modified(clients): + client, _, _ = clients + page = client.get("/workspace") + assert page.headers["cache-control"] == "no-cache" + path = re.search( + r'href="(/static/v/[0-9a-f]{16}/css/workspace.css)"', page.text + ).group(1) + asset = client.get(path) + assert asset.status_code == 200 + assert asset.headers["cache-control"] == "no-cache" + unchanged = client.get(path, headers={"If-None-Match": asset.headers["etag"]}) + assert unchanged.status_code == 304 + assert unchanged.headers["cache-control"] == "no-cache" + assert client.get("/api/health").headers["cache-control"] == "no-store" + + +def test_imported_module_changes_refresh_the_entire_asset_graph(tmp_path, monkeypatch): + import shutil + from urllib.parse import urljoin + + web = tmp_path / "web" + shutil.copytree(application.WEB_DIR, web) + monkeypatch.setattr(application, "WEB_DIR", web) + client = TestClient(application.create_app(tmp_path / "runtime")) + first = client.get("/workspace").text + original = re.search( + r'src="(/static/v/[0-9a-f]{16}/js/workspace.js)"', first + ).group(1) + assert original in client.get("/workspace").text + module = web / "js/examples.js" + module.write_text(module.read_text() + "\n// Regression fixture: module changed.\n") + updated = re.search( + r'src="(/static/v/[0-9a-f]{16}/js/workspace.js)"', client.get("/workspace").text + ).group(1) + assert updated != original + # Relative imports stay in the new revision, rather than reusing a cached module URL. + imported = urljoin(updated, "./examples.js") + result = client.get(imported) + assert result.status_code == 200 + assert "Regression fixture: module changed." in result.text + assert imported.split("/js/")[0] in client.get("/").text + assert client.get(urljoin(updated, "../css/workspace.css")).status_code == 200 + + +def test_versioned_assets_preserve_the_public_directory_boundary(clients): + client, _, _ = clients + assert client.get("/static/v/not-a-revision/css/workspace.css").status_code == 404 + result = client.get("/static/v/0123456789abcdef/..%2F..%2Fapi.py") + assert result.status_code == 404 + + +def saved_chat_payload(): + return { + "document_id": "manual-one", + "demo": False, + "messages": [ + { + "role": "user", + "content": "What does this alarm mean?", + "photo": "omitted", + }, + { + "role": "assistant", + "content": "Record the exact alarm and equipment model.", + "insufficient_evidence": True, + "sources": [], + }, + ], + } + + +def test_chat_history_persists_and_is_workspace_scoped(clients, tmp_path): + first, second, _ = clients + created = first.post("/api/chats", json=saved_chat_payload()) + assert created.status_code == 201, created.text + saved = created.json()["chat"] + identifier = saved["id"] + assert saved["revision"] == 1 + assert saved["title"] == "What does this alarm mean?" + assert first.get("/api/chats").json()["chats"][0]["id"] == identifier + assert second.get("/api/chats").json()["chats"] == [] + assert second.get(f"/api/chats/{identifier}").status_code == 404 + assert ( + second.put( + f"/api/chats/{identifier}", json={**saved_chat_payload(), "revision": 1} + ).status_code + == 404 + ) + assert second.delete(f"/api/chats/{identifier}").status_code == 404 + restarted = TestClient(application.create_app(tmp_path)) + restarted.cookies.update(first.cookies) + response = restarted.get(f"/api/chats/{identifier}") + assert response.headers["cache-control"] == "no-store" + assert response.json()["chat"]["messages"][0]["photo"] == "omitted" + + +def test_chat_revision_prevents_overwrite_and_context_changes(clients): + first, _, _ = clients + payload = saved_chat_payload() + identifier = first.post("/api/chats", json=payload).json()["chat"]["id"] + update = {**payload, "revision": 1, "messages": payload["messages"] * 2} + result = first.put(f"/api/chats/{identifier}", json=update) + assert result.status_code == 200 + assert result.json()["chat"]["revision"] == 2 + assert first.put(f"/api/chats/{identifier}", json=update).status_code == 409 + assert ( + first.put( + f"/api/chats/{identifier}", + json={**update, "revision": 2, "document_id": "different"}, + ).status_code + == 409 + ) + assert len(first.get(f"/api/chats/{identifier}").json()["chat"]["messages"]) == 4 + assert first.delete(f"/api/chats/{identifier}").status_code == 200 + assert first.get(f"/api/chats/{identifier}").status_code == 404 + + +def test_chat_payload_rejects_photo_bytes_and_privileged_roles(clients): + client, _, _ = clients + payload = saved_chat_payload() + payload["messages"][0]["image"] = "data:image/png;base64,private-photo" + assert client.post("/api/chats", json=payload).status_code == 422 + del payload["messages"][0]["image"] + payload["messages"][0]["role"] = "system" + assert client.post("/api/chats", json=payload).status_code == 422 + assert client.get("/api/chats").json()["chats"] == [] + + +def test_chat_history_limits_before_storage_and_parsing(clients): + client, _, _ = clients + payload = saved_chat_payload() + assert ( + client.post( + "/api/chats", json={**payload, "messages": payload["messages"] * 51} + ).status_code + == 422 + ) + for method, path in [("POST", "/api/chats"), ("PUT", "/api/chats/unused")]: + result = client.request( + method, + path, + content=b"{}", + headers={ + "Content-Type": "application/json", + "Content-Length": str(1024 * 1024 + 1), + }, + ) + assert result.status_code == 413 + assert client.get("/api/chats").json()["chats"] == [] + + +def test_chat_quota_allows_existing_chat_updates(clients): + client, _, api = clients + workspace = application.hashlib.sha256( + client.cookies.get("mantis_workspace").encode() + ).hexdigest() + payload = {**saved_chat_payload(), "revision": 0} + for _ in range(100): + saved = api.state.store.save_chat(workspace, payload) + result = client.post("/api/chats", json=saved_chat_payload()) + assert result.status_code == 409 + assert "100 chats" in result.json()["detail"] + result = client.put( + f"/api/chats/{saved['id']}", json={**saved_chat_payload(), "revision": 1} + ) + assert result.status_code == 200 diff --git a/tests/test_review_regressions.py b/tests/test_review_regressions.py new file mode 100644 index 0000000..88e4037 --- /dev/null +++ b/tests/test_review_regressions.py @@ -0,0 +1,78 @@ +import asyncio +from contextlib import contextmanager +from pathlib import Path + +import pytest +from starlette.exceptions import HTTPException + +from mantis.frontend import FrontendFiles +from mantis.store import Store + + +@pytest.mark.parametrize( + "asset", ["css/workspace.css", "js/workspace.js", "assets/mantis-mark.png"] +) +def test_windows_revisioned_asset_paths(asset): + web = Path(__file__).parents[1] / "mantis" / "web" + files = FrontendFiles(directory=web) + path = ("v/0123456789abcdef/" + asset).replace("/", "\\") + response = asyncio.run( + files.get_response(path, {"type": "http", "method": "GET", "headers": []}) + ) + assert response.status_code == 200 + assert Path(response.path) == web / asset + + +@pytest.mark.parametrize( + "path", [r"v\bad\css\workspace.css", r"v\0123456789abcdef\..\..\pyproject.toml"] +) +def test_windows_revision_paths_reject_invalid_prefix_and_escape(path): + files = FrontendFiles(directory=Path(__file__).parents[1] / "mantis" / "web") + with pytest.raises(HTTPException) as error: + asyncio.run( + files.get_response(path, {"type": "http", "method": "GET", "headers": []}) + ) + assert error.value.status_code == 404 + + +def test_save_returns_own_revision_when_another_tab_writes_after_commit( + tmp_path, monkeypatch +): + store = Store(tmp_path / "db.sqlite") + other = Store(store.path) + payload = { + "document_id": "", + "demo": False, + "revision": 0, + "messages": [{"role": "user", "content": "Initial question"}], + } + saved = store.save_chat("workspace", payload) + original_connect = store.connect + interleaved = False + + @contextmanager + def connect_with_other_tab(): + nonlocal interleaved + with original_connect() as db: + yield db + if not interleaved: + interleaved = True + other.save_chat( + "workspace", + { + **payload, + "revision": 2, + "messages": [{"role": "user", "content": "Other tab"}], + }, + saved["id"], + ) + + monkeypatch.setattr(store, "connect", connect_with_other_tab) + result = store.save_chat("workspace", {**payload, "revision": 1}, saved["id"]) + assert result["revision"] == 2 + assert result["messages"] == payload["messages"] + assert other.chat("workspace", saved["id"])["revision"] == 3 + with pytest.raises(ValueError, match="another tab"): + store.save_chat( + "workspace", {**payload, "revision": result["revision"]}, saved["id"] + )