samagotchi 0.194.0 → 0.196.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 (152) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +80 -1
  3. data/docs/architecture.md +2 -1
  4. data/docs/bundle-authoring.md +23 -23
  5. data/docs/bundles.md +201 -7
  6. data/docs/cli.md +5 -1
  7. data/docs/configuration.md +25 -4
  8. data/docs/context.md +13 -3
  9. data/docs/guardrails.md +6 -4
  10. data/docs/hooks.md +3 -1
  11. data/docs/internals/attached-context.md +2 -0
  12. data/docs/internals/block-renderers.md +4 -1
  13. data/docs/internals/bridge.md +4 -0
  14. data/docs/internals/engine.md +15 -2
  15. data/docs/internals/knowledge.md +215 -0
  16. data/docs/internals/pages.md +17 -9
  17. data/docs/internals/panes.md +51 -13
  18. data/docs/internals/participants.md +15 -3
  19. data/docs/internals/peers.md +14 -9
  20. data/docs/internals/session-lifecycle.md +26 -12
  21. data/docs/internals/web-frontend.md +64 -27
  22. data/docs/memory.md +4 -2
  23. data/docs/pages.md +72 -1
  24. data/docs/peers.md +25 -14
  25. data/docs/plugins.md +132 -6
  26. data/docs/releasing.md +1 -1
  27. data/docs/scheduling.md +4 -0
  28. data/docs/sessions.md +9 -2
  29. data/docs/system-one.md +3 -1
  30. data/docs/testing.md +3 -1
  31. data/lib/samagotchi/bundle_manifest.rb +30 -5
  32. data/lib/samagotchi/bundles/claude-peer/manifest.yml +8 -5
  33. data/lib/samagotchi/bundles/claude-peer/plugin.rb +2 -2
  34. data/lib/samagotchi/bundles/codex-peer/manifest.yml +8 -5
  35. data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
  36. data/lib/samagotchi/bundles/coordinator/manifest.yml +7 -4
  37. data/lib/samagotchi/bundles/coordinator/plugin.rb +15 -5
  38. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +10 -0
  39. data/lib/samagotchi/bundles/core/manifest.yml +2 -2
  40. data/lib/samagotchi/bundles/cost-cap/manifest.yml +4 -4
  41. data/lib/samagotchi/bundles/cost-cap/plugin.rb +54 -3
  42. data/lib/samagotchi/bundles/dev/manifest.yml +3 -2
  43. data/lib/samagotchi/bundles/github-pr/manifest.yml +4 -2
  44. data/lib/samagotchi/bundles/knowledge/adapters.rb +205 -0
  45. data/lib/samagotchi/bundles/knowledge/catalog.rb +151 -0
  46. data/lib/samagotchi/bundles/knowledge/chi_adapters.rb +178 -0
  47. data/lib/samagotchi/bundles/knowledge/chunker.rb +55 -0
  48. data/lib/samagotchi/bundles/knowledge/github.rb +246 -0
  49. data/lib/samagotchi/bundles/knowledge/manifest.yml +27 -0
  50. data/lib/samagotchi/bundles/knowledge/plugin.rb +807 -0
  51. data/lib/samagotchi/bundles/knowledge/query.rb +30 -0
  52. data/lib/samagotchi/bundles/knowledge/query_log.rb +55 -0
  53. data/lib/samagotchi/bundles/knowledge/refresh.rb +133 -0
  54. data/lib/samagotchi/bundles/knowledge/store.rb +264 -0
  55. data/lib/samagotchi/bundles/reflect/manifest.yml +17 -0
  56. data/lib/samagotchi/bundles/reflect/scripts/reflect.rb +439 -0
  57. data/lib/samagotchi/bundles/reflect/skill_reflect.md +100 -0
  58. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  59. data/lib/samagotchi/context_change.rb +44 -0
  60. data/lib/samagotchi/context_note.rb +1 -1
  61. data/lib/samagotchi/context_providers.rb +14 -0
  62. data/lib/samagotchi/context_sources.rb +3 -25
  63. data/lib/samagotchi/engine/plugins.rb +21 -0
  64. data/lib/samagotchi/events.rb +1 -0
  65. data/lib/samagotchi/guardrails/pair_boundary.rb +12 -4
  66. data/lib/samagotchi/guardrails/review_paths.rb +13 -3
  67. data/lib/samagotchi/guardrails/targets.rb +24 -2
  68. data/lib/samagotchi/guardrails_command.rb +3 -9
  69. data/lib/samagotchi/hook_label.rb +19 -0
  70. data/lib/samagotchi/hook_routes.rb +3 -2
  71. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  72. data/lib/samagotchi/memory_bundle/builder.rb +2 -1
  73. data/lib/samagotchi/memory_bundle/installed_copy.rb +2 -1
  74. data/lib/samagotchi/page_command.rb +90 -6
  75. data/lib/samagotchi/pages/launch.rb +16 -8
  76. data/lib/samagotchi/pages/runner.rb +7 -2
  77. data/lib/samagotchi/pages/runtime.rb +62 -2
  78. data/lib/samagotchi/pages.rb +4 -0
  79. data/lib/samagotchi/panes/kitty.rb +20 -5
  80. data/lib/samagotchi/panes.rb +81 -12
  81. data/lib/samagotchi/participants.rb +17 -6
  82. data/lib/samagotchi/peer_exchanges.rb +1 -2
  83. data/lib/samagotchi/peer_note.rb +38 -5
  84. data/lib/samagotchi/peer_presence.rb +20 -7
  85. data/lib/samagotchi/plugin/api.rb +11 -1
  86. data/lib/samagotchi/plugin/attached_context.rb +46 -1
  87. data/lib/samagotchi/plugin/chips.rb +125 -0
  88. data/lib/samagotchi/plugin/context.rb +43 -8
  89. data/lib/samagotchi/plugin/panes.rb +52 -9
  90. data/lib/samagotchi/plugin/peer_pairing.rb +2 -2
  91. data/lib/samagotchi/plugin/peer_start.rb +61 -36
  92. data/lib/samagotchi/plugin/peers.rb +6 -3
  93. data/lib/samagotchi/plugin/project.rb +63 -0
  94. data/lib/samagotchi/plugin/sessions.rb +36 -1
  95. data/lib/samagotchi/plugin/tool_spec.rb +28 -9
  96. data/lib/samagotchi/schedules.rb +8 -2
  97. data/lib/samagotchi/session.rb +22 -9
  98. data/lib/samagotchi/session_access/local.rb +34 -33
  99. data/lib/samagotchi/session_chain/sharing.rb +79 -0
  100. data/lib/samagotchi/session_chain/successor.rb +4 -2
  101. data/lib/samagotchi/session_chips.rb +133 -0
  102. data/lib/samagotchi/session_inbox_delivery.rb +11 -11
  103. data/lib/samagotchi/session_manager/emptiness.rb +4 -1
  104. data/lib/samagotchi/session_observer.rb +1 -1
  105. data/lib/samagotchi/session_stats.rb +437 -0
  106. data/lib/samagotchi/session_stores.rb +3 -0
  107. data/lib/samagotchi/session_window.rb +30 -0
  108. data/lib/samagotchi/speaker.rb +228 -0
  109. data/lib/samagotchi/steer.rb +36 -132
  110. data/lib/samagotchi/system_one/approval_choice.rb +22 -0
  111. data/lib/samagotchi/system_one/approval_label.rb +4 -6
  112. data/lib/samagotchi/system_prompt.rb +3 -1
  113. data/lib/samagotchi/terminal_ui/attach_launcher.rb +30 -0
  114. data/lib/samagotchi/testing/boundary.rb +17 -4
  115. data/lib/samagotchi/testing/bundle.rb +5 -0
  116. data/lib/samagotchi/testing/host.rb +1 -0
  117. data/lib/samagotchi/testing/recorder.rb +10 -0
  118. data/lib/samagotchi/testing/sessions.rb +11 -3
  119. data/lib/samagotchi/toolkit.rb +11 -4
  120. data/lib/samagotchi/toolkit_report_command.rb +14 -18
  121. data/lib/samagotchi/toolkit_suggest.rb +9 -2
  122. data/lib/samagotchi/tools/registry.rb +48 -18
  123. data/lib/samagotchi/tools/tool_index.rb +6 -2
  124. data/lib/samagotchi/turn_excerpts.rb +302 -0
  125. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +9 -0
  126. data/lib/samagotchi/version.rb +1 -1
  127. data/lib/samagotchi/web/app.rb +21 -10
  128. data/lib/samagotchi/web/participant_view.rb +1 -1
  129. data/lib/samagotchi/web/peer_routes.rb +5 -2
  130. data/lib/samagotchi/web/plugin_chip_rows.rb +39 -0
  131. data/lib/samagotchi/web/public/agent_rows.js +1 -0
  132. data/lib/samagotchi/web/public/app.js +17 -25
  133. data/lib/samagotchi/web/public/chains.js +0 -26
  134. data/lib/samagotchi/web/public/command_list.js +2 -3
  135. data/lib/samagotchi/web/public/composer.js +2 -3
  136. data/lib/samagotchi/web/public/composer_mount.js +3 -6
  137. data/lib/samagotchi/web/public/context_chips.js +240 -93
  138. data/lib/samagotchi/web/public/context_groups.js +84 -0
  139. data/lib/samagotchi/web/public/draft_follow.js +33 -0
  140. data/lib/samagotchi/web/public/drafts.js +26 -22
  141. data/lib/samagotchi/web/public/index.html +32 -0
  142. data/lib/samagotchi/web/public/peer_chip_kind.js +49 -0
  143. data/lib/samagotchi/web/public/peer_note.js +2 -2
  144. data/lib/samagotchi/web/public/peer_row.js +10 -5
  145. data/lib/samagotchi/web/public/peer_wait.js +4 -2
  146. data/lib/samagotchi/web/public/plugin_chip.js +55 -0
  147. data/lib/samagotchi/web/public/plugin_chip_kind.js +48 -0
  148. data/lib/samagotchi/web/public/send_turn.js +8 -21
  149. data/lib/samagotchi/web/public/session_actions.js +10 -23
  150. data/lib/samagotchi/web/public/session_view.js +7 -3
  151. data/lib/samagotchi/web/public/stream_handlers.js +2 -0
  152. metadata +33 -1
@@ -12,8 +12,9 @@ import { popoverPlace, SHEET_MAX, sheetPlace } from "./chip_popover.js";
12
12
  import { focusBack, modalDialog } from "./popover_modal.js";
13
13
  import { cantText } from "./format.js";
14
14
  import { createLatest } from "./latest.js";
15
- import { peerChipModel, peerGroups, peerKey, peerPopoverTemplate } from "./peer_chip.js";
16
- import { waitingChipModel, waitingPopoverTemplate } from "./peer_wait.js";
15
+ import { createPeerChipKind } from "./peer_chip_kind.js";
16
+ import { createPluginChipKind } from "./plugin_chip_kind.js";
17
+ import { groupChipModel, groupListTemplate, groupRows, isGroup } from "./context_groups.js";
17
18
 
18
19
  // "now", "3m", "2h", "4d" since an ISO time; "" for none.
19
20
  export function ageText(iso, now = Date.now()) {
@@ -50,16 +51,19 @@ export function chipModel(rows, now = Date.now()) {
50
51
  // too, so they keep their order). open: the chip whose popover is open (its
51
52
  // key: a source's name, or a peer chip's "peer:<name>", peer_chip.js). A
52
53
  // peer chip (peerChipModel) is drawn as one: class "peer", its dot when it
53
- // says answered.
54
+ // says answered. A chip that opens nothing (opens: false, a bundle's
55
+ // label-only chip) has no popup to announce.
54
56
  export function chipsTemplate(chips, { open = null } = {}) {
55
57
  return html`${chips.map((chip) => html`<button type="button" class=${`ctx-chip${chip.peer ? " peer" : ""} ${chip.state}${chip.name === open ? " open" : ""}`}
56
- data-name=${chip.name} title=${chip.title} aria-haspopup=${"dialog"} aria-expanded=${chip.name === open ? "true" : "false"}>${
58
+ data-name=${chip.name} title=${chip.title} aria-haspopup=${chip.opens === false ? nothing : "dialog"}
59
+ aria-expanded=${chip.opens === false ? nothing : chip.name === open ? "true" : "false"}>${
57
60
  chip.state === "unread" || chip.dot ? html`<span class="ctx-dot" aria-hidden="true"></span>` : nothing}${chip.label}</button>`)}`;
58
61
  }
59
62
 
60
63
  // The popover's inside for one row (GET …/context's); +text+ the row's
61
- // text once "view text" read it (null before).
62
- export function popoverTemplate(row, { text = null, now = Date.now() } = {}) {
64
+ // text once "view text" read it (null before); +back+: the label of the
65
+ // group it was opened from (context_groups.js), a button back to its list.
66
+ export function popoverTemplate(row, { text = null, now = Date.now(), back = null } = {}) {
63
67
  const kind = row.kind === "cmd" ? `runs every ${row.every_seconds ? `${row.every_seconds}s` : "few minutes"}` : "pushed";
64
68
  const url = hintUrl(row.hint);
65
69
  const hint = url
@@ -73,7 +77,9 @@ export function popoverTemplate(row, { text = null, now = Date.now() } = {}) {
73
77
  const detachTitle = row.scope === "project"
74
78
  ? "The project's source: this session stops seeing it (chi context unmute brings it back)"
75
79
  : "Remove it from this session";
76
- return html`<div class="ctx-pop-head"><strong>${row.name}</strong
80
+ return html`<div class="ctx-pop-head">${back === null ? nothing
81
+ : html`<button type="button" class="ctx-back" data-act="back" aria-label=${`Back to ${back}`}>‹ ${back}</button>`
82
+ }<strong>${row.name}</strong
77
83
  ><span class="ctx-pop-kind">${row.scope} · ${kind}</span
78
84
  ><button type="button" class="ctx-pop-close" data-act="close" aria-label="Close">×</button></div
79
85
  >${row.why ? html`<div class="ctx-pop-why">${row.why}</div>` : nothing}${hint}${
@@ -85,8 +91,90 @@ export function popoverTemplate(row, { text = null, now = Date.now() } = {}) {
85
91
  }<button type="button" class="ctx-pop-detach" data-act="detach" title=${detachTitle}>${detach}</button></div>`;
86
92
  }
87
93
 
94
+
95
+ // The chips' kinds. The controller below asks its kinds and never branches
96
+ // on what a chip is; the strip is their chips joined end to end, in the
97
+ // kinds' order. A kind is:
98
+ // - chips(now): its chips now, in order (chipsTemplate's shape, keyed by name);
99
+ // - owns(key): whether a chip key is its own (and known now);
100
+ // - popover(key, {text, now, member}): its popover's inside (+text+: read,
101
+ // or null; +member+: the member open in a chip that lists several, null
102
+ // for its list);
103
+ // - label(key, {member}): the popover's aria-label;
104
+ // - shape: {width, sheet (a bottom sheet in a phone's window), className};
105
+ // - readText(key, {serial, box, member}): {name (for a failure's toast),
106
+ // read()} for "view text", or null (nothing to read);
107
+ // - onLoad(): what a session's open also reads;
108
+ // - ticks(): whether the minute's tick redraws;
109
+ // - keyFor(name): the chip key showText/showMessage open;
110
+ // - onRead(data): GET …/context's answer read (its +sources+, its
111
+ // +chips+); reset(): a session's open or close, or a failed read;
112
+ // - optional: hasMember(key, name), whether +name+ is a member +key+'s
113
+ // popover can open; standsFor(key), the key of the chip drawn now for a
114
+ // key that isn't (a source that joined a group: the group's); opens(key),
115
+ // false for a chip that opens nothing; act(name, target, {close}), a
116
+ // data-act of its own popover, true when it took it.
117
+ // The peer kind is peer_chip_kind.js, the bundles' own chips are
118
+ // plugin_chip_kind.js.
119
+
120
+ // The sources (GET …/context's rows) as a kind, holding the read rows.
121
+ // Two or more of one bundle with a label are one chip, a group
122
+ // (context_groups.js), keyed "group:<provider>": its popover lists them,
123
+ // and a member opens that source's popover with a way back.
124
+ function createSourceKind({ api, sessionId }) {
125
+ let read = [];
126
+ const rows = () => read;
127
+ const rowOf = (name) => rows().find((r) => r.name === name) || null;
128
+ const entries = () => groupRows(rows());
129
+ const groupAt = (key) => entries().find((entry) => isGroup(entry) && entry.key === key) || null;
130
+ const groupWith = (name) => entries().find((entry) => isGroup(entry) && entry.rows.some((r) => r.name === name)) || null;
131
+ // The row +key+'s popover shows: a lone source's; a group's +member+ (null: its list, no row).
132
+ const rowAt = (key, member = null) => {
133
+ const group = groupAt(key);
134
+ return group ? group.rows.find((r) => r.name === member) || null : rowOf(key);
135
+ };
136
+ return {
137
+ chips: (now) => entries().map((entry) => (isGroup(entry) ? groupChipModel(entry, now) : chipModel([entry], now)[0])),
138
+ owns: (key) => !!groupAt(key) || !!rowOf(key),
139
+ popover(key, { text, now, member = null }) {
140
+ const group = groupAt(key);
141
+ if (!group) return popoverTemplate(rowOf(key), { text, now });
142
+ const row = rowAt(key, member);
143
+ return row ? popoverTemplate(row, { text, now, back: group.label }) : groupListTemplate(group, now);
144
+ },
145
+ label: (key, { member = null } = {}) => {
146
+ const group = groupAt(key);
147
+ return group ? rowAt(key, member)?.name || group.label : key;
148
+ },
149
+ shape: Object.freeze({ width: 380, sheet: false, className: null }),
150
+ // A group's list has nothing to read; its member's text is the member's.
151
+ readText(key, { member = null } = {}) {
152
+ const name = groupAt(key) ? rowAt(key, member)?.name : key;
153
+ return name ? { name, read: () => api.show(sessionId(), name) } : null;
154
+ },
155
+ onLoad() {},
156
+ onRead(data) { read = data.sources || []; },
157
+ reset() { read = []; },
158
+ // The ages move on by themselves.
159
+ ticks: () => rows().length > 0,
160
+ // A grouped source opens its group.
161
+ keyFor: (name) => groupWith(name)?.key || name,
162
+ hasMember: (key, name) => !!groupAt(key)?.rows.some((r) => r.name === name),
163
+ // A source that joined a group: the group; a group down to one source: that source.
164
+ standsFor(key) {
165
+ const group = groupAt(key) ? null : groupWith(key);
166
+ if (group) return group.key;
167
+ const lone = entries().filter((entry) => !isGroup(entry) && entry.provider && `group:${entry.provider}` === key);
168
+ return lone.length === 1 ? lone[0].name : null;
169
+ },
170
+ rowAt,
171
+ rows,
172
+ };
173
+ }
174
+
88
175
  // The chips for the session bar. el: #contextChips; api: {list(id),
89
- // show(id, name), detach(id, name)}; toast(text). Chips and popover are
176
+ // show(id, name), detach(id, name), command(id, line): a bundle chip's
177
+ // button (plugin_chip_kind.js)}; toast(text). Chips and popover are
90
178
  // lit templates: a redraw (a refresh, the minute's tick) keeps their nodes,
91
179
  // so focus stays. The
92
180
  // popover behaves as every popover does (popover_modal.js): a modal dialog, its chip's
@@ -105,9 +193,11 @@ export function createContextChips({ el, api, toast = () => {}, peers = () => nu
105
193
  focusAway = () => doc.getElementById("prompt")?.focus?.({ preventScroll: true }),
106
194
  doc = document, win = window }) {
107
195
  let sessionId = null;
108
- let rows = [];
109
- // The chip whose popover is open: its key (a source's name, or "peer:<name>").
196
+ // The chip whose popover is open: its key (a source's name, a group's
197
+ // "group:<provider>", or "peer:<name>").
110
198
  let openKey = null;
199
+ // The member its popover shows (a group's source), null for none (its list).
200
+ let openMember = null;
111
201
  // Only the newest list read for the open session is drawn (latest.js).
112
202
  const latest = createLatest(() => sessionId);
113
203
  // The open popover's text once read (view text; a peer's: a message's).
@@ -119,23 +209,41 @@ export function createContextChips({ el, api, toast = () => {}, peers = () => nu
119
209
  doc.body.appendChild(pop);
120
210
  modalDialog(pop, { isOpen: () => openKey !== null, doc });
121
211
 
122
- const groups = () => peerGroups(peers()?.peers?.() || []);
123
- const groupOf = (key) => groups().find((group) => group.key === key) || null;
124
- const exchangesOf = (name) => peers()?.peer?.(name)?.exchanges || [];
125
- const rowOf = (name) => rows.find((r) => r.name === name) || null;
212
+ const peerKind = createPeerChipKind({ peers, peerActions, api, sessionId: () => sessionId });
213
+ const sourceKind = createSourceKind({ api, sessionId: () => sessionId });
214
+ const pluginKind = createPluginChipKind({ api, sessionId: () => sessionId, toast });
215
+ // Peer chips first, the bundles' own last.
216
+ const kinds = [peerKind, sourceKind, pluginKind];
217
+ const reset = () => kinds.forEach((kind) => kind.reset?.());
218
+ const kindOf = (key) => kinds.find((kind) => kind.owns(key)) || null;
219
+ // A key no kind owns any more (a peer gone while its popover stays open)
220
+ // is placed and read as a source's, as before the kinds.
221
+ const kindAt = (key) => kindOf(key) || sourceKind;
222
+ const popClasses = kinds.map((kind) => kind.shape.className).filter(Boolean);
126
223
 
127
224
  function chips(now = Date.now()) {
128
- // A peer waited for and not paired yet: the waiting chip (peer_wait.js).
129
- const peerChips = groups().map((group) => (group.peer.paired_at ? peerChipModel(group, exchangesOf(group.name), now)
130
- : waitingChipModel(group, now)));
131
- return [...peerChips, ...chipModel(rows, now)];
225
+ return kinds.flatMap((kind) => kind.chips(now));
226
+ }
227
+
228
+ // The chip drawn now for +key+: its own, else the one a kind says
229
+ // stands for it (a source that joined a group: the group's chip).
230
+ function chipFor(key) {
231
+ const find = (name) => [...el.querySelectorAll(".ctx-chip[data-name]")].find((chip) => chip.dataset.name === name);
232
+ const own = find(key);
233
+ if (own || key === null) return own || null;
234
+ const stand = kinds.map((kind) => kind.standsFor?.(key)).find(Boolean);
235
+ return stand ? find(stand) || null : null;
132
236
  }
133
237
 
134
238
  function drawChips() {
135
239
  const drawn = chips();
240
+ const focused = doc.activeElement?.closest?.(".ctx-chip[data-name]");
241
+ const was = focused && el.contains(focused) ? focused.dataset.name : null;
136
242
  // A source inserted before the focused chip: the focus stays on its source.
137
243
  keepFocus(el, "data-name", () => render(chipsTemplate(drawn, { open: openKey }), el));
138
244
  el.hidden = drawn.length === 0;
245
+ // Its chip gone into a group (or a group down to one): the chip that stands for it now.
246
+ if (was !== null && !drawn.some((chip) => chip.name === was)) chipFor(was)?.focus();
139
247
  }
140
248
 
141
249
  // The chips, and the open popover closed when its chip isn't drawn any more.
@@ -144,12 +252,21 @@ export function createContextChips({ el, api, toast = () => {}, peers = () => nu
144
252
  else drawChips();
145
253
  }
146
254
 
147
- // The open popover drawn again from what is known (not while it shows a text).
255
+ // The open popover drawn again from what is known (not while it shows a
256
+ // text); a member that left its group (detached elsewhere, muted) falls
257
+ // back to the group's list.
148
258
  function follow() {
149
- if (openKey === null || text !== null) return;
150
- const group = groupOf(openKey);
151
- const row = group ? null : rowOf(openKey);
152
- if (group || row) fill(group, row);
259
+ if (openKey === null) return;
260
+ const kind = kindOf(openKey);
261
+ if (!kind) return;
262
+ if (openMember !== null && !kind.hasMember?.(openKey, openMember)) {
263
+ openMember = null;
264
+ text = null;
265
+ fill(kind);
266
+ placeAtOpenChip();
267
+ return;
268
+ }
269
+ if (text === null) fill(kind);
153
270
  }
154
271
 
155
272
  async function refresh({ loading = false } = {}) {
@@ -159,49 +276,45 @@ export function createContextChips({ el, api, toast = () => {}, peers = () => nu
159
276
  try {
160
277
  const data = await api.list(id);
161
278
  if (!fresh()) return;
162
- rows = data.sources || [];
279
+ kinds.forEach((kind) => kind.onRead?.(data || {}));
163
280
  } catch {
164
281
  // A session the server doesn't know (gone, or an older chi web): no chips.
165
282
  if (!fresh()) return;
166
- rows = [];
283
+ reset();
167
284
  }
168
285
  draw();
169
286
  // An open popover follows its row, but not while it shows the text.
170
287
  follow();
171
- // The peers for their chips: at a session's open (reuse the
172
- // conversation's read if loaded or in flight).
173
- if (loading) peers()?.refresh?.({ reuse: true });
288
+ // What a session's open also reads (the peers, for their chips).
289
+ if (loading) kinds.forEach((kind) => kind.onLoad());
174
290
  }
175
291
 
176
292
  function load(id) {
177
293
  sessionId = id;
178
- rows = [];
294
+ reset();
179
295
  close();
180
296
  return refresh({ loading: true });
181
297
  }
182
298
 
183
299
  function clear() {
184
300
  sessionId = null;
185
- rows = [];
301
+ reset();
186
302
  close();
187
303
  }
188
304
 
189
- function fill(group, row) {
190
- if (group && !group.peer.paired_at) render(waitingPopoverTemplate(group), pop);
191
- else if (group) {
192
- const actions = peerActions;
193
- render(peerPopoverTemplate(group, exchangesOf(group.name), {
194
- text, status: actions.status?.(group.name) || null, drawn: (id) => !!actions.drawn?.(id),
195
- }), pop);
196
- } else render(popoverTemplate(row, { text }), pop);
305
+ function fill(kind) {
306
+ pop.setAttribute("aria-label", kind.label(openKey, { member: openMember }));
307
+ render(kind.popover(openKey, { text, now: Date.now(), member: openMember }), pop);
197
308
  }
198
309
 
199
310
  // At the chip as the session bar's chips place theirs (popoverPlace):
200
311
  // above it, or below when the room above is short; capped to the room
201
- // (it scrolls), inside the window with a 16px gutter. A peer's popover in
202
- // a phone's window is a bottom sheet (sheetPlace), as scene 2 has it.
312
+ // (it scrolls), inside the window with a 16px gutter. A kind's shape may
313
+ // ask for a bottom sheet (sheetPlace) in a phone's window, as the peer's
314
+ // scene 2 has it.
203
315
  function place(chip) {
204
- const sheet = !!groupOf(openKey) && win.innerWidth < SHEET_MAX;
316
+ const shape = kindAt(openKey).shape;
317
+ const sheet = shape.sheet && win.innerWidth < SHEET_MAX;
205
318
  pop.classList.toggle("sheet", sheet);
206
319
  if (sheet) {
207
320
  const at = sheetPlace({ innerWidth: win.innerWidth, innerHeight: win.innerHeight });
@@ -212,8 +325,7 @@ export function createContextChips({ el, api, toast = () => {}, peers = () => nu
212
325
  pop.style.maxHeight = `${at.maxHeight}px`;
213
326
  return;
214
327
  }
215
- // A peer's is wider: its actions on one line (scene 2).
216
- const width = Math.min(groupOf(openKey) ? 440 : 380, win.innerWidth - 32);
328
+ const width = Math.min(shape.width, win.innerWidth - 32);
217
329
  pop.style.width = `${width}px`;
218
330
  pop.style.maxHeight = "";
219
331
  const at = popoverPlace(chip.getBoundingClientRect(), { width, height: pop.offsetHeight,
@@ -230,16 +342,15 @@ export function createContextChips({ el, api, toast = () => {}, peers = () => nu
230
342
  }
231
343
 
232
344
  function open(key, chip) {
233
- const group = groupOf(key);
234
- const row = group ? null : rowOf(key);
235
- if (!group && !row) return;
345
+ const kind = kindOf(key);
346
+ if (!kind) return;
236
347
  // Another popover's nodes go, so this one starts fresh.
237
348
  render(nothing, pop);
238
349
  openKey = key;
350
+ openMember = null;
239
351
  text = null;
240
- pop.setAttribute("aria-label", group ? group.label : key);
241
- pop.classList.toggle("peer-pop", !!group);
242
- fill(group, row);
352
+ popClasses.forEach((name) => pop.classList.toggle(name, name === kind.shape.className));
353
+ fill(kind);
243
354
  pop.hidden = false;
244
355
  place(chip);
245
356
  drawChips();
@@ -250,39 +361,57 @@ export function createContextChips({ el, api, toast = () => {}, peers = () => nu
250
361
  const back = focusBack(pop, { refocus, doc });
251
362
  const key = openKey;
252
363
  openKey = null;
364
+ openMember = null;
253
365
  text = null;
254
366
  pop.hidden = true;
255
- pop.classList.remove("sheet", "peer-pop");
367
+ pop.classList.remove("sheet", ...popClasses);
256
368
  render(nothing, pop);
257
369
  drawChips();
258
- if (key !== null) back([...el.querySelectorAll(".ctx-chip[data-name]")].find((chip) => chip.dataset.name === key));
370
+ if (key !== null) back(chipFor(key));
371
+ }
372
+
373
+ // A group's member +name+ (its source's popover, with a way back), or
374
+ // its list again (null): drawn and placed, the focus on the way back or
375
+ // on the member's row.
376
+ function showMember(name) {
377
+ const kind = kindOf(openKey);
378
+ if (!kind) return;
379
+ const was = openMember;
380
+ openMember = name;
381
+ text = null;
382
+ // The other view's nodes go.
383
+ render(nothing, pop);
384
+ fill(kind);
385
+ placeAtOpenChip();
386
+ const to = name === null
387
+ ? [...pop.querySelectorAll("[data-member]")].find((row) => row.dataset.member === was)
388
+ : pop.querySelector('[data-act="back"]');
389
+ to?.focus();
259
390
  }
260
391
 
261
- // The open popover's text: a source's, or a peer's message (+serial+;
262
- // default its newest).
392
+ // The open popover's text, as its kind reads it (a source's text; a
393
+ // peer's message +serial+ in +box+, default its newest).
263
394
  async function viewText(serial = null, box = null) {
264
395
  const key = openKey;
396
+ const member = openMember;
265
397
  if (!key) return;
266
- const peer = groupOf(key);
267
- const number = peer ? serial ?? peer.peer.messages?.[0]?.serial : null;
268
- const name = peer ? `${peer.label}'s message #${number}` : key;
269
- if (peer && (number === null || number === undefined)) return;
398
+ const reading = kindAt(key).readText(key, { serial, box, member });
399
+ if (!reading) return;
270
400
  try {
271
- const data = peer ? await api.message(sessionId, peer.name, number, box) : await api.show(sessionId, key);
272
- if (key !== openKey) return;
273
- const group = groupOf(key);
274
- const row = group ? null : rowOf(key);
275
- if (!group && !row) return;
401
+ const data = await reading.read();
402
+ if (key !== openKey || member !== openMember) return;
403
+ const kind = kindOf(key);
404
+ if (!kind) return;
276
405
  text = data.text || "";
277
- fill(group, row);
406
+ fill(kind);
278
407
  // The text makes it taller: placed again.
279
408
  placeAtOpenChip();
280
409
  } catch (e) {
281
- toast(cantText(`read ${name}`, e));
410
+ toast(cantText(`read ${reading.name}`, e));
282
411
  }
283
412
  }
284
413
  async function detach() {
285
- const row = rowOf(openKey);
414
+ const row = sourceKind.rowAt(openKey, openMember);
286
415
  if (!row) return;
287
416
  const ask = row.scope === "project"
288
417
  ? `Mute ${row.name} for this session? It is the project's: other sessions keep it.`
@@ -301,15 +430,15 @@ export function createContextChips({ el, api, toast = () => {}, peers = () => nu
301
430
  // Unpair: one confirm, then the pairing ends (DELETE …/peers/NAME; its
302
431
  // messages stay) and the peers are read again: the chip goes.
303
432
  async function unpair() {
304
- const group = groupOf(openKey);
305
- if (!group) return;
306
- if (!win.confirm(`Unpair ${group.label}? chi stops sending to it; its messages stay.`)) return;
433
+ const peer = peerKind.peerOf(openKey);
434
+ if (!peer) return;
435
+ if (!win.confirm(`Unpair ${peer.label}? chi stops sending to it; its messages stay.`)) return;
307
436
  const id = sessionId;
308
437
  close();
309
438
  try {
310
- await api.unpair(id, group.name);
439
+ await api.unpair(id, peer.name);
311
440
  } catch (e) {
312
- toast(cantText(`unpair ${group.label}`, e));
441
+ toast(cantText(`unpair ${peer.label}`, e));
313
442
  }
314
443
  await peers()?.refresh?.();
315
444
  drawChips();
@@ -319,14 +448,14 @@ export function createContextChips({ el, api, toast = () => {}, peers = () => nu
319
448
  // Cancel (the waiting chip's): the wait ends (DELETE …/peers/NAME, no
320
449
  // confirm: it pairs nothing), the peers are read again and the chip goes.
321
450
  async function cancelWait() {
322
- const group = groupOf(openKey);
323
- if (!group) return;
451
+ const peer = peerKind.peerOf(openKey);
452
+ if (!peer) return;
324
453
  const id = sessionId;
325
454
  close();
326
455
  try {
327
- await api.unpair(id, group.name);
456
+ await api.unpair(id, peer.name);
328
457
  } catch (e) {
329
- toast(cantText(`stop waiting for ${group.label}`, e));
458
+ toast(cantText(`stop waiting for ${peer.label}`, e));
330
459
  }
331
460
  await peers()?.refresh?.();
332
461
  drawChips();
@@ -344,14 +473,18 @@ export function createContextChips({ el, api, toast = () => {}, peers = () => nu
344
473
  }
345
474
 
346
475
  function act(name, target) {
347
- const group = groupOf(openKey);
476
+ // A kind's own (a bundle chip's button).
477
+ if (name !== "close" && kindOf(openKey)?.act?.(name, target, { close })) return;
478
+ const peer = peerKind.peerOf(openKey);
348
479
  if (name === "close") close();
480
+ else if (name === "member") showMember(target.dataset.member);
481
+ else if (name === "back") showMember(null);
349
482
  else if (name === "view") viewText();
350
483
  else if (name === "detach") detach();
351
484
  else if (name === "unpair") unpair();
352
485
  else if (name === "cancel") cancelWait();
353
- else if (name === "status" && group) {
354
- const line = peerActions.status?.(group.name);
486
+ else if (name === "status" && peer) {
487
+ const line = peerActions.status?.(peer.name);
355
488
  close();
356
489
  if (line) peerActions.run?.(line);
357
490
  } else if (name === "jump") {
@@ -366,50 +499,64 @@ export function createContextChips({ el, api, toast = () => {}, peers = () => nu
366
499
  if (!chip) return;
367
500
  // On to the document: a session-bar chip's popover closes (the close
368
501
  // below leaves clicks in +el+ alone).
369
- if (openKey === chip.dataset.name) close();
370
- else open(chip.dataset.name, chip);
502
+ const key = chip.dataset.name;
503
+ // A chip that opens nothing (a bundle's label-only chip) only closes another's.
504
+ if (openKey === key || kindOf(key)?.opens?.(key) === false) close();
505
+ else open(key, chip);
371
506
  });
507
+ let ownClick = null;
372
508
  pop.addEventListener("click", (e) => {
509
+ ownClick = e;
373
510
  const target = e.target.closest("[data-act]");
374
511
  if (target) act(target.dataset.act, target);
375
512
  });
513
+ // A click the popover itself had is inside, even when its act redrew the
514
+ // clicked button away (a group's row, back), as chip_popover.js has it.
376
515
  doc.addEventListener("click", (e) => {
377
- if (openKey && !pop.contains(e.target) && !el.contains(e.target)) close();
516
+ if (openKey && e !== ownClick && !pop.contains(e.target) && !el.contains(e.target)) close();
378
517
  });
379
518
  doc.addEventListener("keydown", (e) => {
380
519
  if (e.key === "Escape" && openKey) close({ refocus: true });
381
520
  });
382
521
  win.addEventListener("resize", placeAtOpenChip);
383
522
  win.addEventListener("focus", () => refresh());
384
- // The ages move on by themselves.
385
- win.setInterval(() => { if (rows.length) drawChips(); }, 60_000);
523
+ // Every minute, when a kind has a chip that moves on by itself.
524
+ win.setInterval(() => { if (kinds.some((kind) => kind.ticks())) drawChips(); }, 60_000);
386
525
 
387
- // The popover of chip +key+ on its text (+serial+: a peer's message), at
388
- // its chip. In a task of its own: the click that asks would close it on
389
- // its way to the document.
390
- function showAt(key, serial = null, box = null) {
526
+ // The popover of chip +key+ on its text (+serial+: a peer's message;
527
+ // +member+: a group's source), at its chip. In a task of its own: the
528
+ // click that asks would close it on its way to the document.
529
+ function showAt(key, { serial = null, box = null, member = null } = {}) {
391
530
  setTimeout(() => {
392
531
  const chip = [...el.querySelectorAll(".ctx-chip[data-name]")].find((c) => c.dataset.name === key);
393
532
  if (!chip) return;
394
533
  chip.scrollIntoView?.({ block: "nearest", inline: "nearest" });
395
534
  if (openKey !== key) open(key, chip);
535
+ if (openKey === key && member !== null && openMember !== member) showMember(member);
396
536
  if (openKey === key && text === null) viewText(serial, box);
397
537
  }, 0);
398
538
  }
399
539
 
400
540
  // +name+'s popover on its text: an older peer answer's "Read the full
401
- // answer" (peer_links.js; its context source, an ordinary chip now).
402
- const showText = (name) => showAt(name);
541
+ // answer" (peer_links.js; its context source, an ordinary chip now). A
542
+ // source in a group opens the group on it.
543
+ const showText = (name) => {
544
+ const key = sourceKind.keyFor(name);
545
+ showAt(key, { member: key === name ? null : name });
546
+ };
403
547
  // Peer +name+'s chip on its message +serial+ (a mailbox note's "Read the
404
548
  // full answer", peer_links.js).
405
- const showMessage = (name, serial, box) => showAt(peerKey(name), serial, box);
549
+ const showMessage = (name, serial, box) => showAt(peerKind.keyFor(name), { serial, box });
406
550
 
407
- // The peers model read again: the chips and an open peer's popover follow it.
408
- function peersChanged() {
551
+ // A kind's model changed (another model's data, not a context read): the
552
+ // chips, and an open popover of that kind, follow it.
553
+ function changed(kind) {
409
554
  if (!sessionId) return;
410
555
  drawChips();
411
- if (groupOf(openKey)) follow();
556
+ if (kind.owns(openKey)) follow();
412
557
  }
558
+ // The peers model read again.
559
+ const peersChanged = () => changed(peerKind);
413
560
 
414
- return { load, clear, refresh, close, showText, showMessage, peersChanged, get rows() { return rows; } };
561
+ return { load, clear, refresh, close, showText, showMessage, peersChanged, get rows() { return sourceKind.rows(); } };
415
562
  }
@@ -0,0 +1,84 @@
1
+ // The context chips' groups (context_chips.js, the source kind): two or more sources of one bundle that names a label
2
+ // (its manifest's context_group:, GET …/context's row `group`, beside `provider`) fold into one chip, "PRs 3 · 2m", at
3
+ // the place of the group's first source; its popover lists them, and a row opens that source's own popover.
4
+ // A lone source of such a bundle, and a source with no bundle or no label, keep their own chip. Pure: rows in,
5
+ // entries and templates out. docs/internals/web-frontend.md, The context chips' groups.
6
+ //
7
+ // It reuses the chips' ageText and chipModel: an import cycle, safe since both sides call each other's functions
8
+ // only at call time (never while loading).
9
+
10
+ import { html, nothing } from "./vendor/lit-html.js";
11
+ import { ageText, chipModel } from "./context_chips.js";
12
+
13
+ // A group chip's key: "group:<provider>" (a source's name never holds ":").
14
+ const KEY_PREFIX = "group:";
15
+
16
+ // GET …/context's rows as the strip's entries, in row order, the muted ones left out: each a lone row, or a group
17
+ // {key: "group:<provider>", label, provider, rows} at its first source's place, for a bundle with a label and two or
18
+ // more of its sources.
19
+ export function groupRows(rows) {
20
+ const shown = (rows || []).filter((row) => row && !row.muted);
21
+ const counts = new Map();
22
+ shown.forEach((row) => { if (row.provider && row.group) counts.set(row.provider, (counts.get(row.provider) || 0) + 1); });
23
+ const groups = new Map();
24
+ const entries = [];
25
+ shown.forEach((row) => {
26
+ if (!row.group || !(counts.get(row.provider) >= 2)) {
27
+ entries.push(row);
28
+ return;
29
+ }
30
+ let group = groups.get(row.provider);
31
+ if (!group) {
32
+ group = { key: `${KEY_PREFIX}${row.provider}`, label: row.group, provider: row.provider, rows: [] };
33
+ groups.set(row.provider, group);
34
+ entries.push(group);
35
+ }
36
+ group.rows.push(row);
37
+ });
38
+ return entries;
39
+ }
40
+
41
+ // Whether an entry of groupRows is a group (a row is not).
42
+ export const isGroup = (entry) => Array.isArray(entry?.rows);
43
+
44
+ // The group's chip (chipsTemplate's shape): "PRs 3 · 2m", the count in its own span. Its age is the newest fetch's,
45
+ // its state the worst of its sources' (error, then unread, then ok; empty only when all are), its dot when any has a
46
+ // change the agent hasn't read.
47
+ export function groupChipModel(group, now = Date.now()) {
48
+ const states = chipModel(group.rows, now).map((chip) => chip.state);
49
+ const state = ["error", "unread"].find((worst) => states.includes(worst))
50
+ || (states.every((each) => each === "empty") ? "empty" : "ok");
51
+ const age = ageText(newest(group.rows), now);
52
+ const count = group.rows.length;
53
+ const failed = states.filter((each) => each === "error").length;
54
+ const why = failed ? `${failed} of them failed their last refresh`
55
+ : group.rows.some((row) => row.unread) ? "a change the agent hasn't read" : "";
56
+ return {
57
+ name: group.key, state, dot: group.rows.some((row) => row.unread && row.has_text),
58
+ label: html`${group.label} <span class="ctx-count">${count}</span>${age ? ` · ${age}` : nothing}`,
59
+ title: [`${count} sources · ${group.provider}`, why].filter(Boolean).join(" · "),
60
+ };
61
+ }
62
+
63
+ // The group's popover: its label, how many and whose, and one row per source (a button: its name, its one-line
64
+ // summary or why its refresh failed, its age and dot). The group has no action of its own.
65
+ export function groupListTemplate(group, now = Date.now()) {
66
+ const chips = chipModel(group.rows, now);
67
+ return html`<div class="ctx-pop-head"><strong>${group.label}</strong
68
+ ><span class="ctx-pop-kind">${group.rows.length} sources · ${group.provider}</span
69
+ ><button type="button" class="ctx-pop-close" data-act="close" aria-label="Close">×</button></div
70
+ ><div class="ctx-group-rows">${group.rows.map((row, i) => {
71
+ const state = chips[i].state;
72
+ const summary = row.error ? `last refresh failed: ${row.error}` : (row.summary || (row.has_text ? "" : "no text yet"));
73
+ return html`<button type="button" class=${`ctx-group-row ${state}`} data-act="member" data-member=${row.name}
74
+ title=${chips[i].title}><span class="ctx-group-name">${row.name}</span><span class="ctx-group-sum">${summary}</span
75
+ ><span class="ctx-group-age">${state === "unread" ? html`<span class="ctx-dot" aria-hidden="true"></span>` : nothing
76
+ }${ageText(row.fetched_at, now)}</span></button>`;
77
+ })}</div>`;
78
+ }
79
+
80
+ // The newest fetched_at of +rows+ (ISO), or null.
81
+ function newest(rows) {
82
+ const times = rows.map((row) => Date.parse(row.fetched_at || "")).filter((at) => !Number.isNaN(at));
83
+ return times.length ? new Date(Math.max(...times)).toISOString() : null;
84
+ }