samagotchi 0.185.0 → 0.187.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 (67) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +37 -1
  3. data/bin/chi +2 -0
  4. data/docs/cli.md +1 -0
  5. data/docs/configuration.md +18 -0
  6. data/docs/guardrails.md +13 -0
  7. data/docs/internals/bridge.md +1 -0
  8. data/docs/internals/engine.md +15 -1
  9. data/docs/internals/inline-widgets.md +18 -0
  10. data/docs/internals/pages.md +172 -0
  11. data/docs/internals/prompt-caching.md +14 -0
  12. data/docs/internals/remote-sessions.md +7 -0
  13. data/docs/internals/web-frontend.md +5 -4
  14. data/docs/memory.md +7 -0
  15. data/docs/pages.md +150 -0
  16. data/docs/thin-clients.md +67 -2
  17. data/lib/samagotchi/bridge.rb +1 -1
  18. data/lib/samagotchi/bundles/system/manifest.yml +5 -2
  19. data/lib/samagotchi/bundles/system/self_map.md +5 -1
  20. data/lib/samagotchi/bundles/system/skill_pages.md +93 -0
  21. data/lib/samagotchi/config.rb +3 -1
  22. data/lib/samagotchi/context_absorber.rb +5 -2
  23. data/lib/samagotchi/engine.rb +9 -2
  24. data/lib/samagotchi/inline_widgets.rb +65 -0
  25. data/lib/samagotchi/llm/chat_loop.rb +16 -2
  26. data/lib/samagotchi/page_command.rb +234 -0
  27. data/lib/samagotchi/pages/builder.rb +187 -0
  28. data/lib/samagotchi/pages/launch.rb +187 -0
  29. data/lib/samagotchi/pages/runner.rb +154 -0
  30. data/lib/samagotchi/pages/store.rb +143 -0
  31. data/lib/samagotchi/pages.rb +119 -0
  32. data/lib/samagotchi/plain_reply.rb +75 -0
  33. data/lib/samagotchi/reply_for.rb +254 -0
  34. data/lib/samagotchi/run_options.rb +1 -0
  35. data/lib/samagotchi/session_access/ask.rb +5 -2
  36. data/lib/samagotchi/session_access/contract.rb +1 -1
  37. data/lib/samagotchi/session_access/exchange/token.rb +42 -7
  38. data/lib/samagotchi/session_access/exchange.rb +5 -2
  39. data/lib/samagotchi/session_access/local.rb +4 -2
  40. data/lib/samagotchi/session_access/remote.rb +5 -1
  41. data/lib/samagotchi/session_manager/delivery.rb +36 -6
  42. data/lib/samagotchi/steer.rb +30 -8
  43. data/lib/samagotchi/turn_anchors.rb +65 -17
  44. data/lib/samagotchi/turn_checkpoint.rb +5 -3
  45. data/lib/samagotchi/version.rb +1 -1
  46. data/lib/samagotchi/web/app.rb +6 -6
  47. data/lib/samagotchi/web/ask_routes.rb +62 -17
  48. data/lib/samagotchi/web/page_routes.rb +116 -0
  49. data/lib/samagotchi/web/participant_access.rb +1 -1
  50. data/lib/samagotchi/web/public/app.js +24 -84
  51. data/lib/samagotchi/web/public/index.html +3 -0
  52. data/lib/samagotchi/web/public/page_blocks.js +58 -0
  53. data/lib/samagotchi/web/public/page_links.js +33 -0
  54. data/lib/samagotchi/web/public/page_model.js +68 -0
  55. data/lib/samagotchi/web/public/page_route.js +24 -0
  56. data/lib/samagotchi/web/public/page_table.js +74 -0
  57. data/lib/samagotchi/web/public/page_table_model.js +76 -0
  58. data/lib/samagotchi/web/public/page_view.js +218 -0
  59. data/lib/samagotchi/web/public/pages.css +77 -0
  60. data/lib/samagotchi/web/public/pages_group.js +65 -0
  61. data/lib/samagotchi/web/public/peer_text.js +22 -5
  62. data/lib/samagotchi/web/public/views.js +161 -0
  63. data/lib/samagotchi/web/session_access_routes.rb +30 -2
  64. data/lib/samagotchi/web/session_control.rb +21 -2
  65. data/lib/samagotchi/web/viewer.rb +1 -1
  66. data/lib/samagotchi/worker.rb +2 -1
  67. metadata +23 -1
@@ -0,0 +1,218 @@
1
+ // The page view, #/p/NAME (docs/pages.md, docs/internals/pages.md): in
2
+ // place of the session area, a page's header (Back, the title, when it ran
3
+ // and how long it took, Refresh, ⋯ with Delete) and its blocks. Opening
4
+ // reads the stored page (GET /api/pages/NAME) and runs nothing; Refresh
5
+ // runs the script (POST …/run, answered when the run ended) and redraws
6
+ // from its answer. A failed run keeps the last result, dimmed, under the
7
+ // failure line; a script changed since the result says so. Nothing is
8
+ // live: a run from a terminal shows after the next open.
9
+ //
10
+ // Made only with the pages capability (app.js; the null-control rule).
11
+ // +root+: #pageView. +api+: data.js api. +toast(text)+, +copyText(text)+:
12
+ // the page's. +back()+: Back (views.js closePage). +gone()+: the page was
13
+ // removed (a Delete, or a Refresh answered "no such page"): views.js leaves
14
+ // for All sessions. +backLabel()+: what Back says ("Sessions" or "Back").
15
+ // +phone()+: the page's phone width now (the table's phone form). The view
16
+ // keeps each table's sort and opened rows (page_table.js) until another
17
+ // page opens.
18
+ import { html, nothing, render } from "./vendor/lit-html.js";
19
+ import { createLatest } from "./latest.js";
20
+ import { cantText } from "./format.js";
21
+ import { blocksTemplate, drawWalks } from "./page_blocks.js";
22
+ import { tableTemplate } from "./page_table.js";
23
+ import { nextSort } from "./page_table_model.js";
24
+ import { changedText, errorCopy, failureParts, keptAfterFailure, metaText } from "./page_model.js";
25
+
26
+ const PAGE_NAME = /^[a-z0-9][a-z0-9-]{0,39}$/;
27
+
28
+ export function createPageView({
29
+ root, api, toast = () => {}, copyText = async () => false, back = () => {}, gone = () => {},
30
+ backLabel = () => "Sessions", phone = () => false, doc = document, win = window, now = () => Date.now(),
31
+ }) {
32
+ // The page open now: {name, status: "loading" | "ready" | "missing" |
33
+ // "error", page, error, running, stderr, menu: "closed" | "open" |
34
+ // "confirm", deleting, sorts: {block index: {index, dir}}, opened: {block
35
+ // index: Set of rows}}; null while closed.
36
+ let view = null;
37
+ const runs = new Map();
38
+ const latest = createLatest(() => view?.name ?? null);
39
+ const path = (name) => `/api/pages/${encodeURIComponent(name)}`;
40
+
41
+ function draw() {
42
+ if (!view) {
43
+ render(nothing, root);
44
+ return;
45
+ }
46
+ render(template(view), root);
47
+ drawWalks(root, { doc, win });
48
+ }
49
+
50
+ function set(fields) {
51
+ view = { ...view, ...fields };
52
+ draw();
53
+ }
54
+
55
+ async function open(name) {
56
+ if (view?.name === name) return;
57
+ const run = runs.get(name);
58
+ const valid = PAGE_NAME.exec(name)?.[0] === name;
59
+ view = { name, status: valid ? "loading" : "missing", page: null, error: null, running: !!run, stderr: "", menu: "closed", deleting: false,
60
+ sorts: {}, opened: {} };
61
+ draw();
62
+ if (!valid) return;
63
+ const fresh = latest.begin();
64
+ try {
65
+ const page = await api(path(name));
66
+ if (!fresh() || run?.answered) return;
67
+ set({ status: "ready", page });
68
+ } catch (error) {
69
+ if (!fresh()) return;
70
+ set(error.code === "page_missing" ? { status: "missing" } : { status: "error", error });
71
+ }
72
+ }
73
+
74
+ function close() {
75
+ latest.drop();
76
+ view = null;
77
+ draw();
78
+ }
79
+
80
+ async function refresh() {
81
+ if (!view || view.running || view.status !== "ready") return;
82
+ const name = view.name;
83
+ const run = { answered: false };
84
+ runs.set(name, run);
85
+ set({ running: true, menu: "closed" });
86
+ const still = () => view?.name === name;
87
+ try {
88
+ const page = await api(`${path(name)}/run`, { method: "POST" });
89
+ run.answered = true;
90
+ if (runs.get(name) === run) runs.delete(name);
91
+ if (!still()) return;
92
+ const sorts = Object.fromEntries(Object.entries(view.sorts).filter(([index]) => {
93
+ const before = view.page?.blocks?.[index]?.columns;
94
+ const after = page.blocks?.[index]?.columns;
95
+ return Array.isArray(before) && Array.isArray(after) && before.length === after.length;
96
+ }));
97
+ set({ status: "ready", running: false, page, stderr: page.stderr || "", sorts, opened: {} });
98
+ } catch (error) {
99
+ if (runs.get(name) === run) runs.delete(name);
100
+ if (!still()) return;
101
+ set({ running: false });
102
+ if (error.code === "page_missing") {
103
+ toast(error.message);
104
+ gone();
105
+ } else if (error.code === "page_busy" || error.code === "server_stopping") {
106
+ toast(error.message);
107
+ } else {
108
+ toast(cantText("refresh the page", error));
109
+ }
110
+ }
111
+ }
112
+
113
+ async function remove() {
114
+ if (!view || view.deleting) return;
115
+ const name = view.name;
116
+ const title = view.page?.title || name;
117
+ set({ deleting: true });
118
+ try {
119
+ await api(path(name), { method: "DELETE" });
120
+ if (view?.name !== name) return;
121
+ toast(`Deleted the page ${title}`);
122
+ gone();
123
+ } catch (error) {
124
+ if (view?.name !== name) return;
125
+ set({ deleting: false, menu: "closed" });
126
+ if (error.code === "page_missing") gone();
127
+ toast(error.code === "page_busy" ? error.message : cantText("delete the page", error));
128
+ }
129
+ }
130
+
131
+ async function copyError() {
132
+ const ok = await copyText(errorCopy(view.page, view.stderr));
133
+ toast(ok ? "Copied the error" : "Can't copy here");
134
+ }
135
+
136
+ function menuTemplate(v) {
137
+ if (v.menu === "closed") return nothing;
138
+ if (v.menu === "confirm") {
139
+ return html`<div class="pg-menu" role="menu">
140
+ <span class="pg-confirm">Delete this page?</span>
141
+ <button type="button" class="pg-delete danger" role="menuitem" ?disabled=${v.deleting} @click=${remove}>${v.deleting ? "Deleting…" : "Delete"}</button>
142
+ <button type="button" class="ghost" role="menuitem" @click=${() => set({ menu: "closed" })}>Cancel</button>
143
+ </div>`;
144
+ }
145
+ return html`<div class="pg-menu" role="menu">
146
+ <button type="button" class="pg-delete-ask" role="menuitem" @click=${() => set({ menu: "confirm" })}>Delete</button>
147
+ </div>`;
148
+ }
149
+
150
+ function headTemplate(v, page) {
151
+ const meta = page ? metaText(page, now()) : null;
152
+ const title = page?.title || v.name;
153
+ const ready = v.status === "ready";
154
+ return html`<div class="pg-head">
155
+ <button type="button" class="pg-back ghost" @click=${back}>← ${backLabel()}</button>
156
+ <h1 class="pg-title">${title}</h1>
157
+ ${meta ? html`<span class="pg-meta">${meta}</span>` : nothing}
158
+ ${ready ? html`<span class="pg-actions">
159
+ <button type="button" class="pg-refresh primary" ?disabled=${v.running} @click=${refresh}>${v.running ? "Running…" : "Refresh"}</button>
160
+ <span class="pg-more">
161
+ <button type="button" class="pg-menu-btn ghost" aria-label="More" title="More" aria-haspopup="menu"
162
+ aria-expanded=${v.menu === "closed" ? "false" : "true"}
163
+ @click=${() => set({ menu: v.menu === "closed" ? "open" : "closed" })}>⋯</button>
164
+ ${menuTemplate(v)}
165
+ </span>
166
+ </span>` : nothing}
167
+ </div>`;
168
+ }
169
+
170
+ function linesTemplate(page) {
171
+ const failed = failureParts(page);
172
+ const changed = changedText(page, now());
173
+ return html`${failed ? html`<div class="pg-line pg-failed" role="status">
174
+ ${failed.lead}<code>${failed.message}</code>.${failed.tail}
175
+ <button type="button" class="pg-copy ghost" @click=${copyError}>Copy the error</button>
176
+ </div>` : nothing}
177
+ ${changed ? html`<div class="pg-line pg-changed" role="status">${changed}</div>` : nothing}`;
178
+ }
179
+
180
+ function bodyTemplate(v) {
181
+ if (v.status === "loading") return html`<div class="pg-note">Loading…</div>`;
182
+ if (v.status === "missing") return html`<div class="pg-note">There is no page called ${v.name}.</div>`;
183
+ if (v.status === "error") return html`<div class="pg-note">${cantText("read the page", v.error)}</div>`;
184
+ const page = v.page;
185
+ const kept = keptAfterFailure(page);
186
+ const table = (block, index) => tableTemplate(block, {
187
+ phone: phone(),
188
+ sort: v.sorts[index] || null,
189
+ onSort: (column, numeric) => set({ sorts: { ...v.sorts, [index]: nextSort(v.sorts[index], column, numeric) } }),
190
+ opened: v.opened[index] || new Set(),
191
+ onToggle: (row) => {
192
+ const opened = new Set(view.opened[index] || []);
193
+ if (opened.has(row)) opened.delete(row);
194
+ else opened.add(row);
195
+ set({ opened: { ...view.opened, [index]: opened } });
196
+ },
197
+ });
198
+ const blocks = page.ran_at ? blocksTemplate(page.blocks, { table }) : nothing;
199
+ return html`${linesTemplate(page)}
200
+ ${page.ran_at ? html`<div class="pg-blocks ${kept ? "pg-kept" : ""}">${blocks}</div>`
201
+ : html`<div class="pg-note">No result yet${page.state === "failed" ? "" : ": Refresh runs the script"}.</div>`}`;
202
+ }
203
+
204
+ function template(v) {
205
+ return html`${headTemplate(v, v.status === "ready" ? v.page : null)}${bodyTemplate(v)}`;
206
+ }
207
+
208
+ // A click outside the open menu closes it (one inside it that redrew it
209
+ // has a target no longer in the page: not outside).
210
+ doc.addEventListener("click", (e) => {
211
+ if (!view || view.menu === "closed" || !e.target?.isConnected || e.target.closest?.(".pg-more")) return;
212
+ set({ menu: "closed" });
213
+ });
214
+ // The phone's table form follows the width.
215
+ win.matchMedia?.("(max-width: 600px)")?.addEventListener?.("change", () => view && draw());
216
+
217
+ return { open, close, refresh, name: () => view?.name ?? null };
218
+ }
@@ -0,0 +1,77 @@
1
+ /* A page, #/p/NAME (page_view.js): in place of the session area, the strip and All sessions while body.page-view.
2
+ The view scrolls down inside itself; it never scrolls sideways: a wide table or a walk's lanes scroll in their own box.
3
+ Colours are the :root tokens only (tokens.css). */
4
+ #pageView{display:none;flex:1;min-height:0;min-width:0;flex-direction:column;gap:12px;overflow-y:auto;overflow-x:hidden;padding:2px 2px 24px}
5
+ body.page-view #pageView{display:flex}
6
+ body.page-view :is(#center,#topStrip,#stripGrip,#allView,#sessionTitleRow){display:none}
7
+ .pg-head{display:flex;flex-wrap:wrap;align-items:center;gap:8px 12px}
8
+ .pg-back{flex:none;padding:5px 10px;font-size:13px;color:var(--accent);background:transparent;border:1px solid transparent}
9
+ @media(hover:hover){.pg-back:hover{filter:none;border-color:var(--border-strong)}}
10
+ .pg-title{flex:1 1 160px;min-width:0;margin:0;font-size:17px;font-weight:650;line-height:1.3;color:var(--text);overflow-wrap:anywhere}
11
+ .pg-meta{font-size:12px;color:var(--text-muted);white-space:nowrap}
12
+ .pg-actions{display:flex;align-items:center;gap:8px;flex:none}
13
+ .pg-actions button{padding:6px 12px;font-size:12px;font-weight:600;border-radius:8px}
14
+ .pg-refresh:disabled{opacity:.7;cursor:default}
15
+ .pg-menu-btn{border:1px solid var(--border-strong)}
16
+ .pg-more{position:relative}
17
+ .pg-menu{position:absolute;right:0;top:calc(100% + 6px);z-index:20;display:flex;align-items:center;gap:8px;padding:8px;white-space:nowrap;background:var(--bg-panel);border:1px solid var(--border-strong);border-radius:10px;box-shadow:var(--shadow-strong)}
18
+ .pg-menu .pg-delete-ask{background:transparent;color:var(--danger-text);border:1px solid transparent}
19
+ .pg-menu .pg-delete{background:var(--danger-bg-dim);color:var(--danger-text);border:1px solid var(--danger)}
20
+ .pg-confirm{font-size:12.5px;color:var(--text-2)}
21
+ .pg-line{border:1px solid var(--warn-border);background:var(--warn-bg);color:var(--warn-text);border-radius:8px;padding:8px 10px;font-size:12.5px;line-height:1.5;overflow-wrap:anywhere}
22
+ .pg-line code{font:12px ui-monospace,SFMono-Regular,Menlo,monospace}
23
+ .pg-line .pg-copy{margin-left:6px;padding:3px 9px;font-size:12px;border:1px solid var(--border-strong)}
24
+ .pg-blocks{display:flex;flex-direction:column;gap:12px;min-width:0}
25
+ .pg-kept{opacity:.62}
26
+ .pg-text{color:var(--text-2);font-size:13.5px;line-height:1.5;min-width:0;overflow-wrap:anywhere}
27
+ .pg-plain{white-space:pre-wrap}
28
+ .pg-text.markdown pre{overflow:auto;padding:10px;border-radius:8px;background:var(--bg-inset);border:1px solid var(--border)}
29
+ .pg-text.markdown :not(pre)>code{background:var(--bg-inset);border:1px solid var(--border);border-radius:4px;padding:1px 3px}
30
+ .pg-text.markdown a{color:var(--accent)}
31
+ .pg-walk{display:block;min-width:0;max-width:100%;overflow-x:auto}
32
+ .pg-note,.pg-unknown{font-size:12.5px;color:var(--text-muted)}
33
+ /* A table (page_table.js): desktop's real table in a box of its own that scrolls sideways; the phone's rows that open. */
34
+ .pg-table{display:flex;flex-direction:column;gap:6px;min-width:0}
35
+ .pg-scroll{overflow-x:auto;border:1px solid var(--border);border-radius:10px;background:var(--bg-panel)}
36
+ .pg-scroll table{border-collapse:collapse;width:100%;font-size:12.5px;font-variant-numeric:tabular-nums}
37
+ .pg-scroll th,.pg-scroll td{padding:7px 10px;text-align:left;white-space:nowrap;border-bottom:1px solid var(--border)}
38
+ .pg-scroll :is(th,td).pg-num{text-align:right}
39
+ .pg-scroll th{font-weight:600;color:var(--text-muted);background:var(--bg-inset);padding:0}
40
+ .pg-scroll th[aria-sort]{color:var(--accent)}
41
+ .pg-sort{all:unset;box-sizing:border-box;display:block;width:100%;padding:7px 10px;cursor:pointer;text-align:inherit;font:inherit;color:inherit}
42
+ .pg-sort:focus-visible{outline:2px solid var(--accent);outline-offset:-2px}
43
+ @media(hover:hover){.pg-sort:hover{color:var(--text-2)}}
44
+ .pg-scroll tfoot td{font-weight:650;border-bottom:0;border-top:1px solid var(--border-strong);color:var(--text)}
45
+ .pg-scroll tbody tr:last-child td{border-bottom:0}
46
+ .pg-blank{color:var(--text-faint)}
47
+ .pg-rows{border:1px solid var(--border);border-radius:10px;background:var(--bg-panel);font-variant-numeric:tabular-nums}
48
+ .pg-row{border-bottom:1px solid var(--border)}
49
+ .pg-row:last-child{border-bottom:0}
50
+ .pg-row.open{background:var(--bg-hover)}
51
+ .pg-row-main{all:unset;box-sizing:border-box;display:grid;grid-template-columns:minmax(0,1fr) repeat(var(--pg-keys,0),auto);gap:4px 14px;align-items:baseline;width:100%;padding:9px 12px;font-size:13px;color:var(--text)}
52
+ button.pg-row-main{cursor:pointer}
53
+ button.pg-row-main:focus-visible{outline:2px solid var(--accent);outline-offset:-2px}
54
+ .pg-k{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
55
+ .pg-kv{text-align:right;white-space:nowrap}
56
+ .pg-lab{display:block;font-size:10.5px;color:var(--text-faint)}
57
+ .pg-total .pg-row-main{font-weight:650}
58
+ .pg-cells{display:grid;grid-template-columns:1fr 1fr;gap:2px 16px;padding:0 12px 9px;font-size:12px;color:var(--text-2)}
59
+ .pg-cells span{display:flex;justify-content:space-between;gap:8px;min-width:0}
60
+ .pg-cells em{font-style:normal;color:var(--text-muted)}
61
+ @media(max-width:600px){
62
+ .pg-head{gap:6px 8px}
63
+ .pg-title{flex:1 1 0}
64
+ /* The meta wraps under the title, on a line of its own. */
65
+ .pg-meta{order:5;flex-basis:100%;white-space:normal}
66
+ }
67
+ /* All sessions' Pages group (pages_group.js): one row of cards that scrolls sideways, over a "Sessions" heading. Its own
68
+ card rules: the session cards' are scoped to #allList .card. */
69
+ #pagesGroup{display:flex;flex-direction:column;gap:8px;flex:none;min-width:0}
70
+ #pagesGroup[hidden]{display:none}
71
+ .pg-group-label{font-size:11px;font-weight:600;line-height:1;letter-spacing:.06em;text-transform:uppercase;color:var(--text-faint)}
72
+ .pg-cards{display:flex;gap:8px;overflow-x:auto;padding-bottom:2px;scrollbar-width:thin}
73
+ .pg-card{all:unset;box-sizing:border-box;flex:0 0 190px;display:flex;flex-direction:column;gap:2px;min-width:0;padding:9px 11px;border:1px solid var(--accent-border);border-radius:10px;background:var(--bg-panel);font-size:12.5px;color:var(--text-muted);cursor:pointer}
74
+ .pg-card b{display:block;font-size:13px;color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
75
+ .pg-card:focus-visible{outline:2px solid var(--accent);outline-offset:1px}
76
+ @media(hover:hover){.pg-card:hover{border-color:var(--accent);background:var(--bg-hover)}}
77
+ @media(max-width:600px){.pg-card{flex-basis:160px}}
@@ -0,0 +1,65 @@
1
+ // All sessions' Pages group (decision D1 A, docs/pages.md): above the
2
+ // session cards, one row of page cards that scrolls sideways (it never takes
3
+ // more than a row of a phone's first screen), each with its title and "ran 2
4
+ // min ago", "failed 1 h ago" or "never ran"; a tap opens the page. A
5
+ // "Sessions" heading sits over the session cards while the group shows. It
6
+ // is read when All sessions opens (GET /api/pages) and filtered by the
7
+ // search field (#filter) by name and title; with no page, or none the search
8
+ // matches, the group and its heading are not there. Not live: a page made
9
+ // meanwhile shows the next time All sessions opens.
10
+ //
11
+ // Made only with the pages capability (app.js). +root+: #pagesGroup.
12
+ // +filterEl+: #filter. +api+: data.js api. +open(name)+: views.js openPage.
13
+ import { html, nothing, render } from "./vendor/lit-html.js";
14
+ import { createLatest } from "./latest.js";
15
+ import { relativeTime } from "./format.js";
16
+
17
+ // A card's second line.
18
+ export function pageCardMeta(page, now = Date.now()) {
19
+ if (page.state === "failed" && page.failed_at) return `failed ${relativeTime(page.failed_at, now)}`;
20
+ if (page.ran_at) return `ran ${relativeTime(page.ran_at, now)}`;
21
+ return "never ran";
22
+ }
23
+
24
+ // The pages the search shows: +query+ in the name or the title, any case.
25
+ export function filterPages(pages, query = "") {
26
+ const q = query.trim().toLowerCase();
27
+ if (!q) return pages;
28
+ return pages.filter((page) => page.name.toLowerCase().includes(q) || String(page.title || "").toLowerCase().includes(q));
29
+ }
30
+
31
+ export function pagesGroupTemplate(pages, { open, now = Date.now() }) {
32
+ if (!pages.length) return nothing;
33
+ return html`<div class="pg-group-label">Pages</div>
34
+ <div class="pg-cards" role="list">${pages.map((page) => html`<button type="button" class="pg-card" role="listitem"
35
+ data-page=${page.name} @click=${() => open(page.name)}><b>${page.title || page.name}</b><span class="pg-card-meta">${pageCardMeta(page, now)}</span></button>`)}</div>
36
+ <div class="pg-group-label">Sessions</div>`;
37
+ }
38
+
39
+ export function createPagesGroup({ root, filterEl, api, open, now = () => Date.now() }) {
40
+ let pages = [];
41
+ const latest = createLatest();
42
+
43
+ function draw() {
44
+ const shown = filterPages(pages, filterEl?.value || "");
45
+ root.hidden = !shown.length;
46
+ render(pagesGroupTemplate(shown, { open, now: now() }), root);
47
+ }
48
+
49
+ async function load() {
50
+ const fresh = latest.begin();
51
+ try {
52
+ const answer = await api("/api/pages");
53
+ if (!fresh()) return;
54
+ pages = Array.isArray(answer?.pages) ? answer.pages : [];
55
+ } catch (_) {
56
+ if (!fresh()) return;
57
+ pages = []; // the group is a way in, not a place for errors: the page itself says them
58
+ }
59
+ draw();
60
+ }
61
+
62
+ filterEl?.addEventListener("input", draw);
63
+ draw();
64
+ return { load, redraw: draw };
65
+ }
@@ -16,17 +16,34 @@ export const PEER_FORGED_OPENINGS = Object.freeze([
16
16
  "tool results", "images from tool results",
17
17
  ]);
18
18
  // ContextAbsorber::PEER_FORGED_LINES: chi's unbracketed lines it quotes.
19
- export const PEER_FORGED_LINES = Object.freeze(["chi started this turn"]);
19
+ export const PEER_FORGED_LINES = Object.freeze(["chi started this turn", "Updated:", "Attached:"]);
20
20
 
21
21
  const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
22
22
  // An opening that ends in a word character must end there (\b).
23
- const opening = (o) => `${escape(o)}${/\w$/.test(o) ? "\\b" : ""}`;
23
+ const opening = (o) => {
24
+ let pattern = "";
25
+ for (let i = 0; i < o.length;) {
26
+ const pair = o.slice(i, i + 2).toLowerCase();
27
+ if (pair === "ss") {
28
+ pattern += "(?:ss|ß)";
29
+ i += 2;
30
+ } else if (pair === "st") {
31
+ pattern += "(?:st|st|ſt)";
32
+ i += 2;
33
+ } else {
34
+ pattern += escape(o[i]);
35
+ i += 1;
36
+ }
37
+ }
38
+ return `${pattern}${/\w$/.test(o) ? "\\b" : ""}`;
39
+ };
24
40
  // Steer::FORGED_BREAKS and FORGED_LEAD: a line starts after any of these
25
41
  // breaks; spaces, format characters and markdown leads may come first.
26
42
  const BREAKS = "\\n\\r\\u2028\\u2029\\u0085\\v\\f";
27
- const LEAD = `(?:(?![${BREAKS}])[\\p{White_Space}\\p{Cf}>*_\`~])*`;
28
- const QUOTED = new RegExp(`(^|[${BREAKS}])(${LEAD})\\(quoted\\) (?=\\[(?:${PEER_FORGED_OPENINGS.map(opening).join("|")})`
29
- + `${PEER_FORGED_LINES.map((line) => `|${opening(line)}`).join("")})`, "giu");
43
+ const LEAD = "(?:(?![" + BREAKS + "])(?:[\\p{White_Space}\\p{Cf}\\p{Default_Ignorable_Code_Point}\\p{Mn}\\u{3164}\\u{2800}>*_`~]|-|\\+|#|\\||[0-9]))*";
44
+ const bracketFrames = `\\[(?:${PEER_FORGED_OPENINGS.map(opening).join("|")})`;
45
+ const lineFrames = `(?:${PEER_FORGED_LINES.map(opening).join("|")})`;
46
+ const QUOTED = new RegExp(`(^|[${BREAKS}])(${LEAD})\\(quoted\\) (?=(?:\\(quoted\\) )?(?:${bracketFrames}|${lineFrames}))`, "giu");
30
47
  const OPEN = /^\[PEER MESSAGE from [^\]\n]*\]$/;
31
48
  const CLOSE = "[END PEER MESSAGE]";
32
49
 
@@ -0,0 +1,161 @@
1
+ // The page's views by hash: All sessions, its own view at #/sessions so the
2
+ // browser's back button leaves it, and the open session's #/s/<id>, so a
3
+ // reload or a copied link opens it again. A hash typed, pasted or reached by
4
+ // back selects what it names (hashIntent). Opened from the page, All sessions
5
+ // closes with history.back(). A page, #/p/NAME (page_view.js), is read here
6
+ // before the session intent (hashIntent calls it "keep"): it shows in place
7
+ // of the session area, and the session's hash isn't written while it is
8
+ // open. app.js makes this once its pieces exist and hands the functions on
9
+ // (lazily to anything made before it).
10
+ //
11
+ // +win+ / +doc+: the window (location, history, the hashchange listener) and
12
+ // the document. +participant+: the participant's page (createParticipantMain),
13
+ // or null on the owner's. +store+: the session store (selected, sessions,
14
+ // update). +lists+: lists_view.js (selecting, leaveSelect, chainPop,
15
+ // familyPop). +topStripEl+: #topStrip. +pictures+: the picture viewer.
16
+ // +eventsLive()+: the hub's stream is open. +refresh()+, +updateSessionTitle()+,
17
+ // +select(id)+, +clearSelection()+: the page's. +ownerClaim()+: owner_claim.js's
18
+ // (made after this, so a getter). +pages+: page_view.js's view, or null
19
+ // without the pages capability (then no hash is a page). +allViewOpened()+:
20
+ // All sessions just opened (the Pages group reads its list then).
21
+ import { ALL_SESSIONS_HASH, sessionHash } from "./route.js";
22
+ import { hashIntent } from "./hash_intent.js";
23
+ import { claimFromHash } from "./claim_link.js";
24
+ import { sortedByUpdated } from "./sessions_list.js";
25
+ import { openPageName, pageHash } from "./page_route.js";
26
+
27
+ export function createViews({
28
+ win = globalThis, doc = globalThis.document, participant, store, lists, topStripEl, pictures, eventsLive,
29
+ refresh, updateSessionTitle, select, clearSelection, ownerClaim, pages = null, allViewOpened = () => {},
30
+ }) {
31
+ const { location, history } = win;
32
+ const $ = (sel) => doc.querySelector(sel);
33
+ let allViewPushed = false;
34
+ // A page this page opened itself (a Pages card, an answer's link): Back is
35
+ // history.back(), to where it was opened from ("sessions" or "back").
36
+ let pagePushed = null;
37
+
38
+ // The page the hash opens, or null.
39
+ function pageOpen() {
40
+ return openPageName(location.hash, { participant, canPages: !!pages });
41
+ }
42
+ function openPage(name) {
43
+ if (pageOpen() === name) return;
44
+ pagePushed = allViewOpen() ? "sessions" : "back";
45
+ location.hash = pageHash(name);
46
+ }
47
+ // Back: where the page was opened from, else All sessions.
48
+ function closePage() {
49
+ if (!pageOpen()) return;
50
+ if (pagePushed) history.back();
51
+ else leaveAllView(ALL_SESSIONS_HASH);
52
+ }
53
+ // The page went (deleted, or no such page on Refresh): All sessions, in
54
+ // its history entry.
55
+ function leavePage() {
56
+ if (pageOpen()) leaveAllView(ALL_SESSIONS_HASH);
57
+ }
58
+ function pageBackLabel() {
59
+ return pagePushed === "back" ? "Back" : "Sessions";
60
+ }
61
+
62
+ function allViewOpen() {
63
+ return !participant && location.hash === ALL_SESSIONS_HASH;
64
+ }
65
+ function openAllView() {
66
+ if (allViewOpen()) return;
67
+ allViewPushed = true;
68
+ location.hash = ALL_SESSIONS_HASH;
69
+ }
70
+ function closeAllView() {
71
+ if (!allViewOpen()) return;
72
+ if (allViewPushed) {
73
+ history.back();
74
+ } else {
75
+ leaveAllView(sessionHash(store.selected));
76
+ }
77
+ }
78
+ // Leave all sessions, or a page, for a place of our own (a picked session,
79
+ // a new session, All sessions after a page's Delete): replace its history
80
+ // entry, since history.back() would come back later with the session the
81
+ // view was opened from.
82
+ function leaveAllView(hash) {
83
+ history.replaceState(null, "", location.pathname + location.search + hash);
84
+ allViewPushed = false;
85
+ applyView();
86
+ }
87
+ // The open session in the URL, so a reload or a copied link opens it again.
88
+ // Switching sessions replaces the entry; only all sessions pushes one.
89
+ // A page open: a session picked (a continue, a created session) leaves the
90
+ // page for it; the selection cleared under it (a gone session) doesn't.
91
+ function setSessionHash(id) {
92
+ if (allViewOpen()) return;
93
+ if (pageOpen()) {
94
+ if (id) leaveAllView(sessionHash(id));
95
+ return;
96
+ }
97
+ const hash = sessionHash(id);
98
+ if (location.hash === hash || (!hash && !location.hash)) return;
99
+ history.replaceState(null, "", location.pathname + location.search + hash);
100
+ }
101
+ // A #/s/<id> typed or pasted into the address bar, or reached by back.
102
+ // A claim link (claim_link.js; #/s/<id>?t=…&q=…, or the participant's
103
+ // #s=<id>&t=… opened in this browser) opens its session and, once drawn,
104
+ // shows the claim. The start page's own hash ("#/", or none) while one is
105
+ // open is the start page: the same clear the + button does, so the page and
106
+ // the composer stop addressing the session the URL has left behind.
107
+ function selectFromHash() {
108
+ const claim = claimFromHash(location.hash);
109
+ if (claim) ownerClaim().pending(claim);
110
+ // A participant's page has one session, whatever the hash names.
111
+ const intent = participant ? { kind: "session", id: participant.sessionId } : hashIntent(location.hash, { selected: store.selected, claim });
112
+ if (intent.kind === "session" && intent.id !== store.selected) select(intent.id);
113
+ else if (claim) ownerClaim().showPending();
114
+ else if (intent.kind === "start") clearSelection();
115
+ }
116
+ function applyView() {
117
+ const open = allViewOpen();
118
+ const page = pageOpen();
119
+ doc.body.classList.toggle("page-view", !!page);
120
+ if (page) {
121
+ pictures.close(); // #center, the picture viewer's parent, is hidden there
122
+ pages.open(page);
123
+ } else {
124
+ pagePushed = null;
125
+ pages?.close();
126
+ }
127
+ if (!open && !page) {
128
+ allViewPushed = false;
129
+ }
130
+ if (!open) {
131
+ // A running batch ends on its own and clears the picks then.
132
+ if (lists.selecting.on && !lists.selecting.running) lists.leaveSelect();
133
+ topStripEl.scrollLeft = 0; // a phone's strip scrolls sideways to the tile
134
+ }
135
+ doc.body.classList.toggle("all-view", open);
136
+ // The sessions pill is the view's button there: pressed while it is open.
137
+ $("#stripStatus").setAttribute("aria-pressed", String(open));
138
+ updateSessionTitle();
139
+ // Its chip was in the list just hidden (the strip, or all sessions).
140
+ lists.chainPop.close();
141
+ if (open) {
142
+ lists.familyPop.close(); pictures.close(); // the strip and #center (the picture viewer's parent) are hidden there
143
+ // The list is live; only its order can lag (upserts keep cards in
144
+ // place), so the all view opens in the server's order.
145
+ // A new list: the lists' redraw draws the all view (lists.render).
146
+ store.update({ sessions: sortedByUpdated(store.sessions) });
147
+ if (!eventsLive()) refresh();
148
+ allViewOpened();
149
+ $("#filter").select();
150
+ }
151
+ }
152
+ win.addEventListener("hashchange", () => {
153
+ applyView();
154
+ selectFromHash();
155
+ });
156
+
157
+ return {
158
+ allViewOpen, openAllView, closeAllView, leaveAllView, setSessionHash, selectFromHash, applyView,
159
+ pageOpen, openPage, closePage, leavePage, pageBackLabel,
160
+ };
161
+ }
@@ -5,6 +5,8 @@ require_relative "../session_access/local"
5
5
  require_relative "../session_inbox"
6
6
  require_relative "../reply_wait"
7
7
  require_relative "../pending_question"
8
+ require_relative "../plain_reply"
9
+ require_relative "../reply_for"
8
10
  require_relative "../context_sources"
9
11
  require_relative "../peer_exchanges"
10
12
  require_relative "../context_command"
@@ -183,6 +185,25 @@ module Samagotchi
183
185
  question: busy.question&.to_file, parent_strategy: (strategy_json(busy.strategy) if busy.strategy) }.compact
184
186
  end
185
187
 
188
+ # A question +reply_for+'s surface may not answer (ReplyFor#answers?):
189
+ # needs: "detail", the words to say in its text, the question's id and
190
+ # kind only (no options, no approval's facts); {} for any other.
191
+ def needs_detail_fields(reply_for, question)
192
+ return {} if reply_for.nil? || question.nil? || reply_for.answers?(question)
193
+
194
+ { needs: "detail", text: reply_for.needs_detail_text(question), question: question.to_file.slice("id", "kind") }
195
+ end
196
+
197
+ # The question as +reply_for+'s surface gets it: a plain one's text and
198
+ # header made plain (PlainReply), its options byte-exact (they are
199
+ # answered by label); the saved question is never touched.
200
+ def question_json(question, reply_for)
201
+ json = question&.to_file
202
+ return json unless json && reply_for&.plain?
203
+
204
+ json.merge(%w[question header].to_h { |key| [key, PlainReply.strip(json[key])] }.compact)
205
+ end
206
+
186
207
  def strategy_json(strategy) = { name: strategy.name, allowed: strategy.allowed, origin: strategy.origin.to_s }
187
208
 
188
209
  def wait_start_json(id, start)
@@ -249,11 +270,18 @@ module Samagotchi
249
270
 
250
271
  RESULT_FIELDS = %i[text file outcome limit error_kind retryable cancel_reason stopped_by kept_steps turn_id origin].freeze
251
272
 
252
- def wait_result_json(result, strategy)
273
+ # +reply_for+: the asking surface's (ReplyFor), passed in by the route
274
+ # (an ask's from its request, a token's from the token, an answer's
275
+ # from the pending turn's saved opener), never looked up after the
276
+ # turn: a plain one gets the reply and its question's words made plain
277
+ # (PlainReply, #question_json), here only.
278
+ def wait_result_json(result, strategy, reply_for: nil)
253
279
  json = { status: result.status.to_s }
254
280
  RESULT_FIELDS.each { |key| json[key] = result[key] }
255
281
  json[:text] = json[:text]&.dup&.force_encoding(Encoding::UTF_8)&.scrub
256
- json[:question] = result.question&.to_file
282
+ json[:text] = PlainReply.strip(json[:text]) if reply_for&.plain?
283
+ json[:question] = question_json(result.question, reply_for)
284
+ json.merge!(needs_detail_fields(reply_for, result.question)) if result.status == :waiting_for_answer
257
285
  json[:parent_strategy] = strategy_json(strategy)
258
286
  json
259
287
  end