samagotchi 0.182.0 → 0.184.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 (197) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +107 -1
  3. data/bin/chi +3 -1
  4. data/docs/architecture.md +22 -11
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +28 -6
  8. data/docs/configuration.md +4 -2
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +58 -3
  11. data/docs/internals/bridge.md +14 -6
  12. data/docs/internals/bundles.md +26 -5
  13. data/docs/internals/engine.md +20 -9
  14. data/docs/internals/participants.md +1 -1
  15. data/docs/internals/prompt-caching.md +8 -1
  16. data/docs/internals/remote-sessions.md +40 -5
  17. data/docs/internals/web-frontend.md +96 -31
  18. data/docs/internals/web-push.md +11 -0
  19. data/docs/internals/working-set.md +239 -7
  20. data/docs/mcp-server.md +84 -0
  21. data/docs/memory.md +2 -1
  22. data/docs/plugins.md +309 -22
  23. data/docs/scheduling.md +14 -0
  24. data/docs/sessions.md +4 -4
  25. data/docs/sub-agent.md +9 -0
  26. data/docs/testing.md +3 -1
  27. data/docs/thin-clients.md +165 -0
  28. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  29. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  30. data/lib/samagotchi/bridge.rb +59 -68
  31. data/lib/samagotchi/bridge_client.rb +12 -4
  32. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  33. data/lib/samagotchi/bundle_command/check.rb +55 -20
  34. data/lib/samagotchi/bundle_command.rb +50 -21
  35. data/lib/samagotchi/bundle_manifest.rb +105 -4
  36. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  37. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  38. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  39. data/lib/samagotchi/bundles/mcp/http_client.rb +432 -0
  40. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  41. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  42. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  43. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  44. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  45. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  46. data/lib/samagotchi/bundles/system/self_map.md +7 -2
  47. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  48. data/lib/samagotchi/command_intake.rb +7 -0
  49. data/lib/samagotchi/commands/registry.rb +8 -3
  50. data/lib/samagotchi/continue_offer.rb +24 -15
  51. data/lib/samagotchi/engine/block_fix.rb +4 -4
  52. data/lib/samagotchi/engine/cards.rb +14 -5
  53. data/lib/samagotchi/engine/events.rb +10 -15
  54. data/lib/samagotchi/engine/models.rb +1 -1
  55. data/lib/samagotchi/engine/plugins.rb +3 -0
  56. data/lib/samagotchi/engine/recap.rb +1 -1
  57. data/lib/samagotchi/engine/session.rb +14 -6
  58. data/lib/samagotchi/engine/side_requests.rb +1 -1
  59. data/lib/samagotchi/engine/sign_in.rb +142 -0
  60. data/lib/samagotchi/engine/turn_end.rb +3 -3
  61. data/lib/samagotchi/engine/turn_helpers.rb +4 -3
  62. data/lib/samagotchi/engine.rb +43 -27
  63. data/lib/samagotchi/engine_snapshots.rb +1 -1
  64. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  65. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  66. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  67. data/lib/samagotchi/hold_stop.rb +4 -4
  68. data/lib/samagotchi/idle_recap.rb +19 -11
  69. data/lib/samagotchi/idle_reminders.rb +7 -5
  70. data/lib/samagotchi/idle_scheduler.rb +7 -10
  71. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  72. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  73. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  74. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  75. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  76. data/lib/samagotchi/llm/http.rb +96 -5
  77. data/lib/samagotchi/mcp_command.rb +110 -0
  78. data/lib/samagotchi/mcp_server/http.rb +112 -0
  79. data/lib/samagotchi/mcp_server/protocol.rb +263 -0
  80. data/lib/samagotchi/mcp_server/stdio.rb +93 -0
  81. data/lib/samagotchi/mcp_server/text.rb +155 -0
  82. data/lib/samagotchi/mcp_server/tools.rb +246 -0
  83. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  84. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  85. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  86. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  87. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  88. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  89. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  90. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  91. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  92. data/lib/samagotchi/model_notes.rb +34 -12
  93. data/lib/samagotchi/plugin/api.rb +6 -1
  94. data/lib/samagotchi/plugin/card.rb +36 -11
  95. data/lib/samagotchi/plugin/context.rb +63 -6
  96. data/lib/samagotchi/plugin/http.rb +40 -15
  97. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  98. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  99. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  100. data/lib/samagotchi/plugin/loader.rb +18 -11
  101. data/lib/samagotchi/plugin/secrets.rb +266 -0
  102. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  103. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  104. data/lib/samagotchi/prompt_files.rb +11 -4
  105. data/lib/samagotchi/prompt_layout.rb +88 -0
  106. data/lib/samagotchi/prompt_part.rb +82 -20
  107. data/lib/samagotchi/queued_command.rb +28 -4
  108. data/lib/samagotchi/recap_setup.rb +13 -4
  109. data/lib/samagotchi/ref.rb +3 -2
  110. data/lib/samagotchi/relay_verifier.rb +8 -7
  111. data/lib/samagotchi/relay_watcher.rb +4 -4
  112. data/lib/samagotchi/reply_wait.rb +6 -3
  113. data/lib/samagotchi/run_options.rb +2 -1
  114. data/lib/samagotchi/schedule_command.rb +18 -4
  115. data/lib/samagotchi/schedules.rb +40 -8
  116. data/lib/samagotchi/send_command.rb +54 -41
  117. data/lib/samagotchi/session_access/ask.rb +285 -0
  118. data/lib/samagotchi/session_access/contract.rb +5 -0
  119. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  120. data/lib/samagotchi/session_access/exchange.rb +176 -0
  121. data/lib/samagotchi/session_access/local.rb +34 -6
  122. data/lib/samagotchi/session_access/remote.rb +4 -1
  123. data/lib/samagotchi/session_command_catalog.rb +10 -0
  124. data/lib/samagotchi/session_commands.rb +17 -0
  125. data/lib/samagotchi/session_config.rb +4 -4
  126. data/lib/samagotchi/session_inbox.rb +15 -0
  127. data/lib/samagotchi/session_manager/delivery.rb +8 -4
  128. data/lib/samagotchi/session_observer.rb +27 -0
  129. data/lib/samagotchi/steer_cut.rb +4 -3
  130. data/lib/samagotchi/system_prompt.rb +196 -161
  131. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  132. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  133. data/lib/samagotchi/testing/boundary.rb +4 -0
  134. data/lib/samagotchi/testing/bundle.rb +48 -2
  135. data/lib/samagotchi/testing/fake_http.rb +60 -15
  136. data/lib/samagotchi/testing/host.rb +4 -1
  137. data/lib/samagotchi/testing/recorder.rb +45 -5
  138. data/lib/samagotchi/tools/memory.rb +11 -3
  139. data/lib/samagotchi/tools/tool_index.rb +14 -3
  140. data/lib/samagotchi/turn_stages/warmup.rb +2 -2
  141. data/lib/samagotchi/version.rb +1 -1
  142. data/lib/samagotchi/web/app.rb +9 -8
  143. data/lib/samagotchi/web/ask_routes.rb +362 -0
  144. data/lib/samagotchi/web/mcp_route.rb +91 -0
  145. data/lib/samagotchi/web/public/app.js +2 -3
  146. data/lib/samagotchi/web/public/block_frame.js +72 -11
  147. data/lib/samagotchi/web/public/block_host.js +44 -8
  148. data/lib/samagotchi/web/public/block_regions.js +126 -0
  149. data/lib/samagotchi/web/public/card.js +22 -9
  150. data/lib/samagotchi/web/public/card_actions.js +21 -0
  151. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  152. data/lib/samagotchi/web/public/card_registry.js +3 -2
  153. data/lib/samagotchi/web/public/data.js +15 -12
  154. data/lib/samagotchi/web/public/delete_sheet.js +231 -169
  155. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  156. data/lib/samagotchi/web/public/format.js +3 -0
  157. data/lib/samagotchi/web/public/index.html +52 -7
  158. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  159. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  160. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  161. data/lib/samagotchi/web/public/refs.js +5 -3
  162. data/lib/samagotchi/web/public/region_hit.js +144 -0
  163. data/lib/samagotchi/web/public/removal_sheet_model.js +274 -0
  164. data/lib/samagotchi/web/public/running_tasks.js +3 -17
  165. data/lib/samagotchi/web/public/session_actions.js +96 -100
  166. data/lib/samagotchi/web/public/working_set_view.js +167 -21
  167. data/lib/samagotchi/web/public/ws_part_peek.js +277 -0
  168. data/lib/samagotchi/web/public/ws_peek.js +3 -1
  169. data/lib/samagotchi/web/public/ws_preview.css +30 -0
  170. data/lib/samagotchi/web/public/ws_reader.js +7 -3
  171. data/lib/samagotchi/web/public/ws_sections.js +37 -7
  172. data/lib/samagotchi/web/push/notifier.rb +33 -6
  173. data/lib/samagotchi/web/server.rb +1 -1
  174. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  175. data/lib/samagotchi/web/session_control.rb +31 -9
  176. data/lib/samagotchi/web/session_create.rb +2 -2
  177. data/lib/samagotchi/web/session_hub.rb +26 -4
  178. data/lib/samagotchi/web/working_set_routes.rb +93 -5
  179. data/lib/samagotchi/worker/child_side.rb +3 -2
  180. data/lib/samagotchi/worker/command_queue.rb +13 -13
  181. data/lib/samagotchi/worker/leave.rb +3 -3
  182. data/lib/samagotchi/worker/scratch.rb +6 -6
  183. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  184. data/lib/samagotchi/worker/startup.rb +3 -3
  185. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  186. data/lib/samagotchi/worker.rb +32 -21
  187. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  188. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  189. data/lib/samagotchi/worker_inbound.rb +12 -7
  190. data/lib/samagotchi/worker_link.rb +2 -2
  191. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  192. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  193. data/lib/samagotchi/working_set.rb +162 -90
  194. data/lib/samagotchi/working_set_locator.rb +221 -0
  195. data/lib/samagotchi/working_set_own_changes.rb +221 -0
  196. data/lib/samagotchi/working_set_part.rb +281 -0
  197. metadata +36 -1
@@ -1,9 +1,11 @@
1
1
  import { continueRefusal, continuedText, openChildrenTemplate, openerText } from "./chains.js";
2
- import { cantText, deleteConfirmText, goneSessionNotice } from "./format.js";
3
- import { tasksConfirmText, tasksCount, tasksStoppedSuffix } from "./running_tasks.js";
2
+ import { cantText, goneSessionNotice } from "./format.js";
3
+ import { tasksStoppedSuffix } from "./running_tasks.js";
4
4
  import { sessionHash } from "./route.js";
5
5
  import { inTree } from "./sessions_list.js";
6
- import { isChained, listAfterDelete, deleteToast, runDeleteFlow } from "./delete_sheet.js";
6
+ import { stillOn } from "./latest.js";
7
+ import { listAfterDelete, runDeleteFlow } from "./delete_sheet.js";
8
+ import { deleteToast } from "./removal_sheet_model.js";
7
9
 
8
10
  // What the page does to a whole session (used by app.js): Continue, Archive
9
11
  // and Unarchive, Delete and Stop, from the info bar's buttons, a card's or a
@@ -25,113 +27,72 @@ import { isChained, listAfterDelete, deleteToast, runDeleteFlow } from "./delete
25
27
  // from another session it displaced, or null), +restoreDraft(draft, opener)+
26
28
  // (that draft back, never over newer text), +closeLiveStream()+ (the live
27
29
  // stream's close, the stream left as it is) and +workerGone(id)+ the page's.
28
- // +alert+ / +confirm+: the browser's.
30
+ // +confirm+: the browser's (Stop's, when nothing else runs).
29
31
  export function createSessionActions({
30
32
  selected, store, sessions, setSessions, api, eventsLive, refresh,
31
33
  select, clearSelection, showNotice, toast, addCreatedSession, fillOpener, restoreDraft, closeLiveStream, workerGone,
32
- alert = (text) => globalThis.alert(text), confirm = (text) => globalThis.confirm(text),
34
+ confirm = (text) => globalThis.confirm(text),
33
35
  // The Stop sheet (stop_sheet.js): +open(id, holds)+ shows it and answers
34
36
  // true; nothing to stop (or no sheet wired) is false, and Stop is the
35
37
  // confirm.
36
38
  stopSheet = { open: () => false },
37
- // A card's delete sheet (delete_sheet.js createDeleteSheet): +host(anchor)+
38
- // draws a chained session's choices at it.
39
+ // The delete sheet's shell (delete_sheet.js createDeleteSheet):
40
+ // +host(anchor, id)+ draws a delete's or an archive's sheet at it.
39
41
  deleteSheet = null,
42
+ // The page's document: where a card's control and ⋯ are found.
43
+ doc = globalThis.document,
40
44
  }) {
41
45
  // The session this tab is stopping: its stream may close before the stop
42
46
  // request returns (workerGone reads it).
43
47
  let stoppingId = null;
44
48
 
45
- // Delete a session (the ⋯ More panel's Delete, an all-sessions card's ✕).
46
- // A chained session gets the delete sheet (delete_sheet.js): in the More
47
- // panel's place (deleteIn), at the card's ✕ (+anchor+), else at ⋯. Any
48
- // other keeps today's confirm. The list drops what went without a reload.
49
- // The server stops a live worker first and refuses a session a terminal
50
- // chi has open.
51
- async function confirmDelete(id, { anchor = null } = {}) {
49
+ // Delete a session (the ⋯ More panel's Delete, an all-sessions card's ✕):
50
+ // the delete sheet (delete_sheet.js) says what goes, what is stopped first
51
+ // and what stays, from the server's plan; in the More panel's place
52
+ // (deleteIn), at the card's ✕ (+anchor+), else at ⋯. A refusal the plan
53
+ // carries (a terminal's one-turn run, a schedule) is the sheet's Can't
54
+ // delete. The list drops what went without a reload.
55
+ function confirmDelete(id, { anchor = null } = {}) {
52
56
  const sess = sessions().find((s) => s.id === id) || { id };
53
- if (sess.owner === "tui") {
54
- alert(`Session ${id.slice(0, 8)} is open in a terminal chi; close it there first.`);
55
- return;
56
- }
57
- if (deleteSheet && api.deletePlan && isChained(sess, sessions())) {
58
- const at = anchor || globalThis.document?.querySelector("#infoMoreBtn");
59
- if (at) { startDeleteFlow(id, sess, deleteSheet.host(at, id)); return; }
60
- }
61
- await plainDelete(id, sess);
57
+ const at = anchor || doc?.querySelector("#infoMoreBtn");
58
+ if (!deleteSheet || !api.deletePlan || !at) return;
59
+ startDeleteFlow(id, sess, deleteSheet.host(at, id));
62
60
  }
63
61
 
64
- // The More panel's Delete: true when it took +host+ (a chained session).
62
+ // The More panel's Delete: it always takes +host+ (the panel turns into
63
+ // the sheet), so no second popover opens inside More's click.
65
64
  function deleteIn(id, host) {
66
- const sess = sessions().find((s) => s.id === id);
67
- if (!sess || sess.owner === "tui" || !api.deletePlan || !isChained(sess, sessions())) return false;
68
- startDeleteFlow(id, sess, host);
65
+ if (!id || !api.deletePlan) return false;
66
+ startDeleteFlow(id, sessions().find((s) => s.id === id) || { id }, host);
69
67
  return true;
70
68
  }
71
69
 
72
70
  function startDeleteFlow(id, sess, host) {
73
71
  const flow = runDeleteFlow({
74
- id, session: sess, host, api,
72
+ id, session: sess, host, api, sessions,
75
73
  done: (which, result, plan) => afterDelete(id, which, result, plan),
76
- plain: () => plainDelete(id, sess),
77
- failed: (error) => alert(`Could not delete session ${id.slice(0, 8)}: ${error.message}`),
74
+ failed: (error) => {
75
+ notShown(host, `delete ${id.slice(0, 8)}`, error);
76
+ if (!eventsLive()) refresh();
77
+ },
78
78
  });
79
79
  host.wire(flow);
80
80
  }
81
81
 
82
+ // A delete or archive that didn't happen, when its sheet no longer shows
83
+ // why (an older cached delete_sheet.js closes it first): a sticky toast.
84
+ function notShown(host, what, error) {
85
+ if (!host.live || host.live()) return;
86
+ toast(cantText(what, error), null, { sticky: true });
87
+ }
88
+
82
89
  function afterDelete(id, which, result, plan) {
83
90
  setSessions(listAfterDelete(sessions(), result));
84
91
  const gone = new Set(result.deleted || [id]);
85
92
  if (gone.has(selected())) clearSelection();
86
93
  if (!eventsLive()) refresh();
87
- const { text, back } = deleteToast(which, result, plan, id);
88
- toast(`${text}${tasksStoppedSuffix(result)}`, back ? { label: `Open ${back.slice(0, 8)}`, run: () => select(back) } : null);
89
- }
90
-
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).
95
- async function plainDelete(id, sess) {
96
- if (!confirm(deleteConfirmText(sess))) return;
97
- try {
98
- await api.deleteSession(id);
99
- } catch (e) {
100
- if (e.code === "tasks_running") { await deleteStoppingTasks(id, e.body?.tasks); return; }
101
- deleteFailed(id, e);
102
- return;
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) {
127
- setSessions(sessions().filter((s) => s.id !== id));
128
- if (selected() === id) clearSelection();
129
- }
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"}…`;
94
+ const { text, back, sticky = false } = deleteToast(which, result, plan, id);
95
+ toast(text, back ? { label: `Open ${back.slice(0, 8)}`, run: () => select(back) } : null, { sticky });
135
96
  }
136
97
 
137
98
  // The open session no longer exists: back to the start page, saying why.
@@ -282,10 +243,11 @@ export function createSessionActions({
282
243
  // the open session's worker was stopped (it, or a delegate of the archived
283
244
  // one), its stream ending is a stop, not a lost worker.
284
245
  // +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).
246
+ // first, only +tasks+ (the ids the sheet named) when given (else a session
247
+ // whose tasks still run is refused: 409 tasks_running; a batch passes
248
+ // nothing, and skips it with that reason).
287
249
  // @return {ok: true, result} | {ok: false, error}
288
- async function archiveOne(id, archive, { stopTasks = false } = {}) {
250
+ async function archiveOne(id, archive, { stopTasks = false, tasks = null } = {}) {
289
251
  // A live worker in the tree is stopped by the archive: the open
290
252
  // session's stream ending then is a stop.
291
253
  const open = selected();
@@ -293,7 +255,7 @@ export function createSessionActions({
293
255
  if (mine) stoppingId = mine;
294
256
  try {
295
257
  const result = archive
296
- ? await api.archiveSession(id, ...(stopTasks ? [{ stopTasks: true }] : []))
258
+ ? await api.archiveSession(id, ...(stopTasks ? [{ stopTasks: true, ...(tasks ? { tasks } : {}) }] : []))
297
259
  : await api.unarchiveSession(id);
298
260
  markArchived(archive ? result.archived : result.unarchived, archive);
299
261
  if (mine && mine === selected() && (result.stopped || []).includes(mine)) stoppedWorker(mine);
@@ -306,35 +268,69 @@ export function createSessionActions({
306
268
  }
307
269
  }
308
270
 
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.
312
- async function setArchived(id, archive, { undo = true } = {}) {
313
- const short = id.slice(0, 8);
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
- }
271
+ // No confirm: one tap and the toast's Undo. Unless the archive can't
272
+ // happen as it is (a 409): background tasks the tree started still run
273
+ // (tasks_running) opens the sheet in Archive's words, whose button archives
274
+ // stopping the tasks it named; any other refusal is its Can't archive. The
275
+ // sheet is at the control tapped: +anchor+ (⋯ for the open session's), else
276
+ // the card's archive button, found by the session's id. Undo only
277
+ // unarchives: stopped tasks stay stopped.
278
+ // A sheet opened since for another session (a card's ✕ while the archive
279
+ // was out) keeps its place: the refusal is a sticky toast instead
280
+ // (latest.js stillOn on the shell's session).
281
+ async function setArchived(id, archive, { undo = true, anchor = null } = {}) {
282
+ const sheetSame = deleteSheet?.openFor ? stillOn(() => deleteSheet.openFor()) : () => true;
283
+ const answer = await archiveOne(id, archive);
323
284
  if (!answer.ok) {
324
- alert(`Could not ${archive ? "archive" : "unarchive"} session ${short}: ${answer.error.message}`);
285
+ const taken = !sheetSame() && deleteSheet.openFor() !== id;
286
+ const at = archive && deleteSheet && !taken ? anchor || archiveAnchor(id) : null;
287
+ if (at) askArchive(id, answer.error, at, undo);
288
+ else {
289
+ toast(cantText(`${archive ? "archive" : "unarchive"} ${id.slice(0, 8)}`, answer.error), null, { sticky: true });
290
+ if (!eventsLive()) refresh();
291
+ }
325
292
  return;
326
293
  }
327
- // markArchived's list redrew the lists and the bar already.
294
+ archived(id, archive, answer.result, undo);
295
+ }
296
+
297
+ // markArchived's list redrew the lists and the bar already.
298
+ function archived(id, archive, result, undo) {
328
299
  if (!eventsLive()) refresh();
329
300
  const what = archive ? "Archived" : "Unarchived";
330
- toast(`${what} ${short}${suffix}`, undo ? { label: "Undo", run: () => setArchived(id, !archive, { undo: false }) } : null);
301
+ toast(`${what} ${id.slice(0, 8)}${archive ? tasksStoppedSuffix(result) : ""}`,
302
+ undo ? { label: "Undo", run: () => setArchived(id, !archive, { undo: false }) } : null);
303
+ }
304
+
305
+ // A card's archive button for +id+ that has a box (the strip's, the list's
306
+ // or the all-sessions view's), else ⋯.
307
+ function archiveAnchor(id) {
308
+ const cards = [...(doc?.querySelectorAll(`[data-arch="${id}"]`) || [])];
309
+ return cards.find((el) => el.getClientRects?.().length) || doc?.querySelector("#infoMoreBtn") || null;
310
+ }
311
+
312
+ function askArchive(id, error, at, undo) {
313
+ const host = deleteSheet.host(at, id);
314
+ host.wire(runDeleteFlow({
315
+ id, session: sessions().find((s) => s.id === id) || { id }, host, sessions,
316
+ archive: { refusal: error },
317
+ api: {
318
+ archive: async (sid, opts) => {
319
+ const answer = await archiveOne(sid, true, opts);
320
+ if (!answer.ok) throw answer.error;
321
+ return answer.result;
322
+ },
323
+ },
324
+ done: (_which, result) => archived(id, true, result, undo),
325
+ failed: (failure) => notShown(host, `archive ${id.slice(0, 8)}`, failure),
326
+ }));
331
327
  }
332
328
 
333
329
  // The info bar's Archive / Unarchive: the open session's, by its state.
334
330
  function toggleArchiveSelected() {
335
331
  if (!selected()) return;
336
332
  if (selectedArchived()) setArchived(selected(), false);
337
- else setArchived(selected(), true);
333
+ else setArchived(selected(), true, { anchor: doc?.querySelector("#infoMoreBtn") || null });
338
334
  }
339
335
 
340
336
  return {
@@ -42,7 +42,6 @@ import { repeat } from "./vendor/directives/repeat.js";
42
42
  import { createChipPopover, SHEET_SHARE, SHEET_TALL } from "./chip_popover.js";
43
43
  import { stillOn } from "./latest.js";
44
44
  import { showRow } from "./refs.js";
45
- import { PEEK_WIDTH } from "./ws_peek.js";
46
45
  import { read as readPref, write as writePref } from "./session_prefs.js";
47
46
  import {
48
47
  foldedSections, headItems, headLine, headSections, heldTwice, heldTwiceNote, lensTouched, memoryPartWords, promptKeys, startTokensText, WS_SECTION_FOLD,
@@ -53,8 +52,20 @@ import {
53
52
  steerId, steerLine, stepRange, stepTag, tokensText, turnLens, undroppable,
54
53
  } from "./working_set.js";
55
54
  import { serverSig } from "./ws_item_sig.js";
55
+ import { placeOf } from "./ws_timeline.js";
56
56
  import { heldOrder, recencyOrder } from "./ws_order.js";
57
57
 
58
+ // The popover's width, open row or not (a peek no longer widens it: the rows
59
+ // stayed put only at one width).
60
+ const WIDTH = 520;
61
+ // A stale start row's title words (ws_part_peek.js's now tab says the same).
62
+ const PART_CHANGED = "changed after chi's prompt was built";
63
+ const BOTH_CHANGED = "read changed · prompt text changed";
64
+ // A prompt row whose source chi changed itself (the GET's by_chi, current):
65
+ // its title after "chi edited it at …".
66
+ const OWN_EDITED = "the new text is in its conversation; its prompt still sends the old text until it is next built";
67
+ const OWN_REMOVED = "its prompt still sends it until it is next built";
68
+
58
69
  // The popover's files fold to this many lines (groups open in place, one at
59
70
  // a time), its memories past this many to one group.
60
71
  const POP_BUDGET = 6;
@@ -198,6 +209,64 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
198
209
  let stripOpen = null;
199
210
  const listeners = new Set();
200
211
  const lit = (items) => overlay(items, server);
212
+ // The prompt parts whose source changed since chi was sent them (chi
213
+ // web's GET's parts, WorkingSetPart.states): a GET's word, kept across
214
+ // the events' sets (takeServer), asked again at each open, a rebuilt
215
+ // prompt and a hand-off.
216
+ const partStates = () => (Array.isArray(server?.parts) ? server.parts : null);
217
+ // What the states say, to tell two answers' apart ("" for none).
218
+ const partsSig = (parts) => (Array.isArray(parts) && parts.length ? JSON.stringify(parts) : "");
219
+ // chi's own change of each stale part the GET named (by_chi: {tool_id,
220
+ // step, op, current}), by part key. Read here, off the GET's parts, not
221
+ // through ws_sections.js (an older cached one maps states to "stale").
222
+ const partChanges = () => new Map((partStates() || []).filter((s) => s && typeof s.key === "string" && s.by_chi && typeof s.by_chi === "object").map((s) => [s.key, s.by_chi]));
223
+ // Where a call sits in the page's turns ({turn, step, row}), by its chi id
224
+ // (ws_timeline.js placeOf over every turn's items), or null.
225
+ const placeFor = (toolId) => {
226
+ for (const items of [...turns.map((t) => t.items), live?.items || []]) {
227
+ for (const item of items || []) {
228
+ const at = placeOf({ tool_id: toolId }, item);
229
+ if (at) return at;
230
+ }
231
+ }
232
+ return null;
233
+ };
234
+ // A change's step tag: its place in the turns ("t3·s2"), else the
235
+ // server's step ("step 5"); +where+ the title's words.
236
+ const changeTag = (change) => {
237
+ const at = placeFor(change.tool_id);
238
+ if (at) return { at, text: stepTag({ at }, { session: true }), where: `turn ${at.turn + 1}, step ${at.step + 1}` };
239
+ const step = Number.isFinite(change.step) ? `step ${change.step}` : "";
240
+ return { at: null, text: step, where: step || "a step" };
241
+ };
242
+ // A start row with chi's own changes laid on it: each stale part chi's
243
+ // current change made "edited" (partStates; the peek's edited tab), the
244
+ // row partEdited ({op, tag}) when no part of it is stale any more;
245
+ // partByChi and partTags beside partKeys for the peek's lines (a stale
246
+ // part chi changed, then it changed again). A row without partKeys (an
247
+ // older cached ws_sections.js) as it is.
248
+ const ownRow = (row) => {
249
+ const keys = row?.partKeys;
250
+ if (!Array.isArray(keys) || !Array.isArray(row.partStates)) return row;
251
+ const changes = partChanges();
252
+ const byChi = keys.map((key) => changes.get(key) || null);
253
+ if (!byChi.some(Boolean)) return row;
254
+ const tags = byChi.map((change) => (change ? changeTag(change) : null));
255
+ const partStates = row.partStates.map((st, i) => (st === "stale" && byChi[i]?.current === true ? "edited" : st));
256
+ const partStale = partStates.includes("stale");
257
+ const edited = !partStale && partStates.includes("edited");
258
+ const last = edited ? partStates.map((st, i) => (st === "edited" ? i : -1)).filter((i) => i >= 0).sort((a, b) => (byChi[a].step || 0) - (byChi[b].step || 0)).at(-1) : -1;
259
+ return { ...row, partStates, partStale, partByChi: byChi, partTags: tags.map((t) => t?.text || ""), partEdited: edited ? { op: byChi[last].op, tag: tags[last] } : null };
260
+ };
261
+ // The session's prompt parts as built (each part's head and digest): a new
262
+ // build asks the GET again, so a rebuilt prompt's stale states go.
263
+ let builtSig = null;
264
+ let builtOf = null;
265
+ const builtSigOf = (parts) => JSON.stringify((Array.isArray(parts) ? parts : []).map((p) => [p?.kind, p?.head, p?.digest]));
266
+ // The prompt peek of "From the start" rows (ws_part_peek.js), on the peek
267
+ // a newer ws_reader.js makes; none (an older cached one): today's rows.
268
+ const part = peek?.part || null;
269
+ const anyPeek = () => !!(peek?.any() || part?.any());
201
270
 
202
271
  const sessionSet = () => {
203
272
  const st = state();
@@ -214,8 +283,8 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
214
283
  const promptOf = (t) => (live && t === live.ordinal ? live.prompt : turns[t]?.prompt || "");
215
284
 
216
285
  const popover = createChipPopover({
217
- id: "workingSetPopover", className: "ctx-popover ws-popover", width: () => (peek?.any() ? PEEK_WIDTH : 420), el: infoEl, anchor: ".ws-chip",
218
- openers: ".ws-chip, .ts-ws, .ws-foot", sheet: true, label: "Working set", sheetShare: () => (peek?.any() ? SHEET_TALL : SHEET_SHARE),
286
+ id: "workingSetPopover", className: "ctx-popover ws-popover", width: () => WIDTH, el: infoEl, anchor: ".ws-chip",
287
+ openers: ".ws-chip, .ts-ws, .ws-foot", sheet: true, label: "Working set", sheetShare: () => (anyPeek() ? SHEET_TALL : SHEET_SHARE),
219
288
  // The chip opens the session lens; the rail and a footprint set theirs
220
289
  // before they open it.
221
290
  summary: (anchor) => {
@@ -236,7 +305,7 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
236
305
  draw();
237
306
  if (opening) fetchServer();
238
307
  },
239
- onClose: () => { openGroup = null; openKeys = null; peek?.close(); onChange(); },
308
+ onClose: () => { openGroup = null; openKeys = null; part?.close(); peek?.close(); onChange(); },
240
309
  // The foot's + add (the popover's submit): one KEY as typed (quoted
241
310
  // when it has spaces).
242
311
  onSubmit: (form) => {
@@ -300,7 +369,9 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
300
369
  // +start+: a "From the start" memory row (ws_sections.js): its part's
301
370
  // words and tokens, no "prompt" tag (the section says it), "held twice"
302
371
  // when it was read again, and the note in a turn lens that read it.
303
- function rowTemplate(row0, { session: inSession, group = null, now, pend = new Map(), forget = false, touched = null, start = false }) {
372
+ function rowTemplate(given, { session: inSession, group = null, now, pend = new Map(), forget = false, touched = null, start = false }) {
373
+ // A start row with chi's own changes of its parts laid on it (ownRow).
374
+ const row0 = start ? ownRow(given) : given;
304
375
  // +row0+ is the session's item: its state, tokens, actions, peek. +item+ is
305
376
  // what the lens shows of it: the turn's `at`, ops and count (the step tag,
306
377
  // the words, the edited mark) and nothing else.
@@ -347,23 +418,72 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
347
418
  const isPending = pill !== nothing;
348
419
  const strip = stripOpen === id && buttons !== nothing;
349
420
  const open = item.kind === "file" ? html`<button type="button" class="ws-act-b open ref" data-ref-kind="file" data-ref-path=${item.ref?.path || full}>open</button>` : nothing;
350
- // The ▸ that peeks at what chi has of it (the owner's: +peek+).
351
- const canPeek = peek && peekable(row0);
352
- const peeked = canPeek && peek.isOpen(id);
353
- const toggle = canPeek ? html`<button type="button" class="ws-peek-toggle" data-ws="peek" data-ws-id=${id} aria-expanded=${String(peeked)} aria-label=${`What chi has of ${name}`} title="What chi has of it">${peeked ? "▾" : "▸"}</button>` : nothing;
354
- const row = html`<div class=${`ws-row ${item.kind}${row0.added ? " added" : ""}${fresh ? " fresh" : ""}${row0.muted ? " muted" : ""}${group ? " member" : ""}${state}${isPending ? " pending" : ""}${strip ? " strip-open" : ""}${peeked ? " peeked" : ""}${canPeek ? " peekable" : ""}${note ? " twice" : ""}${lensClass}`} data-ws-id=${id}>${toggle}<span class="k">${glyph}</span>${nameEl}${pin}${edited ? html`<span class="e">✎</span>` : nothing}<span class="st">${words}</span>${pill}${tokens ? html`<span class="tk" title=${start ? "about its tokens in the prompt, + its reads'" : `about ${row0.tokens} tokens of it are sent`}>${tokens}</span>` : nothing}${tagEl}${buttons !== nothing ? html`<span class="ws-act">${buttons}</span>` : nothing}</div>`;
421
+ // The ▸ that peeks at what chi has of it (the owner's: +peek+); a start
422
+ // row's opens the prompt peek, its read (when it has one) a tab of it;
423
+ // a row without its parts' keys (an older cached ws_sections.js) keeps today's.
424
+ const prompt = start && !!part && !!row0.partKeys?.length;
425
+ const partId = prompt ? `start:${itemKey(row0)}` : null;
426
+ const canPeek = prompt || (peek && peekable(row0));
427
+ const peeked = prompt ? part.isOpen(partId) : canPeek && peek.isOpen(id);
428
+ // Its read tab: the item peek, when it has one. A row chi only wrote has none: its edited tab (or the now
429
+ // tab's "chi edited it" line) says that write.
430
+ const readTab = !!peek && peekable(row0) && !(row0.partByChi?.some(Boolean) && !row0.ops.includes("read"));
431
+ const toggle = prompt ? partToggle(partId, row0, name, peeked, { read: readTab, item: id })
432
+ : canPeek ? html`<button type="button" class="ws-peek-toggle" data-ws="peek" data-ws-id=${id} aria-expanded=${String(peeked)} aria-label=${`What chi has of ${name}`} title="What chi has of it">${peeked ? "▾" : "▸"}</button>` : nothing;
433
+ const peekEl = !peeked ? nothing : prompt ? part.template(row0, { read: readTab, readTag: stepTag({ ...row0, preloaded: false, at: row0.last || row0.at }, { session: true }) }) : peek.template(row0);
434
+ // A prompt row whose source changed since chi was sent it says "stale" in place of its words, kept in
435
+ // its title; a read stale too: still one word, both causes in the title.
436
+ const pstale = start && !item.added && row0.partStale;
437
+ // A prompt row whose source chi changed itself: ✎, its words then "edited" (the read's own stale wins), its
438
+ // tag the call's.
439
+ const pedited = start && !item.added && !!row0.partEdited && row0.state !== "stale";
440
+ // The call's tag in place of the row's own (a turn lens's step), beside "held twice".
441
+ if (pedited) tagEl = start && inSession && heldTwice(row0) ? html`${tagEl}${ownTagTemplate(row0.partEdited)}` : ownTagTemplate(row0.partEdited);
442
+ const staleTitle = pstale ? `${row0.state === "stale" ? `${memoryPartWords(row0)} · ${row0.ops.includes("read") ? BOTH_CHANGED : PART_CHANGED}` : `${what} · ${PART_CHANGED}`}${fresh ? " · just now" : ""}` : "";
443
+ const row = html`<div class=${`ws-row ${item.kind}${row0.added ? " added" : ""}${fresh ? " fresh" : ""}${row0.muted ? " muted" : ""}${group ? " member" : ""}${state}${isPending ? " pending" : ""}${strip ? " strip-open" : ""}${peeked ? " peeked" : ""}${canPeek ? " peekable" : ""}${note ? " twice" : ""}${lensClass}`} data-ws-id=${id}>${toggle}<span class="k">${glyph}</span>${nameEl}${pin}${edited || pedited ? html`<span class="e">✎</span>` : nothing}${pstale ? staleTemplate(staleTitle) : pedited ? ownTemplate(memoryPartWords(row0), row0.partEdited) : html`<span class="st">${words}</span>`}${pill}${tokens ? html`<span class="tk" title=${start ? "about its tokens in the prompt, + its reads'" : `about ${row0.tokens} tokens of it are sent`}>${tokens}</span>` : nothing}${tagEl}${buttons !== nothing ? html`<span class="ws-act">${buttons}</span>` : nothing}</div>`;
355
444
  // One template either way, so the tapped row stays the same node (a
356
445
  // click outside the popover closes it).
357
446
  const noteEl = note ? html`<div class="ws-note twice" role="note">${note}</div>` : nothing;
358
- return html`${row}${noteEl}${strip ? html`<div class="ws-strip">${buttons}${open}</div>` : nothing}${peeked ? peek.template(row0) : nothing}`;
447
+ return html`${row}${noteEl}${strip ? html`<div class="ws-strip">${buttons}${open}</div>` : nothing}${peekEl}`;
359
448
  }
360
449
 
361
- // A prompt part's row: its label, its sub, its tokens; read-only, no
362
- // peek. Never touched by a turn: dim in a turn lens.
363
- function partRowTemplate(row, { touched = null }) {
450
+ // A prompt row's "stale": its source changed since chi was sent it.
451
+ const staleTemplate = (title = `its source ${PART_CHANGED}`) => html`<span class="st ws-pstale" title=${title}>stale</span>`;
452
+
453
+ // A prompt row chi changed itself: its part words (a phone's sheet hides them, .ws-pwords) then "edited"
454
+ // ("removed"), the title saying both facts.
455
+ function ownTemplate(words, own) {
456
+ const removed = own.op === "remove";
457
+ const title = `${words ? `${words} · ` : ""}chi ${removed ? "removed" : "edited"} it at ${own.tag.where}: ${removed ? OWN_REMOVED : OWN_EDITED}`;
458
+ return html`<span class="st ws-pedited" title=${title}>${words ? html`<span class="ws-pwords">${words} · </span>` : nothing}${removed ? "removed" : "edited"}</span>`;
459
+ }
460
+
461
+ // Its tag: the call's place, a jump as the read rows' (a plain "step N" without one).
462
+ function ownTagTemplate(own) {
463
+ const { at, text, where } = own.tag;
464
+ if (!text) return nothing;
465
+ const title = `chi ${own.op === "remove" ? "removed" : "edited"} it at ${where}: go to the call`;
466
+ return at ? html`<button type="button" class="ws-step p ws-own" data-ws="jump" data-at=${atAttr(at)} title=${title}>${text}</button>`
467
+ : html`<span class="ws-step p ws-own" title=${title}>${text}</span>`;
468
+ }
469
+
470
+ // A start row's ▸: the prompt peek (+opts+: its read, its item's id).
471
+ function partToggle(id, row, name, peeked, opts) {
472
+ return html`<button type="button" class="ws-peek-toggle" data-ws-part-peek=${id} aria-expanded=${String(peeked)} aria-label=${`What chi was sent of ${name}`} title="What chi was sent" @click=${() => part.toggle(id, row, opts)}>${peeked ? "▾" : "▸"}</button>`;
473
+ }
474
+
475
+ // A prompt part's row: its label, its sub, its tokens; read-only. Its ▸
476
+ // (with the prompt peek: a newer ws_reader.js) opens what chi was sent.
477
+ // Never touched by a turn: dim in a turn lens.
478
+ function partRowTemplate(given, { touched = null }) {
479
+ const row = ownRow(given);
364
480
  const lensClass = touched ? " dim" : "";
365
481
  const tokens = tokensText(row.partTokens);
366
- return html`<div class=${`ws-row ${row.kind}${lensClass}`} data-ws-part=${row.key}><span class="k"></span><span class="t" title=${row.sub ? `${row.label}: ${row.sub}` : row.label}>${row.label}</span>${row.sub ? html`<span class="st">${row.sub}</span>` : nothing}${tokens ? html`<span class="tk" title="about its tokens in every request">${tokens}</span>` : nothing}</div>`;
482
+ const opens = !!part && !!row.partKeys?.length;
483
+ const id = opens ? `start:part:${row.key}` : null;
484
+ const peeked = opens && part.isOpen(id);
485
+ const toggle = opens ? partToggle(id, row, row.label, peeked, {}) : nothing;
486
+ return html`<div class=${`ws-row ${row.kind}${lensClass}${opens ? " peekable" : ""}${peeked ? " peeked" : ""}`} data-ws-part=${row.key}>${toggle}<span class="k"></span><span class="t" title=${row.sub ? `${row.label}: ${row.sub}` : row.label}>${row.label}</span>${row.partEdited ? html`<span class="e">✎</span>` : nothing}${row.partStale ? staleTemplate(row.sub ? `${row.sub} · ${PART_CHANGED}` : undefined) : row.partEdited ? ownTemplate(row.sub, row.partEdited) : row.sub ? html`<span class="st">${row.sub}</span>` : nothing}${tokens ? html`<span class="tk" title="about its tokens in every request">${tokens}</span>` : nothing}${row.partEdited ? ownTagTemplate(row.partEdited) : nothing}</div>${peeked ? part.template(row) : nothing}`;
367
487
  }
368
488
 
369
489
  // The Conversation section as one row at section level ("Conversation ·
@@ -465,7 +585,7 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
465
585
  const set = { ...full, items: heldOrder(full.items, openKeys) };
466
586
  // The head view (no parts: today's list); a turn's read of `system/x`
467
587
  // lights the start row of `x`, and a prompt memory is never new.
468
- const head = headSections(set, POP_BUDGET, { parts: st.promptParts, ctxTokens: st.ctxTokens, turns: last + 1, inTurn: !inSession });
588
+ const head = headSections(set, POP_BUDGET, { parts: st.promptParts, ctxTokens: st.ctxTokens, turns: last + 1, inTurn: !inSession, states: partStates() });
469
589
  const inPrompt = promptKeys(head);
470
590
  const picked = inSession ? null : turnLens(headItems(set, st.promptParts).filter((item) => !inPrompt.has(itemKey(item))), turnItems(at), at);
471
591
  const opts = { session: inSession, now, pend, forget, touched: lensTouched(head, picked?.touched || null) };
@@ -552,7 +672,8 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
552
672
  }
553
673
  } else if (act.dataset.ws === "peek" && peek) {
554
674
  const item = rowItem(act.dataset.wsId);
555
- if (item) peek.toggle(act.dataset.wsId, item);
675
+ // One peek at a time across both kinds.
676
+ if (item) { part?.close(); peek.toggle(act.dataset.wsId, item); }
556
677
  } else if (act.dataset.ws === "timeline" && onTimeline) {
557
678
  const item = rowItem(act.dataset.wsId);
558
679
  if (popover.isOpen()) popover.close();
@@ -635,10 +756,20 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
635
756
  }
636
757
 
637
758
  // A newer server snapshot redraws every form; an older one (a GET that
638
- // answered after a newer event) is dropped. +how+: newerSnapshot's.
759
+ // answered after a newer event) is dropped, all but its parts. +how+:
760
+ // newerSnapshot's. The parts (the stale prompt parts) are a GET's word
761
+ // alone: an event's set carries none, so the session's last GET's stay
762
+ // (stale lasts until chi rebuilds its prompt; #sessionChanged and a
763
+ // hand-off ask again), and a GET an event overtook still gives them.
639
764
  function takeServer(snapshot, how) {
640
- const next = newerSnapshot(server, snapshot, how);
641
- if (next === server) return;
765
+ let next = newerSnapshot(server, snapshot, how);
766
+ const same = !!server && serverOf === session();
767
+ if (next === server) {
768
+ if (how?.event || !same || !Array.isArray(snapshot?.items) || partsSig(snapshot.parts) === partsSig(server.parts)) return;
769
+ next = withParts(server, snapshot.parts);
770
+ } else if (how?.event && same && !("parts" in next) && server.parts) {
771
+ next = withParts(next, server.parts);
772
+ }
642
773
  server = next;
643
774
  serverOf = session();
644
775
  changed();
@@ -649,6 +780,12 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
649
780
  if (how?.event && popover.isOpen()) peek?.refresh();
650
781
  }
651
782
 
783
+ // +snapshot+ with +parts+ (none: without the field).
784
+ function withParts(snapshot, parts) {
785
+ const { parts: _drop, ...rest } = snapshot;
786
+ return Array.isArray(parts) && parts.length ? { ...rest, parts } : rest;
787
+ }
788
+
652
789
  // The server's set for the open session, asked again; an answer for a
653
790
  // session no longer open is dropped.
654
791
  function fetchServer() {
@@ -692,7 +829,14 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
692
829
  if (popover.isOpen()) popover.refresh();
693
830
  },
694
831
  // Prompt memories changed; the open session list reads them from state.
832
+ // A new prompt build (its parts' heads or digests) asks the server's set
833
+ // again: its stale states are the build's.
695
834
  sessionChanged() {
835
+ const sig = builtSigOf(state().promptParts);
836
+ const rebuilt = builtOf === session() && builtSig !== null && sig !== builtSig;
837
+ builtSig = sig;
838
+ builtOf = session();
839
+ if (rebuilt) fetchServer();
696
840
  if (popover.isOpen()) popover.refresh();
697
841
  },
698
842
  // The context's tokens or window changed (a chunk, a context_status):
@@ -702,7 +846,7 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
702
846
  const st = state();
703
847
  const inSession = curLens() === null;
704
848
  const set = sessionSet();
705
- const head = headSections(set, POP_BUDGET, { parts: st.promptParts, ctxTokens: st.ctxTokens, turns: lastTurn() + 1, inTurn: !inSession });
849
+ const head = headSections(set, POP_BUDGET, { parts: st.promptParts, ctxTokens: st.ctxTokens, turns: lastTurn() + 1, inTurn: !inSession, states: partStates() });
706
850
  if (tokenText(lensLines(st, set, head, inSession), head) !== shownTokens) popover.refresh();
707
851
  },
708
852
  // A :working_set_updated event's set ({items, at}).
@@ -750,6 +894,8 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
750
894
  turns.push({ items, prompt });
751
895
  live = null;
752
896
  changed();
897
+ // A turn's end: the stale states asked again when there are some, or the list is open.
898
+ if (server?.parts || popover.isOpen()) fetchServer();
753
899
  return footprintNode(lit(items), ordinal);
754
900
  },
755
901
  // The running turn left without a hand-off (a reset): forgotten.