From cdc29f9a7b1db6c6b4e00203e582957247a2fabb Mon Sep 17 00:00:00 2001 From: maun200 <18380842+maun200@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:52:12 +0100 Subject: [PATCH 1/3] Store AI-chat conversations locally in the app (/local/chats) One owner-only JSON file per conversation under /chats//, listed newest first, with create/read/update/delete endpoints behind the existing session guard. Chats never go to the coordinator. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014XvdYnpnYBSTkq2tBgQTA3 --- projectzero/app.py | 54 +++++++++++++++++++++++ projectzero/chats.py | 92 ++++++++++++++++++++++++++++++++++++++++ tests/test_chats.py | 92 ++++++++++++++++++++++++++++++++++++++++ tests/test_client_app.py | 46 ++++++++++++++++++++ 4 files changed, 284 insertions(+) create mode 100644 projectzero/chats.py create mode 100644 tests/test_chats.py diff --git a/projectzero/app.py b/projectzero/app.py index 130e429..3956904 100644 --- a/projectzero/app.py +++ b/projectzero/app.py @@ -18,11 +18,14 @@ import httpx from fastapi import FastAPI, HTTPException, Request from fastapi.responses import HTMLResponse, JSONResponse, Response +from typing import Literal + from pydantic import BaseModel, Field from worker.client import Worker from . import __version__ +from .chats import ChatStore, account_key from .config import Config, check_coordinator_url, clamp_settings OLLAMA = "http://127.0.0.1:11434" @@ -52,6 +55,18 @@ class PullIn(BaseModel): model: str = Field(min_length=1, max_length=80) +class ChatMessage(BaseModel): + role: Literal["user", "assistant"] + content: str = Field(max_length=100_000) + model: str | None = Field(default=None, max_length=80) + + +class ChatIn(BaseModel): + title: str = Field(default="", max_length=500) + model: str = Field(default="", max_length=80) + messages: list[ChatMessage] = Field(max_length=500) + + class WorkerRunner: """Runs worker.client.Worker as an asyncio task; restarts on settings changes.""" @@ -257,6 +272,45 @@ async def settings(values: dict): await runner.apply() return {"settings": merged, "worker": runner.status()} + # ------------------------------------------------------------ local AI-chat history + chats = ChatStore(config.dir / "chats") + + def chat_account() -> str: + url, token = require_account() + return account_key(url, config.get("name") or token) + + def chat_body(payload: ChatIn) -> dict: + return {"title": payload.title, "model": payload.model, + "messages": [m.model_dump(exclude_none=True) for m in payload.messages]} + + @app.get("/local/chats") + def list_chats(): + return {"chats": chats.list(chat_account())} + + @app.post("/local/chats", status_code=201) + def create_chat(payload: ChatIn): + return chats.save(chat_account(), None, **chat_body(payload)) + + @app.get("/local/chats/{chat_id}") + def get_chat(chat_id: str): + chat = chats.get(chat_account(), chat_id) + if chat is None: + raise HTTPException(404, "Chat not found") + return chat + + @app.put("/local/chats/{chat_id}") + def update_chat(chat_id: str, payload: ChatIn): + try: + return chats.save(chat_account(), chat_id, **chat_body(payload)) + except (KeyError, ValueError): + raise HTTPException(404, "Chat not found") from None + + @app.delete("/local/chats/{chat_id}") + def delete_chat(chat_id: str): + if not chats.delete(chat_account(), chat_id): + raise HTTPException(404, "Chat not found") + return {"ok": True} + @app.post("/local/ollama/pull") async def pull(payload: PullIn): public = await coordinator("GET", "/api/public/config") diff --git a/projectzero/chats.py b/projectzero/chats.py new file mode 100644 index 0000000..ffb2a11 --- /dev/null +++ b/projectzero/chats.py @@ -0,0 +1,92 @@ +"""Local AI-chat history for the ProjectZero client. + +One JSON file per conversation under ``//.json``. Chats never leave +this computer; like the config file they are written owner-only (POSIX) and replaced atomically. +""" +import hashlib +import json +import os +import re +import secrets +import time +from pathlib import Path + +ID_RE = re.compile(r"^[0-9a-f]{16}$") +TITLE_MAX = 60 + + +def account_key(coordinator_url: str, name: str) -> str: + """Stable, filesystem-safe key so each account (server + name) has its own history.""" + return hashlib.sha256(f"{coordinator_url}\n{name}".encode()).hexdigest()[:16] + + +def _check(value: str) -> str: + if not isinstance(value, str) or not ID_RE.fullmatch(value): + raise ValueError("invalid id") + return value + + +class ChatStore: + def __init__(self, root: Path): + self.root = Path(root) + + def _dir(self, account: str, create: bool = False) -> Path: + path = self.root / _check(account) + if create: + for directory in (self.root, path): + directory.mkdir(parents=True, exist_ok=True) + if os.name == "posix": + os.chmod(directory, 0o700) + return path + + def _read(self, path: Path) -> dict | None: + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + return data if isinstance(data, dict) and data.get("id") == path.stem else None + + def list(self, account: str) -> list[dict]: + directory = self._dir(account) + chats = [] + for path in directory.glob("*.json") if directory.is_dir() else []: + if ID_RE.fullmatch(path.stem) and (chat := self._read(path)): + chats.append({k: chat.get(k) for k in ("id", "title", "model", "created", "updated")}) + return sorted(chats, key=lambda c: c.get("updated") or 0, reverse=True) + + def get(self, account: str, chat_id: str) -> dict | None: + try: + return self._read(self._dir(account) / f"{_check(chat_id)}.json") + except ValueError: + return None + + def save(self, account: str, chat_id: str | None, title: str, model: str, messages: list[dict]) -> dict: + directory = self._dir(account, create=True) + now = time.time() + if chat_id is None: + chat_id, created = secrets.token_hex(8), now + else: + existing = self.get(account, _check(chat_id)) + if existing is None: + raise KeyError(chat_id) + created = existing.get("created", now) + chat = {"id": chat_id, "title": " ".join(title.split())[:TITLE_MAX], "model": model, + "created": created, "updated": now, "messages": messages} + path = directory / f"{chat_id}.json" + tmp = path.with_suffix(".tmp") + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as handle: + json.dump(chat, handle, ensure_ascii=False) + os.replace(tmp, path) + return chat + + def delete(self, account: str, chat_id: str) -> bool: + try: + path = self._dir(account) / f"{_check(chat_id)}.json" + except ValueError: + return False + try: + path.unlink() + return True + except FileNotFoundError: + return False diff --git a/tests/test_chats.py b/tests/test_chats.py new file mode 100644 index 0000000..b795344 --- /dev/null +++ b/tests/test_chats.py @@ -0,0 +1,92 @@ +"""Local AI-chat history store (projectzero/chats.py).""" +import os +import time + +import pytest + +from projectzero.chats import ChatStore, account_key + +A = account_key("http://coord.local:8765", "alice") +B = account_key("http://coord.local:8765", "bob") +MSGS = [{"role": "user", "content": "Hallo"}, {"role": "assistant", "content": "Hi!", "model": "demo-model"}] + + +def test_account_key_is_stable_and_distinct(): + assert A == account_key("http://coord.local:8765", "alice") + assert A != B and A != account_key("http://other.local:8765", "alice") + assert len(A) == 16 and all(c in "0123456789abcdef" for c in A) + + +def test_save_get_roundtrip_and_update(tmp_path): + store = ChatStore(tmp_path) + chat = store.save(A, None, "Hallo", "demo-model", MSGS[:1]) + assert len(chat["id"]) == 16 and chat["created"] == chat["updated"] + again = store.save(A, chat["id"], "Hallo", "demo-model", MSGS) + assert again["id"] == chat["id"] and again["created"] == chat["created"] + loaded = store.get(A, chat["id"]) + assert loaded["messages"] == MSGS and loaded["model"] == "demo-model" and loaded["title"] == "Hallo" + + +def test_list_newest_first_without_messages(tmp_path): + store = ChatStore(tmp_path) + first = store.save(A, None, "eins", "demo-model", MSGS) + time.sleep(0.01) + second = store.save(A, None, "zwei", "demo-model", MSGS) + listed = store.list(A) + assert [c["id"] for c in listed] == [second["id"], first["id"]] + assert "messages" not in listed[0] and listed[0]["title"] == "zwei" + time.sleep(0.01) + store.save(A, first["id"], "eins", "demo-model", MSGS + MSGS) # continuing moves it to the top + assert store.list(A)[0]["id"] == first["id"] + + +def test_accounts_are_isolated(tmp_path): + store = ChatStore(tmp_path) + chat = store.save(A, None, "geheim", "demo-model", MSGS) + assert store.list(B) == [] and store.get(B, chat["id"]) is None + assert store.delete(B, chat["id"]) is False and store.get(A, chat["id"]) is not None + + +def test_delete(tmp_path): + store = ChatStore(tmp_path) + chat = store.save(A, None, "weg", "demo-model", MSGS) + assert store.delete(A, chat["id"]) is True + assert store.get(A, chat["id"]) is None and store.list(A) == [] + assert store.delete(A, chat["id"]) is False + + +@pytest.mark.parametrize("bad", ["../../config", "x" * 16, "ABCDEF0123456789", "", "0123456789abcde", "/etc/passwd"]) +def test_invalid_ids_are_rejected(tmp_path, bad): + store = ChatStore(tmp_path) + assert store.get(A, bad) is None and store.delete(A, bad) is False + with pytest.raises(ValueError): + store.save(A, bad, "t", "demo-model", MSGS) + with pytest.raises(ValueError): + store.list("../" + A) + + +def test_save_with_unknown_valid_id_is_rejected(tmp_path): + with pytest.raises(KeyError): + ChatStore(tmp_path).save(A, "0123456789abcdef", "t", "demo-model", MSGS) + + +def test_corrupt_file_is_skipped(tmp_path): + store = ChatStore(tmp_path) + good = store.save(A, None, "ok", "demo-model", MSGS) + (tmp_path / A / "fedcba9876543210.json").write_text("{not json") + assert [c["id"] for c in store.list(A)] == [good["id"]] + assert store.get(A, "fedcba9876543210") is None + + +def test_title_is_trimmed(tmp_path): + chat = ChatStore(tmp_path).save(A, None, " " + "x" * 200 + " ", "demo-model", MSGS) + assert chat["title"] == "x" * 60 + + +@pytest.mark.skipif(os.name != "posix", reason="POSIX permissions") +def test_files_are_owner_only(tmp_path): + store = ChatStore(tmp_path / "chats") + chat = store.save(A, None, "t", "demo-model", MSGS) + assert (tmp_path / "chats" / A / f"{chat['id']}.json").stat().st_mode & 0o777 == 0o600 + assert (tmp_path / "chats" / A).stat().st_mode & 0o777 == 0o700 + assert (tmp_path / "chats").stat().st_mode & 0o777 == 0o700 diff --git a/tests/test_client_app.py b/tests/test_client_app.py index 56ed107..41b902d 100644 --- a/tests/test_client_app.py +++ b/tests/test_client_app.py @@ -117,3 +117,49 @@ def test_clamp_settings_and_private_config_file(tmp_path): if os.name == "posix" and probe.stat().st_mode & 0o077 == 0: # some mounts (fuseblk) ignore chmod assert (config.path.stat().st_mode & 0o077) == 0 assert Config(tmp_path / "c").get("user_token") == "cag_usr_secret" + + +def test_chat_history_endpoints(stack): + client, config, _ = stack + client.post("/local/connect", json={"coordinator_url": COORD}) + assert client.get("/local/chats").status_code == 409 # not signed in yet + client.post("/local/register", json={"name": "carol"}) + assert client.get("/local/chats").json() == {"chats": []} + + msgs = [{"role": "user", "content": "Erzähl mir was"}] + created = client.post("/local/chats", json={"title": "Erzähl mir was", "model": "demo-model", "messages": msgs}) + assert created.status_code == 201, created.text + chat_id = created.json()["id"] + msgs.append({"role": "assistant", "content": "Es war einmal ...", "model": "demo-model"}) + updated = client.put(f"/local/chats/{chat_id}", json={"title": "Erzähl mir was", "model": "demo-model", + "messages": msgs}) + assert updated.status_code == 200 and updated.json()["id"] == chat_id + assert client.get(f"/local/chats/{chat_id}").json()["messages"] == msgs + listed = client.get("/local/chats").json()["chats"] + assert [c["id"] for c in listed] == [chat_id] and "messages" not in listed[0] + files = list((config.dir / "chats").rglob("*.json")) + assert len(files) == 1 and "carol" not in str(files[0]) # account dir is a hash, not the name + + assert client.get("/local/chats/0123456789abcdef").status_code == 404 + assert client.get("/local/chats/..%2F..%2Fconfig").status_code == 404 + assert client.put("/local/chats/0123456789abcdef", json={"title": "x", "model": "m", "messages": msgs} + ).status_code == 404 + assert client.post("/local/chats", json={"title": "x", "model": "m", + "messages": [{"role": "system", "content": "x"}]}).status_code == 422 + assert client.post("/local/chats", json={"title": "x", "model": "m", + "messages": [{"role": "user", "content": "x"}] * 501}).status_code == 422 + assert client.get("/local/chats", headers={"X-PZ-Session": "wrong"}).status_code == 403 + + # another account on the same computer does not see carol's chats; logging back in does + client.post("/local/logout") # also forgets the server address + client.post("/local/connect", json={"coordinator_url": COORD}) + client.post("/local/register", json={"name": "dave"}) + assert client.get("/local/chats").json() == {"chats": []} + assert client.get(f"/local/chats/{chat_id}").status_code == 404 + client.post("/local/logout") + config.update(coordinator_url=COORD, user_token="ignored", name="carol") # same server + name = same history + assert [c["id"] for c in client.get("/local/chats").json()["chats"]] == [chat_id] + + assert client.delete(f"/local/chats/{chat_id}").json() == {"ok": True} + assert client.delete(f"/local/chats/{chat_id}").status_code == 404 + assert client.get("/local/chats").json() == {"chats": []} From 6c591188d8afee097064e9225c67866aca25320b Mon Sep 17 00:00:00 2001 From: maun200 <18380842+maun200@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:55:26 +0100 Subject: [PATCH 2/3] Show saved AI chats in the sidebar and continue them The AI chat now lists previous conversations (newest first) under the AI chat entry, saves after every question and answer, reopens a chat with its model, and offers New chat / delete. A reply that arrives after switching chats is stored in the chat it belongs to. Also tolerate job status responses without lifecycle events (older coordinators) instead of failing the request. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014XvdYnpnYBSTkq2tBgQTA3 --- projectzero/static/index.html | 46 ++++++++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 11 deletions(-) diff --git a/projectzero/static/index.html b/projectzero/static/index.html index e30e347..47ee052 100644 --- a/projectzero/static/index.html +++ b/projectzero/static/index.html @@ -36,6 +36,11 @@ nav li button{width:100%;text-align:left;border:0;background:none;padding:.4rem .5rem;border-radius:6px;display:flex;gap:.4rem;align-items:center;justify-content:space-between} nav li button[aria-current="true"]{background:var(--mine);font-weight:600} nav li button:hover{background:var(--soft)} +nav li.chat{display:flex;align-items:center} +nav li.chat>button:first-child{flex:1;min-width:0} +nav li.chat .label span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +nav li.chat .chat-del{width:auto;padding:.2rem .45rem;opacity:.35;color:var(--muted)} +nav li.chat:hover .chat-del,nav li.chat .chat-del:focus{opacity:1} .badge{background:var(--accent);color:var(--accent-text);border-radius:999px;font-size:.72rem;padding:0 .4rem} .muted{color:var(--muted)} main{display:flex;flex-direction:column;min-width:0;min-height:0} @@ -120,6 +125,7 @@