samagotchi 0.180.0 → 0.182.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 (123) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +71 -1
  3. data/bin/chi +11 -0
  4. data/docs/architecture.md +2 -2
  5. data/docs/bundles.md +7 -2
  6. data/docs/cli.md +46 -13
  7. data/docs/configuration.md +25 -4
  8. data/docs/internals/anthropic.md +4 -3
  9. data/docs/internals/background-tasks.md +2 -0
  10. data/docs/internals/block-renderers.md +123 -6
  11. data/docs/internals/bridge.md +10 -0
  12. data/docs/internals/engine.md +11 -0
  13. data/docs/internals/inline-widgets.md +3 -1
  14. data/docs/internals/objectives.md +9 -4
  15. data/docs/internals/prompt-caching.md +9 -1
  16. data/docs/internals/remote-sessions.md +14 -2
  17. data/docs/internals/web-frontend.md +100 -10
  18. data/docs/internals/working-set.md +24 -5
  19. data/docs/memory.md +3 -0
  20. data/docs/plugins.md +11 -4
  21. data/docs/sessions.md +8 -5
  22. data/docs/testing.md +1 -1
  23. data/lib/samagotchi/answer_display.rb +3 -2
  24. data/lib/samagotchi/block_fix/stamp.rb +49 -0
  25. data/lib/samagotchi/block_fix.rb +220 -0
  26. data/lib/samagotchi/bridge/block_fix_route.rb +30 -0
  27. data/lib/samagotchi/bridge/turn_drawings.rb +19 -0
  28. data/lib/samagotchi/bridge.rb +11 -2
  29. data/lib/samagotchi/bridge_client.rb +9 -0
  30. data/lib/samagotchi/bundle_command.rb +4 -1
  31. data/lib/samagotchi/bundles/known-names/manifest.yml +2 -2
  32. data/lib/samagotchi/bundles/known-names/plugin.rb +4 -3
  33. data/lib/samagotchi/bundles/system/config_modification_protocol.md +3 -2
  34. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  35. data/lib/samagotchi/client.rb +8 -1
  36. data/lib/samagotchi/config.rb +9 -1
  37. data/lib/samagotchi/continue_intent.rb +8 -0
  38. data/lib/samagotchi/core_notice.rb +44 -0
  39. data/lib/samagotchi/engine/block_fix.rb +332 -0
  40. data/lib/samagotchi/engine/side_requests.rb +7 -5
  41. data/lib/samagotchi/engine.rb +4 -0
  42. data/lib/samagotchi/events.rb +1 -0
  43. data/lib/samagotchi/host_address.rb +7 -0
  44. data/lib/samagotchi/host_config.rb +8 -5
  45. data/lib/samagotchi/host_registry.rb +26 -8
  46. data/lib/samagotchi/idle_client.rb +10 -6
  47. data/lib/samagotchi/inline_widgets.rb +12 -0
  48. data/lib/samagotchi/kernel_loop.rb +10 -7
  49. data/lib/samagotchi/llm/adapter_common.rb +3 -2
  50. data/lib/samagotchi/llm/adapters.rb +2 -1
  51. data/lib/samagotchi/llm/anthropic_assembly.rb +5 -0
  52. data/lib/samagotchi/llm/anthropic_messages.rb +6 -2
  53. data/lib/samagotchi/llm/chat_loop.rb +8 -5
  54. data/lib/samagotchi/llm/errors.rb +41 -3
  55. data/lib/samagotchi/llm/http.rb +85 -22
  56. data/lib/samagotchi/llm/openai_chat.rb +20 -3
  57. data/lib/samagotchi/markdown_parser.rb +28 -0
  58. data/lib/samagotchi/memory_bundle/status.rb +2 -1
  59. data/lib/samagotchi/objectives.rb +7 -2
  60. data/lib/samagotchi/owner_lock.rb +2 -0
  61. data/lib/samagotchi/plugin/api.rb +4 -1
  62. data/lib/samagotchi/plugin/context.rb +9 -0
  63. data/lib/samagotchi/plugin/peer.rb +32 -15
  64. data/lib/samagotchi/plugin/tool_spec.rb +13 -2
  65. data/lib/samagotchi/row_refs.rb +14 -3
  66. data/lib/samagotchi/session_access/contract.rb +3 -0
  67. data/lib/samagotchi/session_access/delete_plan.rb +77 -0
  68. data/lib/samagotchi/session_access/local.rb +13 -0
  69. data/lib/samagotchi/session_access/remote.rb +19 -1
  70. data/lib/samagotchi/session_access.rb +1 -0
  71. data/lib/samagotchi/session_chain/delete.rb +45 -87
  72. data/lib/samagotchi/session_chain/delete_preview.rb +55 -19
  73. data/lib/samagotchi/session_delete_command.rb +129 -3
  74. data/lib/samagotchi/session_manager/delegate_rule.rb +86 -0
  75. data/lib/samagotchi/session_manager/listing.rb +4 -4
  76. data/lib/samagotchi/session_manager/removal.rb +40 -14
  77. data/lib/samagotchi/session_manager/running_tasks.rb +50 -23
  78. data/lib/samagotchi/session_manager.rb +1 -0
  79. data/lib/samagotchi/tool_ids.rb +19 -0
  80. data/lib/samagotchi/tool_runner.rb +8 -4
  81. data/lib/samagotchi/tools/registry.rb +3 -2
  82. data/lib/samagotchi/tools/task_runtime.rb +34 -0
  83. data/lib/samagotchi/turn_stages/objectives.rb +10 -5
  84. data/lib/samagotchi/version.rb +1 -1
  85. data/lib/samagotchi/web/app.rb +13 -1
  86. data/lib/samagotchi/web/block_fix_routes.rb +39 -0
  87. data/lib/samagotchi/web/markdown_renderer.rb +24 -9
  88. data/lib/samagotchi/web/message_display.rb +6 -1
  89. data/lib/samagotchi/web/participant_view.rb +1 -1
  90. data/lib/samagotchi/web/public/app.js +15 -19
  91. data/lib/samagotchi/web/public/block_fix.js +270 -0
  92. data/lib/samagotchi/web/public/block_fix_note.js +104 -0
  93. data/lib/samagotchi/web/public/block_frame.js +6 -3
  94. data/lib/samagotchi/web/public/block_host.js +21 -21
  95. data/lib/samagotchi/web/public/block_renderers.css +17 -5
  96. data/lib/samagotchi/web/public/block_watch.js +16 -2
  97. data/lib/samagotchi/web/public/context_chips.js +3 -4
  98. data/lib/samagotchi/web/public/images.js +1 -1
  99. data/lib/samagotchi/web/public/index.html +24 -5
  100. data/lib/samagotchi/web/public/inline_widgets.js +1 -1
  101. data/lib/samagotchi/web/public/objectives_strip.js +16 -6
  102. data/lib/samagotchi/web/public/pan_zoom.js +121 -0
  103. data/lib/samagotchi/web/public/peer_chip.js +3 -3
  104. data/lib/samagotchi/web/public/peer_data.js +27 -15
  105. data/lib/samagotchi/web/public/picture_viewer.js +304 -0
  106. data/lib/samagotchi/web/public/popover_modal.js +3 -2
  107. data/lib/samagotchi/web/public/session_view.js +4 -0
  108. data/lib/samagotchi/web/public/stream_handlers.js +5 -1
  109. data/lib/samagotchi/web/public/turn_block.js +5 -2
  110. data/lib/samagotchi/web/public/working_set.js +9 -3
  111. data/lib/samagotchi/web/public/working_set_view.js +28 -11
  112. data/lib/samagotchi/web/public/ws_cards.js +36 -10
  113. data/lib/samagotchi/web/public/ws_markdown.js +129 -0
  114. data/lib/samagotchi/web/public/ws_order.js +48 -0
  115. data/lib/samagotchi/web/public/ws_peek.js +22 -5
  116. data/lib/samagotchi/web/public/ws_preview.css +41 -1
  117. data/lib/samagotchi/web/public/ws_reader.js +35 -6
  118. data/lib/samagotchi/web/public/ws_sections.js +24 -15
  119. data/lib/samagotchi/web/server.rb +6 -4
  120. data/lib/samagotchi/web/session_control.rb +53 -21
  121. data/lib/samagotchi/worker/block_fixes.rb +22 -0
  122. data/lib/samagotchi/worker.rb +10 -3
  123. metadata +17 -1
@@ -0,0 +1,129 @@
1
+ // Markdown in the working set's reader and peek (ws_cards.js, ws_reader.js,
2
+ // ws_peek.js): which texts render, the text to send, a leading front
3
+ // matter taken off, the HTML of each text kept for the page, and its
4
+ // template (lit: its spec loads dom_shim.js). The HTML comes from markdown_place.js
5
+ // renderMarkdown (POST /api/render, sanitised there); null is markdown off,
6
+ // a viewer that may not render, or a failed read: the source stays.
7
+ //
8
+ // What renders (docs/internals/web-frontend.md, The working set's reader):
9
+ // a memory's text (read, written, its overlay, the greyed "what it was") and
10
+ // a whole read of an .md file. A slice stays numbered source (it can start
11
+ // inside a fence or a list, and its line numbers are the strip's jumps); an
12
+ // edit or a write stays its diff; a fetch's text is not rendered.
13
+
14
+ import { html, nothing } from "./vendor/lit-html.js";
15
+ import { unsafeHTML } from "./vendor/directives/unsafe-html.js";
16
+
17
+ // The route's cap on its JSON body (web/message_display.rb MAX_RENDER_BYTES;
18
+ // block_host.js MAX_SOURCE_BYTES mirrors it too).
19
+ export const RENDER_MAX_BYTES = 64 * 1024;
20
+ // About how many texts the page keeps the HTML of.
21
+ const CACHE_MAX = 50;
22
+
23
+ const MD_FILE = /\.(md|markdown)$/i;
24
+ const MEMORY_CARDS = new Set(["memory", "written"]);
25
+ const MEMORY_OPS = new Set(["memory_read", "memory_write"]);
26
+
27
+ const markdownFile = (item) => item?.kind === "file" && MD_FILE.test(String(item.key || ""));
28
+
29
+ // A card (ws_timeline.js timelineCards) of +item+ that renders: a memory's,
30
+ // or a slice of an .md file that is the whole file (from line 1, one of its
31
+ // reads a whole one).
32
+ export function renderable(card, item) {
33
+ if (!card) return false;
34
+ if (MEMORY_CARDS.has(card.type)) return true;
35
+ if (card.type !== "slice" || card.first !== 1 || !markdownFile(item)) return false;
36
+ return (card.reads || []).some((read) => read?.lines?.whole);
37
+ }
38
+
39
+ // The same rule for the peek's event (ws_timeline.js peekOf): a memory read
40
+ // or write; a whole read of an .md file, not a preview of it.
41
+ export function renderableEvent(event, item) {
42
+ if (!event) return false;
43
+ if (MEMORY_OPS.has(event.op)) return true;
44
+ return event.op === "read" && !!event.lines?.whole && !event.lines?.partial && markdownFile(item);
45
+ }
46
+
47
+ // The text a card renders: a slice's lines, else its event's text.
48
+ export function sourceText(card) {
49
+ if (card?.type === "slice") return (card.rows || []).map((r) => r.text).join("\n");
50
+ return String(card?.event?.text ?? "");
51
+ }
52
+
53
+ const FRONT = /^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/;
54
+
55
+ // A leading YAML front matter block (a --- line closed by a --- line):
56
+ // {front, body}, +front+ without its last newline; "" when there is none.
57
+ export function splitFrontMatter(text) {
58
+ const all = String(text ?? "");
59
+ const found = all.match(FRONT);
60
+ if (!found) return { front: "", body: all };
61
+ return { front: found[0].replace(/\r?\n$/, ""), body: all.slice(found[0].length) };
62
+ }
63
+
64
+ // The peek's source and rendered body omit a leading front matter block.
65
+ // The reader uses splitFrontMatter separately so it keeps that block above
66
+ // the rendered body.
67
+ export function peekText(text) {
68
+ return splitFrontMatter(text).body;
69
+ }
70
+
71
+ const tooBig = (text) => new TextEncoder().encode(JSON.stringify({ text })).length > RENDER_MAX_BYTES;
72
+
73
+ // The page's HTML of each text: +html(text)+ answers the HTML, null (too big
74
+ // for the route: no request) or undefined while its one request is on its
75
+ // way (+onReady()+ runs when HTML comes). A null answer (markdown off, a
76
+ // failed read) is not kept, so the next draw asks again; at most one
77
+ // request per text at a time. Bounded (+max+), the least recently used
78
+ // text going first.
79
+ export function createRenderCache(renderMarkdown, onReady = () => {}, { max = CACHE_MAX } = {}) {
80
+ const kept = new Map();
81
+ const asking = new Set();
82
+
83
+ function html(text) {
84
+ const key = String(text ?? "");
85
+ if (kept.has(key)) {
86
+ const found = kept.get(key);
87
+ kept.delete(key);
88
+ kept.set(key, found);
89
+ return found;
90
+ }
91
+ if (tooBig(key)) return null;
92
+ if (asking.has(key)) return undefined;
93
+ asking.add(key);
94
+ let asked;
95
+ try {
96
+ asked = Promise.resolve(renderMarkdown(key));
97
+ } catch {
98
+ asked = Promise.resolve(null);
99
+ }
100
+ asked
101
+ .catch(() => null)
102
+ .then((answer) => {
103
+ asking.delete(key);
104
+ if (typeof answer !== "string" || !answer) return;
105
+ kept.set(key, answer);
106
+ while (kept.size > max) kept.delete(kept.keys().next().value);
107
+ onReady();
108
+ });
109
+ return undefined;
110
+ }
111
+
112
+ return { html };
113
+ }
114
+
115
+ // +text+ as markdown: its front matter as source, then the HTML (sanitised
116
+ // on the server, POST /api/render); null while its HTML isn't there
117
+ // (+md.html+: undefined on its way, null off or failed).
118
+ export function markdownTemplate(text, md) {
119
+ if (!md?.html) return null;
120
+ const { front, body } = splitFrontMatter(text);
121
+ const found = md.html(body);
122
+ if (typeof found !== "string") return null;
123
+ return html`${front ? html`<pre class="wsr-front">${front}</pre>` : nothing}<div class="wsr-md">${unsafeHTML(found)}</div>`;
124
+ }
125
+
126
+ // The peek renders only the front matter's body, without source above it.
127
+ export function peekMarkdownTemplate(text, md) {
128
+ return markdownTemplate(peekText(text), md);
129
+ }
@@ -0,0 +1,48 @@
1
+ // The working-set list's order (docs/internals/working-set.md, The list's
2
+ // order): last touched first, and held still while the list is open.
3
+ // recencyOrder newest `last` (else `at`) first: turn, then step, then
4
+ // row; the items with neither (a preloaded memory never
5
+ // read, a used memory no row explains) after the rest, in
6
+ // the order they came.
7
+ // heldOrder the order taken at the open (+openKeys+, the item keys
8
+ // drawn then): the items not in it on top, newest first,
9
+ // the others where they stood.
10
+ // Only the popover's list is ordered this way; the rail, the footprints and
11
+ // the reader's side list keep the set's entry order.
12
+ //
13
+ // No DOM: `node --test` covers the rules; working_set_view.js uses them.
14
+ // A module of its own: static JS is cached at unversioned URLs, and a new
15
+ // export on an old module would blank the page.
16
+ import { itemKey } from "./working_set.js";
17
+
18
+ // An item's newest place: its last touch, else its first entry (an older
19
+ // page's item has no `last`), else null.
20
+ const placeOf = (item) => item?.last || item?.at || null;
21
+
22
+ // Which of two places is newer: > 0 when +a+ is.
23
+ function newer(a, b) {
24
+ return (a.turn - b.turn) || (a.step - b.step) || (a.row - b.row);
25
+ }
26
+
27
+ // +items+ newest first (a copy; stable on ties).
28
+ export function recencyOrder(items) {
29
+ return (items || [])
30
+ .map((item, i) => ({ item, i, at: placeOf(item) }))
31
+ .sort((x, y) => {
32
+ if (x.at && y.at) return newer(y.at, x.at) || x.i - y.i;
33
+ if (x.at || y.at) return x.at ? -1 : 1;
34
+ return x.i - y.i;
35
+ })
36
+ .map((x) => x.item);
37
+ }
38
+
39
+ // +items+ in the order of +openKeys+ (the keys drawn at the open), the ones
40
+ // it doesn't hold before them, newest first; an item that left the set is
41
+ // simply not there. Without +openKeys+: recencyOrder.
42
+ export function heldOrder(items, openKeys) {
43
+ if (!Array.isArray(openKeys)) return recencyOrder(items);
44
+ const place = new Map(openKeys.map((key, i) => [key, i]));
45
+ const fresh = recencyOrder((items || []).filter((item) => !place.has(itemKey(item))));
46
+ const kept = (items || []).filter((item) => place.has(itemKey(item))).sort((a, b) => place.get(itemKey(a)) - place.get(itemKey(b)));
47
+ return [...fresh, ...kept];
48
+ }
@@ -14,6 +14,11 @@
14
14
  // asks again (refresh) only when the item's server signature changed
15
15
  // (+sigOf+: working_set.js serverSig): mid-turn the route answers the
16
16
  // running turn's view as of its last step.
17
+ //
18
+ // A memory's text and a whole read of an .md file show rendered, the whole
19
+ // text in the peek's scroll box, once their HTML is in the reader's cache
20
+ // (+md+: ws_markdown.js createRenderCache); else, and without +md+, the
21
+ // first lines as source.
17
22
 
18
23
  import { html, nothing } from "./vendor/lit-html.js";
19
24
  import { createLatest } from "./latest.js";
@@ -21,6 +26,11 @@ import { diffCounts, diffTemplate } from "./diff_view.js";
21
26
  import { callTemplate, linesTemplate, textTemplate } from "./ws_cards.js";
22
27
  import { countsText, eventTag, eventWords, peekOf } from "./ws_timeline.js";
23
28
  import { olderAnswer } from "./ws_item_sig.js";
29
+ import { peekMarkdownTemplate, peekText, renderableEvent } from "./ws_markdown.js";
30
+
31
+ // No events while a turn runs (the answer's +running+): the read is in the
32
+ // step whose tool batch hasn't ended.
33
+ const STEP_RUNNING = "chi read this in the step still running. It shows here when that step's tools finish.";
24
34
 
25
35
  // The popover's width while a row is peeked (it is 420 otherwise).
26
36
  export const PEEK_WIDTH = 520;
@@ -28,8 +38,9 @@ export const PEEK_WIDTH = 520;
28
38
  // +session()+: the open session's id; +getItem(id, kind, key, opts)+: the item
29
39
  // route's answer; +sigOf(item)+: its server signature (undefined: always ask
30
40
  // again); +onChange()+: the peek's content changed (the popover redraws and
31
- // places itself again).
32
- export function createPeek({ session, getItem, sigOf = () => undefined, onChange = () => {} }) {
41
+ // places itself again); +md+: the reader's markdown cache ({html(text)}),
42
+ // null: none.
43
+ export function createPeek({ session, getItem, sigOf = () => undefined, onChange = () => {}, md = null }) {
33
44
  let openId = null;
34
45
  let item = null;
35
46
  let data = null;
@@ -98,16 +109,22 @@ export function createPeek({ session, getItem, sigOf = () => undefined, onChange
98
109
  if (!data) return html`<div class="ws-peek" role="region" aria-label="What chi has"><div class="ws-peek-note">Loading…</div></div>`;
99
110
  const events = data.events || [];
100
111
  const peek = peekOf(events);
101
- if (!peek) return html`<div class="ws-peek" role="region" aria-label="What chi has"><div class="ws-peek-note">Nothing of it in the conversation yet.</div></div>`;
112
+ if (!peek) return html`<div class="ws-peek" role="region" aria-label="What chi has"><div class="ws-peek-note">${data.running ? STEP_RUNNING : "Nothing of it in the conversation yet."}</div></div>`;
102
113
  const { event } = peek;
103
114
  const counts = peek.kind === "diff" && event.diff?.text && !event.diff.error && !event.diff.skipped ? diffCounts(event.diff) : "";
104
115
  const after = peek.after ? html`<span class="ws-peek-after">then ${eventWords(peek.after)} at ${eventTag(peek.after, row)}</span>` : nothing;
105
116
  const gone = event.sent === false ? html`<span class="wsr-pill gone">chi no longer has this</span>` : nothing;
106
117
  const head = html`<div class="ws-peek-h"><span class="ws-peek-t">latest · ${eventWords(event)} at ${eventTag(event, row)}</span>${counts ? html`<span class="ws-peek-c">${counts}</span>` : nothing}${gone}${after}</div>`;
107
118
  let body;
108
- if (peek.kind === "diff") body = diffTemplate(event.diff, { fold: 12 });
119
+ const markdown = peek.kind !== "diff" && renderableEvent(event, row);
120
+ const rendered = md && markdown ? peekMarkdownTemplate(event.text, md) : null;
121
+ if (rendered) body = rendered;
122
+ else if (peek.kind === "diff") body = diffTemplate(event.diff, { fold: 12 });
109
123
  else if (peek.kind === "lines") body = linesTemplate(peek.rows, { fold: Infinity });
110
- else body = textTemplate(peek.rows.map((r) => r.text).join("\n"), { fold: Infinity });
124
+ else {
125
+ const text = peek.rows.map((r) => r.text).join("\n");
126
+ body = textTemplate(markdown ? peekText(text) : text, { fold: Infinity });
127
+ }
111
128
  const words = countsText(events, data.counts);
112
129
  const foot = html`<div class="ws-peek-f"><button type="button" class="ws-peek-open" data-ws="timeline" data-ws-id=${openId}>Open the timeline${words ? html`<span class="ws-peek-n"> · ${words}</span>` : nothing}</button>${callTemplate(event, row)}</div>`;
113
130
  return html`<div class="ws-peek" role="region" aria-label="What chi has">${head}<div class="ws-peek-b">${body}</div>${foot}</div>`;
@@ -69,7 +69,8 @@
69
69
  .wsr-card-h{display:flex;align-items:center;gap:10px;flex-wrap:wrap;padding:6px 12px;border-bottom:1px solid var(--border);background:var(--bg-raised);font-size:12px}
70
70
  .wsr-card-t{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--text)}
71
71
  .wsr-card-m{color:var(--ws-faint)}
72
- .wsr-card-h .wsr-call{margin-left:auto;font-size:12px}
72
+ .wsr-card-actions{display:inline-flex;align-items:center;gap:6px;margin-left:auto;white-space:nowrap}
73
+ .wsr-card-h .wsr-call{margin-left:0;font-size:12px}
73
74
  .wsr-pill{padding:0 6px;border-radius:4px;font-size:11px}
74
75
  .wsr-pill.latest{background:var(--accent-bg);color:var(--accent)}
75
76
  .wsr-pill.gone{background:var(--badge-bg);color:var(--text-muted)}
@@ -81,6 +82,37 @@
81
82
  .wsr-had>summary{cursor:pointer}
82
83
  .wsr-overlay{margin:0 10px 10px;padding:6px 0 0;border:1px dashed var(--border-strong);border-radius:6px}
83
84
  .wsr-overlay-h{padding:0 10px;font-size:11.5px;color:var(--ws-muted)}
85
+ /* Markdown (ws_markdown.js): a memory's text, a whole read of an .md file; the answers' values, scoped here. */
86
+ .wsr-md{padding:10px 14px;font-size:13.5px;line-height:1.55;color:var(--text-2);white-space:normal;overflow-wrap:anywhere}
87
+ .wsr-md :is(h1,h2,h3,h4,h5,h6){margin:16px 0 6px;font-weight:600;line-height:1.3;color:var(--text-bright)}
88
+ .wsr-md>:is(h1,h2,h3,h4,h5,h6):first-child{margin-top:2px}
89
+ .wsr-md h1{font-size:18px}
90
+ .wsr-md h2{font-size:16px}
91
+ .wsr-md h3{font-size:15px}
92
+ .wsr-md :is(h4,h5,h6){font-size:14px;color:var(--text-2)}
93
+ .wsr-md :is(p,ul,ol,blockquote,table,pre){margin:0 0 10px}
94
+ .wsr-md>:last-child{margin-bottom:0}
95
+ .wsr-md :is(ul,ol){padding-left:1.5em}
96
+ .wsr-md li+li{margin-top:3px}
97
+ .wsr-md li>:is(ul,ol){margin:3px 0 0}
98
+ .wsr-md strong{color:var(--text-bright)}
99
+ .wsr-md a{color:var(--accent)}
100
+ .wsr-md hr{border:0;border-top:1px solid var(--border);margin:12px 0}
101
+ .wsr-md code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.88em}
102
+ .wsr-md :not(pre)>code{padding:1px 4px;border:1px solid var(--border);border-radius:4px;background:var(--bg-inset);color:var(--text)}
103
+ .wsr-md pre{overflow-x:auto;padding:8px 10px;border:1px solid var(--border);border-radius:6px;background:var(--bg-inset);font-size:12.5px;line-height:1.45;white-space:pre;overflow-wrap:normal}
104
+ .wsr-md blockquote{padding-left:12px;border-left:3px solid var(--border-strong);color:var(--text-muted)}
105
+ .wsr-md table{display:block;max-width:100%;overflow-x:auto;border-collapse:collapse}
106
+ .wsr-md :is(th,td){padding:4px 8px;border:1px solid var(--border-strong);font-size:13px;overflow-wrap:normal}
107
+ .wsr-md th{background:var(--bg-inset);font-weight:600}
108
+ .wsr-front{margin:0;padding:6px 14px;border-bottom:1px solid var(--border);font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11.5px;line-height:16px;white-space:pre-wrap;word-break:break-word;color:var(--text-faint)}
109
+ /* The card's "rendered | source" switch, as the list's lens. */
110
+ .wsr-view{display:inline-flex;gap:2px}
111
+ .wsr-view button{padding:1px 8px;border:1px solid transparent;border-radius:999px;background:transparent;color:var(--text-muted);font-size:11px;line-height:16px;cursor:pointer}
112
+ .wsr-view button.on{color:var(--text-2);border-color:var(--border-strong);background:var(--bg-inset)}
113
+ .wsr-view button:hover:not(:disabled){filter:none}@media(hover:hover){.wsr-view button:hover{color:var(--text)}}
114
+ .ws-peek-b .wsr-md{max-height:220px;overflow:auto;font-size:12.5px}
115
+ .ws-peek-b .wsr-front{font-size:11px}
84
116
  .wsr-banner{flex:none;margin:10px 20px 0;padding:8px 10px;border:1px solid var(--warn-border);border-radius:8px;background:var(--warn-bg);color:var(--warn-text);font-size:12.5px;line-height:18px}
85
117
  .wsr-tabs{flex:none;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));margin:10px 20px 0;padding:2px;border-radius:8px;background:var(--bg-inset);max-width:420px}
86
118
  .wsr-tabs button{height:32px;border:0;border-radius:6px;background:transparent;color:var(--text-muted);font-size:13px;cursor:pointer}
@@ -116,8 +148,16 @@
116
148
  .wsr-bar{height:8px}
117
149
  .wsr-body{padding:10px 0;gap:10px}
118
150
  .wsr-card{border-left:0;border-right:0;border-radius:0}
151
+ .wsr-card-h{flex-wrap:wrap;gap:6px;padding:6px 8px}
152
+ .wsr-card-t{flex:1 1 160px;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
153
+ .wsr-card-actions{flex:none;margin-left:auto}
154
+ .wsr-card-h .wsr-call{white-space:nowrap}
119
155
  .wsr-lines{font-size:11.5px;line-height:18px}
120
156
  .wsr-card .read-lines code{min-width:max-content}
157
+ .wsr-view{flex:none}
158
+ .wsr-view button{position:relative;min-height:20px;padding:1px 8px}
159
+ .wsr-view button::after{content:"";position:absolute;inset:-12px 0}
160
+ .wsr-md{padding:10px 14px}
121
161
  .wsr-banner,.wsr-tabs{margin:10px 12px 0}
122
162
  .wsr-tabs{max-width:none}
123
163
  .wsr-from{padding:8px 14px}
@@ -22,6 +22,11 @@
22
22
  // the running turn's view as of its last step. Leaving the
23
23
  // session (another one, the start page) resets it: session_view.js
24
24
  // forgetSession calls reset(), so #center is never left inert under it.
25
+ //
26
+ // Markdown (+renderMarkdown+, markdown_place.js): a memory's text and a
27
+ // whole read of an .md file render, in the reader and the peek, from one
28
+ // cache (ws_markdown.js); the reader's cards carry a "rendered | source"
29
+ // switch, one choice per open item, back to rendered when another opens.
25
30
 
26
31
  import { html, nothing, render } from "./vendor/lit-html.js";
27
32
  import { api } from "./data.js";
@@ -32,6 +37,7 @@ import { setTimelineWayIn } from "./ws_way_in.js";
32
37
  import { cardTemplate } from "./ws_cards.js";
33
38
  import { bandBox, countsText, eventTag, fileStrip, itemPath, linesText, timelineCards } from "./ws_timeline.js";
34
39
  import { olderAnswer } from "./ws_item_sig.js";
40
+ import { createRenderCache } from "./ws_markdown.js";
35
41
  import { GLYPHS, leafText, opsText, steerId, steerLine, tokensText } from "./working_set.js";
36
42
 
37
43
  // The item route's answer for session +id+ (+now+: a memory's text now;
@@ -41,6 +47,10 @@ export function getWorkingSetItem(id, kind, key, { now = false, latest = false }
41
47
  }
42
48
 
43
49
  const PHONE_MAX = 600;
50
+ // An item with no events while a turn runs (the answer's +running+): its
51
+ // read is in the step whose tool batch hasn't ended (the route answers the
52
+ // turn as of its last step).
53
+ const STEP_RUNNING = "chi read this in the step still running. It shows here when that step's tools finish.";
44
54
 
45
55
  // The head's pill: what is true of the item as a whole.
46
56
  function itemPill(item, events) {
@@ -62,9 +72,10 @@ function itemName(item) {
62
72
  // +centerEl+: what the reader covers (#center); +session()+, +state()+: the
63
73
  // open session's id and fields (its folder: the undrop line); +getItem+: the
64
74
  // item route (tests pass a stand-in); +sendLine(line)+: a steer line
65
- // (undrop; null: none).
75
+ // (undrop; null: none); +renderMarkdown(text)+: a text's markdown HTML or
76
+ // null (none: every text as its source).
66
77
  export function createWorkingSetPreview({ centerEl, session, state = () => ({}), getItem = getWorkingSetItem, sendLine = null,
67
- doc = document, win = window }) {
78
+ renderMarkdown = null, doc = document, win = window }) {
68
79
  let workingSet = null;
69
80
  // The open item ({kind, key}), its answer, the memory's now, the tab.
70
81
  let open = null;
@@ -73,9 +84,16 @@ export function createWorkingSetPreview({ centerEl, session, state = () => ({}),
73
84
  let tab = "has";
74
85
  let openFor = null;
75
86
  let askedSig;
87
+ // The open item's "rendered | source".
88
+ let view = "rendered";
76
89
  const latest = createLatest(() => `${session()}|${open ? `${open.kind}:${open.key}` : ""}`);
77
90
  const sigOf = (it) => workingSet?.serverSig?.(it);
78
- const peek = createPeek({ session, getItem, sigOf, onChange: () => workingSet?.peekChanged() });
91
+ // One cache for both places: HTML that came redraws the open one(s).
92
+ const cache = renderMarkdown ? createRenderCache(renderMarkdown, () => {
93
+ if (open && !el.hidden) draw();
94
+ if (peek.any()) workingSet?.peekChanged();
95
+ }) : null;
96
+ const peek = createPeek({ session, getItem, sigOf, onChange: () => workingSet?.peekChanged(), md: cache });
79
97
 
80
98
  const el = doc.createElement("section");
81
99
  el.className = "ws-reader";
@@ -169,9 +187,12 @@ export function createWorkingSetPreview({ centerEl, session, state = () => ({}),
169
187
  let body;
170
188
  if (failed) body = html`<div class="wsr-note">Couldn't load what chi has of it.</div>`;
171
189
  else if (!data) body = html`<div class="wsr-note">Loading…</div>`;
172
- else if (!cards.length) body = html`<div class="wsr-note">Nothing of it in the conversation yet: a running turn's reads show at its next step.</div>`;
190
+ else if (!cards.length) body = html`<div class="wsr-note">${data.running ? STEP_RUNNING : "Nothing of it in the conversation yet: a running turn's reads show at its next step."}</div>`;
173
191
  else if (memory?.nowBody) body = memory.nowBody;
174
- else body = cards.map((card) => cardTemplate(card, { item, undrop }));
192
+ else {
193
+ const md = cache ? { view, html: cache.html } : null;
194
+ body = cards.map((card) => cardTemplate(card, { item, undrop, md }));
195
+ }
175
196
  const list = shown();
176
197
  const at = list.findIndex((it) => it.kind === item.kind && it.key === item.key);
177
198
  const tpl = html`<div class="wsr-main">
@@ -200,6 +221,7 @@ export function createWorkingSetPreview({ centerEl, session, state = () => ({}),
200
221
  data = null;
201
222
  failed = false;
202
223
  tab = "has";
224
+ view = "rendered";
203
225
  }
204
226
  if (el.hidden) {
205
227
  const active = doc.activeElement;
@@ -262,9 +284,16 @@ export function createWorkingSetPreview({ centerEl, session, state = () => ({}),
262
284
  else if (what === "tab") {
263
285
  tab = act.dataset.tab === "now" ? "now" : "has";
264
286
  draw();
287
+ } else if (what === "view") {
288
+ view = act.dataset.view === "source" ? "source" : "rendered";
289
+ draw();
265
290
  } else if (what === "band") {
291
+ // The slice holding the band's first line; a rendered one has no
292
+ // numbered lines: the slice its first line falls in (data-first).
266
293
  const first = Number(act.dataset.first);
267
- const card = [...el.querySelectorAll(".wsr-card.slice")].find((c) => c.querySelector(`.read-line[data-line="${first}"]`));
294
+ const slices = [...el.querySelectorAll(".wsr-card.slice")];
295
+ const card = slices.find((c) => c.querySelector(`.read-line[data-line="${first}"]`))
296
+ || slices.filter((c) => Number(c.dataset.first) <= first).sort((a, b) => Number(b.dataset.first) - Number(a.dataset.first))[0];
268
297
  card?.scrollIntoView?.({ block: "start" });
269
298
  } else if (what === "undrop" && sendLine) {
270
299
  const item = current();
@@ -1,5 +1,6 @@
1
1
  // The working set's head view (docs/internals/working-set.md, The head
2
- // view): the popover's list as what is in chi's head, in three sections.
2
+ // view): the popover's list as what is in chi's head, in three sections,
3
+ // drawn in this order: read, talk, start (folded until the user opens it).
3
4
  // start From the start: the system prompt's parts (the session's
4
5
  // prompt_parts), in prompt order, the tools part first. A memory
5
6
  // part (identity, a model note, a preload) IS a memory row: merged
@@ -10,7 +11,9 @@
10
11
  // `x@system`, no actions). Other parts are `part` rows: a label, a
11
12
  // sub, their tokens, no actions.
12
13
  // read Read in this session: today's files / memories / urls sections
13
- // (working_set.js bodySections), minus the memories shown in start.
14
+ // (working_set.js bodySections), minus the memories shown in start,
15
+ // in the order of the set given (the view's: last touched first,
16
+ // ws_order.js).
14
17
  // talk Conversation: one row (drawn at section level, no header, no
15
18
  // fold), the rest of the context: the context's
16
19
  // tokens minus the parts' and the held items'. Mixed units (parts and
@@ -25,9 +28,11 @@
25
28
  import { bodySections, itemKey, tokensText } from "./working_set.js";
26
29
 
27
30
  // The sections folded by hand, per session (session_prefs.js): a JSON list
28
- // of section keys. None: all open.
31
+ // of section keys. None stored: start folded (DEFAULT_FOLDED).
29
32
  export const WS_SECTION_FOLD = "chi_ws_sections_folded";
30
33
 
34
+ const DEFAULT_FOLDED = Object.freeze(["start"]);
35
+
31
36
  export const MEMORY_PARTS = Object.freeze(["identity", "notes", "preloads"]);
32
37
 
33
38
  // What a memory part's row says it is.
@@ -118,7 +123,8 @@ export function heldTwiceNote(row, turnItem) {
118
123
  // overlaid), or null without parts (today's list). +parts+: the session's
119
124
  // prompt_parts; +ctxTokens+: the context's tokens now (null: unknown);
120
125
  // +turns+: how many turns the session has (the conversation row's).
121
- // @return [{key, title, meta, tokens, rows?, inner?}] start, read, talk?
126
+ // @return [{key, title, meta, tokens, rows?, inner?, twice?}] read, talk?, start
127
+ // (start's +twice+: how many of its rows are held twice)
122
128
  export function headSections(set, budget, { parts = null, ctxTokens = null, turns = 0, inTurn = false } = {}) {
123
129
  if (!Array.isArray(parts) || !parts.length) return null;
124
130
  const { rows, used, partNames } = startRows(set, parts);
@@ -136,18 +142,19 @@ export function headSections(set, budget, { parts = null, ctxTokens = null, turn
136
142
  // into the conversation's arithmetic, not into either section.
137
143
  const readTokens = sum(readItems.filter(held), (i) => i.tokens);
138
144
  const heldTokens = readTokens + sum(rows.filter(readHeld), (r) => r.tokens);
139
- const sections = [
140
- { key: "start", title: "From the start", meta: inTurn ? "in every turn" : `${rows.length} part${rows.length === 1 ? "" : "s"} · in every turn`, tokens: partsTokens, rows },
141
- {
142
- key: "read", title: "Read in this session", meta: [`${readItems.filter(held).length} held`, out ? `${out} out` : ""].filter(Boolean).join(" · "),
143
- tokens: readTokens, inner: bodySections(rest, budget),
144
- },
145
- ];
145
+ const sections = [{
146
+ key: "read", title: "Read in this session", meta: [`${readItems.filter(held).length} held`, out ? `${out} out` : ""].filter(Boolean).join(" · "),
147
+ tokens: readTokens, inner: bodySections(rest, budget),
148
+ }];
146
149
  const talk = Number.isFinite(ctxTokens) ? ctxTokens - partsTokens - heldTokens : NaN;
147
150
  if (talk > 0) {
148
151
  const row = { kind: "talk", key: "conversation", label: "conversation", sub: `${turns} turn${turns === 1 ? "" : "s"}`, partTokens: talk, ops: [], at: null, count: 0, state: "live" };
149
152
  sections.push({ key: "talk", title: "Conversation", meta: "", tokens: talk, rows: [row] });
150
153
  }
154
+ sections.push({
155
+ key: "start", title: "From the start", meta: inTurn ? "in every turn" : `${rows.length} part${rows.length === 1 ? "" : "s"} · in every turn`, tokens: partsTokens, rows,
156
+ twice: rows.filter(heldTwice).length,
157
+ });
151
158
  return sections;
152
159
  }
153
160
 
@@ -232,14 +239,16 @@ export function lensTouched(sections, touched) {
232
239
  return out;
233
240
  }
234
241
 
235
- // The section keys folded, from the stored value (a JSON list); unreadable: none.
242
+ // The section keys folded, from the stored value (a JSON list). Nothing
243
+ // stored (null) or unreadable: the default, start folded; a stored list,
244
+ // an empty one too, as it is (the user folded or opened them by hand).
236
245
  // Conversation never folds (one row): an older page's stored "talk" is ignored.
237
246
  export function foldedSections(stored) {
238
247
  try {
239
- const list = JSON.parse(stored || "[]");
240
- return new Set(Array.isArray(list) ? list.filter((k) => typeof k === "string" && k !== "talk") : []);
248
+ const list = stored == null ? null : JSON.parse(stored);
249
+ return new Set((Array.isArray(list) ? list : DEFAULT_FOLDED).filter((k) => typeof k === "string" && k !== "talk"));
241
250
  } catch (_) {
242
- return new Set();
251
+ return new Set(DEFAULT_FOLDED);
243
252
  }
244
253
  }
245
254
 
@@ -172,6 +172,7 @@ module Samagotchi
172
172
  working_set: Config::BY_KEY["web.working_set"].default, tunnel: nil, start_dir_from: :flag,
173
173
  stage_collapsed: Config::BY_KEY["web.stage_collapsed"].default,
174
174
  reload_check: Config::BY_KEY["web.reload_check"].default,
175
+ block_fix: Config::BY_KEY["web.block_fix"].default,
175
176
  restarted: false, restart_argv: ["web"], exec: nil)
176
177
  handed_on = false # a :restart leaves Serve to the next process, a run turns it off itself
177
178
  start_given = !start_dir.to_s.strip.empty?
@@ -231,8 +232,8 @@ module Samagotchi
231
232
  Push.preflight!(public_url)
232
233
  options = { port: port, host: host, url: url, open_browser: open_browser, markdown: markdown,
233
234
  annotate_presets: annotate_presets, editor: editor, lan: lan, working_set: working_set,
234
- stage_collapsed: stage_collapsed, reload_check: reload_check, public_url: public_url,
235
- start_dir: start_dir }
235
+ stage_collapsed: stage_collapsed, reload_check: reload_check, block_fix: block_fix,
236
+ public_url: public_url, start_dir: start_dir }
236
237
  started = if plan
237
238
  with_tunnel(provider, plan) do |up|
238
239
  start(**options, public_notes: provider.start_lines(plan, restarted: restarted), on_bound: up)
@@ -463,6 +464,7 @@ module Samagotchi
463
464
  working_set: Config::BY_KEY["web.working_set"].default, public_url: nil, public_notes: [],
464
465
  stage_collapsed: Config::BY_KEY["web.stage_collapsed"].default,
465
466
  reload_check: Config::BY_KEY["web.reload_check"].default,
467
+ block_fix: Config::BY_KEY["web.block_fix"].default,
466
468
  on_bound: nil, start_dir: Dir.pwd, update_check: nil, auto_update: nil)
467
469
  config_restart_unsubscribe = ConfigFile.watch_restart_settings!(process: :web) do |message|
468
470
  Samagotchi::Log.warn(:config, "restart_required", echo: "Warning: config: #{message}")
@@ -479,8 +481,8 @@ module Samagotchi
479
481
  push = push_runtime(public_url, state_dir)
480
482
  app = App.new(manager: manager, state_dir: state_dir, markdown: markdown,
481
483
  annotate_presets: annotate_presets, editor: editor, hub: hub, lan: lan_option, working_set: working_set,
482
- stage_collapsed: stage_collapsed, reload_check: reload_check, public_url: public_url,
483
- public_token: public_token, push: push, start_dir: start_dir)
484
+ stage_collapsed: stage_collapsed, reload_check: reload_check, block_fix: block_fix,
485
+ public_url: public_url, public_token: public_token, push: push, start_dir: start_dir)
484
486
  # update.auto: install; a stand-in app (a spec's) has no operations to run.
485
487
  auto_update ||= AutoUpdate.new(hub: hub, ops: app.update_ops, check: update_check, preflight: method(:restart_preflight)) if app.respond_to?(:update_ops)
486
488
  webrick = nil