samagotchi 0.176.0 → 0.177.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 (40) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +30 -1
  3. data/docs/cli.md +8 -4
  4. data/docs/internals/participants.md +2 -1
  5. data/docs/internals/prompt-caching.md +3 -0
  6. data/docs/internals/web-frontend.md +18 -5
  7. data/docs/internals/working-set.md +77 -6
  8. data/docs/sessions.md +1 -0
  9. data/lib/samagotchi/bridge.rb +3 -3
  10. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  11. data/lib/samagotchi/engine/models.rb +11 -0
  12. data/lib/samagotchi/engine/session.rb +9 -0
  13. data/lib/samagotchi/engine.rb +1 -0
  14. data/lib/samagotchi/engine_snapshots.rb +3 -0
  15. data/lib/samagotchi/prompt_part.rb +66 -0
  16. data/lib/samagotchi/session.rb +10 -1
  17. data/lib/samagotchi/system_prompt.rb +191 -12
  18. data/lib/samagotchi/version.rb +1 -1
  19. data/lib/samagotchi/web/participant_show.rb +1 -1
  20. data/lib/samagotchi/web/public/app.js +3 -0
  21. data/lib/samagotchi/web/public/ctx_tokens.js +33 -0
  22. data/lib/samagotchi/web/public/index.html +43 -9
  23. data/lib/samagotchi/web/public/session_fields.js +10 -4
  24. data/lib/samagotchi/web/public/session_prefs.js +5 -2
  25. data/lib/samagotchi/web/public/session_state.js +14 -1
  26. data/lib/samagotchi/web/public/session_store.js +1 -1
  27. data/lib/samagotchi/web/public/session_view.js +1 -1
  28. data/lib/samagotchi/web/public/stream_handlers.js +7 -3
  29. data/lib/samagotchi/web/public/tokens.css +2 -2
  30. data/lib/samagotchi/web/public/working_set.js +51 -7
  31. data/lib/samagotchi/web/public/working_set_view.js +188 -58
  32. data/lib/samagotchi/web/public/ws_sections.js +251 -0
  33. data/lib/samagotchi/web/session_show.rb +13 -2
  34. data/lib/samagotchi/worker/command_queue.rb +5 -1
  35. data/lib/samagotchi/worker/startup.rb +1 -1
  36. data/lib/samagotchi/worker.rb +1 -0
  37. data/lib/samagotchi/working_set.rb +32 -4
  38. data/lib/samagotchi/working_set_command.rb +3 -2
  39. data/lib/samagotchi/working_set_steer.rb +21 -3
  40. metadata +4 -1
@@ -16,6 +16,8 @@ require_relative "memory_bundle/index_size"
16
16
  require_relative "thinking"
17
17
  require_relative "prompt_files"
18
18
  require_relative "plugin/prompt_sections"
19
+ require_relative "prompt_part"
20
+ require "json"
19
21
 
20
22
  module Samagotchi
21
23
  # The system prompt an Engine gives its model: the base prompt (tool
@@ -95,7 +97,21 @@ module Samagotchi
95
97
  # plugins' sections it holds, its stable part's length (chat) and the
96
98
  # Tools::ToolSurface it declares (the tools, the not-loaded line, the
97
99
  # kit's prompt text).
98
- Built = Data.define(:prompt, :memory_index, :notes, :files, :sections, :stable_length, :surface)
100
+ #
101
+ # parts: the Sections the prompt is joined from (stable ones, then the
102
+ # volatile ones), in prompt order; Gemma's tail declarations are not one.
103
+ # prompt_parts: the same as sizes, one PromptPart per memory, file and
104
+ # plugin section, the tools part first (#prompt_parts).
105
+ Built = Data.define(:prompt, :memory_index, :notes, :files, :sections, :stable_length, :surface, :memory_names, :parts,
106
+ :prompt_parts)
107
+
108
+ # One part of the prompt: its kind (KINDS), what it was made from (the
109
+ # memory names of identity and preloads, the files of agents and
110
+ # appended, the notes of notes, the plugins' Built of plugins; nil
111
+ # elsewhere) and its text, as the prompt holds it.
112
+ Section = Data.define(:kind, :ref, :text)
113
+
114
+ KINDS = %i[base identity notes preloads agents appended kit plugins indexes participants model location session].freeze
99
115
 
100
116
  # The full prompt: #base wrapped with the index and the rest. Built once
101
117
  # per loop and level (until #reset!) so the prompt prefix, and the
@@ -120,6 +136,7 @@ module Samagotchi
120
136
  built = cache[key] || (cache[key] = build_prompt(chat: chat, thinking: thinking, layers: layers))
121
137
  @memory_index = built.memory_index
122
138
  @last = built
139
+ @last_prompt_memory_names = built.memory_names
123
140
  built.prompt
124
141
  end
125
142
 
@@ -137,6 +154,19 @@ module Samagotchi
137
154
  # @return [Array<ModelNotes::Note>, nil]
138
155
  def prompt_notes = @last&.notes
139
156
 
157
+ # The sizes of the parts the prompt #build returned last is made of
158
+ # (PromptPart: the tools first, then each memory, file and plugin
159
+ # section in prompt order; chars at TokenUsage's one ratio). Worked out
160
+ # once with the prompt, kept with it. [] before a build and after
161
+ # #reset!.
162
+ # @return [Array<PromptPart>]
163
+ def prompt_parts = @last&.prompt_parts || []
164
+
165
+ # The identity and preloaded memories the last prompt build actually
166
+ # rendered; retained across reset! until another build completes.
167
+ # @return [Array<String>]
168
+ def prompt_memory_names = @last_prompt_memory_names || []
169
+
140
170
  # The files whose text the prompt #build returned last holds, as
141
171
  # absolute paths in prompt order: the AGENTS.md chain, then the
142
172
  # appended files (append_system_prompt:, --append-system-prompt). [] before a
@@ -192,16 +222,108 @@ module Samagotchi
192
222
  # @section_* and @measured_* scratch is this build's (the turn thread's)
193
223
  # alone: #reset! never touches it.
194
224
  def build_prompt(chat:, thinking:, layers:)
225
+ @section_identity_memory_name = nil
226
+ @section_activated_memory_names = []
195
227
  @section_notes = nil
196
228
  @section_files = []
197
229
  @section_plugins = []
198
230
  @measured_stable_length = nil
231
+ @section_parts = []
232
+ @section_file_chars = []
233
+ @section_item_chars = {}
234
+ @section_preload_chars = []
235
+ @section_preload_scopes = []
236
+ @section_index_chars = {}
199
237
  surface = tool_surface(layers)
200
238
  prompt = system_prompt_with_index(assist_system_prompt(chat: chat, surface: surface),
201
239
  chat: chat, thinking: thinking, surface: surface)
240
+ prompt_parts = Degrade.call(:prompt, "prompt_parts_failed", fallback: []) do
241
+ prompt_parts_for(@section_parts, chat: chat, surface: surface)
242
+ end
202
243
  Built.new(prompt: prompt, memory_index: @measured_index, notes: @section_notes || [],
203
244
  files: @section_files.freeze, sections: @section_plugins.freeze, stable_length: @measured_stable_length,
204
- surface: surface)
245
+ surface: surface, memory_names: [@section_identity_memory_name, *@section_activated_memory_names].compact.uniq.freeze,
246
+ parts: @section_parts.freeze, prompt_parts: prompt_parts.freeze)
247
+ end
248
+
249
+ # ── The parts' sizes ───────────────────────────────────────────────────────
250
+
251
+ LABELS = { base: "base prompt", kit: "toolkit prompt", participants: "participants", model: "model",
252
+ location: "location", session: "session" }.freeze
253
+
254
+ # The PromptParts of +sections+ (a build's), the tools part first. A
255
+ # multi-item section is one part per item; its headings and joins go
256
+ # into its first part, so the parts sum to the section's text.
257
+ def prompt_parts_for(sections, chat:, surface:)
258
+ tools_chars = tools_chars(chat: chat, surface: surface)
259
+ parts = sections.flat_map { |part| section_parts(part) }
260
+ if tools_chars[:from_base]
261
+ base = parts.index { |part| part.kind == "base" }
262
+ parts[base] = PromptPart.build(kind: :base, label: parts[base].label, chars: parts[base].chars - tools_chars[:chars]) if base
263
+ end
264
+ [PromptPart.build(kind: :tools, label: "#{surface.declared_names.size} declared", chars: tools_chars[:chars]), *parts]
265
+ end
266
+
267
+ # The tool declarations' size, once. chat: the schemas as the request's
268
+ # tools field sends them. Native: the declarations text, inside the base
269
+ # prompt (from_base: its chars move out of the base part) or, on Gemma,
270
+ # after the last section (nothing to move).
271
+ def tools_chars(chat:, surface:)
272
+ return { chars: JSON.generate(surface.schemas).length, from_base: false } if chat
273
+
274
+ { chars: tool_declarations(surface).length, from_base: !gemma_tail_declarations? }
275
+ end
276
+
277
+ def section_parts(section)
278
+ items = section_items(section)
279
+ return [PromptPart.build(kind: section.kind, label: LABELS.fetch(section.kind, section.kind), chars: section.text.length)] if items.nil?
280
+
281
+ # The first item's own chars are the rest of the text.
282
+ rest = items.drop(1).sum { |item| item[2] }
283
+ items.each_with_index.map do |(label, ref, chars, scope), index|
284
+ PromptPart.build(kind: section.kind, label: label, ref: ref, scope: scope,
285
+ chars: index.zero? ? section.text.length - rest : chars)
286
+ end
287
+ end
288
+
289
+ # [label, ref, own chars, scope] per item of a section made of several
290
+ # (scope: a memory part's, else nil), nil for a section that is one part.
291
+ def section_items(section)
292
+ case section.kind
293
+ when :identity then [[section.ref.to_s, section.ref, section.text.length, "system"]] if section.ref
294
+ when :notes
295
+ # In the text's order: it groups the notes by scope.
296
+ Array(section.ref).group_by(&:scope).values.flatten(1).map do |note|
297
+ [note.name, note.name, "## #{note.name}\n#{note.body}".length, note.scope]
298
+ end
299
+ when :preloads
300
+ scopes = @section_preload_scopes
301
+ item_list(Array(section.ref), @section_preload_chars) { |name| [name, name] }
302
+ &.each_with_index&.map { |item, index| [*item, scopes&.[](index)] }
303
+ when :agents, :appended
304
+ top = MemoryPaths.work_tree_root(Dir.pwd)
305
+ item_list(Array(section.ref), @section_item_chars[section.kind]) { |path| [file_label(path, top), path] }
306
+ when :plugins
307
+ Array(section.ref).map { |built| ["#{built.bundle}: #{built.name}", "#{built.bundle}/#{built.name}", built.prompt_text.length] }
308
+ when :indexes
309
+ [["project memory index", "project", @section_index_chars[:project]], ["system memory index", "system", @section_index_chars[:system]]]
310
+ end&.then { |items| items.empty? ? nil : items }
311
+ end
312
+
313
+ # A file part's label: its path under the work tree +top+ (AGENTS.md,
314
+ # docs/rules.md), else with ~ for the home directory.
315
+ def file_label(path, top)
316
+ return Paths.tilde(path) unless top && path.start_with?("#{top}/")
317
+
318
+ path.delete_prefix("#{top}/")
319
+ end
320
+
321
+ # [label, ref, chars] per ref (+yield+ gives label and ref), nil when
322
+ # the recorded chars don't line up with the refs.
323
+ def item_list(refs, chars)
324
+ return nil unless chars && chars.size == refs.size
325
+
326
+ refs.each_with_index.map { |ref, index| [*yield(ref), chars[index]] }
205
327
  end
206
328
 
207
329
  # The session's tools as a build under +layers+ declares them, read
@@ -348,21 +470,59 @@ module Samagotchi
348
470
  thinking_token = chat ? "" : Thinking.native(thinking || turn_thinking, profile).system_token
349
471
  indexes = { project: read_memory_index("project"), system: read_memory_index("system") }
350
472
  @measured_index = measure_indexes(indexes)
351
- memory_sections = [
352
- "Project memories:\n#{indexes[:project]}",
353
- "System memories:\n#{indexes[:system]}"
354
- ].join("\n\n")
355
- stable = [thinking_token + base, not_loaded_line(surface), rg_guidance, system_identity_section, model_notes_section, explicit_memory_section,
356
- project_specific_description, appended_section, kit_prompt_section(surface), plugin_prompt_section, memory_sections]
357
- stable_text = stable.compact.join("\n")
358
- volatile = [participants_section, current_model, project_location, current_session].compact
473
+ memory_sections = %i[project system].map { |scope| memory_sections_head(indexes, scope) }.join("\n\n")
474
+ # Built eagerly and in this order: the builders set the @section_* scratch.
475
+ base_text = [thinking_token + base, not_loaded_line(surface), rg_guidance].compact.join("\n")
476
+ @section_index_chars = { project: memory_sections_head(indexes, :project).length,
477
+ system: memory_sections_head(indexes, :system).length }
478
+ stable = [
479
+ Section.new(kind: :base, ref: nil, text: base_text),
480
+ section(:identity, -> { @section_identity_memory_name }) { system_identity_section },
481
+ section(:notes, -> { @section_notes }) { model_notes_section },
482
+ section(:preloads, -> { Array(@section_activated_memory_names).dup }) { explicit_memory_section },
483
+ files_section(:agents) { project_specific_description },
484
+ files_section(:appended) { appended_section },
485
+ section(:kit, nil) { kit_prompt_section(surface) },
486
+ section(:plugins, -> { @section_plugins }) { plugin_prompt_section },
487
+ Section.new(kind: :indexes, ref: %i[project system], text: memory_sections)
488
+ ].compact
489
+ stable_text = stable.map(&:text).join("\n")
490
+ volatile = [section(:participants, nil) { participants_section }, section(:model, nil) { current_model },
491
+ section(:location, nil) { project_location }, section(:session, nil) { current_session }].compact
492
+ @section_parts = stable + volatile
359
493
  return with_tail_declarations(stable_text, chat: chat, surface: surface) if volatile.empty?
360
494
 
361
- prompt = "#{stable_text}\n#{volatile.join("\n")}"
495
+ prompt = "#{stable_text}\n#{volatile.map(&:text).join("\n")}"
362
496
  @measured_stable_length = stable_text.length + 1 if chat
363
497
  with_tail_declarations(prompt, chat: chat, surface: surface)
364
498
  end
365
499
 
500
+ # One scope's block of the indexes section.
501
+ def memory_sections_head(indexes, scope)
502
+ "#{scope.to_s.capitalize} memories:\n#{indexes[scope]}"
503
+ end
504
+
505
+ # A Section of +kind+ with what the block (a builder) returns, nil when
506
+ # that is nil (never when it is empty: an "" part stays in the prompt).
507
+ # +ref+ is read after the block ran, so it may name what the builder set.
508
+ def section(kind, ref = nil, &)
509
+ text = yield
510
+ if text.nil?
511
+ nil
512
+ else
513
+ Section.new(kind: kind, ref: ref.respond_to?(:call) ? ref.call : ref, text: text)
514
+ end
515
+ end
516
+
517
+ # A Section whose ref is the files its builder added to @section_files.
518
+ def files_section(kind, &block)
519
+ before = @section_files&.size || 0
520
+ section(kind, nil, &block)&.then do |part|
521
+ @section_item_chars[kind] = Array(@section_file_chars)[before..].dup if @section_item_chars
522
+ part.with(ref: Array(@section_files)[before..].dup)
523
+ end
524
+ end
525
+
366
526
  # The tools the session's toolkit leaves out, named once right after the
367
527
  # base prompt: sessions on another toolkit already differ at the tools,
368
528
  # and nothing later (a memory write) moves it. nil when none are (full):
@@ -432,6 +592,7 @@ module Samagotchi
432
592
  next if body.start_with?("Error:")
433
593
  next if body.strip.empty?
434
594
 
595
+ @section_identity_memory_name = name
435
596
  return "System identity (auto-loaded, scope=system):\n#{body}"
436
597
  end
437
598
  nil
@@ -546,7 +707,11 @@ module Samagotchi
546
707
  # status line. The memory-body injection itself stays here — the
547
708
  # SystemPrompt is the single source of truth for the system prompt.
548
709
  @activated_memory_names << actual_name
549
- entries << "this memory is required by the user in the current context: memory name: #{actual_name}\n#{body}"
710
+ @section_activated_memory_names << actual_name
711
+ entry = "this memory is required by the user in the current context: memory name: #{actual_name}\n#{body}"
712
+ @section_preload_chars&.push(entry.length)
713
+ @section_preload_scopes&.push(scope || answered_scope(body, actual_name))
714
+ entries << entry
550
715
  end
551
716
  end
552
717
 
@@ -555,6 +720,18 @@ module Samagotchi
555
720
  entries.join("\n\n")
556
721
  end
557
722
 
723
+ # The scope whose file answered a bare preload's read (memory_read
724
+ # falls back project -> system): its file under the project's memories
725
+ # is the project's, else the system's. nil without the read's record (a
726
+ # plain String body).
727
+ def answered_scope(body, name)
728
+ read = body.respond_to?(:reads) ? body.reads[name] : nil
729
+ return nil unless read.is_a?(Hash)
730
+
731
+ dir = read[:project_dir]
732
+ dir && read[:path].to_s.start_with?("#{dir}/") ? "project" : "system"
733
+ end
734
+
558
735
  def split_memory_scope(raw)
559
736
  value = raw.to_s.strip
560
737
  if value.include?("/")
@@ -577,6 +754,7 @@ module Samagotchi
577
754
  return nil if sections.empty?
578
755
 
579
756
  @section_files&.concat(sections.map(&:path))
757
+ @section_file_chars&.concat(sections.map { |section| section.text.length })
580
758
  sections.map(&:text).join("\n\n")
581
759
  end
582
760
  end
@@ -603,6 +781,7 @@ module Samagotchi
603
781
  next unless text
604
782
 
605
783
  @section_files&.push(path)
784
+ @section_file_chars&.push(text.length)
606
785
  sections << text
607
786
  end
608
787
  sections.empty? ? nil : sections.join("\n\n")
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.176.0"
4
+ VERSION = "0.177.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -201,7 +201,7 @@ module Samagotchi
201
201
  status = Session::STATUS_IDLE if status == Session::STATUS_RUNNING && reads.turn_snapshot && reads.current_turn.nil?
202
202
  json_response(200, {
203
203
  tail: true,
204
- session: { id: id, status: status, used_memory_names: [], prompt_notes: [] },
204
+ session: { id: id, status: status, used_memory_names: [], prompt_notes: [], prompt_parts: [] },
205
205
  messages: with_reply_html([answer].compact),
206
206
  # The owner's chi web's own setup notes: never a participant's.
207
207
  markdown_warning: nil,
@@ -1599,6 +1599,9 @@ store.on("paintActive", () => lists.paintActive());
1599
1599
  store.on("settingsPanel", () => settingsControl?.refresh());
1600
1600
  // The working set's list offers pin only under forget.
1601
1601
  store.on("workingSetStrategy", () => workingSet?.strategyChanged());
1602
+ store.on("workingSet", () => workingSet?.sessionChanged());
1603
+ // ?.(): a page holding an older working_set_view.js cached (the mixed-cache rule).
1604
+ store.on("workingSetTokens", () => workingSet?.tokensChanged?.());
1602
1605
  store.on("featureGates", () => featureGates.check(store.current));
1603
1606
  store.on("composer", composerMode.update);
1604
1607
  store.on("composer", () => objectives.redraw());
@@ -0,0 +1,33 @@
1
+ // The context's token count, next to its % (ctx.js): what the working set's
2
+ // head view says is in chi's head ("~X of Y") and what its Conversation row is
3
+ // the rest of. The same data ctx.js extractCtxPct reads: a :context_status's
4
+ // usage.estimated_used_tokens, a :generation_chunk's counts.total_tokens; on
5
+ // load the live worker's newest % back into tokens, else the saved
6
+ // timing.context.used_tokens.
7
+ //
8
+ // A module of its own: static JS is cached at unversioned URLs, and a new
9
+ // export on an old module would blank the page.
10
+
11
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
12
+
13
+ // The tokens in context a stream event says (+data+: a :context_status or a
14
+ // :generation_chunk), null when it says none.
15
+ export function ctxTokensOf(data) {
16
+ if (!data || typeof data !== "object") return null;
17
+ const used = num(data.usage?.estimated_used_tokens);
18
+ if (used !== null) return used;
19
+ return num(data.counts?.total_tokens);
20
+ }
21
+
22
+ // On load: the live worker's newest % (+pct+, counted against the window or
23
+ // the smaller budget) as tokens when the window is known, else the saved
24
+ // count (+context+: the session's timing.context). null when neither is.
25
+ export function loadedCtxTokens({ pct = null, context = null, budgetTokens = null } = {}) {
26
+ const window = num(context?.window_tokens);
27
+ if (num(pct) !== null && window && window > 0) {
28
+ const budget = num(budgetTokens);
29
+ const against = budget && budget > 0 ? Math.min(budget, window) : window;
30
+ return Math.round((pct / 100) * against);
31
+ }
32
+ return num(context?.used_tokens);
33
+ }
@@ -1123,12 +1123,41 @@ button.ws-step:hover:not(:disabled){filter:none}@media(hover:hover){button.ws-st
1123
1123
  /* The expanded view (a chip popover; a bottom sheet on a phone). */
1124
1124
  .ws-popover{gap:0}
1125
1125
  .ws-popover .ctx-pop-head{align-items:center;flex-wrap:wrap;margin-bottom:4px}
1126
- .ws-scope{display:inline-flex;gap:2px}
1127
- .ws-scope button{padding:1px 8px;border:1px solid transparent;border-radius:999px;background:transparent;color:var(--text-muted);font-size:11px;line-height:16px}
1128
- .ws-scope button.on{color:var(--text-2);border-color:var(--border-strong);background:var(--bg-raised)}
1129
- .ws-scope button:hover:not(:disabled){filter:none}@media(hover:hover){.ws-scope button:hover:not(:disabled){color:var(--text)}}
1126
+ /* The ring sits by ×, at the header's end (no size text between them now). */
1127
+ .ws-popover .ctx-pop-head>.ws-ring{margin-left:auto}
1128
+ .ws-popover .ctx-pop-head>.ws-ring~.ctx-pop-close{margin-left:0}
1129
+ .ws-lens{display:inline-flex;gap:2px;align-items:center}
1130
+ .ws-lens button{padding:1px 8px;border:1px solid transparent;border-radius:999px;background:transparent;color:var(--text-muted);font-size:11px;line-height:16px}
1131
+ .ws-lens button.arrow{padding:1px 5px}
1132
+ .ws-lens button.on{color:var(--text-2);border-color:var(--border-strong);background:var(--bg-raised)}
1133
+ .ws-lens button:disabled{opacity:.4}
1134
+ .ws-lens button:hover:not(:disabled){filter:none}@media(hover:hover){.ws-lens button:hover:not(:disabled){color:var(--text)}}
1135
+ /* A turn lens (--ws-lens-dim): the rows the turn touched lit, the rest dimmed; the line under the header says how many. */
1136
+ .ws-row.dim{opacity:var(--ws-lens-dim)}
1137
+ .ws-row.lit{background:var(--accent-tint)}
1130
1138
  .ws-popover .ctx-pop-meta{margin-top:6px;color:var(--ws-muted)}
1139
+ .ws-popover .ws-lens-line{color:var(--accent)}
1131
1140
  .ws-popover .ws-hint{margin-top:10px;color:var(--ws-faint)}
1141
+ /* The head view (ws_sections.js): From the start · Read in this session · Conversation, each header folding (per session); prompt parts read-only rows; a prompt memory read again "held twice" in the warn tokens. */
1142
+ .ws-sec-head{display:flex;align-items:center;gap:8px;width:100%;min-height:30px;box-sizing:border-box;margin-top:6px;padding:0 6px;border:0;border-top:1px solid var(--border);border-radius:0;background:transparent;font-family:ui-sans-serif,system-ui,sans-serif;font-size:12px;color:var(--ws-muted);text-align:left;cursor:pointer}
1143
+ .ws-sec-head:hover:not(:disabled){filter:none}@media(hover:hover){.ws-sec-head:hover{background:var(--bg-hover)}}
1144
+ .ws-sec-head .k{flex:none;width:12px;text-align:center;color:var(--ws-faint)}
1145
+ .ws-sec-head .t{font-weight:600;color:var(--text-2)}
1146
+ .ws-sec-head .n{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ws-faint)}
1147
+ .ws-sec-head .tk{flex:none;margin-left:auto;font-size:11px;color:var(--ws-faint);font-variant-numeric:tabular-nums}
1148
+ .ws-sec .ws-sub{margin-top:2px;padding-left:6px}
1149
+ .ws-row.part .t{margin-right:auto;font-family:ui-sans-serif,system-ui,sans-serif}
1150
+ /* Conversation: one row at section level (a section header's look, nothing to fold). */
1151
+ .ws-row.ws-sec-row{height:30px;margin-top:6px;border-top:1px solid var(--border);border-radius:0;font-family:ui-sans-serif,system-ui,sans-serif;font-size:12px}
1152
+ .ws-row.ws-sec-row .t{flex:none;font-weight:600;color:var(--text-2)}
1153
+ .ws-row.ws-sec-row .n{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ws-faint)}
1154
+ .ws-row.ws-sec-row .tk{margin-left:auto}
1155
+ .ws-popover.sheet .ws-row.ws-sec-row{font-size:13px}
1156
+ .ws-twice{flex:none;padding:0 6px;border:1px solid var(--warn-border);border-radius:999px;background:var(--warn-bg);color:var(--warn-text);font-family:ui-sans-serif,system-ui,sans-serif;font-size:10.5px;line-height:15px;white-space:nowrap}
1157
+ .ws-step.twice{color:var(--warn-text);background:var(--warn-bg)}
1158
+ .ws-row.twice.lit{background:var(--warn-bg)}
1159
+ .ws-note{padding:0 6px 4px 26px;font-size:11px;line-height:15px}
1160
+ .ws-note.twice{color:var(--warn-text);background:var(--warn-bg);border-radius:0 0 6px 6px}
1132
1161
  .ws-row{display:flex;align-items:center;gap:8px;width:100%;min-width:0;height:28px;box-sizing:border-box;padding:0 6px;border:0;border-radius:6px;background:transparent;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12.5px;line-height:28px;color:var(--text-2);text-align:left}
1133
1162
  @media(hover:hover){.ws-row:hover{background:var(--bg-hover)}}
1134
1163
  button.ws-row:hover:not(:disabled){filter:none}@media(hover:hover){button.ws-row:hover:not(:disabled){background:var(--bg-hover)}}
@@ -1172,11 +1201,16 @@ button.ws-row:hover:not(:disabled){filter:none}@media(hover:hover){button.ws-row
1172
1201
  .ws-strip{display:flex;gap:8px;padding:2px 6px 6px 26px}
1173
1202
  .ws-strip .ws-act-b{padding:0 14px;font-size:12.5px;line-height:28px;border-radius:6px}
1174
1203
  .ws-popover.sheet{border-radius:14px}
1175
- /* A phone's sheet: the name, the scope and × on the first line, the count and the ring under them. */
1176
- .ws-popover.sheet .ctx-pop-close{order:2}
1177
- .ws-popover.sheet .ctx-pop-head>.ctx-pop-kind{order:3;flex:1 0 calc(100% - 30px)}
1178
- .ws-popover.sheet .ctx-pop-head>.ws-ring{order:4}
1179
- .ws-popover.sheet .ws-row{height:30px;line-height:30px}
1204
+ /* A phone's sheet: one line, the name, the lens, the ring and ×; the size is the line under it. */
1205
+ .ws-popover.sheet .ctx-pop-head{flex-wrap:nowrap;gap:4px}
1206
+ .ws-popover.sheet .ws-lens{flex:none;white-space:nowrap}
1207
+ /* A long turn number (turn 100) shortens the name, never wraps the line. */
1208
+ .ws-popover.sheet .ctx-pop-head strong{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1209
+ /* A phone's sheet: rows and lens buttons 44 px targets; a part row drops its sub text. */
1210
+ .ws-popover.sheet .ws-row{height:44px;line-height:44px}
1211
+ .ws-popover.sheet .ws-sec-head{min-height:44px;font-size:13px}
1212
+ .ws-popover.sheet .ws-lens button{min-height:44px;min-width:44px;padding:1px 4px;font-size:12.5px;white-space:nowrap}
1213
+ .ws-popover.sheet .ws-row.part .st{display:none}
1180
1214
  /* + add: the list's foot (a sheet's last row), one KEY typed; an added item the set doesn't hold yet is a pending row of its own. */
1181
1215
  .ws-add{display:flex;align-items:center;gap:6px;margin-top:8px}
1182
1216
  .ws-add-in{flex:1;min-width:0;height:26px;box-sizing:border-box;padding:0 8px;border:1px dashed var(--border-strong);border-radius:6px;background:transparent;color:var(--text);font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px}
@@ -34,12 +34,15 @@ export const FIELDS = {
34
34
  firstPreview: { redraws: ["infoBar"], writers: "send_turn.js (the first prompt)" },
35
35
  usedMemories: {
36
36
  source: (d) => list(d.session?.used_memory_names),
37
- redraws: ["infoBar"],
37
+ redraws: ["workingSet", "infoBar"],
38
38
  writers: "setUsedMemories (stream), readTurnEnd; both replace the card too",
39
39
  },
40
- preloadedMemories: { source: (d) => list(d.session?.preloaded_memory_names), redraws: ["infoBar"], writers: "the payload" },
40
+ preloadedMemories: { source: (d) => list(d.session?.preloaded_memory_names), redraws: ["workingSet", "infoBar"], writers: "the payload" },
41
41
  mutedMemories: { source: (d) => list(d.session?.muted_memory_names), redraws: ["infoBar"], writers: "the payload" },
42
- promptNotes: { source: (d) => list(d.session?.prompt_notes), redraws: ["infoBar"], writers: "readTurnEnd" },
42
+ promptNotes: { source: (d) => list(d.session?.prompt_notes), redraws: ["workingSet", "infoBar"], writers: "readTurnEnd" },
43
+ // A tail without the key (an older live worker) keeps the parts the page
44
+ // has: unknown is not none; only a list replaces them.
45
+ promptParts: { source: (d) => list(d.session?.prompt_parts), redraws: ["workingSet"], writers: "readTurnEnd" },
43
46
  parentId: { redraws: ["infoBar"], writers: "the payload" },
44
47
  continues: { redraws: ["infoBar"], writers: "the payload" },
45
48
  verdicts: {
@@ -54,7 +57,10 @@ export const FIELDS = {
54
57
  },
55
58
  createdAt: { redraws: ["infoBar"], writers: "the payload" },
56
59
  ctxPct: { redraws: ["infoBar"], writers: "session_state.js sessionStateFrom (the payload's context_status, else the saved fill), stream_handlers.js (generation_chunk, context_status)" },
57
- ctxWindow: { redraws: ["infoBar"], writers: "stream_handlers.js (generation_started, context_status)" },
60
+ // Changes with almost every chunk: its redraw draws the open list only
61
+ // when the text it shows changes (working_set_view.js tokensChanged).
62
+ ctxTokens: { redraws: ["workingSetTokens"], writers: "session_state.js sessionStateFrom (ctx_tokens.js loadedCtxTokens), stream_handlers.js (generation_chunk, context_status; cleared with ctxPct)" },
63
+ ctxWindow: { redraws: ["workingSetTokens", "infoBar"], writers: "stream_handlers.js (generation_started, context_status)" },
58
64
  ctxWindowSource: { redraws: ["infoBar"], writers: "stream_handlers.js (generation_started, context_status)" },
59
65
  ctxUnknownAfterSwitch: { redraws: ["infoBar"], writers: "stream_handlers.js (generation_started, context_status)" },
60
66
  status: {
@@ -1,6 +1,8 @@
1
1
  // A session's own view settings (per browser, localStorage through
2
2
  // storage.js): the stage's fold, the composer's dragged height and its fold,
3
- // the working-set rail's fold. Each is kept under `<key>:<session>`, so what
3
+ // the working-set rail's fold, the working-set list's folded sections
4
+ // (ws_sections.js WS_SECTION_FOLD, defined there: a new export here would
5
+ // blank a page holding this module cached). Each is kept under `<key>:<session>`, so what
4
6
  // you do to one session's window never shows in another, and a session never
5
7
  // set by hand follows the default: the page's own (the stage fold's comes
6
8
  // from config, web.stage_collapsed, as <body data-stage-collapsed="1">), else
@@ -20,12 +22,13 @@
20
22
  // A module of its own: static JS is cached at unversioned URLs, and a new
21
23
  // export on an old module would blank the page.
22
24
  import { readStored, removeStored, storedKeys, writeStored } from "./storage.js";
25
+ import { WS_SECTION_FOLD } from "./ws_sections.js";
23
26
 
24
27
  export const STAGE_FOLD = "chi_stage_collapsed";
25
28
  export const COMPOSER_FLOOR = "chi_composer_floor";
26
29
  export const COMPOSER_FOLD = "chi_composer_collapsed";
27
30
  export const WS_RAIL_FOLD = "chi_working_set_collapsed";
28
- export const PREF_KEYS = [STAGE_FOLD, COMPOSER_FLOOR, COMPOSER_FOLD, WS_RAIL_FOLD];
31
+ export const PREF_KEYS = [STAGE_FOLD, COMPOSER_FLOOR, COMPOSER_FOLD, WS_RAIL_FOLD, WS_SECTION_FOLD];
29
32
 
30
33
  // The page's defaults: <body>'s data attribute that turns a key on ("1").
31
34
  const PAGE_DEFAULTS = { [STAGE_FOLD]: "stageCollapsed" };
@@ -5,6 +5,7 @@
5
5
  // shows for the next one).
6
6
 
7
7
  import { savedCtxPct } from "./ctx.js";
8
+ import { loadedCtxTokens } from "./ctx_tokens.js";
8
9
  import { firstPreview, previewForCard } from "./format.js";
9
10
  import { normalizeTiming } from "./timing.js";
10
11
 
@@ -19,6 +20,10 @@ export function emptySessionState() {
19
20
  // The model notes the session's prompt carried (its prompt_notes: name,
20
21
  // scope, chars, digest; the info bar's notes chip).
21
22
  promptNotes: [],
23
+ // The parts of its system prompt as sizes (its prompt_parts: kind, label,
24
+ // chars, tokens, ref; the working set's "From the start"). [] from an
25
+ // older worker or file: no head-view sections.
26
+ promptParts: [],
22
27
  // A delegated session's parent (the info bar's "delegated by" chip).
23
28
  parentId: null,
24
29
  // The previous link of its chain (its `continues`), or null.
@@ -30,6 +35,9 @@ export function emptySessionState() {
30
35
  // times on its day), or null.
31
36
  createdAt: null,
32
37
  ctxPct: null,
38
+ // The tokens in context now (ctx_tokens.js: the count ctxPct is of; the
39
+ // working set's "in chi's head now"), or null.
40
+ ctxTokens: null,
33
41
  // Window the kernel resolved for the running generation (:generation_started).
34
42
  ctxWindow: null,
35
43
  // Where it came from ("server", "config", … "default": chi's guess).
@@ -111,7 +119,8 @@ export function sessionStateFrom(data) {
111
119
  // JSON as context_status, kept per request by the Engine) beats the saved
112
120
  // fill, which is only the last counted turn's; without it, the saved fill.
113
121
  const livePct = s.context_status?.est_pct;
114
- if (typeof livePct === "number" && Number.isFinite(livePct)) {
122
+ const live = typeof livePct === "number" && Number.isFinite(livePct);
123
+ if (live) {
115
124
  state.ctxPct = livePct;
116
125
  } else {
117
126
  // The saved fill, so a reloaded or stopped session shows it before its
@@ -119,6 +128,9 @@ export function sessionStateFrom(data) {
119
128
  const savedPct = savedCtxPct(data.timing?.context, s.llm_context?.budget_tokens);
120
129
  if (savedPct !== null) state.ctxPct = savedPct;
121
130
  }
131
+ // Its tokens, from the same source; left out (kept) when neither says.
132
+ const tokens = loadedCtxTokens({ pct: live ? livePct : null, context: data.timing?.context, budgetTokens: s.llm_context?.budget_tokens });
133
+ if (tokens !== null) state.ctxTokens = tokens;
122
134
  if (data.timing?.context?.window_tokens) {
123
135
  state.ctxWindow = data.timing.context.window_tokens;
124
136
  state.ctxWindowSource = data.timing.context.window_source || null;
@@ -128,6 +140,7 @@ export function sessionStateFrom(data) {
128
140
  state.preloadedMemories = s.preloaded_memory_names || [];
129
141
  state.mutedMemories = s.muted_memory_names || [];
130
142
  state.promptNotes = Array.isArray(s.prompt_notes) ? s.prompt_notes : [];
143
+ state.promptParts = Array.isArray(s.prompt_parts) ? s.prompt_parts : [];
131
144
  state.llmContext = s.llm_context || null;
132
145
  state.thinking = s.thinking || null;
133
146
  // null on a native host (it ignores the level) and from an older worker.
@@ -17,7 +17,7 @@ import { FIELDS, statusWrite } from "./session_fields.js";
17
17
  export const ORDER = [
18
18
  "lists",
19
19
  "paintActive",
20
- "settingsPanel", "workingSetStrategy",
20
+ "settingsPanel", "workingSetStrategy", "workingSet", "workingSetTokens",
21
21
  "featureGates",
22
22
  "composer",
23
23
  "infoBar",
@@ -283,7 +283,7 @@ export function createSessionView(deps) {
283
283
  // answer's markdown.
284
284
  store.batch(() => {
285
285
  // The notes chip: the first turn's build (or a /model) records them.
286
- applySessionPayload(d, { fields: ["usedMemories", "promptNotes"] });
286
+ applySessionPayload(d, { fields: ["usedMemories", "promptNotes", "promptParts"] });
287
287
  turnEndStatus(d);
288
288
  setMarkdownWarning(d.markdown_warning);
289
289
  markdownTip.show(d.markdown_tip);
@@ -47,6 +47,7 @@
47
47
 
48
48
  import { routeChunk } from "./chunk_router.js";
49
49
  import { extractCtxPct, generationTokens } from "./ctx.js";
50
+ import { ctxTokensOf } from "./ctx_tokens.js";
50
51
  import { failedTurnText, fullTime } from "./format.js";
51
52
  import { cancelLineText } from "./timing.js";
52
53
  import { keepFollowing } from "./scroll.js";
@@ -92,8 +93,9 @@ export function createStreamHandlers(deps) {
92
93
  turnDom.chunk({ text, thinking, iteration: data.iteration ?? null, now: data.replayed ? null : Date.now() });
93
94
  const current = store.current;
94
95
  const pct = extractCtxPct(data, current.ctxWindow, current.llmContext?.budget_tokens);
95
- // A chunk with the same % redraws nothing (the store compares).
96
- if (pct !== null && !Number.isNaN(pct)) store.update({ current: { ctxPct: pct } });
96
+ // A chunk with the same % redraws nothing (the store compares); its
97
+ // tokens go with it (the working set's head line).
98
+ if (pct !== null && !Number.isNaN(pct)) store.update({ current: { ctxPct: pct, ctxTokens: ctxTokensOf(data) ?? current.ctxTokens } });
97
99
  },
98
100
  generation_started: (data) => {
99
101
  // The request after a /model's unresolved window started: whatever it
@@ -399,12 +401,14 @@ export function createStreamHandlers(deps) {
399
401
  patch.ctxUnknownAfterSwitch = !data.context_window_tokens;
400
402
  }
401
403
  if (data && "usage" in data && data.usage === null) {
402
- store.update({ current: { ...patch, ctxPct: null } });
404
+ store.update({ current: { ...patch, ctxPct: null, ctxTokens: null } });
403
405
  return;
404
406
  }
405
407
  const ctxWindow = "ctxWindow" in patch ? patch.ctxWindow : current.ctxWindow;
406
408
  const pct = extractCtxPct(data, ctxWindow, current.llmContext?.budget_tokens);
407
409
  if (pct !== null) patch.ctxPct = pct;
410
+ const tokens = ctxTokensOf(data);
411
+ if (tokens !== null) patch.ctxTokens = tokens;
408
412
  store.update({ current: patch });
409
413
  },
410
414
  question_requested: (data) => {
@@ -3,11 +3,11 @@
3
3
  --glass-bg:color-mix(in srgb,var(--bg-panel) 70%,transparent);--glass-border:rgba(255,255,255,.08);--glass-highlight:rgba(255,255,255,.05);--glass-shadow:0 8px 30px rgba(0,0,0,.35);
4
4
  --diff-add-bg:rgba(63,185,80,.14);--diff-add-text:#aff5b4;--diff-del-bg:rgba(248,81,73,.14);--diff-del-text:#ffc1bc;
5
5
  --code-text:#c9d1d9;--code-keyword:#ff7b72;--code-string:#a5d6ff;--code-comment:#8b949e;--code-constant:#79c0ff;--code-func:#d2a8ff;--code-type:#ffa657;
6
- --card-hover-border:rgba(255,255,255,.14);--on-solid:#fff;--on-warn:#fff;--text-hover:#fff;--badge-bg:rgba(255,255,255,.08);--badge-ring:rgba(255,255,255,.18);--shadow-strong:rgba(0,0,0,.5);--backdrop:rgba(0,0,0,.85);--toast-shadow:0 6px 24px rgba(0,0,0,.25);--ws-stale-opacity:.4;--ws-rule:var(--border-strong);--ws-muted:var(--text-3);--ws-faint:var(--text-muted);--ws-act-border:#444c56;--author-1:#79c0ff;--author-2:#d2a8ff;--author-3:#7ee787;--author-4:#ffa657;--author-5:#ff7b72;--author-6:#f2cc60;--author-owner:var(--text-3);--time-gap:var(--text-faint);
6
+ --card-hover-border:rgba(255,255,255,.14);--on-solid:#fff;--on-warn:#fff;--text-hover:#fff;--badge-bg:rgba(255,255,255,.08);--badge-ring:rgba(255,255,255,.18);--shadow-strong:rgba(0,0,0,.5);--backdrop:rgba(0,0,0,.85);--toast-shadow:0 6px 24px rgba(0,0,0,.25);--ws-stale-opacity:.4;--ws-lens-dim:.38;--ws-rule:var(--border-strong);--ws-muted:var(--text-3);--ws-faint:var(--text-muted);--ws-act-border:#444c56;--author-1:#79c0ff;--author-2:#d2a8ff;--author-3:#7ee787;--author-4:#ffa657;--author-5:#ff7b72;--author-6:#f2cc60;--author-owner:var(--text-3);--time-gap:var(--text-faint);
7
7
  --claim-mark:color-mix(in srgb,var(--warn-bright) 32%,transparent);--claim-ring:var(--warn)}
8
8
  /* Light palette: follows the system setting. :not([data-theme="dark"]) leaves room for a later in-page toggle (data-theme on <html>); there is none yet. Each palette sets color-scheme, so native radios, inputs and scrollbars follow it. */
9
9
  @media (prefers-color-scheme:light){:root:not([data-theme="dark"]){color-scheme:light;--bg:#f5f6f8;--bg-top:#dde8f4;--bg-panel:#ffffff;--bg-inset:#f1f3f6;--bg-raised:#e8ebf0;--bg-hover:#eceff4;--border:#dde1e7;--border-strong:#c3c9d2;--text:#1f2328;--text-bright:#0d1117;--text-2:#2f363d;--text-3:#475160;--text-muted:#57606a;--text-faint:#636c76;--accent:#0066cc;--accent-strong:#0058b0;--accent-bg:#e3f0ff;--accent-ring:rgba(0,102,204,.2);--primary:#0071e3;--ok:#1a7f37;--ok-text:#116329;--ok-bg:#dafbe1;--warn:#9a6700;--warn-text:#7d4e00;--warn-bright:#875c00;--warn-bg:#fff6cc;--warn-border:#d4a72c;--danger:#cf222e;--danger-bg:#cf222e;--danger-text:#a40e26;--danger-bg-dim:#ffebe9;--think:#8250df;--think-text:#6639ba;--accent-border:#b3d4f7;--pick-border:#0969da;
10
10
  --glass-border:rgba(31,35,40,.10);--glass-highlight:rgba(255,255,255,.7);--glass-shadow:0 8px 30px rgba(31,35,40,.10);
11
11
  --diff-add-bg:rgba(26,127,55,.12);--diff-add-text:#116329;--diff-del-bg:rgba(207,34,46,.10);--diff-del-text:#82071e;
12
12
  --code-text:#1f2328;--code-keyword:#cf222e;--code-string:#0a3069;--code-comment:#57606a;--code-constant:#0550ae;--code-func:#8250df;--code-type:#953800;
13
- --card-hover-border:rgba(31,35,40,.18);--on-solid:#fff;--on-warn:#1f2328;--text-hover:#0d1117;--badge-bg:rgba(31,35,40,.06);--badge-ring:rgba(31,35,40,.15);--shadow-strong:rgba(31,35,40,.18);--backdrop:rgba(13,17,23,.85);--toast-shadow:0 6px 24px rgba(31,35,40,.14);--ws-stale-opacity:.55;--ws-rule:var(--border);--ws-muted:var(--text-muted);--ws-faint:var(--text-faint);--ws-act-border:var(--border-strong);--author-1:#0550ae;--author-2:#8250df;--author-3:#116329;--author-4:#953800;--author-5:#a40e26;--author-6:#7d4e00;--author-owner:var(--text-3);--time-gap:var(--text-faint)}}
13
+ --card-hover-border:rgba(31,35,40,.18);--on-solid:#fff;--on-warn:#1f2328;--text-hover:#0d1117;--badge-bg:rgba(31,35,40,.06);--badge-ring:rgba(31,35,40,.15);--shadow-strong:rgba(31,35,40,.18);--backdrop:rgba(13,17,23,.85);--toast-shadow:0 6px 24px rgba(31,35,40,.14);--ws-stale-opacity:.55;--ws-lens-dim:.38;--ws-rule:var(--border);--ws-muted:var(--text-muted);--ws-faint:var(--text-faint);--ws-act-border:var(--border-strong);--author-1:#0550ae;--author-2:#8250df;--author-3:#116329;--author-4:#953800;--author-5:#a40e26;--author-6:#7d4e00;--author-owner:var(--text-3);--time-gap:var(--text-faint)}}