Czat: załączniki (PDF, DOCX, TXT/MD/CSV) jako źródła pytania

POST /chat/attachments zwraca tekst pliku i niczego nie zapisuje (audyt: nazwa i rozmiar,
bez treści). PDF przez pypdf (BSD-3), DOCX biblioteką standardową z odmową DTD, tekst
UTF-8 albo cp1250. Konsola: spinacz i upuszczenie pliku na stronie głównej, etykiety
plików, każdy plik jako ponumerowane źródło (przypis [n], sprawdzanie cytatów). Tekst
przycinany do pamięci modelu (context_window z listy modeli) z uczciwym „do strony X z Y”.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqL6AphKDyHPDToUMin
This commit is contained in:
tobayah
2026-11-18 15:07:19 +01:00
co-authored by Claude Opus 5.5
parent 68a5f55eb6
commit bf46fb5724
8 changed files with 385 additions and 19 deletions
+2 -2
View File
@@ -35,7 +35,7 @@ from .deps import refuse_cross_site_write
from .errors import ProblemDetailErrorMiddleware, install_error_handlers, problem_response
from .logging_config import configure_logging
from .observability import setup_observability
from .routers import admin, admin_modules, admin_providers, auth, health, marketplace, models, nodes, users
from .routers import admin, admin_modules, admin_providers, attachments, auth, health, marketplace, models, nodes, users
API_PREFIX = "/api/v1"
@@ -157,7 +157,7 @@ async def _security_headers(request, call_next):
for router in (
health.router, auth.router, users.router, admin.router, admin_modules.router,
admin_providers.router, nodes.router, marketplace.router, models.router,
admin_providers.router, nodes.router, marketplace.router, models.router, attachments.router,
):
app.include_router(router, prefix=API_PREFIX)
+32
View File
@@ -0,0 +1,32 @@
"""POST /chat/attachments: the text of a file attached to a Home chat question. Nothing is stored.
The body is the file's raw bytes (no multipart, so no parser dependency), its name in `?name=`. The
audit row names the file and its size, never its content.
"""
from __future__ import annotations
from fastapi import APIRouter, Depends, Query, Request
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, get_current_user
from ..models import AppUser
from ..services import attachments, audit
router = APIRouter(tags=["chat"])
@router.post("/chat/attachments")
async def extract(request: Request, name: str = Query(min_length=1, max_length=255),
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
data = bytearray()
async for chunk in request.stream():
data += chunk
if len(data) > attachments.MAX_BYTES:
break # extract() refuses it; nothing past the limit is read
out = attachments.extract(name, bytes(data))
audit.record(db, action="chat.attachment", entity_type="attachment", actor_id=user.id, detail=name[:200],
ip=client_ip(request), diff={"kind": out["kind"], "bytes": len(data), "pages": out["pages"],
"chars": out["chars"]})
db.commit()
return out
+117
View File
@@ -0,0 +1,117 @@
"""A file attached to a Home chat question: its text, and nothing kept.
The bytes arrive, the text goes back, and neither is stored: the console holds the text for the
conversation and sends it to the model as one more source, the way it sends a contract or a matter.
So the privacy of an attachment is the privacy of the question itself (the provider's policy decides
where it may go), and there is no file anywhere to delete afterwards.
PDF through pypdf (BSD-3, pure Python), DOCX through the standard library (it is a ZIP of XML),
plain text decoded as UTF-8 and, failing that, as Windows-1250, which is what Polish text files
from older Office installations are. Every page of a PDF is marked `[strona N]` so the model can say
where it read something.
"""
from __future__ import annotations
import io
import zipfile
from xml.etree import ElementTree
from ..errors import ValidationError
MAX_BYTES = 10 * 1024 * 1024
MAX_PAGES = 300
MAX_CHARS = 400_000 # more than any model here reads; the console trims to the model's budget
_MAX_XML = 50 * 1024 * 1024 # word/document.xml unpacked: a ZIP bomb stops here, not in memory
TEXT_TYPES = (".txt", ".md", ".csv")
_W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
def _refuse(code: str, pl: str, en: str) -> ValidationError:
return ValidationError(pl, {"code": code, "en": en})
def _pdf(data: bytes) -> tuple[str, int]:
from pypdf import PdfReader
from pypdf.errors import PdfReadError
try:
reader = PdfReader(io.BytesIO(data))
if reader.is_encrypted and not reader.decrypt(""):
raise _refuse("attachment_encrypted", "Plik PDF jest zabezpieczony hasłem.",
"The PDF is password-protected.")
pages = reader.pages
if len(pages) > MAX_PAGES:
raise _refuse("attachment_too_long", f"Plik ma więcej niż {MAX_PAGES} stron.",
f"The file has more than {MAX_PAGES} pages.")
parts, total = [], 0
for n, page in enumerate(pages, 1):
text = (page.extract_text() or "").strip()
parts.append(f"[strona {n}]\n{text}")
total += len(text)
if total > MAX_CHARS:
break
except PdfReadError as exc:
raise _refuse("attachment_unreadable", "Nie da się odczytać tego pliku PDF.",
"This PDF cannot be read.") from exc
if not total:
raise _refuse("attachment_no_text",
"Ten PDF nie ma warstwy tekstu (to skan). Potrzebne jest rozpoznanie tekstu (OCR).",
"This PDF has no text layer (a scan). It needs OCR.")
return "\n\n".join(parts), len(pages)
def _docx(data: bytes) -> str:
try:
with zipfile.ZipFile(io.BytesIO(data)) as z:
info = z.getinfo("word/document.xml")
if info.file_size > _MAX_XML:
raise _refuse("attachment_too_long", "Dokument jest za duży.", "The document is too large.")
xml = z.read(info)
# Word never writes a DTD; without one there are no entities to expand (XXE, billion laughs).
if b"<!DOCTYPE" in xml or b"<!ENTITY" in xml:
raise _refuse("attachment_unreadable", "Nie da się odczytać tego pliku DOCX.",
"This DOCX cannot be read.")
root = ElementTree.fromstring(xml)
except (zipfile.BadZipFile, KeyError, ElementTree.ParseError) as exc:
raise _refuse("attachment_unreadable", "Nie da się odczytać tego pliku DOCX.",
"This DOCX cannot be read.") from exc
lines = []
for p in root.iter(f"{_W}p"):
bits = []
for el in p.iter():
if el.tag == f"{_W}t":
bits.append(el.text or "")
elif el.tag == f"{_W}tab":
bits.append("\t")
elif el.tag in (f"{_W}br", f"{_W}cr"):
bits.append("\n")
lines.append("".join(bits))
return "\n".join(lines).strip()
def _plain(data: bytes) -> str:
try:
return data.decode("utf-8-sig")
except UnicodeDecodeError:
return data.decode("cp1250", errors="replace")
def extract(name: str, data: bytes) -> dict:
"""`{name, kind, pages, chars, text}` of one attached file, or a 422 saying why not."""
if len(data) > MAX_BYTES:
raise _refuse("attachment_too_large", "Plik jest większy niż 10 MB.", "The file is larger than 10 MB.")
lower = name.lower()
pages = None
if lower.endswith(".pdf") and data.startswith(b"%PDF"):
kind = "pdf"
text, pages = _pdf(data)
elif lower.endswith(".docx") and data.startswith(b"PK"):
kind, text = "docx", _docx(data)
elif lower.endswith(TEXT_TYPES) and b"\x00" not in data[:4096]:
kind, text = "text", _plain(data)
else:
raise _refuse("attachment_type", "Ten rodzaj pliku nie jest obsługiwany. Dołącz PDF, DOCX, TXT, MD albo CSV.",
"This kind of file is not supported. Attach a PDF, DOCX, TXT, MD or CSV.")
text = text.strip()
if not text:
raise _refuse("attachment_empty", "W pliku nie ma tekstu.", "The file has no text.")
return {"name": name, "kind": kind, "pages": pages, "chars": len(text), "text": text[:MAX_CHARS]}
+1 -1
View File
@@ -141,7 +141,7 @@ def usable_models(db: DbSession, user: AppUser) -> list[dict]:
tells Home that a `user` provider needs the person's own key (Settings → My model keys)."""
return [
{"id": m["id"], "provider": p.name, "kind": p.kind, "stays_in_the_eu": core.stays_in_the_eu(p),
"key_mode": p.key_mode}
"key_mode": p.key_mode, "context_window": m.get("context_window")}
for p in core.usable_providers(db, is_admin=bool(user.is_admin))
for m in p.models or [] if m.get("dialect", CHAT_DIALECT) == CHAT_DIALECT
]
+1
View File
@@ -89,3 +89,4 @@ opentelemetry-sdk==1.42.1
opentelemetry-exporter-otlp-proto-grpc==1.42.1
opentelemetry-instrumentation-fastapi==0.63b1
opentelemetry-instrumentation-sqlalchemy==0.63b1
pypdf==6.21.4 # text of a PDF attached to a chat question (BSD-3-Clause, pure Python)
+114
View File
@@ -0,0 +1,114 @@
"""A file attached to a Home chat question: its text back, nothing stored, and the refusals by code."""
from __future__ import annotations
import io
import types
import uuid
import zipfile
import pytest
from fastapi import Request
from fastapi.testclient import TestClient
from app import deps
from app.db import get_db
from app.errors import ValidationError
from app.services import attachments, audit
def _pdf(*pages: str) -> bytes:
"""A real PDF with one text line per page (Helvetica, WinAnsi), xref offsets computed."""
objs = ["<< /Type /Catalog /Pages 2 0 R >>",
"<< /Type /Pages /Kids [" + " ".join(f"{4 + 2 * i} 0 R" for i in range(len(pages)))
+ f"] /Count {len(pages)} >>",
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"]
for i, text in enumerate(pages):
stream = f"BT /F1 12 Tf 72 720 Td ({text}) Tj ET" if text else ""
objs.append(f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> "
f"/Contents {5 + 2 * i} 0 R >>")
objs.append(f"<< /Length {len(stream)} >>\nstream\n{stream}\nendstream")
out, offsets = io.BytesIO(), []
out.write(b"%PDF-1.4\n")
for n, body in enumerate(objs, 1):
offsets.append(out.tell())
out.write(f"{n} 0 obj\n{body}\nendobj\n".encode("latin-1"))
xref = out.tell()
out.write(f"xref\n0 {len(objs) + 1}\n0000000000 65535 f \n".encode())
for o in offsets:
out.write(f"{o:010d} 00000 n \n".encode())
out.write(f"trailer\n<< /Size {len(objs) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode())
return out.getvalue()
def _docx(xml: str) -> bytes:
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("word/document.xml", xml)
return buf.getvalue()
W = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"'
def test_a_pdf_comes_back_page_by_page():
out = attachments.extract("Umowa.PDF", _pdf("Okres wypowiedzenia 3 miesiace", "Kara umowna 10 procent"))
assert out["kind"] == "pdf" and out["pages"] == 2
assert "[strona 1]\nOkres wypowiedzenia 3 miesiace" in out["text"]
assert "[strona 2]\nKara umowna 10 procent" in out["text"]
def test_a_scan_is_refused_with_its_reason():
with pytest.raises(ValidationError) as refused:
attachments.extract("skan.pdf", _pdf("", ""))
assert refused.value.extra["code"] == "attachment_no_text"
def test_a_docx_keeps_its_paragraphs_tabs_and_breaks():
xml = (f'<w:document {W}><w:body><w:p><w:r><w:t>§ 1. Strony</w:t></w:r></w:p>'
'<w:p><w:r><w:t>Najemca</w:t><w:tab/><w:t>ABC</w:t><w:br/><w:t>sp. z o.o.</w:t></w:r></w:p></w:body></w:document>')
out = attachments.extract("najem.docx", _docx(xml))
assert out["kind"] == "docx" and out["text"] == "§ 1. Strony\nNajemca\tABC\nsp. z o.o."
def test_a_docx_with_a_dtd_is_refused_before_parsing():
bomb = f'<!DOCTYPE w [<!ENTITY a "aaaa">]><w:document {W}><w:body><w:p><w:r><w:t>&a;</w:t></w:r></w:p></w:body></w:document>'
with pytest.raises(ValidationError) as refused:
attachments.extract("bomba.docx", _docx(bomb))
assert refused.value.extra["code"] == "attachment_unreadable"
def test_plain_text_falls_back_to_windows_1250():
assert attachments.extract("notatka.txt", "Zażółć gęślą jaźń".encode("cp1250"))["text"] == "Zażółć gęślą jaźń"
assert attachments.extract("a.md", "# Tytuł".encode("utf-8"))["text"] == "# Tytuł"
@pytest.mark.parametrize(("name", "data", "code"), [
("obraz.png", b"\x89PNG\r\n", "attachment_type"),
("udaje.pdf", b"PK\x03\x04 not a pdf", "attachment_type"), # the name says PDF, the bytes do not
("binarny.txt", b"MZ\x00\x00", "attachment_type"),
("pusty.txt", b" \n", "attachment_empty"),
("duzy.txt", b"a" * (attachments.MAX_BYTES + 1), "attachment_too_large"),
])
def test_refusals_carry_a_code(name, data, code):
with pytest.raises(ValidationError) as refused:
attachments.extract(name, data)
assert refused.value.extra["code"] == code and refused.value.extra["en"]
def test_the_route_returns_the_text_and_audits_only_the_name(monkeypatch):
from app.main import app
audited = []
monkeypatch.setattr(audit, "record", lambda *a, **k: audited.append(k))
def signed_in(request: Request):
request.state.credential_id, request.state.credential_kind = uuid.uuid4(), "session"
return types.SimpleNamespace(id=uuid.uuid4(), is_admin=False)
app.dependency_overrides[deps.get_current_user] = signed_in
app.dependency_overrides[get_db] = lambda: types.SimpleNamespace(commit=lambda: None)
try:
r = TestClient(app).post("/api/v1/chat/attachments?name=tajne.txt", content="Treść poufna".encode())
finally:
app.dependency_overrides.clear()
assert r.status_code == 200 and r.json()["text"] == "Treść poufna"
assert audited[0]["detail"] == "tajne.txt" and "Treść" not in repr(audited)
+7
View File
@@ -114,6 +114,13 @@
font-size: 12px; color: var(--at-text-secondary);
}
.home-tools { margin-left: auto; display: inline-flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: 8px; min-width: 0; }
/* Attached files: chips above the question; the whole composer outlines while a file is dragged over the page. */
.home-files { display: flex; flex-wrap: wrap; gap: 6px; margin: 0 0 8px -6px; font-size: 12px; }
.home-file { display: inline-flex; align-items: center; gap: 6px; max-width: 100%; padding: 2px 4px 2px 8px; }
.home-file > span[data-no-i18n] { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 260px; }
.home-file-x { display: grid; place-items: center; width: 20px; height: 20px; border: 0; border-radius: 50%; background: none; color: inherit; cursor: pointer; }
.home-file-x:hover { background: var(--at-hover); }
.home-box.drop .home-input { border-color: var(--at-primary); border-style: dashed; }
.home-scope-mod { display: inline-flex; align-items: center; gap: 6px; color: var(--at-text); }
/* The model picker sits at the end of the scope bar; the answer is a quiet card, plain text only. */
.home-model { display: inline-flex; align-items: center; gap: 8px; }
+111 -16
View File
@@ -66,7 +66,8 @@ const state = {
for the person to copy into a desktop client, and is never used by this console. */
async function api(method, path, body) {
const opt = { method, headers: {}, credentials: 'same-origin' };
if (body !== undefined) {
if (body instanceof Blob) opt.body = body; // a file attached to a chat question, as raw bytes
else if (body !== undefined) {
opt.headers['Content-Type'] = 'application/json';
opt.body = JSON.stringify(body);
}
@@ -172,6 +173,8 @@ const ICN = {
check: '<path d="M5 12l5 5l10 -10"/>',
// tabler: x
x: '<path d="M18 6l-12 12"/><path d="M6 6l12 12"/>',
// tabler: paperclip
paperclip: '<path d="M15 7l-6.5 6.5a1.5 1.5 0 0 0 3 3l6.5 -6.5a3 3 0 0 0 -6 -6l-6.5 6.5a4.5 4.5 0 0 0 9 9l6.5 -6.5"/>',
stop: '<path d="M5 7a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2z"/>',
// tabler: sun
sun: '<path d="M8 12a4 4 0 1 0 8 0a4 4 0 1 0 -8 0"/><path d="M3 12h1m8 -9v1m8 8h1m-9 8v1m-6.4 -15.4l.7 .7m12.1 -.7l-.7 .7m0 11.4l.7 .7m-12.1 -.7l-.7 .7"/>',
@@ -389,6 +392,13 @@ const I18N = {
'Odpowiedź AI': 'AI answer',
'· sprawdź w źródle': '· check it against the source',
'Nowa rozmowa': 'New conversation',
'Dołącz plik': 'Attach a file',
'Dołącz plik (PDF, DOCX, TXT, MD, CSV)': 'Attach a file (PDF, DOCX, TXT, MD, CSV)',
'Usuń plik': 'Remove the file',
'Czytam plik…': 'Reading the file…',
'Pliki nie przetrwały odświeżenia strony, dołącz je ponownie:': 'The files did not survive the page reload, attach them again:',
'Wybierz model asystenta, żeby zapytać o plik.': 'Pick an assistant model to ask about a file.',
'Do rozmowy można dołączyć najwyżej 3 pliki.': 'A conversation takes at most 3 files.',
'Myślę…': 'Thinking…',
'Ładuję model do pamięci karty graficznej, to trwa około minuty…': 'Loading the model into the graphics card, this takes about a minute…',
'Model nie odpowiedział.': 'The model did not answer.',
@@ -1240,7 +1250,7 @@ function homeSubmit(ev) {
browser, per account (modelPickKey); the server keeps no choice. The answer is
written with textContent and nothing else, so a model cannot put markup, a link or an image on
the platform's one origin. The conversation lives in this tab (sessionStorage, see chatSave). */
const chat = { model: '', turns: [], ctl: null };
const chat = { model: '', turns: [], ctl: null, files: [], filesLost: [] };
const modelLabel = (m) => m.id;
async function loadModels() {
@@ -1271,8 +1281,86 @@ function homeModelChange(sel) {
document.querySelector('.home-send').setAttribute('aria-label', _tr(ask ? 'Wyślij' : 'Szukaj'));
document.querySelectorAll('[data-chat-only]').forEach((e) => e.classList.toggle('hidden', !ask));
saveModelPick(sel.value);
chatFilesRender(); // how much of a file fits depends on the model
}
/* Files attached to the conversation: the server returns their text and keeps nothing (routers/attachments.py);
each becomes a numbered source of every following question, so the answer cites it as [n] and its quotations
are checked like a contract's. The text lives in this page only: not in sessionStorage (a 40-page contract
would fill it), so after a reload the chips say the files have to be attached again. */
const CHAT_MAX_FILES = 3;
// ponytail: the whole text while it fits, else its beginning, said out loud; choosing the passages that answer is
// the next step. About 2.5 characters a token (Polish legal text, cautious), less room for the rest and the answer.
function chatFileBudget(model) {
const m = ((state._models || {}).models || []).find((x) => x.id === model);
const tokens = (m && Number(m.context_window)) || 32768;
return Math.max(6000, Math.min(100000, Math.round(tokens * 2.5) - 25000));
}
function chatFileSources(files, model) {
let left = chatFileBudget(model);
const fit = new Map();
// The shortest first, each its share of what is left: a short file is read whole beside a long one.
[...files].sort((a, b) => a.text.length - b.text.length).forEach((f, i, all) => {
const n = Math.min(f.text.length, Math.floor(left / (all.length - i)));
fit.set(f, n);
left -= n;
});
return files.map((f, i) => {
const n = fit.get(f);
const text = f.text.slice(0, n);
const read = n >= f.text.length ? '' : f.pages ? `do strony ${(text.match(/\[strona \d+\]/g) || []).length} z ${f.pages}`
: `${Math.round((100 * n) / f.text.length)}% tekstu`;
const note = read ? `\n(Plik przycięty: przeczytano tylko ${read}. Jeśli odpowiedzi tu nie ma, napisz, że nie przeczytałem dalszej części pliku.)` : '';
return { slug: 'załącznik', kind: 'plik', key: `plik:${i}:${f.name}`, title: f.name, read, note, text: text + note };
});
}
function chatFilesRender() {
const box = $('homeFiles');
if (!box) return;
const srcs = chatFileSources(chat.files, ($('homeModel') && $('homeModel').value) || chat.model);
box.innerHTML = srcs.map((s, i) => `<span class="chip home-file">${svg(ICN.paperclip, 13)}<span data-no-i18n>${esc(s.title)}</span>`
+ (s.read ? `<span class="faint" data-no-i18n>· model przeczyta ${esc(s.read)}</span>` : '')
+ `<button type="button" class="home-file-x" aria-label="Usuń plik" onclick="chatDropFile(${i})">${svg(ICN.x, 12)}</button></span>`).join('')
+ (chat.reading ? '<span class="chip home-file faint">Czytam plik…</span>' : '')
+ (chat.filesLost.length ? `<span class="faint tiny">Pliki nie przetrwały odświeżenia strony, dołącz je ponownie: <span data-no-i18n>${esc(chat.filesLost.join(', '))}</span></span>` : '');
localize(box);
box.classList.toggle('hidden', !box.innerHTML);
}
function chatDropFile(i) {
chat.files.splice(i, 1);
chatFilesRender();
}
async function homeAttach(list) {
const files = [...list];
if (!files.length) return;
if (!($('homeModel') && $('homeModel').value)) { toast('Wybierz model asystenta, żeby zapytać o plik.'); return; }
if (chat.files.length + files.length > CHAT_MAX_FILES) { toast('Do rozmowy można dołączyć najwyżej 3 pliki.'); return; }
chat.filesLost = [];
for (const f of files) {
if (f.size > 10 * 1024 * 1024) { toast(`${f.name}: plik jest większy niż 10 MB.`); continue; }
chat.reading = true;
chatFilesRender();
try { chat.files.push(await api('POST', '/chat/attachments?name=' + encodeURIComponent(f.name), f)); }
catch (ex) { toast(`${f.name}: ${ex.message}`); }
}
chat.reading = false;
chatFilesRender();
}
// A file dropped anywhere on Home is attached; anywhere else the browser would leave the page to open it.
const homeBox = () => document.querySelector('.home-box');
addEventListener('dragover', (e) => {
if (!e.dataTransfer || !e.dataTransfer.types.includes('Files')) return;
e.preventDefault();
if (homeBox()) homeBox().classList.add('drop');
});
addEventListener('dragleave', (e) => { if (!e.relatedTarget && homeBox()) homeBox().classList.remove('drop'); });
addEventListener('drop', (e) => {
if (!e.dataTransfer || !e.dataTransfer.files.length) return;
e.preventDefault();
if (homeBox()) homeBox().classList.remove('drop');
if ($('homeQ')) homeAttach(e.dataTransfer.files);
});
// Rebuilt on every streamed chunk inside its own scrolling box, so the reader's place is kept as it was.
// `toEnd`: the asker just sent, so their question goes to the top and the answer is read from its first line
// while it is written below; nothing pulls the reader down after it.
@@ -1377,8 +1465,10 @@ function chatReset() {
chat.busy = null; // or the send button stays a stop button for an answer that is gone
chat.turns = [];
chat.index = null; // the next question reads the modules again
Object.assign(chat, { files: [], filesLost: [] });
chatSave();
chatRender();
chatFilesRender();
}
// The conversation outlives leaving Home: Back from a source's link brings it back, also after a module's
@@ -1393,12 +1483,12 @@ function chatSave() {
const cited = new Set((t.content.match(/\[\d+(?:\s*,\s*\d+)*\]/g) || []).flatMap((m) => m.match(/\d+/g).map(Number)));
return { ...t, refs: t.refs.map((r) => ({ ...r, text: cited.has(r.n) ? String(r.text || '').slice(0, 8000) : '' })) };
};
try { sessionStorage.setItem('atrium.chat', JSON.stringify({ user: state.user.id, model: chat.model, turns: chat.turns.map(slim) })); }
try { sessionStorage.setItem('atrium.chat', JSON.stringify({ user: state.user.id, model: chat.model, turns: chat.turns.map(slim), files: chat.files.map((f) => f.name) })); }
catch { /* storage off (private window): the conversation lives as long as the page */ }
}
function chatForget() {
if (chat.ctl) chat.ctl.abort();
Object.assign(chat, { user: null, model: '', turns: [], index: null });
Object.assign(chat, { user: null, model: '', turns: [], index: null, files: [], filesLost: [] });
try { sessionStorage.removeItem('atrium.chat'); } catch { /* storage off */ }
}
// Checked on every Home render, not only on a reload: a sign-in after another in this tab keeps the page.
@@ -1408,7 +1498,7 @@ function chatRestore() {
if (chat.turns.length) return;
try {
const saved = JSON.parse(sessionStorage.getItem('atrium.chat') || 'null');
if (saved && saved.user === state.user.id) Object.assign(chat, { model: saved.model, turns: saved.turns });
if (saved && saved.user === state.user.id) Object.assign(chat, { model: saved.model, turns: saved.turns, filesLost: chat.files.length ? [] : saved.files || [] });
} catch { /* nothing saved, or storage off */ }
}
@@ -3665,11 +3755,13 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
prawo = chat.prawo ?? true,
// istnienie: a code source saying a capitalised name of the question matches no visible record (audit P9, 13.11);
// the condition for a milder rule 3, not yet measured on the models, so off by default.
istnienie = chat.istnienie ?? false }) {
istnienie = chat.istnienie ?? false, files = chat.files }) {
const done = (content, extra = {}) => Object.assign(answer, { content, status: '', ...extra });
try {
// "Umowa o dzieło" in a question about the law is not a question about the register's contracts.
const coded = chatRoute(question) === 'law_topic' ? null : chatRefusal(index, question);
// An attached file is what the question is about: "w tej umowie" means it, not the register.
const att = chatFileSources(files, model);
const coded = att.length || chatRoute(question) === 'law_topic' ? null : chatRefusal(index, question);
if (coded) return done(coded, { coded: 'refusal' });
// A turn that failed its check still named its records (kept in `mentioned`): "ta umowa" after it means them.
const at = turns.map((t) => t.role === 'assistant' && !t.aborted && (!t.failed || !!(t.mentioned && t.mentioned.length))).lastIndexOf(true);
@@ -3685,7 +3777,7 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
const asked = graf && !named.length && ana.ordinal && prev && prev.coded === 'ask' && prev.graf && prev.graf.order;
const pin = asked ? asked.at(ana.ordinal < 0 ? -1 : ana.ordinal - 1) || null : null;
let resolved = [];
if (!named.length && !pin && (ana.demonstrative || ana.ordinal)) {
if (!att.length && !named.length && !pin && (ana.demonstrative || ana.ordinal)) {
const res = chatResolveRefs(prev, ana, index);
const which = CHAT_WHICH[res.kind] || 'który z nich';
if (res.ambiguous) {
@@ -3740,7 +3832,7 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
const route0 = chatRoute(question, named.length + resolved.length);
const route1 = chatRoute(question, named.length + resolved.length + 1);
const usable = !!(graf && gt && route1 === 'data' && (route0 === 'data' || gt.hit !== 'czesciowe'));
if (usable && gt.ask) return done(gt.ask, { coded: 'ask', mentioned: gt.mentioned, graf: gt });
if (usable && gt.ask && !att.length) return done(gt.ask, { coded: 'ask', mentioned: gt.mentioned, graf: gt });
const route = usable && (gt.root || gt.link) ? route1 : route0;
// A card only for a data question: a cited article stays Insider's. A fault in building it leaves the turn as A.
let card = null;
@@ -3783,10 +3875,10 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
found = Object.assign(found.filter((r) => card.members.has(r.key) || card.names(r) || (gt.ja && /^galena:(?:umowa|zestawienie|wygasajace|ranking)/.test(r.key))), { top });
}
const seen = new Set();
const pick = law.length || topic.length || named.length || resolved.length || back.length || card ? null : chatPick(question, index);
const pick = att.length || law.length || topic.length || named.length || resolved.length || back.length || card ? null : chatPick(question, index);
if (pick && !pick.table.rows.length) return done(pick.empty, { coded: 'pick', refs: [], verify: [] });
// The entity's card right after law and topic; a one-record link card behind its record, so [1] stays the record.
const pool = [...(istnienie && !pick && !named.length && !resolved.length && !card && !law.length ? chatExistence(question, index) : []),
const pool = [...att, ...(istnienie && !pick && !named.length && !resolved.length && !card && !law.length ? chatExistence(question, index) : []),
...(pick ? [pick.rec] : []), ...law, ...topic, ...lawGraph.near,
...(card && card.rec.kind === 'karta' ? [card.rec] : []), ...named, ...resolved,
...(card && card.rec.kind !== 'karta' ? [card.rec] : []), ...backSum, ...back, ...chatCarry(prev, index),
@@ -3800,12 +3892,12 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
const listHit = (r) => (r.list || []).some((g) => g.re && g.re.test(question));
const hitFams = new Set(pool.filter(listHit).map(fam));
const sources = pool.filter((r) => !(r.list && hitFams.has(fam(r))) || listHit(r))
.slice(0, CHAT_TOP + law.length + topic.length + lawGraph.near.length);
.slice(0, att.length + CHAT_TOP + law.length + topic.length + lawGraph.near.length);
const name = (slug) => (chatModules().find((m) => m.slug === slug) || { name: slug }).name;
const toRef = (r, i) => ({ n: i + 1, key: r.key, kind: r.kind, slug: r.slug, module: name(r.slug), title: r.title, text: r.text,
data: !['przepis', 'akt', 'orzeczenie'].includes(r.kind), inner: r.inner, url: r.url });
data: !['przepis', 'akt', 'orzeczenie', 'plik'].includes(r.kind), inner: r.inner, url: r.url });
answer.refs = sources.map(toRef);
answer.trace = sources.map((r, i) => `[${i + 1}] ${name(r.slug)}: ${r.title}`);
answer.trace = sources.map((r, i) => `[${i + 1}] ${name(r.slug)}: ${r.title}${r.read ? ` (${r.read})` : ''}`);
answer.status = 'Myślę…';
onUpdate(answer);
const about = [...resolved, ...(card && card.rec.kind === 'karta' ? [card.rec] : [])].map((r) => `[${sources.indexOf(r) + 1}] ${r.title}`);
@@ -3904,7 +3996,7 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
// Uncited and saying nothing about the data, where only the search matched (q-wiersz: "kancelarii" pulled in
// Counsel), is a refusal in other words: said by code too. Where code itself picked records (the urgent list, a
// list, a named record) "nie znalazłem nic" would be false: shown is what code assembled. A card stays an error (T13).
const matched = named.length || resolved.length || law.length || topic.length || card || pick || want;
const matched = att.length || named.length || resolved.length || law.length || topic.length || card || pick || want;
if ((!matched && found.top < CHAT_OFFTOPIC) || (!matched && bare(text))) {
return done(en ? CHAT_SCOPE_EN : CHAT_SCOPE, { coded: 'refusal', refs: [], verify: [] });
}
@@ -4163,11 +4255,13 @@ async function viewHome(C) {
<div id="homeSay" class="sr-only" aria-live="polite" data-no-i18n></div>
<form class="home-box" role="search" onsubmit="homeSubmit(event)">
<div class="home-input">
<div id="homeFiles" class="home-files hidden"></div>
<div class="home-line">${svg(ICN.search, 20)}
<textarea id="homeQ" rows="1" autocomplete="off" placeholder="${picked ? 'Zapytaj asystenta albo szukaj w modułach…' : 'Szukaj spraw, umów, plików i kancelarii…'}"
aria-label="${picked ? 'Zapytaj asystenta' : 'Szukaj we wszystkich modułach'}" oninput="homeQuery(this)" onkeydown="homeKey(event)"></textarea></div>
<div class="home-scope"><span>Szuka w:</span>${searchable.map((m) => `<span class="home-scope-mod" data-no-i18n>${moduleIcon(m, 14)}${esc(m.name)}</span>`).join('')}${lawChip}
<span class="home-tools">${picker}<button class="btn sm ghost home-new" type="button" onclick="chatReset()">Nowa rozmowa</button>
<span class="home-tools">${picker}<button class="btn sm ghost home-attach" type="button" onclick="$('homeFile').click()" aria-label="Dołącz plik" title="Dołącz plik (PDF, DOCX, TXT, MD, CSV)">${svg(ICN.paperclip, 16)}</button>
<input id="homeFile" class="hidden" type="file" multiple accept=".pdf,.docx,.txt,.md,.csv" onchange="homeAttach(this.files); this.value = ''"><button class="btn sm ghost home-new" type="button" onclick="chatReset()">Nowa rozmowa</button>
<button class="home-send" type="submit" aria-label="${picked ? 'Wyślij' : 'Szukaj'}" onclick="homeSendClick(event)">${svg(ICN.arrowright, 18)}</button></span></div></div>
</form>
<div id="homeResults" class="home-results hidden" aria-live="polite"></div>` : '')
@@ -4182,6 +4276,7 @@ async function viewHome(C) {
+ '</div>';
chatRestore();
chatRender(true);
chatFilesRender();
loadHomeKeys();
loadHomeStats();
loadModuleStats();