Spaces:
Paused
Paused
Commit ·
bc1c646
1
Parent(s): 386c43e
Mapa prywatnego backendu nie nalezy do publicznego Space'a
Browse filesKatalog cloudflare/ trzymal tu zrodlo aria-workera razem z Durable Objectem,
migracje D1, wrangler.jsonc z identyfikatorem bazy i skrypt instalacyjny. Space
jest publiczny, wiec bylo to wystawione bez powodu. Sekretow tam nie bylo, ale
byla cala architektura i id bazy.
Calosc przeniesiona do repozytorium strony, gdzie mieszka reszta deploymentu.
Kopie frontendu i tak odstawaly od tego, co jest na zywo. Tu zostaje sam mozg.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
- README.md +6 -7
- cloudflare/aria-worker/package.json +0 -12
- cloudflare/aria-worker/src/conversation-do.js +0 -695
- cloudflare/aria-worker/src/events.js +0 -101
- cloudflare/aria-worker/src/index.js +0 -163
- cloudflare/aria-worker/src/orchestrator.js +0 -134
- cloudflare/aria-worker/src/r2.js +0 -74
- cloudflare/aria-worker/src/usage.js +0 -67
- cloudflare/aria-worker/wrangler.jsonc +0 -59
- cloudflare/db/migration_aria.sql +0 -58
- cloudflare/db/migration_aria_email.sql +0 -45
- cloudflare/db/migration_aria_transcript.sql +0 -35
- cloudflare/integrate.sh +0 -70
- cloudflare/pages-integration/_worker.aria.js +0 -63
- cloudflare/pages-integration/aria.html +0 -143
- cloudflare/pages-integration/css/aria.css +0 -291
- cloudflare/pages-integration/js/aria-chat.js +0 -626
- cloudflare/pages-integration/js/aria-settings.js +0 -63
- cloudflare/pages-integration/profile-picture-aria.png +0 -0
README.md
CHANGED
|
@@ -25,17 +25,16 @@ The full product also ships a Cloudflare realtime backend and a Messenger UI —
|
|
| 25 |
```
|
| 26 |
app.py Gradio Space entry — exposes api_name="respond"
|
| 27 |
brain/ persona, contracts, model orchestration (vision)
|
| 28 |
-
cloudflare/
|
| 29 |
-
aria-worker/ standalone Worker: AriaConversation Durable Object + R2
|
| 30 |
-
pages-integration/ Messenger frontend + _worker.js merge snippet
|
| 31 |
-
db/ D1 migration (additive)
|
| 32 |
-
integrate.sh safe additive install into the live site
|
| 33 |
```
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
## Run / deploy
|
| 36 |
- **Brain (this Space):** set `HF_TOKEN` as a Space secret; optionally `ARIA_MODEL`.
|
| 37 |
-
- **Everything else:** `cloudflare/integrate.sh` prints the exact steps
|
| 38 |
-
(R2 bucket, D1 migration, `wrangler deploy`, service binding, Pages deploy).
|
| 39 |
|
| 40 |
Built on [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub),
|
| 41 |
and [Cloudflare Workers / Durable Objects / R2](https://developers.cloudflare.com/).
|
|
|
|
| 25 |
```
|
| 26 |
app.py Gradio Space entry — exposes api_name="respond"
|
| 27 |
brain/ persona, contracts, model orchestration (vision)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
```
|
| 29 |
|
| 30 |
+
The Cloudflare side (the `aria-worker` Durable Object, the D1 migrations and the
|
| 31 |
+
Messenger front-end) used to live in this repo under `cloudflare/`. It has moved to
|
| 32 |
+
the website repository, where the rest of the deployment lives. This Space is only
|
| 33 |
+
the brain. A public Space is the wrong place to keep the map of a private backend,
|
| 34 |
+
and the copies here had drifted behind the live ones anyway.
|
| 35 |
+
|
| 36 |
## Run / deploy
|
| 37 |
- **Brain (this Space):** set `HF_TOKEN` as a Space secret; optionally `ARIA_MODEL`.
|
|
|
|
|
|
|
| 38 |
|
| 39 |
Built on [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub),
|
| 40 |
and [Cloudflare Workers / Durable Objects / R2](https://developers.cloudflare.com/).
|
cloudflare/aria-worker/package.json
DELETED
|
@@ -1,12 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"name": "aria-worker",
|
| 3 |
-
"private": true,
|
| 4 |
-
"type": "module",
|
| 5 |
-
"scripts": {
|
| 6 |
-
"dev": "wrangler dev",
|
| 7 |
-
"deploy": "wrangler deploy"
|
| 8 |
-
},
|
| 9 |
-
"devDependencies": {
|
| 10 |
-
"wrangler": "^4.0.0"
|
| 11 |
-
}
|
| 12 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cloudflare/aria-worker/src/conversation-do.js
DELETED
|
@@ -1,695 +0,0 @@
|
|
| 1 |
-
/* ============================================================
|
| 2 |
-
AriaConversation — one Durable Object per chat.
|
| 3 |
-
|
| 4 |
-
Responsibilities:
|
| 5 |
-
• hold the live WebSocket(s) for a conversation
|
| 6 |
-
• append user events, cluster consecutive ones into a turn
|
| 7 |
-
(debounced) so "kup jabłka" + "i gruszki" is one context
|
| 8 |
-
• drive the brain and fan out bubbles with a human cadence
|
| 9 |
-
• detect 10s inactivity → emit system_idle → maybe proactive bubble
|
| 10 |
-
• mirror everything to D1 for cross-device history
|
| 11 |
-
|
| 12 |
-
The owning Worker has already validated auth and passes the
|
| 13 |
-
trusted cid / uid / lang on the upgrade URL.
|
| 14 |
-
============================================================ */
|
| 15 |
-
|
| 16 |
-
import { normalizeEvent, idleEvent, newId, LIMITS, ALLOWED_REACTIONS } from "./events.js";
|
| 17 |
-
import { runBrain } from "./orchestrator.js";
|
| 18 |
-
import { consume, usageStatus } from "./usage.js";
|
| 19 |
-
|
| 20 |
-
export class AriaConversation {
|
| 21 |
-
constructor(state, env) {
|
| 22 |
-
this.state = state;
|
| 23 |
-
this.env = env;
|
| 24 |
-
this.sockets = new Set();
|
| 25 |
-
this.pending = []; // unanswered user events (current cluster)
|
| 26 |
-
this.recent = []; // rolling history fed to the brain
|
| 27 |
-
this.topic = null;
|
| 28 |
-
this.idleCount = 0;
|
| 29 |
-
this.busy = false;
|
| 30 |
-
this.debounceTimer = null;
|
| 31 |
-
this.idleTimer = null;
|
| 32 |
-
this.cid = null;
|
| 33 |
-
this.uid = null;
|
| 34 |
-
this.lang = "auto";
|
| 35 |
-
this.uname = "";
|
| 36 |
-
this.uemail = "";
|
| 37 |
-
this.userTyping = false; // is the user currently typing? (gates idle)
|
| 38 |
-
this.msgTimes = []; // recent message timestamps (spam guard)
|
| 39 |
-
this.spamUntil = 0;
|
| 40 |
-
this.lastAccept = 0;
|
| 41 |
-
this.limited = false; // limit reached → said "muszę lecieć / pa pa", now away
|
| 42 |
-
this.limitedNagged = false; // (legacy) second nag — no longer used
|
| 43 |
-
this.backlogStored = 0; // user messages stored while over the limit (capped)
|
| 44 |
-
this.blocked = false; // user "blocked" ARIA → she stays silent until unblocked
|
| 45 |
-
this.reactTimer = null; // debounce for react-to-reaction comment
|
| 46 |
-
this.pendingReact = null;
|
| 47 |
-
this.seenIds = new Set(); // event ids already received (idempotent resends)
|
| 48 |
-
this.unsent = null; // {texts,since}: bubbles composed but not sent (user cut in)
|
| 49 |
-
this._delayResolve = null; // resolver for the current interruptible "typing" pause
|
| 50 |
-
this._delayTimer = null;
|
| 51 |
-
}
|
| 52 |
-
|
| 53 |
-
/* ---- HTTP entry: only WS upgrade arrives here ---- */
|
| 54 |
-
async fetch(request) {
|
| 55 |
-
const url = new URL(request.url);
|
| 56 |
-
if (request.headers.get("Upgrade") !== "websocket") {
|
| 57 |
-
return new Response("expected websocket", { status: 426 });
|
| 58 |
-
}
|
| 59 |
-
this.cid = url.searchParams.get("cid") || this.cid;
|
| 60 |
-
this.uid = Number(url.searchParams.get("uid")) || this.uid;
|
| 61 |
-
this.lang = url.searchParams.get("lang") || this.lang;
|
| 62 |
-
this.uname = url.searchParams.get("name") || this.uname;
|
| 63 |
-
this.uemail = url.searchParams.get("email") || this.uemail;
|
| 64 |
-
|
| 65 |
-
const pair = new WebSocketPair();
|
| 66 |
-
const [client, server] = [pair[0], pair[1]];
|
| 67 |
-
server.accept();
|
| 68 |
-
this.sockets.add(server);
|
| 69 |
-
|
| 70 |
-
server.addEventListener("message", (ev) => this.onMessage(server, ev.data));
|
| 71 |
-
const drop = () => { this.sockets.delete(server); this.clearIdle(); };
|
| 72 |
-
server.addEventListener("close", drop);
|
| 73 |
-
server.addEventListener("error", drop);
|
| 74 |
-
|
| 75 |
-
await this.sendHistory(server);
|
| 76 |
-
this.maybeCatchUp(); // back after a limit? answer what came in while away
|
| 77 |
-
return new Response(null, { status: 101, webSocket: client });
|
| 78 |
-
}
|
| 79 |
-
|
| 80 |
-
/* ---- inbound WS messages ---- */
|
| 81 |
-
async onMessage(ws, data) {
|
| 82 |
-
let msg; try { msg = JSON.parse(data); } catch { return; }
|
| 83 |
-
|
| 84 |
-
if (msg.t === "ping") { this.send(ws, { t: "pong" }); return; }
|
| 85 |
-
|
| 86 |
-
if (msg.t === "clear") { await this.clearHistory(); return; }
|
| 87 |
-
|
| 88 |
-
// user typing state — gates idle pings ("gdy jest typing aria czeka")
|
| 89 |
-
if (msg.t === "typing") {
|
| 90 |
-
this.userTyping = !!msg.on;
|
| 91 |
-
if (this.userTyping) this.clearIdle();
|
| 92 |
-
else this.armIdle();
|
| 93 |
-
return;
|
| 94 |
-
}
|
| 95 |
-
|
| 96 |
-
// user reacted to one of ARIA's messages (long-press → emoji)
|
| 97 |
-
if (msg.t === "react") { await this.userReact(msg.id, msg.emoji); return; }
|
| 98 |
-
|
| 99 |
-
// user blocked/unblocked ARIA on the chat. While blocked she says nothing (incl.
|
| 100 |
-
// proactive); on unblock she pops back with a cheeky line (runUnblockReaction).
|
| 101 |
-
if (msg.t === "block") {
|
| 102 |
-
this.blocked = true; this.clearIdle();
|
| 103 |
-
if (this.debounceTimer) { clearTimeout(this.debounceTimer); this.debounceTimer = null; }
|
| 104 |
-
this.pending = [];
|
| 105 |
-
return;
|
| 106 |
-
}
|
| 107 |
-
if (msg.t === "unblock") {
|
| 108 |
-
const was = this.blocked; this.blocked = false;
|
| 109 |
-
if (was) await this.runUnblockReaction();
|
| 110 |
-
return;
|
| 111 |
-
}
|
| 112 |
-
|
| 113 |
-
if (msg.t === "event") {
|
| 114 |
-
if (this.blocked) return; // blocked → ignore (client UI also prevents sending)
|
| 115 |
-
const norm = normalizeEvent(msg.event);
|
| 116 |
-
if (!norm.ok) { this.send(ws, { t: "error", v: norm.error }); return; }
|
| 117 |
-
const event = { ...norm.event, role: "user" };
|
| 118 |
-
|
| 119 |
-
// Idempotent receive: a flaky mobile socket makes the client resend events it
|
| 120 |
-
// never got an ack for. Ack EVERY receipt so the client can drop it, and skip
|
| 121 |
-
// reprocessing (and re-billing) anything we've already handled.
|
| 122 |
-
this.send(ws, { t: "ack", id: event.id });
|
| 123 |
-
if (this.seenIds.has(event.id)) return;
|
| 124 |
-
this.seenIds.add(event.id);
|
| 125 |
-
if (this.seenIds.size > 400) this.seenIds = new Set([...this.seenIds].slice(-200));
|
| 126 |
-
|
| 127 |
-
// Spam guard: > N msgs within a window → enforce min spacing for a cooldown.
|
| 128 |
-
// Excess fast messages are silently dropped (client also blocks; this is the backstop).
|
| 129 |
-
const now = Date.now();
|
| 130 |
-
this.msgTimes = this.msgTimes.filter(t => now - t < LIMITS.SPAM_WINDOW);
|
| 131 |
-
this.msgTimes.push(now);
|
| 132 |
-
if (this.msgTimes.length > LIMITS.SPAM_N) this.spamUntil = now + LIMITS.SPAM_COOL;
|
| 133 |
-
if (now < this.spamUntil && this.lastAccept && now - this.lastAccept < LIMITS.SPAM_GAP) {
|
| 134 |
-
return; // drop silently
|
| 135 |
-
}
|
| 136 |
-
this.lastAccept = now;
|
| 137 |
-
|
| 138 |
-
// Budget: 20 messages / 5h / user.
|
| 139 |
-
const wasLimited = this.limited;
|
| 140 |
-
const u = await consume(this.env, this.uid, this.uemail);
|
| 141 |
-
if (!u.ok) {
|
| 142 |
-
// Over the limit → ARIA is "away". STORE what the user writes (it becomes the
|
| 143 |
-
// backlog she answers on her return) but don't reply and don't burn budget.
|
| 144 |
-
this.send(ws, { t: "limit", resetAt: u.resetAt, limit: u.limit }); // popup
|
| 145 |
-
if (!this.limited) {
|
| 146 |
-
this.limited = true;
|
| 147 |
-
await this.emitBubbles([{ text: "muszę lecieć" }, { text: "pa pa" }]); // one goodbye, then silence
|
| 148 |
-
}
|
| 149 |
-
if (this.backlogStored < 40) { // cap the stored backlog (anti-abuse)
|
| 150 |
-
this.recent.push(event);
|
| 151 |
-
await this.persistEvent(event); // answered = 0 → picked up on her return
|
| 152 |
-
this.backlogStored++;
|
| 153 |
-
this.broadcast({ t: "echo", event: { id: event.id, ts: event.ts, type: event.type, payload: event.payload } });
|
| 154 |
-
}
|
| 155 |
-
return;
|
| 156 |
-
}
|
| 157 |
-
this.broadcast({ t: "usage", remaining: u.remaining, resetAt: u.resetAt, limit: u.limit });
|
| 158 |
-
|
| 159 |
-
this.idleCount = 0; // any real input resets proactive budget
|
| 160 |
-
this.userTyping = false;
|
| 161 |
-
this.clearIdle();
|
| 162 |
-
this.pending.push(event);
|
| 163 |
-
this.wakeDelay(); // if ARIA is mid-"typing", end the pause so she finishes
|
| 164 |
-
// the current bubble and re-evaluates (see emitBubbles)
|
| 165 |
-
this.recent.push(event);
|
| 166 |
-
await this.persistEvent(event);
|
| 167 |
-
// live mirror: echo to ALL sockets incl. the sender. The sender de-dups by DOM
|
| 168 |
-
// id normally, but after a reconnect (which rebuilds the view from history) a
|
| 169 |
-
// just-resent message would otherwise be missing — the echo re-renders it.
|
| 170 |
-
this.broadcast({ t: "echo", event: { id: event.id, ts: event.ts, type: event.type, payload: event.payload } });
|
| 171 |
-
|
| 172 |
-
if (wasLimited) {
|
| 173 |
-
// The 5h window just reset after a limit → come back and answer everything that
|
| 174 |
-
// piled up (incl. this message) in one natural catch-up turn (see runCatchUp).
|
| 175 |
-
this.limited = false; this.limitedNagged = false; this.backlogStored = 0;
|
| 176 |
-
this.pending = []; // catch-up covers it
|
| 177 |
-
if (this.debounceTimer) { clearTimeout(this.debounceTimer); this.debounceTimer = null; }
|
| 178 |
-
await this.runCatchUp();
|
| 179 |
-
return;
|
| 180 |
-
}
|
| 181 |
-
|
| 182 |
-
// Adaptive debounce: wait for the user to finish a multi-bubble thought.
|
| 183 |
-
// A question → reply soon; a lead-in/buildup → be patient (up to 10s, reset
|
| 184 |
-
// on each new bubble) so "dobra / już ci tłumaczę / no więc…" all land first.
|
| 185 |
-
if (this.debounceTimer) clearTimeout(this.debounceTimer);
|
| 186 |
-
this.debounceTimer = setTimeout(() => this.flushTurn(), this.clusterWait(event));
|
| 187 |
-
}
|
| 188 |
-
}
|
| 189 |
-
|
| 190 |
-
/* ---- user reaction to an ARIA message ---- */
|
| 191 |
-
async userReact(bubbleId, emoji) {
|
| 192 |
-
if (typeof bubbleId !== "string") return;
|
| 193 |
-
if (emoji && !ALLOWED_REACTIONS.includes(emoji)) return; // null/"" clears it
|
| 194 |
-
const value = emoji || null;
|
| 195 |
-
await this.env.DB.prepare(
|
| 196 |
-
"UPDATE aria_bubbles SET reaction = ? WHERE id = ? AND conversation_id = ?"
|
| 197 |
-
).bind(value, bubbleId, this.cid).run().catch(() => {});
|
| 198 |
-
this.broadcast({ t: "reaction", target: "bubble", id: bubbleId, emoji: value });
|
| 199 |
-
|
| 200 |
-
// Adding a reaction (not clearing) may prompt ARIA to quip about it
|
| 201 |
-
// ("lmao co cię tak bawi") — debounced so rapid reacting batches into one.
|
| 202 |
-
if (value) {
|
| 203 |
-
const bub = [...this.recent].reverse().find(e => e.role === "assistant" && e.id === bubbleId);
|
| 204 |
-
this.pendingReact = { emoji: value, onText: bub ? (bub.payload.text || "") : "" };
|
| 205 |
-
if (this.reactTimer) clearTimeout(this.reactTimer);
|
| 206 |
-
this.reactTimer = setTimeout(() => {
|
| 207 |
-
const p = this.pendingReact; this.pendingReact = null;
|
| 208 |
-
if (p) this.reactToReaction(p.emoji, p.onText);
|
| 209 |
-
}, 1800);
|
| 210 |
-
}
|
| 211 |
-
}
|
| 212 |
-
|
| 213 |
-
/* ---- permanently wipe this conversation's history (DB + memory) ---- */
|
| 214 |
-
async clearHistory() {
|
| 215 |
-
this.clearIdle();
|
| 216 |
-
if (this.debounceTimer) { clearTimeout(this.debounceTimer); this.debounceTimer = null; }
|
| 217 |
-
await this.env.DB.batch([
|
| 218 |
-
this.env.DB.prepare("DELETE FROM aria_bubbles WHERE conversation_id = ?").bind(this.cid),
|
| 219 |
-
this.env.DB.prepare("DELETE FROM aria_events WHERE conversation_id = ?").bind(this.cid),
|
| 220 |
-
]).catch(() => {});
|
| 221 |
-
this.recent = [];
|
| 222 |
-
this.pending = [];
|
| 223 |
-
this.lastNudge = null;
|
| 224 |
-
this.idleCount = 0;
|
| 225 |
-
this.touchConvo();
|
| 226 |
-
this.broadcast({ t: "cleared" }); // tell every open tab to wipe the view
|
| 227 |
-
}
|
| 228 |
-
|
| 229 |
-
/* ---- run one logical turn over the clustered pending events ---- */
|
| 230 |
-
async flushTurn(systemEvent = null) {
|
| 231 |
-
if (this.busy) { // re-arm; don't overlap brain calls
|
| 232 |
-
if (this.debounceTimer) clearTimeout(this.debounceTimer);
|
| 233 |
-
this.debounceTimer = setTimeout(() => this.flushTurn(systemEvent), 300);
|
| 234 |
-
return;
|
| 235 |
-
}
|
| 236 |
-
const events = systemEvent ? [systemEvent] : this.pending.splice(0);
|
| 237 |
-
if (!events.length) return;
|
| 238 |
-
this.busy = true;
|
| 239 |
-
|
| 240 |
-
try {
|
| 241 |
-
// ---- idle: the BRAIN decides whether to re-engage (not a canned ping) ----
|
| 242 |
-
// Mostly it returns [] (stay silent). It only speaks up for a genuinely open
|
| 243 |
-
// thread, or to check in / support after an emotional moment. No "jesteś?" spam.
|
| 244 |
-
if (systemEvent) {
|
| 245 |
-
if (this.userTyping) return; // user is typing → don't nudge
|
| 246 |
-
if (this.userAskedToWait()) return; // user said "poczekaj"/"muszę lecieć" → no ping
|
| 247 |
-
const idleWindow = [...this.recent.slice(-LIMITS.WINDOW), { ...systemEvent, role: "system" }];
|
| 248 |
-
const validIdleIds = new Set(idleWindow.map(e => e.id));
|
| 249 |
-
const tThink = Date.now();
|
| 250 |
-
const bubbles = await runBrain(this.env, {
|
| 251 |
-
events: [systemEvent], recent: idleWindow, topic: this.topic, lang: this.lang,
|
| 252 |
-
userName: this.uname, validEventIds: validIdleIds,
|
| 253 |
-
}).catch(() => []);
|
| 254 |
-
const kept = bubbles.filter(b => b.type !== "reaction" && (b.bubble || "").trim());
|
| 255 |
-
if (kept.length) {
|
| 256 |
-
await this.emitBubbles(
|
| 257 |
-
kept.map(b => ({ text: b.bubble, kind: b.type || "proactive", reply_to: b.reply_to })),
|
| 258 |
-
{ paced: true, credit: Date.now() - tThink }
|
| 259 |
-
);
|
| 260 |
-
}
|
| 261 |
-
this.trimRecent();
|
| 262 |
-
return;
|
| 263 |
-
}
|
| 264 |
-
|
| 265 |
-
// ---- normal turn: windowed context → brain ----
|
| 266 |
-
// Carry an interrupted thread (bubbles ARIA composed but didn't get to send before
|
| 267 |
-
// the user cut in). The brain sees it and decides in THIS turn: answer the new
|
| 268 |
-
// message first, then resume that thread or drop it. Consumed once.
|
| 269 |
-
const carried = this.unsent; this.unsent = null;
|
| 270 |
-
const window = this.recent.slice(-LIMITS.WINDOW); // sliding memory (token budget)
|
| 271 |
-
const validEventIds = new Set(window.map(e => e.id));
|
| 272 |
-
const tThink = Date.now(); // model latency → credited to the pause
|
| 273 |
-
this.broadcast({ t: "typing", on: true });
|
| 274 |
-
let bubbles = await runBrain(this.env, {
|
| 275 |
-
events, recent: window, topic: this.topic, lang: this.lang,
|
| 276 |
-
userName: this.uname, replyTo: this.resolveReplyTo(events), validEventIds, unsent: carried,
|
| 277 |
-
});
|
| 278 |
-
|
| 279 |
-
// ARIA's reactions to user messages — applied instantly (no typing delay)
|
| 280 |
-
for (const b of bubbles.filter(b => b.type === "reaction")) await this.applyAriaReaction(b);
|
| 281 |
-
|
| 282 |
-
// Keep the text bubbles. Only block: echoing THIS turn's user message, or
|
| 283 |
-
// repeating the immediately-previous ARIA line. (Do NOT dedupe against the
|
| 284 |
-
// whole history — aya reuses phrases like "co słychać", and over-filtering
|
| 285 |
-
// dropped every bubble → "typing then nothing".)
|
| 286 |
-
let kept = this.keepText(bubbles, events, window);
|
| 287 |
-
|
| 288 |
-
// If the model gave no usable text, retry once (transient). No dumb
|
| 289 |
-
// placeholder: an intentional empty (e.g. a pure follow-up of the user's own
|
| 290 |
-
// thought) → stay silent. The model is instructed to GUESS otherwise.
|
| 291 |
-
if (!kept.length) {
|
| 292 |
-
const retry = await runBrain(this.env, {
|
| 293 |
-
events, recent: window, topic: this.topic, lang: this.lang,
|
| 294 |
-
userName: this.uname, replyTo: this.resolveReplyTo(events), validEventIds, unsent: carried,
|
| 295 |
-
}).catch(() => []);
|
| 296 |
-
kept = this.keepText(retry, events, window);
|
| 297 |
-
}
|
| 298 |
-
this.broadcast({ t: "typing", on: false });
|
| 299 |
-
|
| 300 |
-
// reply_to (the visible quote) is the model's call now — the persona quotes only
|
| 301 |
-
// when it adds value, else null. We no longer strip a quote that points at the
|
| 302 |
-
// last user message: that was silently killing "reply to my last message" and
|
| 303 |
-
// emphasis quotes, so ARIA looked like she never used reply-to.
|
| 304 |
-
|
| 305 |
-
const emitItems = kept.map(b => ({
|
| 306 |
-
text: b.bubble, kind: b.type || "response", target_event_id: b.target_event_id, reply_to: b.reply_to,
|
| 307 |
-
}));
|
| 308 |
-
if (this.pending.length) {
|
| 309 |
-
// User cut in WHILE ARIA was still thinking → don't send the now-stale reply;
|
| 310 |
-
// hold all of it so the re-decision turn (next flush) can fold it in.
|
| 311 |
-
this.unsent = emitItems.length ? { texts: emitItems.map(it => it.text), since: Date.now() } : null;
|
| 312 |
-
} else {
|
| 313 |
-
// Paced send; if the user cuts in mid-delivery, emitBubbles finishes the current
|
| 314 |
-
// bubble and returns the rest, which we hold as the resumable thread.
|
| 315 |
-
const held = await this.emitBubbles(emitItems, { paced: true, credit: Date.now() - tThink });
|
| 316 |
-
this.unsent = (held && held.length) ? { texts: held.map(h => h.text), since: Date.now() } : null;
|
| 317 |
-
}
|
| 318 |
-
await this.markAnswered(events);
|
| 319 |
-
this.trimRecent();
|
| 320 |
-
} catch (e) {
|
| 321 |
-
this.broadcast({ t: "typing", on: false });
|
| 322 |
-
const pick = (a) => a[Math.floor(Math.random() * a.length)];
|
| 323 |
-
await this.emitBubbles([
|
| 324 |
-
{ text: pick(["muszę lecieć", "muszę spadać", "ok to ja lecę", "dobra lecę"]) },
|
| 325 |
-
{ text: pick(["siemanko", "nara", "do zobaczenia", "trzymaj się", "na razie"]) },
|
| 326 |
-
]);
|
| 327 |
-
} finally {
|
| 328 |
-
this.busy = false;
|
| 329 |
-
this.armIdle();
|
| 330 |
-
}
|
| 331 |
-
}
|
| 332 |
-
|
| 333 |
-
/* Persist + mirror a batch of ARIA text bubbles. With paced:true each bubble
|
| 334 |
-
appears after a length-scaled "typing" pause — the human reply delay.
|
| 335 |
-
INTERRUPTIBLE: if the user sends a new message mid-delivery, we finish the
|
| 336 |
-
bubble currently being typed and STOP, returning the not-yet-sent remainder so
|
| 337 |
-
the caller can hold it as a resumable thread. Returns [] when fully delivered. */
|
| 338 |
-
async emitBubbles(items, { paced = false, credit = 0 } = {}) {
|
| 339 |
-
for (let i = 0; i < items.length; i++) {
|
| 340 |
-
const it = items[i];
|
| 341 |
-
if (paced) {
|
| 342 |
-
let wait = replyDelay(it.text);
|
| 343 |
-
// The model already kept the user waiting while it thought — count THAT toward
|
| 344 |
-
// the first bubble's "typing" pause instead of stacking another 1–8s on top
|
| 345 |
-
// (unify the wait: total ≈ max(modelTime, pause), not modelTime + pause).
|
| 346 |
-
if (i === 0 && credit > 0) wait = Math.max(0, wait - credit);
|
| 347 |
-
if (wait > 0) {
|
| 348 |
-
this.broadcast({ t: "typing", on: true });
|
| 349 |
-
await this.pacedDelay(wait); // a new user msg ends this early
|
| 350 |
-
this.broadcast({ t: "typing", on: false });
|
| 351 |
-
}
|
| 352 |
-
}
|
| 353 |
-
const row = {
|
| 354 |
-
id: newId("bub"), conversation_id: this.cid,
|
| 355 |
-
target_event_id: it.target_event_id || null, reply_to: it.reply_to || null,
|
| 356 |
-
kind: it.kind || "proactive", text: it.text,
|
| 357 |
-
};
|
| 358 |
-
await this.persistBubble(row);
|
| 359 |
-
this.recent.push({ id: row.id, role: "assistant", type: "message", ts: Date.now(), payload: { text: it.text } });
|
| 360 |
-
this.broadcast({ t: "bubble", id: row.id, bubble: it.text, target_event_id: row.target_event_id,
|
| 361 |
-
reply_to: row.reply_to, kind: row.kind });
|
| 362 |
-
// user cut in (a new pending event)? finish THIS bubble (just sent), hold the rest.
|
| 363 |
-
if (paced && this.pending.length) return items.slice(i + 1);
|
| 364 |
-
}
|
| 365 |
-
return [];
|
| 366 |
-
}
|
| 367 |
-
|
| 368 |
-
/* An interruptible "typing" pause: resolves after ms, or early when wakeDelay()
|
| 369 |
-
is called (a new user message arrived). */
|
| 370 |
-
pacedDelay(ms) {
|
| 371 |
-
return new Promise((resolve) => {
|
| 372 |
-
this._delayResolve = resolve;
|
| 373 |
-
this._delayTimer = setTimeout(() => { this._delayResolve = null; this._delayTimer = null; resolve(); }, ms);
|
| 374 |
-
});
|
| 375 |
-
}
|
| 376 |
-
wakeDelay() {
|
| 377 |
-
if (this._delayTimer) { clearTimeout(this._delayTimer); this._delayTimer = null; }
|
| 378 |
-
if (this._delayResolve) { const r = this._delayResolve; this._delayResolve = null; r(); }
|
| 379 |
-
}
|
| 380 |
-
|
| 381 |
-
/* Keep ARIA's text bubbles, blocking only: an echo of THIS turn's user message,
|
| 382 |
-
a repeat of the immediately-previous ARIA line, or an in-batch duplicate.
|
| 383 |
-
If filtering would empty it, keep the originals (never go silent). */
|
| 384 |
-
keepText(bubbles, events, window) {
|
| 385 |
-
const userEcho = new Set(events.filter(e => e.type === "message").map(e => norm(e.payload.text)));
|
| 386 |
-
const lastA = [...window].reverse().find(e => e.role === "assistant");
|
| 387 |
-
const prev = lastA ? norm(lastA.payload.text) : "";
|
| 388 |
-
const seen = new Set();
|
| 389 |
-
const texts = (bubbles || []).filter(b => b.type !== "reaction");
|
| 390 |
-
const out = texts.filter(b => {
|
| 391 |
-
const t = norm(b.bubble);
|
| 392 |
-
if (!t || userEcho.has(t) || seen.has(t) || t === prev) return false;
|
| 393 |
-
seen.add(t); return true;
|
| 394 |
-
});
|
| 395 |
-
return out.length ? out : texts;
|
| 396 |
-
}
|
| 397 |
-
|
| 398 |
-
/* ARIA reacting (emoji) to a user message. */
|
| 399 |
-
async applyAriaReaction(b) {
|
| 400 |
-
await this.env.DB.prepare(
|
| 401 |
-
"UPDATE aria_events SET reaction = ? WHERE id = ? AND conversation_id = ?"
|
| 402 |
-
).bind(b.bubble, b.target_event_id, this.cid).run().catch(() => {});
|
| 403 |
-
this.broadcast({ t: "reaction", target: "event", id: b.target_event_id, emoji: b.bubble });
|
| 404 |
-
}
|
| 405 |
-
|
| 406 |
-
/* How long to wait before treating the user's input as a finished thought.
|
| 407 |
-
Question → short; lead-in/mid-stream (or a 2nd quick bubble) → patient (up to
|
| 408 |
-
10s, reset on each new bubble); lone statement → normal. */
|
| 409 |
-
clusterWait(event) {
|
| 410 |
-
if (!event || event.type !== "message") return LIMITS.WAIT_SINGLE;
|
| 411 |
-
const t = (event.payload.text || "").trim().toLowerCase();
|
| 412 |
-
if (t.endsWith("?")) return LIMITS.WAIT_QUESTION;
|
| 413 |
-
if (this.pending.length >= 2 || isLeadIn(t)) return LIMITS.WAIT_BUILDUP;
|
| 414 |
-
return LIMITS.WAIT_SINGLE;
|
| 415 |
-
}
|
| 416 |
-
|
| 417 |
-
/* Resolve the message a user turn replies to → {role, text} for the brain. */
|
| 418 |
-
resolveReplyTo(events) {
|
| 419 |
-
const last = [...events].reverse().find(e => e.type === "message");
|
| 420 |
-
const rid = last && last.payload && last.payload.reply_to;
|
| 421 |
-
if (!rid) return null;
|
| 422 |
-
const m = [...this.recent].reverse().find(e => e.id === rid);
|
| 423 |
-
if (!m) return null;
|
| 424 |
-
return { role: m.role, text: (m.payload && m.payload.text) || "" };
|
| 425 |
-
}
|
| 426 |
-
|
| 427 |
-
/* User reacted to one of ARIA's messages → maybe she quips about it. */
|
| 428 |
-
async reactToReaction(emoji, onText) {
|
| 429 |
-
if (this.busy || this.userTyping) return;
|
| 430 |
-
this.busy = true;
|
| 431 |
-
this.broadcast({ t: "typing", on: true });
|
| 432 |
-
try {
|
| 433 |
-
const window = this.recent.slice(-LIMITS.WINDOW);
|
| 434 |
-
const tThink = Date.now();
|
| 435 |
-
const bubbles = await runBrain(this.env, {
|
| 436 |
-
events: [], recent: window, topic: this.topic, lang: this.lang, userName: this.uname,
|
| 437 |
-
userReaction: { emoji, on_text: onText }, validEventIds: new Set(window.map(e => e.id)),
|
| 438 |
-
});
|
| 439 |
-
this.broadcast({ t: "typing", on: false });
|
| 440 |
-
await this.emitBubbles(
|
| 441 |
-
bubbles.filter(b => b.type !== "reaction").map(b => ({ text: b.bubble, kind: b.type })),
|
| 442 |
-
{ paced: true, credit: Date.now() - tThink }
|
| 443 |
-
);
|
| 444 |
-
} catch (e) {
|
| 445 |
-
this.broadcast({ t: "typing", on: false });
|
| 446 |
-
} finally {
|
| 447 |
-
this.busy = false;
|
| 448 |
-
this.armIdle();
|
| 449 |
-
}
|
| 450 |
-
}
|
| 451 |
-
|
| 452 |
-
/* ---- limit catch-up: she was "away" (over budget) and the user kept writing ---- */
|
| 453 |
-
/* Called on (re)connect: if the window has reset and a backlog piled up, come back. */
|
| 454 |
-
async maybeCatchUp() {
|
| 455 |
-
if (this.busy) return;
|
| 456 |
-
const u = await usageStatus(this.env, this.uid, this.uemail);
|
| 457 |
-
if (u.remaining <= 0) return; // still over the limit window
|
| 458 |
-
const backlog = await this.unansweredUserEvents();
|
| 459 |
-
if (!backlog.length) return;
|
| 460 |
-
await this.runCatchUp(backlog);
|
| 461 |
-
}
|
| 462 |
-
|
| 463 |
-
/* Unanswered user messages (answered = 0) — what piled up while she was away. */
|
| 464 |
-
async unansweredUserEvents() {
|
| 465 |
-
const r = await this.env.DB.prepare(
|
| 466 |
-
"SELECT id, ts, type, payload FROM aria_events WHERE conversation_id = ? AND answered = 0 " +
|
| 467 |
-
"AND type IN ('message','image','file') ORDER BY ts ASC LIMIT 30"
|
| 468 |
-
).bind(this.cid).all().catch(() => ({ results: [] }));
|
| 469 |
-
return (r.results || []).map(row => ({
|
| 470 |
-
id: row.id, ts: row.ts, type: row.type, payload: safeParse(row.payload), role: "user",
|
| 471 |
-
}));
|
| 472 |
-
}
|
| 473 |
-
|
| 474 |
-
/* One natural "I'm back, sorry" turn that answers the whole backlog at once
|
| 475 |
-
(comeback=true → persona apologises in her own words, then addresses it). */
|
| 476 |
-
async runCatchUp(backlog) {
|
| 477 |
-
if (this.busy) { setTimeout(() => this.runCatchUp(backlog), 400); return; }
|
| 478 |
-
backlog = backlog || await this.unansweredUserEvents();
|
| 479 |
-
if (!backlog.length) return;
|
| 480 |
-
this.busy = true;
|
| 481 |
-
try {
|
| 482 |
-
this.clearIdle();
|
| 483 |
-
const window = this.recent.slice(-LIMITS.WINDOW);
|
| 484 |
-
const validEventIds = new Set([...window.map(e => e.id), ...backlog.map(e => e.id)]);
|
| 485 |
-
const tThink = Date.now();
|
| 486 |
-
this.broadcast({ t: "typing", on: true });
|
| 487 |
-
const ask = () => runBrain(this.env, {
|
| 488 |
-
events: backlog, recent: window, topic: this.topic, lang: this.lang,
|
| 489 |
-
userName: this.uname, validEventIds, comeback: true,
|
| 490 |
-
});
|
| 491 |
-
let bubbles = await ask();
|
| 492 |
-
for (const b of bubbles.filter(b => b.type === "reaction")) await this.applyAriaReaction(b);
|
| 493 |
-
let kept = this.keepText(bubbles, backlog, window);
|
| 494 |
-
if (!kept.length) kept = this.keepText(await ask().catch(() => []), backlog, window);
|
| 495 |
-
this.broadcast({ t: "typing", on: false });
|
| 496 |
-
await this.emitBubbles(
|
| 497 |
-
kept.map(b => ({ text: b.bubble, kind: b.type || "response", target_event_id: b.target_event_id, reply_to: b.reply_to })),
|
| 498 |
-
{ paced: true, credit: Date.now() - tThink }
|
| 499 |
-
);
|
| 500 |
-
await this.markAnswered(backlog);
|
| 501 |
-
this.limited = false; this.limitedNagged = false; this.backlogStored = 0;
|
| 502 |
-
this.trimRecent();
|
| 503 |
-
} catch (e) {
|
| 504 |
-
this.broadcast({ t: "typing", on: false });
|
| 505 |
-
} finally {
|
| 506 |
-
this.busy = false;
|
| 507 |
-
this.armIdle();
|
| 508 |
-
}
|
| 509 |
-
}
|
| 510 |
-
|
| 511 |
-
/* User just unblocked ARIA → she pops back with a short cheeky line about the block. */
|
| 512 |
-
async runUnblockReaction() {
|
| 513 |
-
if (this.busy) { setTimeout(() => this.runUnblockReaction(), 400); return; }
|
| 514 |
-
this.busy = true;
|
| 515 |
-
this.broadcast({ t: "typing", on: true });
|
| 516 |
-
try {
|
| 517 |
-
const window = this.recent.slice(-LIMITS.WINDOW);
|
| 518 |
-
const tThink = Date.now();
|
| 519 |
-
const bubbles = await runBrain(this.env, {
|
| 520 |
-
events: [], recent: window, topic: this.topic, lang: this.lang, userName: this.uname,
|
| 521 |
-
validEventIds: new Set(window.map(e => e.id)), unblocked: true,
|
| 522 |
-
});
|
| 523 |
-
this.broadcast({ t: "typing", on: false });
|
| 524 |
-
await this.emitBubbles(
|
| 525 |
-
bubbles.filter(b => b.type !== "reaction").map(b => ({ text: b.bubble, kind: b.type || "proactive" })),
|
| 526 |
-
{ paced: true, credit: Date.now() - tThink }
|
| 527 |
-
);
|
| 528 |
-
} catch (e) {
|
| 529 |
-
this.broadcast({ t: "typing", on: false });
|
| 530 |
-
} finally {
|
| 531 |
-
this.busy = false;
|
| 532 |
-
this.armIdle();
|
| 533 |
-
}
|
| 534 |
-
}
|
| 535 |
-
|
| 536 |
-
/* Did the user just say they're stepping away / asking to wait? Then ARIA must
|
| 537 |
-
NOT nag with idle pings ("jesteś?") — they'll be back or are mid-thought. */
|
| 538 |
-
userAskedToWait() {
|
| 539 |
-
const lastUser = [...this.recent].reverse().find(e => e.role === "user" && e.type === "message");
|
| 540 |
-
if (!lastUser) return false;
|
| 541 |
-
return _WAIT_RE.test(norm(lastUser.payload?.text || ""));
|
| 542 |
-
}
|
| 543 |
-
|
| 544 |
-
/* ---- idle / proactive ---- */
|
| 545 |
-
armIdle() {
|
| 546 |
-
this.clearIdle();
|
| 547 |
-
if (!this.sockets.size) return;
|
| 548 |
-
if (this.blocked) return; // blocked → no proactive pings
|
| 549 |
-
if (this.userTyping) return; // don't ping while user is typing
|
| 550 |
-
if (this.userAskedToWait()) return; // user is stepping away / asked to wait
|
| 551 |
-
if (this.idleCount >= LIMITS.IDLE_MAX_PER_TURN) return;
|
| 552 |
-
if (this.limited) return; // out of budget → stay silent
|
| 553 |
-
const since = Date.now();
|
| 554 |
-
const delay = LIMITS.IDLE_MIN_MS + Math.random() * (LIMITS.IDLE_MAX_MS - LIMITS.IDLE_MIN_MS);
|
| 555 |
-
this.idleTimer = setTimeout(() => {
|
| 556 |
-
if (this.userTyping) { this.armIdle(); return; } // re-check at fire time
|
| 557 |
-
this.idleCount++;
|
| 558 |
-
this.flushTurn(idleEvent(since));
|
| 559 |
-
}, delay);
|
| 560 |
-
}
|
| 561 |
-
clearIdle() { if (this.idleTimer) { clearTimeout(this.idleTimer); this.idleTimer = null; } }
|
| 562 |
-
|
| 563 |
-
/* One short check-in ping, in the language of the user's LAST message, not
|
| 564 |
-
repeating the previous nudge. Always returns exactly one proactive bubble. */
|
| 565 |
-
idleNudge() {
|
| 566 |
-
const lastUser = [...this.recent].reverse()
|
| 567 |
-
.find(e => e.role === "user" && e.type === "message");
|
| 568 |
-
const lang = detectLang(lastUser ? (lastUser.payload.text || "") : "");
|
| 569 |
-
const pool = lang === "en" ? IDLE_EN : IDLE_PL;
|
| 570 |
-
const opts = pool.filter(x => x.toLowerCase() !== (this.lastNudge || "").toLowerCase());
|
| 571 |
-
const from = opts.length ? opts : pool;
|
| 572 |
-
const pick = from[Math.floor(Math.random() * from.length)];
|
| 573 |
-
this.lastNudge = pick;
|
| 574 |
-
return [{ bubble: pick, target_event_id: null, type: "proactive" }];
|
| 575 |
-
}
|
| 576 |
-
|
| 577 |
-
trimRecent() {
|
| 578 |
-
if (this.recent.length > LIMITS.EVENTS_CONTEXT * 2)
|
| 579 |
-
this.recent = this.recent.slice(-LIMITS.EVENTS_CONTEXT * 2);
|
| 580 |
-
}
|
| 581 |
-
|
| 582 |
-
/* ---- D1 persistence (cross-device history) ---- */
|
| 583 |
-
async persistEvent(e) {
|
| 584 |
-
await this.env.DB.prepare(
|
| 585 |
-
"INSERT INTO aria_events (id, conversation_id, ts, type, payload, answered, created_at) " +
|
| 586 |
-
"VALUES (?, ?, ?, ?, ?, 0, ?)"
|
| 587 |
-
).bind(e.id, this.cid, e.ts, e.type, JSON.stringify(e.payload), Date.now())
|
| 588 |
-
.run().catch(() => {});
|
| 589 |
-
this.touchConvo();
|
| 590 |
-
}
|
| 591 |
-
async persistBubble(r) {
|
| 592 |
-
await this.env.DB.prepare(
|
| 593 |
-
"INSERT INTO aria_bubbles (id, conversation_id, target_event_id, reply_to, kind, text, created_at) " +
|
| 594 |
-
"VALUES (?, ?, ?, ?, ?, ?, ?)"
|
| 595 |
-
).bind(r.id, r.conversation_id, r.target_event_id, r.reply_to || null, r.kind, r.text, Date.now())
|
| 596 |
-
.run().catch(() => {});
|
| 597 |
-
this.touchConvo();
|
| 598 |
-
}
|
| 599 |
-
async markAnswered(events) {
|
| 600 |
-
const ids = events.map(e => e.id);
|
| 601 |
-
if (!ids.length) return;
|
| 602 |
-
const q = "UPDATE aria_events SET answered = 1 WHERE id IN (" +
|
| 603 |
-
ids.map(() => "?").join(",") + ")";
|
| 604 |
-
await this.env.DB.prepare(q).bind(...ids).run().catch(() => {});
|
| 605 |
-
}
|
| 606 |
-
touchConvo() {
|
| 607 |
-
this.env.DB.prepare("UPDATE aria_conversations SET updated_at = ? WHERE id = ?")
|
| 608 |
-
.bind(Date.now(), this.cid).run().catch(() => {});
|
| 609 |
-
}
|
| 610 |
-
|
| 611 |
-
async sendHistory(ws) {
|
| 612 |
-
if (!this.cid) return;
|
| 613 |
-
const convo = await this.env.DB.prepare("SELECT blocked FROM aria_conversations WHERE id = ?")
|
| 614 |
-
.bind(this.cid).first().catch(() => null);
|
| 615 |
-
this.blocked = !!(convo && convo.blocked); // stay silent (incl. proactive) while blocked
|
| 616 |
-
const ev = await this.env.DB.prepare(
|
| 617 |
-
"SELECT id, ts, type, payload, reaction FROM aria_events WHERE conversation_id = ? ORDER BY ts ASC LIMIT 200"
|
| 618 |
-
).bind(this.cid).all().catch(() => ({ results: [] }));
|
| 619 |
-
const bub = await this.env.DB.prepare(
|
| 620 |
-
"SELECT id, target_event_id, reply_to, kind, text, created_at, reaction FROM aria_bubbles WHERE conversation_id = ? ORDER BY created_at ASC LIMIT 200"
|
| 621 |
-
).bind(this.cid).all().catch(() => ({ results: [] }));
|
| 622 |
-
// Rehydrate rolling context — MERGE user events AND ARIA's bubbles in time
|
| 623 |
-
// order with correct roles. Previously only user events were loaded, so after a
|
| 624 |
-
// reconnect the model couldn't tell its own messages from the user's (caused
|
| 625 |
-
// repeats / confusion).
|
| 626 |
-
if (!this.recent.length) {
|
| 627 |
-
const evItems = (ev.results || []).map(r => ({
|
| 628 |
-
_t: r.ts, ts: r.ts, id: r.id,
|
| 629 |
-
role: r.type === "system_idle" ? "system" : "user",
|
| 630 |
-
type: r.type, payload: safeParse(r.payload),
|
| 631 |
-
}));
|
| 632 |
-
const bubItems = (bub.results || []).map(r => ({
|
| 633 |
-
_t: r.created_at, ts: r.created_at, id: r.id, role: "assistant",
|
| 634 |
-
type: "message", payload: { text: r.text },
|
| 635 |
-
}));
|
| 636 |
-
this.recent = [...evItems, ...bubItems]
|
| 637 |
-
.sort((a, z) => a._t - z._t)
|
| 638 |
-
.map(({ _t, ...rest }) => rest);
|
| 639 |
-
}
|
| 640 |
-
this.send(ws, {
|
| 641 |
-
t: "history",
|
| 642 |
-
events: (ev.results || []).map(r => ({ ...r, payload: safeParse(r.payload) })),
|
| 643 |
-
bubbles: bub.results || [],
|
| 644 |
-
});
|
| 645 |
-
try {
|
| 646 |
-
const u = await usageStatus(this.env, this.uid, this.uemail);
|
| 647 |
-
this.send(ws, { t: "usage", remaining: u.remaining, resetAt: u.resetAt, limit: u.limit });
|
| 648 |
-
} catch {}
|
| 649 |
-
}
|
| 650 |
-
|
| 651 |
-
/* ---- WS helpers ---- */
|
| 652 |
-
send(ws, obj) { try { ws.send(JSON.stringify(obj)); } catch {} }
|
| 653 |
-
broadcast(obj, except) { const s = JSON.stringify(obj); for (const ws of this.sockets) { if (ws === except) continue; try { ws.send(s); } catch {} } }
|
| 654 |
-
}
|
| 655 |
-
|
| 656 |
-
const safeParse = (s) => { try { return JSON.parse(s); } catch { return {}; } };
|
| 657 |
-
const norm = (s) => (s || "").trim().toLowerCase();
|
| 658 |
-
// Does the bubble look like a lead-in / unfinished thought (so we should wait
|
| 659 |
-
// for more)? Short with no end punctuation, ends with .../:, or a known opener.
|
| 660 |
-
const _LEADIN = /\b(dobra|okej|ok|czekaj|zaraz|słuchaj|sluchaj|posłuchaj|posluchaj|więc|wiec|bo|patrz|już ci|juz ci|mam pytanie|mam pomysł|mam pomysl|wiesz co|chwila|moment|sekund|sec|btw|aha)\b/;
|
| 661 |
-
function isLeadIn(t) {
|
| 662 |
-
if (!t) return true;
|
| 663 |
-
if (t.endsWith("...") || t.endsWith("…") || t.endsWith(":")) return true;
|
| 664 |
-
// (a generic "short = lead-in" rule was too broad — "ładnie dzisiaj" isn't a
|
| 665 |
-
// lead-in. Rely on explicit openers + the "2nd quick bubble" signal instead.)
|
| 666 |
-
return _LEADIN.test(t);
|
| 667 |
-
}
|
| 668 |
-
|
| 669 |
-
// User is stepping away or asking to wait → suppress idle "jesteś?" pings.
|
| 670 |
-
const _WAIT_RE = /(poczekaj|zaczekaj|czekaj|chwil(a|e|ę|eczk)|momen(t|cik)|sekund|zaraz (wracam|przyjd|wrócę|wroce)|już wracam|juz wracam|wracam za|musz[eę] (lecie[ćc]|spada[ćc]|i[śs][ćc]|wyj[śs][ćc]|odej[śs][ćc]|ogarn|co[śs] zrobi)|lec[eę] (na|do|coś|cos)|id[eę] (na|do|coś|cos)|oddzwoni|napisz[eę] (pó|po)źniej|wr[óo]c[eę] (za|póź|poz)|\bbrb\b|\bgtg\b|\bafk\b|\bsec\b|gotta go|be right back|hold on|one sec|give me a (sec|min))/i;
|
| 671 |
-
|
| 672 |
-
// Human reply delay per bubble: short bubbles (<5 words) = 1s; longer scale up to 8s.
|
| 673 |
-
const replyDelay = (text) => {
|
| 674 |
-
const s = (text || "").trim();
|
| 675 |
-
const words = s ? s.split(/\s+/).length : 0;
|
| 676 |
-
if (words < 5) return 1000;
|
| 677 |
-
return Math.min(8000, Math.max(1500, 600 + s.length * 80));
|
| 678 |
-
};
|
| 679 |
-
|
| 680 |
-
// Idle check-in pings (no trailing period, lowercase — messenger style).
|
| 681 |
-
const IDLE_PL = ["halo?", "jesteś?", "no i?", "halo halo?", "jesteś tam?",
|
| 682 |
-
"ej?", "no co tam?", "haloo?", "wróciłeś?", "ej halo?", "siedzisz tam?"];
|
| 683 |
-
const IDLE_EN = ["you there?", "hello?", "still there?", "you alive?", "helloo?",
|
| 684 |
-
"u there?", "yo?", "still with me?", "hey?", "anyone there?", "you back?", "hey you there?"];
|
| 685 |
-
|
| 686 |
-
// Guess the language of a piece of text: Polish if it has Polish diacritics or
|
| 687 |
-
// common Polish words, English if it has English markers; Polish by default.
|
| 688 |
-
function detectLang(text) {
|
| 689 |
-
const t = (text || "").toLowerCase();
|
| 690 |
-
if (/[ąćęłńóśźż]/.test(t)) return "pl";
|
| 691 |
-
const pl = /\b(nie|tak|cześć|czesc|jesteś|jestes|co|jak|dzięki|dzieki|gdzie|czemu|jestem|mam|robisz|siema|elo|dobra|spoko|kup|gruszki)\b/.test(t);
|
| 692 |
-
const en = /\b(the|you|do|are|what|hello|hi|can|yeah|yes|how|where|why|im|hey|your|with|me|good|thanks)\b/.test(t);
|
| 693 |
-
if (en && !pl) return "en";
|
| 694 |
-
return "pl"; // Polish-first
|
| 695 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cloudflare/aria-worker/src/events.js
DELETED
|
@@ -1,101 +0,0 @@
|
|
| 1 |
-
/* ============================================================
|
| 2 |
-
ARIA event & bubble contracts (single source of truth, JS side).
|
| 3 |
-
Mirrors brain/schema.py — keep the two in sync.
|
| 4 |
-
============================================================ */
|
| 5 |
-
|
| 6 |
-
export const EVENT_TYPES = ["message", "image", "file", "system_idle"];
|
| 7 |
-
export const BUBBLE_TYPES = ["response", "follow_up", "proactive", "reaction"];
|
| 8 |
-
|
| 9 |
-
// Messenger-style reactions. ❤️ means a casual "ok / nice", NOT romance.
|
| 10 |
-
export const ALLOWED_REACTIONS = ["❤️", "😆", "😮", "🥹", "😢", "😡"];
|
| 11 |
-
|
| 12 |
-
// Hard caps — defensive, the client is never trusted.
|
| 13 |
-
export const LIMITS = {
|
| 14 |
-
TEXT_MAX: 4000, // hard cap (defensive)
|
| 15 |
-
MSG_MAX: 400, // product limit: user message length
|
| 16 |
-
EVENTS_CONTEXT: 40, // recent events fed to the brain
|
| 17 |
-
WINDOW: 30, // sliding memory window sent to the model (token budget)
|
| 18 |
-
BUBBLES_MAX: 6, // bubbles accepted per turn
|
| 19 |
-
BUBBLE_CHARS: 1200, // chars per bubble
|
| 20 |
-
NAME_MAX: 300,
|
| 21 |
-
CLUSTER_DEBOUNCE_MS: 900, // (legacy) base debounce
|
| 22 |
-
// Adaptive clustering: wait for the user to finish a multi-bubble thought.
|
| 23 |
-
WAIT_QUESTION: 1200, // bubble ends with "?" → they asked, reply soon
|
| 24 |
-
WAIT_SINGLE: 2200, // a lone complete statement → normal
|
| 25 |
-
WAIT_BUILDUP: 10000, // user is clearly mid-stream → wait up to 10s for more
|
| 26 |
-
IDLE_MIN_MS: 15_000, // idle ping after 15–50s of silence (random)
|
| 27 |
-
IDLE_MAX_MS: 50_000,
|
| 28 |
-
IDLE_MAX_PER_TURN: 2, // up to two proactive nudges (spaced) before the next user msg
|
| 29 |
-
// spam guard: >SPAM_N msgs within SPAM_WINDOW → SPAM_GAP min spacing for SPAM_COOL
|
| 30 |
-
SPAM_N: 5, SPAM_WINDOW: 8_000, SPAM_GAP: 2_000, SPAM_COOL: 20_000,
|
| 31 |
-
};
|
| 32 |
-
|
| 33 |
-
export function newId(prefix = "evt") {
|
| 34 |
-
return `${prefix}_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
|
| 35 |
-
}
|
| 36 |
-
|
| 37 |
-
/** Validate + normalize a client-supplied event. Returns {ok, event|error}. */
|
| 38 |
-
export function normalizeEvent(raw) {
|
| 39 |
-
if (!raw || typeof raw !== "object") return { ok: false, error: "bad event" };
|
| 40 |
-
const type = raw.type;
|
| 41 |
-
if (!EVENT_TYPES.includes(type)) return { ok: false, error: "unknown type" };
|
| 42 |
-
if (type === "system_idle") return { ok: false, error: "system events are server-only" };
|
| 43 |
-
|
| 44 |
-
const id = typeof raw.id === "string" && raw.id ? raw.id.slice(0, 64) : newId();
|
| 45 |
-
const ts = Number.isFinite(raw.ts) ? raw.ts : Date.now();
|
| 46 |
-
// which earlier message this one replies to (Messenger-style quote)
|
| 47 |
-
const replyTo = typeof raw.reply_to === "string" && raw.reply_to
|
| 48 |
-
? raw.reply_to.slice(0, 64) : null;
|
| 49 |
-
let payload = {};
|
| 50 |
-
|
| 51 |
-
if (type === "message") {
|
| 52 |
-
const text = String(raw.payload?.text ?? "").slice(0, LIMITS.MSG_MAX).trim();
|
| 53 |
-
if (!text) return { ok: false, error: "empty message" };
|
| 54 |
-
payload = { text };
|
| 55 |
-
} else if (type === "image" || type === "file") {
|
| 56 |
-
const key = String(raw.payload?.key ?? "");
|
| 57 |
-
if (!/^aria\/[A-Za-z0-9/_.-]+$/.test(key)) return { ok: false, error: "bad media key" };
|
| 58 |
-
payload = {
|
| 59 |
-
key,
|
| 60 |
-
mime: String(raw.payload?.mime ?? "").slice(0, 120),
|
| 61 |
-
name: String(raw.payload?.name ?? "file").slice(0, LIMITS.NAME_MAX),
|
| 62 |
-
size: Number(raw.payload?.size) || 0,
|
| 63 |
-
};
|
| 64 |
-
}
|
| 65 |
-
if (replyTo) payload.reply_to = replyTo;
|
| 66 |
-
return { ok: true, event: { id, ts, type, payload } };
|
| 67 |
-
}
|
| 68 |
-
|
| 69 |
-
/** A server-emitted idle event. */
|
| 70 |
-
export function idleEvent(since) {
|
| 71 |
-
return { id: newId("sys"), ts: Date.now(), type: "system_idle", payload: { since } };
|
| 72 |
-
}
|
| 73 |
-
|
| 74 |
-
/** Validate + clamp the brain's bubble array. Always returns a safe array. */
|
| 75 |
-
export function sanitizeBubbles(raw, validEventIds) {
|
| 76 |
-
let arr = raw;
|
| 77 |
-
if (typeof raw === "string") { try { arr = JSON.parse(raw); } catch { arr = []; } }
|
| 78 |
-
if (!Array.isArray(arr)) arr = [];
|
| 79 |
-
const out = [];
|
| 80 |
-
for (const b of arr) {
|
| 81 |
-
if (out.length >= LIMITS.BUBBLES_MAX) break;
|
| 82 |
-
// models vary on the field name
|
| 83 |
-
const text = String(b?.bubble ?? b?.content ?? b?.text ?? b?.message ?? b?.emoji ?? "")
|
| 84 |
-
.slice(0, LIMITS.BUBBLE_CHARS).trim();
|
| 85 |
-
if (!text) continue;
|
| 86 |
-
const type = BUBBLE_TYPES.includes(b?.type) ? b.type : "response";
|
| 87 |
-
let target = b?.target_event_id;
|
| 88 |
-
if (!validEventIds || !validEventIds.has(target)) target = null;
|
| 89 |
-
// optional quote (Aria replying to a specific earlier message)
|
| 90 |
-
let replyTo = b?.reply_to;
|
| 91 |
-
if (!validEventIds || !validEventIds.has(replyTo)) replyTo = null;
|
| 92 |
-
// A reaction must be an allowed emoji aimed at a real event — else drop it.
|
| 93 |
-
if (type === "reaction") {
|
| 94 |
-
if (!ALLOWED_REACTIONS.includes(text) || !target) continue;
|
| 95 |
-
out.push({ bubble: text, target_event_id: target, type });
|
| 96 |
-
continue;
|
| 97 |
-
}
|
| 98 |
-
out.push({ bubble: text, target_event_id: target, reply_to: replyTo, type });
|
| 99 |
-
}
|
| 100 |
-
return out;
|
| 101 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cloudflare/aria-worker/src/index.js
DELETED
|
@@ -1,163 +0,0 @@
|
|
| 1 |
-
/* ============================================================
|
| 2 |
-
aria-worker entry.
|
| 3 |
-
|
| 4 |
-
Reached only via the Pages service binding (env.ARIA.fetch),
|
| 5 |
-
AFTER the Pages _worker.js has validated the nnl_session cookie
|
| 6 |
-
and the usage window. The trusted user id arrives in the
|
| 7 |
-
X-Aria-Uid header. The /media/* route is the one exception:
|
| 8 |
-
it is HMAC-signed and may be fetched by the public Space.
|
| 9 |
-
============================================================ */
|
| 10 |
-
|
| 11 |
-
import { AriaConversation } from "./conversation-do.js";
|
| 12 |
-
import { putMedia, serveMedia, verifyMediaSig, MEDIA } from "./r2.js";
|
| 13 |
-
import { LIMITS } from "./events.js";
|
| 14 |
-
|
| 15 |
-
export { AriaConversation };
|
| 16 |
-
|
| 17 |
-
const J = (o, s = 200) =>
|
| 18 |
-
new Response(JSON.stringify(o), { status: s, headers: { "Content-Type": "application/json" } });
|
| 19 |
-
|
| 20 |
-
export default {
|
| 21 |
-
async fetch(request, env) {
|
| 22 |
-
const url = new URL(request.url);
|
| 23 |
-
const parts = url.pathname.split("/").filter(Boolean); // ["api","aria",...]
|
| 24 |
-
const sub = parts[2] || "";
|
| 25 |
-
|
| 26 |
-
try {
|
| 27 |
-
// --- signed media (no uid header; verified by HMAC) ---
|
| 28 |
-
if (sub === "media") {
|
| 29 |
-
if (!env.ARIA_MEDIA) return new Response("Media unavailable", { status: 503 });
|
| 30 |
-
const key = decodeURIComponent(parts.slice(3).join("/"));
|
| 31 |
-
const ok = await verifyMediaSig(env, key, url.searchParams.get("exp"), url.searchParams.get("sig"));
|
| 32 |
-
if (!ok) return new Response("Forbidden", { status: 403 });
|
| 33 |
-
return serveMedia(env, key);
|
| 34 |
-
}
|
| 35 |
-
|
| 36 |
-
// Trusted uid from the Pages layer: REST passes it as a header, the
|
| 37 |
-
// WebSocket upgrade passes it in the query (header injection can strip the
|
| 38 |
-
// Upgrade header). Safe because this Worker is service-binding-only.
|
| 39 |
-
const uid = Number(request.headers.get("X-Aria-Uid")) || Number(url.searchParams.get("uid"));
|
| 40 |
-
if (!uid) return J({ error: "unauthorized" }, 401);
|
| 41 |
-
|
| 42 |
-
// --- conversation collection ---
|
| 43 |
-
if (sub === "conversations" && parts.length === 3) {
|
| 44 |
-
if (request.method === "GET") return listConvos(env, uid);
|
| 45 |
-
if (request.method === "POST") return createConvo(request, env, uid);
|
| 46 |
-
}
|
| 47 |
-
|
| 48 |
-
// --- single conversation ---
|
| 49 |
-
if (sub === "conversations" && parts[3]) {
|
| 50 |
-
const cid = parts[3];
|
| 51 |
-
if (!(await owns(env, cid, uid))) return J({ error: "not found" }, 404);
|
| 52 |
-
|
| 53 |
-
if (parts.length === 4) {
|
| 54 |
-
if (request.method === "GET") return getConvo(env, cid);
|
| 55 |
-
if (request.method === "PATCH") return patchConvo(request, env, cid);
|
| 56 |
-
if (request.method === "DELETE") return delConvo(env, cid);
|
| 57 |
-
}
|
| 58 |
-
if (parts[4] === "upload" && request.method === "POST")
|
| 59 |
-
return upload(request, env, uid);
|
| 60 |
-
if (parts[4] === "ws")
|
| 61 |
-
return openSocket(request, env, cid, uid, url);
|
| 62 |
-
}
|
| 63 |
-
|
| 64 |
-
return J({ error: "not found" }, 404);
|
| 65 |
-
} catch (e) {
|
| 66 |
-
return J({ error: "server error" }, 500);
|
| 67 |
-
}
|
| 68 |
-
},
|
| 69 |
-
};
|
| 70 |
-
|
| 71 |
-
/* ---------- conversations ---------- */
|
| 72 |
-
async function owns(env, cid, uid) {
|
| 73 |
-
const r = await env.DB.prepare("SELECT 1 FROM aria_conversations WHERE id = ? AND user_id = ?")
|
| 74 |
-
.bind(cid, uid).first();
|
| 75 |
-
return !!r;
|
| 76 |
-
}
|
| 77 |
-
|
| 78 |
-
async function listConvos(env, uid) {
|
| 79 |
-
const { results } = await env.DB.prepare(
|
| 80 |
-
"SELECT id, title, theme, muted, blocked, updated_at FROM aria_conversations " +
|
| 81 |
-
"WHERE user_id = ? ORDER BY updated_at DESC LIMIT 50"
|
| 82 |
-
).bind(uid).all();
|
| 83 |
-
return J({ conversations: results || [] });
|
| 84 |
-
}
|
| 85 |
-
|
| 86 |
-
async function createConvo(request, env, uid) {
|
| 87 |
-
const body = await request.json().catch(() => ({}));
|
| 88 |
-
const id = "ac_" + crypto.randomUUID();
|
| 89 |
-
const now = Date.now();
|
| 90 |
-
const title = String(body.title || "ARIA").slice(0, 200);
|
| 91 |
-
const theme = String(body.theme || "default").slice(0, 32);
|
| 92 |
-
await env.DB.prepare(
|
| 93 |
-
"INSERT INTO aria_conversations (id, user_id, title, theme, created_at, updated_at) " +
|
| 94 |
-
"VALUES (?, ?, ?, ?, ?, ?)"
|
| 95 |
-
).bind(id, uid, title, theme, now, now).run();
|
| 96 |
-
return J({ id, title, theme, created_at: now, updated_at: now }, 201);
|
| 97 |
-
}
|
| 98 |
-
|
| 99 |
-
async function getConvo(env, cid) {
|
| 100 |
-
const convo = await env.DB.prepare(
|
| 101 |
-
"SELECT id, title, theme, muted, blocked, topic, created_at, updated_at " +
|
| 102 |
-
"FROM aria_conversations WHERE id = ?"
|
| 103 |
-
).bind(cid).first();
|
| 104 |
-
const ev = await env.DB.prepare(
|
| 105 |
-
"SELECT id, ts, type, payload FROM aria_events WHERE conversation_id = ? ORDER BY ts ASC LIMIT 500"
|
| 106 |
-
).bind(cid).all();
|
| 107 |
-
const bub = await env.DB.prepare(
|
| 108 |
-
"SELECT id, target_event_id, kind, text, created_at FROM aria_bubbles WHERE conversation_id = ? ORDER BY created_at ASC LIMIT 500"
|
| 109 |
-
).bind(cid).all();
|
| 110 |
-
return J({ conversation: convo, events: ev.results || [], bubbles: bub.results || [] });
|
| 111 |
-
}
|
| 112 |
-
|
| 113 |
-
async function patchConvo(request, env, cid) {
|
| 114 |
-
const body = await request.json().catch(() => ({}));
|
| 115 |
-
const cols = [], vals = [];
|
| 116 |
-
if (typeof body.title === "string") { cols.push("title = ?"); vals.push(body.title.slice(0, 200)); }
|
| 117 |
-
if (typeof body.theme === "string") { cols.push("theme = ?"); vals.push(body.theme.slice(0, 32)); }
|
| 118 |
-
if (typeof body.muted === "boolean") { cols.push("muted = ?"); vals.push(body.muted ? 1 : 0); }
|
| 119 |
-
if (typeof body.blocked === "boolean") { cols.push("blocked = ?"); vals.push(body.blocked ? 1 : 0); }
|
| 120 |
-
if (!cols.length) return J({ ok: true });
|
| 121 |
-
cols.push("updated_at = ?"); vals.push(Date.now(), cid);
|
| 122 |
-
await env.DB.prepare(`UPDATE aria_conversations SET ${cols.join(", ")} WHERE id = ?`).bind(...vals).run();
|
| 123 |
-
return J({ ok: true });
|
| 124 |
-
}
|
| 125 |
-
|
| 126 |
-
async function delConvo(env, cid) {
|
| 127 |
-
await env.DB.batch([
|
| 128 |
-
env.DB.prepare("DELETE FROM aria_bubbles WHERE conversation_id = ?").bind(cid),
|
| 129 |
-
env.DB.prepare("DELETE FROM aria_events WHERE conversation_id = ?").bind(cid),
|
| 130 |
-
env.DB.prepare("DELETE FROM aria_conversations WHERE id = ?").bind(cid),
|
| 131 |
-
]);
|
| 132 |
-
return J({ ok: true });
|
| 133 |
-
}
|
| 134 |
-
|
| 135 |
-
/* ---------- media upload ---------- */
|
| 136 |
-
async function upload(request, env, uid) {
|
| 137 |
-
if (!env.ARIA_MEDIA) return J({ error: "Media upload isn't enabled yet." }, 503);
|
| 138 |
-
const name = request.headers.get("X-File-Name") || "file";
|
| 139 |
-
const type = request.headers.get("Content-Type") || "application/octet-stream";
|
| 140 |
-
const bytes = await request.arrayBuffer();
|
| 141 |
-
if (bytes.byteLength > MEDIA.MAX_BYTES) return J({ error: "file too large (max 12MB)" }, 413);
|
| 142 |
-
try {
|
| 143 |
-
const meta = await putMedia(env, uid, { name, type }, bytes);
|
| 144 |
-
return J(meta, 201);
|
| 145 |
-
} catch (e) {
|
| 146 |
-
return J({ error: "upload failed" }, 500);
|
| 147 |
-
}
|
| 148 |
-
}
|
| 149 |
-
|
| 150 |
-
/* ---------- websocket → Durable Object ---------- */
|
| 151 |
-
function openSocket(request, env, cid, uid, url) {
|
| 152 |
-
if (request.headers.get("Upgrade") !== "websocket")
|
| 153 |
-
return J({ error: "expected websocket" }, 426);
|
| 154 |
-
const id = env.ARIA_DO.idFromName(cid);
|
| 155 |
-
const stub = env.ARIA_DO.get(id);
|
| 156 |
-
const fwd = new URL(url);
|
| 157 |
-
fwd.searchParams.set("cid", cid);
|
| 158 |
-
fwd.searchParams.set("uid", String(uid));
|
| 159 |
-
fwd.searchParams.set("lang", url.searchParams.get("lang") || "auto");
|
| 160 |
-
fwd.searchParams.set("name", url.searchParams.get("name") || "");
|
| 161 |
-
fwd.searchParams.set("email", url.searchParams.get("email") || "");
|
| 162 |
-
return stub.fetch(new Request(fwd, request));
|
| 163 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cloudflare/aria-worker/src/orchestrator.js
DELETED
|
@@ -1,134 +0,0 @@
|
|
| 1 |
-
/* ============================================================
|
| 2 |
-
Orchestration: turn a clustered batch of events into a context
|
| 3 |
-
payload, call the ARIA Gradio Space, and return safe bubbles.
|
| 4 |
-
|
| 5 |
-
Mirrors the queue/join + queue/data SSE pattern used by the
|
| 6 |
-
existing NINA/LUNA proxy in the site's _worker.js.
|
| 7 |
-
============================================================ */
|
| 8 |
-
|
| 9 |
-
import { sanitizeBubbles, LIMITS } from "./events.js";
|
| 10 |
-
import { signMediaUrl } from "./r2.js";
|
| 11 |
-
|
| 12 |
-
const TURN_HARD_MS = 90_000;
|
| 13 |
-
|
| 14 |
-
/** Build the structured request the brain receives. */
|
| 15 |
-
async function buildContext(env, { events, recent, topic, lang, userName, replyTo, userReaction, unsent, comeback, unblocked }) {
|
| 16 |
-
// Resolve media keys → short-lived signed URLs the Space can GET.
|
| 17 |
-
const media = {};
|
| 18 |
-
for (const e of events) {
|
| 19 |
-
if (e.type === "image" || e.type === "file") {
|
| 20 |
-
media[e.id] = {
|
| 21 |
-
url: await signMediaUrl(env, e.payload.key),
|
| 22 |
-
mime: e.payload.mime, name: e.payload.name, kind: e.type,
|
| 23 |
-
};
|
| 24 |
-
}
|
| 25 |
-
}
|
| 26 |
-
// Compact transcript of recent history for topic/follow-up resolution.
|
| 27 |
-
const now = Date.now();
|
| 28 |
-
|
| 29 |
-
// Time sense (Europe/Warsaw): ARIA perceives the wall clock + each message's send time
|
| 30 |
-
// and how long ago it was — so she can react to the hour ("już po północy") or a long
|
| 31 |
-
// gap ("o, dawno cię nie było"). She must never state it like a robot (see persona).
|
| 32 |
-
const TZ = "Europe/Warsaw";
|
| 33 |
-
const fmtTime = new Intl.DateTimeFormat("pl-PL", { timeZone: TZ, hour: "2-digit", minute: "2-digit" });
|
| 34 |
-
const fmtDay = new Intl.DateTimeFormat("pl-PL", { timeZone: TZ, day: "2-digit", month: "2-digit" });
|
| 35 |
-
const fmtNow = new Intl.DateTimeFormat("pl-PL", { timeZone: TZ, weekday: "long", day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" });
|
| 36 |
-
const todayKey = fmtDay.format(now);
|
| 37 |
-
const stamp = (ms) => {
|
| 38 |
-
if (!ms) return null;
|
| 39 |
-
const t = fmtTime.format(ms);
|
| 40 |
-
return fmtDay.format(ms) === todayKey ? t : `${fmtDay.format(ms)} ${t}`; // add date only if not today
|
| 41 |
-
};
|
| 42 |
-
|
| 43 |
-
const history = recent.slice(-LIMITS.EVENTS_CONTEXT).map(e => ({
|
| 44 |
-
id: e.id, role: e.role || (e.type === "system_idle" ? "system" : "user"),
|
| 45 |
-
type: e.type,
|
| 46 |
-
ago: e.ts ? Math.max(0, Math.round((now - e.ts) / 1000)) : null, // seconds since sent
|
| 47 |
-
at: stamp(e.ts), // wall-clock, Europe/Warsaw
|
| 48 |
-
text: e.type === "message" ? e.payload.text
|
| 49 |
-
: e.type === "system_idle" ? "(user went quiet)"
|
| 50 |
-
: `(${e.type}: ${e.payload?.name || ""})`,
|
| 51 |
-
}));
|
| 52 |
-
return {
|
| 53 |
-
lang, // "auto" — brain defaults to Polish, mirrors the user
|
| 54 |
-
topic: topic || null, // last resolved topic (for "i gruszki")
|
| 55 |
-
user_name: userName || "",
|
| 56 |
-
now_text: fmtNow.format(now), // current local time (Europe/Warsaw)
|
| 57 |
-
reply_to: replyTo || null,
|
| 58 |
-
user_reaction: userReaction || null,
|
| 59 |
-
// bubbles ARIA composed but didn't send before the user cut in (resumable thread)
|
| 60 |
-
interrupted: (unsent && Array.isArray(unsent.texts) && unsent.texts.length) ? { texts: unsent.texts } : null,
|
| 61 |
-
comeback: !!comeback, // she's back after being "away" (over the limit) → apologise + catch up
|
| 62 |
-
unblocked: !!unblocked, // user just unblocked her → cheeky line about the block
|
| 63 |
-
turn_events: events.map(e => e.id),
|
| 64 |
-
media,
|
| 65 |
-
history,
|
| 66 |
-
};
|
| 67 |
-
}
|
| 68 |
-
|
| 69 |
-
/** Gradio differential-patch accumulation (Gradio 6.x). */
|
| 70 |
-
function applyPatches(prev, patch) {
|
| 71 |
-
if (!Array.isArray(patch)) return patch;
|
| 72 |
-
// Full-value replacement is the common case for a single string output.
|
| 73 |
-
if (patch.length && Array.isArray(patch[0])) return patch[patch.length - 1]?.[2] ?? prev;
|
| 74 |
-
return patch;
|
| 75 |
-
}
|
| 76 |
-
|
| 77 |
-
/**
|
| 78 |
-
* Call the ARIA Space. Returns sanitized bubble array.
|
| 79 |
-
* @param turn { events, recent, topic, lang, validEventIds }
|
| 80 |
-
*/
|
| 81 |
-
export async function runBrain(env, turn) {
|
| 82 |
-
const ctx = await buildContext(env, turn);
|
| 83 |
-
const root = env.ARIA_SPACE_ROOT;
|
| 84 |
-
|
| 85 |
-
let apiPrefix = "", fnIndex = 0;
|
| 86 |
-
try {
|
| 87 |
-
const cfg = await (await fetch(root + "/config")).json();
|
| 88 |
-
apiPrefix = cfg.api_prefix || "";
|
| 89 |
-
const i = (cfg.dependencies || []).findIndex(d => d.api_name === "respond");
|
| 90 |
-
if (i >= 0) fnIndex = i;
|
| 91 |
-
} catch { /* fall back to fn_index 0 */ }
|
| 92 |
-
|
| 93 |
-
const hash = Math.random().toString(36).slice(2) + Date.now().toString(36);
|
| 94 |
-
const join = await fetch(root + apiPrefix + "/queue/join", {
|
| 95 |
-
method: "POST", headers: { "Content-Type": "application/json" },
|
| 96 |
-
body: JSON.stringify({
|
| 97 |
-
data: [JSON.stringify(ctx)],
|
| 98 |
-
fn_index: fnIndex, session_hash: hash, event_data: null, trigger_id: null,
|
| 99 |
-
}),
|
| 100 |
-
});
|
| 101 |
-
if (!join.ok) throw new Error("brain join failed " + join.status);
|
| 102 |
-
await join.json().catch(() => {});
|
| 103 |
-
|
| 104 |
-
const sse = await fetch(root + apiPrefix + "/queue/data?session_hash=" + hash, {
|
| 105 |
-
headers: { Accept: "text/event-stream" },
|
| 106 |
-
});
|
| 107 |
-
const reader = sse.body.getReader();
|
| 108 |
-
const dec = new TextDecoder();
|
| 109 |
-
let buf = "", out = "", finished = false;
|
| 110 |
-
const deadline = Date.now() + TURN_HARD_MS;
|
| 111 |
-
|
| 112 |
-
while (!finished) {
|
| 113 |
-
if (Date.now() > deadline) { try { reader.cancel(); } catch {} break; }
|
| 114 |
-
const { value, done } = await reader.read();
|
| 115 |
-
if (done) break;
|
| 116 |
-
buf += dec.decode(value, { stream: true });
|
| 117 |
-
let nl;
|
| 118 |
-
while ((nl = buf.indexOf("\n")) >= 0) {
|
| 119 |
-
const line = buf.slice(0, nl).replace(/\r$/, ""); buf = buf.slice(nl + 1);
|
| 120 |
-
if (!line.startsWith("data: ")) continue;
|
| 121 |
-
let msg; try { msg = JSON.parse(line.slice(6)); } catch { continue; }
|
| 122 |
-
if (msg.msg === "close_stream") { finished = true; break; }
|
| 123 |
-
if (msg.msg === "process_completed") {
|
| 124 |
-
if (msg.success && msg.output?.data) out = msg.output.data[0] ?? out;
|
| 125 |
-
finished = true; break;
|
| 126 |
-
}
|
| 127 |
-
if (msg.msg === "process_generating" && msg.output?.data) {
|
| 128 |
-
out = applyPatches(out, msg.output.data[0]);
|
| 129 |
-
}
|
| 130 |
-
}
|
| 131 |
-
}
|
| 132 |
-
|
| 133 |
-
return sanitizeBubbles(out, turn.validEventIds);
|
| 134 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cloudflare/aria-worker/src/r2.js
DELETED
|
@@ -1,74 +0,0 @@
|
|
| 1 |
-
/* ============================================================
|
| 2 |
-
R2 media: upload through the Worker, serve via short-lived
|
| 3 |
-
HMAC-signed GET URLs so the public Gradio Space can fetch an
|
| 4 |
-
image without the bucket being public.
|
| 5 |
-
|
| 6 |
-
Requires:
|
| 7 |
-
env.ARIA_MEDIA R2 bucket binding
|
| 8 |
-
env.PUBLIC_BASE e.g. "https://app.nnlabs.pl"
|
| 9 |
-
env.ARIA_SIGNING_KEY secret (wrangler secret put ARIA_SIGNING_KEY)
|
| 10 |
-
============================================================ */
|
| 11 |
-
|
| 12 |
-
export const MEDIA = {
|
| 13 |
-
MAX_BYTES: 12 * 1024 * 1024, // 12 MB per upload
|
| 14 |
-
IMAGE_MIME: /^image\/(png|jpe?g|webp|gif|heic)$/i,
|
| 15 |
-
URL_TTL: 600, // signed GET valid 10 min
|
| 16 |
-
};
|
| 17 |
-
|
| 18 |
-
const enc = new TextEncoder();
|
| 19 |
-
|
| 20 |
-
async function hmacKey(env) {
|
| 21 |
-
return crypto.subtle.importKey(
|
| 22 |
-
"raw", enc.encode(env.ARIA_SIGNING_KEY || "dev-insecure-key"),
|
| 23 |
-
{ name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]
|
| 24 |
-
);
|
| 25 |
-
}
|
| 26 |
-
|
| 27 |
-
function b64url(buf) {
|
| 28 |
-
return btoa(String.fromCharCode(...new Uint8Array(buf)))
|
| 29 |
-
.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
| 30 |
-
}
|
| 31 |
-
|
| 32 |
-
/** Store bytes in R2 under a namespaced key. Returns the key. */
|
| 33 |
-
export async function putMedia(env, userId, file, bytes) {
|
| 34 |
-
if (bytes.byteLength > MEDIA.MAX_BYTES) throw new Error("file too large");
|
| 35 |
-
const safeName = (file.name || "file").replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 80);
|
| 36 |
-
const key = `aria/${userId}/${Date.now().toString(36)}-${crypto.randomUUID().slice(0, 8)}-${safeName}`;
|
| 37 |
-
await env.ARIA_MEDIA.put(key, bytes, {
|
| 38 |
-
httpMetadata: { contentType: file.type || "application/octet-stream" },
|
| 39 |
-
});
|
| 40 |
-
return { key, mime: file.type || "application/octet-stream", name: safeName, size: bytes.byteLength };
|
| 41 |
-
}
|
| 42 |
-
|
| 43 |
-
/** Short-lived signed GET URL for a key (handed to the brain). */
|
| 44 |
-
export async function signMediaUrl(env, key) {
|
| 45 |
-
const exp = Math.floor(Date.now() / 1000) + MEDIA.URL_TTL;
|
| 46 |
-
const k = await hmacKey(env);
|
| 47 |
-
const sig = b64url(await crypto.subtle.sign("HMAC", k, enc.encode(`${key}.${exp}`)));
|
| 48 |
-
const base = (env.PUBLIC_BASE || "").replace(/\/$/, "");
|
| 49 |
-
return `${base}/api/aria/media/${encodeURIComponent(key)}?exp=${exp}&sig=${sig}`;
|
| 50 |
-
}
|
| 51 |
-
|
| 52 |
-
export async function verifyMediaSig(env, key, exp, sig) {
|
| 53 |
-
if (!exp || !sig) return false;
|
| 54 |
-
if (Number(exp) < Math.floor(Date.now() / 1000)) return false;
|
| 55 |
-
const k = await hmacKey(env);
|
| 56 |
-
try {
|
| 57 |
-
return await crypto.subtle.verify(
|
| 58 |
-
"HMAC", k,
|
| 59 |
-
Uint8Array.from(atob(sig.replace(/-/g, "+").replace(/_/g, "/")), c => c.charCodeAt(0)),
|
| 60 |
-
enc.encode(`${key}.${exp}`)
|
| 61 |
-
);
|
| 62 |
-
} catch { return false; }
|
| 63 |
-
}
|
| 64 |
-
|
| 65 |
-
/** Stream an object out of R2 (used by GET /api/aria/media/:key). */
|
| 66 |
-
export async function serveMedia(env, key) {
|
| 67 |
-
const obj = await env.ARIA_MEDIA.get(key);
|
| 68 |
-
if (!obj) return new Response("Not found", { status: 404 });
|
| 69 |
-
const h = new Headers();
|
| 70 |
-
obj.writeHttpMetadata(h);
|
| 71 |
-
h.set("etag", obj.httpEtag);
|
| 72 |
-
h.set("Cache-Control", "private, max-age=600");
|
| 73 |
-
return new Response(obj.body, { headers: h });
|
| 74 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cloudflare/aria-worker/src/usage.js
DELETED
|
@@ -1,67 +0,0 @@
|
|
| 1 |
-
/* ============================================================
|
| 2 |
-
ARIA per-user message budget: 20 messages / rolling 5h window.
|
| 3 |
-
Separate from the site's model_usage pool (NINA/IRIS/LUNA).
|
| 4 |
-
|
| 5 |
-
Window semantics mirror the existing _worker.js usage:
|
| 6 |
-
the window starts at the first message and resets after 5h.
|
| 7 |
-
Counting happens in the Durable Object, the only layer that
|
| 8 |
-
sees each individual message inside the WebSocket.
|
| 9 |
-
============================================================ */
|
| 10 |
-
|
| 11 |
-
export const ARIA_MSG_LIMIT = 50;
|
| 12 |
-
export const ARIA_WINDOW = 5 * 60 * 60 * 1000; // 5h in ms
|
| 13 |
-
|
| 14 |
-
async function getRow(env, uid, email) {
|
| 15 |
-
const row = await env.DB.prepare(
|
| 16 |
-
"SELECT user_id, window_start, used FROM aria_usage WHERE user_id = ?"
|
| 17 |
-
).bind(uid).first();
|
| 18 |
-
if (!row) await env.DB.prepare("INSERT OR IGNORE INTO aria_usage (user_id) VALUES (?)").bind(uid).run();
|
| 19 |
-
// Keep the owner's email on the usage row (added by migration). Defensive: a
|
| 20 |
-
// separate, catch-guarded write so a missing column never breaks the counter.
|
| 21 |
-
if (email) env.DB.prepare("UPDATE aria_usage SET email = ? WHERE user_id = ?").bind(email, uid).run().catch(() => {});
|
| 22 |
-
return row || { user_id: uid, window_start: 0, used: 0 };
|
| 23 |
-
}
|
| 24 |
-
|
| 25 |
-
/** Read-only view of the budget (no mutation). */
|
| 26 |
-
export async function usageStatus(env, uid, email) {
|
| 27 |
-
const now = Date.now();
|
| 28 |
-
const row = await getRow(env, uid, email);
|
| 29 |
-
let ws = row.window_start, used = row.used;
|
| 30 |
-
if (!ws || now - ws >= ARIA_WINDOW) { ws = 0; used = 0; }
|
| 31 |
-
return {
|
| 32 |
-
limit: ARIA_MSG_LIMIT,
|
| 33 |
-
used,
|
| 34 |
-
remaining: Math.max(0, ARIA_MSG_LIMIT - used),
|
| 35 |
-
resetAt: ws ? ws + ARIA_WINDOW : 0,
|
| 36 |
-
};
|
| 37 |
-
}
|
| 38 |
-
|
| 39 |
-
/**
|
| 40 |
-
* Try to consume one message from the budget.
|
| 41 |
-
* @returns { ok, remaining, resetAt, limit }
|
| 42 |
-
* ok=false when the window is full.
|
| 43 |
-
*/
|
| 44 |
-
export async function consume(env, uid, email) {
|
| 45 |
-
const now = Date.now();
|
| 46 |
-
// A couple of optimistic-locked attempts in case of concurrent messages.
|
| 47 |
-
for (let attempt = 0; attempt < 3; attempt++) {
|
| 48 |
-
const row = await getRow(env, uid, email);
|
| 49 |
-
let ws = row.window_start, used = row.used;
|
| 50 |
-
if (!ws || now - ws >= ARIA_WINDOW) { ws = now; used = 0; } // start / reset
|
| 51 |
-
|
| 52 |
-
if (used >= ARIA_MSG_LIMIT) {
|
| 53 |
-
return { ok: false, remaining: 0, resetAt: ws + ARIA_WINDOW, limit: ARIA_MSG_LIMIT };
|
| 54 |
-
}
|
| 55 |
-
|
| 56 |
-
const res = await env.DB.prepare(
|
| 57 |
-
"UPDATE aria_usage SET window_start = ?, used = ? " +
|
| 58 |
-
"WHERE user_id = ? AND window_start = ? AND used = ?"
|
| 59 |
-
).bind(ws, used + 1, uid, row.window_start, row.used).run();
|
| 60 |
-
|
| 61 |
-
if (res.meta.changes) {
|
| 62 |
-
return { ok: true, remaining: ARIA_MSG_LIMIT - (used + 1), resetAt: ws + ARIA_WINDOW, limit: ARIA_MSG_LIMIT };
|
| 63 |
-
}
|
| 64 |
-
// lost the race — retry with fresh values
|
| 65 |
-
}
|
| 66 |
-
return { ok: false, remaining: 0, resetAt: now + ARIA_WINDOW, limit: ARIA_MSG_LIMIT, retry: true };
|
| 67 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cloudflare/aria-worker/wrangler.jsonc
DELETED
|
@@ -1,59 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
// ============================================================
|
| 3 |
-
// aria-worker — standalone Worker that owns ARIA's realtime
|
| 4 |
-
// backend: the AriaConversation Durable Object + R2 media.
|
| 5 |
-
//
|
| 6 |
-
// The Pages app (app.nnlabs.pl) reaches this via a *service
|
| 7 |
-
// binding* named ARIA, after it has already validated the
|
| 8 |
-
// nnl_session cookie + usage window. This Worker is not meant
|
| 9 |
-
// to be exposed on its own public hostname.
|
| 10 |
-
//
|
| 11 |
-
// Deploy: wrangler deploy
|
| 12 |
-
// Dev: wrangler dev
|
| 13 |
-
// Secrets: (none required; brain is public Space)
|
| 14 |
-
// ============================================================
|
| 15 |
-
"$schema": "node_modules/wrangler/config-schema.json",
|
| 16 |
-
"name": "aria-worker",
|
| 17 |
-
"main": "src/index.js",
|
| 18 |
-
"compatibility_date": "2025-05-01",
|
| 19 |
-
"compatibility_flags": ["nodejs_compat"],
|
| 20 |
-
|
| 21 |
-
// No public URL: this Worker is reachable ONLY via the Pages service binding,
|
| 22 |
-
// which is the trust boundary that validates the session. Without this, the
|
| 23 |
-
// workers.dev URL would let anyone forge the X-Aria-Uid header.
|
| 24 |
-
"workers_dev": false,
|
| 25 |
-
|
| 26 |
-
"durable_objects": {
|
| 27 |
-
"bindings": [
|
| 28 |
-
{ "name": "ARIA_DO", "class_name": "AriaConversation" }
|
| 29 |
-
]
|
| 30 |
-
},
|
| 31 |
-
// SQLite-backed Durable Object (storage API lives inside the DO).
|
| 32 |
-
"migrations": [
|
| 33 |
-
{ "tag": "v1", "new_sqlite_classes": ["AriaConversation"] }
|
| 34 |
-
],
|
| 35 |
-
|
| 36 |
-
// TODO(R2): re-enable once R2 is turned on in the dashboard, then:
|
| 37 |
-
// wrangler r2 bucket create aria-media && wrangler deploy
|
| 38 |
-
// Until then the worker runs text-only; image/file upload returns an error.
|
| 39 |
-
// "r2_buckets": [
|
| 40 |
-
// { "binding": "ARIA_MEDIA", "bucket_name": "aria-media" }
|
| 41 |
-
// ],
|
| 42 |
-
|
| 43 |
-
// Shared with the rest of the site. id taken from APP_WEBSITE/wrangler.toml.
|
| 44 |
-
"d1_databases": [
|
| 45 |
-
{
|
| 46 |
-
"binding": "DB",
|
| 47 |
-
"database_name": "app-nnlabs-db",
|
| 48 |
-
"database_id": "3885ce74-4ac8-4ee8-b88c-34ccdfca7c27"
|
| 49 |
-
}
|
| 50 |
-
],
|
| 51 |
-
|
| 52 |
-
"vars": {
|
| 53 |
-
"ARIA_SPACE_ROOT": "https://nextneural-aria.hf.space",
|
| 54 |
-
"PUBLIC_BASE": "https://app.nnlabs.pl"
|
| 55 |
-
},
|
| 56 |
-
// Secret (not stored here): wrangler secret put ARIA_SIGNING_KEY
|
| 57 |
-
|
| 58 |
-
"observability": { "enabled": true }
|
| 59 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cloudflare/db/migration_aria.sql
DELETED
|
@@ -1,58 +0,0 @@
|
|
| 1 |
-
-- ============================================================
|
| 2 |
-
-- ARIA tables — additive migration for the shared D1 (app-nnlabs-db).
|
| 3 |
-
-- Apply: wrangler d1 execute app-nnlabs-db --file=cloudflare/db/migration_aria.sql --remote
|
| 4 |
-
-- Safe to re-run (IF NOT EXISTS). Touches no NINA/IRIS/LUNA tables.
|
| 5 |
-
-- ============================================================
|
| 6 |
-
|
| 7 |
-
-- One chat per row, owned by an existing user (users.id from the auth system).
|
| 8 |
-
CREATE TABLE IF NOT EXISTS aria_conversations (
|
| 9 |
-
id TEXT PRIMARY KEY,
|
| 10 |
-
user_id INTEGER NOT NULL,
|
| 11 |
-
title TEXT NOT NULL DEFAULT 'ARIA',
|
| 12 |
-
theme TEXT NOT NULL DEFAULT 'default', -- chat theme (settings menu)
|
| 13 |
-
muted INTEGER NOT NULL DEFAULT 0, -- playful "mute ARIA"
|
| 14 |
-
blocked INTEGER NOT NULL DEFAULT 0, -- playful "block ARIA"
|
| 15 |
-
topic TEXT, -- last resolved topic (follow-up chaining)
|
| 16 |
-
created_at INTEGER NOT NULL,
|
| 17 |
-
updated_at INTEGER NOT NULL
|
| 18 |
-
);
|
| 19 |
-
CREATE INDEX IF NOT EXISTS idx_aria_convos_user ON aria_conversations(user_id, updated_at DESC);
|
| 20 |
-
|
| 21 |
-
-- Append-only event log (message / image / file / system_idle).
|
| 22 |
-
CREATE TABLE IF NOT EXISTS aria_events (
|
| 23 |
-
id TEXT PRIMARY KEY,
|
| 24 |
-
conversation_id TEXT NOT NULL,
|
| 25 |
-
ts INTEGER NOT NULL,
|
| 26 |
-
type TEXT NOT NULL, -- message | image | file | system_idle
|
| 27 |
-
payload TEXT NOT NULL, -- JSON
|
| 28 |
-
answered INTEGER NOT NULL DEFAULT 0,
|
| 29 |
-
created_at INTEGER NOT NULL
|
| 30 |
-
);
|
| 31 |
-
CREATE INDEX IF NOT EXISTS idx_aria_events_convo ON aria_events(conversation_id, ts ASC);
|
| 32 |
-
|
| 33 |
-
-- Assistant bubbles, each tied to the event it responds to (or null for proactive).
|
| 34 |
-
CREATE TABLE IF NOT EXISTS aria_bubbles (
|
| 35 |
-
id TEXT PRIMARY KEY,
|
| 36 |
-
conversation_id TEXT NOT NULL,
|
| 37 |
-
target_event_id TEXT, -- which event this answers (nullable)
|
| 38 |
-
kind TEXT NOT NULL, -- response | follow_up | proactive
|
| 39 |
-
text TEXT NOT NULL,
|
| 40 |
-
created_at INTEGER NOT NULL
|
| 41 |
-
);
|
| 42 |
-
CREATE INDEX IF NOT EXISTS idx_aria_bubbles_convo ON aria_bubbles(conversation_id, created_at ASC);
|
| 43 |
-
|
| 44 |
-
-- Per-user message budget: 20 messages per rolling 5h window. Separate from the
|
| 45 |
-
-- NINA/IRIS/LUNA model_usage pool (a messenger chat sends far more, shorter turns).
|
| 46 |
-
-- window_start = ms of the first message in the current window; resets after 5h.
|
| 47 |
-
CREATE TABLE IF NOT EXISTS aria_usage (
|
| 48 |
-
user_id INTEGER PRIMARY KEY,
|
| 49 |
-
window_start INTEGER NOT NULL DEFAULT 0,
|
| 50 |
-
used INTEGER NOT NULL DEFAULT 0
|
| 51 |
-
);
|
| 52 |
-
|
| 53 |
-
-- Reactions (Messenger-style). One emoji per message.
|
| 54 |
-
-- aria_events.reaction = ARIA's reaction to a user message
|
| 55 |
-
-- aria_bubbles.reaction = the user's reaction to ARIA's message
|
| 56 |
-
-- Applied separately (D1 has no IF NOT EXISTS for columns); safe-guarded in code.
|
| 57 |
-
-- ALTER TABLE aria_events ADD COLUMN reaction TEXT;
|
| 58 |
-
-- ALTER TABLE aria_bubbles ADD COLUMN reaction TEXT;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cloudflare/db/migration_aria_email.sql
DELETED
|
@@ -1,45 +0,0 @@
|
|
| 1 |
-
-- ============================================================
|
| 2 |
-
-- ARIA: email on the usage row + read-by-email views.
|
| 3 |
-
-- Apply ONCE:
|
| 4 |
-
-- wrangler d1 execute app-nnlabs-db --file=cloudflare/db/migration_aria_email.sql --remote
|
| 5 |
-
-- Note: the ALTER errors if re-run (column already exists) — that's expected,
|
| 6 |
-
-- the rest (views/backfill) is idempotent.
|
| 7 |
-
-- ============================================================
|
| 8 |
-
|
| 9 |
-
-- email on the per-user budget row (requested), kept fresh by the worker.
|
| 10 |
-
ALTER TABLE aria_usage ADD COLUMN email TEXT;
|
| 11 |
-
|
| 12 |
-
-- backfill existing usage rows from the auth users table.
|
| 13 |
-
UPDATE aria_usage
|
| 14 |
-
SET email = (SELECT u.email FROM users u WHERE u.id = aria_usage.user_id)
|
| 15 |
-
WHERE email IS NULL;
|
| 16 |
-
|
| 17 |
-
-- Read each user's conversations by email (no manual JOIN at query time):
|
| 18 |
-
-- SELECT * FROM aria_conversations_by_email WHERE email = 'x@y.z';
|
| 19 |
-
CREATE VIEW IF NOT EXISTS aria_conversations_by_email AS
|
| 20 |
-
SELECT u.email, u.name AS user_name, c.*
|
| 21 |
-
FROM aria_conversations c
|
| 22 |
-
JOIN users u ON u.id = c.user_id;
|
| 23 |
-
|
| 24 |
-
-- Clean chronological transcript per user email (readable text + UTC time):
|
| 25 |
-
-- SELECT at_utc, sender, text FROM aria_messages_by_email WHERE email = 'x@y.z';
|
| 26 |
-
-- (see migration_aria_transcript.sql to rebuild this view on an existing DB)
|
| 27 |
-
CREATE VIEW IF NOT EXISTS aria_messages_by_email AS
|
| 28 |
-
SELECT u.email AS email, e.ts AS ts, datetime(e.ts / 1000, 'unixepoch') AS at_utc,
|
| 29 |
-
'user' AS sender,
|
| 30 |
-
CASE e.type
|
| 31 |
-
WHEN 'message' THEN json_extract(e.payload, '$.text')
|
| 32 |
-
ELSE '[' || e.type || ': ' || COALESCE(json_extract(e.payload, '$.name'), '') || ']'
|
| 33 |
-
END AS text,
|
| 34 |
-
c.id AS conversation_id
|
| 35 |
-
FROM aria_events e
|
| 36 |
-
JOIN aria_conversations c ON c.id = e.conversation_id
|
| 37 |
-
JOIN users u ON u.id = c.user_id
|
| 38 |
-
WHERE e.type IN ('message', 'image', 'file')
|
| 39 |
-
UNION ALL
|
| 40 |
-
SELECT u.email AS email, b.created_at AS ts, datetime(b.created_at / 1000, 'unixepoch') AS at_utc,
|
| 41 |
-
'aria' AS sender, b.text AS text, c.id AS conversation_id
|
| 42 |
-
FROM aria_bubbles b
|
| 43 |
-
JOIN aria_conversations c ON c.id = b.conversation_id
|
| 44 |
-
JOIN users u ON u.id = c.user_id
|
| 45 |
-
ORDER BY email, ts;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cloudflare/db/migration_aria_transcript.sql
DELETED
|
@@ -1,35 +0,0 @@
|
|
| 1 |
-
-- Rebuild aria_messages_by_email as a clean, chronological transcript:
|
| 2 |
-
-- email · ts · at_utc · sender · text · conversation_id
|
| 3 |
-
-- User message text is pulled out of the JSON payload; attachments shown as [type: name].
|
| 4 |
-
-- Apply:
|
| 5 |
-
-- wrangler d1 execute app-nnlabs-db --file=cloudflare/db/migration_aria_transcript.sql --remote
|
| 6 |
-
-- Read one user's chat:
|
| 7 |
-
-- SELECT at_utc, sender, text FROM aria_messages_by_email WHERE email = 'x@y.z';
|
| 8 |
-
|
| 9 |
-
DROP VIEW IF EXISTS aria_messages_by_email;
|
| 10 |
-
|
| 11 |
-
CREATE VIEW aria_messages_by_email AS
|
| 12 |
-
SELECT u.email AS email,
|
| 13 |
-
e.ts AS ts,
|
| 14 |
-
datetime(e.ts / 1000, 'unixepoch') AS at_utc,
|
| 15 |
-
'user' AS sender,
|
| 16 |
-
CASE e.type
|
| 17 |
-
WHEN 'message' THEN json_extract(e.payload, '$.text')
|
| 18 |
-
ELSE '[' || e.type || ': ' || COALESCE(json_extract(e.payload, '$.name'), '') || ']'
|
| 19 |
-
END AS text,
|
| 20 |
-
c.id AS conversation_id
|
| 21 |
-
FROM aria_events e
|
| 22 |
-
JOIN aria_conversations c ON c.id = e.conversation_id
|
| 23 |
-
JOIN users u ON u.id = c.user_id
|
| 24 |
-
WHERE e.type IN ('message', 'image', 'file')
|
| 25 |
-
UNION ALL
|
| 26 |
-
SELECT u.email AS email,
|
| 27 |
-
b.created_at AS ts,
|
| 28 |
-
datetime(b.created_at / 1000, 'unixepoch') AS at_utc,
|
| 29 |
-
'aria' AS sender,
|
| 30 |
-
b.text AS text,
|
| 31 |
-
c.id AS conversation_id
|
| 32 |
-
FROM aria_bubbles b
|
| 33 |
-
JOIN aria_conversations c ON c.id = b.conversation_id
|
| 34 |
-
JOIN users u ON u.id = c.user_id
|
| 35 |
-
ORDER BY email, ts;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cloudflare/integrate.sh
DELETED
|
@@ -1,70 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env bash
|
| 2 |
-
# ============================================================
|
| 3 |
-
# Additively install ARIA's frontend into the live site
|
| 4 |
-
# (~/desktop/NNLABS.PL/WEBSITE/APP_WEBSITE). Never overwrites an
|
| 5 |
-
# existing, differing file — it stops and tells you instead, so
|
| 6 |
-
# NINA / IRIS / LUNA can't be clobbered.
|
| 7 |
-
#
|
| 8 |
-
# This handles the static frontend only. Three steps stay manual
|
| 9 |
-
# (printed at the end): the _worker.js merge, the dashboard service
|
| 10 |
-
# binding, and the resource provisioning (R2 / D1 / secret).
|
| 11 |
-
# ============================================================
|
| 12 |
-
set -euo pipefail
|
| 13 |
-
|
| 14 |
-
SRC="$(cd "$(dirname "$0")" && pwd)/pages-integration"
|
| 15 |
-
DEST="${1:-$HOME/desktop/NNLABS.PL/WEBSITE/APP_WEBSITE}"
|
| 16 |
-
|
| 17 |
-
if [[ ! -d "$DEST" ]]; then
|
| 18 |
-
echo "✗ Destination not found: $DEST"
|
| 19 |
-
echo " Pass it explicitly: ./integrate.sh /path/to/APP_WEBSITE"
|
| 20 |
-
exit 1
|
| 21 |
-
fi
|
| 22 |
-
|
| 23 |
-
copy() { # copy SRC/$1 → DEST/$1, refusing to overwrite a different file
|
| 24 |
-
local rel="$1" from="$SRC/$1" to="$DEST/$1"
|
| 25 |
-
mkdir -p "$(dirname "$to")"
|
| 26 |
-
if [[ -e "$to" ]] && ! cmp -s "$from" "$to"; then
|
| 27 |
-
echo "✗ EXISTS & DIFFERS, skipping: $rel"
|
| 28 |
-
echo " review: diff '$to' '$from'"
|
| 29 |
-
return
|
| 30 |
-
fi
|
| 31 |
-
cp "$from" "$to"
|
| 32 |
-
echo "✓ $rel"
|
| 33 |
-
}
|
| 34 |
-
|
| 35 |
-
echo "Installing ARIA frontend → $DEST"
|
| 36 |
-
copy "aria.html"
|
| 37 |
-
copy "css/aria.css"
|
| 38 |
-
copy "js/aria-chat.js"
|
| 39 |
-
copy "js/aria-settings.js"
|
| 40 |
-
|
| 41 |
-
cat <<'NEXT'
|
| 42 |
-
|
| 43 |
-
────────────────────────────────────────────────────────────
|
| 44 |
-
Manual steps remaining:
|
| 45 |
-
|
| 46 |
-
1. _worker.js — merge cloudflare/pages-integration/_worker.aria.js
|
| 47 |
-
(two clearly-marked pieces; reuses the existing currentUser()).
|
| 48 |
-
|
| 49 |
-
2. Provision resources (once):
|
| 50 |
-
wrangler r2 bucket create aria-media
|
| 51 |
-
wrangler d1 execute app-nnlabs-db \
|
| 52 |
-
--file=cloudflare/db/migration_aria.sql --remote
|
| 53 |
-
|
| 54 |
-
3. Deploy the realtime backend:
|
| 55 |
-
cd cloudflare/aria-worker
|
| 56 |
-
wrangler secret put ARIA_SIGNING_KEY # any long random string
|
| 57 |
-
wrangler deploy
|
| 58 |
-
|
| 59 |
-
4. Pages dashboard → app-nnlabs → Settings → Functions → Service bindings:
|
| 60 |
-
add ARIA → aria-worker
|
| 61 |
-
|
| 62 |
-
5. Deploy the brain Space (separate): push this repo to the
|
| 63 |
-
nextneural-aria Hugging Face Space; set HF_TOKEN as a Space secret.
|
| 64 |
-
|
| 65 |
-
6. Deploy the site:
|
| 66 |
-
wrangler pages deploy APP_WEBSITE --project-name=app-nnlabs
|
| 67 |
-
|
| 68 |
-
Then open https://app.nnlabs.pl/aria
|
| 69 |
-
────────────────────────────────────────────────────────────
|
| 70 |
-
NEXT
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cloudflare/pages-integration/_worker.aria.js
DELETED
|
@@ -1,63 +0,0 @@
|
|
| 1 |
-
/* ============================================================
|
| 2 |
-
ARIA integration snippet for APP_WEBSITE/_worker.js
|
| 3 |
-
------------------------------------------------------------
|
| 4 |
-
This is NOT a standalone file — paste the two pieces below into
|
| 5 |
-
the existing Pages _worker.js. It is additive: it adds /api/aria/*
|
| 6 |
-
and touches nothing else.
|
| 7 |
-
|
| 8 |
-
PREREQS (Pages dashboard → Settings → Functions):
|
| 9 |
-
• Service binding: ARIA → aria-worker (the standalone Worker)
|
| 10 |
-
|
| 11 |
-
The aria-worker enforces nothing about identity; THIS layer is the
|
| 12 |
-
trust boundary. We validate the existing nnl_session cookie here and
|
| 13 |
-
pass the user id to the worker as X-Aria-Uid. The /api/aria/media/*
|
| 14 |
-
route is the one public exception (HMAC-signed; the brain fetches it).
|
| 15 |
-
============================================================ */
|
| 16 |
-
|
| 17 |
-
/* ---- STEP 1: add this route inside `export default { async fetch() }`,
|
| 18 |
-
right after the existing `if (url.pathname.startsWith("/api/luna"))`
|
| 19 |
-
block and before the final fallthrough. ---- */
|
| 20 |
-
//
|
| 21 |
-
// if (url.pathname.startsWith("/api/aria")) {
|
| 22 |
-
// try {
|
| 23 |
-
// return await handleAriaApi(request, env, url);
|
| 24 |
-
// } catch {
|
| 25 |
-
// return json({ error: "Server error." }, 500);
|
| 26 |
-
// }
|
| 27 |
-
// }
|
| 28 |
-
//
|
| 29 |
-
|
| 30 |
-
/* ---- STEP 2: add this function near the other handle*Api functions.
|
| 31 |
-
It reuses the existing currentUser() helper already in _worker.js. ---- */
|
| 32 |
-
|
| 33 |
-
async function handleAriaApi(request, env, url) {
|
| 34 |
-
// Signed media is fetched by the public Gradio Space — no cookie there.
|
| 35 |
-
// Forward it straight through; aria-worker verifies the HMAC signature.
|
| 36 |
-
if (url.pathname.startsWith("/api/aria/media/")) {
|
| 37 |
-
return env.ARIA.fetch(new Request(request));
|
| 38 |
-
}
|
| 39 |
-
|
| 40 |
-
// Everything else requires a signed-in user.
|
| 41 |
-
const user = await currentUser(request, env);
|
| 42 |
-
if (!user) return json({ error: "Not signed in." }, 401);
|
| 43 |
-
|
| 44 |
-
// WebSocket upgrade: forward the ORIGINAL request so the upgrade survives, and
|
| 45 |
-
// carry the trusted uid in the query. Building a fresh Headers() to inject a
|
| 46 |
-
// header strips the Upgrade header and breaks the handshake. The aria-worker is
|
| 47 |
-
// service-binding-only (workers_dev=false), so a query uid is trustworthy.
|
| 48 |
-
if (request.headers.get("Upgrade") === "websocket") {
|
| 49 |
-
const fwd = new URL(request.url);
|
| 50 |
-
fwd.searchParams.set("uid", String(user.id));
|
| 51 |
-
fwd.searchParams.set("name", (user.name || "").slice(0, 80));
|
| 52 |
-
fwd.searchParams.set("email", (user.email || "").slice(0, 200));
|
| 53 |
-
return env.ARIA.fetch(new Request(fwd, request));
|
| 54 |
-
}
|
| 55 |
-
|
| 56 |
-
// Normal REST: inject the trusted uid + email as headers. Usage (20 msgs/5h) is
|
| 57 |
-
// NOT gated here — it's counted per message inside the Durable Object, the only
|
| 58 |
-
// layer that sees each message. This layer is purely the auth boundary.
|
| 59 |
-
const headers = new Headers(request.headers);
|
| 60 |
-
headers.set("X-Aria-Uid", String(user.id));
|
| 61 |
-
headers.set("X-Aria-Email", (user.email || "").slice(0, 200));
|
| 62 |
-
return env.ARIA.fetch(new Request(request, { headers }));
|
| 63 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cloudflare/pages-integration/aria.html
DELETED
|
@@ -1,143 +0,0 @@
|
|
| 1 |
-
<!DOCTYPE html>
|
| 2 |
-
<html lang="pl">
|
| 3 |
-
<head>
|
| 4 |
-
<meta charset="UTF-8" />
|
| 5 |
-
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, viewport-fit=cover, interactive-widget=resizes-content" />
|
| 6 |
-
<title>ARIA · NNL</title>
|
| 7 |
-
<link rel="icon" href="favicon.png" />
|
| 8 |
-
<link rel="stylesheet" href="css/styles.css" />
|
| 9 |
-
<link rel="stylesheet" href="css/aria.css?v=23" />
|
| 10 |
-
</head>
|
| 11 |
-
<body class="app-body aria-page" data-theme="default">
|
| 12 |
-
|
| 13 |
-
<!-- auth gate: aria-chat.js verifies the session before revealing the app -->
|
| 14 |
-
<div class="aria-gate" id="ariaGate"><span class="app-spinner"></span></div>
|
| 15 |
-
|
| 16 |
-
<div class="aria-shell" id="ariaApp" hidden>
|
| 17 |
-
<main class="aria-main">
|
| 18 |
-
<!-- header bar -->
|
| 19 |
-
<header class="aria-bar">
|
| 20 |
-
<div class="aria-id">
|
| 21 |
-
<span class="aria-avatar" aria-hidden="true"></span>
|
| 22 |
-
<span class="aria-title">ARIA</span>
|
| 23 |
-
<span class="aria-presence" id="ariaPresence">Connecting...</span>
|
| 24 |
-
</div>
|
| 25 |
-
<span class="spacer"></span>
|
| 26 |
-
<button class="aria-iconbtn kebab" id="ariaSettingsBtn" type="button" aria-label="Settings">
|
| 27 |
-
<svg viewBox="0 0 24 24" width="26" height="26" aria-hidden="true">
|
| 28 |
-
<circle cx="12" cy="5" r="2.2" fill="currentColor" />
|
| 29 |
-
<circle cx="12" cy="12" r="2.2" fill="currentColor" />
|
| 30 |
-
<circle cx="12" cy="19" r="2.2" fill="currentColor" />
|
| 31 |
-
</svg>
|
| 32 |
-
</button>
|
| 33 |
-
</header>
|
| 34 |
-
|
| 35 |
-
<!-- messages (single, permanent, scrollable conversation) -->
|
| 36 |
-
<div class="aria-messages" id="ariaMessages"></div>
|
| 37 |
-
|
| 38 |
-
<!-- ARIA typing indicator (left) -->
|
| 39 |
-
<div class="aria-typing-row" id="ariaTypingRow" hidden>
|
| 40 |
-
<span class="aria-avatar sm" aria-hidden="true"></span>
|
| 41 |
-
<span class="aria-typing"><i></i><i></i><i></i></span>
|
| 42 |
-
</div>
|
| 43 |
-
|
| 44 |
-
<!-- user typing indicator: dots on the right, "Typing..." caption on the left -->
|
| 45 |
-
<div class="aria-usertyping" id="ariaUserTyping" hidden>
|
| 46 |
-
<span class="aria-usertyping-label">Typing...</span>
|
| 47 |
-
<span class="spacer"></span>
|
| 48 |
-
<span class="aria-typing me"><i></i><i></i><i></i></span>
|
| 49 |
-
</div>
|
| 50 |
-
|
| 51 |
-
<!-- reply quote bar (shown when replying to a message) -->
|
| 52 |
-
<div class="aria-replybar" id="ariaReplyBar" hidden>
|
| 53 |
-
<svg class="aria-replybar-icon" viewBox="0 0 24 24" width="18" height="18" fill="none"
|
| 54 |
-
stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
| 55 |
-
<polyline points="9 14 4 9 9 4" />
|
| 56 |
-
<path d="M4 9h8a8 8 0 0 1 8 8v1" />
|
| 57 |
-
</svg>
|
| 58 |
-
<span class="aria-replybar-q" id="ariaReplyText"></span>
|
| 59 |
-
<button class="aria-iconbtn" id="ariaReplyCancel" type="button" aria-label="Anuluj">✕</button>
|
| 60 |
-
</div>
|
| 61 |
-
|
| 62 |
-
<!-- input bar -->
|
| 63 |
-
<form class="aria-inputbar" id="ariaForm">
|
| 64 |
-
<input type="file" id="ariaFile" hidden multiple
|
| 65 |
-
accept="image/*,.pdf,.txt,.csv,.json,.zip,.doc,.docx" />
|
| 66 |
-
<button class="aria-iconbtn attach" id="ariaAttach" type="button" aria-label="Attach">
|
| 67 |
-
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor"
|
| 68 |
-
stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
| 69 |
-
<path d="M21.44 11.05l-9.19 9.19a5.5 5.5 0 0 1-7.78-7.78l9.19-9.19a3.5 3.5 0 0 1 4.95 4.95l-9.2 9.19a1.5 1.5 0 0 1-2.12-2.12l8.49-8.49" />
|
| 70 |
-
</svg>
|
| 71 |
-
</button>
|
| 72 |
-
<textarea id="ariaInput" rows="1" maxlength="400" placeholder="Type message..."></textarea>
|
| 73 |
-
<button class="aria-send" id="ariaSend" type="submit" aria-label="Send">➤</button>
|
| 74 |
-
</form>
|
| 75 |
-
<div class="aria-attach-tray" id="ariaTray" hidden></div>
|
| 76 |
-
<div class="aria-blockedbar" id="ariaBlockedBar" hidden>Nie możesz odpowiedzieć na tę konwersację</div>
|
| 77 |
-
</main>
|
| 78 |
-
</div>
|
| 79 |
-
|
| 80 |
-
<!-- settings drawer -->
|
| 81 |
-
<div class="aria-drawer" id="ariaDrawer" hidden>
|
| 82 |
-
<div class="aria-drawer-card">
|
| 83 |
-
<div class="aria-drawer-head">
|
| 84 |
-
<span>Ustawienia</span>
|
| 85 |
-
<button class="aria-iconbtn" id="ariaDrawerClose" type="button" aria-label="Zamknij">✕</button>
|
| 86 |
-
</div>
|
| 87 |
-
|
| 88 |
-
<div class="aria-set-group">
|
| 89 |
-
<label class="aria-set-label">Motyw czatu</label>
|
| 90 |
-
<div class="aria-themes" id="ariaThemes">
|
| 91 |
-
<button class="aria-theme-dot t-default" data-theme="default" title="Default"></button>
|
| 92 |
-
<button class="aria-theme-dot t-sunset" data-theme="sunset" title="Sunset"></button>
|
| 93 |
-
<button class="aria-theme-dot t-matrix" data-theme="matrix" title="Matrix"></button>
|
| 94 |
-
<button class="aria-theme-dot t-bubble" data-theme="bubble" title="Bubblegum"></button>
|
| 95 |
-
<button class="aria-theme-dot t-mono" data-theme="mono" title="Mono"></button>
|
| 96 |
-
</div>
|
| 97 |
-
<button class="aria-rand" id="ariaThemeRand" type="button">🎲 Losowy</button>
|
| 98 |
-
</div>
|
| 99 |
-
|
| 100 |
-
<div class="aria-set-group">
|
| 101 |
-
<label class="aria-set-label">A tak na serio…</label>
|
| 102 |
-
<button class="aria-fun" id="ariaMute" type="button">🔇 Wycisz ARIĘ</button>
|
| 103 |
-
<button class="aria-fun" id="ariaBlock" type="button">🚫 Zablokuj ARIĘ</button>
|
| 104 |
-
<button class="aria-fun" id="ariaReport" type="button">🚩 Zgłoś ARIĘ</button>
|
| 105 |
-
</div>
|
| 106 |
-
|
| 107 |
-
<div class="aria-set-group">
|
| 108 |
-
<label class="aria-set-label">Dane</label>
|
| 109 |
-
<button class="aria-fun danger" id="ariaClear" type="button">🗑️ Usuń historię czatu</button>
|
| 110 |
-
</div>
|
| 111 |
-
|
| 112 |
-
<a class="aria-fun ghost" href="index.html">← Modele</a>
|
| 113 |
-
<button class="aria-fun ghost" id="ariaLogout" type="button">Wyloguj</button>
|
| 114 |
-
</div>
|
| 115 |
-
</div>
|
| 116 |
-
|
| 117 |
-
<!-- confirm modal: clearing history is irreversible -->
|
| 118 |
-
<div class="aria-confirm" id="ariaConfirm" hidden>
|
| 119 |
-
<div class="aria-confirm-card">
|
| 120 |
-
<div class="aria-confirm-title">Usunąć historię czatu?</div>
|
| 121 |
-
<p class="aria-confirm-text">Tego <strong>nie da się cofnąć</strong>. Wszystkie wiadomości zostaną trwale usunięte z bazy.</p>
|
| 122 |
-
<div class="aria-confirm-actions">
|
| 123 |
-
<button class="aria-fun" id="ariaConfirmCancel" type="button">Anuluj</button>
|
| 124 |
-
<button class="aria-fun danger solid" id="ariaConfirmYes" type="button">Usuń na zawsze</button>
|
| 125 |
-
</div>
|
| 126 |
-
</div>
|
| 127 |
-
</div>
|
| 128 |
-
|
| 129 |
-
<!-- profile popup: tap ARIA's header avatar/name -->
|
| 130 |
-
<div class="aria-profile" id="ariaProfile" hidden>
|
| 131 |
-
<div class="aria-profile-card">
|
| 132 |
-
<button class="aria-profile-x" id="ariaProfileClose" type="button" aria-label="Zamknij">✕</button>
|
| 133 |
-
<span class="aria-profile-pic" aria-hidden="true"></span>
|
| 134 |
-
<div class="aria-profile-name">ARIA</div>
|
| 135 |
-
<div class="aria-profile-sub">Adaptive Response & Intelligence Agent</div>
|
| 136 |
-
</div>
|
| 137 |
-
</div>
|
| 138 |
-
|
| 139 |
-
<div class="aria-toast" id="ariaToast" hidden></div>
|
| 140 |
-
|
| 141 |
-
<script type="module" src="js/aria-chat.js?v=23"></script>
|
| 142 |
-
</body>
|
| 143 |
-
</html>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cloudflare/pages-integration/css/aria.css
DELETED
|
@@ -1,291 +0,0 @@
|
|
| 1 |
-
/* ============================================================
|
| 2 |
-
ARIA — Messenger UI. Builds on the site's design tokens
|
| 3 |
-
(--bg, --text, --accent, --grad, --line… from styles.css)
|
| 4 |
-
and adds layout, 5 themes, bubbles, typing dots.
|
| 5 |
-
============================================================ */
|
| 6 |
-
|
| 7 |
-
/* The `hidden` attribute must win even on elements that set an explicit display
|
| 8 |
-
(grid/flex below). Without this the loading gate + settings drawer + typing
|
| 9 |
-
rows never hide — the gate overlay then covers the whole chat, which looks like
|
| 10 |
-
"stuck connecting" and blocks typing/sending entirely. */
|
| 11 |
-
.aria-page [hidden] { display: none !important; }
|
| 12 |
-
|
| 13 |
-
/* override the shared .app-body (used by login screens): it centers + pads, which
|
| 14 |
-
created background bars on the sides of the chat. ARIA fills the whole viewport.
|
| 15 |
-
position:fixed + overflow:hidden also stops the mobile keyboard from scrolling the
|
| 16 |
-
whole layout up (it stays pinned; the visible height is driven by --app-h). */
|
| 17 |
-
body.aria-page { position: fixed; inset: 0; width: 100%; height: 100%; display: block; padding: 0; margin: 0; min-height: 0; overflow: hidden; overscroll-behavior: none; }
|
| 18 |
-
|
| 19 |
-
/* swipe-right-to-reply (Messenger-style) — just the bubble slide, no arrow glyph */
|
| 20 |
-
/* touch-action: manipulation kills the browser's double-tap-to-zoom (iOS + Android)
|
| 21 |
-
so double-tap-to-❤️ doesn't zoom the screen; vertical scroll + swipe still work. */
|
| 22 |
-
.aria-row { position: relative; touch-action: manipulation; }
|
| 23 |
-
.aria-bubble { transition: transform .18s var(--ease, ease); touch-action: manipulation; }
|
| 24 |
-
|
| 25 |
-
.aria-page {
|
| 26 |
-
--aria-me: var(--accent, #6ea0ff); /* user bubble */
|
| 27 |
-
--aria-them: rgba(255,255,255,0.06); /* ARIA bubble */
|
| 28 |
-
--aria-me-fg: #07080c;
|
| 29 |
-
--aria-them-fg: var(--text, #f4f5f7);
|
| 30 |
-
--aria-bar: rgba(8,8,12,0.82);
|
| 31 |
-
height: var(--app-h, 100dvh); overflow: hidden;
|
| 32 |
-
}
|
| 33 |
-
|
| 34 |
-
/* ---- themes ---- */
|
| 35 |
-
.aria-page[data-theme="sunset"] { --aria-me:#ff8f6b; --aria-them:rgba(255,170,120,0.12); --aria-me-fg:#240b06; }
|
| 36 |
-
.aria-page[data-theme="matrix"] { --aria-me:#36e07a; --aria-them:rgba(54,224,122,0.10); --aria-me-fg:#01160a; --text:#bdf5cf; }
|
| 37 |
-
.aria-page[data-theme="bubble"] { --aria-me:#ff7ac6; --aria-them:rgba(255,122,198,0.14); --aria-me-fg:#2a0a1d; }
|
| 38 |
-
.aria-page[data-theme="mono"] { --aria-me:#e7e9ee; --aria-them:rgba(255,255,255,0.07); --aria-me-fg:#0b0c10; }
|
| 39 |
-
|
| 40 |
-
/* ---- gate ---- */
|
| 41 |
-
.aria-gate { position: fixed; inset: 0; display: grid; place-items: center; background: var(--bg, #050507); z-index: 50; }
|
| 42 |
-
|
| 43 |
-
/* ---- shell: a centered phone-sized chat on desktop, full-screen on mobile ----
|
| 44 |
-
Fixed to the layout viewport, then sized to the VISIBLE viewport (--app-h) and
|
| 45 |
-
nudged down by the visual-viewport offset (--app-top). On iOS this makes the whole
|
| 46 |
-
app track the keyboard like a native chat — no scroll fight, no drift-and-settle. */
|
| 47 |
-
.aria-shell {
|
| 48 |
-
position: fixed; top: 0; left: 0; right: 0;
|
| 49 |
-
height: var(--app-h, 100dvh);
|
| 50 |
-
transform: translateY(var(--app-top, 0px));
|
| 51 |
-
display: flex; justify-content: center;
|
| 52 |
-
background: var(--bg, #050507);
|
| 53 |
-
will-change: transform, height;
|
| 54 |
-
}
|
| 55 |
-
|
| 56 |
-
/* ---- sidebar (legacy, no longer rendered) ---- */
|
| 57 |
-
.aria-sidebar { display: flex; flex-direction: column; border-right: 1px solid var(--line, #ffffff14); background: rgba(255,255,255,0.015); }
|
| 58 |
-
.aria-sidebar-head { display: flex; align-items: center; justify-content: space-between; padding: 16px 18px; }
|
| 59 |
-
.aria-sidebar-title { font-weight: 600; letter-spacing: -0.01em; }
|
| 60 |
-
.aria-sidebar-close { display: none; }
|
| 61 |
-
.aria-list { flex: 1; overflow-y: auto; padding: 4px 10px; display: flex; flex-direction: column; gap: 4px; }
|
| 62 |
-
.aria-convo { text-align: left; padding: 10px 12px; border-radius: 12px; border: 0; background: transparent; color: var(--text-soft, #b9bcc6); cursor: pointer; font: inherit; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
| 63 |
-
.aria-convo:hover { background: var(--surface-2, #ffffff0d); }
|
| 64 |
-
.aria-convo.active { background: var(--surface-2, #ffffff0d); color: var(--text, #fff); }
|
| 65 |
-
.aria-sidebar-foot { padding: 12px; }
|
| 66 |
-
.aria-newbtn { width: 100%; padding: 11px; border-radius: 12px; border: 1px solid var(--line-strong, #ffffff29); background: transparent; color: var(--text, #fff); font: inherit; cursor: pointer; }
|
| 67 |
-
.aria-newbtn:hover { background: var(--surface-2, #ffffff0d); }
|
| 68 |
-
@media (max-width: 800px) {
|
| 69 |
-
.aria-sidebar { position: fixed; inset: 0 auto 0 0; width: 84%; max-width: 320px; z-index: 30; transform: translateX(-100%); transition: transform .25s var(--ease, ease); background: var(--bg-2, #0a0a0f); }
|
| 70 |
-
.aria-sidebar.open { transform: none; }
|
| 71 |
-
.aria-sidebar-close { display: inline-flex; }
|
| 72 |
-
}
|
| 73 |
-
|
| 74 |
-
/* ---- main: full-bleed on every phone; centered "phone frame" only on big screens ---- */
|
| 75 |
-
.aria-main {
|
| 76 |
-
display: flex; flex-direction: column; min-width: 0;
|
| 77 |
-
width: 100%; height: var(--app-h, 100dvh);
|
| 78 |
-
background: var(--bg-2, #0a0a0f);
|
| 79 |
-
}
|
| 80 |
-
/* only desktops/large tablets get the centered narrow column; all phones fill width */
|
| 81 |
-
@media (min-width: 640px) {
|
| 82 |
-
.aria-main { max-width: 430px; border-inline: 1px solid var(--line, #ffffff14); }
|
| 83 |
-
}
|
| 84 |
-
.aria-bar { display: flex; align-items: center; gap: 12px; padding: 10px 16px; backdrop-filter: blur(12px); background: var(--aria-bar); border-bottom: 1px solid var(--line, #ffffff14); max-height: 64px; overflow: hidden; transition: max-height .25s var(--ease, ease), padding .25s var(--ease, ease), opacity .2s var(--ease, ease); }
|
| 85 |
-
/* phones: while the keyboard is open, reclaim screen — collapse the top bar upward,
|
| 86 |
-
hide the (redundant) tip, and tighten the input padding. */
|
| 87 |
-
@media (max-width: 639px) {
|
| 88 |
-
body.kb-open .aria-bar { max-height: 0; padding-top: 0; padding-bottom: 0; opacity: 0; border-bottom-color: transparent; }
|
| 89 |
-
body.kb-open .aria-inputbar { padding-bottom: 6px; }
|
| 90 |
-
}
|
| 91 |
-
.aria-id { display: flex; align-items: center; gap: 10px; min-width: 0; }
|
| 92 |
-
.aria-avatar { display: inline-grid; place-items: center; width: 36px; height: 36px; border-radius: 50%; background: url("/profile-picture-aria.png") center / cover no-repeat, var(--grad, linear-gradient(110deg,#5e9bff,#a78bfa,#22d3ee)); color: transparent; font-size: 0; overflow: hidden; }
|
| 93 |
-
.aria-avatar.sm { width: 26px; height: 26px; font-size: 13px; }
|
| 94 |
-
.aria-avatar.big { width: 64px; height: 64px; font-size: 28px; }
|
| 95 |
-
.aria-title { font-weight: 700; letter-spacing: -0.02em; }
|
| 96 |
-
.aria-presence { font-size: 12px; color: var(--text-dim, #7c808d); }
|
| 97 |
-
.aria-iconbtn { background: transparent; border: 0; color: var(--text-soft, #b9bcc6); font-size: 19px; cursor: pointer; padding: 6px; border-radius: 10px; line-height: 1; display: inline-flex; align-items: center; justify-content: center; }
|
| 98 |
-
.aria-iconbtn:hover { background: var(--surface-2, #ffffff0d); color: var(--text, #fff); }
|
| 99 |
-
.aria-iconbtn svg { display: block; }
|
| 100 |
-
/* clean white icons for the kebab (settings) + paperclip (attach) */
|
| 101 |
-
.aria-iconbtn.kebab, .aria-iconbtn.attach { color: #fff; }
|
| 102 |
-
.aria-iconbtn.kebab { padding: 4px 8px; }
|
| 103 |
-
.aria-iconbtn.kebab:hover { background: var(--surface-2, #ffffff0d); }
|
| 104 |
-
.aria-iconbtn.attach:hover { background: transparent; opacity: .8; }
|
| 105 |
-
.spacer { flex: 1; }
|
| 106 |
-
|
| 107 |
-
/* ---- messages ---- */
|
| 108 |
-
.aria-messages { flex: 1; overflow-y: auto; -webkit-overflow-scrolling: touch; touch-action: pan-y; overscroll-behavior: contain; padding: 12px 16px 6px; display: flex; flex-direction: column; gap: 4px; scroll-behavior: smooth; }
|
| 109 |
-
.aria-empty { margin: auto; text-align: center; color: var(--text-dim, #7c808d); display: flex; flex-direction: column; align-items: center; gap: 14px; }
|
| 110 |
-
|
| 111 |
-
.aria-row { display: flex; align-items: flex-end; gap: 8px; max-width: min(680px, 86%); }
|
| 112 |
-
.aria-row.me { align-self: flex-end; flex-direction: row-reverse; }
|
| 113 |
-
.aria-row.them { align-self: flex-start; }
|
| 114 |
-
.aria-row .aria-avatar.sm { flex: 0 0 auto; opacity: 0; } /* shown only on last of a group */
|
| 115 |
-
.aria-row.show-av .aria-avatar.sm { opacity: 1; }
|
| 116 |
-
|
| 117 |
-
.aria-bubble { font-size: 15px; line-height: 1.5; padding: 9px 13px; border-radius: 18px; overflow-wrap: anywhere; white-space: pre-wrap; }
|
| 118 |
-
.aria-row.me .aria-bubble { background: var(--aria-me); color: var(--aria-me-fg); border-bottom-right-radius: 5px; font-weight: 500; }
|
| 119 |
-
.aria-row.them .aria-bubble { background: var(--aria-them); color: var(--aria-them-fg); border-bottom-left-radius: 5px; }
|
| 120 |
-
.aria-bubble.kind-proactive { font-style: normal; }
|
| 121 |
-
|
| 122 |
-
/* ---- reactions ---- */
|
| 123 |
-
.aria-bubble { position: relative; -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; }
|
| 124 |
-
.aria-react-badge {
|
| 125 |
-
position: absolute; bottom: -11px; z-index: 2;
|
| 126 |
-
display: inline-flex; align-items: center; height: 20px; padding: 0 4px;
|
| 127 |
-
font-size: 13px; line-height: 1; border-radius: 12px;
|
| 128 |
-
background: var(--bg-2, #0a0a0f); border: 1px solid var(--line, #ffffff14);
|
| 129 |
-
box-shadow: 0 2px 8px rgba(0,0,0,0.45);
|
| 130 |
-
}
|
| 131 |
-
.aria-row.them .aria-react-badge { right: 6px; }
|
| 132 |
-
.aria-row.me .aria-react-badge { left: 6px; }
|
| 133 |
-
.aria-row:has(.aria-react-badge) { margin-bottom: 12px; }
|
| 134 |
-
.aria-react-badge.pop { animation: aria-reactpop .38s var(--ease, cubic-bezier(.22,1,.36,1)); }
|
| 135 |
-
@keyframes aria-reactpop { 0% { transform: scale(0); } 55% { transform: scale(1.35); } 100% { transform: scale(1); } }
|
| 136 |
-
|
| 137 |
-
.aria-react-picker {
|
| 138 |
-
position: fixed; z-index: 80; display: flex; gap: 2px; padding: 6px 8px;
|
| 139 |
-
max-width: calc(100vw - 16px); flex-wrap: nowrap;
|
| 140 |
-
background: var(--bg-2, #0a0a0f); border: 1px solid var(--line-strong, #ffffff29);
|
| 141 |
-
border-radius: 26px; box-shadow: 0 10px 34px rgba(0,0,0,0.55);
|
| 142 |
-
transform-origin: bottom center; transform: scale(.7) translateY(8px); opacity: 0;
|
| 143 |
-
transition: transform .2s var(--ease, cubic-bezier(.22,1,.36,1)), opacity .18s;
|
| 144 |
-
}
|
| 145 |
-
.aria-react-picker.in { transform: scale(1) translateY(0); opacity: 1; }
|
| 146 |
-
.aria-react-opt {
|
| 147 |
-
font-size: 26px; line-height: 1; background: none; border: 0; cursor: pointer;
|
| 148 |
-
padding: 4px 5px; border-radius: 50%; transition: transform .13s var(--ease, ease);
|
| 149 |
-
}
|
| 150 |
-
.aria-react-opt:hover, .aria-react-opt:active { transform: scale(1.4) translateY(-4px); }
|
| 151 |
-
|
| 152 |
-
/* ---- hold-to-react (iMessage-style: blur + raised clone + menu) ---- */
|
| 153 |
-
.aria-holdscreen { position: fixed; inset: 0; z-index: 60; background: rgba(0,0,0,0.38); -webkit-backdrop-filter: blur(7px); backdrop-filter: blur(7px); opacity: 0; transition: opacity .22s var(--ease, ease); }
|
| 154 |
-
.aria-holdscreen.in { opacity: 1; }
|
| 155 |
-
.aria-held-clone { position: fixed; z-index: 62; margin: 0 !important; transform: scale(.97); transition: transform .2s var(--ease, cubic-bezier(.22,1,.36,1)); pointer-events: none; max-width: 86vw; }
|
| 156 |
-
.aria-held-clone.in { transform: scale(1.04); }
|
| 157 |
-
.aria-held-clone .aria-react-badge { display: none; }
|
| 158 |
-
.aria-held-clone.them { background: var(--aria-them); color: var(--aria-them-fg); border-bottom-left-radius: 5px; }
|
| 159 |
-
.aria-held-clone.me { background: var(--aria-me); color: var(--aria-me-fg); border-bottom-right-radius: 5px; }
|
| 160 |
-
/* plain (no box) actions under the held bubble, left-aligned to the bubble's left edge */
|
| 161 |
-
.aria-holdmenu { position: fixed; z-index: 64; display: flex; flex-direction: column; align-items: flex-start; gap: 4px;
|
| 162 |
-
transform: scale(.9); opacity: 0; transform-origin: top left; transition: transform .18s var(--ease, ease), opacity .18s; }
|
| 163 |
-
.aria-holdmenu.in { transform: scale(1); opacity: 1; }
|
| 164 |
-
.aria-holdmenu-time { font-size: 12px; color: var(--text-soft, #b9bcc6); white-space: nowrap; text-shadow: 0 1px 4px rgba(0,0,0,0.7); }
|
| 165 |
-
.aria-holdmenu-item { background: none; border: 0; color: var(--text, #fff); font: inherit; font-size: 15px; font-weight: 600; text-align: left; padding: 0; cursor: pointer; text-shadow: 0 1px 4px rgba(0,0,0,0.7); }
|
| 166 |
-
.aria-react-picker { z-index: 82; } /* above the blur overlay */
|
| 167 |
-
.aria-fly { position: fixed; z-index: 90; font-size: 26px; line-height: 1; pointer-events: none; transition: transform .36s cubic-bezier(.4,0,.2,1), opacity .36s; }
|
| 168 |
-
|
| 169 |
-
/* ---- reply: quote bar above input + quote inside bubble ---- */
|
| 170 |
-
.aria-replybar { display: flex; align-items: center; gap: 8px; padding: 8px 16px; border-top: 1px solid var(--line, #ffffff14); background: var(--aria-bar); color: var(--text-soft, #b9bcc6); font-size: 13px; }
|
| 171 |
-
.aria-replybar-icon { color: var(--text, #fff); display: inline-flex; align-items: center; flex: 0 0 auto; }
|
| 172 |
-
.aria-replybar-q { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
| 173 |
-
.aria-quote { font-size: 12px; opacity: .7; border-left: 2px solid currentColor; padding: 1px 0 1px 8px; margin-bottom: 5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
| 174 |
-
.aria-bubble.err { background: rgba(255,80,80,0.12); color: #ff9b9b; }
|
| 175 |
-
.aria-bubble img.aria-media { max-width: 240px; border-radius: 12px; display: block; }
|
| 176 |
-
.aria-bubble .aria-filechip { display: inline-flex; align-items: center; gap: 8px; }
|
| 177 |
-
|
| 178 |
-
/* grouped bubble spacing */
|
| 179 |
-
.aria-row + .aria-row.cont { margin-top: 2px; }
|
| 180 |
-
.aria-row:not(.cont) { margin-top: 10px; }
|
| 181 |
-
|
| 182 |
-
/* ---- typing ---- */
|
| 183 |
-
.aria-typing-row { display: flex; align-items: center; gap: 8px; padding: 2px 16px 10px; }
|
| 184 |
-
.aria-typing { display: inline-flex; align-items: center; gap: 5px; padding: 11px 14px; background: var(--aria-them); border-radius: 18px; border-bottom-left-radius: 5px; }
|
| 185 |
-
.aria-typing i { width: 8px; height: 8px; border-radius: 50%; background: var(--text-soft, #b9bcc6); animation: aria-bounce 1.35s cubic-bezier(.45,0,.55,1) infinite; }
|
| 186 |
-
.aria-typing i:nth-child(2) { animation-delay: .18s; }
|
| 187 |
-
.aria-typing i:nth-child(3) { animation-delay: .36s; }
|
| 188 |
-
@keyframes aria-bounce {
|
| 189 |
-
0%, 70%, 100% { transform: translateY(0) scale(.8); opacity: .35; }
|
| 190 |
-
35% { transform: translateY(-8px) scale(1.18); opacity: 1; }
|
| 191 |
-
}
|
| 192 |
-
|
| 193 |
-
/* user-side typing indicator: "Typing..." at left, 3 dots on the right */
|
| 194 |
-
.aria-usertyping { display: flex; align-items: center; gap: 10px; padding: 2px 16px 10px; }
|
| 195 |
-
.aria-usertyping-label { font-size: 12px; color: var(--text-dim, #7c808d); letter-spacing: .01em; }
|
| 196 |
-
.aria-typing.me { background: var(--aria-me); }
|
| 197 |
-
.aria-typing.me i { background: var(--aria-me-fg); }
|
| 198 |
-
|
| 199 |
-
/* ---- input ---- */
|
| 200 |
-
.aria-inputbar { display: flex; align-items: flex-end; gap: 8px; padding: 8px 16px 12px; background: var(--aria-bar); }
|
| 201 |
-
.aria-blockedbar { padding: 16px; text-align: center; font-size: 13px; color: var(--text-dim, #7c808d); background: var(--aria-bar); }
|
| 202 |
-
.aria-inputbar textarea { flex: 1; resize: none; max-height: 140px; padding: 11px 14px; border-radius: 20px; border: 1px solid var(--line-strong, #ffffff29); background: var(--surface, #ffffff08); color: var(--text, #fff); font: inherit; }
|
| 203 |
-
.aria-inputbar textarea:focus { outline: none; border-color: var(--aria-me); }
|
| 204 |
-
.aria-send { flex: 0 0 auto; width: 42px; height: 42px; border-radius: 50%; border: 0; background: var(--aria-me); color: var(--aria-me-fg); font-size: 16px; cursor: pointer; }
|
| 205 |
-
.aria-send:disabled { opacity: .4; cursor: default; }
|
| 206 |
-
.aria-attach-tray { display: flex; gap: 8px; flex-wrap: wrap; padding: 0 16px 10px; }
|
| 207 |
-
.aria-attach-tray .chip { display: flex; align-items: center; gap: 6px; padding: 6px 10px; border-radius: 10px; background: var(--surface-2, #ffffff0d); font-size: 13px; }
|
| 208 |
-
.aria-attach-tray .chip button { background: none; border: 0; color: var(--text-dim,#7c808d); cursor: pointer; }
|
| 209 |
-
/* affordance hint: a faint 🙂⁺ in the reaction spot of the LATEST ARIA message,
|
| 210 |
-
so the user knows messages can be reacted to. Visual only (pointer-events:none). */
|
| 211 |
-
.aria-react-hint {
|
| 212 |
-
position: absolute; bottom: -11px; right: 6px; z-index: 1;
|
| 213 |
-
display: inline-flex; align-items: center; justify-content: center; gap: 1px;
|
| 214 |
-
height: 20px; padding: 0 4px; line-height: 1; border-radius: 12px;
|
| 215 |
-
color: var(--text, #fff);
|
| 216 |
-
background: var(--bg-2, #0a0a0f); border: 1px dashed var(--line-strong, #ffffff29);
|
| 217 |
-
opacity: .55; pointer-events: none;
|
| 218 |
-
}
|
| 219 |
-
.aria-react-hint svg { display: block; }
|
| 220 |
-
.aria-react-hint::after { content: "+"; font-size: 11px; font-weight: 600; line-height: 1; }
|
| 221 |
-
.aria-row:has(.aria-react-hint) { margin-bottom: 12px; }
|
| 222 |
-
.aria-held-clone .aria-react-hint { display: none; }
|
| 223 |
-
|
| 224 |
-
/* ---- settings drawer ---- */
|
| 225 |
-
.aria-drawer { position: fixed; inset: 0; background: rgba(0,0,0,0.5); display: grid; place-items: end center; z-index: 40; }
|
| 226 |
-
.aria-drawer-card { width: min(440px, 94vw); margin: 0 0 0 0; background: var(--bg-2, #0a0a0f); border: 1px solid var(--line, #ffffff14); border-radius: 18px 18px 0 0; padding: 18px; display: flex; flex-direction: column; gap: 14px; animation: aria-up .22s var(--ease, ease); }
|
| 227 |
-
@media (min-width: 600px) { .aria-drawer { place-items: center; } .aria-drawer-card { border-radius: 18px; } }
|
| 228 |
-
@keyframes aria-up { from { transform: translateY(20px); opacity: 0; } to { transform: none; opacity: 1; } }
|
| 229 |
-
.aria-drawer-head { display: flex; justify-content: space-between; align-items: center; font-weight: 600; }
|
| 230 |
-
.aria-set-group { display: flex; flex-direction: column; gap: 10px; }
|
| 231 |
-
.aria-set-label { font-size: 12px; color: var(--text-dim, #7c808d); text-transform: uppercase; letter-spacing: .06em; }
|
| 232 |
-
.aria-themes { display: flex; gap: 10px; }
|
| 233 |
-
.aria-theme-dot { width: 34px; height: 34px; border-radius: 50%; border: 2px solid transparent; cursor: pointer; }
|
| 234 |
-
.aria-theme-dot.sel { border-color: var(--text, #fff); }
|
| 235 |
-
.t-default { background: linear-gradient(110deg,#5e9bff,#a78bfa,#22d3ee); }
|
| 236 |
-
.t-sunset { background: linear-gradient(110deg,#ff8f6b,#ffb56b); }
|
| 237 |
-
.t-matrix { background: linear-gradient(110deg,#36e07a,#0a3); }
|
| 238 |
-
.t-bubble { background: linear-gradient(110deg,#ff7ac6,#ffd1ec); }
|
| 239 |
-
.t-mono { background: linear-gradient(110deg,#e7e9ee,#8a8d97); }
|
| 240 |
-
.aria-rand, .aria-fun { padding: 11px 14px; border-radius: 12px; border: 1px solid var(--line-strong, #ffffff29); background: transparent; color: var(--text, #fff); font: inherit; cursor: pointer; text-align: left; text-decoration: none; }
|
| 241 |
-
.aria-rand:hover, .aria-fun:hover { background: var(--surface-2, #ffffff0d); }
|
| 242 |
-
.aria-fun.ghost { color: var(--text-soft, #b9bcc6); }
|
| 243 |
-
.aria-fun.on { border-color: var(--aria-me); color: var(--aria-me); }
|
| 244 |
-
.aria-fun.danger { color: #ff8d8d; border-color: rgba(255,90,90,0.35); }
|
| 245 |
-
.aria-fun.danger:hover { background: rgba(255,80,80,0.10); }
|
| 246 |
-
.aria-fun.danger.solid { background: #e5484d; color: #fff; border-color: #e5484d; text-align: center; }
|
| 247 |
-
.aria-fun.danger.solid:hover { background: #d23b40; }
|
| 248 |
-
|
| 249 |
-
/* confirm modal (irreversible clear) */
|
| 250 |
-
.aria-confirm { position: fixed; inset: 0; background: rgba(0,0,0,0.6); display: grid; place-items: center; z-index: 70; padding: 20px; }
|
| 251 |
-
.aria-confirm-card { width: min(380px, 94vw); background: var(--bg-2, #0a0a0f); border: 1px solid var(--line-strong, #ffffff29); border-radius: 18px; padding: 22px; animation: aria-up .2s var(--ease, ease); }
|
| 252 |
-
.aria-confirm-title { font-size: 18px; font-weight: 700; letter-spacing: -0.01em; }
|
| 253 |
-
.aria-confirm-text { margin: 10px 0 18px; font-size: 14px; color: var(--text-soft, #b9bcc6); line-height: 1.5; }
|
| 254 |
-
.aria-confirm-text strong { color: #ff9b9b; }
|
| 255 |
-
.aria-confirm-actions { display: flex; gap: 10px; }
|
| 256 |
-
.aria-confirm-actions .aria-fun { flex: 1; text-align: center; }
|
| 257 |
-
|
| 258 |
-
/* ---- toast ---- */
|
| 259 |
-
.aria-toast { position: fixed; left: 50%; bottom: 26px; transform: translateX(-50%); background: var(--bg-2, #0a0a0f); border: 1px solid var(--line-strong, #ffffff29); padding: 11px 16px; border-radius: 12px; z-index: 60; max-width: 90vw; }
|
| 260 |
-
|
| 261 |
-
/* ---- profile popup (tap the header avatar/name) ---- */
|
| 262 |
-
.aria-bar .aria-id { cursor: pointer; }
|
| 263 |
-
.aria-profile { position: fixed; inset: 0; z-index: 95; display: grid; place-items: center; padding: 20px;
|
| 264 |
-
background: rgba(0,0,0,0.6); -webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px); animation: aria-fade .2s ease; }
|
| 265 |
-
.aria-profile.closing { animation: aria-fade-out .25s ease forwards; }
|
| 266 |
-
.aria-profile-card { position: relative; display: flex; flex-direction: column; align-items: center; gap: 8px;
|
| 267 |
-
padding: 30px 36px 26px; border-radius: 24px; background: var(--bg-2, #0a0a0f); border: 1px solid var(--line-strong, #ffffff29);
|
| 268 |
-
box-shadow: 0 24px 70px rgba(0,0,0,0.6); transform-origin: top center; animation: aria-swing-in .55s cubic-bezier(.2,.75,.3,1.25); }
|
| 269 |
-
.aria-profile.closing .aria-profile-card { animation: aria-swing-out .25s ease forwards; }
|
| 270 |
-
.aria-profile-pic { width: min(62vw, 220px); height: min(62vw, 220px); border-radius: 50%;
|
| 271 |
-
background: url("/profile-picture-aria.png") center / cover no-repeat, var(--grad, linear-gradient(110deg,#5e9bff,#a78bfa,#22d3ee));
|
| 272 |
-
box-shadow: 0 10px 34px rgba(0,0,0,0.5); }
|
| 273 |
-
.aria-profile-name { font-size: 22px; font-weight: 700; letter-spacing: -0.02em; margin-top: 6px; }
|
| 274 |
-
.aria-profile-sub { font-size: 12px; color: var(--text-soft, #b9bcc6); text-align: center; }
|
| 275 |
-
.aria-profile-x { position: absolute; top: 10px; right: 10px; width: 34px; height: 34px; border-radius: 50%; border: 0;
|
| 276 |
-
background: var(--surface-2, #ffffff0d); color: var(--text, #fff); font-size: 15px; cursor: pointer;
|
| 277 |
-
display: inline-flex; align-items: center; justify-content: center; transition: transform .15s var(--ease, ease), background .15s; }
|
| 278 |
-
.aria-profile-x:hover { background: var(--surface, #ffffff14); transform: rotate(90deg); }
|
| 279 |
-
|
| 280 |
-
@keyframes aria-fade { from { opacity: 0; } to { opacity: 1; } }
|
| 281 |
-
@keyframes aria-fade-out { from { opacity: 1; } to { opacity: 0; } }
|
| 282 |
-
@keyframes aria-swing-in {
|
| 283 |
-
0% { opacity: 0; transform: scale(.7) rotate(-11deg); }
|
| 284 |
-
55% { opacity: 1; transform: scale(1.04) rotate(7deg); }
|
| 285 |
-
75% { transform: scale(.99) rotate(-3deg); }
|
| 286 |
-
100% { transform: scale(1) rotate(0); }
|
| 287 |
-
}
|
| 288 |
-
@keyframes aria-swing-out {
|
| 289 |
-
0% { opacity: 1; transform: scale(1) rotate(0); }
|
| 290 |
-
100% { opacity: 0; transform: scale(.7) rotate(10deg); }
|
| 291 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cloudflare/pages-integration/js/aria-chat.js
DELETED
|
@@ -1,626 +0,0 @@
|
|
| 1 |
-
/* ============================================================
|
| 2 |
-
ARIA chat client.
|
| 3 |
-
- reuses the site's auth (GET /api/auth/me)
|
| 4 |
-
- ONE permanent conversation per user (live-synced across devices)
|
| 5 |
-
- WebSocket to the DO: bubbles, typing, reactions, reply, echo
|
| 6 |
-
- Messenger/iMessage-style: hold-to-react (blur + picker), reply, emoji fly
|
| 7 |
-
============================================================ */
|
| 8 |
-
|
| 9 |
-
import { initSettings } from "./aria-settings.js?v=5";
|
| 10 |
-
|
| 11 |
-
const MSG_MAX = 400;
|
| 12 |
-
const $ = (id) => document.getElementById(id);
|
| 13 |
-
const state = {
|
| 14 |
-
cur: null, ws: null, pingTimer: null, reconnectDelay: 1000,
|
| 15 |
-
attachments: [], replyTo: null, // {id, text, role} being replied to
|
| 16 |
-
sendTimes: [], spamUntil: 0, lastSend: 0, // client spam guard
|
| 17 |
-
typingOn: false, typingTimer: null,
|
| 18 |
-
outbox: [], lastRecv: 0, wsGen: 0, // WS resilience: unacked events, liveness, generation
|
| 19 |
-
};
|
| 20 |
-
let _pressTimer = null, _psx = 0, _psy = 0;
|
| 21 |
-
let _overlay = null, _picker = null, _menu = null, _menuTime = null, _holdRow = null, _holdClone = null, _holdAuto = null;
|
| 22 |
-
|
| 23 |
-
/* ---- keep the app glued to the VISIBLE viewport (mobile keyboard) ----
|
| 24 |
-
iOS Safari shrinks visualViewport.height when the keyboard opens and may offset the
|
| 25 |
-
visible area (visualViewport.offsetTop). We size the shell to that height and shift it
|
| 26 |
-
down by offsetTop via CSS vars — the app then tracks the keyboard like a native chat.
|
| 27 |
-
We deliberately do NOT call window.scrollTo: fighting iOS's own auto-scroll was what
|
| 28 |
-
made the whole layout drift up and only snap back on a tap. */
|
| 29 |
-
function fitViewport() {
|
| 30 |
-
const vv = window.visualViewport;
|
| 31 |
-
const root = document.documentElement.style;
|
| 32 |
-
root.setProperty("--app-h", (vv ? vv.height : window.innerHeight) + "px");
|
| 33 |
-
root.setProperty("--app-top", (vv ? vv.offsetTop : 0) + "px");
|
| 34 |
-
const m = $("ariaMessages"); if (m) m.scrollTop = m.scrollHeight; // keep pinned to bottom
|
| 35 |
-
}
|
| 36 |
-
let _vvSettle = null;
|
| 37 |
-
function settleViewport() { // fit now, next frame, then once more after the keyboard animation
|
| 38 |
-
fitViewport();
|
| 39 |
-
requestAnimationFrame(fitViewport);
|
| 40 |
-
clearTimeout(_vvSettle);
|
| 41 |
-
_vvSettle = setTimeout(fitViewport, 320);
|
| 42 |
-
}
|
| 43 |
-
fitViewport();
|
| 44 |
-
if (window.visualViewport) {
|
| 45 |
-
window.visualViewport.addEventListener("resize", fitViewport);
|
| 46 |
-
window.visualViewport.addEventListener("scroll", fitViewport);
|
| 47 |
-
}
|
| 48 |
-
window.addEventListener("resize", fitViewport);
|
| 49 |
-
window.addEventListener("orientationchange", () => setTimeout(settleViewport, 250));
|
| 50 |
-
|
| 51 |
-
/* ---------------- boot ---------------- */
|
| 52 |
-
(async function boot() {
|
| 53 |
-
let me;
|
| 54 |
-
try { me = await (await fetch("/api/auth/me")).json(); } catch { me = null; }
|
| 55 |
-
if (!me || !me.user) { location.href = "index.html"; return; }
|
| 56 |
-
$("ariaGate").hidden = true;
|
| 57 |
-
$("ariaApp").hidden = false;
|
| 58 |
-
initSettings({ getConvo: () => state.cur, patchConvo, toast, onBlockChange });
|
| 59 |
-
wireUi();
|
| 60 |
-
await ensureChat();
|
| 61 |
-
})();
|
| 62 |
-
|
| 63 |
-
/* ---------------- UI wiring ---------------- */
|
| 64 |
-
function wireUi() {
|
| 65 |
-
$("ariaForm").addEventListener("submit", onSend);
|
| 66 |
-
$("ariaInput").addEventListener("input", onInput);
|
| 67 |
-
$("ariaInput").addEventListener("keydown", (e) => {
|
| 68 |
-
if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); onSend(e); }
|
| 69 |
-
});
|
| 70 |
-
$("ariaAttach").addEventListener("click", () => $("ariaFile").click());
|
| 71 |
-
$("ariaFile").addEventListener("change", onPickFiles);
|
| 72 |
-
$("ariaSettingsBtn").addEventListener("click", () => { $("ariaDrawer").hidden = false; });
|
| 73 |
-
$("ariaDrawerClose").addEventListener("click", () => { $("ariaDrawer").hidden = true; });
|
| 74 |
-
$("ariaLogout").addEventListener("click", async () => {
|
| 75 |
-
await fetch("/api/auth/logout", { method: "POST" }); location.href = "index.html";
|
| 76 |
-
});
|
| 77 |
-
$("ariaClear").addEventListener("click", () => { $("ariaConfirm").hidden = false; });
|
| 78 |
-
$("ariaConfirmCancel").addEventListener("click", () => { $("ariaConfirm").hidden = true; });
|
| 79 |
-
$("ariaConfirmYes").addEventListener("click", () => {
|
| 80 |
-
$("ariaConfirm").hidden = true;
|
| 81 |
-
if (state.ws?.readyState === 1) { send({ t: "clear" }); $("ariaDrawer").hidden = true; }
|
| 82 |
-
else toast("Brak połączenia — spróbuj za chwilę");
|
| 83 |
-
});
|
| 84 |
-
$("ariaReplyCancel")?.addEventListener("click", clearReply);
|
| 85 |
-
// keyboard open/close → recompute layout through the animation (fixes the
|
| 86 |
-
// "layout jumps up and doesn't settle until I tap" bug on mobile). The kb-open
|
| 87 |
-
// class collapses the top bar (phones only, see CSS) for more chat room.
|
| 88 |
-
$("ariaInput").addEventListener("focus", () => { document.body.classList.add("kb-open"); settleViewport(); });
|
| 89 |
-
$("ariaInput").addEventListener("blur", () => { document.body.classList.remove("kb-open"); settleViewport(); });
|
| 90 |
-
// tapping Send must NOT move focus off the textarea (that closes the mobile keyboard).
|
| 91 |
-
// preventDefault on the (simulated) mousedown keeps focus; the click still submits.
|
| 92 |
-
$("ariaSend").addEventListener("mousedown", (e) => e.preventDefault());
|
| 93 |
-
// tap ARIA's header avatar/name → profile popup (swing in, animated close)
|
| 94 |
-
document.querySelector(".aria-bar .aria-id")?.addEventListener("click", openProfile);
|
| 95 |
-
$("ariaProfileClose")?.addEventListener("click", closeProfile);
|
| 96 |
-
$("ariaProfile")?.addEventListener("click", (e) => { if (e.target.id === "ariaProfile") closeProfile(); });
|
| 97 |
-
wireHold();
|
| 98 |
-
}
|
| 99 |
-
|
| 100 |
-
/* ---------------- input: typing signal + 100-char + user dots ---------------- */
|
| 101 |
-
function onInput() {
|
| 102 |
-
const ta = $("ariaInput");
|
| 103 |
-
if (ta.value.length > MSG_MAX) ta.value = ta.value.slice(0, MSG_MAX); // hard cap (also blocks paste)
|
| 104 |
-
autoGrow();
|
| 105 |
-
const hasText = ta.value.trim().length > 0;
|
| 106 |
-
$("ariaUserTyping").hidden = !hasText;
|
| 107 |
-
setTyping(hasText);
|
| 108 |
-
scrollDown();
|
| 109 |
-
}
|
| 110 |
-
function setTyping(on) {
|
| 111 |
-
if (on !== state.typingOn) { state.typingOn = on; send({ t: "typing", on }); }
|
| 112 |
-
clearTimeout(state.typingTimer);
|
| 113 |
-
if (on) state.typingTimer = setTimeout(() => setTyping(false), 4000); // auto-stop if idle
|
| 114 |
-
}
|
| 115 |
-
function autoGrow() { const t = $("ariaInput"); t.style.height = "auto"; t.style.height = Math.min(t.scrollHeight, 140) + "px"; }
|
| 116 |
-
|
| 117 |
-
/* ---------------- the single, permanent conversation ---------------- */
|
| 118 |
-
async function ensureChat() {
|
| 119 |
-
const r = await fetch("/api/aria/conversations").then(x => x.json()).catch(() => ({}));
|
| 120 |
-
let convos = r.conversations || [];
|
| 121 |
-
let c = convos.length ? convos[convos.length - 1] : null;
|
| 122 |
-
if (!c) {
|
| 123 |
-
c = await fetch("/api/aria/conversations", {
|
| 124 |
-
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: "ARIA" }),
|
| 125 |
-
}).then(x => x.json()).catch(() => null);
|
| 126 |
-
}
|
| 127 |
-
if (!c) { setPresence("Offline"); return; }
|
| 128 |
-
state.cur = c;
|
| 129 |
-
document.body.dataset.theme = c.theme || "default";
|
| 130 |
-
applyBlockedUI(!!c.blocked);
|
| 131 |
-
openSocket(c.id);
|
| 132 |
-
}
|
| 133 |
-
async function patchConvo(patch) {
|
| 134 |
-
if (!state.cur) return;
|
| 135 |
-
Object.assign(state.cur, patch);
|
| 136 |
-
try {
|
| 137 |
-
await fetch(`/api/aria/conversations/${state.cur.id}`, {
|
| 138 |
-
method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(patch),
|
| 139 |
-
});
|
| 140 |
-
} catch {}
|
| 141 |
-
}
|
| 142 |
-
|
| 143 |
-
/* ---------------- websocket (resilient: heartbeat + reconnect + outbox) ---------------- */
|
| 144 |
-
function openSocket(cid) {
|
| 145 |
-
closeSocket();
|
| 146 |
-
setPresence("Connecting...");
|
| 147 |
-
const gen = ++state.wsGen; // token: handlers of a superseded socket bail
|
| 148 |
-
const proto = location.protocol === "https:" ? "wss" : "ws";
|
| 149 |
-
const ws = new WebSocket(`${proto}://${location.host}/api/aria/conversations/${cid}/ws?lang=auto`);
|
| 150 |
-
state.ws = ws;
|
| 151 |
-
ws.onopen = () => {
|
| 152 |
-
if (gen !== state.wsGen) { try { ws.close(); } catch {} return; }
|
| 153 |
-
state.reconnectDelay = 1000; state.lastRecv = Date.now(); setPresence("Active");
|
| 154 |
-
clearInterval(state.pingTimer);
|
| 155 |
-
state.pingTimer = setInterval(heartbeat, 20000);
|
| 156 |
-
flushOutbox(); // resend anything that wasn't acked
|
| 157 |
-
if (state.cur?.blocked) send({ t: "block" }); // keep the DO in sync on (re)connect
|
| 158 |
-
};
|
| 159 |
-
ws.onmessage = (ev) => {
|
| 160 |
-
state.lastRecv = Date.now();
|
| 161 |
-
let m; try { m = JSON.parse(ev.data); } catch { return; }
|
| 162 |
-
if (m.t === "pong") return;
|
| 163 |
-
if (m.t === "ack") return ackEvent(m.id);
|
| 164 |
-
if (m.t === "history") return renderHistory(m.events, m.bubbles);
|
| 165 |
-
if (m.t === "typing") return showTyping(m.on);
|
| 166 |
-
if (m.t === "bubble") return addBubble(m);
|
| 167 |
-
if (m.t === "echo") return onEcho(m.event); // user's own msg (also re-renders after reconnect)
|
| 168 |
-
if (m.t === "error") return addErrorBubble(m.v);
|
| 169 |
-
if (m.t === "usage") return onUsage(m);
|
| 170 |
-
if (m.t === "limit") return onLimit(m);
|
| 171 |
-
if (m.t === "cleared") { $("ariaMessages").innerHTML = ""; state.outbox = []; toast("Historia usunięta"); return; }
|
| 172 |
-
if (m.t === "reaction") return applyReaction(m.id, m.emoji);
|
| 173 |
-
};
|
| 174 |
-
ws.onerror = () => { try { ws.close(); } catch {} };
|
| 175 |
-
ws.onclose = () => {
|
| 176 |
-
if (gen !== state.wsGen) return; // superseded → its replacement owns reconnect
|
| 177 |
-
clearInterval(state.pingTimer); setPresence("Connecting...");
|
| 178 |
-
if (state.cur?.id === cid) {
|
| 179 |
-
state.reconnectDelay = Math.min(state.reconnectDelay * 1.6, 15000);
|
| 180 |
-
setTimeout(() => { if (state.cur?.id === cid && state.wsGen === gen) openSocket(cid); }, state.reconnectDelay);
|
| 181 |
-
}
|
| 182 |
-
};
|
| 183 |
-
}
|
| 184 |
-
function closeSocket() {
|
| 185 |
-
clearInterval(state.pingTimer);
|
| 186 |
-
state.wsGen++; // invalidate the old socket's handlers
|
| 187 |
-
if (state.ws) { try { state.ws.onclose = null; state.ws.onerror = null; state.ws.close(); } catch {} state.ws = null; }
|
| 188 |
-
}
|
| 189 |
-
function reconnectNow() { if (state.cur) openSocket(state.cur.id); } // closeSocket() inside bumps the gen
|
| 190 |
-
function send(obj) { try { if (state.ws?.readyState === 1) state.ws.send(JSON.stringify(obj)); } catch {} }
|
| 191 |
-
function setPresence(t) { $("ariaPresence").textContent = t; }
|
| 192 |
-
|
| 193 |
-
/* Heartbeat: ping every 20s; if nothing has come back for 30s the socket is a
|
| 194 |
-
zombie (iOS keeps readyState OPEN on a dead link) → force a reconnect. */
|
| 195 |
-
function heartbeat() {
|
| 196 |
-
const ws = state.ws;
|
| 197 |
-
if (!ws || ws.readyState !== 1) return;
|
| 198 |
-
if (state.lastRecv && Date.now() - state.lastRecv > 30000) { reconnectNow(); return; }
|
| 199 |
-
try { ws.send(JSON.stringify({ t: "ping" })); } catch { reconnectNow(); }
|
| 200 |
-
}
|
| 201 |
-
/* Foregrounding / network changes silently kill mobile sockets — re-check fast. */
|
| 202 |
-
function ensureLive() {
|
| 203 |
-
if (!state.cur) return;
|
| 204 |
-
const ws = state.ws;
|
| 205 |
-
if (!ws || ws.readyState === 2 || ws.readyState === 3) { reconnectNow(); return; } // CLOSING/CLOSED
|
| 206 |
-
if (ws.readyState === 1) {
|
| 207 |
-
const tag = state.lastRecv;
|
| 208 |
-
try { ws.send(JSON.stringify({ t: "ping" })); } catch { reconnectNow(); return; }
|
| 209 |
-
setTimeout(() => { if (state.cur && state.ws === ws && state.lastRecv === tag) reconnectNow(); }, 4000);
|
| 210 |
-
}
|
| 211 |
-
}
|
| 212 |
-
document.addEventListener("visibilitychange", () => { if (!document.hidden) ensureLive(); });
|
| 213 |
-
window.addEventListener("online", ensureLive);
|
| 214 |
-
window.addEventListener("pageshow", ensureLive);
|
| 215 |
-
window.addEventListener("focus", ensureLive);
|
| 216 |
-
|
| 217 |
-
/* Outbox: user events are queued and resent until the DO acks them, so a send that
|
| 218 |
-
vanishes into a half-dead socket isn't lost (you saw "message sent, no reply"). */
|
| 219 |
-
function queueEvent(ev) {
|
| 220 |
-
state.outbox.push(ev);
|
| 221 |
-
if (state.outbox.length > 50) state.outbox = state.outbox.slice(-50);
|
| 222 |
-
flushOutbox();
|
| 223 |
-
}
|
| 224 |
-
function flushOutbox() {
|
| 225 |
-
if (state.ws?.readyState !== 1) return;
|
| 226 |
-
for (const ev of state.outbox) { try { state.ws.send(JSON.stringify({ t: "event", event: ev })); } catch { break; } }
|
| 227 |
-
}
|
| 228 |
-
function ackEvent(id) { state.outbox = state.outbox.filter(e => e.id !== id); }
|
| 229 |
-
|
| 230 |
-
/* ---------------- usage / limit ---------------- */
|
| 231 |
-
function onUsage(m) {
|
| 232 |
-
state.usage = m;
|
| 233 |
-
if (state.ws?.readyState === 1) setPresence("Active"); // no "x/5h left" countdown
|
| 234 |
-
}
|
| 235 |
-
function onLimit(m) {
|
| 236 |
-
state.usage = { remaining: 0, ...m };
|
| 237 |
-
setPresence("Limit reached");
|
| 238 |
-
toast("Limit 20 wiadomości / 5h. Reset " + fmtReset(m.resetAt));
|
| 239 |
-
}
|
| 240 |
-
function fmtReset(ts) {
|
| 241 |
-
if (!ts) return "później";
|
| 242 |
-
const mins = Math.max(1, Math.round((ts - Date.now()) / 60000));
|
| 243 |
-
if (mins < 60) return `za ${mins} min`;
|
| 244 |
-
const h = Math.floor(mins / 60), mm = mins % 60;
|
| 245 |
-
return `za ${h}h${mm ? " " + mm + "min" : ""}`;
|
| 246 |
-
}
|
| 247 |
-
|
| 248 |
-
/* ---------------- rendering ---------------- */
|
| 249 |
-
function renderHistory(events, bubbles) {
|
| 250 |
-
const msgs = $("ariaMessages"); msgs.innerHTML = "";
|
| 251 |
-
const timeline = [
|
| 252 |
-
...(events || []).map(e => ({ t: e.ts, kind: "event", e })),
|
| 253 |
-
...(bubbles || []).map(b => ({ t: b.created_at, kind: "bubble", b })),
|
| 254 |
-
].sort((a, z) => a.t - z.t);
|
| 255 |
-
for (const item of timeline) {
|
| 256 |
-
if (item.kind === "event") renderEvent(item.e);
|
| 257 |
-
else addBubble({ id: item.b.id, bubble: item.b.text, kind: item.b.kind, reaction: item.b.reaction, reply_to: item.b.reply_to, ts: item.b.created_at }, false);
|
| 258 |
-
}
|
| 259 |
-
scrollDown();
|
| 260 |
-
}
|
| 261 |
-
function renderEvent(e) {
|
| 262 |
-
const reply = e.payload?.reply_to;
|
| 263 |
-
if (e.type === "message") addUserRow(textNode(e.payload.text), e.id, e.reaction, reply, e.ts);
|
| 264 |
-
else if (e.type === "image") addUserRow(mediaNode(e.payload, true), e.id, e.reaction, reply, e.ts);
|
| 265 |
-
else if (e.type === "file") addUserRow(mediaNode(e.payload, false), e.id, e.reaction, reply, e.ts);
|
| 266 |
-
}
|
| 267 |
-
function onEcho(e) { // a message we sent on another device
|
| 268 |
-
if (!e || $("ariaMessages").querySelector(`.aria-row[data-id="${cssId(e.id)}"]`)) return; // dedup
|
| 269 |
-
renderEvent(e);
|
| 270 |
-
}
|
| 271 |
-
|
| 272 |
-
function row(side, id, ts) {
|
| 273 |
-
const r = document.createElement("div");
|
| 274 |
-
r.className = `aria-row ${side} show-av`;
|
| 275 |
-
if (id) r.dataset.id = id;
|
| 276 |
-
if (ts) r.dataset.ts = ts;
|
| 277 |
-
if (side === "them") { const av = document.createElement("span"); av.className = "aria-avatar sm"; r.appendChild(av); }
|
| 278 |
-
return r;
|
| 279 |
-
}
|
| 280 |
-
function trunc(t) { t = (t || "").trim(); return t.length > 25 ? t.slice(0, 20) + "..." : t; }
|
| 281 |
-
function quoteSnippet(refId) {
|
| 282 |
-
const ref = refId && $("ariaMessages").querySelector(`.aria-row[data-id="${cssId(refId)}"] .aria-bubble`);
|
| 283 |
-
if (!ref) return null;
|
| 284 |
-
return trunc(ref.querySelector(".aria-bubble-text")?.textContent || ref.textContent || "");
|
| 285 |
-
}
|
| 286 |
-
function bubbleEl(text, kind) {
|
| 287 |
-
const b = document.createElement("div");
|
| 288 |
-
b.className = "aria-bubble" + (kind ? " kind-" + kind : "");
|
| 289 |
-
return b;
|
| 290 |
-
}
|
| 291 |
-
function addQuote(bubble, refId) {
|
| 292 |
-
const q = quoteSnippet(refId);
|
| 293 |
-
if (!q) return;
|
| 294 |
-
const el = document.createElement("div"); el.className = "aria-quote"; el.textContent = q;
|
| 295 |
-
bubble.appendChild(el);
|
| 296 |
-
}
|
| 297 |
-
function addUserRow(contentEl, id, reaction, replyTo, ts) {
|
| 298 |
-
const r = row("me", id, ts);
|
| 299 |
-
const b = bubbleEl();
|
| 300 |
-
if (replyTo) addQuote(b, replyTo);
|
| 301 |
-
const wrap = document.createElement("span"); wrap.className = "aria-bubble-text"; wrap.appendChild(contentEl);
|
| 302 |
-
b.appendChild(wrap); r.appendChild(b);
|
| 303 |
-
$("ariaMessages").appendChild(r);
|
| 304 |
-
if (reaction) applyReaction(r, reaction);
|
| 305 |
-
scrollDown();
|
| 306 |
-
}
|
| 307 |
-
function addBubble(m, animate = true) {
|
| 308 |
-
if (state.cur?.muted || state.cur?.blocked) return;
|
| 309 |
-
const r = row("them", m.id, m.ts || Date.now());
|
| 310 |
-
const b = bubbleEl(null, m.kind || "response");
|
| 311 |
-
if (m.reply_to) addQuote(b, m.reply_to);
|
| 312 |
-
const wrap = document.createElement("span"); wrap.className = "aria-bubble-text"; wrap.textContent = m.bubble;
|
| 313 |
-
b.appendChild(wrap); r.appendChild(b);
|
| 314 |
-
$("ariaMessages").appendChild(r);
|
| 315 |
-
if (m.reaction) applyReaction(r, m.reaction);
|
| 316 |
-
updateReactHint();
|
| 317 |
-
scrollDown();
|
| 318 |
-
}
|
| 319 |
-
/* Faint 🙂⁺ marker in the reaction spot of the LATEST ARIA message (only the latest,
|
| 320 |
-
and only while it has no real reaction) — a visual cue that messages are reactable. */
|
| 321 |
-
function updateReactHint() {
|
| 322 |
-
document.querySelectorAll(".aria-react-hint").forEach(el => el.remove());
|
| 323 |
-
const thems = $("ariaMessages").querySelectorAll(".aria-row.them");
|
| 324 |
-
const bubble = thems[thems.length - 1]?.querySelector(".aria-bubble");
|
| 325 |
-
if (!bubble || bubble.querySelector(".aria-react-badge")) return; // none, or already reacted
|
| 326 |
-
const hint = document.createElement("span");
|
| 327 |
-
hint.className = "aria-react-hint"; hint.setAttribute("aria-hidden", "true");
|
| 328 |
-
hint.innerHTML = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" ' +
|
| 329 |
-
'stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">' +
|
| 330 |
-
'<circle cx="12" cy="12" r="9"/><path d="M8.5 14.5a4.5 4.5 0 0 0 7 0"/>' +
|
| 331 |
-
'<path d="M9 9.5v.3"/><path d="M15 9.5v.3"/></svg>';
|
| 332 |
-
bubble.appendChild(hint);
|
| 333 |
-
}
|
| 334 |
-
function addErrorBubble(v) {
|
| 335 |
-
const r = row("them"); const b = bubbleEl(null); b.classList.add("err");
|
| 336 |
-
b.textContent = v; r.appendChild(b); $("ariaMessages").appendChild(r); scrollDown();
|
| 337 |
-
}
|
| 338 |
-
function showTyping(on) { if (state.cur?.muted || state.cur?.blocked) on = false; $("ariaTypingRow").hidden = !on; if (on) scrollDown(); }
|
| 339 |
-
/* blocked → swap the composer for a "can't reply" notice; unblocked → restore */
|
| 340 |
-
function applyBlockedUI(blocked) {
|
| 341 |
-
const f = $("ariaForm"), bb = $("ariaBlockedBar");
|
| 342 |
-
if (f) f.hidden = !!blocked;
|
| 343 |
-
if (bb) bb.hidden = !blocked;
|
| 344 |
-
if (blocked) { clearReply(); const t = $("ariaTray"); if (t) { t.hidden = true; t.innerHTML = ""; } $("ariaUserTyping").hidden = true; }
|
| 345 |
-
}
|
| 346 |
-
function onBlockChange(blocked) { applyBlockedUI(blocked); send({ t: blocked ? "block" : "unblock" }); }
|
| 347 |
-
function textNode(t) { const s = document.createElement("span"); s.textContent = t; return s; }
|
| 348 |
-
function mediaNode(p, isImage) {
|
| 349 |
-
if (isImage) { const img = document.createElement("img"); img.className = "aria-media"; img.alt = p.name || "image"; img.src = `/api/aria/media/${encodeURIComponent(p.key)}?${p._sig || ""}`; return img; }
|
| 350 |
-
const span = document.createElement("span"); span.className = "aria-filechip"; span.textContent = "📄 " + (p.name || "file"); return span;
|
| 351 |
-
}
|
| 352 |
-
function scrollDown() { const m = $("ariaMessages"); m.scrollTop = m.scrollHeight; }
|
| 353 |
-
function cssId(s) { return (window.CSS && CSS.escape) ? CSS.escape(s) : s; }
|
| 354 |
-
function fmtTs(ms) { if (!ms) return ""; return new Date(ms).toISOString().slice(0, 19).replace("T", " ") + " UTC"; }
|
| 355 |
-
|
| 356 |
-
/* ---------------- reactions ---------------- */
|
| 357 |
-
const REACTIONS = ["❤️", "😆", "😮", "🥹", "😢", "😡"];
|
| 358 |
-
function applyReaction(rowOrId, emoji) {
|
| 359 |
-
const r = typeof rowOrId === "string" ? $("ariaMessages").querySelector(`.aria-row[data-id="${cssId(rowOrId)}"]`) : rowOrId;
|
| 360 |
-
const bubble = r && r.querySelector(".aria-bubble");
|
| 361 |
-
if (!bubble) return;
|
| 362 |
-
let badge = bubble.querySelector(".aria-react-badge");
|
| 363 |
-
if (!emoji) { if (badge) badge.remove(); updateReactHint(); return; }
|
| 364 |
-
if (!badge) { badge = document.createElement("span"); badge.className = "aria-react-badge"; bubble.appendChild(badge); }
|
| 365 |
-
badge.textContent = emoji;
|
| 366 |
-
badge.classList.remove("pop"); void badge.offsetWidth; badge.classList.add("pop");
|
| 367 |
-
updateReactHint();
|
| 368 |
-
}
|
| 369 |
-
|
| 370 |
-
/* ---------------- sending ---------------- */
|
| 371 |
-
function spamBlocked() {
|
| 372 |
-
const now = Date.now();
|
| 373 |
-
state.sendTimes = state.sendTimes.filter(t => now - t < 8000);
|
| 374 |
-
if (state.sendTimes.length >= 5) state.spamUntil = now + 20000;
|
| 375 |
-
if (now < state.spamUntil && state.lastSend && now - state.lastSend < 2000) return true; // silently block
|
| 376 |
-
return false;
|
| 377 |
-
}
|
| 378 |
-
async function onSend(e) {
|
| 379 |
-
e?.preventDefault?.();
|
| 380 |
-
if (state.cur?.blocked) { toast("ARIA jest zablokowana. Odblokuj ją w ustawieniach 🙃"); return; }
|
| 381 |
-
const ta = $("ariaInput");
|
| 382 |
-
const text = ta.value.trim().slice(0, MSG_MAX);
|
| 383 |
-
if (!text && !state.attachments.length) return;
|
| 384 |
-
if (spamBlocked()) { return; } // anti-spam: silently ignore
|
| 385 |
-
state.sendTimes.push(Date.now()); state.lastSend = Date.now();
|
| 386 |
-
|
| 387 |
-
const reply = state.replyTo ? state.replyTo.id : null;
|
| 388 |
-
// attachments first
|
| 389 |
-
for (const a of state.attachments.splice(0)) {
|
| 390 |
-
const ev = makeEvent(a.mime.startsWith("image/") ? "image" : "file", a, reply);
|
| 391 |
-
addUserRow(mediaNode(a, a.mime.startsWith("image/")), ev.id, null, reply, ev.ts);
|
| 392 |
-
queueEvent(ev);
|
| 393 |
-
}
|
| 394 |
-
$("ariaTray").hidden = true; $("ariaTray").innerHTML = "";
|
| 395 |
-
|
| 396 |
-
ta.value = ""; autoGrow();
|
| 397 |
-
$("ariaUserTyping").hidden = true; setTyping(false);
|
| 398 |
-
if (text) {
|
| 399 |
-
const ev = makeEvent("message", { text }, reply);
|
| 400 |
-
addUserRow(textNode(text), ev.id, null, reply, ev.ts);
|
| 401 |
-
queueEvent(ev);
|
| 402 |
-
}
|
| 403 |
-
clearReply();
|
| 404 |
-
$("ariaInput").focus(); // keep the keyboard open after sending (mobile)
|
| 405 |
-
}
|
| 406 |
-
function makeEvent(type, payload, replyTo) {
|
| 407 |
-
const ev = { id: "evt_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), ts: Date.now(), type, payload };
|
| 408 |
-
if (replyTo) ev.reply_to = replyTo;
|
| 409 |
-
return ev;
|
| 410 |
-
}
|
| 411 |
-
|
| 412 |
-
/* ---------------- reply ---------------- */
|
| 413 |
-
function startReply(rowEl) {
|
| 414 |
-
const id = rowEl.dataset.id; if (!id) return;
|
| 415 |
-
const text = (rowEl.querySelector(".aria-bubble-text")?.textContent || "").trim();
|
| 416 |
-
const role = rowEl.classList.contains("them") ? "assistant" : "user";
|
| 417 |
-
state.replyTo = { id, text, role };
|
| 418 |
-
$("ariaReplyText").textContent = (role === "assistant" ? "ARIA: " : "Ty: ") + trunc(text);
|
| 419 |
-
$("ariaReplyBar").hidden = false;
|
| 420 |
-
$("ariaInput").focus();
|
| 421 |
-
}
|
| 422 |
-
function clearReply() { state.replyTo = null; const bar = $("ariaReplyBar"); if (bar) bar.hidden = true; }
|
| 423 |
-
|
| 424 |
-
/* ---------------- attachments ---------------- */
|
| 425 |
-
async function onPickFiles(e) {
|
| 426 |
-
const files = [...e.target.files]; e.target.value = "";
|
| 427 |
-
for (const f of files) {
|
| 428 |
-
try {
|
| 429 |
-
const r = await fetch(`/api/aria/conversations/${state.cur.id}/upload`, {
|
| 430 |
-
method: "POST", headers: { "Content-Type": f.type || "application/octet-stream", "X-File-Name": f.name }, body: f,
|
| 431 |
-
});
|
| 432 |
-
if (!r.ok) { toast("Couldn't upload file."); continue; }
|
| 433 |
-
const meta = await r.json(); state.attachments.push(meta); addTrayChip(meta);
|
| 434 |
-
} catch { toast("Upload error."); }
|
| 435 |
-
}
|
| 436 |
-
}
|
| 437 |
-
function addTrayChip(meta) {
|
| 438 |
-
const tray = $("ariaTray"); tray.hidden = false;
|
| 439 |
-
const chip = document.createElement("div"); chip.className = "chip";
|
| 440 |
-
chip.innerHTML = `<span>${meta.mime.startsWith("image/") ? "🖼️" : "📄"} ${escapeHtml(meta.name)}</span>`;
|
| 441 |
-
const x = document.createElement("button"); x.textContent = "✕";
|
| 442 |
-
x.onclick = () => { state.attachments = state.attachments.filter(a => a.key !== meta.key); chip.remove(); if (!tray.children.length) tray.hidden = true; };
|
| 443 |
-
chip.appendChild(x); tray.appendChild(chip);
|
| 444 |
-
}
|
| 445 |
-
|
| 446 |
-
/* ---------------- hold-to-react (iMessage-style: blur + clone + picker + reply) ---------------- */
|
| 447 |
-
function wireHold() {
|
| 448 |
-
const msgs = $("ariaMessages");
|
| 449 |
-
let row = null, sx = 0, sy = 0, dx = 0, mode = null; // mode: null | "swipe" | "scroll"
|
| 450 |
-
let heldOpen = false, downAt = 0, lastTapId = null, lastTapAt = 0; // for double-tap detection
|
| 451 |
-
const snapBack = (animate) => {
|
| 452 |
-
if (!row) return;
|
| 453 |
-
const b = row.querySelector(".aria-bubble");
|
| 454 |
-
if (b) { b.style.transition = animate ? "transform .18s var(--ease, ease)" : "none"; b.style.transform = ""; }
|
| 455 |
-
row.classList.remove("swipe-armed");
|
| 456 |
-
};
|
| 457 |
-
msgs.addEventListener("pointerdown", (e) => {
|
| 458 |
-
const r = e.target.closest(".aria-row");
|
| 459 |
-
if (!r || !r.dataset.id) { row = null; return; }
|
| 460 |
-
row = r; sx = _psx = e.clientX; sy = _psy = e.clientY; dx = 0; mode = null;
|
| 461 |
-
downAt = Date.now(); heldOpen = false;
|
| 462 |
-
clearTimeout(_pressTimer);
|
| 463 |
-
_pressTimer = setTimeout(() => { if (mode !== "swipe") { heldOpen = true; openHold(r); } }, 380);
|
| 464 |
-
});
|
| 465 |
-
msgs.addEventListener("pointermove", (e) => {
|
| 466 |
-
if (!row) return;
|
| 467 |
-
const ddx = e.clientX - sx, ddy = e.clientY - sy;
|
| 468 |
-
if (mode === null) {
|
| 469 |
-
if (Math.abs(ddx) < 8 && Math.abs(ddy) < 8) return;
|
| 470 |
-
clearTimeout(_pressTimer);
|
| 471 |
-
mode = (Math.abs(ddx) > Math.abs(ddy) && ddx > 0) ? "swipe" : "scroll";
|
| 472 |
-
if (mode === "scroll") { row = null; return; } // vertical → let the list scroll
|
| 473 |
-
}
|
| 474 |
-
if (mode === "swipe") {
|
| 475 |
-
if (e.cancelable) e.preventDefault();
|
| 476 |
-
dx = Math.max(0, Math.min(ddx, 80));
|
| 477 |
-
const b = row.querySelector(".aria-bubble");
|
| 478 |
-
if (b) { b.style.transition = "none"; b.style.transform = `translateX(${dx}px)`; }
|
| 479 |
-
row.classList.toggle("swipe-armed", dx > 50);
|
| 480 |
-
}
|
| 481 |
-
});
|
| 482 |
-
const end = () => {
|
| 483 |
-
clearTimeout(_pressTimer);
|
| 484 |
-
if (row && mode === "swipe") {
|
| 485 |
-
const armed = dx > 50, r = row;
|
| 486 |
-
snapBack(true);
|
| 487 |
-
if (armed) { if (navigator.vibrate) navigator.vibrate(12); startReply(r); }
|
| 488 |
-
} else if (row && mode === null && !heldOpen && Date.now() - downAt < 350) {
|
| 489 |
-
// a quick tap (not a swipe, not a long-press): detect double-tap → ❤️ on ARIA's bubble
|
| 490 |
-
const r = row, id = r.dataset.id, now = Date.now();
|
| 491 |
-
if (id && lastTapId === id && now - lastTapAt < 320) {
|
| 492 |
-
lastTapId = null; lastTapAt = 0;
|
| 493 |
-
if (r.classList.contains("them")) quickHeart(r);
|
| 494 |
-
} else { lastTapId = id; lastTapAt = now; }
|
| 495 |
-
}
|
| 496 |
-
row = null; mode = null; dx = 0;
|
| 497 |
-
};
|
| 498 |
-
msgs.addEventListener("pointerup", end);
|
| 499 |
-
msgs.addEventListener("pointercancel", () => { snapBack(true); row = null; mode = null; });
|
| 500 |
-
msgs.addEventListener("scroll", () => { clearTimeout(_pressTimer); closeHold(); }, { passive: true });
|
| 501 |
-
msgs.addEventListener("contextmenu", (e) => { if (e.target.closest(".aria-row")) e.preventDefault(); });
|
| 502 |
-
// iOS Safari ignores touch-action:manipulation for double-tap zoom — so swallow the
|
| 503 |
-
// SECOND quick tap's default (the zoom gesture). Must be a non-passive listener for
|
| 504 |
-
// preventDefault to take effect. Double-tap-to-❤️ (pointer events) is unaffected.
|
| 505 |
-
let lastTouchEnd = 0;
|
| 506 |
-
msgs.addEventListener("touchend", (e) => {
|
| 507 |
-
const now = Date.now();
|
| 508 |
-
if (now - lastTouchEnd <= 350 && e.cancelable) e.preventDefault();
|
| 509 |
-
lastTouchEnd = now;
|
| 510 |
-
}, { passive: false });
|
| 511 |
-
}
|
| 512 |
-
function ensureHoldDom() {
|
| 513 |
-
if (_overlay) return;
|
| 514 |
-
_overlay = document.createElement("div"); _overlay.className = "aria-holdscreen"; _overlay.hidden = true;
|
| 515 |
-
_overlay.addEventListener("pointerdown", (e) => { if (e.target === _overlay) closeHold(); });
|
| 516 |
-
_picker = document.createElement("div"); _picker.className = "aria-react-picker";
|
| 517 |
-
for (const em of REACTIONS) {
|
| 518 |
-
const btn = document.createElement("button"); btn.type = "button"; btn.className = "aria-react-opt"; btn.textContent = em;
|
| 519 |
-
btn.addEventListener("click", (e) => { e.stopPropagation(); onPickEmoji(em, btn); });
|
| 520 |
-
_picker.appendChild(btn);
|
| 521 |
-
}
|
| 522 |
-
_menu = document.createElement("div"); _menu.className = "aria-holdmenu";
|
| 523 |
-
_menuTime = document.createElement("div"); _menuTime.className = "aria-holdmenu-time";
|
| 524 |
-
_menu.appendChild(_menuTime); // sent date+time, shown above "Odpowiedz"
|
| 525 |
-
const reply = document.createElement("button"); reply.type = "button"; reply.className = "aria-holdmenu-item";
|
| 526 |
-
reply.textContent = "Odpowiedz";
|
| 527 |
-
reply.addEventListener("click", (e) => { e.stopPropagation(); const r = _holdRow; closeHold(); if (r) startReply(r); });
|
| 528 |
-
_menu.appendChild(reply);
|
| 529 |
-
_overlay.append(_picker, _menu);
|
| 530 |
-
document.body.appendChild(_overlay);
|
| 531 |
-
}
|
| 532 |
-
function openHold(rowEl) {
|
| 533 |
-
ensureHoldDom();
|
| 534 |
-
_holdRow = rowEl;
|
| 535 |
-
if (_menuTime) { const ts = Number(rowEl.dataset.ts); _menuTime.textContent = fmtTs(ts); _menuTime.style.display = ts ? "block" : "none"; }
|
| 536 |
-
const bubble = rowEl.querySelector(".aria-bubble");
|
| 537 |
-
if (!bubble) return;
|
| 538 |
-
const rect = bubble.getBoundingClientRect();
|
| 539 |
-
const them = rowEl.classList.contains("them");
|
| 540 |
-
|
| 541 |
-
// sharp clone of the held bubble, floating above the blur
|
| 542 |
-
_holdClone = bubble.cloneNode(true);
|
| 543 |
-
_holdClone.classList.add("aria-held-clone", them ? "them" : "me");
|
| 544 |
-
Object.assign(_holdClone.style, { top: rect.top + "px", left: rect.left + "px", width: rect.width + "px" });
|
| 545 |
-
_overlay.appendChild(_holdClone);
|
| 546 |
-
|
| 547 |
-
_overlay.hidden = false;
|
| 548 |
-
requestAnimationFrame(() => { _overlay.classList.add("in"); _holdClone.classList.add("in"); });
|
| 549 |
-
|
| 550 |
-
// picker above, menu below (clamped to viewport)
|
| 551 |
-
const vw = (window.visualViewport ? window.visualViewport.width : window.innerWidth);
|
| 552 |
-
const pw = 250;
|
| 553 |
-
const px = Math.max(8, Math.min(rect.left + rect.width / 2 - pw / 2, vw - pw - 8));
|
| 554 |
-
_picker.style.left = px + "px";
|
| 555 |
-
_picker.style.top = Math.max(8, rect.top - 60) + "px";
|
| 556 |
-
_menu.style.left = Math.max(8, Math.min(rect.left, vw - 180)) + "px"; // align to the bubble's left edge
|
| 557 |
-
_menu.style.top = (rect.bottom + 10) + "px";
|
| 558 |
-
requestAnimationFrame(() => { _picker.classList.add("in"); _menu.classList.add("in"); });
|
| 559 |
-
|
| 560 |
-
if (navigator.vibrate) navigator.vibrate(12);
|
| 561 |
-
clearTimeout(_holdAuto); _holdAuto = setTimeout(closeHold, 6000);
|
| 562 |
-
}
|
| 563 |
-
function closeHold() {
|
| 564 |
-
clearTimeout(_holdAuto);
|
| 565 |
-
if (_overlay) { _overlay.classList.remove("in"); _overlay.hidden = true; }
|
| 566 |
-
if (_picker) _picker.classList.remove("in");
|
| 567 |
-
if (_menu) _menu.classList.remove("in");
|
| 568 |
-
if (_holdClone) { _holdClone.remove(); _holdClone = null; }
|
| 569 |
-
_holdRow = null;
|
| 570 |
-
}
|
| 571 |
-
function onPickEmoji(em, btn) {
|
| 572 |
-
const rowEl = _holdRow; if (!rowEl || !rowEl.dataset.id) { closeHold(); return; }
|
| 573 |
-
const them = rowEl.classList.contains("them");
|
| 574 |
-
const cur = rowEl.querySelector(".aria-react-badge");
|
| 575 |
-
const emoji = (cur && cur.textContent === em) ? null : em; // toggle off
|
| 576 |
-
// animate the emoji flying onto the (cloned) bubble before applying
|
| 577 |
-
if (emoji) flyEmoji(em, btn, () => finishReact(rowEl, them, emoji));
|
| 578 |
-
else finishReact(rowEl, them, emoji);
|
| 579 |
-
closeHoldSoon();
|
| 580 |
-
}
|
| 581 |
-
function finishReact(rowEl, them, emoji) {
|
| 582 |
-
applyReaction(rowEl, emoji);
|
| 583 |
-
if (them) send({ t: "react", id: rowEl.dataset.id, emoji }); // user reacting to ARIA's message
|
| 584 |
-
// (reacting to your own message is local-only flourish; backend only stores user→ARIA)
|
| 585 |
-
}
|
| 586 |
-
/* double-tap ARIA's bubble → quick ❤️ (toggles off on a second double-tap), iMessage-style */
|
| 587 |
-
function quickHeart(rowEl) {
|
| 588 |
-
if (!rowEl.dataset.id) return;
|
| 589 |
-
const cur = rowEl.querySelector(".aria-react-badge");
|
| 590 |
-
const emoji = (cur && cur.textContent === "❤️") ? null : "❤️";
|
| 591 |
-
applyReaction(rowEl, emoji);
|
| 592 |
-
send({ t: "react", id: rowEl.dataset.id, emoji });
|
| 593 |
-
if (emoji && navigator.vibrate) navigator.vibrate(10);
|
| 594 |
-
}
|
| 595 |
-
function closeHoldSoon() { clearTimeout(_holdAuto); _holdAuto = setTimeout(closeHold, 420); }
|
| 596 |
-
function flyEmoji(em, fromBtn, done) {
|
| 597 |
-
const fly = document.createElement("div"); fly.className = "aria-fly"; fly.textContent = em;
|
| 598 |
-
const from = fromBtn.getBoundingClientRect();
|
| 599 |
-
const target = (_holdClone || _holdRow.querySelector(".aria-bubble")).getBoundingClientRect();
|
| 600 |
-
const tx = (_holdRow.classList.contains("them") ? target.right - 24 : target.left + 8);
|
| 601 |
-
const ty = target.bottom - 18;
|
| 602 |
-
Object.assign(fly.style, { left: from.left + "px", top: from.top + "px" });
|
| 603 |
-
(_overlay || document.body).appendChild(fly);
|
| 604 |
-
requestAnimationFrame(() => {
|
| 605 |
-
fly.style.transform = `translate(${tx - from.left}px, ${ty - from.top}px) scale(1.4)`;
|
| 606 |
-
fly.style.opacity = "0.2";
|
| 607 |
-
});
|
| 608 |
-
setTimeout(() => { fly.remove(); if (done) done(); }, 360);
|
| 609 |
-
}
|
| 610 |
-
|
| 611 |
-
/* ---------------- profile popup ---------------- */
|
| 612 |
-
function openProfile() { const m = $("ariaProfile"); if (m) { m.classList.remove("closing"); m.hidden = false; } }
|
| 613 |
-
function closeProfile() {
|
| 614 |
-
const m = $("ariaProfile"); if (!m || m.hidden) return;
|
| 615 |
-
m.classList.add("closing");
|
| 616 |
-
setTimeout(() => { m.hidden = true; m.classList.remove("closing"); }, 260); // let the swing-out finish
|
| 617 |
-
}
|
| 618 |
-
|
| 619 |
-
/* ---------------- misc ---------------- */
|
| 620 |
-
function toast(msg) {
|
| 621 |
-
const t = $("ariaToast"); t.textContent = msg; t.hidden = false;
|
| 622 |
-
clearTimeout(t._timer); t._timer = setTimeout(() => { t.hidden = true; }, 3200);
|
| 623 |
-
}
|
| 624 |
-
function escapeHtml(s) { return String(s).replace(/[&<>"]/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """ }[c])); }
|
| 625 |
-
|
| 626 |
-
export { toast };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cloudflare/pages-integration/js/aria-settings.js
DELETED
|
@@ -1,63 +0,0 @@
|
|
| 1 |
-
/* ============================================================
|
| 2 |
-
ARIA settings: 5 chat themes + the playful mute / block / report
|
| 3 |
-
"treat the AI like a person" jokes. Persists to the conversation.
|
| 4 |
-
============================================================ */
|
| 5 |
-
|
| 6 |
-
const THEMES = ["default", "sunset", "matrix", "bubble", "mono"];
|
| 7 |
-
const $ = (id) => document.getElementById(id);
|
| 8 |
-
|
| 9 |
-
const REPORT_LINES = [
|
| 10 |
-
"Dzięki za zgłoszenie. Nasz zespół (czyli ja) rozpatrzy je z najwyższą powagą.",
|
| 11 |
-
"Status zgłoszenia: zignorowane XD",
|
| 12 |
-
"ARIA otrzymała ostrzeżenie. ARIA się tym nie przejęła.",
|
| 13 |
-
];
|
| 14 |
-
|
| 15 |
-
export function initSettings({ getConvo, patchConvo, toast, onBlockChange }) {
|
| 16 |
-
const applyTheme = (theme, persist = true) => {
|
| 17 |
-
if (!THEMES.includes(theme)) theme = "default";
|
| 18 |
-
document.body.dataset.theme = theme;
|
| 19 |
-
[...$("ariaThemes").children].forEach(d =>
|
| 20 |
-
d.classList.toggle("sel", d.dataset.theme === theme));
|
| 21 |
-
if (persist) patchConvo({ theme });
|
| 22 |
-
};
|
| 23 |
-
|
| 24 |
-
// sync drawer state to the current conversation whenever opened
|
| 25 |
-
$("ariaSettingsBtn").addEventListener("click", () => {
|
| 26 |
-
const c = getConvo();
|
| 27 |
-
applyTheme(c?.theme || "default", false);
|
| 28 |
-
$("ariaMute").classList.toggle("on", !!c?.muted);
|
| 29 |
-
$("ariaBlock").classList.toggle("on", !!c?.blocked);
|
| 30 |
-
});
|
| 31 |
-
|
| 32 |
-
$("ariaThemes").addEventListener("click", (e) => {
|
| 33 |
-
const btn = e.target.closest("[data-theme]");
|
| 34 |
-
if (btn) applyTheme(btn.dataset.theme);
|
| 35 |
-
});
|
| 36 |
-
|
| 37 |
-
$("ariaThemeRand").addEventListener("click", () => {
|
| 38 |
-
const pick = THEMES[Math.floor(Math.random() * THEMES.length)];
|
| 39 |
-
applyTheme(pick);
|
| 40 |
-
toast("Motyw: " + pick);
|
| 41 |
-
});
|
| 42 |
-
|
| 43 |
-
$("ariaMute").addEventListener("click", () => {
|
| 44 |
-
const c = getConvo(); const next = !c?.muted;
|
| 45 |
-
patchConvo({ muted: next });
|
| 46 |
-
$("ariaMute").classList.toggle("on", next);
|
| 47 |
-
toast(next ? "ARIA wyciszona. Nie usłyszysz jej... znaczy nie zobaczysz." : "ARIA znów mówi.");
|
| 48 |
-
});
|
| 49 |
-
|
| 50 |
-
$("ariaBlock").addEventListener("click", () => {
|
| 51 |
-
const c = getConvo(); const next = !c?.blocked;
|
| 52 |
-
patchConvo({ blocked: next });
|
| 53 |
-
onBlockChange?.(next); // swap composer UI + tell the DO (silence / cheeky comeback)
|
| 54 |
-
$("ariaBlock").classList.toggle("on", next);
|
| 55 |
-
toast(next ? "Zablokowano ARIĘ. Odważne." : "Odblokowano ARIĘ. Wybaczyła ci.");
|
| 56 |
-
});
|
| 57 |
-
|
| 58 |
-
$("ariaReport").addEventListener("click", () => {
|
| 59 |
-
let i = 0;
|
| 60 |
-
const next = () => { toast(REPORT_LINES[i++]); if (i < REPORT_LINES.length) setTimeout(next, 1700); };
|
| 61 |
-
next();
|
| 62 |
-
});
|
| 63 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cloudflare/pages-integration/profile-picture-aria.png
DELETED
|
Binary file (81.7 kB)
|
|
|