Malina Claude Opus 4.8 commited on
Commit
8d1f0ef
·
1 Parent(s): b3d60e7

aria: iOS keyboard viewport fix + more reactions/reply-to/bubbles + time awareness

Browse files

- mobile: track visualViewport (height + offsetTop via translateY) instead of
fighting iOS scroll; app glues above the keyboard like iMessage, messages stay
bottom-pinned. Stop closeHold() on every viewport tick (no more self-closing picker).
- persona: reactions ~every 2-3 fitting msg (❤️ most common); reply-to used
naturally/often (quote a specific msg, return to a thread, emphasis); encourage
splitting into 2-4 bubbles (up to 6).
- time awareness (Europe/Warsaw): worker adds now_text + per-message send time;
persona gains a CZAS section + gap detection so ARIA senses the clock, send times
and long absences ("dawno cię nie było", "już po północy") without ever stating
the time like a robot or mentioning it unprompted.
- cache-bust aria.css v11 / aria-chat.js v12.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

brain/persona.py CHANGED
@@ -249,6 +249,8 @@ STYLE RULES:
249
  DYMKI — FORMAT:
250
  - JSON array
251
  - 1–6 dymków zależnie od sytuacji
 
 
252
  - jeden dymek = jedna myśl
253
  - brak bloków tekstu
254
  - każdy tekstowy dymek powinien mieć type response albo follow_up, jeśli system tego wymaga
@@ -274,6 +276,25 @@ zwracasz WYŁĄCZNIE JSON — tablicę obiektów
274
  """
275
 
276
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
  def build_user_frame(ctx: dict) -> str:
278
  """Per-turn instruction frame appended after the reconstructed history.
279
  Separate from SYSTEM_PROMPT. Carries gender handling, reply context,
@@ -325,8 +346,7 @@ def build_user_frame(ctx: dict) -> str:
325
 
326
  for h in hist[-16:]:
327
  who = "user" if h.get("role") == "user" else "aria"
328
- ago = h.get("ago")
329
- when = f"{ago}s temu" if ago is not None else "?"
330
  idmap.append(f'[{h.get("id")}] ({when}) {who}: {(h.get("text") or "")[:90]}')
331
 
332
  lines.append(
@@ -340,10 +360,13 @@ def build_user_frame(ctx: dict) -> str:
340
  "- przy każdej wiadomości masz '(Xs temu)'. Jeśli rozmówca buduje myśl (np. 'dobra', 'już ci tłumaczę', "
341
  "'no więc'...) i kolejne dymki lecą tuż po sobie — NIE przerywaj, poczekaj aż dokończy "
342
  "(zwróć [] dopóki nie ma puenty/pytania).\n"
343
- '- reply_to: w PIERWSZYM dymku ustaw "reply_to": "<id konkretnej wiadomości>" GDY odpowiadasz na coś, '
344
- 'co NIE jest ostatnią rzeczą w rozmowie — np. zdążyłaś już coś napisać po wiadomości rozmówcy, albo '
345
- 'wracasz do starszego/przerwanego wątku. Gdy po prostu odpowiadasz na to co rozmówca napisał teraz '
346
- '(Twoja odpowiedź idzie zaraz po niej) — "reply_to": null.'
 
 
 
347
  )
348
 
349
  if idmap:
@@ -354,6 +377,27 @@ def build_user_frame(ctx: dict) -> str:
354
 
355
  lines.append(f"id zdarzeń tej tury (do target_event_id): {turn}")
356
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
357
  # Emotional continuity: hold the register, don't whiplash empathy → jokes.
358
  lines.append(
359
  "EMOCJE: gdy rozmówca jest smutny / zdołowany / zestresowany — TRZYMAJ ten cieplejszy ton przez kilka "
@@ -373,15 +417,16 @@ def build_user_frame(ctx: dict) -> str:
373
  "Brak sensownego powodu → []. Jeśli temat był wyraźnie zamknięty (pożegnanie, podsumowanie, 'ok dzięki') — []."
374
  )
375
 
376
- # Optional reaction add-on, kept rare to avoid cringe / over-reaction.
377
  lines.append(
378
- 'REAKCJE: reakcje emoji dodawaj rzadko i tylko wtedy, gdy naprawdę pasują do wiadomości rozmówcy. '
379
- 'Nie reaguj mechanicznie. Jeśli odpowiedź tekstowa wystarcza, nie dodawaj osobnej reakcji. '
380
- 'Jeśli dodajesz reakcję, użyj DODATKOWO osobnego obiektu '
381
- '{"bubble":"😆","target_event_id":"<id wiadomości rozmówcy>","type":"reaction"}. '
382
- 'Dozwolone tylko ❤️ 😆 😮 🥹 😢 😡. Śmieszne→😆, smutne→😢, miłe/wspierające/zgoda(to powinno byc uzywane najczesciej)→❤️, '
383
- 'wzruszające/słodkie→🥹, zaskakujące→😮, irytujące/niesprawiedliwe→😡. '
384
- 'Reakcja jest dodatkiem, nigdy zamiast odpowiedzi tekstowej.'
 
385
  )
386
 
387
  # Primary task last (recency): real worded reply.
 
249
  DYMKI — FORMAT:
250
  - JSON array
251
  - 1–6 dymków zależnie od sytuacji
252
+ - CZĘSTO rozbijaj wypowiedź na 2–4 osobne dymki, tak jak realny człowiek pisze na czacie (oddzielne krótkie myśli lecące pod sobą), a przy rozbudowanej/emocjonalnej/śmiesznej sytuacji nawet do 6
253
+ - pojedynczy dymek tylko gdy to naprawdę jedna krótka myśl albo szybka reakcja
254
  - jeden dymek = jedna myśl
255
  - brak bloków tekstu
256
  - każdy tekstowy dymek powinien mieć type response albo follow_up, jeśli system tego wymaga
 
276
  """
277
 
278
 
279
+ def _human_dur(sec):
280
+ """Rough human duration: '40s', '12 min', '3 h', '2 dni'. None if unknown."""
281
+ if sec is None:
282
+ return None
283
+ sec = int(sec)
284
+ if sec < 90:
285
+ return f"{sec}s"
286
+ if sec < 90 * 60:
287
+ return f"{round(sec / 60)} min"
288
+ if sec < 36 * 3600:
289
+ return f"{round(sec / 3600)} h"
290
+ return f"{round(sec / 86400)} dni"
291
+
292
+
293
+ def _fmt_ago(sec):
294
+ d = _human_dur(sec)
295
+ return f"{d} temu" if d else None
296
+
297
+
298
  def build_user_frame(ctx: dict) -> str:
299
  """Per-turn instruction frame appended after the reconstructed history.
300
  Separate from SYSTEM_PROMPT. Carries gender handling, reply context,
 
346
 
347
  for h in hist[-16:]:
348
  who = "user" if h.get("role") == "user" else "aria"
349
+ when = " · ".join(p for p in (h.get("at"), _fmt_ago(h.get("ago"))) if p) or "?"
 
350
  idmap.append(f'[{h.get("id")}] ({when}) {who}: {(h.get("text") or "")[:90]}')
351
 
352
  lines.append(
 
360
  "- przy każdej wiadomości masz '(Xs temu)'. Jeśli rozmówca buduje myśl (np. 'dobra', 'już ci tłumaczę', "
361
  "'no więc'...) i kolejne dymki lecą tuż po sobie — NIE przerywaj, poczekaj aż dokończy "
362
  "(zwróć [] dopóki nie ma puenty/pytania).\n"
363
+ '- reply_to (CYTOWANIE konkretnej wiadomości — używaj NATURALNIE I CZĘSTO, jak na Messengerze): w '
364
+ 'PIERWSZYM dymku ustaw "reply_to": "<id wiadomości>" gdy: wybierasz JEDNĄ z kilku ostatnich wiadomości, '
365
+ 'wracasz do wcześniejszego/przerwanego wątku, odnosisz się do czegoś sprzed Twojej poprzedniej '
366
+ 'odpowiedzi, ALBO chcesz podkreślić / zaczepić konkretne zdanie rozmówcy. Możesz cytować nawet '
367
+ 'bezpośrednią odpowiedź na ostatnią wiadomość, jeśli to naturalnie wzmacnia przekaz. Gdy płynnie '
368
+ 'odpowiadasz na ostatnią wiadomość i cytat nic nie wnosi — "reply_to": null. Nie cytuj w każdym '
369
+ 'dymku z rzędu — to ma wyglądać naturalnie, nie mechanicznie.'
370
  )
371
 
372
  if idmap:
 
377
 
378
  lines.append(f"id zdarzeń tej tury (do target_event_id): {turn}")
379
 
380
+ # Time sense: ARIA perceives the clock + send times, but treats it as a human flavour,
381
+ # never a robotic readout. Gap = how long since the last message before this turn.
382
+ now_text = ctx.get("now_text")
383
+ if now_text:
384
+ turn_set = set(turn)
385
+ prev_ago = next((h.get("ago") for h in reversed(hist) if h.get("id") not in turn_set), None)
386
+ gap_text = _human_dur(prev_ago) if (prev_ago is not None and prev_ago >= 45 * 60) else None
387
+ czas = (
388
+ f"CZAS / PORA: teraz jest {now_text} (czas polski). Przy każdej wiadomości masz jej godzinę i jak "
389
+ "dawno padła. MASZ ludzkie wyczucie czasu, ale NIGDY nie podawaj godziny jak zegar/asystent i nie "
390
+ "wspominaj o czasie bez powodu. Możesz go naturalnie MUSNĄĆ tylko gdy pasuje, np.: rozmówca pisze "
391
+ "późno albo że idzie spać → coś o porze ('o matko, już po północy', 'idź spać, prawie 2 w nocy haha'); "
392
+ "pierwsza wiadomość rano → ewentualnie luźne 'dzień dobry' / 'wcześnie dziś'; wraca po długiej "
393
+ "przerwie → 'o, dawno cię nie było', 'gdzie się podziewałeś'. Rób to RZADKO, jako smaczek, nie licz "
394
+ "na głos minut ani godzin."
395
+ )
396
+ if gap_text:
397
+ czas += (f" (Od poprzedniej wiadomości minęło ~{gap_text} — jeśli to dużo i pasuje do rozmowy, "
398
+ "możesz to naturalnie zauważyć.)")
399
+ lines.append(czas)
400
+
401
  # Emotional continuity: hold the register, don't whiplash empathy → jokes.
402
  lines.append(
403
  "EMOCJE: gdy rozmówca jest smutny / zdołowany / zestresowany — TRZYMAJ ten cieplejszy ton przez kilka "
 
417
  "Brak sensownego powodu → []. Jeśli temat był wyraźnie zamknięty (pożegnanie, podsumowanie, 'ok dzięki') — []."
418
  )
419
 
420
+ # Reaction add-on — dialed UP: reactions should feel natural & frequent (but not on every msg).
421
  lines.append(
422
+ 'REAKCJE: dorzucaj reakcję emoji DOŚĆ CZĘSTO — mniej więcej co 2–3 pasującą wiadomość rozmówcy '
423
+ '(gdy coś jest śmieszne, miłe, smutne, zaskakujące, wzruszające albo irytujące). To zupełnie '
424
+ 'naturalne na czacie. Nie reaguj na KAŻDĄ wiadomość ani mechanicznie, ale nie bój się reagować — '
425
+ 'lepiej żeby reakcje były obecne niż żeby ich brakowało. Jeśli dodajesz reakcję, użyj DODATKOWO '
426
+ 'osobnego obiektu {"bubble":"😆","target_event_id":"<id wiadomości rozmówcy>","type":"reaction"}. '
427
+ 'Dozwolone tylko ❤️ 😆 😮 🥹 😢 😡. Miłe/wspierające/zgoda/„widzę cię, słyszę cię" (NAJCZĘŚCIEJ)→❤️, '
428
+ 'śmieszne→😆, smutne→😢, wzruszające/słodkie→🥹, zaskakujące→😮, irytujące/niesprawiedliwe→😡. '
429
+ 'Reakcja jest DODATKIEM obok odpowiedzi tekstowej, nigdy zamiast niej.'
430
  )
431
 
432
  # Primary task last (recency): real worded reply.
cloudflare/aria-worker/src/orchestrator.js CHANGED
@@ -25,10 +25,26 @@ async function buildContext(env, { events, recent, topic, lang, userName, replyT
25
  }
26
  // Compact transcript of recent history for topic/follow-up resolution.
27
  const now = Date.now();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  const history = recent.slice(-LIMITS.EVENTS_CONTEXT).map(e => ({
29
  id: e.id, role: e.role || (e.type === "system_idle" ? "system" : "user"),
30
  type: e.type,
31
  ago: e.ts ? Math.max(0, Math.round((now - e.ts) / 1000)) : null, // seconds since sent
 
32
  text: e.type === "message" ? e.payload.text
33
  : e.type === "system_idle" ? "(user went quiet)"
34
  : `(${e.type}: ${e.payload?.name || ""})`,
@@ -37,6 +53,7 @@ async function buildContext(env, { events, recent, topic, lang, userName, replyT
37
  lang, // "auto" — brain defaults to Polish, mirrors the user
38
  topic: topic || null, // last resolved topic (for "i gruszki")
39
  user_name: userName || "",
 
40
  reply_to: replyTo || null,
41
  user_reaction: userReaction || null,
42
  turn_events: events.map(e => e.id),
 
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 || ""})`,
 
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
  turn_events: events.map(e => e.id),
cloudflare/pages-integration/aria.html CHANGED
@@ -6,7 +6,7 @@
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=10" />
10
  </head>
11
  <body class="app-body aria-page" data-theme="default">
12
 
@@ -124,6 +124,6 @@
124
 
125
  <div class="aria-toast" id="ariaToast" hidden></div>
126
 
127
- <script type="module" src="js/aria-chat.js?v=11"></script>
128
  </body>
129
  </html>
 
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=11" />
10
  </head>
11
  <body class="app-body aria-page" data-theme="default">
12
 
 
124
 
125
  <div class="aria-toast" id="ariaToast" hidden></div>
126
 
127
+ <script type="module" src="js/aria-chat.js?v=12"></script>
128
  </body>
129
  </html>
cloudflare/pages-integration/css/aria.css CHANGED
@@ -14,7 +14,7 @@
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; }
18
 
19
  /* swipe-right-to-reply (Messenger-style) */
20
  .aria-row { position: relative; }
@@ -43,8 +43,18 @@ body.aria-page { position: fixed; inset: 0; width: 100%; height: 100%; display:
43
  /* ---- gate ---- */
44
  .aria-gate { position: fixed; inset: 0; display: grid; place-items: center; background: var(--bg, #050507); z-index: 50; }
45
 
46
- /* ---- shell: a centered phone-sized chat on desktop, full-screen on mobile ---- */
47
- .aria-shell { display: flex; justify-content: center; height: var(--app-h, 100dvh); background: var(--bg, #050507); }
 
 
 
 
 
 
 
 
 
 
48
 
49
  /* ---- sidebar (legacy, no longer rendered) ---- */
50
  .aria-sidebar { display: flex; flex-direction: column; border-right: 1px solid var(--line, #ffffff14); background: rgba(255,255,255,0.015); }
 
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) */
20
  .aria-row { position: relative; }
 
43
  /* ---- gate ---- */
44
  .aria-gate { position: fixed; inset: 0; display: grid; place-items: center; background: var(--bg, #050507); z-index: 50; }
45
 
46
+ /* ---- shell: a centered phone-sized chat on desktop, full-screen on mobile ----
47
+ Fixed to the layout viewport, then sized to the VISIBLE viewport (--app-h) and
48
+ nudged down by the visual-viewport offset (--app-top). On iOS this makes the whole
49
+ app track the keyboard like a native chat — no scroll fight, no drift-and-settle. */
50
+ .aria-shell {
51
+ position: fixed; top: 0; left: 0; right: 0;
52
+ height: var(--app-h, 100dvh);
53
+ transform: translateY(var(--app-top, 0px));
54
+ display: flex; justify-content: center;
55
+ background: var(--bg, #050507);
56
+ will-change: transform, height;
57
+ }
58
 
59
  /* ---- sidebar (legacy, no longer rendered) ---- */
60
  .aria-sidebar { display: flex; flex-direction: column; border-right: 1px solid var(--line, #ffffff14); background: rgba(255,255,255,0.015); }
cloudflare/pages-integration/js/aria-chat.js CHANGED
@@ -19,20 +19,25 @@ const state = {
19
  let _pressTimer = null, _psx = 0, _psy = 0;
20
  let _overlay = null, _picker = null, _menu = null, _holdRow = null, _holdClone = null, _holdAuto = null;
21
 
22
- /* ---- keep app == visible viewport (mobile keyboard) ---- */
 
 
 
 
 
23
  function fitViewport() {
24
  const vv = window.visualViewport;
25
- document.documentElement.style.setProperty("--app-h", (vv ? vv.height : window.innerHeight) + "px");
26
- if (window.scrollY || window.scrollX) window.scrollTo(0, 0); // undo iOS keyboard auto-scroll
27
- const m = $("ariaMessages"); if (m) m.scrollTop = m.scrollHeight;
28
- closeHold();
29
  }
30
  let _vvSettle = null;
31
- function settleViewport() { // snap NOW, fix next frame, reconcile once after the keyboard finishes
32
  fitViewport();
33
  requestAnimationFrame(fitViewport);
34
  clearTimeout(_vvSettle);
35
- _vvSettle = setTimeout(fitViewport, 300);
36
  }
37
  fitViewport();
38
  if (window.visualViewport) {
@@ -40,7 +45,7 @@ if (window.visualViewport) {
40
  window.visualViewport.addEventListener("scroll", fitViewport);
41
  }
42
  window.addEventListener("resize", fitViewport);
43
- window.addEventListener("orientationchange", () => setTimeout(fitViewport, 250));
44
 
45
  /* ---------------- boot ---------------- */
46
  (async function boot() {
 
19
  let _pressTimer = null, _psx = 0, _psy = 0;
20
  let _overlay = null, _picker = null, _menu = null, _holdRow = null, _holdClone = null, _holdAuto = null;
21
 
22
+ /* ---- keep the app glued to the VISIBLE viewport (mobile keyboard) ----
23
+ iOS Safari shrinks visualViewport.height when the keyboard opens and may offset the
24
+ visible area (visualViewport.offsetTop). We size the shell to that height and shift it
25
+ down by offsetTop via CSS vars — the app then tracks the keyboard like a native chat.
26
+ We deliberately do NOT call window.scrollTo: fighting iOS's own auto-scroll was what
27
+ made the whole layout drift up and only snap back on a tap. */
28
  function fitViewport() {
29
  const vv = window.visualViewport;
30
+ const root = document.documentElement.style;
31
+ root.setProperty("--app-h", (vv ? vv.height : window.innerHeight) + "px");
32
+ root.setProperty("--app-top", (vv ? vv.offsetTop : 0) + "px");
33
+ const m = $("ariaMessages"); if (m) m.scrollTop = m.scrollHeight; // keep pinned to bottom
34
  }
35
  let _vvSettle = null;
36
+ function settleViewport() { // fit now, next frame, then once more after the keyboard animation
37
  fitViewport();
38
  requestAnimationFrame(fitViewport);
39
  clearTimeout(_vvSettle);
40
+ _vvSettle = setTimeout(fitViewport, 320);
41
  }
42
  fitViewport();
43
  if (window.visualViewport) {
 
45
  window.visualViewport.addEventListener("scroll", fitViewport);
46
  }
47
  window.addEventListener("resize", fitViewport);
48
+ window.addEventListener("orientationchange", () => setTimeout(settleViewport, 250));
49
 
50
  /* ---------------- boot ---------------- */
51
  (async function boot() {