Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ All notable changes to this project are documented here. The format follows

## [Unreleased]

### Added

- Desktop app: AI-chat history. Every conversation is saved locally by the app (one owner-only
JSON file per chat under `<config>/chats/<account-key>/`, never sent to the coordinator) and
listed under "Previous chats" in the sidebar, newest first. Opening a chat restores its
messages and model so you can continue it; "+" starts a new chat, "×" deletes one. Chats are
kept per account (server + name) and survive sign-out. New endpoints: `GET/POST /local/chats`,
`GET/PUT/DELETE /local/chats/{id}`.

### Changed

- Desktop app: a finished AI answer now reveals word by word (a short "typing" animation,
Expand All @@ -14,6 +23,10 @@ All notable changes to this project are documented here. The format follows

### Fixed

- Desktop app: an AI request failed with "s.events is undefined" when the coordinator was older
than the app and returned job status without the lifecycle `events` list. The app now treats a
missing list as empty.

- Desktop app: changing "Model on this device" snapped back to the old value and never actually
saved. `fillMachineModels()` reset the `<select>` to the server's last-known model on every
call, including the one the model-change handler itself made before saving the new value —
Expand Down
54 changes: 54 additions & 0 deletions projectzero/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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."""

Expand Down Expand Up @@ -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")
Expand Down
92 changes: 92 additions & 0 deletions projectzero/chats.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
"""Local AI-chat history for the ProjectZero client.

One JSON file per conversation under ``<root>/<account-key>/<chat-id>.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
Loading
Loading