samagotchi 0.166.0 → 0.168.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.
Files changed (94) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +89 -1
  3. data/docs/architecture.md +1 -0
  4. data/docs/cli.md +24 -15
  5. data/docs/configuration.md +1 -0
  6. data/docs/guardrails.md +5 -5
  7. data/docs/hooks.md +4 -6
  8. data/docs/internals/bundles.md +2 -4
  9. data/docs/internals/engine.md +4 -5
  10. data/docs/internals/objectives.md +141 -9
  11. data/docs/internals/remote-sessions.md +5 -6
  12. data/docs/internals/web-frontend.md +85 -40
  13. data/docs/memory.md +1 -2
  14. data/docs/sessions.md +20 -2
  15. data/docs/testing.md +3 -3
  16. data/lib/samagotchi/bridge.rb +1 -1
  17. data/lib/samagotchi/bundle_command/installed_check.rb +2 -14
  18. data/lib/samagotchi/bundle_command.rb +35 -12
  19. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  20. data/lib/samagotchi/cli/command.rb +10 -0
  21. data/lib/samagotchi/compat.rb +1 -13
  22. data/lib/samagotchi/config.rb +3 -0
  23. data/lib/samagotchi/context_command.rb +2 -1
  24. data/lib/samagotchi/engine/objectives.rb +20 -1
  25. data/lib/samagotchi/engine/side_requests.rb +3 -2
  26. data/lib/samagotchi/engine/turn_end.rb +4 -1
  27. data/lib/samagotchi/engine.rb +3 -0
  28. data/lib/samagotchi/extension_load.rb +2 -26
  29. data/lib/samagotchi/guardrails/approvals.rb +15 -16
  30. data/lib/samagotchi/jsonl_store.rb +61 -0
  31. data/lib/samagotchi/memory_bundle/status.rb +3 -15
  32. data/lib/samagotchi/memory_bundle/system_bundle.rb +16 -10
  33. data/lib/samagotchi/memory_command.rb +4 -2
  34. data/lib/samagotchi/objectives.rb +43 -14
  35. data/lib/samagotchi/objectives_backing.rb +124 -0
  36. data/lib/samagotchi/objectives_check.rb +19 -126
  37. data/lib/samagotchi/objectives_command.rb +14 -7
  38. data/lib/samagotchi/objectives_record.rb +104 -0
  39. data/lib/samagotchi/objectives_track.rb +353 -0
  40. data/lib/samagotchi/push_command.rb +2 -1
  41. data/lib/samagotchi/remote_command.rb +2 -1
  42. data/lib/samagotchi/reply_wait/poll.rb +6 -6
  43. data/lib/samagotchi/reply_wait.rb +4 -24
  44. data/lib/samagotchi/schedule_command.rb +6 -0
  45. data/lib/samagotchi/schedules.rb +1 -1
  46. data/lib/samagotchi/session_access/remote.rb +3 -5
  47. data/lib/samagotchi/session_commands.rb +1 -1
  48. data/lib/samagotchi/sessions_command.rb +12 -6
  49. data/lib/samagotchi/share_command.rb +2 -1
  50. data/lib/samagotchi/tool_activity.rb +11 -1
  51. data/lib/samagotchi/tool_declarations.rb +5 -1
  52. data/lib/samagotchi/tools/objectives_tool.rb +19 -2
  53. data/lib/samagotchi/turn_stages/objectives.rb +46 -3
  54. data/lib/samagotchi/version.rb +1 -1
  55. data/lib/samagotchi/web/participant_access.rb +1 -1
  56. data/lib/samagotchi/web/public/app.js +52 -424
  57. data/lib/samagotchi/web/public/copy.js +2 -1
  58. data/lib/samagotchi/web/public/dock_reserve.js +12 -2
  59. data/lib/samagotchi/web/public/history_end.js +16 -0
  60. data/lib/samagotchi/web/public/index.html +74 -22
  61. data/lib/samagotchi/web/public/info_bar_model.js +3 -1
  62. data/lib/samagotchi/web/public/no_contact_fill.js +29 -0
  63. data/lib/samagotchi/web/public/objectives.css +14 -0
  64. data/lib/samagotchi/web/public/objectives_moves.js +82 -9
  65. data/lib/samagotchi/web/public/objectives_state.js +42 -0
  66. data/lib/samagotchi/web/public/objectives_strip.js +33 -9
  67. data/lib/samagotchi/web/public/objectives_track.js +52 -0
  68. data/lib/samagotchi/web/public/objectives_wiring.js +16 -1
  69. data/lib/samagotchi/web/public/participant.html +1 -1
  70. data/lib/samagotchi/web/public/participants_panel.js +14 -7
  71. data/lib/samagotchi/web/public/question_cards.js +8 -13
  72. data/lib/samagotchi/web/public/refs.js +4 -1
  73. data/lib/samagotchi/web/public/reload_check.js +5 -4
  74. data/lib/samagotchi/web/public/resync_reach.js +10 -6
  75. data/lib/samagotchi/web/public/scope.js +3 -3
  76. data/lib/samagotchi/web/public/session_rename.js +6 -2
  77. data/lib/samagotchi/web/public/session_state.js +1 -1
  78. data/lib/samagotchi/web/public/session_sync.js +249 -0
  79. data/lib/samagotchi/web/public/session_view.js +279 -0
  80. data/lib/samagotchi/web/public/stage_cards.js +20 -0
  81. data/lib/samagotchi/web/public/stage_frame.js +14 -16
  82. data/lib/samagotchi/web/public/stage_model.js +11 -4
  83. data/lib/samagotchi/web/public/stage_opened.js +229 -0
  84. data/lib/samagotchi/web/public/stage_slots.js +2 -3
  85. data/lib/samagotchi/web/public/stage_view.js +219 -147
  86. data/lib/samagotchi/web/public/stage_watch.js +8 -4
  87. data/lib/samagotchi/web/public/stream_handlers.js +1 -1
  88. data/lib/samagotchi/web/public/tokens.css +2 -2
  89. data/lib/samagotchi/web/public/turn_block.js +22 -2
  90. data/lib/samagotchi/web/public/turn_html.js +1 -1
  91. data/lib/samagotchi/web/public/widget_picks.js +3 -0
  92. data/lib/samagotchi/web/public/working_set_view.js +1 -1
  93. data/lib/samagotchi/web/session_access_routes.rb +4 -15
  94. metadata +13 -1
@@ -0,0 +1,52 @@
1
+ // The tracker on the page (pure, no DOM): ObjectivesTrack's reading of each
2
+ // objective (the view's item.track: {reading, reason, at, model, stale?}) and
3
+ // the view's tracking: {until} while one runs. Information only. A module of
4
+ // its own, not new exports of objectives_model.js or objectives_state.js:
5
+ // static JS is cached at unversioned URLs, and an existing module importing a
6
+ // new export of another existing one blanks a page with a mixed cache. See
7
+ // docs/internals/objectives.md, The tracker.
8
+ import { workerPredates } from "./worker_features.js";
9
+
10
+ // The one line both of its buttons post (ObjectivesCommand).
11
+ export const TRACK_LINE = "/objectives track";
12
+
13
+ // The worker's Bridge feature (ObjectivesTrack::FEATURE): an older worker hides Where are we?.
14
+ export const TRACK_FEATURE = "objectives_track";
15
+
16
+ // The page's objectivesTrack gate (feature_gates.js): a live worker that predates the tracker.
17
+ export function trackWorkerUnavailable(workerFeatures, bridgeUp) {
18
+ return workerPredates(workerFeatures, bridgeUp, TRACK_FEATURE);
19
+ }
20
+
21
+ const word = (reading) => (reading === "no_answer" ? "no answer" : String(reading ?? ""));
22
+
23
+ // The list's row: "tracker: no sign — nothing ran for it". null with no reading.
24
+ export function trackText(track) {
25
+ if (!track?.reading) return null;
26
+ return `tracker: ${word(track.reading)}${track.reason ? ` — ${track.reason}` : ""}`;
27
+ }
28
+
29
+ // Whether the reading disagrees with the agent's last move on it (claims done vs no
30
+ // sign): the signal to look at. Not for an objective with no move, nor no answer.
31
+ export function trackDiffers(item) {
32
+ const reading = item?.track?.reading;
33
+ const state = item?.move?.state || "progress";
34
+ return !!(item?.move && reading && reading !== "no_answer" && reading !== state);
35
+ }
36
+
37
+ // When the running read runs out, in ms; null with none. No event says so when its worker dies.
38
+ export function trackingUntil(list) {
39
+ const at = Date.parse(list?.tracking?.until);
40
+ return Number.isFinite(at) ? at : null;
41
+ }
42
+
43
+ // +list+ without a running read past its time.
44
+ export function expireTracking(list, now) {
45
+ const at = trackingUntil(list);
46
+ if (at === null || at > now) return list;
47
+ const { tracking: _gone, ...rest } = list;
48
+ return rest;
49
+ }
50
+
51
+ // Whether a read runs now.
52
+ export const tracking = (list) => trackingUntil(list) !== null;
@@ -6,6 +6,7 @@ import { stillOn } from "./latest.js";
6
6
  import { cantText } from "./format.js";
7
7
  import { createObjectivesMoves } from "./objectives_moves.js";
8
8
  import { createObjectivesStrip } from "./objectives_strip.js";
9
+ import { TRACK_LINE } from "./objectives_track.js";
9
10
 
10
11
  // @param el the strip's element
11
12
  // @param historyEl the history
@@ -17,8 +18,10 @@ import { createObjectivesStrip } from "./objectives_strip.js";
17
18
  // @param sendCommand, sendTurn data.js's
18
19
  // @param follow () follows a worker a post woke
19
20
  // @param toast (text, action, options)
21
+ // @param canTrack () the open session's worker has the tracker (feature_gates.js's objectivesTrack gate)
20
22
  // @return {seed, update, reset, redraw, notYet}
21
- export function createObjectives({ el, historyEl, session, running, holding = () => false, commands, clientId, sendCommand, sendTurn, follow, toast }) {
23
+ export function createObjectives({ el, historyEl, session, running, holding = () => false, commands, clientId, sendCommand, sendTurn, follow, toast,
24
+ canTrack = () => false }) {
22
25
  const posted = async (request) => {
23
26
  const still = stillOn(session);
24
27
  await request(session());
@@ -34,13 +37,25 @@ export function createObjectives({ el, historyEl, session, running, holding = ()
34
37
  sendMessage: (text) => posted((id) => sendTurn(id, text, { clientId: `${clientId}:objectives`, history: false })),
35
38
  failed: told("edit the objectives"),
36
39
  onChange: () => moves.decorate(),
40
+ canTrack,
37
41
  });
38
42
  const moves = createObjectivesMoves({
39
43
  historyEl, notYet: (id) => strip.notYet(id),
44
+ // The view's move is the newest: not while a turn runs or one is held in the
45
+ // stage, whose move the history doesn't have yet. ?.: a cached older strip.
46
+ latestMove: (id) => (running() || holding() ? null : strip.moveOf?.(id) ?? null),
47
+ // The history's newest block is the newest turn's only then (canShorten's rule).
48
+ canMarkNoMove: () => !running() && !holding() && !!strip.hasActive?.(),
40
49
  // Not during a turn: its answer isn't there yet, and /short refuses it. Nor
41
50
  // with a turn still in the stage: the history's last answer isn't the newest,
42
51
  // which is what /short reads. The hand-off fills the history, which redraws this.
43
52
  canShorten: () => strip.hasList() && !running() && !holding() && (commands() || []).some((c) => c?.name === "/short"),
53
+ canTrack,
54
+ // As a strip tap: no echo; the card is the answer. false: a failure, already told.
55
+ track: () => posted((id) => sendCommand(id, TRACK_LINE, { clientId, card: true })).then(() => true, (e) => {
56
+ told("ask where the objectives stand")(e);
57
+ return false;
58
+ }),
44
59
  // false: a failure, already told: the button comes back.
45
60
  shorten: () => posted((id) => sendCommand(id, "/short", { clientId, card: true })).then(() => true, (e) => {
46
61
  told("ask for it")(e);
@@ -193,7 +193,7 @@ button.small{font-size:12px;padding:2px 8px}
193
193
  <div class="p-hint composer-line" id="hint">⏎ sends, ⇧⏎ a new line, ↑ an earlier comment. The model answers in a read-only turn; the owner sees everything.</div>
194
194
  <div class="compose-col">
195
195
  <div id="chips" hidden></div>
196
- <textarea id="comment" rows="1" placeholder="Comment or ask" aria-label="Comment or ask"></textarea>
196
+ <textarea id="comment" name="chi-comment" autocomplete="off" rows="1" placeholder="Comment or ask" aria-label="Comment or ask"></textarea>
197
197
  </div>
198
198
  <div class="actions-col">
199
199
  <button type="button" id="attachBtn" class="attach-btn" title="Add images" aria-label="Add images" hidden></button>
@@ -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 email field (a bound link could never open).
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="name" type="text" placeholder="Name (Alex)" autocomplete="off" aria-label="Their name" maxlength="64"
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="identity" type="email" placeholder="Their email (alex@example.com)"
218
- autocomplete="off" aria-label="Their email: the link opens only for that account"></div>
219
- <div class="ctx-pop-meta pp-bind-note">With their email the link opens only for them, signed in through the proxy.
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 email field.
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(["name", "kind", "days", "cap", "identity"].map((k) => [k, form.elements[k]?.value]));
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
@@ -91,7 +95,7 @@ export function createQuestionCards({
91
95
  const card = doc.createElement("details");
92
96
  card.className = approval ? "bubble question approval" : stepLimit ? "bubble question step-limit" : "bubble question";
93
97
  card.dataset.qid = pq.id;
94
- // What asks (the stage's question room is a model's own question's,
98
+ // What asks (a model's own question opens its turn in the history,
95
99
  // stage_view.js): the kind, and a delegate's question relayed here.
96
100
  card.dataset.kind = pq.kind || "question";
97
101
  if (relayView(pq)) card.dataset.relay = "1";
@@ -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");
@@ -381,8 +381,11 @@ export function turnRowFor(target) {
381
381
  // history). null when there is none.
382
382
  function turnBlockOf(el) {
383
383
  const own = el.closest(".turn-work, .turn-stage");
384
- if (own) return own;
385
384
  const doc = el.ownerDocument;
385
+ // A turn opened in the history (stage_view.js): its block is the
386
+ // history's last one, the stage's rows are that turn's.
387
+ if (own?.dataset.block === "history") return [...doc.querySelectorAll("#history .turn-work")].at(-1) || null;
388
+ if (own) return own;
386
389
  const block = [...doc.querySelectorAll(".turn-work")].filter((b) => precedes(b, el)).at(-1);
387
390
  if (!block) return null;
388
391
  const prompt = [...doc.querySelectorAll(".bubble.user")].some((u) => precedes(block, u) && precedes(u, el));
@@ -13,9 +13,10 @@
13
13
  // fallback, data-undrawn): 0 unless chi web missed one. Fire-and-forget: no toast, no
14
14
  // store write, a failure is dropped.
15
15
  //
16
- // Cards are left out on both sides: a reload places them after the render
17
- // (CardStore's stamps, cards_place.js), which the offscreen render doesn't
18
- // run; the e2e reload checks compare them.
16
+ // Cards and answered question cards are left out on both sides: a reload
17
+ // places them after the render (CardStore's stamps and the snapshot's
18
+ // questions, cards_place.js placeResolvedQuestion), which the offscreen
19
+ // render doesn't run; the e2e reload checks compare them.
19
20
  import { compareShapes, historyShape } from "./history_shape.js";
20
21
  import { turnElements } from "./turn_range.js";
21
22
 
@@ -29,7 +30,7 @@ function openingId(el) {
29
30
  }
30
31
 
31
32
  function withoutCards(shape) {
32
- return shape.filter((item) => item.kind !== "card");
33
+ return shape.filter((item) => item.kind !== "card" && item.kind !== "question");
33
34
  }
34
35
 
35
36
  // @param enabled () => whether the check is on (the body's attribute)
@@ -1,22 +1,26 @@
1
- // A re-read of the open session (app.js resync) that could not reach chi web:
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
- // reconnecting, then, once the retries ran out, that it can't reach chi web;
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: "reconnecting…",
16
- tip: "Can't reach chi web: trying again. The conversation shown is as it was; newer events show once it's back.",
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: "can't reach chi web",
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 title";
119
- el.setAttribute("aria-label", "Session title (Enter saves, empty clears, Esc cancels)");
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 (app.js followWokenWorker).
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
+ }