samagotchi 0.177.0 → 0.178.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 (88) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +44 -1
  3. data/docs/architecture.md +5 -4
  4. data/docs/cli.md +31 -6
  5. data/docs/guardrails.md +1 -1
  6. data/docs/internals/background-tasks.md +23 -2
  7. data/docs/internals/bridge.md +17 -6
  8. data/docs/internals/bundles.md +4 -3
  9. data/docs/internals/participants.md +8 -5
  10. data/docs/internals/remote-sessions.md +6 -1
  11. data/docs/internals/session-lifecycle.md +176 -0
  12. data/docs/internals/web-frontend.md +14 -6
  13. data/docs/internals/working-set.md +33 -6
  14. data/docs/plugins.md +1 -1
  15. data/docs/releasing.md +3 -2
  16. data/docs/scheduling.md +8 -1
  17. data/docs/sessions.md +15 -9
  18. data/docs/testing.md +4 -2
  19. data/lib/samagotchi/bridge/card_store.rb +2 -19
  20. data/lib/samagotchi/bridge.rb +38 -6
  21. data/lib/samagotchi/bundle_command/check.rb +1 -1
  22. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  23. data/lib/samagotchi/compat.rb +0 -7
  24. data/lib/samagotchi/engine/events.rb +43 -0
  25. data/lib/samagotchi/engine/session.rb +7 -0
  26. data/lib/samagotchi/engine.rb +9 -3
  27. data/lib/samagotchi/event_fanout.rb +56 -0
  28. data/lib/samagotchi/guardrails/approvals.rb +0 -4
  29. data/lib/samagotchi/memory_bundle/shipped_update.rb +1 -1
  30. data/lib/samagotchi/note_delivery.rb +9 -4
  31. data/lib/samagotchi/plugin/sessions.rb +2 -1
  32. data/lib/samagotchi/revise_anchor.rb +2 -0
  33. data/lib/samagotchi/schedules.rb +12 -5
  34. data/lib/samagotchi/session_access/contract.rb +4 -0
  35. data/lib/samagotchi/session_access/local.rb +16 -4
  36. data/lib/samagotchi/session_access/remote.rb +42 -9
  37. data/lib/samagotchi/session_archive_command.rb +38 -10
  38. data/lib/samagotchi/session_chain/delete.rb +98 -25
  39. data/lib/samagotchi/session_chain/delete_preview.rb +2 -2
  40. data/lib/samagotchi/session_delete_command.rb +33 -10
  41. data/lib/samagotchi/session_inbox.rb +29 -0
  42. data/lib/samagotchi/session_inbox_delivery.rb +13 -5
  43. data/lib/samagotchi/session_lifecycle/allowed.rb +69 -0
  44. data/lib/samagotchi/session_lifecycle/canonical.rb +49 -0
  45. data/lib/samagotchi/session_lifecycle/reading.rb +65 -0
  46. data/lib/samagotchi/session_lifecycle.rb +59 -0
  47. data/lib/samagotchi/session_manager/delivery.rb +29 -6
  48. data/lib/samagotchi/session_manager/lifecycle.rb +33 -39
  49. data/lib/samagotchi/session_manager/removal.rb +117 -25
  50. data/lib/samagotchi/session_manager/running_tasks.rb +334 -0
  51. data/lib/samagotchi/session_manager/spawn.rb +2 -2
  52. data/lib/samagotchi/sessions_command.rb +1 -1
  53. data/lib/samagotchi/system_prompt.rb +22 -2
  54. data/lib/samagotchi/task_files.rb +37 -4
  55. data/lib/samagotchi/terminal_ui/attached_loop/exit_commands.rb +7 -1
  56. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  57. data/lib/samagotchi/terminal_ui/local_link.rb +11 -3
  58. data/lib/samagotchi/tool_names.rb +1 -1
  59. data/lib/samagotchi/tools/memory.rb +29 -0
  60. data/lib/samagotchi/tools/task_runtime.rb +25 -6
  61. data/lib/samagotchi/turn_anchors.rb +5 -0
  62. data/lib/samagotchi/verify_anchor.rb +2 -0
  63. data/lib/samagotchi/version.rb +1 -1
  64. data/lib/samagotchi/web/app.rb +5 -1
  65. data/lib/samagotchi/web/participant_show.rb +3 -4
  66. data/lib/samagotchi/web/participant_view.rb +4 -6
  67. data/lib/samagotchi/web/public/data.js +19 -3
  68. data/lib/samagotchi/web/public/delete_sheet.js +67 -11
  69. data/lib/samagotchi/web/public/running_tasks.js +73 -0
  70. data/lib/samagotchi/web/public/session_actions.js +57 -8
  71. data/lib/samagotchi/web/public/stop_sheet.js +3 -2
  72. data/lib/samagotchi/web/public/working_set.js +3 -28
  73. data/lib/samagotchi/web/public/working_set_view.js +5 -2
  74. data/lib/samagotchi/web/public/ws_item_sig.js +51 -0
  75. data/lib/samagotchi/web/public/ws_peek.js +23 -13
  76. data/lib/samagotchi/web/public/ws_reader.js +22 -12
  77. data/lib/samagotchi/web/public/ws_sections.js +1 -0
  78. data/lib/samagotchi/web/public/ws_timeline.js +9 -6
  79. data/lib/samagotchi/web/session_control.rb +66 -16
  80. data/lib/samagotchi/web/session_summary.rb +7 -0
  81. data/lib/samagotchi/web/working_set_routes.rb +29 -8
  82. data/lib/samagotchi/worker_boot.rb +9 -6
  83. data/lib/samagotchi/worker_link.rb +9 -1
  84. data/lib/samagotchi/worker_presence.rb +4 -0
  85. data/lib/samagotchi/working_set.rb +26 -0
  86. data/lib/samagotchi/working_set_command.rb +10 -7
  87. data/lib/samagotchi/working_set_steer.rb +3 -10
  88. metadata +9 -1
@@ -0,0 +1,73 @@
1
+ // A session's background tasks a delete or an archive was refused for
2
+ // (the 409 tasks_running, SessionManager::RunningTasks), in the page's
3
+ // words: their one line, the second confirm, the toast's suffix after a
4
+ // stop. DOM-free (no lit-html): format.js-style text helpers, a module of
5
+ // their own (docs/internals/web-frontend.md, "New exports go in new modules").
6
+ // session_actions.js asks the confirm; delete_sheet.js' refusal view and
7
+ // stop_sheet.js' cut share NAMED_MAX and cutCommand.
8
+
9
+ // At most this many tasks (or holds of a kind) named in a line; the rest
10
+ // are one "+N more" (stop_sheet.js MAX_NAMED, RunningTasks::MAX_NAMED).
11
+ export const NAMED_MAX = 3;
12
+
13
+ // A command (a task's, a hold's label) cut short to fit a phone line
14
+ // (RunningTasks::COMMAND_CHARS).
15
+ export function cutCommand(label) {
16
+ return label.length > 42 ? `${label.slice(0, 42)}…` : label;
17
+ }
18
+
19
+ // The background tasks a delete or an archive was refused for (the 409
20
+ // tasks_running's tasks: {running, unverified, unreadable}, each
21
+ // [{session_id, id, command}]; a plain array reads as running), as one line:
22
+ // "npm run dev · rspec", at most NAMED_MAX named then "+N more". A task of
23
+ // another session than +sessionId+ (a delegate's, another link's) carries
24
+ // its short id ("9d0e1f2a: rspec"); one chi can't verify or read is named by
25
+ // its id. SessionManager::RunningTasks.words is the CLI's twin.
26
+ export function tasksLine(listing, sessionId = null) {
27
+ const names = taskEntries(listing).map(({ task, kind }) => {
28
+ const hex = String(task?.id ?? "").split("-").pop().slice(0, 8);
29
+ let name;
30
+ if (kind === "unverified") name = `task ${hex} (may still be running)`;
31
+ else if (kind === "unreadable") name = `task ${hex} (record unreadable)`;
32
+ else name = String(task?.command ?? "").trim() ? cutCommand(String(task.command).trim()) : `task ${hex}`;
33
+ const owner = String(task?.session_id ?? "");
34
+ return sessionId && owner && owner !== sessionId ? `${owner.slice(0, 8)}: ${name}` : name;
35
+ });
36
+ const more = names.length - NAMED_MAX;
37
+ return `${names.slice(0, NAMED_MAX).join(" · ")}${more > 0 ? ` +${more} more` : ""}`;
38
+ }
39
+
40
+ // How many tasks +listing+ (as tasksLine's) holds.
41
+ export function tasksCount(listing) {
42
+ return taskEntries(listing).length;
43
+ }
44
+
45
+ function taskEntries(listing) {
46
+ if (Array.isArray(listing)) return listing.map((task) => ({ task, kind: "running" }));
47
+ return ["running", "unverified", "unreadable"].flatMap((kind) =>
48
+ (Array.isArray(listing?.[kind]) ? listing[kind] : []).map((task) => ({ task, kind })));
49
+ }
50
+
51
+ // The second confirm of a delete or an archive refused for background tasks
52
+ // still running (409 tasks_running): which, and whether to stop them and
53
+ // +verb+ ("delete" / "archive") the session. +listing+ is the 409's tasks.
54
+ export function tasksConfirmText(id, listing, verb) {
55
+ const n = tasksCount(listing);
56
+ const one = n === 1;
57
+ return [
58
+ `Session ${String(id).slice(0, 8)} started ${n} background task${one ? "" : "s"} that ${one ? "is" : "are"} still running:`,
59
+ tasksLine(listing, id),
60
+ `Stop ${one ? "it" : "them"} and ${verb} the session?`,
61
+ ].join("\n");
62
+ }
63
+
64
+ // What a delete's or an archive's toast adds for the tasks it stopped (its
65
+ // 200's tasks_stopped / tasks_not_stopped): " · stopped 2 background tasks",
66
+ // " · 1 not stopped: npm run dev"; "" when it stopped none.
67
+ export function tasksStoppedSuffix(result) {
68
+ const stopped = (result?.tasks_stopped || []).length;
69
+ const left = result?.tasks_not_stopped || [];
70
+ let text = stopped ? ` · stopped ${stopped} background task${stopped === 1 ? "" : "s"}` : "";
71
+ if (left.length) text += ` · ${left.length} not stopped: ${tasksLine(left, result?.session_id ?? null)}`;
72
+ return text;
73
+ }
@@ -1,5 +1,6 @@
1
1
  import { continueRefusal, continuedText, openChildrenTemplate, openerText } from "./chains.js";
2
2
  import { cantText, deleteConfirmText, goneSessionNotice } from "./format.js";
3
+ import { tasksConfirmText, tasksCount, tasksStoppedSuffix } from "./running_tasks.js";
3
4
  import { sessionHash } from "./route.js";
4
5
  import { inTree } from "./sessions_list.js";
5
6
  import { isChained, listAfterDelete, deleteToast, runDeleteFlow } from "./delete_sheet.js";
@@ -84,23 +85,55 @@ export function createSessionActions({
84
85
  if (gone.has(selected())) clearSelection();
85
86
  if (!eventsLive()) refresh();
86
87
  const { text, back } = deleteToast(which, result, plan, id);
87
- toast(text, back ? { label: `Open ${back.slice(0, 8)}`, run: () => select(back) } : null);
88
+ toast(`${text}${tasksStoppedSuffix(result)}`, back ? { label: `Open ${back.slice(0, 8)}`, run: () => select(back) } : null);
88
89
  }
89
90
 
90
- // Today's confirm: a session in no chain.
91
+ // Today's confirm: a session in no chain. A session whose background
92
+ // tasks still run is refused (409 tasks_running, nothing deleted): a
93
+ // second confirm names them, and OK sends the delete again with
94
+ // stopTasks (they are stopped, then the session goes).
91
95
  async function plainDelete(id, sess) {
92
96
  if (!confirm(deleteConfirmText(sess))) return;
93
97
  try {
94
98
  await api.deleteSession(id);
95
99
  } catch (e) {
96
- alert(`Could not delete session ${id.slice(0, 8)}: ${e.message}`);
97
- if (!eventsLive()) refresh();
100
+ if (e.code === "tasks_running") { await deleteStoppingTasks(id, e.body?.tasks); return; }
101
+ deleteFailed(id, e);
98
102
  return;
99
103
  }
104
+ dropDeleted(id);
105
+ }
106
+
107
+ async function deleteStoppingTasks(id, listing) {
108
+ if (!confirm(tasksConfirmText(id, listing, "delete"))) return;
109
+ toast(stoppingText(listing));
110
+ let result;
111
+ try {
112
+ result = await api.deleteSession(id, { stopTasks: true });
113
+ } catch (e) {
114
+ deleteFailed(id, e);
115
+ return;
116
+ }
117
+ dropDeleted(id);
118
+ toast(`Deleted ${id.slice(0, 8)}${tasksStoppedSuffix(result)}`);
119
+ }
120
+
121
+ function deleteFailed(id, e) {
122
+ alert(`Could not delete session ${id.slice(0, 8)}: ${e.message}`);
123
+ if (!eventsLive()) refresh();
124
+ }
125
+
126
+ function dropDeleted(id) {
100
127
  setSessions(sessions().filter((s) => s.id !== id));
101
128
  if (selected() === id) clearSelection();
102
129
  }
103
130
 
131
+ // The toast while a delete or an archive stops the tasks (about 4 s at most).
132
+ function stoppingText(listing) {
133
+ const n = tasksCount(listing);
134
+ return `Stopping ${n} background task${n === 1 ? "" : "s"}…`;
135
+ }
136
+
104
137
  // The open session no longer exists: back to the start page, saying why.
105
138
  function leaveGoneSession(id, why) {
106
139
  if (selected() !== id) return;
@@ -248,15 +281,20 @@ export function createSessionActions({
248
281
  // and a batch share. The ids in the answer flip in the list at once. When
249
282
  // the open session's worker was stopped (it, or a delegate of the archived
250
283
  // one), its stream ending is a stop, not a lost worker.
284
+ // +stopTasks+: the archive stops the background tasks the tree started
285
+ // first (else a session whose tasks still run is refused: 409
286
+ // tasks_running; a batch passes nothing, and skips it with that reason).
251
287
  // @return {ok: true, result} | {ok: false, error}
252
- async function archiveOne(id, archive) {
288
+ async function archiveOne(id, archive, { stopTasks = false } = {}) {
253
289
  // A live worker in the tree is stopped by the archive: the open
254
290
  // session's stream ending then is a stop.
255
291
  const open = selected();
256
292
  const mine = archive && open && inTree(sessions(), id, open) ? open : null;
257
293
  if (mine) stoppingId = mine;
258
294
  try {
259
- const result = archive ? await api.archiveSession(id) : await api.unarchiveSession(id);
295
+ const result = archive
296
+ ? await api.archiveSession(id, ...(stopTasks ? [{ stopTasks: true }] : []))
297
+ : await api.unarchiveSession(id);
260
298
  markArchived(archive ? result.archived : result.unarchived, archive);
261
299
  if (mine && mine === selected() && (result.stopped || []).includes(mine)) stoppedWorker(mine);
262
300
  return { ok: true, result };
@@ -268,9 +306,20 @@ export function createSessionActions({
268
306
  }
269
307
  }
270
308
 
309
+ // No confirm, unless background tasks the tree started still run (409
310
+ // tasks_running): then the confirm names them, and OK archives again with
311
+ // stopTasks. Undo only unarchives: stopped tasks stay stopped.
271
312
  async function setArchived(id, archive, { undo = true } = {}) {
272
313
  const short = id.slice(0, 8);
273
- const answer = await archiveOne(id, archive);
314
+ let answer = await archiveOne(id, archive);
315
+ let suffix = "";
316
+ if (!answer.ok && archive && answer.error?.code === "tasks_running") {
317
+ const listing = answer.error.body?.tasks;
318
+ if (!confirm(tasksConfirmText(id, listing, "archive"))) return;
319
+ toast(stoppingText(listing));
320
+ answer = await archiveOne(id, true, { stopTasks: true });
321
+ if (answer.ok) suffix = tasksStoppedSuffix(answer.result);
322
+ }
274
323
  if (!answer.ok) {
275
324
  alert(`Could not ${archive ? "archive" : "unarchive"} session ${short}: ${answer.error.message}`);
276
325
  return;
@@ -278,7 +327,7 @@ export function createSessionActions({
278
327
  // markArchived's list redrew the lists and the bar already.
279
328
  if (!eventsLive()) refresh();
280
329
  const what = archive ? "Archived" : "Unarchived";
281
- toast(`${what} ${short}`, undo ? { label: "Undo", run: () => setArchived(id, !archive, { undo: false }) } : null);
330
+ toast(`${what} ${short}${suffix}`, undo ? { label: "Undo", run: () => setArchived(id, !archive, { undo: false }) } : null);
282
331
  }
283
332
 
284
333
  // The info bar's Archive / Unarchive: the open session's, by its state.
@@ -16,9 +16,10 @@
16
16
 
17
17
  import { html, nothing, render } from "./vendor/lit-html.js";
18
18
  import { createChipPopover } from "./chip_popover.js";
19
+ import { cutCommand, NAMED_MAX } from "./running_tasks.js";
19
20
 
20
21
  // At most this many of a kind named in the sheet; the rest are one "+N more".
21
- export const MAX_NAMED = 3;
22
+ export const MAX_NAMED = NAMED_MAX;
22
23
 
23
24
  // The Stop button the sheet opens at.
24
25
  export const STOP_ANCHOR = "#infoStopBtn";
@@ -35,7 +36,7 @@ const KIND_WORDS = {
35
36
  function itemWords(item, kind) {
36
37
  const label = String(item?.label ?? item?.id ?? "").trim();
37
38
  const detail = String(item?.detail ?? "").trim();
38
- const cut = label.length > 42 ? `${label.slice(0, 42)}…` : label;
39
+ const cut = cutCommand(label);
39
40
  if (kind === "delegates") {
40
41
  const id = String(item?.id ?? "").slice(0, 8);
41
42
  return `${id} "${cut || "untitled"}"${detail ? ` ${detail}` : ""}`;
@@ -23,6 +23,8 @@
23
23
  // until the next turn sends its note (the server's adds). Pins show only
24
24
  // under a strategy with the forget layer (forgetOn).
25
25
 
26
+ import { ITEM_STATES, serverIndex, serverItem } from "./ws_item_sig.js";
27
+
26
28
  export const FLASH_MS = 4000;
27
29
  // Labels per form: the rail's four lines, the row's and the footprint's
28
30
  // three, the collapsed head's newest one.
@@ -197,34 +199,7 @@ export function sessionItems({ turns = [], live = [], preloaded = [], notes = []
197
199
 
198
200
  // ── the server's truth ────────────────────────────────────────────────────
199
201
 
200
- export const STATES = Object.freeze(["live", "stale", "forgotten", "dropped"]);
201
- const ELLIPSIS = "\u2026";
202
-
203
- // The server's items by "kind:key", and its URLs (a cut row key matches one
204
- // by prefix).
205
- function serverIndex(server) {
206
- const byKey = new Map();
207
- const urls = [];
208
- for (const it of server?.items || []) {
209
- if (!it || !STATES.includes(it.state)) continue;
210
- byKey.set(`${it.kind}:${it.key}`, it);
211
- if (it.kind === "url") urls.push(it);
212
- }
213
- return { byKey, urls };
214
- }
215
-
216
- // The server's item for +item+: files by absolute path (a title fallback
217
- // won't match), memories by name, URLs by the row's key (its params
218
- // preview: cut at 80 characters with a "…", whose head must start the
219
- // server's URL). null when the server doesn't know it (a running call).
220
- function serverItem(index, item) {
221
- const exact = index.byKey.get(`${item.kind}:${item.key}`);
222
- if (exact || item.kind !== "url") return exact || null;
223
- const key = String(item.key);
224
- if (!key.endsWith(ELLIPSIS)) return null;
225
- const head = key.slice(0, -1);
226
- return index.urls.find((it) => String(it.key).startsWith(head)) || null;
227
- }
202
+ export const STATES = ITEM_STATES;
228
203
 
229
204
  // +items+ with the server's state, tokens, pinned, hasDrop (its
230
205
  // has_drop: some output holds the user's drop) and a memory's scope (the
@@ -52,6 +52,7 @@ import {
52
52
  labelTitle, lensItem, newerSnapshot, opsText, overlay, parseSteerLine, pendingSteers, pinnable, refreshable, serverAddIds, sessionItems, STEER_OPS,
53
53
  steerId, steerLine, stepRange, stepTag, tokensText, turnLens, undroppable,
54
54
  } from "./working_set.js";
55
+ import { serverSig } from "./ws_item_sig.js";
55
56
 
56
57
  // The popover's files fold to this many lines (groups open in place, one at
57
58
  // a time), its memories past this many to one group.
@@ -626,8 +627,8 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
626
627
  changed();
627
628
  refreshFootprints();
628
629
  for (const fn of listeners) fn();
629
- // An open peek asks again on an event (a GET answers the open itself):
630
- // the route builds from the messages.
630
+ // An open peek asks again on an event (a GET answers the open itself),
631
+ // when its item's server signature changed (ws_peek.js refresh).
631
632
  if (how?.event && popover.isOpen()) peek?.refresh();
632
633
  }
633
634
 
@@ -765,6 +766,8 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
765
766
  jump,
766
767
  // The session's set as the list shows it (overlaid), for the reader.
767
768
  items: () => sessionSet().items,
769
+ // +item+'s server signature (working_set.js serverSig), for the peek and the reader.
770
+ serverSig: (item) => serverSig(server, item),
768
771
  // The list opened at the session bar's chip (the reader's ‹ Set).
769
772
  openList() {
770
773
  const chip = infoEl.querySelector(".ws-chip");
@@ -0,0 +1,51 @@
1
+ // When the working set's peek and reader ask the item route again: the
2
+ // server's item for a page row (its signature), and which of two answers
3
+ // is the newer. A module of its own (docs/internals/web-frontend.md, "New
4
+ // exports go in new modules"); working_set.js matches rows with it too.
5
+
6
+ // The states the server's items carry (working_set.js STATES).
7
+ export const ITEM_STATES = Object.freeze(["live", "stale", "forgotten", "dropped"]);
8
+ const ELLIPSIS = "…";
9
+
10
+ // The server's items by "kind:key", and its URLs (a cut row key matches one
11
+ // by prefix).
12
+ export function serverIndex(server) {
13
+ const byKey = new Map();
14
+ const urls = [];
15
+ for (const it of server?.items || []) {
16
+ if (!it || !ITEM_STATES.includes(it.state)) continue;
17
+ byKey.set(`${it.kind}:${it.key}`, it);
18
+ if (it.kind === "url") urls.push(it);
19
+ }
20
+ return { byKey, urls };
21
+ }
22
+
23
+ // The server's item for +item+: files by absolute path (a title fallback
24
+ // won't match), memories by name, URLs by the row's key (its params
25
+ // preview: cut at 80 characters with a "…", whose head must start the
26
+ // server's URL). null when the server doesn't know it (a running call).
27
+ export function serverItem(index, item) {
28
+ const exact = index.byKey.get(`${item.kind}:${item.key}`);
29
+ if (exact || item.kind !== "url") return exact || null;
30
+ const key = String(item.key);
31
+ if (!key.endsWith(ELLIPSIS)) return null;
32
+ const head = key.slice(0, -1);
33
+ return index.urls.find((it) => String(it.key).startsWith(head)) || null;
34
+ }
35
+
36
+ // The signature of +item+'s server item (count, ops, tokens, state,
37
+ // has_drop, pinned: a new run of it raises count), null when the server
38
+ // doesn't know it (+server+: a snapshot {items, at}, or null). The peek and
39
+ // the reader ask the item route again only when it changed.
40
+ export function serverSig(server, item) {
41
+ const found = item && server ? serverItem(serverIndex(server), item) : null;
42
+ return found ? JSON.stringify([found.count, found.ops, found.tokens, found.state, found.has_drop, found.pinned]) : null;
43
+ }
44
+
45
+ // Whether the item route's +answer+ is older than the +kept+ one: both
46
+ // from the same running turn (its turn_id) and built from a shorter
47
+ // conversation (at). Its at may go down otherwise (a turn's end keeps
48
+ // less), so a running → idle answer is always taken.
49
+ export function olderAnswer(kept, answer) {
50
+ return !!(kept?.running && answer?.running && kept.turn_id && kept.turn_id === answer.turn_id && Number(answer.at) < Number(kept.at));
51
+ }
@@ -6,28 +6,35 @@
6
6
  // One row at a time. The owner's only: working_set_view.js gets none for a
7
7
  // participant (the null-control idiom) and draws today's rows.
8
8
  //
9
- // The item's timeline comes from the item route (+getItem+); an answer for
10
- // a row no longer open, or another session, is dropped (latest.js). While a
11
- // row is open, each new server snapshot asks again (refresh): the route
12
- // builds from the session's messages, which lag a running turn.
9
+ // The item's peek comes from the item route (+getItem+, latest: only the
10
+ // events peekOf picks and the counts; an older worker's whole timeline
11
+ // draws the same); an answer for a row no longer open, or another session,
12
+ // is dropped (latest.js), and so is one older than the drawn one within a
13
+ // running turn (olderAnswer). While a row is open, a new server snapshot
14
+ // asks again (refresh) only when the item's server signature changed
15
+ // (+sigOf+: working_set.js serverSig): mid-turn the route answers the
16
+ // running turn's view as of its last step.
13
17
 
14
18
  import { html, nothing } from "./vendor/lit-html.js";
15
19
  import { createLatest } from "./latest.js";
16
20
  import { diffCounts, diffTemplate } from "./diff_view.js";
17
21
  import { callTemplate, linesTemplate, textTemplate } from "./ws_cards.js";
18
22
  import { countsText, eventTag, eventWords, peekOf } from "./ws_timeline.js";
23
+ import { olderAnswer } from "./ws_item_sig.js";
19
24
 
20
25
  // The popover's width while a row is peeked (it is 420 otherwise).
21
26
  export const PEEK_WIDTH = 520;
22
27
 
23
- // +session()+: the open session's id; +getItem(id, kind, key)+: the item
24
- // route's answer; +onChange()+: the peek's content changed (the popover
25
- // redraws and places itself again).
26
- export function createPeek({ session, getItem, onChange = () => {} }) {
28
+ // +session()+: the open session's id; +getItem(id, kind, key, opts)+: the item
29
+ // route's answer; +sigOf(item)+: its server signature (undefined: always ask
30
+ // again); +onChange()+: the peek's content changed (the popover redraws and
31
+ // places itself again).
32
+ export function createPeek({ session, getItem, sigOf = () => undefined, onChange = () => {} }) {
27
33
  let openId = null;
28
34
  let item = null;
29
35
  let data = null;
30
36
  let failed = false;
37
+ let askedSig;
31
38
  const latest = createLatest(() => `${session()}|${openId}`);
32
39
 
33
40
  function load() {
@@ -35,10 +42,11 @@ export function createPeek({ session, getItem, onChange = () => {} }) {
35
42
  if (!id || !item) return;
36
43
  const fresh = latest.begin();
37
44
  const { kind, key } = item;
45
+ askedSig = sigOf(item);
38
46
  Promise.resolve()
39
- .then(() => getItem(id, kind, key))
47
+ .then(() => getItem(id, kind, key, { latest: true }))
40
48
  .then((answer) => {
41
- if (!fresh()) return;
49
+ if (!fresh() || olderAnswer(data, answer)) return;
42
50
  data = answer;
43
51
  failed = false;
44
52
  onChange();
@@ -74,11 +82,13 @@ export function createPeek({ session, getItem, onChange = () => {} }) {
74
82
  isOpen: (id) => openId === id,
75
83
  any: () => openId !== null,
76
84
  close,
77
- // A new server snapshot: the open row's timeline asked again (its
78
- // drawn one stays until the answer).
85
+ // A new server snapshot: the open row's timeline asked again when its
86
+ // server signature changed (its drawn one stays until the answer).
79
87
  refresh(row = item) {
80
88
  if (!openId) return;
81
89
  item = row || item;
90
+ const sig = sigOf(item);
91
+ if (!failed && sig !== undefined && sig === askedSig) return;
82
92
  load();
83
93
  },
84
94
  // The peek under +row+ (the row's item, overlaid: its runs for the
@@ -98,7 +108,7 @@ export function createPeek({ session, getItem, onChange = () => {} }) {
98
108
  if (peek.kind === "diff") body = diffTemplate(event.diff, { fold: 12 });
99
109
  else if (peek.kind === "lines") body = linesTemplate(peek.rows, { fold: Infinity });
100
110
  else body = textTemplate(peek.rows.map((r) => r.text).join("\n"), { fold: Infinity });
101
- const words = countsText(events);
111
+ const words = countsText(events, data.counts);
102
112
  const foot = html`<div class="ws-peek-f"><button type="button" class="ws-peek-open" data-ws="timeline" data-ws-id=${openId}>Open the timeline${words ? html`<span class="ws-peek-n"> · ${words}</span>` : nothing}</button>${callTemplate(event, row)}</div>`;
103
113
  return html`<div class="ws-peek" role="region" aria-label="What chi has">${head}<div class="ws-peek-b">${body}</div>${foot}</div>`;
104
114
  },
@@ -15,9 +15,11 @@
15
15
  // the owner's: app.js makes this only for a viewer with working_set_items.
16
16
  //
17
17
  // The timeline comes from the item route (getWorkingSetItem); an answer for
18
- // an item no longer open, or another session, is dropped (latest.js). While
19
- // open, each new server snapshot asks again (the route builds from the
20
- // session's messages, which lag a running turn's events). Leaving the
18
+ // an item no longer open, or another session, is dropped (latest.js), and
19
+ // so is one older than the drawn one within a running turn (olderAnswer).
20
+ // While open, a new server snapshot asks again only when the item's server
21
+ // signature changed (working_set.js serverSig): mid-turn the route answers
22
+ // the running turn's view as of its last step. Leaving the
21
23
  // session (another one, the start page) resets it: session_view.js
22
24
  // forgetSession calls reset(), so #center is never left inert under it.
23
25
 
@@ -29,11 +31,13 @@ import { createPeek } from "./ws_peek.js";
29
31
  import { setTimelineWayIn } from "./ws_way_in.js";
30
32
  import { cardTemplate } from "./ws_cards.js";
31
33
  import { bandBox, countsText, eventTag, fileStrip, itemPath, linesText, timelineCards } from "./ws_timeline.js";
34
+ import { olderAnswer } from "./ws_item_sig.js";
32
35
  import { GLYPHS, leafText, opsText, steerId, steerLine, tokensText } from "./working_set.js";
33
36
 
34
- // The item route's answer for session +id+ (+now+: a memory's text now).
35
- export function getWorkingSetItem(id, kind, key, { now = false } = {}) {
36
- return api(itemPath(id, kind, key, { now }));
37
+ // The item route's answer for session +id+ (+now+: a memory's text now;
38
+ // +latest+: the peek's events and counts only).
39
+ export function getWorkingSetItem(id, kind, key, { now = false, latest = false } = {}) {
40
+ return api(itemPath(id, kind, key, { now, latest }));
37
41
  }
38
42
 
39
43
  const PHONE_MAX = 600;
@@ -68,8 +72,10 @@ export function createWorkingSetPreview({ centerEl, session, state = () => ({}),
68
72
  let failed = false;
69
73
  let tab = "has";
70
74
  let openFor = null;
75
+ let askedSig;
71
76
  const latest = createLatest(() => `${session()}|${open ? `${open.kind}:${open.key}` : ""}`);
72
- const peek = createPeek({ session, getItem: (id, kind, key) => getItem(id, kind, key), onChange: () => workingSet?.peekChanged() });
77
+ const sigOf = (it) => workingSet?.serverSig?.(it);
78
+ const peek = createPeek({ session, getItem, sigOf, onChange: () => workingSet?.peekChanged() });
73
79
 
74
80
  const el = doc.createElement("section");
75
81
  el.className = "ws-reader";
@@ -95,10 +101,11 @@ export function createWorkingSetPreview({ centerEl, session, state = () => ({}),
95
101
  if (!id || !open) return;
96
102
  const fresh = latest.begin();
97
103
  const { kind, key } = open;
104
+ askedSig = sigOf(current());
98
105
  Promise.resolve()
99
106
  .then(() => getItem(id, kind, key, { now: kind === "memory" }))
100
107
  .then((answer) => {
101
- if (!fresh()) return;
108
+ if (!fresh() || olderAnswer(data, answer)) return;
102
109
  data = answer;
103
110
  failed = false;
104
111
  draw();
@@ -295,12 +302,15 @@ export function createWorkingSetPreview({ centerEl, session, state = () => ({}),
295
302
  workingSet = view;
296
303
  if (!view) return;
297
304
  setTimelineWayIn(true);
298
- // A new snapshot: asked again (a snapshot of another session: closed,
299
- // though forgetSession's reset has done it already).
305
+ // A new snapshot: asked again when the open item's server signature
306
+ // changed, else only drawn (the set beside it); a snapshot of another session: closed, though
307
+ // forgetSession's reset has done it already).
300
308
  view.onServer(() => {
301
309
  if (el.hidden) return;
302
- if (session() !== openFor) close({ refocus: false });
303
- else load();
310
+ if (session() !== openFor) return close({ refocus: false });
311
+ const sig = sigOf(current());
312
+ if (failed || sig === undefined || sig !== askedSig) load();
313
+ else draw();
304
314
  });
305
315
  },
306
316
  open: openItem,
@@ -52,6 +52,7 @@ const sameScope = (a, b) => !a || !b || a === b;
52
52
 
53
53
  // Whether +item+ (a set item) is the memory +part+ names: its name, and its
54
54
  // scope when both know theirs.
55
+ // The server-side twin is Tools::MemoryRead.prompt_memory? in tools/memory.rb.
55
56
  export const same = (part, item) => item.kind === "memory" && memoryName(item.key) === memoryName(part.ref) && sameScope(part.scope, item.scope);
56
57
 
57
58
  // A part's row: never an item the set or a steer line knows.
@@ -35,10 +35,12 @@ export function eventState(event) {
35
35
  return "sent";
36
36
  }
37
37
 
38
- // The path of the item route for session +id+ (+now+: a memory's text now).
39
- export function itemPath(id, kind, key, { now = false } = {}) {
38
+ // The path of the item route for session +id+ (+now+: a memory's text now;
39
+ // +latest+: the peek's events and counts only).
40
+ export function itemPath(id, kind, key, { now = false, latest = false } = {}) {
40
41
  const query = new URLSearchParams({ kind, key });
41
42
  if (now) query.set("now", "1");
43
+ if (latest) query.set("latest", "1");
42
44
  return `/api/sessions/${encodeURIComponent(id)}/working_set/item?${query}`;
43
45
  }
44
46
 
@@ -132,10 +134,11 @@ export function bandBox(band, length) {
132
134
  return { left: `${left.toFixed(2)}%`, width: `${Math.min(width, 100 - left).toFixed(2)}%` };
133
135
  }
134
136
 
135
- // "3 reads, 1 edit" (the peek's link and the reader's head).
136
- export function countsText(events = []) {
137
- const reads = events.filter((e) => e.op === "read" || e.op === "memory_read" || e.op === "fetch").length;
138
- const edits = events.filter((e) => e.op === "edit" || e.op === "write" || e.op === "memory_write").length;
137
+ // "3 reads, 1 edit" (the peek's link and the reader's head); +counts+: a
138
+ // latest=1 answer's ({read, edit}), whose events are the peek's only.
139
+ export function countsText(events = [], counts = null) {
140
+ const reads = counts ? Number(counts.read) || 0 : events.filter((e) => e.op === "read" || e.op === "memory_read" || e.op === "fetch").length;
141
+ const edits = counts ? Number(counts.edit) || 0 : events.filter((e) => e.op === "edit" || e.op === "write" || e.op === "memory_write").length;
139
142
  const word = (n, one) => `${n} ${one}${n === 1 ? "" : "s"}`;
140
143
  return [reads ? word(reads, "read") : "", edits ? word(edits, "edit") : ""].filter(Boolean).join(", ");
141
144
  }