samagotchi 0.166.0 → 0.167.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 +63 -1
- data/docs/architecture.md +1 -0
- data/docs/cli.md +10 -5
- data/docs/configuration.md +1 -0
- data/docs/guardrails.md +6 -5
- data/docs/hooks.md +4 -6
- data/docs/internals/bundles.md +2 -4
- data/docs/internals/engine.md +4 -5
- data/docs/internals/objectives.md +141 -9
- data/docs/internals/remote-sessions.md +5 -6
- data/docs/internals/web-frontend.md +30 -25
- data/docs/memory.md +1 -2
- data/docs/sessions.md +20 -2
- data/docs/testing.md +4 -3
- data/lib/samagotchi/bridge.rb +1 -1
- data/lib/samagotchi/bundle_command/installed_check.rb +2 -14
- data/lib/samagotchi/bundle_command.rb +19 -11
- data/lib/samagotchi/bundles/system/manifest.yml +1 -1
- data/lib/samagotchi/cli/command.rb +10 -0
- data/lib/samagotchi/compat.rb +3 -11
- data/lib/samagotchi/config.rb +3 -0
- data/lib/samagotchi/context_command.rb +2 -1
- data/lib/samagotchi/engine/objectives.rb +20 -1
- data/lib/samagotchi/engine/side_requests.rb +3 -2
- data/lib/samagotchi/engine/turn_end.rb +4 -1
- data/lib/samagotchi/engine.rb +3 -0
- data/lib/samagotchi/extension_load.rb +2 -26
- data/lib/samagotchi/guardrails/approvals.rb +36 -13
- data/lib/samagotchi/jsonl_store.rb +61 -0
- data/lib/samagotchi/memory_bundle/status.rb +3 -15
- data/lib/samagotchi/memory_bundle/system_bundle.rb +16 -10
- data/lib/samagotchi/memory_command.rb +4 -2
- data/lib/samagotchi/objectives.rb +43 -14
- data/lib/samagotchi/objectives_backing.rb +124 -0
- data/lib/samagotchi/objectives_check.rb +19 -126
- data/lib/samagotchi/objectives_command.rb +14 -7
- data/lib/samagotchi/objectives_record.rb +104 -0
- data/lib/samagotchi/objectives_track.rb +353 -0
- data/lib/samagotchi/push_command.rb +2 -1
- data/lib/samagotchi/remote_command.rb +2 -1
- data/lib/samagotchi/reply_wait/poll.rb +6 -6
- data/lib/samagotchi/reply_wait.rb +4 -24
- data/lib/samagotchi/schedule_command.rb +6 -0
- data/lib/samagotchi/schedules.rb +1 -1
- data/lib/samagotchi/session_access/remote.rb +3 -5
- data/lib/samagotchi/session_commands.rb +1 -1
- data/lib/samagotchi/sessions_command.rb +12 -6
- data/lib/samagotchi/share_command.rb +2 -1
- data/lib/samagotchi/tool_activity.rb +11 -1
- data/lib/samagotchi/tool_declarations.rb +5 -1
- data/lib/samagotchi/tools/objectives_tool.rb +19 -2
- data/lib/samagotchi/turn_stages/objectives.rb +46 -3
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/participant_access.rb +1 -1
- data/lib/samagotchi/web/public/app.js +52 -424
- data/lib/samagotchi/web/public/copy.js +2 -1
- data/lib/samagotchi/web/public/index.html +35 -9
- data/lib/samagotchi/web/public/info_bar_model.js +3 -1
- data/lib/samagotchi/web/public/no_contact_fill.js +29 -0
- data/lib/samagotchi/web/public/objectives.css +14 -0
- data/lib/samagotchi/web/public/objectives_moves.js +82 -9
- data/lib/samagotchi/web/public/objectives_state.js +42 -0
- data/lib/samagotchi/web/public/objectives_strip.js +33 -9
- data/lib/samagotchi/web/public/objectives_track.js +52 -0
- data/lib/samagotchi/web/public/objectives_wiring.js +16 -1
- data/lib/samagotchi/web/public/participant.html +1 -1
- data/lib/samagotchi/web/public/participants_panel.js +14 -7
- data/lib/samagotchi/web/public/question_cards.js +7 -12
- data/lib/samagotchi/web/public/resync_reach.js +10 -6
- data/lib/samagotchi/web/public/scope.js +3 -3
- data/lib/samagotchi/web/public/session_rename.js +6 -2
- data/lib/samagotchi/web/public/session_state.js +1 -1
- data/lib/samagotchi/web/public/session_sync.js +249 -0
- data/lib/samagotchi/web/public/session_view.js +279 -0
- data/lib/samagotchi/web/public/stream_handlers.js +1 -1
- data/lib/samagotchi/web/public/tokens.css +2 -2
- data/lib/samagotchi/web/public/turn_block.js +8 -0
- data/lib/samagotchi/web/public/turn_html.js +1 -1
- data/lib/samagotchi/web/public/widget_picks.js +3 -0
- data/lib/samagotchi/web/public/working_set_view.js +1 -1
- data/lib/samagotchi/web/session_access_routes.rb +4 -15
- metadata +10 -1
|
@@ -169,6 +169,12 @@ function rowTemplate(row, { capFor }) {
|
|
|
169
169
|
row.expires ? html` · ${row.expires}` : nothing}${row.identity ? html` · <span class="pp-bound">bound to ${row.identity}</span>` : nothing}</div>${actions}</li>`;
|
|
170
170
|
}
|
|
171
171
|
|
|
172
|
+
// The Invite form's fields by what inviteBody takes. The text fields' names
|
|
173
|
+
// have no contact word in them (no_contact_fill.js): iOS Safari's AutoFill
|
|
174
|
+
// Contact bar, offered on a "name" or an email field, then stays on the
|
|
175
|
+
// page's later fields, the composer's too.
|
|
176
|
+
export const INVITE_FIELDS = { name: "chi-invitee", kind: "kind", days: "days", cap: "cap", identity: "chi-invitee-account" };
|
|
177
|
+
|
|
172
178
|
function inviteTemplate(invite, { canShare }) {
|
|
173
179
|
if (!invite) return nothing;
|
|
174
180
|
return html`<div class="pp-invite-done">
|
|
@@ -195,7 +201,7 @@ export const EMPTY_PAIR = "Nobody yet. Invite a person (or an agent) to work wit
|
|
|
195
201
|
// turns act; otherwise (a review session, an older worker) that they read.
|
|
196
202
|
// +identityHeader+: the header chi web's auth proxy names the signed-in
|
|
197
203
|
// user in (the list's identity_header), null without one: then the Invite
|
|
198
|
-
// has no
|
|
204
|
+
// has no account field (a bound link could never open).
|
|
199
205
|
export function panelTemplate(grants, { now, sessionId, invite = null, error = null, capFor = null, canShare = false,
|
|
200
206
|
busy = false, working = null, reviewing = false, identityHeader = null,
|
|
201
207
|
pair = false } = {}) {
|
|
@@ -212,11 +218,12 @@ export function panelTemplate(grants, { now, sessionId, invite = null, error = n
|
|
|
212
218
|
${working && !invite ? html`<div class="pp-warning pp-working" role="note">${working}<button type="button"
|
|
213
219
|
data-act="start-review" ?disabled=${reviewing}>${reviewing ? "Starting…" : "Start a review of it"}</button></div>` : nothing}
|
|
214
220
|
${invite ? inviteTemplate(invite, { canShare }) : html`<form class="pp-invite">
|
|
215
|
-
<div class="pp-invite-row"><input name="
|
|
221
|
+
<div class="pp-invite-row"><input name="chi-invitee" type="text" placeholder="Who (Alex)" autocomplete="off" aria-label="Who the link is for" maxlength="64"
|
|
216
222
|
><span class="select-wrap"><select name="kind" aria-label="A person or an agent"><option value="human">person</option><option value="agent">agent</option></select></span></div>
|
|
217
|
-
${identityHeader ? html`<div class="pp-invite-row"><input name="
|
|
218
|
-
autocomplete="off"
|
|
219
|
-
|
|
223
|
+
${identityHeader ? html`<div class="pp-invite-row"><input name="chi-invitee-account" type="text" inputmode="email"
|
|
224
|
+
placeholder="Their account (alex@example.com)" autocomplete="off" autocapitalize="off" spellcheck="false"
|
|
225
|
+
aria-label="Their sign-in account: the link opens only for it"></div>
|
|
226
|
+
<div class="ctx-pop-meta pp-bind-note">Bound to their account, the link opens only for them, signed in through the proxy.
|
|
220
227
|
Without one, anyone the proxy lets in who gets the link can open it.</div>` : nothing}
|
|
221
228
|
<div class="pp-invite-row"><label>Expires <span class="select-wrap"><select name="days">${EXPIRY_DAYS.map((d) => html`<option value=${d}
|
|
222
229
|
?selected=${d === DEFAULT_EXPIRY_DAYS}>${d === 1 ? "1 day" : `${d} days`}</option>`)}</select></span></label
|
|
@@ -246,7 +253,7 @@ export function createParticipantsControl({ el, session, api, onChange = () => {
|
|
|
246
253
|
// "review", the server's ReviewStart.share_terms), never guessed from the warning.
|
|
247
254
|
let inviteMode = null;
|
|
248
255
|
// The header chi web's proxy names the user in (GET …/participants), null
|
|
249
|
-
// without one: the Invite's
|
|
256
|
+
// without one: the Invite's account field.
|
|
250
257
|
let identityHeader = null;
|
|
251
258
|
// Where a participant's link opens, no token (GET …/participants
|
|
252
259
|
// link_base): a claim link's base (claimTarget).
|
|
@@ -326,7 +333,7 @@ export function createParticipantsControl({ el, session, api, onChange = () => {
|
|
|
326
333
|
}
|
|
327
334
|
|
|
328
335
|
async function submitInvite(form) {
|
|
329
|
-
const values = Object.fromEntries(
|
|
336
|
+
const values = Object.fromEntries(Object.entries(INVITE_FIELDS).map(([k, field]) => [k, form.elements[field]?.value]));
|
|
330
337
|
const { body, error: problem } = inviteBody(values);
|
|
331
338
|
if (problem) {
|
|
332
339
|
error = problem;
|
|
@@ -23,6 +23,10 @@ import { sessionHash } from "./route.js";
|
|
|
23
23
|
import { clientLabel, isOwn } from "./turn_events.js";
|
|
24
24
|
import { continueLine } from "./commands.js";
|
|
25
25
|
import { plainText } from "./plain_line.js";
|
|
26
|
+
import { noContactFill } from "./no_contact_fill.js";
|
|
27
|
+
|
|
28
|
+
// A card's text fields' name: not a contact field (no_contact_fill.js).
|
|
29
|
+
const CARD_NOTE = "chi-card-note";
|
|
26
30
|
|
|
27
31
|
// @param sessionId () => the open session's id (answers go there)
|
|
28
32
|
// @param clientId this tab's id in the session's events
|
|
@@ -175,7 +179,7 @@ export function createQuestionCards({
|
|
|
175
179
|
if (pq.allow_freeform) {
|
|
176
180
|
freeformInput = doc.createElement("input");
|
|
177
181
|
freeformInput.type = "text";
|
|
178
|
-
noContactFill(freeformInput);
|
|
182
|
+
noContactFill(freeformInput, CARD_NOTE, { prose: true });
|
|
179
183
|
freeformInput.className = "question-freeform";
|
|
180
184
|
freeformInput.placeholder = approval ? "Reason for the model (with Deny, or alone to deny)…" : "Other…";
|
|
181
185
|
card.appendChild(freeformInput);
|
|
@@ -255,15 +259,6 @@ export function createQuestionCards({
|
|
|
255
259
|
focusWhenIdle(card, pq.id, { staged });
|
|
256
260
|
}
|
|
257
261
|
|
|
258
|
-
// A card's text field isn't a contact form: what iOS Safari respects
|
|
259
|
-
// against its "AutoFill Contact" bar (no autocomplete, a name with no
|
|
260
|
-
// contact word in it). Autocorrect stays: the reader writes prose here.
|
|
261
|
-
function noContactFill(input) {
|
|
262
|
-
input.setAttribute("autocomplete", "off");
|
|
263
|
-
input.setAttribute("autocorrect", "on");
|
|
264
|
-
input.name = "chi-card-note";
|
|
265
|
-
}
|
|
266
|
-
|
|
267
262
|
function isPlainEnter(e) {
|
|
268
263
|
return e.key === "Enter" && !e.isComposing && !e.shiftKey && !e.altKey && !e.ctrlKey && !e.metaKey;
|
|
269
264
|
}
|
|
@@ -294,7 +289,7 @@ export function createQuestionCards({
|
|
|
294
289
|
function renderStepLimitActions(card, pq, options) {
|
|
295
290
|
const reason = doc.createElement("input");
|
|
296
291
|
reason.type = "text";
|
|
297
|
-
noContactFill(reason);
|
|
292
|
+
noContactFill(reason, CARD_NOTE, { prose: true });
|
|
298
293
|
reason.className = "question-freeform continue-reason";
|
|
299
294
|
reason.placeholder = CONTINUE_REASON_PLACEHOLDER;
|
|
300
295
|
const err = doc.createElement("div");
|
|
@@ -635,7 +630,7 @@ export function createQuestionCards({
|
|
|
635
630
|
no.addEventListener("click", () => answer(continueLine("no")));
|
|
636
631
|
const reason = doc.createElement("input");
|
|
637
632
|
reason.type = "text";
|
|
638
|
-
noContactFill(reason);
|
|
633
|
+
noContactFill(reason, CARD_NOTE, { prose: true });
|
|
639
634
|
reason.className = "continue-reason";
|
|
640
635
|
reason.placeholder = "Why not? (the model reads it)";
|
|
641
636
|
const noBecause = doc.createElement("button");
|
|
@@ -1,22 +1,26 @@
|
|
|
1
|
-
// A re-read of the open session (
|
|
1
|
+
// A re-read of the open session (session_sync.js resync) that could not reach chi web:
|
|
2
2
|
// the one rule for what the page does then. The history already drawn for
|
|
3
3
|
// this session stays as it is (the conversation is still right, only newer
|
|
4
4
|
// events are missing) and the info bar's status chip says the page is
|
|
5
|
-
//
|
|
5
|
+
// retrying, then, once the retries ran out, that it is offline (the full
|
|
6
|
+
// words in its tooltip); while a turn runs the stage's own line says
|
|
7
|
+
// "reconnecting…" instead (stage_stall.js) and the chip keeps the turn's word;
|
|
6
8
|
// the next re-read that succeeds clears it (the hub's next event re-reads a
|
|
7
9
|
// session left in that state: needsReread). Only a first load (select()'s
|
|
8
10
|
// "Loading…", nothing of the session drawn yet) shows the error in the
|
|
9
11
|
// history, as there is nothing to keep.
|
|
10
12
|
// Its own module: new exports go in new modules (web-frontend.md).
|
|
11
13
|
|
|
12
|
-
// The status chip's word (its class), text and tooltip per state.
|
|
14
|
+
// The status chip's word (its class), text and tooltip per state. The texts
|
|
15
|
+
// fit the room the chip keeps for its widest word (running, stopped), so the
|
|
16
|
+
// bar doesn't move while one shows.
|
|
13
17
|
export const REACH = Object.freeze({
|
|
14
18
|
reconnecting: Object.freeze({
|
|
15
|
-
status: "reconnecting", text: "
|
|
16
|
-
tip: "
|
|
19
|
+
status: "reconnecting", text: "retrying",
|
|
20
|
+
tip: "Reconnecting: can't reach chi web, trying again. The conversation shown is as it was; newer events show once it's back.",
|
|
17
21
|
}),
|
|
18
22
|
offline: Object.freeze({
|
|
19
|
-
status: "offline", text: "
|
|
23
|
+
status: "offline", text: "offline",
|
|
20
24
|
tip: "Can't reach chi web. The conversation shown is as it was; the page reads it again once chi web is back.",
|
|
21
25
|
}),
|
|
22
26
|
});
|
|
@@ -50,13 +50,13 @@ export function scopeTemplate(scope, { error = null, where = () => ({ hash: "" }
|
|
|
50
50
|
const at = where();
|
|
51
51
|
const allHref = () => allScopeHref(where().hash, scope.dir);
|
|
52
52
|
const all = html`<a class="scope-all" href=${allScopeHref(at.hash, scope.dir)} title=${"Sessions of every project"} @click=${(e) => { e.currentTarget.href = allHref(); }}>all</a>`;
|
|
53
|
-
if (error) return html`<button id="scopePick" class="scope-name error" type="button" aria-haspopup="dialog" aria-expanded="false" title=${error}>folder not found</button>${all}`;
|
|
54
|
-
if (scope.projectName) return html`<button id="scopePick" class="scope-name" type="button" aria-haspopup="dialog" aria-expanded="false" title=${`Sessions of ${scope.projectDir}`}>${scope.projectName}</button>${all}`;
|
|
53
|
+
if (error) return html`<button id="scopePick" class="scope-name error" type="button" aria-haspopup="dialog" aria-expanded="false" title=${error}><span class="scope-label">folder not found</span></button>${all}`;
|
|
54
|
+
if (scope.projectName) return html`<button id="scopePick" class="scope-name" type="button" aria-haspopup="dialog" aria-expanded="false" title=${`Sessions of ${scope.projectDir}`}><span class="scope-label">${scope.projectName}</span></button>${all}`;
|
|
55
55
|
const dir = scope.dir || scope.serverDir;
|
|
56
56
|
const backHref = () => projectScopeHref(scope.backDir, where().hash);
|
|
57
57
|
const back = scope.backName
|
|
58
58
|
? html`<a class="scope-all scope-back" href=${projectScopeHref(scope.backDir, at.hash)} title=${`Sessions of ${scope.backName} only`} @click=${(e) => { e.currentTarget.href = backHref(); }}>← ${scope.backName}</a>`
|
|
59
59
|
: nothing;
|
|
60
60
|
const newSession = dir ? html`<span class="scope-where" title=${`New sessions start in ${dir}`}>new session in<span class="path"><bdi>${dir}</bdi></span></span>` : nothing;
|
|
61
|
-
return html`<button id="scopePick" class="scope-name" type="button" aria-haspopup="dialog" aria-expanded="false" title="Sessions of every project">all projects</button>${back}${newSession}`;
|
|
61
|
+
return html`<button id="scopePick" class="scope-name" type="button" aria-haspopup="dialog" aria-expanded="false" title="Sessions of every project"><span class="scope-label">all projects</span></button>${back}${newSession}`;
|
|
62
62
|
}
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
// strip draws every card from new nodes on each session event, so an input
|
|
13
13
|
// inside a card would be thrown away mid-typing.
|
|
14
14
|
import { normalize } from "./format.js";
|
|
15
|
+
import { noContactFill } from "./no_contact_fill.js";
|
|
15
16
|
|
|
16
17
|
// As long as a title may be (TitleCommand::LIMIT).
|
|
17
18
|
const TITLE_CHARS = 80;
|
|
@@ -114,9 +115,12 @@ export function createRename({ doc = document, anchor, session, titleOf, shownTi
|
|
|
114
115
|
const el = doc.createElement("input");
|
|
115
116
|
el.type = "text";
|
|
116
117
|
el.className = "rename-input";
|
|
118
|
+
// Not a contact field (no_contact_fill.js): no contact word in its
|
|
119
|
+
// name or its wording, so "label", never "title".
|
|
120
|
+
noContactFill(el, "chi-session-label");
|
|
117
121
|
el.maxLength = TITLE_CHARS;
|
|
118
|
-
el.placeholder = normalize(shownTitle(id)) || "Session
|
|
119
|
-
el.setAttribute("aria-label", "Session
|
|
122
|
+
el.placeholder = normalize(shownTitle(id)) || "Session label";
|
|
123
|
+
el.setAttribute("aria-label", "Session label (Enter saves, empty clears, Esc cancels)");
|
|
120
124
|
el.value = titleOf(id) || "";
|
|
121
125
|
el.dataset.before = el.value;
|
|
122
126
|
el.addEventListener("keydown", (e) => {
|
|
@@ -78,7 +78,7 @@ export function emptySessionState() {
|
|
|
78
78
|
// has to start; set by the page's resync, not by the payload.
|
|
79
79
|
streamSeq: null,
|
|
80
80
|
// The stream was opened from 0 (a wake with no cursor to go on) and no
|
|
81
|
-
// new turn has started on it yet (
|
|
81
|
+
// new turn has started on it yet (session_sync.js followWokenWorker).
|
|
82
82
|
streamFromGuess: false,
|
|
83
83
|
// A re-read that couldn't reach chi web kept the drawn history
|
|
84
84
|
// (resync_reach.js): "reconnecting" while it retries, "offline" once
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
// The open session's sync with the server (split out of app.js): select()
|
|
2
|
+
// opens a session, resync() (re)renders it from GET /api/sessions/:id and
|
|
3
|
+
// streams on from the cursor that render covers, and the stream's life
|
|
4
|
+
// (startStream, workerGone, closeStream, restart). The stream handle and the
|
|
5
|
+
// re-read bookkeeping (resyncsInFlight, resyncAgain, resyncAttempts, the
|
|
6
|
+
// resync_reach.js instance) live here and nowhere else: the page reads them
|
|
7
|
+
// through hasStream() and streamLive().
|
|
8
|
+
//
|
|
9
|
+
// Everything that changes while the page runs is read through deps at the
|
|
10
|
+
// call, never captured at creation (as stream_handlers.js): the open session
|
|
11
|
+
// (store.selected), its fields (store.current), the views made after this
|
|
12
|
+
// one (the getters in +later+), the session view's hooks (+view+).
|
|
13
|
+
//
|
|
14
|
+
// deps:
|
|
15
|
+
// store the page's session store (session_store.js)
|
|
16
|
+
// historyEl, emptyEl the history and the start page's empty box
|
|
17
|
+
// getSession(id, opts), openStream(id, fromSeq, handlers, opts) data.js
|
|
18
|
+
// liveTurn, turnDom, questionCards, contextChips, participantsControl the page's views
|
|
19
|
+
// view: {forgetSession(opts), renderSessionView(data, opts), endTurnView(kind, endText, opts)}
|
|
20
|
+
// the session view (session_view.js)
|
|
21
|
+
// page: {clearNotice(), setSessionHash(id), setTurnRunning(running), setLiveStatus(status),
|
|
22
|
+
// replaceCard(id, change), addEndBubble(text)} the page's hooks
|
|
23
|
+
// later: {handlers(), composer(), focusPrompt(opts), sessionActions(), ownerClaim()}
|
|
24
|
+
// the views made after this one: the stream handlers,
|
|
25
|
+
// the composer, session_actions.js, owner_claim.js
|
|
26
|
+
//
|
|
27
|
+
// @return {select, resync, followSelectedSession, followWokenWorker, workerGone, resetTurnView, closeStream,
|
|
28
|
+
// restart, closeLive, hasStream, streamLive, startStream, retryResync}
|
|
29
|
+
// hasStream(): a stream object exists (the info bar's streaming, also while it connects);
|
|
30
|
+
// streamLive(): it delivers (its .live); restart(): close it and resync;
|
|
31
|
+
// closeLive(): close it, keeping the handle (workerGone clears it, through onStreamClosed).
|
|
32
|
+
// Its own module: new exports go in new modules (web-frontend.md).
|
|
33
|
+
|
|
34
|
+
import { fieldsFromCard } from "./session_fields.js";
|
|
35
|
+
import { hintEl } from "./bubbles.js";
|
|
36
|
+
import { withoutWorker } from "./format.js";
|
|
37
|
+
import { resyncRetry, streamDropEnd } from "./turn_events.js";
|
|
38
|
+
import { createResyncReach } from "./resync_reach.js";
|
|
39
|
+
import { keptCommandBubbles } from "./commands.js";
|
|
40
|
+
|
|
41
|
+
// +opened+ false: the stream never delivered a frame (the proxy answered
|
|
42
|
+
// 503, or the bridge refused it), so a retry waits a moment rather than
|
|
43
|
+
// spinning through resync → stream → error.
|
|
44
|
+
export const STREAM_RETRY_MS = 3000;
|
|
45
|
+
// A re-read that failed (the phone still offline, chi web a moment): try it
|
|
46
|
+
// again, backing off, and stop when the tries run out. The running turn's DOM
|
|
47
|
+
// is left alone meanwhile: a worker that still owns the turn keeps showing it running,
|
|
48
|
+
// and the hub's next event for the session is the fallback once the tries end.
|
|
49
|
+
export const RESYNC_RETRIES = 3;
|
|
50
|
+
|
|
51
|
+
export function createSessionSync(deps) {
|
|
52
|
+
const {
|
|
53
|
+
store, historyEl, emptyEl, getSession, openStream,
|
|
54
|
+
liveTurn, turnDom, questionCards, contextChips, participantsControl,
|
|
55
|
+
page, later,
|
|
56
|
+
} = deps;
|
|
57
|
+
let streamControl = null;
|
|
58
|
+
// resync() calls in flight, and whether a worker came up for the selected
|
|
59
|
+
// session while one ran (its bridge_up event): the tail runs once more.
|
|
60
|
+
let resyncsInFlight = 0;
|
|
61
|
+
let resyncAgain = false;
|
|
62
|
+
// A failed re-read keeps the drawn history and says so in the bar (resync_reach.js).
|
|
63
|
+
const resyncReach = createResyncReach({ store, historyEl, errorHint: (message) => hintEl(`Error: ${message}`) });
|
|
64
|
+
let resyncAttempts = 0;
|
|
65
|
+
|
|
66
|
+
// The selected session's card changed: its owner and, without a live
|
|
67
|
+
// stream, its status show in the info bar; a worker whose bridge is up
|
|
68
|
+
// (a turn another client sent woke one, or a replacement after a kill)
|
|
69
|
+
// gets the stream attached through one resync.
|
|
70
|
+
function followSelectedSession(sess) {
|
|
71
|
+
const streaming = !!(streamControl && streamControl.live);
|
|
72
|
+
// A Verify gate that flips (a restart brought the feature) redraws the
|
|
73
|
+
// cards' Verify fresh part: featureGates.
|
|
74
|
+
store.batch(() => {
|
|
75
|
+
store.update({ current: fieldsFromCard(sess) });
|
|
76
|
+
store.setStatus(sess.status, "hub", { streaming });
|
|
77
|
+
});
|
|
78
|
+
if (streaming || !(sess.bridge_up || resyncReach.needsReread())) return;
|
|
79
|
+
if (resyncsInFlight > 0) resyncAgain = true;
|
|
80
|
+
else resync();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function select(id) {
|
|
84
|
+
page.clearNotice();
|
|
85
|
+
const same = store.selected === id;
|
|
86
|
+
// Its synchronous part in one batch: the active card, the composer and
|
|
87
|
+
// the bar redraw once, at its end (never across the await).
|
|
88
|
+
store.batch(() => {
|
|
89
|
+
store.update({ selected: id });
|
|
90
|
+
page.setSessionHash(id);
|
|
91
|
+
historyEl.replaceChildren(hintEl("Loading…"));
|
|
92
|
+
resyncReach.loading();
|
|
93
|
+
emptyEl.classList.add("hidden");
|
|
94
|
+
resyncAttempts = 0; // this session has its own re-read budget
|
|
95
|
+
deps.view.forgetSession({ keepVerify: same });
|
|
96
|
+
contextChips.load(id);
|
|
97
|
+
participantsControl.load(id);
|
|
98
|
+
});
|
|
99
|
+
await resync();
|
|
100
|
+
// A folded composer stays folded: typing on the page opens it.
|
|
101
|
+
later.focusPrompt({ open: false });
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Clear everything that belongs to one turn's rendering.
|
|
105
|
+
function resetTurnView() {
|
|
106
|
+
closeStream();
|
|
107
|
+
// workerGone and a re-render come through here: the answer_display wait
|
|
108
|
+
// goes too.
|
|
109
|
+
liveTurn.forget();
|
|
110
|
+
questionCards.removeQuestion();
|
|
111
|
+
questionCards.forgetContinue();
|
|
112
|
+
page.setTurnRunning(false);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// @return whether another try is scheduled
|
|
116
|
+
function retryResync(id, { endText = null } = {}) {
|
|
117
|
+
if (id !== store.selected) return false;
|
|
118
|
+
const { attempt, delayMs } = resyncRetry({ attempts: resyncAttempts, max: RESYNC_RETRIES, baseMs: STREAM_RETRY_MS });
|
|
119
|
+
if (delayMs === null) return false;
|
|
120
|
+
resyncAttempts = attempt;
|
|
121
|
+
setTimeout(() => {
|
|
122
|
+
if (id !== store.selected || (streamControl && streamControl.live)) return;
|
|
123
|
+
resync({ endText });
|
|
124
|
+
}, delayMs);
|
|
125
|
+
return true;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// (Re)render the selected session from the server and stream on from the
|
|
129
|
+
// event_seq that render covers. Used on select, when the stream resets
|
|
130
|
+
// (its cursor could not be replayed) and when it dropped (workerGone).
|
|
131
|
+
// Without a live bridge there is nothing to stream: the session's next
|
|
132
|
+
// event with bridge_up (a worker another client woke) resyncs again
|
|
133
|
+
// (followSelectedSession); a bridge_up that arrived while this ran is
|
|
134
|
+
// taken by the tail. +endText+: what workerGone said about the turn the
|
|
135
|
+
// worker left unfinished; shown again after the re-render when no worker
|
|
136
|
+
// took over.
|
|
137
|
+
async function resync({ endText = null } = {}) {
|
|
138
|
+
const id = store.selected;
|
|
139
|
+
if (!id) return;
|
|
140
|
+
resyncsInFlight += 1;
|
|
141
|
+
let data;
|
|
142
|
+
try {
|
|
143
|
+
try {
|
|
144
|
+
data = await getSession(id);
|
|
145
|
+
} catch (e) {
|
|
146
|
+
if (e.status === 404) return later.sessionActions().leaveGoneSession(id, "not_found");
|
|
147
|
+
if (id === store.selected) resyncReach.failed(id, e.message, { retrying: retryResync(id, { endText }) });
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
resyncAttempts = 0;
|
|
151
|
+
if (id !== store.selected) return;
|
|
152
|
+
// An archived session opens folded: decided once per visit, from its
|
|
153
|
+
// first answer (the list may not hold it yet, or ever under ?dir).
|
|
154
|
+
later.composer().decideVisit(data.session?.archived);
|
|
155
|
+
const kept = keptCommandBubbles(historyEl, id);
|
|
156
|
+
resetTurnView();
|
|
157
|
+
deps.view.renderSessionView(data, { kept });
|
|
158
|
+
resyncReach.drawn(id);
|
|
159
|
+
later.ownerClaim().showPending();
|
|
160
|
+
// Preview is read-only: a worker is woken only by POST /turn, so attach
|
|
161
|
+
// only when a live bridge exists.
|
|
162
|
+
store.update({ current: { streamSeq: typeof data.last_event_seq === "number" ? (data.last_event_id || data.last_event_seq) : null } });
|
|
163
|
+
if (store.current.streamSeq !== null) startStream(id, store.current.streamSeq);
|
|
164
|
+
else if (endText) page.addEndBubble(endText);
|
|
165
|
+
} finally {
|
|
166
|
+
resyncsInFlight -= 1;
|
|
167
|
+
if (resyncsInFlight === 0 && resyncAgain) {
|
|
168
|
+
resyncAgain = false;
|
|
169
|
+
if (id === store.selected && !(streamControl && streamControl.live)) resync();
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// A turn or command just woke the session's worker: follow its stream if
|
|
175
|
+
// none is open, from the render's cursor. A render with none (no worker
|
|
176
|
+
// then) streams from 0, the start of a new worker's events; should that
|
|
177
|
+
// worker have been up already, turn_started says so (replaysDrawnTurn).
|
|
178
|
+
function followWokenWorker() {
|
|
179
|
+
if (streamControl?.live) return;
|
|
180
|
+
startStream(store.selected, store.current.streamSeq ?? 0);
|
|
181
|
+
store.update({ current: { streamFromGuess: store.current.streamSeq === null } });
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function startStream(id, fromSeq) {
|
|
185
|
+
store.update({ current: { streamFromGuess: false } });
|
|
186
|
+
if (streamControl) {
|
|
187
|
+
streamControl.close();
|
|
188
|
+
streamControl = null;
|
|
189
|
+
}
|
|
190
|
+
streamControl = openStream(id, fromSeq, later.handlers(), {
|
|
191
|
+
// The stream dropped or never opened: the worker left (idle exit, stop,
|
|
192
|
+
// crash) or is starting. Its cursor means nothing to the next worker
|
|
193
|
+
// (event_seq starts over), so re-read the session once one is live.
|
|
194
|
+
onStreamClosed: () => workerGone(id),
|
|
195
|
+
onStreamError: () => workerGone(id, { opened: false }),
|
|
196
|
+
});
|
|
197
|
+
store.touch("infoBar"); // streaming
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function workerGone(id, { opened = true } = {}) {
|
|
201
|
+
streamControl = null;
|
|
202
|
+
if (id !== store.selected) return;
|
|
203
|
+
// A turn that was running is over only when the worker really left: a
|
|
204
|
+
// stream that merely dropped (no stop, it was open) waits for the re-read.
|
|
205
|
+
const stopped = later.sessionActions().stoppingId() === id;
|
|
206
|
+
const { endNow, endText } = streamDropEnd({ turnRunning: liveTurn.running, stopped, opened });
|
|
207
|
+
if (endNow) deps.view.endTurnView("gone", endText, { stopped });
|
|
208
|
+
store.batch(() => {
|
|
209
|
+
if (endNow && !stopped) page.setLiveStatus("idle");
|
|
210
|
+
store.update({ current: { ...(store.current.owner === "worker" ? { owner: null } : {}), bridgeUp: false } });
|
|
211
|
+
// Its card says "live" (the list's owner, or setLiveStatus's) until the
|
|
212
|
+
// hub's event says otherwise: the worker is gone now, as far as this
|
|
213
|
+
// tab can tell.
|
|
214
|
+
if (store.sessions.find((s) => s.id === id)?.owner === "worker") page.replaceCard(id, withoutWorker);
|
|
215
|
+
store.touch("infoBar"); // streaming
|
|
216
|
+
});
|
|
217
|
+
// Once: a worker still alive with a bridge (the stream dropped, not the
|
|
218
|
+
// worker: chi web restarted) reconnects right here. Otherwise the next
|
|
219
|
+
// worker's bridge_up event brings the stream back (followSelectedSession).
|
|
220
|
+
if (opened) resync({ endText });
|
|
221
|
+
else setTimeout(() => { if (id === store.selected && !(streamControl && streamControl.live)) resync({ endText }); }, STREAM_RETRY_MS);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function closeStream() {
|
|
225
|
+
turnDom.reset();
|
|
226
|
+
if (streamControl) {
|
|
227
|
+
streamControl.close();
|
|
228
|
+
streamControl = null;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// The stream handlers' restart (a reset the cursor can't replay): close
|
|
233
|
+
// the stream and resync.
|
|
234
|
+
function restart() {
|
|
235
|
+
streamControl?.close();
|
|
236
|
+
streamControl = null;
|
|
237
|
+
resync();
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
return {
|
|
241
|
+
select, resync, followSelectedSession, followWokenWorker, workerGone, resetTurnView, closeStream, restart,
|
|
242
|
+
// session_actions.js closeLiveStream: close only, the handle stays (workerGone clears it).
|
|
243
|
+
closeLive: () => streamControl?.close(),
|
|
244
|
+
hasStream: () => !!streamControl,
|
|
245
|
+
streamLive: () => !!streamControl?.live,
|
|
246
|
+
// For the spec.
|
|
247
|
+
startStream, retryResync,
|
|
248
|
+
};
|
|
249
|
+
}
|