samagotchi 0.95.0 → 0.97.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 (50) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +39 -1
  3. data/bin/chi +3 -0
  4. data/docs/architecture.md +2 -0
  5. data/docs/bundle-authoring.md +2 -1
  6. data/docs/cli.md +13 -1
  7. data/docs/configuration.md +13 -0
  8. data/docs/internals/background-tasks.md +1 -1
  9. data/docs/internals/bundles.md +1 -1
  10. data/docs/internals/engine.md +3 -1
  11. data/docs/memory.md +43 -3
  12. data/docs/plugins.md +4 -3
  13. data/docs/sessions.md +8 -2
  14. data/lib/samagotchi/bundle_command/check.rb +5 -3
  15. data/lib/samagotchi/bundle_command/try/run.rb +19 -4
  16. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  17. data/lib/samagotchi/children_status.rb +1 -1
  18. data/lib/samagotchi/engine.rb +49 -38
  19. data/lib/samagotchi/llm/errors.rb +100 -2
  20. data/lib/samagotchi/memory_bundle/profile.rb +14 -4
  21. data/lib/samagotchi/memory_command.rb +237 -0
  22. data/lib/samagotchi/plugin/api.rb +7 -3
  23. data/lib/samagotchi/plugin/sessions.rb +4 -3
  24. data/lib/samagotchi/send_command.rb +12 -12
  25. data/lib/samagotchi/session.rb +13 -1
  26. data/lib/samagotchi/session_commands.rb +13 -0
  27. data/lib/samagotchi/session_continue.rb +8 -8
  28. data/lib/samagotchi/session_delete_command.rb +1 -1
  29. data/lib/samagotchi/session_inbox.rb +29 -0
  30. data/lib/samagotchi/session_manager.rb +24 -7
  31. data/lib/samagotchi/sessions_command.rb +8 -6
  32. data/lib/samagotchi/terminal_ui/attached_loop.rb +2 -0
  33. data/lib/samagotchi/terminal_ui/status_row.rb +24 -3
  34. data/lib/samagotchi/terminal_ui.rb +1 -0
  35. data/lib/samagotchi/title_command.rb +61 -0
  36. data/lib/samagotchi/tools/memory.rb +1 -1
  37. data/lib/samagotchi/turn_checkpoint.rb +6 -0
  38. data/lib/samagotchi/version.rb +1 -1
  39. data/lib/samagotchi/web/app.rb +4 -4
  40. data/lib/samagotchi/web/public/app.js +12 -0
  41. data/lib/samagotchi/web/public/chains.js +21 -8
  42. data/lib/samagotchi/web/public/format.js +4 -3
  43. data/lib/samagotchi/web/public/index.html +7 -0
  44. data/lib/samagotchi/web/public/info_bar_model.js +2 -0
  45. data/lib/samagotchi/web/public/session_rename.js +86 -0
  46. data/lib/samagotchi/web/public/session_state.js +4 -2
  47. data/lib/samagotchi/web/session_summary.rb +3 -0
  48. data/lib/samagotchi/worker.rb +24 -7
  49. data/lib/samagotchi/worker_idle_exit.rb +16 -8
  50. metadata +4 -1
@@ -83,7 +83,7 @@ module Samagotchi
83
83
  # follows the chain to its new end instead.
84
84
  # @param id_or_ref [String] an id, a prefix, or last:<id> (SessionChain.resolve)
85
85
  # @param prompt [String, nil] its first message (nil: it starts idle)
86
- # @param title [String, nil] what the lists show before the first turn;
86
+ # @param preview [String, nil] what the lists show before the first turn;
87
87
  # by default the prompt, else the previous link's preview
88
88
  # @return [Session] the new link (#model_warning as spawn_session's,
89
89
  # #moved_children: the delegates it took over, #opener:
@@ -92,7 +92,7 @@ module Samagotchi
92
92
  # @raise [Refused] continued already, delegates open that can't
93
93
  # move, or its folder is gone
94
94
  # @raise [ArchiveRefused, OwnedByTUI] as archive_session
95
- def self.run(id_or_ref, prompt: nil, title: nil, model: nil, state_dir: nil, recap_wait: RECAP_WAIT, archive_wait: 5)
95
+ def self.run(id_or_ref, prompt: nil, preview: nil, model: nil, state_dir: nil, recap_wait: RECAP_WAIT, archive_wait: 5)
96
96
  sd = state_dir || Session.default_state_dir
97
97
  TRIES.times do |try|
98
98
  id = SessionChain.resolve(id_or_ref, state_dir: sd)
@@ -100,7 +100,7 @@ module Samagotchi
100
100
  follow = id_or_ref.to_s.strip.start_with?(SessionChain::LAST_PREFIX) && try < TRIES - 1
101
101
  next :moved if follow && SessionChain.next_of(id, state_dir: sd)
102
102
 
103
- run_locked(id, prompt: prompt, title: title, model: model, state_dir: sd, recap_wait: recap_wait,
103
+ run_locked(id, prompt: prompt, preview: preview, model: model, state_dir: sd, recap_wait: recap_wait,
104
104
  archive_wait: archive_wait)
105
105
  end
106
106
  return result unless result == :moved
@@ -116,7 +116,7 @@ module Samagotchi
116
116
  end
117
117
  end
118
118
 
119
- private_class_method def self.run_locked(id, prompt:, title:, model:, state_dir:, recap_wait:, archive_wait:)
119
+ private_class_method def self.run_locked(id, prompt:, preview:, model:, state_dir:, recap_wait:, archive_wait:)
120
120
  previous = Session.load(id, state_dir: state_dir)
121
121
  checked = check!(previous, state_dir, model: model)
122
122
  plan = checked.plan
@@ -132,7 +132,7 @@ module Samagotchi
132
132
  archive = SessionManager.archive_session(id, state_dir: state_dir, wait: archive_wait, except: plan.move)
133
133
  archived = archive[:archived] - already
134
134
  begin
135
- spawn_continuation(previous, prompt: prompt, title: title, choice: checked.choice, state_dir: state_dir,
135
+ spawn_continuation(previous, prompt: prompt, preview: preview, choice: checked.choice, state_dir: state_dir,
136
136
  move: plan.move)
137
137
  rescue StandardError
138
138
  # Nothing started: the delegates go back, what this archived goes
@@ -194,16 +194,16 @@ module Samagotchi
194
194
 
195
195
  # The new link, holding off any worker but its own (ChildMove.starting?)
196
196
  # while +move+ goes to it.
197
- private_class_method def self.spawn_continuation(previous, prompt:, title:, choice:, state_dir:, move:)
197
+ private_class_method def self.spawn_continuation(previous, prompt:, preview:, choice:, state_dir:, move:)
198
198
  recap = RecapStore.read(Session.session_dir(previous.id, state_dir: state_dir))
199
199
  start = prompt.to_s.strip.empty? ? nil : prompt
200
- title = previous.first_preview if title.to_s.strip.empty? && start.nil?
200
+ preview = previous.first_preview if preview.to_s.strip.empty? && start.nil?
201
201
  before_spawn = lambda do |link|
202
202
  ChildMove.mark_starting(link.id, state_dir: state_dir)
203
203
  ChildMove.apply(move, from: previous.id, to: link.id, state_dir: state_dir)
204
204
  end
205
205
  link = SessionManager.spawn_session(
206
- prompt: start, title: title, working_directory: previous.working_directory,
206
+ prompt: start, preview: preview, title: previous.title, working_directory: previous.working_directory,
207
207
  model_name: choice.model, setup: SessionSetup.of(previous),
208
208
  continues: previous.id, note: SessionChain.note_text(previous, recap: recap),
209
209
  note_source: SessionChain::NOTE_SOURCE, state_dir: state_dir, before_spawn: before_spawn
@@ -80,7 +80,7 @@ module Samagotchi
80
80
  end
81
81
 
82
82
  def preview_of(id)
83
- text = Session.load(id, state_dir: @state_dir).first_preview.to_s.gsub(/\s+/, " ").strip
83
+ text = Session.load(id, state_dir: @state_dir).display_title.gsub(/\s+/, " ").strip
84
84
  return nil if text.empty?
85
85
 
86
86
  text.length > PREVIEW_LIMIT ? "#{text[0, PREVIEW_LIMIT - 1]}…" : text
@@ -359,6 +359,35 @@ module Samagotchi
359
359
  end
360
360
  private_class_method :unmark_removed
361
361
 
362
+ # How old a per-input tombstone (input/removed/, TurnCheckpoint's
363
+ # input/settled/) gets before a worker's start prunes it (#prune_old).
364
+ # A wait reads one at its next poll (ReplyWait::POLL_INTERVAL) and a
365
+ # later `chi send --wait --turn` reads a settled one at its start, so
366
+ # only a wait whose process slept (a closed laptop) or one started long
367
+ # after needs it to stay. A removed one gone under a live wait would
368
+ # read as a merge (the wrong reply), so the age is generous: a week,
369
+ # half the session retention (14 days), for one small file per
370
+ # file-delivered command or dequeue.
371
+ TOMBSTONE_MAX_AGE = 7 * 24 * 3600
372
+
373
+ # Deletes the files in input/<+subdir+> last written more than
374
+ # +max_age+ seconds ago; one that can't be read or deleted stays.
375
+ # @return [Integer] how many went
376
+ def self.prune_old(session_dir, subdir, max_age: TOMBSTONE_MAX_AGE)
377
+ cutoff = Time.now - max_age
378
+ Dir.glob(File.join(session_dir, INPUT_DIR, subdir, "*")).count do |file|
379
+ next false unless File.mtime(file) < cutoff
380
+
381
+ File.delete(file)
382
+ true
383
+ rescue SystemCallError
384
+ false
385
+ end
386
+ end
387
+
388
+ # The removed tombstones past +max_age+ (#prune_old).
389
+ def self.prune_removed(session_dir, max_age: TOMBSTONE_MAX_AGE) = prune_old(session_dir, REMOVED_DIR, max_age: max_age)
390
+
362
391
  # @return [Boolean] whether the queued input +enqueued_id+ was removed
363
392
  # before it ran (#take_queued_input's tombstone), or is being removed:
364
393
  # the tombstone goes first, so while its claimed file is still there
@@ -138,8 +138,11 @@ module Samagotchi
138
138
  # @param messages [Array<Hash>] a conversation to start from (a plugin's
139
139
  # ctx.sessions.fork); its image refs are copied from +images_from+
140
140
  # @param images_from [String, nil] the session dir the seed's images are in
141
- # @param title [String, nil] what the lists show before the first turn
141
+ # @param preview [String, nil] what the lists show before the first turn
142
142
  # (the prompt's preview by default, else the seed's first user message)
143
+ # @param title [String, nil] the session's own name (Session#title; a
144
+ # continue's link inherits its previous link's), saved before the
145
+ # worker starts: the worker owns the file from then on
143
146
  # @param setup [SessionSetup] the session's own settings (chi
144
147
  # --llm-context; a fork and a continue copy their session's; a delegate
145
148
  # child the toolkit its delegate call named); without a toolkit the
@@ -156,7 +159,7 @@ module Samagotchi
156
159
  # and #model_warning: an id its host's saved list doesn't have
157
160
  def self.spawn_session(prompt:, mode: "assist", working_directory: nil, model_name: nil, state_dir: nil,
158
161
  memories: [], muted_memories: [], parent_id: nil, messages: [], images_from: nil,
159
- title: nil, delegate: false, setup: SessionSetup.new, continues: nil, note: nil,
162
+ preview: nil, title: nil, delegate: false, setup: SessionSetup.new, continues: nil, note: nil,
160
163
  note_source: "chi", before_spawn: nil)
161
164
  sd = state_dir || Session.default_state_dir
162
165
  # The resolved ref is stored (a resumed session keeps its model when an
@@ -189,7 +192,8 @@ module Samagotchi
189
192
  session.last_prompt = prompt
190
193
  # The worker takes last_prompt and clears it, and messages are saved at
191
194
  # the turn's end: until then this is the only preview a list has.
192
- session.first_preview = Session.preview_of(title.to_s.strip.empty? ? prompt : title)
195
+ session.first_preview = Session.preview_of(preview.to_s.strip.empty? ? prompt : preview)
196
+ session.title = title
193
197
  session_dir = Session.session_dir(session.id, state_dir: sd)
194
198
  unless session.messages.empty?
195
199
  session.messages, dropped = ImageStore.copy_refs(session.messages, from: images_from, to: session_dir)
@@ -321,7 +325,7 @@ module Samagotchi
321
325
  owned = !!owner&.worker?
322
326
  next if live && !owned
323
327
 
324
- { id: s.id, short_id: s.id[0, 8], desc: summary_desc(s), preview: summary_preview(s), cwd: s.working_directory,
328
+ { id: s.id, short_id: s.id[0, 8], desc: summary_desc(s), preview: summary_preview(s), title: s.title, cwd: s.working_directory,
325
329
  project: s.project_root(cache: roots), updated_at: s.updated_at, status: s.status, live: owned, busy: owned && s.status == Session::STATUS_RUNNING,
326
330
  owner: owner&.kind, recap: RecapStore.preview(Session.session_dir(s.id, state_dir: sd)),
327
331
  ctx_pct: SessionMetrics.saved_context_pct(Session.session_dir(s.id, state_dir: sd),
@@ -464,10 +468,12 @@ module Samagotchi
464
468
  cut(summary_text(session), SUMMARY_PREVIEW_LIMIT)
465
469
  end
466
470
 
467
- # A session as one line of text for the lists: its last prompt, else the
468
- # first message it was started with (a session command like `/model x`,
469
- # or a first turn not saved yet).
471
+ # A session as one line of text for the lists: its title (/title), else
472
+ # its last prompt, else the first message it was started with (a session
473
+ # command like `/model x`, or a first turn not saved yet).
470
474
  def self.summary_text(session)
475
+ return one_line(session.title) unless session.title.to_s.strip.empty?
476
+
471
477
  one_line(session.last_prompt.to_s.strip.empty? ? session.first_preview.to_s : session.last_prompt.to_s)
472
478
  end
473
479
 
@@ -1171,6 +1177,17 @@ module Samagotchi
1171
1177
  def error = ack["error"]
1172
1178
 
1173
1179
  def detail = ack["detail"]
1180
+
1181
+ # What the worker applied (a Bridge ack only): the delivery asked for,
1182
+ # or next_step for a --queue that found no turn running; nil from the
1183
+ # input file or a worker older than delivery.
1184
+ def delivery = ack["delivery"]
1185
+
1186
+ # A --cut's outcome ("now", "waits", "off"), nil when nothing was cut.
1187
+ def cut = ack["cut"]
1188
+
1189
+ # The steer cut-after seconds, with a cut that waits only.
1190
+ def cut_after = ack["cut_after"]
1174
1191
  end
1175
1192
 
1176
1193
  # Hand a user message to the session the way a UI does, for the web
@@ -198,11 +198,12 @@ module Samagotchi
198
198
  # scratch: a `chi scratch` session (deleted when its REPL ends, a
199
199
  # leftover one at the next sweep)
200
200
  # ctx_pct: how full the context was after the last turn, or nil
201
+ # title: the session's own name (/title; desc shows it too), or nil
201
202
  # waiting: the kind of question it waits on (question, approval,
202
203
  # hook: chi answer or the web answers it), or nil; waiting_id: its
203
204
  # id, for chi answer --question; relayed_to: the parent session (short
204
205
  # id) whose card it also waits in (the approval relay), or nil
205
- keys = %i[id short_id desc cwd project updated_at live busy owner recap parent_id continues delegate archived scratch ctx_pct
206
+ keys = %i[id short_id desc title cwd project updated_at live busy owner recap parent_id continues delegate archived scratch ctx_pct
206
207
  waiting waiting_id relayed_to stopped_by]
207
208
  @stdout.puts JSON.generate(summaries.map { |summary| summary.slice(*keys) })
208
209
  when "tsv"
@@ -215,9 +216,10 @@ module Samagotchi
215
216
  else summary[:live] ? "live" : summary[:status].to_s
216
217
  end
217
218
  # The saved recap's first sentence says more than the last prompt
218
- # (text only: tsv and json keep desc for pickers).
219
+ # (text only: tsv and json keep desc for pickers); a title (in
220
+ # desc) says what the user named it.
219
221
  desc = summary[:desc]
220
- if summary[:recap]
222
+ if summary[:recap] && !summary[:title]
221
223
  desc = [File.basename(summary[:cwd].to_s), summary[:recap]].reject(&:empty?).join(" · ")
222
224
  desc = "#{desc[0, 59]}…" if desc.length > 60
223
225
  end
@@ -245,11 +247,11 @@ module Samagotchi
245
247
  order ||= "desc"
246
248
  sessions = Samagotchi::SessionManager.list_sessions(sort: sort, order: order, limit: limit, project_root: project,
247
249
  include_archived: include_archived)
248
- # The saved recap's first sentence, else the last prompt (or the first
249
- # message, before any turn), cut as before.
250
+ # The session's title, else the saved recap's first sentence, else the
251
+ # last prompt (or the first message, before any turn), cut as before.
250
252
  state_dir = Samagotchi::Session.default_state_dir
251
253
  list_text = lambda do |s|
252
- recap = Samagotchi::RecapStore.preview(Samagotchi::Session.session_dir(s.id, state_dir: state_dir))
254
+ recap = s.title ? nil : Samagotchi::RecapStore.preview(Samagotchi::Session.session_dir(s.id, state_dir: state_dir))
253
255
  (recap || Samagotchi::SessionManager.summary_text(s))[0, 60]
254
256
  end
255
257
  # How full the context was after the last turn: "ctx 12%", counted
@@ -727,6 +727,8 @@ module Samagotchi
727
727
  @screen.commit("#{paint("model>", 36)} #{output}")
728
728
  end
729
729
  prefill_confirm(event)
730
+ # /title from any client: the row's title follows.
731
+ @status.update(title: event[:title]) if Array(event[:changed]).include?("title")
730
732
  return unless event[:model_name]
731
733
 
732
734
  # After the output, so the status row changes with the line saying why.
@@ -5,7 +5,7 @@ require_relative "formatting"
5
5
  module Samagotchi
6
6
  class TerminalUI
7
7
  # The status row under the prompt, the same for both TUIs:
8
- # `status> model=… | ↳ parent | ⑂ 2 running · 1 waiting | ctx=12.3% (under20) | mem: … | muted: …`.
8
+ # `status> Title | model=… | ↳ parent | ⑂ 2 running · 1 waiting | ctx=12.3% (under20) | mem: … | muted: …`.
9
9
  # A UI feeds it what it learns (attached mode from the Bridge's events,
10
10
  # the REPL from its Engine's) through #update, and the row is redrawn in
11
11
  # the surface's status slot only when its text changes.
@@ -15,6 +15,8 @@ module Samagotchi
15
15
  # Memory names shown before ", +N".
16
16
  MEMORY_LIMIT = 8
17
17
  # What the row shows:
18
+ # title the session's own title (Session#title; not
19
+ # the first message's preview), or nil
18
20
  # model, default_model the model in use, and the config's default
19
21
  # (named beside another model)
20
22
  # served [served, asked, expected]: what the server said it
@@ -29,12 +31,17 @@ module Samagotchi
29
31
  # records them as used)
30
32
  # muted its --mute list
31
33
  # running a turn runs: the row trails STEER_HINT
32
- FIELDS = %i[model default_model served parent_id children context used_memories preloaded muted running].freeze
34
+ FIELDS = %i[title model default_model served parent_id children context used_memories preloaded muted running].freeze
33
35
 
34
36
  # The tail while a turn runs: where a typed line goes (the next step)
35
37
  # and the two other choices. Dropped whole first when the row is cut.
36
38
  STEER_HINT = " · typing goes in at the next step (/cut, /queue)"
37
39
 
40
+ # The longest title shown, and the share of the row it may take on a
41
+ # narrow terminal: the rest of the row still fits.
42
+ TITLE_MAX = 32
43
+ TITLE_SHARE = 3
44
+
38
45
  # The turn events that end a turn (the hint goes).
39
46
  TURN_END_EVENTS = %i[turn_completed turn_canceled turn_failed].freeze
40
47
 
@@ -74,6 +81,7 @@ module Samagotchi
74
81
  fields.merge!(model: state[:model_name], default_model: default_model) if state[:model_name]
75
82
  STATE_LISTS.each { |field, key| fields[field] = Array(state[key]) if state.key?(key) }
76
83
  fields[:parent_id] = state[:parent_id] if state.key?(:parent_id)
84
+ fields[:title] = state[:title] if state.key?(:title)
77
85
  # The last turn's ctx, so it shows before the next turn's.
78
86
  fields[:context] = state[:context_status] if state[:context_status].is_a?(Hash)
79
87
  update(**fields)
@@ -126,7 +134,8 @@ module Samagotchi
126
134
  model_text = status_model_text(model, @values[:default_model], served: served, served_for: served_for,
127
135
  expected: expected.is_a?(String))
128
136
  end
129
- segments = [model_text,
137
+ segments = [title_text(@values[:title], width),
138
+ model_text,
130
139
  parent ? "↳ #{parent.to_s[0, 8]}" : "",
131
140
  children_text(@values[:children]),
132
141
  status_context_text(estimate: @values[:context]),
@@ -147,6 +156,18 @@ module Samagotchi
147
156
  segments[0..-2] + ["#{segments.last}#{STEER_HINT}"]
148
157
  end
149
158
 
159
+ # The title cut to TITLE_MAX, and to a TITLE_SHARE-th of +width+
160
+ # (the row's other segments come after it); "" without one.
161
+ def title_text(title, width)
162
+ title = title.to_s.strip
163
+ return "" if title.empty?
164
+
165
+ max = [TITLE_MAX, width / TITLE_SHARE].min
166
+ return title if title.length <= max
167
+
168
+ max > 1 ? "#{title[0, max - 1]}…" : ""
169
+ end
170
+
150
171
  # `⑂ 2 running · 1 waiting`, the counts there are; "" with neither (no
151
172
  # children, or all ended). Not "not reported": a REPL parent is never
152
173
  # given its children's replies (no wakes there), and a worker moves
@@ -889,6 +889,7 @@ module Samagotchi
889
889
  if command
890
890
  show_command_result(command)
891
891
  refresh_status_row(clear_unknown_context: true) if command.changed.include?(:model)
892
+ refresh_status_row if command.changed.include?(:title)
892
893
  persist_recent_history(input) if command.shell
893
894
  return
894
895
  end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Samagotchi
4
+ # /title, the session's own name (Session#title): with no argument, the
5
+ # title and what shows without one; `/title TEXT` names the session
6
+ # (whitespace collapsed, cut at 80 characters as a preview is), saved at
7
+ # once; `/title --clear` drops it, and the lists show the first message
8
+ # again. Anyone who may send the session a command may name it (a parent
9
+ # agent its delegates too). It runs mid-turn as well (anytime): the save
10
+ # takes the session's lock and writes a running turn's checkpoint, as a
11
+ # turn's own saves do.
12
+ class TitleCommand
13
+ NAME = "/title"
14
+ CLEAR = "--clear"
15
+ USAGE = "usage: #{NAME} [TEXT|#{CLEAR}]".freeze
16
+ # As long as a preview (Session.preview_of) may be.
17
+ LIMIT = 80
18
+
19
+ # @param engine [Engine] #session
20
+ # @param save [#call] saves the session after a change
21
+ def initialize(engine:, save:)
22
+ @engine = engine
23
+ @save = save
24
+ end
25
+
26
+ # @param args [String] what follows /title
27
+ # @return [Array(String, Boolean, Symbol)] the reply, whether the
28
+ # title changed, and :ok or :error
29
+ def run(args)
30
+ session = @engine.session or return ["no session yet", false, :error]
31
+ text = args.to_s.gsub(/\s+/, " ").strip
32
+ return [listing(session), false, :ok] if text.empty?
33
+ # "--clear and more" is a slip, not a title.
34
+ return [USAGE, false, :error] if text.start_with?("#{CLEAR} ")
35
+
36
+ title = if text == CLEAR then nil
37
+ elsif text.length > LIMIT then "#{text[0, LIMIT]}…"
38
+ else text
39
+ end
40
+ return ["#{listing(session)}\n(no change)", false, :ok] if title == session.title
41
+
42
+ session.title = title
43
+ # The command itself as the session's first line (chi send --new
44
+ # "/title X", a web first message) became its preview: it goes, and
45
+ # the save derives the preview from the first user message again.
46
+ session.first_preview = "" if session.first_preview.to_s.start_with?(NAME)
47
+ @save.call(session)
48
+ [listing(session), true, :ok]
49
+ end
50
+
51
+ private
52
+
53
+ # "title: Coordinator", or "title: none (shows the first message: hey chi …)"
54
+ def listing(session)
55
+ return "title: #{session.title}" if session.title
56
+
57
+ preview = session.first_preview.to_s
58
+ "title: none (shows #{preview.empty? ? "the first message" : "the first message: #{preview}"})"
59
+ end
60
+ end
61
+ end
@@ -356,7 +356,7 @@ module Samagotchi
356
356
  ([file] + overlay_files(dir, entry_name, index_text)).each { |path| trash.move(path) }
357
357
  Samagotchi::MemoryBundle::IndexUpdater.remove_index(resolved_scope, entry_name)
358
358
  "Memory '#{entry_name}' removed from #{resolved_scope} scope: moved to #{trash.dir} " \
359
- "(`chi bundle trash` lists and empties it); index line dropped."
359
+ "(`chi bundle trash` lists and empties it)#{"; index line dropped" if line}."
360
360
  end
361
361
 
362
362
  # The entry's model overlays: <name>.<key>.md with a key ModelOverlay
@@ -86,6 +86,12 @@ module Samagotchi
86
86
  settled_record(id)
87
87
  end
88
88
 
89
+ # The settled outcomes past +max_age+ (SessionInbox.prune_old).
90
+ # @return [Integer] how many went
91
+ def self.prune_settled(session_dir, max_age: SessionInbox::TOMBSTONE_MAX_AGE)
92
+ SessionInbox.prune_old(session_dir, SETTLED_DIR, max_age: max_age)
93
+ end
94
+
89
95
  def self.settled_record(id, ended_at: nil, seconds: nil)
90
96
  LastTurn.new(outcome: "canceled", cancel_reason: WORKER_STOPPED, ended_at: ended_at, seconds: seconds, enqueued_id: id)
91
97
  end
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.95.0"
4
+ VERSION = "0.97.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -681,7 +681,7 @@ module Samagotchi
681
681
  # next; the list and the notifications name the session by it
682
682
  # until that turn is saved.
683
683
  preview = idle ? body["preview"].to_s.strip : ""
684
- folder[:title] = preview unless preview.empty?
684
+ folder[:preview] = preview unless preview.empty?
685
685
  setup = SessionSetup.new(llm_context: llm_context, thinking: thinking, bundle_settings: bundle_settings)
686
686
  folder[:setup] = setup unless setup.empty?
687
687
  begin
@@ -725,7 +725,7 @@ module Samagotchi
725
725
 
726
726
  preview = idle ? body["preview"].to_s.strip : ""
727
727
  model = (body["model"] || body["model_name"]).to_s.strip
728
- session, error = continue_from(given, prompt: idle ? nil : prompt.to_s, title: preview.empty? ? nil : preview,
728
+ session, error = continue_from(given, prompt: idle ? nil : prompt.to_s, preview: preview.empty? ? nil : preview,
729
729
  model: model.empty? ? nil : model)
730
730
  return error if error
731
731
 
@@ -742,8 +742,8 @@ module Samagotchi
742
742
  # SessionManager.continue_session, its refusals as responses: [session,
743
743
  # nil] or [nil, the response]. Only its own errors: what fails after
744
744
  # the new link started is not a refusal of it.
745
- def continue_from(given, prompt:, title:, model:)
746
- [@manager.continue_session(given, prompt: prompt, title: title, model: model, state_dir: @state_dir), nil]
745
+ def continue_from(given, prompt:, preview:, model:)
746
+ [@manager.continue_session(given, prompt: prompt, preview: preview, model: model, state_dir: @state_dir), nil]
747
747
  rescue SessionContinue::Refused => e
748
748
  extra = e.reason == :continued ? { next_id: e.ids.first } : { ids: e.ids }
749
749
  [nil, json_response(409, { error: e.reason.to_s, detail: e.message, **extra })]
@@ -85,6 +85,7 @@ import { createToasts } from "./toasts.js";
85
85
  import { createUnqueue } from "./unqueue.js";
86
86
  import { createStartPage } from "./start_page.js";
87
87
  import { createSessionActions } from "./session_actions.js";
88
+ import { createRename } from "./session_rename.js";
88
89
  import { createSendTurn } from "./send_turn.js";
89
90
 
90
91
  const $ = (s) => document.querySelector(s);
@@ -495,6 +496,14 @@ const sessionActions = createSessionActions({
495
496
  closeLiveStream: () => streamControl?.close(),
496
497
  workerGone,
497
498
  });
499
+ // ✎: /title through the chips' path (session_rename.js).
500
+ const rename = createRename({
501
+ button: $("#infoRenameBtn"),
502
+ session: () => selected,
503
+ titleOf: (id) => lists.sessionsById().get(id)?.title || null,
504
+ run: (line) => runSessionCommand(line),
505
+ });
506
+
498
507
  const { confirmDelete, leaveGoneSession, continueSelected, archiveOne, setArchived } = sessionActions;
499
508
 
500
509
  // All sessions: its own view at #/sessions, so the browser's back button
@@ -1046,6 +1055,9 @@ function updateInfoBar() {
1046
1055
  const deleteBtn = document.getElementById("infoDeleteBtn");
1047
1056
  const archiveBtn = document.getElementById("infoArchiveBtn");
1048
1057
  const continueBtn = document.getElementById("infoContinueBtn");
1058
+ const renameBtn = document.getElementById("infoRenameBtn");
1059
+ if (renameBtn) renameBtn.style.display = buttons.rename.shown ? "" : "none";
1060
+ rename.follow(buttons.rename.shown ? selected : null);
1049
1061
  if (continueBtn) {
1050
1062
  continueBtn.style.display = buttons.continue.shown ? "" : "none";
1051
1063
  continueBtn.disabled = buttons.continue.disabled;
@@ -36,9 +36,11 @@ export function isOpener(text) {
36
36
  // reads its chain's first link's title instead, so the links of a chain
37
37
  // keep its name. Its own title when the first link isn't in +byId+ (id →
38
38
  // session; deleted, or a walk a missing link cut short) or is the opener too.
39
+ // A link with a title of its own (/title; a new link inherits it) reads it,
40
+ // and a titled first link names its chain.
39
41
  export function chainTitle(s, byId) {
40
42
  const own = previewForCard(s);
41
- if (!s?.continues || !isOpener(s.first_preview || s.last_prompt)) return own;
43
+ if (s?.title || !s?.continues || !isOpener(s.first_preview || s.last_prompt)) return own;
42
44
  const seen = new Set([s.id]);
43
45
  let at = s;
44
46
  while (at.continues) {
@@ -47,7 +49,7 @@ export function chainTitle(s, byId) {
47
49
  seen.add(prev.id);
48
50
  at = prev;
49
51
  }
50
- return isOpener(at.first_preview || at.last_prompt) ? own : previewForCard(at);
52
+ return !at.title && isOpener(at.first_preview || at.last_prompt) ? own : previewForCard(at);
51
53
  }
52
54
 
53
55
  // The open session's title (app.js updateSessionTitle: the top bar and the
@@ -55,9 +57,10 @@ export function chainTitle(s, byId) {
55
57
  // (+shown+, its summary, has continues) reads +cardTitle+(shown) whatever
56
58
  // its first message: a web link inherits its chain's title, and its first
57
59
  // message is an opener (the constant or the user's own). Else +first+,
58
- // unless it is the opener. +shown+ null: not listed yet, +first+.
60
+ // unless it is the opener. A titled session (/title) reads its card's too.
61
+ // +shown+ null: not listed yet, +first+.
59
62
  export function openTitle({ shown, first, cardTitle }) {
60
- if (shown && (shown.continues || isOpener(first))) return cardTitle(shown);
63
+ if (shown && (shown.title || shown.continues || isOpener(first))) return cardTitle(shown);
61
64
  return first;
62
65
  }
63
66
 
@@ -213,13 +216,23 @@ export function chainChipTemplate(f, { open = false } = {}) {
213
216
 
214
217
  // The chain's list (the chip's popover): one row per other link, newest
215
218
  // first: status dot, "#N", its date (with its HH:MM when another link of
216
- // the chain, the head too, started the same day: chainStamp), its recap's first sentence (else
217
- // its preview), the waiting / stopped badge, archived. A row's click opens
219
+ // the chain, the head too, started the same day: chainStamp), its own title (/title) when it
220
+ // differs from the head's (a link inherits its chain's: the card says it), else its recap's
221
+ // first sentence, else its preview, the waiting / stopped badge, archived. A row's click opens
218
222
  // that link (families_view.js's popover binds .family-row[data-id]).
219
223
  // @param activeId the open session's id (its row is .active)
224
+ // A chain row's words: a name of its own (not the one it shares with the
225
+ // head), else what tells the link apart: its recap, else its preview (an
226
+ // opener's read as the chain's, chainTitle, with its own title left out).
227
+ function rowTitle(s, headTitle, byId) {
228
+ if (s.title && s.title !== headTitle) return s.title;
229
+ return s.recap || chainTitle({ ...s, title: null }, byId);
230
+ }
231
+
220
232
  export function chainRowsTemplate(f, { activeId = null, now = Date.now() } = {}) {
221
- const byId = new Map((f?.chain?.links || []).map((s) => [s.id, s]));
222
233
  const links = f?.chain?.links || [];
234
+ const byId = new Map(links.map((s) => [s.id, s]));
235
+ const headTitle = (byId.get(f?.head?.id) || f?.head)?.title || null;
223
236
  const rows = chainOthers(f).map(({ session: s, n }) => {
224
237
  const cls = ["family-row", "chain-row"];
225
238
  if (activeId && s.id === activeId) cls.push("active");
@@ -231,7 +244,7 @@ export function chainRowsTemplate(f, { activeId = null, now = Date.now() } = {})
231
244
  const tip = `${s.id} · ${s.status || ""}${ago ? ` · updated ${ago}` : ""}`;
232
245
  return html`<div class=${cls.join(" ")} data-id=${s.id} style=${"--depth:1"} role=${"listitem"}><button type="button" class="fr-open"
233
246
  title=${tip}>${rowDotTemplate(s, waiting)}<span class="cr-n">#${n}</span>${
234
- date ? html`<span class=${date.length > 10 ? "cr-date timed" : "cr-date"}>${date}</span>` : nothing}<span class="fr-preview">${s.recap || chainTitle(s, byId)}</span>${
247
+ date ? html`<span class=${date.length > 10 ? "cr-date timed" : "cr-date"}>${date}</span>` : nothing}<span class="fr-preview">${rowTitle(s, headTitle, byId)}</span>${
235
248
  rowBadgesTemplate(waiting, stopped)}${s.archived ? archivedBadge : nothing}</button></div>`;
236
249
  });
237
250
  return html`<div class="family-rows chain-rows" role="list">${rows}</div>`;
@@ -58,8 +58,9 @@ export function firstPreview(text) {
58
58
  }
59
59
 
60
60
  export function previewForCard(session) {
61
- // Unified card preview: first message (80) else previewOf(last_prompt)
62
- const raw = session.first_preview || session.last_prompt || "";
61
+ // Unified card preview: its title (/title), else its first message (80),
62
+ // else its last prompt.
63
+ const raw = session.title || session.first_preview || session.last_prompt || "";
63
64
  return firstPreview(raw) || "\u2014";
64
65
  }
65
66
 
@@ -69,7 +70,7 @@ const DELETE_PREVIEW_CHARS = 40;
69
70
  // list's owner can be stale (a worker idle-exits), so a worker is only
70
71
  // "stopped if it's still running", never promised.
71
72
  export function deleteConfirmText(session) {
72
- const n = normalize(session.first_preview || session.last_prompt || "");
73
+ const n = normalize(session.title || session.first_preview || session.last_prompt || "");
73
74
  const preview = clip(n, DELETE_PREVIEW_CHARS + 1);
74
75
  const shortId = session.short_id || String(session.id).slice(0, 8);
75
76
  const lines = [
@@ -887,6 +887,10 @@ body.stage-view .turn-stage{position:absolute;left:0;right:0;bottom:100%;margin-
887
887
  #infoBar #infoStopBtn{background:var(--bg-raised);color:var(--warn-text);border:1px solid var(--border-strong)}
888
888
  #infoBar #infoStopBtn:hover{background:var(--warn-bg);border-color:var(--warn-border)}
889
889
  #infoBar #infoArchiveBtn{background:transparent;color:var(--text-muted);border:1px solid var(--border-strong)}
890
+ #infoBar #infoRenameBtn{background:transparent;color:var(--text-muted);border:1px solid transparent}
891
+ #infoBar #infoRenameBtn:hover{color:var(--text);background:var(--bg-hover)}
892
+ /* ✎'s input (session_rename.js), in the button's place. */
893
+ #infoBar .rename-input{flex:0 1 18em;min-width:6em;font:inherit;font-size:12px;padding:3px 8px;border-radius:8px;border:1px solid var(--accent-border);background:var(--bg-raised);color:var(--text);outline:none}
890
894
  #infoBar #infoArchiveBtn:hover{color:var(--text);background:var(--bg-hover)}
891
895
  #infoBar #infoDeleteBtn{background:transparent;color:var(--text-muted);border:1px solid transparent}
892
896
  #infoBar #infoDeleteBtn:hover{color:var(--on-solid);background:var(--danger-bg);border-color:var(--danger-bg)}
@@ -976,6 +980,8 @@ body.has-session.composer-folded #infoBar{border-top-color:transparent}
976
980
  #infoBar>button{font-size:0;line-height:0;padding:5px 7px}
977
981
  #infoBar>button::before{content:"";display:block;width:14px;height:14px;background:currentColor;-webkit-mask:var(--icon) center/contain no-repeat;mask:var(--icon) center/contain no-repeat}
978
982
  #infoBar #infoArchiveBtn{--icon:var(--icon-archive)}
983
+ #infoBar #infoRenameBtn{--icon:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='black' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M10.5 2.5l3 3L5.5 13.5H2.5v-3z'/%3E%3C/svg%3E")}
984
+ #infoBar .rename-input{flex:1 1 8em;font-size:16px}
979
985
  #infoBar #infoArchiveBtn.archived{--icon:var(--icon-unarchive)}
980
986
  #infoBar #infoContinueBtn{--icon:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='black' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M3 8h9M8.5 4.5 12 8l-3.5 3.5'/%3E%3C/svg%3E")}
981
987
  #infoBar #infoCancelBtn{--icon:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='black' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='4' y='4' width='8' height='8' rx='1.5'/%3E%3C/svg%3E")}
@@ -1300,6 +1306,7 @@ a{color:var(--accent)}
1300
1306
  <div class="info" id="infoText"></div>
1301
1307
  <div id="contextChips" aria-label="Attached context" hidden></div>
1302
1308
  <button class="ghost" id="infoCancelBtn" title="Cancel the running turn, whoever sent it" style="display:none">Stop turn</button>
1309
+ <button class="ghost" id="infoRenameBtn" title="Rename this session" aria-label="Rename this session" style="display:none">✎</button>
1303
1310
  <button class="ghost" id="infoContinueBtn" title="Continue: start the next link of this session's chain from its recap (this one is archived)" style="display:none">continue →</button>
1304
1311
  <button class="ghost" id="infoArchiveBtn" title="Archive: hide from the lists, keep for good" style="display:none">archive</button>
1305
1312
  <button class="ghost" id="infoStopBtn" title="Stop session (terminate worker)" style="display:none">stop session</button>
@@ -42,6 +42,8 @@ export function infoButtons({ id, state, chain, archived, continuing, streaming
42
42
  const busy = !!id && continuing;
43
43
  return {
44
44
  continue: { shown: !!id && !chain.next && state.owner !== "tui", disabled: busy, text: busy ? "continuing…" : "continue →" },
45
+ // ✎: /title from the web (a plain terminal's session takes no commands).
46
+ rename: { shown: !!id && state.owner !== "tui" },
45
47
  delete: { shown: !!id },
46
48
  archive: {
47
49
  shown: !!id,