samagotchi 0.109.0 → 0.111.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +57 -1
- data/bin/chi +5 -1
- data/docs/architecture.md +9 -6
- data/docs/cli.md +43 -1
- data/docs/configuration.md +140 -3
- data/docs/internals/engine.md +58 -14
- data/docs/internals/participants.md +7 -4
- data/docs/internals/prompt-caching.md +5 -0
- data/docs/internals/remote-sessions.md +3 -3
- data/docs/internals/web-push.md +200 -0
- data/docs/internals/working-set.md +7 -6
- data/docs/plugins.md +1 -1
- data/docs/sessions.md +4 -2
- data/docs/sub-agent.md +1 -1
- data/lib/samagotchi/bridge/turn_accumulator.rb +3 -1
- data/lib/samagotchi/bundles/system/manifest.yml +1 -1
- data/lib/samagotchi/config.rb +4 -0
- data/lib/samagotchi/context_note.rb +7 -3
- data/lib/samagotchi/engine.rb +166 -499
- data/lib/samagotchi/engine_snapshots.rb +223 -0
- data/lib/samagotchi/event_fanout.rb +236 -0
- data/lib/samagotchi/idle_recap.rb +1 -1
- data/lib/samagotchi/idle_reminders.rb +1 -1
- data/lib/samagotchi/kernel_loop.rb +12 -7
- data/lib/samagotchi/llm/chat_loop.rb +9 -2
- data/lib/samagotchi/message_time.rb +104 -0
- data/lib/samagotchi/model_binding.rb +138 -0
- data/lib/samagotchi/reminder_queue.rb +20 -3
- data/lib/samagotchi/reply_wait/poll.rb +39 -1
- data/lib/samagotchi/run_options.rb +4 -1
- data/lib/samagotchi/send_command/wait_target.rb +10 -3
- data/lib/samagotchi/send_command.rb +2 -1
- data/lib/samagotchi/session.rb +12 -3
- data/lib/samagotchi/session_access/contract.rb +1 -1
- data/lib/samagotchi/session_access/local.rb +11 -5
- data/lib/samagotchi/session_access/remote.rb +2 -1
- data/lib/samagotchi/session_access.rb +7 -3
- data/lib/samagotchi/session_inbox.rb +7 -3
- data/lib/samagotchi/session_manager.rb +5 -0
- data/lib/samagotchi/steer.rb +5 -3
- data/lib/samagotchi/terminal_ui/attached_loop.rb +70 -9
- data/lib/samagotchi/terminal_ui/between_turns.rb +8 -3
- data/lib/samagotchi/terminal_ui/formatting.rb +13 -5
- data/lib/samagotchi/terminal_ui/gap_clock.rb +78 -0
- data/lib/samagotchi/terminal_ui/reline_seam.rb +20 -2
- data/lib/samagotchi/terminal_ui.rb +40 -5
- data/lib/samagotchi/tool_activity.rb +11 -0
- data/lib/samagotchi/turn_checkpoint.rb +6 -1
- data/lib/samagotchi/turn_endings.rb +137 -0
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +28 -1369
- data/lib/samagotchi/web/grants.rb +3 -12
- data/lib/samagotchi/web/message_display.rb +274 -0
- data/lib/samagotchi/web/participant_view.rb +12 -5
- data/lib/samagotchi/web/private_files.rb +31 -0
- data/lib/samagotchi/web/public/app.js +41 -9
- data/lib/samagotchi/web/public/apple-touch-icon.png +0 -0
- data/lib/samagotchi/web/public/bubbles.js +29 -7
- data/lib/samagotchi/web/public/format.js +72 -6
- data/lib/samagotchi/web/public/icons/chi-180.png +0 -0
- data/lib/samagotchi/web/public/icons/chi-192.png +0 -0
- data/lib/samagotchi/web/public/icons/chi-512.png +0 -0
- data/lib/samagotchi/web/public/index.html +6 -0
- data/lib/samagotchi/web/public/manifest.webmanifest +13 -0
- data/lib/samagotchi/web/public/notifications.js +137 -3
- data/lib/samagotchi/web/public/notify.js +1 -1
- data/lib/samagotchi/web/public/participant.html +2 -0
- data/lib/samagotchi/web/public/participant.js +30 -7
- data/lib/samagotchi/web/public/participant_model.js +25 -2
- data/lib/samagotchi/web/public/push.js +95 -0
- data/lib/samagotchi/web/public/stage_view.js +8 -0
- data/lib/samagotchi/web/public/stream_handlers.js +32 -4
- data/lib/samagotchi/web/public/sw.js +101 -0
- data/lib/samagotchi/web/public/time_gaps.js +98 -0
- data/lib/samagotchi/web/public/tokens.css +2 -2
- data/lib/samagotchi/web/public/turn_events.js +25 -1
- data/lib/samagotchi/web/public/turn_html.js +15 -8
- data/lib/samagotchi/web/public/turn_view.js +8 -3
- data/lib/samagotchi/web/push/attention.rb +105 -0
- data/lib/samagotchi/web/push/client.rb +103 -0
- data/lib/samagotchi/web/push/crypto.rb +126 -0
- data/lib/samagotchi/web/push/notifier.rb +230 -0
- data/lib/samagotchi/web/push/store.rb +285 -0
- data/lib/samagotchi/web/push.rb +73 -0
- data/lib/samagotchi/web/push_routes.rb +99 -0
- data/lib/samagotchi/web/running.rb +39 -4
- data/lib/samagotchi/web/server.rb +112 -32
- data/lib/samagotchi/web/session_control.rb +441 -0
- data/lib/samagotchi/web/session_create.rb +384 -0
- data/lib/samagotchi/web/session_show.rb +411 -0
- data/lib/samagotchi/web/tunnel/tailscale.rb +325 -0
- data/lib/samagotchi/web/tunnel.rb +133 -0
- data/lib/samagotchi/worker.rb +3 -2
- metadata +30 -1
|
@@ -253,13 +253,79 @@ export function relativeTime(iso, now = Date.now()) {
|
|
|
253
253
|
return d.getFullYear() === new Date(now).getFullYear() ? date : `${date} ${d.getFullYear()}`;
|
|
254
254
|
}
|
|
255
255
|
|
|
256
|
-
//
|
|
257
|
-
//
|
|
258
|
-
|
|
256
|
+
// ── Wall times (MessageTime's twin, lib/samagotchi/message_time.rb) ──
|
|
257
|
+
// A history entry's `at` (local ISO), a turn record's started_at, an
|
|
258
|
+
// event's at / created_at: the bubbles' hover and the gap dividers. Every
|
|
259
|
+
// helper takes its times (ISO text or epoch ms) and +now+ explicitly.
|
|
260
|
+
|
|
261
|
+
// The quiet time after which the page marks a gap (MessageTime::GAP_SECONDS).
|
|
262
|
+
export const GAP_SECONDS = 600;
|
|
263
|
+
|
|
264
|
+
const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
|
265
|
+
|
|
266
|
+
// +time+ (ISO text, epoch ms or a Date) as a Date, or null.
|
|
267
|
+
export function timeOf(time) {
|
|
268
|
+
const t = time instanceof Date ? time.getTime() : typeof time === "number" ? time : typeof time === "string" ? Date.parse(time) : NaN;
|
|
269
|
+
return Number.isFinite(t) ? new Date(t) : null;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const pad2 = (n) => String(n).padStart(2, "0");
|
|
273
|
+
const hhmm = (d) => `${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
|
|
274
|
+
const sameDay = (a, b) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
|
|
275
|
+
// "Sat 24 Oct 09:10" (MessageTime.day_clock).
|
|
276
|
+
const dayClock = (d) => `${DAYS[d.getDay()]} ${d.getDate()} ${MONTHS[d.getMonth()]} ${hhmm(d)}`;
|
|
277
|
+
|
|
278
|
+
// "14:32", local time; on another local day than +now+ (when given) the
|
|
279
|
+
// day form "Sat 24 Oct 09:10". "" for no or bad input.
|
|
280
|
+
export function wallClock(time, now = null) {
|
|
281
|
+
const d = timeOf(time);
|
|
282
|
+
if (!d) return "";
|
|
283
|
+
const today = now === null ? null : timeOf(now);
|
|
284
|
+
return today && !sameDay(d, today) ? dayClock(d) : hhmm(d);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// A bubble's hover: "Sat 24 Oct 2026 14:32:05", local time; "" for none.
|
|
288
|
+
export function fullTime(time) {
|
|
289
|
+
const d = timeOf(time);
|
|
290
|
+
if (!d) return "";
|
|
291
|
+
return `${DAYS[d.getDay()]} ${d.getDate()} ${MONTHS[d.getMonth()]} ${d.getFullYear()} ${hhmm(d)}:${pad2(d.getSeconds())}`;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// "47 min", "3 h", "2 d": whole units, rounded down (MessageTime.ago; the
|
|
295
|
+
// scale of relativeTime).
|
|
296
|
+
export function agoText(seconds) {
|
|
297
|
+
const s = Number(seconds) || 0;
|
|
298
|
+
if (s < 3600) return `${Math.max(Math.floor(s / 60), 0)} min`;
|
|
299
|
+
if (s < 86400) return `${Math.floor(s / 3600)} h`;
|
|
300
|
+
return `${Math.floor(s / 86400)} d`;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// The divider between activity that ended at +prevEnd+ and activity that
|
|
304
|
+
// starts at +nextStart+: null below GAP_SECONDS (or when either is
|
|
305
|
+
// unknown), else "── 14:32 · 47 min later ──" (MessageTime.gap_line). The
|
|
306
|
+
// date is added when the local day changed, and (the page reads old
|
|
307
|
+
// history too) when the next start is on another day than +now+.
|
|
308
|
+
export function gapText(prevEnd, nextStart, now = Date.now()) {
|
|
309
|
+
const prev = timeOf(prevEnd);
|
|
310
|
+
const next = timeOf(nextStart);
|
|
311
|
+
if (!prev || !next) return null;
|
|
312
|
+
const seconds = (next - prev) / 1000;
|
|
313
|
+
if (seconds < GAP_SECONDS) return null;
|
|
314
|
+
const today = timeOf(now);
|
|
315
|
+
const time = sameDay(prev, next) && (!today || sameDay(next, today)) ? hhmm(next) : dayClock(next);
|
|
316
|
+
return `\u2500\u2500 ${time} \u00b7 ${agoText(seconds)} later \u2500\u2500`;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// The recap bubble's label: when it was written (+createdAt+, wallClock
|
|
320
|
+
// against +now+), how many turns came after it (stale: a turn started while
|
|
321
|
+
// the page showed it, count unknown).
|
|
322
|
+
export function recapLabel(turnsSince, stale = false, createdAt = null, now = Date.now()) {
|
|
259
323
|
const n = Number(turnsSince) || 0;
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
324
|
+
const time = wallClock(createdAt, now);
|
|
325
|
+
const head = time ? `recap · ${time}` : "recap";
|
|
326
|
+
if (n === 1) return `${head} · before the last turn`;
|
|
327
|
+
if (n > 1) return `${head} · before the last ${n} turns`;
|
|
328
|
+
return stale ? `${head} · earlier` : head;
|
|
263
329
|
}
|
|
264
330
|
|
|
265
331
|
// The info bar's memory chip on a phone (where the "mem: …" line goes),
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -4,6 +4,10 @@
|
|
|
4
4
|
<meta charset="utf-8">
|
|
5
5
|
<title>Chi</title>
|
|
6
6
|
<link rel="icon" href="/assets/favicon.svg" type="image/svg+xml">
|
|
7
|
+
<!-- The Home Screen app (Web Push): bare paths, served without the token (App::GATE_FREE_PATHS); icons from script/render-icons. -->
|
|
8
|
+
<link rel="manifest" href="/manifest.webmanifest">
|
|
9
|
+
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
|
10
|
+
<meta name="apple-mobile-web-app-title" content="Chi">
|
|
7
11
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
8
12
|
<link rel="stylesheet" href="/assets/tokens.css">
|
|
9
13
|
<style>
|
|
@@ -51,6 +55,8 @@ main{flex:1;display:flex;flex-direction:column;gap:16px;padding:16px;overflow:au
|
|
|
51
55
|
.bubble.output.boxed{overflow:hidden;transition:max-height 360ms ease}
|
|
52
56
|
.bubble.output.revealing>:not(.copy-btn){animation:fadeIn 240ms ease}
|
|
53
57
|
@media (prefers-reduced-motion:reduce){.bubble.output.boxed{transition:none}.bubble.output.revealing>:not(.copy-btn){animation:none}}
|
|
58
|
+
/* A gap divider (time_gaps.js): one centred dim line where a quiet stretch passed, never wrapped (a phone at 360 px keeps it on one line). Not a .bubble. */
|
|
59
|
+
.time-gap{align-self:stretch;text-align:center;color:var(--time-gap);font-size:12px;line-height:1.4;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin:2px 0;user-select:none}
|
|
54
60
|
.turn-timing{margin-top:8px;color:var(--text-muted);font-size:11px;font-variant-numeric:tabular-nums}
|
|
55
61
|
.turn-timing.live{color:var(--accent)}
|
|
56
62
|
.bubble.output.markdown{white-space:normal}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "Chi",
|
|
3
|
+
"short_name": "Chi",
|
|
4
|
+
"start_url": "/",
|
|
5
|
+
"scope": "/",
|
|
6
|
+
"display": "standalone",
|
|
7
|
+
"background_color": "#0b0d11",
|
|
8
|
+
"theme_color": "#7aa5ff",
|
|
9
|
+
"icons": [
|
|
10
|
+
{ "src": "/icons/chi-192.png", "sizes": "192x192", "type": "image/png" },
|
|
11
|
+
{ "src": "/icons/chi-512.png", "sizes": "512x512", "type": "image/png" }
|
|
12
|
+
]
|
|
13
|
+
}
|
|
@@ -5,6 +5,14 @@
|
|
|
5
5
|
// several tabs show one, and none while another chi tab is in front with it
|
|
6
6
|
// (notify.js, Several tabs).
|
|
7
7
|
//
|
|
8
|
+
// In the Home Screen app (push.js pushSupported) the bell means "push to
|
|
9
|
+
// this device" instead (Web Push): chi web pushes approvals and questions to
|
|
10
|
+
// it while the app is closed. chi web without push (no https public URL)
|
|
11
|
+
// leaves the bell as it is in a tab. With the bell on, the app also tidies
|
|
12
|
+
// the device (syncDevice): it closes the pushed notifications whose
|
|
13
|
+
// question isn't open any more and sets the app's badge, as chi web sends
|
|
14
|
+
// no close push (WebKit's silent-push quota).
|
|
15
|
+
//
|
|
8
16
|
// The browser parts come in as deps (globals by default) so the specs can
|
|
9
17
|
// drive it without a DOM.
|
|
10
18
|
|
|
@@ -12,6 +20,9 @@ import { sessionHash } from "./route.js";
|
|
|
12
20
|
import {
|
|
13
21
|
NOTIFY_CHANNEL, attentionText, createNotifyGate, initialAttentionState, notifyState as bellState, trackAttention,
|
|
14
22
|
} from "./notify.js";
|
|
23
|
+
import {
|
|
24
|
+
isQuestionTag, openPushKeys, pushSupported, subscribe as pushSubscribe, unsubscribe as pushUnsubscribe,
|
|
25
|
+
} from "./push.js";
|
|
15
26
|
|
|
16
27
|
export const NOTIFY_KEY = "chi_notify";
|
|
17
28
|
|
|
@@ -21,6 +32,24 @@ const NOTIFY_TITLES = {
|
|
|
21
32
|
denied: "Notifications are blocked for this site in the browser's settings",
|
|
22
33
|
};
|
|
23
34
|
|
|
35
|
+
const PUSH_TITLES = {
|
|
36
|
+
on: "Notifications to this phone: on (approvals and questions, also while the app is closed). Tap to turn off",
|
|
37
|
+
off: "Notify this phone when a session needs approval or an answer, also while the app is closed",
|
|
38
|
+
denied: "Notifications are blocked for this app in the phone's settings",
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
// fetch's JSON, or an Error with chi web's detail.
|
|
42
|
+
async function defaultApi(method, path, body) {
|
|
43
|
+
const res = await fetch(path, {
|
|
44
|
+
method,
|
|
45
|
+
headers: body === undefined ? {} : { "Content-Type": "application/json" },
|
|
46
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
47
|
+
});
|
|
48
|
+
const data = res.status === 204 ? null : await res.json().catch(() => null);
|
|
49
|
+
if (!res.ok) throw new Error(data?.detail || `HTTP ${res.status}`);
|
|
50
|
+
return data;
|
|
51
|
+
}
|
|
52
|
+
|
|
24
53
|
function defaultChannel() {
|
|
25
54
|
try {
|
|
26
55
|
if (typeof globalThis.BroadcastChannel === "function") return new BroadcastChannel(NOTIFY_CHANNEL);
|
|
@@ -35,6 +64,10 @@ function defaultChannel() {
|
|
|
35
64
|
// @param storage () => localStorage (it can throw)
|
|
36
65
|
// @param channel the BroadcastChannel to the other chi tabs, or null
|
|
37
66
|
// @param gateOptions passed to createNotifyGate (specs: schedule, now)
|
|
67
|
+
// @param nav the navigator (serviceWorker; push.js pushSupported)
|
|
68
|
+
// @param api (method, path, body) => Promise of chi web's JSON
|
|
69
|
+
// @param scoped the page shows one project's sessions (?dir=): it never
|
|
70
|
+
// tidies the device, as it doesn't see the others'
|
|
38
71
|
// @return {noticeSessions(type, data), noticeList(sessions), setBaseTitle(title), clearBadge()}
|
|
39
72
|
export function createNotifications({
|
|
40
73
|
button,
|
|
@@ -44,8 +77,17 @@ export function createNotifications({
|
|
|
44
77
|
storage = () => globalThis.localStorage,
|
|
45
78
|
channel = defaultChannel(),
|
|
46
79
|
gateOptions = {},
|
|
80
|
+
nav = globalThis.navigator,
|
|
81
|
+
api = defaultApi,
|
|
82
|
+
scoped = false,
|
|
47
83
|
}) {
|
|
48
84
|
let attention = initialAttentionState();
|
|
85
|
+
// Web Push in the Home Screen app: null until chi web says it pushes
|
|
86
|
+
// ({reg, key, on}), and for good in a tab or without push.
|
|
87
|
+
let push = null;
|
|
88
|
+
let pushBusy = false;
|
|
89
|
+
let syncing = null;
|
|
90
|
+
let syncAgain = false;
|
|
49
91
|
const badgeKeys = new Set();
|
|
50
92
|
let baseTitle = "Chi";
|
|
51
93
|
|
|
@@ -65,6 +107,10 @@ export function createNotifications({
|
|
|
65
107
|
|
|
66
108
|
// "on" | "off" | "denied" | "unsupported" (notify.js)
|
|
67
109
|
function notifyState() {
|
|
110
|
+
if (push) {
|
|
111
|
+
if (typeof NotificationApi === "function" && NotificationApi.permission === "denied") return "denied";
|
|
112
|
+
return push.on ? "on" : "off";
|
|
113
|
+
}
|
|
68
114
|
const hasNotification = typeof NotificationApi === "function";
|
|
69
115
|
return bellState({
|
|
70
116
|
hasNotification,
|
|
@@ -78,11 +124,12 @@ export function createNotifications({
|
|
|
78
124
|
const state = notifyState();
|
|
79
125
|
button.hidden = state === "unsupported";
|
|
80
126
|
button.dataset.state = state;
|
|
81
|
-
button.title = NOTIFY_TITLES[state] || "";
|
|
127
|
+
button.title = (push ? PUSH_TITLES : NOTIFY_TITLES)[state] || "";
|
|
82
128
|
button.setAttribute("aria-pressed", state === "on" ? "true" : "false");
|
|
83
129
|
}
|
|
84
130
|
|
|
85
131
|
async function toggleNotify() {
|
|
132
|
+
if (push) return togglePush();
|
|
86
133
|
const state = notifyState();
|
|
87
134
|
if (state === "unsupported" || state === "denied") return;
|
|
88
135
|
let wanted = state !== "on";
|
|
@@ -93,8 +140,87 @@ export function createNotifications({
|
|
|
93
140
|
renderNotifyBtn();
|
|
94
141
|
}
|
|
95
142
|
|
|
143
|
+
// This device's subscription on (permission from the tap: iOS asks only
|
|
144
|
+
// from one), a test push to show it works; or off.
|
|
145
|
+
async function togglePush() {
|
|
146
|
+
if (pushBusy || notifyState() === "denied") return;
|
|
147
|
+
pushBusy = true;
|
|
148
|
+
let failed = null;
|
|
149
|
+
try {
|
|
150
|
+
if (push.on) {
|
|
151
|
+
await pushUnsubscribe({ reg: push.reg, del: (endpoint) => api("DELETE", "/api/push/subscriptions", { endpoint }) });
|
|
152
|
+
push.on = false;
|
|
153
|
+
setDeviceBadge(0);
|
|
154
|
+
} else if (NotificationApi.permission === "granted" || (await NotificationApi.requestPermission()) === "granted") {
|
|
155
|
+
const { subscription } = await pushSubscribe({
|
|
156
|
+
reg: push.reg, key: push.key, post: (json) => api("POST", "/api/push/subscriptions", { subscription: json }),
|
|
157
|
+
});
|
|
158
|
+
push.on = true;
|
|
159
|
+
api("POST", "/api/push/test", { endpoint: subscription.endpoint }).catch(() => {});
|
|
160
|
+
syncDevice();
|
|
161
|
+
}
|
|
162
|
+
} catch (e) {
|
|
163
|
+
failed = e?.message || String(e);
|
|
164
|
+
} finally {
|
|
165
|
+
pushBusy = false;
|
|
166
|
+
}
|
|
167
|
+
renderNotifyBtn();
|
|
168
|
+
// Said on the bell (its tooltip); the next tap tries again.
|
|
169
|
+
if (failed) button.title = `Notifications to this phone failed: ${failed}`;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// The Home Screen app: its service worker, chi web's key, and whether
|
|
173
|
+
// chi web has this device. A tab, or chi web without push: the bell as is.
|
|
174
|
+
async function startPush() {
|
|
175
|
+
if (typeof NotificationApi !== "function" || !pushSupported({ win, nav })) return;
|
|
176
|
+
try {
|
|
177
|
+
const reg = await nav.serviceWorker.register("/sw.js", { scope: "/" });
|
|
178
|
+
const sub = await reg.pushManager.getSubscription();
|
|
179
|
+
const query = sub ? `?endpoint=${encodeURIComponent(sub.endpoint)}` : "";
|
|
180
|
+
const info = await api("GET", `/api/push${query}`);
|
|
181
|
+
if (!info?.enabled || !info.public_key) return;
|
|
182
|
+
push = { reg, key: info.public_key, on: !!(sub && info.this) };
|
|
183
|
+
renderNotifyBtn();
|
|
184
|
+
} catch (_) {}
|
|
185
|
+
syncDevice();
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function setDeviceBadge(count) {
|
|
189
|
+
try {
|
|
190
|
+
const done = count > 0 && typeof nav?.setAppBadge === "function" ? nav.setAppBadge(count)
|
|
191
|
+
: typeof nav?.clearAppBadge === "function" ? nav.clearAppBadge() : null;
|
|
192
|
+
done?.catch?.(() => {});
|
|
193
|
+
} catch (_) {}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// The Home Screen app with the bell on: closes the pushed notifications
|
|
197
|
+
// whose question isn't open (chi's own, chi:test, stay) and sets the
|
|
198
|
+
// app's badge. Never before the first snapshot (an empty byId would close
|
|
199
|
+
// them all) nor on a project's page (its byId lacks the others). One at a
|
|
200
|
+
// time; asked again meanwhile, it runs once more after.
|
|
201
|
+
function syncDevice() {
|
|
202
|
+
if (!push || !push.on || scoped || !attention.seeded) return syncing;
|
|
203
|
+
if (syncing) {
|
|
204
|
+
syncAgain = true;
|
|
205
|
+
return syncing;
|
|
206
|
+
}
|
|
207
|
+
syncing = (async () => {
|
|
208
|
+
do {
|
|
209
|
+
syncAgain = false;
|
|
210
|
+
const open = new Set(openPushKeys(attention.byId));
|
|
211
|
+
try {
|
|
212
|
+
const shown = await push.reg.getNotifications();
|
|
213
|
+
for (const n of shown || []) if (isQuestionTag(n.tag) && !open.has(n.tag)) n.close();
|
|
214
|
+
} catch (_) {}
|
|
215
|
+
if (push?.on) setDeviceBadge(open.size);
|
|
216
|
+
} while (syncAgain);
|
|
217
|
+
})().finally(() => { syncing = null; });
|
|
218
|
+
return syncing;
|
|
219
|
+
}
|
|
220
|
+
|
|
96
221
|
function showNotification(session, a) {
|
|
97
|
-
|
|
222
|
+
// The app gets chi web's pushes instead.
|
|
223
|
+
if (push || notifyState() !== "on") return;
|
|
98
224
|
const { title, body } = attentionText(session, a);
|
|
99
225
|
try {
|
|
100
226
|
const n = new NotificationApi(title, { body, tag: a.key });
|
|
@@ -135,6 +261,7 @@ export function createNotifications({
|
|
|
135
261
|
}
|
|
136
262
|
}
|
|
137
263
|
if (badgeKeys.size !== size) setTitle();
|
|
264
|
+
if (doc.visibilityState === "visible") syncDevice();
|
|
138
265
|
}
|
|
139
266
|
|
|
140
267
|
// The user is here: the badge goes, and the other tabs drop what it had.
|
|
@@ -149,7 +276,9 @@ export function createNotifications({
|
|
|
149
276
|
// before it has focus, and a tab switch inside a focused window sends no
|
|
150
277
|
// focus event), the window got focus, or they touched the page.
|
|
151
278
|
function backInFront() {
|
|
152
|
-
if (doc.visibilityState
|
|
279
|
+
if (doc.visibilityState !== "visible") return;
|
|
280
|
+
clearBadge();
|
|
281
|
+
syncDevice();
|
|
153
282
|
}
|
|
154
283
|
doc.addEventListener("visibilitychange", backInFront);
|
|
155
284
|
win.addEventListener("focus", backInFront);
|
|
@@ -157,6 +286,7 @@ export function createNotifications({
|
|
|
157
286
|
doc.addEventListener("keydown", clearBadge, true);
|
|
158
287
|
button.addEventListener("click", toggleNotify);
|
|
159
288
|
renderNotifyBtn();
|
|
289
|
+
const pushReady = startPush();
|
|
160
290
|
|
|
161
291
|
return {
|
|
162
292
|
noticeSessions,
|
|
@@ -170,5 +300,9 @@ export function createNotifications({
|
|
|
170
300
|
setTitle();
|
|
171
301
|
},
|
|
172
302
|
clearBadge,
|
|
303
|
+
// Settles once the Home Screen app's push state is known (specs).
|
|
304
|
+
pushReady,
|
|
305
|
+
// The device's tidy-up in flight, or null (specs await it).
|
|
306
|
+
syncing: () => syncing,
|
|
173
307
|
};
|
|
174
308
|
}
|
|
@@ -23,7 +23,7 @@ const UNWATCHED_ORIGINS = ["delegate_report", "context", "task"];
|
|
|
23
23
|
|
|
24
24
|
// The step-limit question (kind "continue": a turn ran out of iterations
|
|
25
25
|
// and asks whether to go on) has its own reason: "out of steps".
|
|
26
|
-
const questionReason = (q) => (q.kind === "approval" ? "approval" : q.kind === "continue" ? "continue" : "question");
|
|
26
|
+
export const questionReason = (q) => (q.kind === "approval" ? "approval" : q.kind === "continue" ? "continue" : "question");
|
|
27
27
|
|
|
28
28
|
// What a session waits on the user for right now, from one summary: an open
|
|
29
29
|
// question or approval, or a running turn's card with actions (check-in's
|
|
@@ -67,6 +67,8 @@ body{font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,Helvetica
|
|
|
67
67
|
main{flex:1;min-height:0;overflow-y:auto;padding:16px 16px 8px}
|
|
68
68
|
.p-thread{max-width:760px;margin:0 auto;display:flex;flex-direction:column;gap:12px}
|
|
69
69
|
.p-empty{color:var(--text-muted);text-align:center;padding:40px 0}
|
|
70
|
+
/* A gap divider (time_gaps.js): one centred dim line where a quiet stretch passed, never wrapped (a phone at 360 px keeps it on one line). Not a .bubble. */
|
|
71
|
+
.time-gap{align-self:stretch;text-align:center;color:var(--time-gap);font-size:12px;line-height:1.4;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin:2px 0;user-select:none}
|
|
70
72
|
.p-msg{display:flex;flex-direction:column;gap:4px;min-width:0}
|
|
71
73
|
.p-who{font-size:12px;color:var(--text-muted);display:flex;align-items:center;gap:6px}
|
|
72
74
|
.p-who b{font-weight:600;color:var(--author-color,var(--author-owner))}
|
|
@@ -7,8 +7,9 @@
|
|
|
7
7
|
// POST …/turn (text only); their queued ones come back with Dequeue.
|
|
8
8
|
import {
|
|
9
9
|
authorColor, participantAuthor, authorLabel, toolLine, toolsSummary, refusalText, dequeueText, endedText, streamURL, reloads, endsLiveTurn, liveFrom, applyLive,
|
|
10
|
-
liveText, withToolSteps, pickSubject, subjectBody, subjectsKey, narrowView, retryDelay, retries,
|
|
10
|
+
liveText, withToolSteps, pickSubject, subjectBody, subjectsKey, narrowView, retryDelay, retries, threadGaps,
|
|
11
11
|
} from "./participant_model.js";
|
|
12
|
+
import { fullTime } from "./format.js";
|
|
12
13
|
import { createAuthLost, lostAnswer } from "./auth_lost.js";
|
|
13
14
|
import { REPLACE_SESSION_TEXT, fragmentCode, tradeFragmentCode } from "./token_fragment.js";
|
|
14
15
|
|
|
@@ -241,6 +242,9 @@ function setView(view) {
|
|
|
241
242
|
function messageNode(message) {
|
|
242
243
|
const user = message.role === "user";
|
|
243
244
|
const node = el("div", `p-msg ${user ? "user" : "reply"}${message.mine ? " mine" : ""}`);
|
|
245
|
+
// When it happened, on hover (the owner's page's bubbles do the same).
|
|
246
|
+
const when = fullTime(message.at);
|
|
247
|
+
if (when) node.title = when;
|
|
244
248
|
if (user) {
|
|
245
249
|
node.style.setProperty("--author-color", authorColor(message.author));
|
|
246
250
|
const who = el("div", "p-who");
|
|
@@ -283,16 +287,35 @@ function toolsNode(rows, open = null) {
|
|
|
283
287
|
return details;
|
|
284
288
|
}
|
|
285
289
|
|
|
290
|
+
// A gap divider (the owner's page's .time-gap line), kept while its text is.
|
|
291
|
+
function gapNode(text, old) {
|
|
292
|
+
if (!text) return null;
|
|
293
|
+
if (old?.textContent === text) return old;
|
|
294
|
+
const node = el("div", "time-gap", text);
|
|
295
|
+
node.setAttribute("role", "separator");
|
|
296
|
+
return node;
|
|
297
|
+
}
|
|
298
|
+
|
|
286
299
|
function renderThread() {
|
|
287
300
|
const thread = $("thread");
|
|
288
|
-
|
|
301
|
+
const messages = withToolSteps(data.messages || []);
|
|
302
|
+
const gaps = threadGaps(messages, { currentAt: data.current_turn?.at || null });
|
|
303
|
+
drawnMessages = messages.map((message, at) => {
|
|
289
304
|
const sig = JSON.stringify(message);
|
|
290
305
|
const old = drawnMessages[at];
|
|
291
|
-
|
|
292
|
-
|
|
306
|
+
const gap = gapNode(gaps.before[at], old?.gap);
|
|
307
|
+
if (old?.sig === sig) return { ...old, gap };
|
|
308
|
+
return { sig, gap, node: keepToolsOpen(messageNode(message), old?.node) };
|
|
293
309
|
});
|
|
294
|
-
const nodes = drawnMessages.
|
|
295
|
-
if (data.current_turn)
|
|
310
|
+
const nodes = drawnMessages.flatMap((entry) => (entry.gap ? [entry.gap, entry.node] : [entry.node]));
|
|
311
|
+
if (data.current_turn) {
|
|
312
|
+
const gap = gapNode(gaps.current, thread.querySelector(":scope > .time-gap.current"));
|
|
313
|
+
if (gap) {
|
|
314
|
+
gap.classList.add("current");
|
|
315
|
+
nodes.push(gap);
|
|
316
|
+
}
|
|
317
|
+
nodes.push(...currentTurnNodes());
|
|
318
|
+
}
|
|
296
319
|
else if (data.waiting_for_owner) nodes.push(el("div", "p-waiting", "Waiting for the session's owner"));
|
|
297
320
|
if (nodes.length === 0) nodes.push(el("div", "p-empty", "Nothing here yet. Comments and replies show here."));
|
|
298
321
|
const main = $("main");
|
|
@@ -326,7 +349,7 @@ function currentTurnNodes() {
|
|
|
326
349
|
const nodes = [];
|
|
327
350
|
if (turn.prompt !== undefined || turn.automatic) {
|
|
328
351
|
nodes.push(messageNode({ role: "user", content: turn.automatic ? "An automatic turn" : turn.prompt, author: turn.author,
|
|
329
|
-
author_name: turn.author_name, mine: turn.mine, automatic: turn.automatic }));
|
|
352
|
+
author_name: turn.author_name, mine: turn.mine, automatic: turn.automatic, at: turn.at }));
|
|
330
353
|
}
|
|
331
354
|
const reply = el("div", "p-msg reply live");
|
|
332
355
|
fillLive(reply, $("liveReply"));
|
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
// refusal in words, the stream's URL, and the live turn as filtered events
|
|
4
4
|
// build it (ParticipantView on the server decides what arrives at all).
|
|
5
5
|
|
|
6
|
+
import { gapText } from "./format.js";
|
|
7
|
+
|
|
6
8
|
// A participant's author: "p:" and its grant id, as the server writes it
|
|
7
9
|
// (Steer.author_for / PARTICIPANT_PREFIX): the one place the web spells it.
|
|
8
10
|
export const PARTICIPANT_PREFIX = "p:";
|
|
@@ -47,30 +49,51 @@ export function toolsSummary(rows) {
|
|
|
47
49
|
// The conversation with each run of text-less tool steps (a reply that
|
|
48
50
|
// only called tools) folded into the next reply's rows, or one row group
|
|
49
51
|
// when no reply follows: one "3 tools: …" line instead of three.
|
|
52
|
+
// A folded run with no reply after it keeps its last step's time (at).
|
|
50
53
|
export function withToolSteps(messages) {
|
|
51
54
|
const out = [];
|
|
52
55
|
let pending = [];
|
|
56
|
+
let pendingAt = null;
|
|
57
|
+
const flush = () => out.push({ role: "assistant", content: "", tools: pending, ...(pendingAt ? { at: pendingAt } : {}) });
|
|
53
58
|
for (const message of messages) {
|
|
54
59
|
const toolOnly = message.role === "assistant" && !String(message.content || "").trim() && message.tools?.length;
|
|
55
60
|
if (toolOnly) {
|
|
56
61
|
pending = pending.concat(message.tools);
|
|
62
|
+
pendingAt = message.at || pendingAt;
|
|
57
63
|
continue;
|
|
58
64
|
}
|
|
59
65
|
if (pending.length) {
|
|
60
66
|
if (message.role === "assistant") {
|
|
61
67
|
out.push({ ...message, tools: pending.concat(message.tools || []) });
|
|
62
68
|
pending = [];
|
|
69
|
+
pendingAt = null;
|
|
63
70
|
continue;
|
|
64
71
|
}
|
|
65
|
-
|
|
72
|
+
flush();
|
|
66
73
|
pending = [];
|
|
74
|
+
pendingAt = null;
|
|
67
75
|
}
|
|
68
76
|
out.push(message);
|
|
69
77
|
}
|
|
70
|
-
if (pending.length)
|
|
78
|
+
if (pending.length) flush();
|
|
71
79
|
return out;
|
|
72
80
|
}
|
|
73
81
|
|
|
82
|
+
// The thread's gap dividers (format.js gapText, the owner's page's words):
|
|
83
|
+
// before each message, and before the turn in progress (+currentAt+, its
|
|
84
|
+
// turn_started's at), the divider's text or null. A gap is marked only
|
|
85
|
+
// where a person's message or a turn starts, measured from the last
|
|
86
|
+
// message's time before it: never inside a turn's work.
|
|
87
|
+
export function threadGaps(messages, { currentAt = null, now = Date.now() } = {}) {
|
|
88
|
+
let last = null;
|
|
89
|
+
const before = (messages || []).map((message) => {
|
|
90
|
+
const text = message?.role === "user" && last && message.at ? gapText(last, message.at, now) : null;
|
|
91
|
+
if (message?.at) last = message.at;
|
|
92
|
+
return text;
|
|
93
|
+
});
|
|
94
|
+
return { before, current: last && currentAt ? gapText(last, currentAt, now) : null };
|
|
95
|
+
}
|
|
96
|
+
|
|
74
97
|
// The server's words (ParticipantMessages, a relay's detail) as the page
|
|
75
98
|
// shows them: a sentence, never reworded; null with none.
|
|
76
99
|
export function sentence(detail) {
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// Web Push, the page's pure parts (notifications.js drives them): whether
|
|
2
|
+
// this page can get pushes, subscribing this device with chi web's key
|
|
3
|
+
// and telling chi web (POST /api/push/subscriptions) or the reverse, and
|
|
4
|
+
// which pushed notifications are still open (the page's cleanup). Only
|
|
5
|
+
// the Home Screen app subscribes (iOS gives push to a standalone app only;
|
|
6
|
+
// a browser tab keeps the in-tab notifications). See
|
|
7
|
+
// docs/internals/web-push.md.
|
|
8
|
+
|
|
9
|
+
import { questionReason } from "./notify.js";
|
|
10
|
+
|
|
11
|
+
// The reasons chi web pushes (Web::Push::Attention::PUSHED).
|
|
12
|
+
const PUSHED = new Set(["approval", "question"]);
|
|
13
|
+
|
|
14
|
+
// The keys still open in a byId (notify.js trackAttention's: session id →
|
|
15
|
+
// summary): a pending question with an id, not relayed, of a reason chi
|
|
16
|
+
// web pushes. Attention.open_keys's rule, so the page, the worker's open
|
|
17
|
+
// list and the badge agree.
|
|
18
|
+
// @return [String] "<session id>:<question id>" keys
|
|
19
|
+
export function openPushKeys(byId) {
|
|
20
|
+
const keys = [];
|
|
21
|
+
for (const summary of Object.values(byId || {})) {
|
|
22
|
+
const q = summary?.pending_question;
|
|
23
|
+
if (!q || !q.id || q.relayed_to || !PUSHED.has(questionReason(q))) continue;
|
|
24
|
+
keys.push(`${summary.id}:${q.id}`);
|
|
25
|
+
}
|
|
26
|
+
return keys;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// A pushed question's tag ("<session id>:<question id>"), not one of chi's
|
|
30
|
+
// own (chi:test, chi:other): only these are ever cleaned up. sw.js keeps
|
|
31
|
+
// the same pattern (a classic script imports nothing).
|
|
32
|
+
export const QUESTION_TAG = /^(?!chi:)[^:]+:[^:]+$/;
|
|
33
|
+
export const isQuestionTag = (tag) => typeof tag === "string" && QUESTION_TAG.test(tag);
|
|
34
|
+
|
|
35
|
+
// A standalone app with a service worker and PushManager, on a secure
|
|
36
|
+
// context (chi web's https public URL; the LAN's plain http has none).
|
|
37
|
+
// @param win the window (isSecureContext, PushManager, matchMedia)
|
|
38
|
+
// @param nav the navigator (serviceWorker, standalone on iOS)
|
|
39
|
+
export function pushSupported({ win, nav }) {
|
|
40
|
+
if (!win || !nav || win.isSecureContext !== true) return false;
|
|
41
|
+
if (!nav.serviceWorker || typeof win.PushManager !== "function") return false;
|
|
42
|
+
let standalone = nav.standalone === true;
|
|
43
|
+
try {
|
|
44
|
+
if (!standalone && typeof win.matchMedia === "function") standalone = win.matchMedia("(display-mode: standalone)").matches === true;
|
|
45
|
+
} catch (_) {}
|
|
46
|
+
return standalone;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// base64url (padded or not) → bytes: applicationServerKey's form.
|
|
50
|
+
export function urlBase64ToBytes(text) {
|
|
51
|
+
const b64 = String(text).replace(/-/g, "+").replace(/_/g, "/");
|
|
52
|
+
const padded = b64 + "=".repeat((4 - (b64.length % 4)) % 4);
|
|
53
|
+
const raw = atob(padded);
|
|
54
|
+
const bytes = new Uint8Array(raw.length);
|
|
55
|
+
for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);
|
|
56
|
+
return bytes;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function sameBytes(a, b) {
|
|
60
|
+
if (!a || !b) return false;
|
|
61
|
+
const x = new Uint8Array(a);
|
|
62
|
+
const y = new Uint8Array(b);
|
|
63
|
+
return x.length === y.length && x.every((v, i) => v === y[i]);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Subscribes this device with chi web's key (a subscription made with
|
|
67
|
+
// another key, an older vapid.pem's, is dropped first: the push service
|
|
68
|
+
// would refuse chi web's token for it) and posts it.
|
|
69
|
+
// @param reg the service worker's registration
|
|
70
|
+
// @param key chi web's public key (GET /api/push's public_key)
|
|
71
|
+
// @param post (subscriptionJson) => Promise of chi web's answer ({id, label})
|
|
72
|
+
// @return {subscription, answer}
|
|
73
|
+
export async function subscribe({ reg, key, post }) {
|
|
74
|
+
const want = urlBase64ToBytes(key);
|
|
75
|
+
let sub = await reg.pushManager.getSubscription();
|
|
76
|
+
if (sub && !sameBytes(sub.options?.applicationServerKey, want)) {
|
|
77
|
+
await sub.unsubscribe();
|
|
78
|
+
sub = null;
|
|
79
|
+
}
|
|
80
|
+
if (!sub) sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: want });
|
|
81
|
+
const answer = await post(typeof sub.toJSON === "function" ? sub.toJSON() : sub);
|
|
82
|
+
return { subscription: sub, answer };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Unsubscribes this device and tells chi web to forget it.
|
|
86
|
+
// @param del (endpoint) => Promise
|
|
87
|
+
// @return whether there was a subscription
|
|
88
|
+
export async function unsubscribe({ reg, del }) {
|
|
89
|
+
const sub = await reg.pushManager.getSubscription();
|
|
90
|
+
if (!sub) return false;
|
|
91
|
+
const endpoint = sub.endpoint;
|
|
92
|
+
await sub.unsubscribe();
|
|
93
|
+
await del(endpoint);
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
@@ -565,6 +565,14 @@ export function createStageView({
|
|
|
565
565
|
|
|
566
566
|
function emptySlots() {
|
|
567
567
|
for (const slot of [promptSlot, extras, answer, tail, cloudBody, queuedSlot, timingSlot]) slot.replaceChildren();
|
|
568
|
+
// The turn left the stage: the status row and the chip say nothing until
|
|
569
|
+
// the next one. Kept as they were, a hidden stage still reads "thinking ·
|
|
570
|
+
// step 1" — the stale stage of a turn the page stopped following.
|
|
571
|
+
mark.textContent = "";
|
|
572
|
+
phaseEl.textContent = "";
|
|
573
|
+
stepEl.textContent = "";
|
|
574
|
+
miniTool.textContent = "";
|
|
575
|
+
chipLabel.textContent = "";
|
|
568
576
|
slotsView.reset();
|
|
569
577
|
rail?.reset();
|
|
570
578
|
promptSlot.classList.remove("full");
|