From 9fed45c0852cf7e945a2fd9754439a4dbfeb9301 Mon Sep 17 00:00:00 2001 From: maun200 <18380842+maun200@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:50:40 +0100 Subject: [PATCH 1/2] Add a per-job lifecycle log and live status in the AI chat Users had no visibility into what was actually happening with a pending chat request beyond a static "waiting..."/"computing..." label, which was confusing when a job sat queued because no worker served the chosen model, or silently retried after a worker failure. GET /api/jobs/{id} now returns `events` (queued/claimed/requeued/completed/ failed/cancelled, each timestamped and naming the worker where relevant) and `available_workers` (online operator-approved workers for this job's model/privacy). Worker identity is resolved from id to display name at read time and only ever shown to the job's own owner. The desktop app's chat renders this live under the pending answer instead of the old static label. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_014XvdYnanfEU1LisNWNpubA --- CHANGELOG.md | 7 +++ coordinator/app/database.py | 2 + coordinator/app/main.py | 66 +++++++++++++++++++--- projectzero/static/index.html | 34 +++++++++--- tests/test_job_events.py | 101 ++++++++++++++++++++++++++++++++++ 5 files changed, 194 insertions(+), 16 deletions(-) create mode 100644 tests/test_job_events.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e7b4f7..56b2a75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ All notable changes to this project are documented here. The format follows ### Added +- `GET /api/jobs/{id}` now reports a lifecycle log (`events`: queued/claimed/requeued/ + completed/failed/cancelled, each with a timestamp and, where relevant, the worker's display + name and error) and `available_workers` (how many online, operator-approved workers could + currently take this job). The desktop app's AI chat shows this live under the pending answer — + which machine is working on it, retries, or that nobody is online for the chosen model yet — + instead of a static "waiting..."/"computing..." label. Worker identity is only ever shown to + the job's own owner, for their own request. - `grid_device.py update --model ` and a matching coordinator endpoint (`POST /api/admin/workers/{id}/model`) to move a device to a different operator-approved model in place — no new worker token, no new bundle to carry to the device, trust level and diff --git a/coordinator/app/database.py b/coordinator/app/database.py index 0ed68b4..c07ffc6 100644 --- a/coordinator/app/database.py +++ b/coordinator/app/database.py @@ -84,6 +84,8 @@ def initialize(self, demo_key: str, initial_credits: int): add_column_if_missing(db, "users", "created_at", "TEXT") add_column_if_missing(db, "users", "last_active", "TEXT") add_column_if_missing(db, "workers", "owner_id", "TEXT") + # v0.4: per-job lifecycle log, so a requester can see what's happening with their request. + add_column_if_missing(db, "jobs", "events_json", "TEXT NOT NULL DEFAULT '[]'") db.executescript(""" CREATE UNIQUE INDEX IF NOT EXISTS users_name_idx ON users(name COLLATE NOCASE) WHERE name IS NOT NULL; CREATE TABLE IF NOT EXISTS invites ( diff --git a/coordinator/app/main.py b/coordinator/app/main.py index 6620d8b..69e2784 100644 --- a/coordinator/app/main.py +++ b/coordinator/app/main.py @@ -51,21 +51,45 @@ def client_ip(request: Request) -> str: return request.client.host if request.client else "unknown" +def append_event(db: sqlite3.Connection, job_id: str, type_: str, worker_id: str | None = None, + error: str | None = None) -> None: + """Append one lifecycle event to a job's event log, for the requester's own status display. + + Keeps only worker ids (resolved to names at read time, see job_status()) so a removed/renamed + worker never leaves a stale name baked into history. Must run inside an open write transaction. + """ + row = db.execute("SELECT events_json FROM jobs WHERE id=?", (job_id,)).fetchone() + if row is None: + return + events = json.loads(row["events_json"] or "[]") + event: dict = {"t": ts(), "type": type_} + if worker_id: + event["worker_id"] = worker_id + if error: + event["error"] = error[:200] + events.append(event) + db.execute("UPDATE jobs SET events_json=? WHERE id=?", (json.dumps(events[-20:]), job_id)) + + def requeue_or_fail(db: sqlite3.Connection, job: sqlite3.Row, error: str, timestamp: str, refund_note: str) -> Literal["queued", "failed"]: """Give a job back to the queue, or fail and refund it once attempts are exhausted. - Must run inside an open write transaction. + `job` must include `assigned_worker` (e.g. from `SELECT *`) so the failing worker can be + recorded on the event log. Must run inside an open write transaction. """ + worker_id = job["assigned_worker"] if "assigned_worker" in job.keys() else None if job["attempts"] < MAX_ATTEMPTS: db.execute("""UPDATE jobs SET status='queued',error=?,assigned_worker=NULL,lease_hash=NULL, lease_until=NULL,updated_at=? WHERE id=?""", (error[:500], timestamp, job["id"])) + append_event(db, job["id"], "requeued", worker_id=worker_id, error=error) return "queued" db.execute("""UPDATE jobs SET status='failed',error=?,lease_hash=NULL, lease_until=NULL,updated_at=? WHERE id=?""", (error[:500], timestamp, job["id"])) db.execute("UPDATE users SET credits=credits+? WHERE id=?", (job["reservation"], job["user_id"])) db.execute("INSERT INTO ledger(actor_type,actor_id,delta,job_id,note,created_at) VALUES ('user',?,?,?,?,?)", (job["user_id"], job["reservation"], job["id"], refund_note, timestamp)) + append_event(db, job["id"], "failed", worker_id=worker_id, error=error) return "failed" @@ -74,8 +98,9 @@ def release_expired(db: sqlite3.Connection, timestamp: str): Must run inside an open write transaction. """ - expired = db.execute("SELECT id,user_id,reservation,attempts FROM jobs WHERE status='running' AND lease_until<=?", - (timestamp,)).fetchall() + expired = db.execute( + "SELECT id,user_id,reservation,attempts,assigned_worker FROM jobs WHERE status='running' AND lease_until<=?", + (timestamp,)).fetchall() for old in expired: requeue_or_fail(db, old, "Worker lease expired", timestamp, "refund_expired_job") @@ -96,6 +121,7 @@ def expire_stale_queued(db: sqlite3.Connection, timestamp: str, cutoff: str) -> db.execute("UPDATE users SET credits=credits+? WHERE id=?", (job["reservation"], job["user_id"])) db.execute("INSERT INTO ledger(actor_type,actor_id,delta,job_id,note,created_at) VALUES ('user',?,?,?,'refund_queue_timeout',?)", (job["user_id"], job["reservation"], job["id"], timestamp)) + append_event(db, job["id"], "failed", error="Queue timeout: no matching worker") return len(stale) @@ -405,10 +431,11 @@ def submit(payload: JobIn, identity: str = Depends(user)): if change.rowcount != 1: db.rollback() raise HTTPException(status_code=402, detail="Insufficient demo credits") - db.execute("""INSERT INTO jobs(id,user_id,model,messages_json,privacy,max_output_tokens,status,created_at,updated_at,reservation) - VALUES (?,?,?,?,?,?,'queued',?,?,?)""", + db.execute("""INSERT INTO jobs(id,user_id,model,messages_json,privacy,max_output_tokens,status, + created_at,updated_at,reservation,events_json) VALUES (?,?,?,?,?,?,'queued',?,?,?,?)""", (ident, identity, payload.model, json.dumps([m.model_dump() for m in payload.messages]), - payload.privacy, payload.max_output_tokens, timestamp, timestamp, COST)) + payload.privacy, payload.max_output_tokens, timestamp, timestamp, COST, + json.dumps([{"t": timestamp, "type": "queued"}]))) db.execute("INSERT INTO ledger(actor_type,actor_id,delta,job_id,note,created_at) VALUES ('user',?,?,?,'reserved_demo_job',?)", (identity, -COST, ident, timestamp)) db.commit() @@ -422,12 +449,30 @@ def job_status(job_id: str, identity: str = Depends(user)): sweep(db, now(), cfg.queue_timeout_seconds) db.commit() row = db.execute("SELECT * FROM jobs WHERE id=? AND user_id=?", (job_id, identity)).fetchone() - if row is None: - raise HTTPException(404, "Job not found") + if row is None: + raise HTTPException(404, "Job not found") + # How many currently-online workers could even take this job, for "nobody is listening yet" vs + # "queued behind other work" - not who they are, which stays scoped to this job's own events. + online_cutoff = ts(now() - timedelta(seconds=community.ONLINE_SECONDS)) + available_workers = db.execute( + """SELECT COUNT(*) c FROM workers WHERE model=? AND revoked_at IS NULL AND last_seen>? + AND (?='community' OR trust_level='trusted')""", + (row["model"], online_cutoff, row["privacy"])).fetchone()["c"] + events = json.loads(row["events_json"] or "[]") + worker_ids = {e["worker_id"] for e in events if e.get("worker_id")} + names = {} + if worker_ids: + placeholders = ",".join("?" * len(worker_ids)) + names = {r["id"]: r["name"] for r in db.execute( + f"SELECT id,name FROM workers WHERE id IN ({placeholders})", tuple(worker_ids))} + resolved_events = [{"t": e["t"], "type": e["type"], + **({"worker": names.get(e["worker_id"], "removed worker")} if e.get("worker_id") else {}), + **({"error": e["error"]} if e.get("error") else {})} for e in events] return {"id": row["id"], "status": row["status"], "model": row["model"], "privacy": row["privacy"], "attempts": row["attempts"], "output": json.loads(row["result_json"]) if row["result_json"] else None, - "error": row["error"] if row["status"] in ("failed", "cancelled") else None} + "error": row["error"] if row["status"] in ("failed", "cancelled") else None, + "available_workers": available_workers, "events": resolved_events} @app.post("/api/jobs/{job_id}/cancel") def cancel(job_id: str, identity: str = Depends(user)): @@ -448,6 +493,7 @@ def cancel(job_id: str, identity: str = Depends(user)): db.execute("UPDATE users SET credits=credits+? WHERE id=?", (row["reservation"], identity)) db.execute("INSERT INTO ledger(actor_type,actor_id,delta,job_id,note,created_at) VALUES ('user',?,?,?,'refund_cancelled_job',?)", (identity, row["reservation"], job_id, timestamp)) + append_event(db, job_id, "cancelled") db.commit() return {"id": job_id, "status": "cancelled", "refunded": row["reservation"]} @@ -673,6 +719,7 @@ def claim(w: sqlite3.Row = Depends(worker)): attempts=attempts+1,updated_at=? WHERE id=?""", (w["id"], digest(lease), ts(current + timedelta(seconds=cfg.lease_seconds)), timestamp, chosen["id"])) db.execute("UPDATE workers SET last_seen=? WHERE id=?", (timestamp, w["id"])) + append_event(db, chosen["id"], "claimed", worker_id=w["id"]) db.commit() return {"job": {"id": chosen["id"], "model": chosen["model"], "messages": json.loads(chosen["messages_json"]), @@ -708,6 +755,7 @@ def complete(payload: Completion, w: sqlite3.Row = Depends(worker)): db.execute("UPDATE workers SET provisional_credits=provisional_credits+? WHERE id=?", (COST, w["id"])) db.execute("INSERT INTO ledger(actor_type,actor_id,delta,job_id,note,created_at) VALUES ('worker',?,?,?,'unverified_provisional_reward',?)", (w["id"], COST, payload.job_id, timestamp)) + append_event(db, payload.job_id, "completed", worker_id=w["id"]) else: requeue_or_fail(db, chosen, payload.error, timestamp, "refund_failed_job") db.commit() diff --git a/projectzero/static/index.html b/projectzero/static/index.html index 0f6c86b..a013f4c 100644 --- a/projectzero/static/index.html +++ b/projectzero/static/index.html @@ -50,6 +50,8 @@ .msg pre.code code{background:none;padding:0} .msg .who{font-size:.78rem;color:var(--muted);margin-bottom:.15rem} .msg.system{align-self:center;background:none;border:0;color:var(--muted);font-size:.88rem;text-align:center} +.pending-timeline{font-size:.76rem;color:var(--muted);margin-top:.2rem;display:flex;flex-direction:column;gap:.1rem} +.pending-timeline .ev-failed,.pending-timeline .ev-requeued{color:var(--warn)} .composer{display:flex;gap:.5rem;padding:.75rem 1rem;border-top:1px solid var(--line);background:var(--panel)} .composer textarea{resize:none;height:3rem} aside{background:var(--panel);border-left:1px solid var(--line);overflow:auto;padding:1rem;display:flex;flex-direction:column;gap:1rem} @@ -220,9 +222,11 @@

const $=id=>document.getElementById(id); const I18N={ en:{notConnected:"not connected",account:"Account",langSwitch:"Switch language",themeSwitch:"Switch colour theme",view:"View",tabChannels:"Channels",tabChat:"Chat",tabCredits:"Credits",channels:"Channels",aiChat:"AI chat",rooms:"Rooms",groups:"Groups",direct:"Direct",newGroup:"New group",newDirect:"New direct message",onlineNow:"Online now",model:"Model",whoProcesses:"Who may process the request",privCommunity:"Community machines",privTrusted:"Trusted machines only",addMember:"Add member",leave:"Leave",message:"Message",composerHint:"Write a message... (Enter to send, Shift+Enter for a new line)",send:"Send",creditsAndCompute:"Credits and your computing power",yourCredits:"Your credits",provisional:"provisional (not yet released)",autoCredited:"credited automatically",costPerAnswer:"cost per AI answer",creditsNote:"Credits are play money for sharing compute time: not money, not transferable.",myCompute:"My computing power",shareCompute:"Share computing power",status:"Status",jobsDone:"jobs completed",deviceName:"Device name (visible to others)",deviceNameHint:"e.g. Living-room-PC",deviceModel:"Model on this device",execution:"Execution",backendOllama:"Ollama (real AI)",backendMock:"Demo (no AI, for testing)",cpuThreads:"CPU threads",gpuLayers:"GPU layers",maxAnswer:"max. answer length (tokens)",context:"context (tokens)",sliderNote:"More threads/GPU = faster, but your computer gets warmer and louder. Changes apply immediately.",goodToKnow:"Good to know",privacyNote:"Chats and AI requests are stored unencrypted on the server, and the computing machine can read your request. Do not enter personal or secret data.",welcome:"Welcome to ProjectZero",whichServer:"Which server do you want to connect to?",serverAddress:"Server address",serverHint:"Plain http is fine inside your own network (e.g. http://192.168.1.10:8765); on the internet use https only.",next:"Next",registerTab:"Create account",loginTab:"I already have an account",displayName:"Display name (3-24 characters: letters, digits, - and _)",inviteCode:"Invite code",accessKey:"Your access key (starts with cag_usr_)",back:"Back",letsGo:"Let's go",keyWarning:"Your access key is your login. Anyone who has it can spend your credits. Never share it.",showKey:"Show key (for a second device)",changeServer:"Change server",signOut:"Sign out",close:"Close", - themeSystem:"System",themeLight:"Light",themeDark:"Anthracite",regOff:"Self-registration is switched off on this server. Ask the operator for access.",regInfo:"You start with {credits} credits. One AI answer costs {cost}.",signedIn:"Signed in. Have fun!",signedInAs:"Signed in as {name} on {server}",notSignedIn:"Not signed in",noName:"(no name)",confirmLogout:"Sign out? Without your access key you cannot get back into this account.",off:"off",computing:"computing...",noConnection:"no connection",ready:"ready",stopped:"stopped",mockNote:"Demo mode: answers are placeholders, not AI.",ollamaFound:"Ollama found ({n} models installed).",ollamaMissing:"Ollama not found. Install it from ollama.com to run real AI jobs.",downloading:"Downloading...",downloadModel:"Download model",available:"available",nobodyOnline:"nobody online right now",machinesPeople:"{m} {mWord} - {p} {pWord} active",machine1:"machine",machineN:"machines",person1:"person",personN:"people",dm:"Direct message",by:"by",aiEmpty:"Ask the AI something. Every answer costs credits and is computed by a machine in the network.",you:"You",ai:"AI",lobbyEmpty:"The lobby is the room for everyone. Say hello!",noMessages:"No messages yet.",error:"Error",whoDm:"Who do you want to write to? (display name)",groupName:"Group name",groupMembers:"Members (names separated by commas, optional)",whoAdd:"Who should be added? (display name)",confirmLeave:"Leave this group?",consent:"Your question will be computed by an unknown community machine that can read the text. No personal data! Continue?",sending:"Sending to a machine in the network...",waiting:"Waiting for a free machine...",working:"A machine is computing...",noAnswer:"No answer: {reason} (credits were refunded)",tooLong:"This is taking unusually long. Please try again later.",myComputer:"My-Computer",appUnreachable:"Local app not reachable: {msg}",new:"new"}, + themeSystem:"System",themeLight:"Light",themeDark:"Anthracite",regOff:"Self-registration is switched off on this server. Ask the operator for access.",regInfo:"You start with {credits} credits. One AI answer costs {cost}.",signedIn:"Signed in. Have fun!",signedInAs:"Signed in as {name} on {server}",notSignedIn:"Not signed in",noName:"(no name)",confirmLogout:"Sign out? Without your access key you cannot get back into this account.",off:"off",computing:"computing...",noConnection:"no connection",ready:"ready",stopped:"stopped",mockNote:"Demo mode: answers are placeholders, not AI.",ollamaFound:"Ollama found ({n} models installed).",ollamaMissing:"Ollama not found. Install it from ollama.com to run real AI jobs.",downloading:"Downloading...",downloadModel:"Download model",available:"available",nobodyOnline:"nobody online right now",machinesPeople:"{m} {mWord} - {p} {pWord} active",machine1:"machine",machineN:"machines",person1:"person",personN:"people",dm:"Direct message",by:"by",aiEmpty:"Ask the AI something. Every answer costs credits and is computed by a machine in the network.",you:"You",ai:"AI",lobbyEmpty:"The lobby is the room for everyone. Say hello!",noMessages:"No messages yet.",error:"Error",whoDm:"Who do you want to write to? (display name)",groupName:"Group name",groupMembers:"Members (names separated by commas, optional)",whoAdd:"Who should be added? (display name)",confirmLeave:"Leave this group?",consent:"Your question will be computed by an unknown community machine that can read the text. No personal data! Continue?",sending:"Sending to a machine in the network...",waiting:"Waiting for a free machine...",working:"A machine is computing...",noAnswer:"No answer: {reason} (credits were refunded)",tooLong:"This is taking unusually long. Please try again later.",myComputer:"My-Computer",appUnreachable:"Local app not reachable: {msg}",new:"new", + waitingCount:"Waiting for a free machine... ({n} online for this model)",waitingNone:"Waiting... nobody is online for this model right now",workingNamed:"{worker} is computing...",evQueued:"Queued",evClaimed:"{worker} picked it up",evRequeued:"{worker} couldn't finish it, retrying...",evCompleted:"{worker} finished it",evFailedBy:"{worker} failed: {error}",evFailed:"Failed: {error}",evCancelled:"Cancelled"}, de:{notConnected:"nicht verbunden",account:"Konto",langSwitch:"Sprache wechseln",themeSwitch:"Farbschema wechseln",view:"Ansicht",tabChannels:"Kanäle",tabChat:"Chat",tabCredits:"Credits",channels:"Kanäle",aiChat:"KI-Chat",rooms:"Räume",groups:"Gruppen",direct:"Direkt",newGroup:"Neue Gruppe",newDirect:"Neue Direktnachricht",onlineNow:"Gerade online",model:"Modell",whoProcesses:"Wer darf die Anfrage verarbeiten",privCommunity:"Community-Maschinen",privTrusted:"Nur vertrauenswürdige Maschinen",addMember:"Mitglied hinzufügen",leave:"Verlassen",message:"Nachricht",composerHint:"Nachricht schreiben ... (Enter senden, Shift+Enter neue Zeile)",send:"Senden",creditsAndCompute:"Credits und eigene Rechenleistung",yourCredits:"Deine Credits",provisional:"vorläufig (noch nicht freigegeben)",autoCredited:"automatisch gutgeschrieben",costPerAnswer:"Kosten pro KI-Antwort",creditsNote:"Credits sind Spielgeld für die Verteilung von Rechenzeit: kein Geld, nicht übertragbar.",myCompute:"Meine Rechenleistung",shareCompute:"Rechenleistung teilen",status:"Status",jobsDone:"erledigte Aufgaben",deviceName:"Gerätename (für andere sichtbar)",deviceNameHint:"z. B. Wohnzimmer-PC",deviceModel:"Modell auf diesem Gerät",execution:"Ausführung",backendOllama:"Ollama (echte KI)",backendMock:"Demo (ohne KI, zum Testen)",cpuThreads:"CPU-Threads",gpuLayers:"GPU-Schichten",maxAnswer:"max. Antwortlänge (Tokens)",context:"Kontext (Tokens)",sliderNote:"Mehr Threads/GPU = schneller, aber dein Rechner wird wärmer und lauter. Änderungen gelten sofort.",goodToKnow:"Gut zu wissen",privacyNote:"Chats und KI-Anfragen liegen unverschlüsselt auf dem Server, und die rechnende Maschine sieht deine Anfrage. Keine persönlichen oder geheimen Daten eingeben.",welcome:"Willkommen bei ProjectZero",whichServer:"Mit welchem Server möchtest du dich verbinden?",serverAddress:"Server-Adresse",serverHint:"Im eigenen Netz geht http (z. B. http://192.168.1.10:8765), im Internet nur https.",next:"Weiter",registerTab:"Neu registrieren",loginTab:"Ich habe schon ein Konto",displayName:"Anzeigename (3-24 Zeichen: Buchstaben, Ziffern, - und _)",inviteCode:"Einladungscode",accessKey:"Dein Zugangsschlüssel (beginnt mit cag_usr_)",back:"Zurück",letsGo:"Los geht's",keyWarning:"Dein Zugangsschlüssel ist dein Login. Wer ihn hat, kann deine Credits ausgeben. Niemals weitergeben.",showKey:"Schlüssel anzeigen (für ein zweites Gerät)",changeServer:"Server wechseln",signOut:"Abmelden",close:"Schließen", - themeSystem:"System",themeLight:"Hell",themeDark:"Anthrazit",regOff:"Auf diesem Server ist Selbst-Registrierung ausgeschaltet. Frag den Betreiber nach einem Zugang.",regInfo:"Du startest mit {credits} Credits. Eine KI-Antwort kostet {cost}.",signedIn:"Angemeldet. Viel Spaß!",signedInAs:"Angemeldet als {name} bei {server}",notSignedIn:"Nicht angemeldet",noName:"(ohne Namen)",confirmLogout:"Abmelden? Ohne deinen Zugangsschlüssel kommst du nicht wieder in dieses Konto.",off:"aus",computing:"rechnet ...",noConnection:"keine Verbindung",ready:"bereit",stopped:"gestoppt",mockNote:"Demo-Modus: Antworten sind Platzhalter, keine KI.",ollamaFound:"Ollama gefunden ({n} Modelle installiert).",ollamaMissing:"Ollama nicht gefunden. Installiere es von ollama.com, um echte KI-Aufgaben zu rechnen.",downloading:"Wird heruntergeladen ...",downloadModel:"Modell herunterladen",available:"verfügbar",nobodyOnline:"gerade niemand online",machinesPeople:"{m} {mWord} - {p} {pWord} aktiv",machine1:"Maschine",machineN:"Maschinen",person1:"Mensch",personN:"Menschen",dm:"Direktnachricht",by:"von",aiEmpty:"Stell der KI eine Frage. Jede Antwort kostet Credits und wird von einer Maschine im Netz berechnet.",you:"Du",ai:"KI",lobbyEmpty:"Die Lobby ist der Raum für alle. Sag hallo!",noMessages:"Noch keine Nachrichten.",error:"Fehler",whoDm:"Mit wem möchtest du schreiben? (Anzeigename)",groupName:"Name der Gruppe",groupMembers:"Mitglieder (Namen mit Komma getrennt, optional)",whoAdd:"Wen hinzufügen? (Anzeigename)",confirmLeave:"Gruppe verlassen?",consent:"Deine Frage wird von einer fremden Community-Maschine berechnet, die den Text lesen kann. Keine persönlichen Daten! Fortfahren?",sending:"Wird an eine Maschine im Netz gesendet ...",waiting:"Wartet auf eine freie Maschine ...",working:"Eine Maschine rechnet ...",noAnswer:"Keine Antwort: {reason} (Credits wurden erstattet)",tooLong:"Das dauert ungewöhnlich lange. Versuch es später erneut.",myComputer:"Mein-Rechner",appUnreachable:"Lokale App nicht erreichbar: {msg}",new:"neu"}}; + themeSystem:"System",themeLight:"Hell",themeDark:"Anthrazit",regOff:"Auf diesem Server ist Selbst-Registrierung ausgeschaltet. Frag den Betreiber nach einem Zugang.",regInfo:"Du startest mit {credits} Credits. Eine KI-Antwort kostet {cost}.",signedIn:"Angemeldet. Viel Spaß!",signedInAs:"Angemeldet als {name} bei {server}",notSignedIn:"Nicht angemeldet",noName:"(ohne Namen)",confirmLogout:"Abmelden? Ohne deinen Zugangsschlüssel kommst du nicht wieder in dieses Konto.",off:"aus",computing:"rechnet ...",noConnection:"keine Verbindung",ready:"bereit",stopped:"gestoppt",mockNote:"Demo-Modus: Antworten sind Platzhalter, keine KI.",ollamaFound:"Ollama gefunden ({n} Modelle installiert).",ollamaMissing:"Ollama nicht gefunden. Installiere es von ollama.com, um echte KI-Aufgaben zu rechnen.",downloading:"Wird heruntergeladen ...",downloadModel:"Modell herunterladen",available:"verfügbar",nobodyOnline:"gerade niemand online",machinesPeople:"{m} {mWord} - {p} {pWord} aktiv",machine1:"Maschine",machineN:"Maschinen",person1:"Mensch",personN:"Menschen",dm:"Direktnachricht",by:"von",aiEmpty:"Stell der KI eine Frage. Jede Antwort kostet Credits und wird von einer Maschine im Netz berechnet.",you:"Du",ai:"KI",lobbyEmpty:"Die Lobby ist der Raum für alle. Sag hallo!",noMessages:"Noch keine Nachrichten.",error:"Fehler",whoDm:"Mit wem möchtest du schreiben? (Anzeigename)",groupName:"Name der Gruppe",groupMembers:"Mitglieder (Namen mit Komma getrennt, optional)",whoAdd:"Wen hinzufügen? (Anzeigename)",confirmLeave:"Gruppe verlassen?",consent:"Deine Frage wird von einer fremden Community-Maschine berechnet, die den Text lesen kann. Keine persönlichen Daten! Fortfahren?",sending:"Wird an eine Maschine im Netz gesendet ...",waiting:"Wartet auf eine freie Maschine ...",working:"Eine Maschine rechnet ...",noAnswer:"Keine Antwort: {reason} (Credits wurden erstattet)",tooLong:"Das dauert ungewöhnlich lange. Versuch es später erneut.",myComputer:"Mein-Rechner",appUnreachable:"Lokale App nicht erreichbar: {msg}",new:"neu", + waitingCount:"Wartet auf eine freie Maschine ... ({n} online für dieses Modell)",waitingNone:"Wartet ... gerade ist niemand für dieses Modell online",workingNamed:"{worker} rechnet ...",evQueued:"In der Warteschlange",evClaimed:"{worker} hat es übernommen",evRequeued:"{worker} konnte es nicht beenden, wird erneut versucht ...",evCompleted:"{worker} hat es fertig",evFailedBy:"{worker} ist gescheitert: {error}",evFailed:"Gescheitert: {error}",evCancelled:"Abgebrochen"}}; let lang="en";try{lang=localStorage.getItem("pz-lang")||"en"}catch(e){}if(!I18N[lang])lang="en"; function t(key,vars={}){let s=(I18N[lang][key]??I18N.en[key]??key);for(const[k,v]of Object.entries(vars))s=s.replaceAll("{"+k+"}",v);return s} function applyLang(){document.documentElement.lang=lang;$("lang-label").textContent=lang.toUpperCase(); @@ -350,17 +354,33 @@

// ---------------------------------------------------------------- send const sleep=ms=>new Promise(r=>setTimeout(r,ms)); +function eventLabel(e){switch(e.type){ + case"queued":return{text:t("evQueued"),cls:""}; + case"claimed":return{text:t("evClaimed",{worker:e.worker}),cls:""}; + case"requeued":return{text:t("evRequeued",{worker:e.worker}),cls:"ev-requeued"}; + case"completed":return{text:t("evCompleted",{worker:e.worker}),cls:""}; + case"failed":return{text:e.worker?t("evFailedBy",{worker:e.worker,error:e.error||""}):t("evFailed",{error:e.error||""}),cls:"ev-failed"}; + case"cancelled":return{text:t("evCancelled"),cls:""}; + default:return{text:e.type,cls:""}}} +function renderPending(pendingStatus,pendingTimeline,s){ + const lastWorker=[...s.events].reverse().find(e=>e.worker&&e.type!=="requeued"&&e.type!=="failed")?.worker; + pendingStatus.textContent=s.status==="queued"?(s.available_workers>0?t("waitingCount",{n:s.available_workers}):t("waitingNone")): + s.status==="running"?(lastWorker?t("workingNamed",{worker:lastWorker}):t("working")):pendingStatus.textContent; + pendingTimeline.replaceChildren(...s.events.map(e=>{const{text,cls}=eventLabel(e); + return el("div",{class:cls,text:`${new Date(e.t).toLocaleTimeString(lang,{hour:"2-digit",minute:"2-digit",second:"2-digit"})} - ${text}`})}))} async function askAi(text){const model=$("model").value;const privacy=$("privacy").value; let consented=false;try{consented=!!localStorage.getItem("pz-consent")}catch(e){} if(privacy==="community"&&!consented){if(!confirm(t("consent")))return;try{localStorage.setItem("pz-consent","1")}catch(e){}} - state.ai.push({role:"user",content:text});renderAi();const pending=el("div",{class:"msg system",text:t("sending")});$("log").append(pending);scrollLog(); + state.ai.push({role:"user",content:text});renderAi(); + const pendingStatus=el("div",{text:t("sending")});const pendingTimeline=el("div",{class:"pending-timeline"}); + const pending=el("div",{class:"msg system"},pendingStatus,pendingTimeline);$("log").append(pending);scrollLog(); const history=state.ai.slice(-15).map(m=>({role:m.role,content:m.content})); try{const job=await post("/api/jobs",{model,privacy,allow_untrusted:privacy==="community",messages:history,max_output_tokens:256});refreshMe(); - for(let i=0;i<200;i++){await sleep(i<10?1000:3000);const s=await call("/api/jobs/"+job.id);pending.textContent=s.status==="queued"?t("waiting"):t("working"); + for(let i=0;i<200;i++){await sleep(i<10?1000:3000);const s=await call("/api/jobs/"+job.id);renderPending(pendingStatus,pendingTimeline,s); if(s.status==="completed"){state.ai.push({role:"assistant",content:s.output.content,model});renderAi();refreshMe();return} - if(s.status==="failed"||s.status==="cancelled"){pending.textContent=t("noAnswer",{reason:s.error||s.status});refreshMe();return}} - pending.textContent=t("tooLong")} - catch(e){pending.textContent=t("error")+": "+e.message;state.ai.pop()}} + if(s.status==="failed"||s.status==="cancelled"){pendingStatus.textContent=t("noAnswer",{reason:s.error||s.status});refreshMe();return}} + pendingStatus.textContent=t("tooLong")} + catch(e){pendingStatus.textContent=t("error")+": "+e.message;state.ai.pop()}} $("composer").onsubmit=async e=>{e.preventDefault();const text=$("input").value.trim();if(!text)return;$("input").value="";$("send").disabled=true; try{if(state.active==="ai")await askAi(text);else{await post(`/api/channels/${encodeURIComponent(state.active)}/messages`,{body:text});await pollMessages(false)}}catch(err){sysmsg(t("error")+": "+err.message)}finally{$("send").disabled=false;$("input").focus()}}; $("input").addEventListener("keydown",e=>{if(e.key==="Enter"&&!e.shiftKey){e.preventDefault();$("composer").requestSubmit()}}); diff --git a/tests/test_job_events.py b/tests/test_job_events.py new file mode 100644 index 0000000..b3ae8d0 --- /dev/null +++ b/tests/test_job_events.py @@ -0,0 +1,101 @@ +"""Per-job lifecycle log: lets a requester see what is actually happening with their own request +(queued/claimed/completed/requeued/failed/cancelled, and which worker handled it) without +exposing worker identity to anyone but the job's own owner.""" +from datetime import timedelta + +from coordinator.app.main import MAX_ATTEMPTS +from grid_helpers import ADMIN, USER, auth, enroll, enroll_full, freeze_clock, submit + + +def event_types(status: dict) -> list[str]: + return [e["type"] for e in status["events"]] + + +def test_fresh_job_starts_with_a_queued_event_and_no_available_workers(api): + job_id = submit(api).json()["id"] + status = api.get(f"/api/jobs/{job_id}", headers=auth(USER)).json() + assert event_types(status) == ["queued"] + assert status["available_workers"] == 0 + + +def test_available_workers_counts_only_online_matching_workers(api): + enroll(api, "never-polled") # enrollment alone never sets last_seen + job_id = submit(api).json()["id"] + status = api.get(f"/api/jobs/{job_id}", headers=auth(USER)).json() + assert status["available_workers"] == 0 + + +def test_claim_and_complete_record_worker_name_not_id(api): + w = enroll_full(api, "cruncher") + api.post("/api/worker/heartbeat", headers=auth(w["worker_token"]), json={}) + job_id = submit(api).json()["id"] + status = api.get(f"/api/jobs/{job_id}", headers=auth(USER)).json() + assert status["available_workers"] == 1 + job = api.post("/api/worker/claim", headers=auth(w["worker_token"])).json()["job"] + status = api.get(f"/api/jobs/{job_id}", headers=auth(USER)).json() + assert event_types(status) == ["queued", "claimed"] + assert status["events"][1]["worker"] == "cruncher" + assert "worker_id" not in status["events"][1] and w["id"] not in str(status) + api.post("/api/worker/complete", headers=auth(w["worker_token"]), + json={"job_id": job_id, "lease_token": job["lease_token"], "ok": True, "content": "done"}) + status = api.get(f"/api/jobs/{job_id}", headers=auth(USER)).json() + assert event_types(status) == ["queued", "claimed", "completed"] + assert status["events"][2]["worker"] == "cruncher" + + +def test_failed_attempt_is_requeued_then_finally_failed_with_worker_and_error(make_api, monkeypatch): + clock = freeze_clock(monkeypatch) + api = make_api(lease_seconds=60) + w = enroll_full(api, "flaky") + job_id = submit(api).json()["id"] + for _ in range(MAX_ATTEMPTS - 1): # earlier failures requeue, the last one fails for good + job = api.post("/api/worker/claim", headers=auth(w["worker_token"])).json()["job"] + api.post("/api/worker/complete", headers=auth(w["worker_token"]), + json={"job_id": job_id, "lease_token": job["lease_token"], "ok": False, "error": "boom"}) + clock[0] += timedelta(seconds=1) + job = api.post("/api/worker/claim", headers=auth(w["worker_token"])).json()["job"] + api.post("/api/worker/complete", headers=auth(w["worker_token"]), + json={"job_id": job_id, "lease_token": job["lease_token"], "ok": False, "error": "boom"}) + status = api.get(f"/api/jobs/{job_id}", headers=auth(USER)).json() + assert event_types(status) == ["queued", "claimed", "requeued", "claimed", "requeued", "claimed", "failed"] + assert all(e["worker"] == "flaky" for e in status["events"] if e["type"] in ("claimed", "requeued", "failed")) + assert all(e.get("error") == "boom" for e in status["events"] if e["type"] in ("requeued", "failed")) + + +def test_cancelled_job_records_a_cancelled_event(api): + job_id = submit(api).json()["id"] + api.post(f"/api/jobs/{job_id}/cancel", headers=auth(USER)) + status = api.get(f"/api/jobs/{job_id}", headers=auth(USER)).json() + assert event_types(status) == ["queued", "cancelled"] + + +def test_available_workers_respects_trust_and_privacy(api): + trusted = enroll_full(api, "t", trust="trusted") + community_w = enroll_full(api, "c", trust="community") + api.post("/api/worker/heartbeat", headers=auth(trusted["worker_token"]), json={}) + api.post("/api/worker/heartbeat", headers=auth(community_w["worker_token"]), json={}) + trusted_job = submit(api, privacy="trusted").json()["id"] + community_job = submit(api, privacy="community", allow_untrusted=True).json()["id"] + assert api.get(f"/api/jobs/{trusted_job}", headers=auth(USER)).json()["available_workers"] == 1 + assert api.get(f"/api/jobs/{community_job}", headers=auth(USER)).json()["available_workers"] == 2 + + +def test_queue_timeout_records_a_failed_event_without_a_worker(make_api, monkeypatch): + clock = freeze_clock(monkeypatch) + api = make_api(queue_timeout_seconds=60) + job_id = submit(api).json()["id"] + clock[0] += timedelta(seconds=61) + status = api.get(f"/api/jobs/{job_id}", headers=auth(USER)).json() + assert event_types(status) == ["queued", "failed"] + assert "worker" not in status["events"][1] + assert status["events"][1]["error"] == "Queue timeout: no matching worker" + + +def test_revoke_requeues_with_an_event_naming_the_revoked_worker(api): + w = enroll_full(api, "going-away") + job_id = submit(api).json()["id"] + api.post("/api/worker/claim", headers=auth(w["worker_token"])) + api.post(f"/api/admin/workers/{w['id']}/revoke", headers=auth(ADMIN)) + status = api.get(f"/api/jobs/{job_id}", headers=auth(USER)).json() + assert event_types(status) == ["queued", "claimed", "requeued"] + assert status["events"][2]["worker"] == "going-away" and status["events"][2]["error"] == "Worker revoked" From 80ea6b18967c9a484b9c90ab4db45dcc007388f8 Mon Sep 17 00:00:00 2001 From: maun200 <18380842+maun200@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:01:51 +0100 Subject: [PATCH 2/2] Add a bouncing-dots animation to the pending chat status The status line and timeline added for the job lifecycle log were purely textual. Human feedback on a pending request benefits from something visibly moving, not just changing words, so add a small 3-dot bounce animation next to the status text while a job is queued or running, honoring prefers-reduced-motion. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_014XvdYnanfEU1LisNWNpubA --- CHANGELOG.md | 5 +++-- projectzero/static/index.html | 30 +++++++++++++++++++++--------- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 56b2a75..26ef4af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,8 +12,9 @@ All notable changes to this project are documented here. The format follows name and error) and `available_workers` (how many online, operator-approved workers could currently take this job). The desktop app's AI chat shows this live under the pending answer — which machine is working on it, retries, or that nobody is online for the chosen model yet — - instead of a static "waiting..."/"computing..." label. Worker identity is only ever shown to - the job's own owner, for their own request. + instead of a static "waiting..."/"computing..." label, plus a small bouncing-dots animation + (respects `prefers-reduced-motion`) so there's always something visibly moving while a request + is in flight. Worker identity is only ever shown to the job's own owner, for their own request. - `grid_device.py update --model ` and a matching coordinator endpoint (`POST /api/admin/workers/{id}/model`) to move a device to a different operator-approved model in place — no new worker token, no new bundle to carry to the device, trust level and diff --git a/projectzero/static/index.html b/projectzero/static/index.html index a013f4c..e8f4d72 100644 --- a/projectzero/static/index.html +++ b/projectzero/static/index.html @@ -52,6 +52,12 @@ .msg.system{align-self:center;background:none;border:0;color:var(--muted);font-size:.88rem;text-align:center} .pending-timeline{font-size:.76rem;color:var(--muted);margin-top:.2rem;display:flex;flex-direction:column;gap:.1rem} .pending-timeline .ev-failed,.pending-timeline .ev-requeued{color:var(--warn)} +.pending-dots{display:inline-flex;gap:.22rem;margin-left:.45rem;vertical-align:middle} +.pending-dots span{width:.38rem;height:.38rem;border-radius:50%;background:var(--muted);animation:pz-bounce 1.1s infinite ease-in-out both} +.pending-dots span:nth-child(2){animation-delay:.15s} +.pending-dots span:nth-child(3){animation-delay:.3s} +@keyframes pz-bounce{0%,80%,100%{opacity:.3;transform:translateY(0)}40%{opacity:1;transform:translateY(-.2rem)}} +@media (prefers-reduced-motion:reduce){.pending-dots span{animation:none;opacity:.6}} .composer{display:flex;gap:.5rem;padding:.75rem 1rem;border-top:1px solid var(--line);background:var(--panel)} .composer textarea{resize:none;height:3rem} aside{background:var(--panel);border-left:1px solid var(--line);overflow:auto;padding:1rem;display:flex;flex-direction:column;gap:1rem} @@ -362,25 +368,31 @@

case"failed":return{text:e.worker?t("evFailedBy",{worker:e.worker,error:e.error||""}):t("evFailed",{error:e.error||""}),cls:"ev-failed"}; case"cancelled":return{text:t("evCancelled"),cls:""}; default:return{text:e.type,cls:""}}} -function renderPending(pendingStatus,pendingTimeline,s){ +function dots(){return el("span",{class:"pending-dots"},el("span"),el("span"),el("span"))} +function setPendingDots(pendingLine,on){const have=pendingLine.querySelector(".pending-dots"); + if(on&&!have)pendingLine.append(dots());if(!on&&have)have.remove()} +function renderPending(pendingLine,pendingText,pendingTimeline,s){ const lastWorker=[...s.events].reverse().find(e=>e.worker&&e.type!=="requeued"&&e.type!=="failed")?.worker; - pendingStatus.textContent=s.status==="queued"?(s.available_workers>0?t("waitingCount",{n:s.available_workers}):t("waitingNone")): - s.status==="running"?(lastWorker?t("workingNamed",{worker:lastWorker}):t("working")):pendingStatus.textContent; + const busy=s.status==="queued"||s.status==="running"; + pendingText.textContent=s.status==="queued"?(s.available_workers>0?t("waitingCount",{n:s.available_workers}):t("waitingNone")): + s.status==="running"?(lastWorker?t("workingNamed",{worker:lastWorker}):t("working")):pendingText.textContent; + setPendingDots(pendingLine,busy); pendingTimeline.replaceChildren(...s.events.map(e=>{const{text,cls}=eventLabel(e); return el("div",{class:cls,text:`${new Date(e.t).toLocaleTimeString(lang,{hour:"2-digit",minute:"2-digit",second:"2-digit"})} - ${text}`})}))} async function askAi(text){const model=$("model").value;const privacy=$("privacy").value; let consented=false;try{consented=!!localStorage.getItem("pz-consent")}catch(e){} if(privacy==="community"&&!consented){if(!confirm(t("consent")))return;try{localStorage.setItem("pz-consent","1")}catch(e){}} state.ai.push({role:"user",content:text});renderAi(); - const pendingStatus=el("div",{text:t("sending")});const pendingTimeline=el("div",{class:"pending-timeline"}); - const pending=el("div",{class:"msg system"},pendingStatus,pendingTimeline);$("log").append(pending);scrollLog(); + const pendingText=el("span",{text:t("sending")});const pendingLine=el("div",{},pendingText,dots()); + const pendingTimeline=el("div",{class:"pending-timeline"}); + const pending=el("div",{class:"msg system"},pendingLine,pendingTimeline);$("log").append(pending);scrollLog(); const history=state.ai.slice(-15).map(m=>({role:m.role,content:m.content})); try{const job=await post("/api/jobs",{model,privacy,allow_untrusted:privacy==="community",messages:history,max_output_tokens:256});refreshMe(); - for(let i=0;i<200;i++){await sleep(i<10?1000:3000);const s=await call("/api/jobs/"+job.id);renderPending(pendingStatus,pendingTimeline,s); + for(let i=0;i<200;i++){await sleep(i<10?1000:3000);const s=await call("/api/jobs/"+job.id);renderPending(pendingLine,pendingText,pendingTimeline,s); if(s.status==="completed"){state.ai.push({role:"assistant",content:s.output.content,model});renderAi();refreshMe();return} - if(s.status==="failed"||s.status==="cancelled"){pendingStatus.textContent=t("noAnswer",{reason:s.error||s.status});refreshMe();return}} - pendingStatus.textContent=t("tooLong")} - catch(e){pendingStatus.textContent=t("error")+": "+e.message;state.ai.pop()}} + if(s.status==="failed"||s.status==="cancelled"){setPendingDots(pendingLine,false);pendingText.textContent=t("noAnswer",{reason:s.error||s.status});refreshMe();return}} + setPendingDots(pendingLine,false);pendingText.textContent=t("tooLong")} + catch(e){setPendingDots(pendingLine,false);pendingText.textContent=t("error")+": "+e.message;state.ai.pop()}} $("composer").onsubmit=async e=>{e.preventDefault();const text=$("input").value.trim();if(!text)return;$("input").value="";$("send").disabled=true; try{if(state.active==="ai")await askAi(text);else{await post(`/api/channels/${encodeURIComponent(state.active)}/messages`,{body:text});await pollMessages(false)}}catch(err){sysmsg(t("error")+": "+err.message)}finally{$("send").disabled=false;$("input").focus()}}; $("input").addEventListener("keydown",e=>{if(e.key==="Enter"&&!e.shiftKey){e.preventDefault();$("composer").requestSubmit()}});