samagotchi 0.191.0 → 0.192.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 (74) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +40 -1
  3. data/docs/architecture.md +5 -4
  4. data/docs/bundles.md +1 -1
  5. data/docs/cli.md +15 -7
  6. data/docs/configuration.md +6 -1
  7. data/docs/internals/inline-widgets.md +2 -1
  8. data/docs/internals/participants.md +1 -5
  9. data/docs/internals/remote-sessions.md +3 -0
  10. data/docs/internals/session-lifecycle.md +33 -19
  11. data/docs/internals/web-frontend.md +107 -9
  12. data/docs/scheduling.md +7 -1
  13. data/docs/sessions.md +2 -2
  14. data/docs/testing.md +1 -2
  15. data/docs/thin-clients.md +98 -12
  16. data/lib/samagotchi/bridge.rb +2 -3
  17. data/lib/samagotchi/bundles/mcp/manifest.yml +4 -2
  18. data/lib/samagotchi/bundles/mcp/plugin.rb +7 -398
  19. data/lib/samagotchi/bundles/mcp/server_config.rb +158 -0
  20. data/lib/samagotchi/bundles/mcp/sign_in.rb +261 -0
  21. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  22. data/lib/samagotchi/client_id.rb +2 -19
  23. data/lib/samagotchi/compat.rb +1 -7
  24. data/lib/samagotchi/config.rb +3 -0
  25. data/lib/samagotchi/delivery.rb +1 -5
  26. data/lib/samagotchi/schedule_command.rb +1 -0
  27. data/lib/samagotchi/schedules/prune_part.rb +32 -0
  28. data/lib/samagotchi/schedules.rb +14 -9
  29. data/lib/samagotchi/session.rb +7 -0
  30. data/lib/samagotchi/session_access/remote.rb +1 -1
  31. data/lib/samagotchi/session_continue.rb +8 -1
  32. data/lib/samagotchi/session_lifecycle.rb +4 -0
  33. data/lib/samagotchi/session_manager/delivery.rb +0 -6
  34. data/lib/samagotchi/session_manager/lifecycle.rb +30 -17
  35. data/lib/samagotchi/session_manager/listing.rb +2 -1
  36. data/lib/samagotchi/session_manager/removal.rb +7 -5
  37. data/lib/samagotchi/session_manager/spawn.rb +2 -3
  38. data/lib/samagotchi/session_manager.rb +4 -0
  39. data/lib/samagotchi/session_row.rb +2 -0
  40. data/lib/samagotchi/session_transition.rb +61 -15
  41. data/lib/samagotchi/tools/cancel_schedule.rb +10 -6
  42. data/lib/samagotchi/version.rb +1 -1
  43. data/lib/samagotchi/web/app.rb +3 -1
  44. data/lib/samagotchi/web/ask_create.rb +138 -0
  45. data/lib/samagotchi/web/ask_routes.rb +56 -9
  46. data/lib/samagotchi/web/last_ask.rb +78 -0
  47. data/lib/samagotchi/web/public/answer_refs.js +3 -9
  48. data/lib/samagotchi/web/public/answer_write.js +28 -0
  49. data/lib/samagotchi/web/public/app.js +72 -96
  50. data/lib/samagotchi/web/public/block_fix.js +30 -12
  51. data/lib/samagotchi/web/public/chains.js +3 -1
  52. data/lib/samagotchi/web/public/command_list.js +5 -3
  53. data/lib/samagotchi/web/public/composer.js +9 -6
  54. data/lib/samagotchi/web/public/composer_mount.js +18 -11
  55. data/lib/samagotchi/web/public/draft_keys.js +10 -0
  56. data/lib/samagotchi/web/public/drafts.js +278 -0
  57. data/lib/samagotchi/web/public/owner_claim.js +7 -12
  58. data/lib/samagotchi/web/public/prompt_history.js +6 -0
  59. data/lib/samagotchi/web/public/send_turn.js +51 -20
  60. data/lib/samagotchi/web/public/session_actions.js +80 -16
  61. data/lib/samagotchi/web/public/session_prefs.js +9 -3
  62. data/lib/samagotchi/web/public/session_view.js +7 -2
  63. data/lib/samagotchi/web/public/turn_events.js +0 -2
  64. data/lib/samagotchi/web/public/unqueue.js +22 -9
  65. data/lib/samagotchi/web/public/viewer_self.js +1 -6
  66. data/lib/samagotchi/web/public/views.js +12 -1
  67. data/lib/samagotchi/web/session_access_routes.rb +6 -3
  68. data/lib/samagotchi/web/session_control.rb +4 -2
  69. data/lib/samagotchi/web/session_create.rb +50 -33
  70. data/lib/samagotchi/web/session_hub.rb +52 -36
  71. data/lib/samagotchi/web/session_summary.rb +45 -7
  72. data/lib/samagotchi/web/start_dir.rb +6 -4
  73. data/lib/samagotchi/worker_presence.rb +22 -6
  74. metadata +8 -1
@@ -23,14 +23,22 @@ import { deleteToast } from "./removal_sheet_model.js";
23
23
  // +refresh()+ fetches the list);
24
24
  // +select(id)+, +clearSelection()+, +showNotice(text)+,
25
25
  // +toast(text, action, options)+, +addCreatedSession(created)+,
26
- // +fillOpener(created, continuedId)+ (the new link's composer; returns a draft
27
- // from another session it displaced, or null), +restoreDraft(draft, opener)+
28
- // (that draft back, never over newer text), +closeLiveStream()+ (the live
29
- // stream's close, the stream left as it is) and +workerGone(id)+ the page's.
26
+ // +handOverDraft(from, to, created)+ (continue →: the session's draft to the
27
+ // new link, else the link's opener: drafts.js handOver), +revealDraft()+ (the
28
+ // open session's draft seen: the composer opens, the box takes the focus,
29
+ // the caret at the end); an older cached app.js passes +fillOpener(created,
30
+ // continuedId)+ instead (the new link's composer, after its select; returns
31
+ // a displaced draft, or null) and +restoreDraft(draft, opener)+ (that draft
32
+ // back), kept for it; +closeLiveStream()+ (the live
33
+ // stream's close, the stream left as it is) and +workerGone(id)+ the page's;
34
+ // +moveDraft(from, to)+ / +dropDraft(id)+ the composer's drafts (drafts.js:
35
+ // a gone session's goes to the start page's, a deleted one's is forgotten;
36
+ // none passed, an older cached app.js: left as they are).
30
37
  // +confirm+: the browser's (Stop's, when nothing else runs).
31
38
  export function createSessionActions({
32
39
  selected, store, sessions, setSessions, api, eventsLive, refresh,
33
40
  select, clearSelection, showNotice, toast, addCreatedSession, fillOpener, restoreDraft, closeLiveStream, workerGone,
41
+ moveDraft = null, dropDraft = null, handOverDraft = null, revealDraft = () => {},
34
42
  confirm = (text) => globalThis.confirm(text),
35
43
  // The Stop sheet (stop_sheet.js): +open(id, holds)+ shows it and answers
36
44
  // true; nothing to stop (or no sheet wired) is false, and Stop is the
@@ -42,9 +50,27 @@ export function createSessionActions({
42
50
  // The page's document: where a card's control and ⋯ are found.
43
51
  doc = globalThis.document,
44
52
  }) {
53
+ // The ids of +id+'s chain in the page's list (its links, by continues).
54
+ function chainOf(id) {
55
+ const list = sessions();
56
+ const ids = new Set([id]);
57
+ for (let grew = true; grew;) {
58
+ grew = false;
59
+ for (const s of list) {
60
+ if (ids.has(s.id) && s.continues && !ids.has(s.continues)) { ids.add(s.continues); grew = true; }
61
+ if (s.continues && ids.has(s.continues) && !ids.has(s.id)) { ids.add(s.id); grew = true; }
62
+ }
63
+ }
64
+ return ids;
65
+ }
66
+
45
67
  // The session this tab is stopping: its stream may close before the stop
46
68
  // request returns (workerGone reads it).
47
69
  let stoppingId = null;
70
+ // The sessions a delete from this tab is taking (filled when its request
71
+ // starts): the hub's session_gone may come before its answer, and their
72
+ // drafts are dropped, not moved to the start page's.
73
+ const deleting = new Set();
48
74
 
49
75
  // Delete a session (the ⋯ More panel's Delete, an all-sessions card's ✕):
50
76
  // the delete sheet (delete_sheet.js) says what goes, what is stopped first
@@ -68,10 +94,24 @@ export function createSessionActions({
68
94
  }
69
95
 
70
96
  function startDeleteFlow(id, sess, host) {
97
+ // What this delete takes: the session, and for a chain the open link
98
+ // too when it is one of it (the plan names no ids).
99
+ const taking = new Set();
100
+ const take = (ids) => ids.forEach((x) => { if (x) { taking.add(x); deleting.add(x); } });
101
+ const over = () => taking.forEach((x) => deleting.delete(x));
102
+ const flowApi = {
103
+ ...api,
104
+ deleteSession: (sid, opts) => { take([sid]); return api.deleteSession(sid, opts); },
105
+ deleteChain: (sid, opts) => { take([sid, chainOf(sid).has(selected()) ? selected() : null]); return api.deleteChain(sid, opts); },
106
+ };
71
107
  const flow = runDeleteFlow({
72
- id, session: sess, host, api, sessions,
73
- done: (which, result, plan) => afterDelete(id, which, result, plan),
108
+ id, session: sess, host, api: flowApi, sessions,
109
+ done: (which, result, plan) => {
110
+ afterDelete(id, which, result, plan);
111
+ over();
112
+ },
74
113
  failed: (error) => {
114
+ over();
75
115
  notShown(host, `delete ${id.slice(0, 8)}`, error);
76
116
  if (!eventsLive()) refresh();
77
117
  },
@@ -90,6 +130,8 @@ export function createSessionActions({
90
130
  setSessions(listAfterDelete(sessions(), result));
91
131
  const gone = new Set(result.deleted || [id]);
92
132
  if (gone.has(selected())) clearSelection();
133
+ // After the start page opened: the swap saved the deleted one's draft last.
134
+ gone.forEach((x) => dropDraft?.(x));
93
135
  if (!eventsLive()) refresh();
94
136
  const { text, back, sticky = false } = deleteToast(which, result, plan, id);
95
137
  toast(text, back ? { label: `Open ${back.slice(0, 8)}`, run: () => select(back) } : null, { sticky });
@@ -98,6 +140,9 @@ export function createSessionActions({
98
140
  // The open session no longer exists: back to the start page, saying why.
99
141
  function leaveGoneSession(id, why) {
100
142
  if (selected() !== id) return;
143
+ // Its draft isn't lost with it: it goes to the start page's (under what
144
+ // is there). A delete from this tab drops it instead (afterDelete).
145
+ if (!deleting.has(id)) moveDraft?.(id, "");
101
146
  clearSelection();
102
147
  showNotice(goneSessionNotice(id, why));
103
148
  }
@@ -152,9 +197,18 @@ export function createSessionActions({
152
197
  await api.stopSession(id);
153
198
  if (id === selected()) stoppedWorker(id);
154
199
  } catch (e) {
155
- // A refusal (a terminal holds it) or a worker that won't stop: said, as
156
- // a failed restart is.
157
- toast(cantText(`stop ${id.slice(0, 8)}`, e), null, { sticky: true });
200
+ if (e?.code === "stop_held") {
201
+ // A continue, a delete or an archive holds it: the server's words say
202
+ // what to do; a continue's new link is the one to open (and stop).
203
+ const next = e.body?.successor_id;
204
+ const words = String(e.message);
205
+ toast(words.charAt(0).toUpperCase() + words.slice(1),
206
+ next ? { label: `Open ${next.slice(0, 8)}`, run: () => select(next) } : null, { sticky: true });
207
+ } else {
208
+ // A refusal (a terminal holds it) or a worker that won't stop: said, as
209
+ // a failed restart is.
210
+ toast(cantText(`stop ${id.slice(0, 8)}`, e), null, { sticky: true });
211
+ }
158
212
  } finally {
159
213
  stoppingId = null;
160
214
  }
@@ -165,8 +219,10 @@ export function createSessionActions({
165
219
  // ── Continue (session chains) ─────────────────────────────────────────────
166
220
  // Continue → starts the next link of the open session's chain (the server
167
221
  // waits up to 30 s for its recap, archives it, starts the new one with the
168
- // recap as a note) and opens it with the opener in the composer, not sent
169
- // (fillOpener: the previous link's own first message when it continues one).
222
+ // recap as a note) and hands it the session's draft (text typed while it
223
+ // waited too), or with none the opener, not sent (the previous link's own
224
+ // first message when it continues one): wherever the page is when it
225
+ // lands, before it opens the link.
170
226
  // A link continued already opens that next link; its open delegates move
171
227
  // to the new link (the toast counts them); a refusal for open delegates
172
228
  // that can't move names them, each a link.
@@ -185,6 +241,7 @@ export function createSessionActions({
185
241
  markArchived([id], true);
186
242
  addCreatedSession(created);
187
243
  const next = created.id;
244
+ handOverDraft?.(id, next, created);
188
245
  // A model fallback's warning stays until closed.
189
246
  const sticky = !!created.model_warning;
190
247
  if (selected() !== id) {
@@ -192,14 +249,14 @@ export function createSessionActions({
192
249
  return;
193
250
  }
194
251
  await select(next);
195
- // A draft carried over from elsewhere gave way to the opener: the
196
- // toast brings it back, and stays until closed so it can't be lost.
197
- const displaced = selected() === next ? fillOpener(created, id) : null;
198
- const restore = displaced ? { label: "Restore draft", run: () => restoreDraft(displaced, openerText(created)) } : null;
199
- toast(continuedText(id, created), restore, { sticky: sticky || !!displaced });
252
+ if (!handOverDraft) return oldOpener(created, id, sticky, selected() === next);
253
+ if (selected() === next) revealDraft();
254
+ toast(continuedText(id, created), null, { sticky });
200
255
  } catch (e) {
201
256
  const refusal = continueRefusal(e, sessions());
202
257
  if (refusal.kind === "open") {
258
+ // The link that continues it takes the draft only into an empty draft of its own.
259
+ handOverDraft?.(id, refusal.id, null);
203
260
  if (selected() === id) await select(refusal.id);
204
261
  toast(`${short} is continued already: ${selected() === refusal.id ? "opened" : "see"} ${refusal.id.slice(0, 8)}`);
205
262
  } else if (refusal.kind === "children") {
@@ -213,6 +270,13 @@ export function createSessionActions({
213
270
  }
214
271
  }
215
272
 
273
+ // An older cached app.js's continue: its fillOpener's guess and Restore draft.
274
+ function oldOpener(created, id, sticky, opened) {
275
+ const displaced = opened ? fillOpener(created, id) : null;
276
+ const restore = displaced ? { label: "Restore draft", run: () => restoreDraft(displaced, openerText(created)) } : null;
277
+ toast(continuedText(id, created), restore, { sticky: sticky || !!displaced });
278
+ }
279
+
216
280
  // ── Archive ───────────────────────────────────────────────────────────────
217
281
  // Archive hides a session (and its delegates) from the strip and the list,
218
282
  // kept for good; "include archived" in all sessions finds it. No confirm:
@@ -2,7 +2,8 @@
2
2
  // storage.js): the stage's fold, the composer's dragged height and its fold,
3
3
  // the working-set rail's fold, the working-set list's folded sections
4
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
5
+ // blank a page holding this module cached), and the composer's draft text
6
+ // (drafts.js, draft_keys.js COMPOSER_DRAFT, the same way). Each is kept under `<key>:<session>`, so what
6
7
  // you do to one session's window never shows in another, and a session never
7
8
  // set by hand follows the default: the page's own (the stage fold's comes
8
9
  // from config, web.stage_collapsed, as <body data-stage-collapsed="1">), else
@@ -23,12 +24,14 @@
23
24
  // export on an old module would blank the page.
24
25
  import { readStored, removeStored, storedKeys, writeStored } from "./storage.js";
25
26
  import { WS_SECTION_FOLD } from "./ws_sections.js";
27
+ import { COMPOSER_DRAFT } from "./draft_keys.js";
26
28
 
27
29
  export const STAGE_FOLD = "chi_stage_collapsed";
28
30
  export const COMPOSER_FLOOR = "chi_composer_floor";
29
31
  export const COMPOSER_FOLD = "chi_composer_collapsed";
30
32
  export const WS_RAIL_FOLD = "chi_working_set_collapsed";
31
- export const PREF_KEYS = [STAGE_FOLD, COMPOSER_FLOOR, COMPOSER_FOLD, WS_RAIL_FOLD, WS_SECTION_FOLD];
33
+ // And the composer's draft text (drafts.js; its key is draft_keys.js'): swept with them.
34
+ export const PREF_KEYS = [STAGE_FOLD, COMPOSER_FLOOR, COMPOSER_FOLD, WS_RAIL_FOLD, WS_SECTION_FOLD, COMPOSER_DRAFT];
32
35
 
33
36
  // The page's defaults: <body>'s data attribute that turns a key on ("1").
34
37
  const PAGE_DEFAULTS = { [STAGE_FOLD]: "stageCollapsed" };
@@ -79,10 +82,13 @@ export function forget(key, session) {
79
82
  }
80
83
 
81
84
  // The session list loaded (+sessions+, each {id}): the keys of sessions not
82
- // in it go. +scoped+ (a project's list): nothing goes.
85
+ // in it go. +scoped+ (a project's list): nothing goes. An empty list sweeps
86
+ // nothing either: chi web's hub answers one before its first scan (a page
87
+ // reloaded as chi web restarts), and the drafts' text would go with it.
83
88
  export function sweepSessionPrefs(sessions, { scoped = false } = {}) {
84
89
  if (scoped) return;
85
90
  const ids = new Set((Array.isArray(sessions) ? sessions : []).map((s) => s?.id).filter(Boolean));
91
+ if (!ids.size) return;
86
92
  for (const key of PREF_KEYS) {
87
93
  const prefix = `${key}:`;
88
94
  for (const stored of storedKeys(prefix)) {
@@ -32,8 +32,9 @@
32
32
  // setCapabilities(capabilities, editorUrl, viewer), findInTurnRoots(selector), appendToHistory(el),
33
33
  // setTurnRunning(running), mergeTurnTiming(id, timing), applySessionPayload(data, opts),
34
34
  // turnEndStatus(data), replaceSelectedCard(change)} the page's hooks
35
- // later: {handlers(), composer(), ownerVerify(), commandList(), initTasks(), resetTurnView()}
36
- // the views made after this one, and session_sync.js's resetTurnView
35
+ // later: {handlers(), composer(), ownerVerify(), commandList(), initTasks(), resetTurnView(), drafts()}
36
+ // the views made after this one, and session_sync.js's resetTurnView;
37
+ // drafts(): the composer's drafts (drafts.js), swapped with the session
37
38
  //
38
39
  // @return {forgetSession, renderSessionView, historyOpts, readTurnEnd, endTurnView, leaveSession}
39
40
  // leaveSession(): what the user opened of the open session's running turn,
@@ -109,6 +110,10 @@ export function createSessionView(deps) {
109
110
  setMarkdownWarning(null);
110
111
  markdownTip.show(null);
111
112
  setCapabilities(null, null);
113
+ // The composer's draft: the session now open's ("" the start page), before
114
+ // the visit and the prefs (the grip's draft class and the fit see it).
115
+ // ?.: an older cached app.js passes no drafts.
116
+ later.drafts?.()?.show(store.selected ?? "");
112
117
  later.composer().newVisit();
113
118
  // The reader and the peek are the session's: another one (or none, the
114
119
  // start page) never finds them over #center, the composer inert under it.
@@ -125,8 +125,6 @@ const CLIENT_LABELS = Object.freeze({
125
125
  "tui:": "tui", "web:": "web", "system:": "reminder", "delegate:": "delegate", "child:": "delegate report",
126
126
  "cli:send": "chi send", "cli:answer": "chi answer", plugin: "plugin", "participant:": "invited",
127
127
  "spawn:first": null, "card:answer": null,
128
- // compat shim review_client_id: a participant's id from before participant:.
129
- "review:": "invited",
130
128
  });
131
129
  const labelFor = (key) => (Object.hasOwn(CLIENT_LABELS, key) ? CLIENT_LABELS[key] : undefined);
132
130
  const AUTOMATIC_LABEL = "automatic";
@@ -2,10 +2,12 @@
2
2
  // turn_html.js stateBadgeTemplate): POST …/turn/:enqueued_id/dequeue
3
3
  // (Bridge#handle_dequeue_turn) takes it back before it runs. The bubble
4
4
  // goes with the turn_dequeued every tab gets (bubbles.js op "remove"), and
5
- // here at the 200 already. Its text comes back (edit): into an empty
6
- // composer, to change and send again; over a draft only in a toast (the
7
- // draft stays), and after a switch to another session meanwhile only in a
8
- // sticky toast naming its session, with Copy. Its images don't come back. A refusal keeps it
5
+ // here at the 200 already. Its text comes back (edit) into the draft of the
6
+ // session it was queued in when that draft is empty, to change and send
7
+ // again: the open session's, or after a switch meanwhile the one left (a
8
+ // toast says where); over a draft only in a toast (the draft stays), after a
9
+ // switch a sticky one naming its session, with Copy. Its images don't come
10
+ // back. A refusal keeps it
9
11
  // and says why in a toast. No confirm: nothing is lost. Pure but for the
10
12
  // injected calls, so `node --test` covers it; app.js binds onClick to the
11
13
  // turn roots.
@@ -28,10 +30,13 @@ function clipped(text) {
28
30
  }
29
31
 
30
32
  // +sessionId+ is read at each click (the open session); +clientId+ is this
31
- // tab's (the turn_dequeued names who removed it); +putBack(text)+ fills the
32
- // composer when it is empty and says whether it did; +copy(text)+ says
33
+ // tab's (the turn_dequeued names who removed it); +putBackTo(text, id)+
34
+ // puts it into session id's draft when that is empty: "shown" (the open
35
+ // one's), "stored" (another's), false (a draft was there); an older cached
36
+ // app.js passes only +putBack(text)+, the open composer's (true when it took
37
+ // it), and a switch meanwhile leaves the text to the toast; +copy(text)+ says
33
38
  // whether the clipboard took it; +toast(text, action, options)+ as showToast.
34
- export function createUnqueue({ sessionId, clientId = null, dequeue = postDequeue, toast = () => {}, putBack = () => false, copy = null }) {
39
+ export function createUnqueue({ sessionId, clientId = null, dequeue = postDequeue, toast = () => {}, putBack = () => false, putBackTo = null, copy = null }) {
35
40
  // A click on a queued bubble's ×; any other click is left alone.
36
41
  async function onClick(e) {
37
42
  const button = e.target?.closest?.("button.unqueue");
@@ -46,13 +51,21 @@ export function createUnqueue({ sessionId, clientId = null, dequeue = postDequeu
46
51
  const result = await dequeue(id, enqueuedId, { clientId });
47
52
  removeQueuedBubble(bubble);
48
53
  const text = String(result?.prompt || "");
54
+ if (!text.trim()) return result;
55
+ if (putBackTo) {
56
+ const put = putBackTo(text, id);
57
+ if (put === "stored") toast(`Removed: back in ${id.slice(0, 8)}'s draft`);
58
+ else if (!put && sessionId() !== id) movedOn(id, text);
59
+ else if (!put) toast(`Removed (your draft stays): ${clipped(text)}`);
60
+ return result;
61
+ }
49
62
  // Another session opened meanwhile: its composer isn't where this
50
63
  // text goes, so only the toast has it.
51
- if (text.trim() && sessionId() !== id) {
64
+ if (sessionId() !== id) {
52
65
  movedOn(id, text);
53
66
  return result;
54
67
  }
55
- if (text.trim() && !putBack(text)) toast(`Removed (your draft stays): ${clipped(text)}`);
68
+ if (!putBack(text)) toast(`Removed (your draft stays): ${clipped(text)}`);
56
69
  return result;
57
70
  } catch (error) {
58
71
  if (button.isConnected) button.disabled = false;
@@ -34,14 +34,9 @@ export function viewerSelf() {
34
34
 
35
35
  // Whether +clientId+ is the viewer's own (chi web gives a participant's
36
36
  // turns participant:<grant id>, whichever tab or device sent them).
37
- const PARTICIPANT_CLIENT = "participant:";
38
- // compat shim review_client_id: the same id as an older chi gave it.
39
- const LEGACY_PARTICIPANT_CLIENT = "review:";
40
37
  export function isViewerClient(clientId) {
41
38
  if (!self?.clientId) return false;
42
- if (clientId === self.clientId) return true;
43
- const own = String(self.clientId);
44
- return own.startsWith(PARTICIPANT_CLIENT) && clientId === LEGACY_PARTICIPANT_CLIENT + own.slice(PARTICIPANT_CLIENT.length);
39
+ return clientId === self.clientId;
45
40
  }
46
41
 
47
42
  // Whether +author+ ("p:<id>") is the viewer's.
@@ -128,6 +128,17 @@ export function createViews({
128
128
  allViewPushed = false;
129
129
  applyView();
130
130
  }
131
+ // The session's hash in the URL, kept without a view's action: the URL
132
+ // names what the page shows, and All sessions or a pages view own it
133
+ // instead (theirs is never replaced). The session's own hash when the
134
+ // page shows the session.
135
+ function keepSessionHash(id) {
136
+ if (!id) return;
137
+ if (allViewOpen() || pagesAreaOpen()) return;
138
+ const hash = sessionHash(id);
139
+ if (location.hash === hash) return;
140
+ history.replaceState(null, "", location.pathname + location.search + hash);
141
+ }
131
142
  // The open session in the URL, so a reload or a copied link opens it again.
132
143
  // Switching sessions replaces the entry; only all sessions pushes one.
133
144
  // A page open: a session picked (a continue, a created session) leaves the
@@ -208,7 +219,7 @@ export function createViews({
208
219
  });
209
220
 
210
221
  return {
211
- allViewOpen, openAllView, closeAllView, leaveAllView, setSessionHash, selectFromHash, applyView,
222
+ allViewOpen, openAllView, closeAllView, leaveAllView, setSessionHash, keepSessionHash, selectFromHash, applyView,
212
223
  pageOpen, openPage, closePage, leavePage, pageBackLabel,
213
224
  listOpen, openPagesList, closePagesList, pagesAreaOpen,
214
225
  };
@@ -83,6 +83,7 @@ module Samagotchi
83
83
  end
84
84
 
85
85
  def truthy_param?(value) = %w[1 true yes].include?(value.to_s.strip.downcase)
86
+ def falsy_param?(value) = %w[0 false no].include?(value.to_s.strip.downcase)
86
87
 
87
88
  # GET /api/sessions/resolve?id=PREFIX: the full id of the session an id
88
89
  # or a unique prefix names (SessionAccess::Local#resolve). 200 {id};
@@ -131,7 +132,8 @@ module Samagotchi
131
132
  # recap, ctx_pct, waiting, …), filtered as its flags filter. Params: dir (a
132
133
  # folder: its project's sessions; none: every project's), cwd (in that
133
134
  # folder or below), live=1, archived=1, tests=0 (leave test runs out),
134
- # sort, order, limit. An array, newest first by default.
135
+ # delegates=0 (leave delegates and chi scratch sessions out: a phone's
136
+ # pick list), sort, order, limit. An array, newest first by default.
135
137
  def handle_summaries(req)
136
138
  dir, error = scope_dir(req.GET["dir"])
137
139
  return error if error
@@ -142,9 +144,10 @@ module Samagotchi
142
144
 
143
145
  rows = session_access.summaries(
144
146
  live: truthy_param?(req.GET["live"]), cwd: cwd, limit: sanitize_limit(req.GET["limit"]),
145
- include_tests: !%w[0 false no].include?(req.GET["tests"].to_s.strip.downcase),
147
+ include_tests: !falsy_param?(req.GET["tests"]),
146
148
  project_root: dir && ProjectScope.root_for(dir), include_archived: truthy_param?(req.GET["archived"]),
147
- sort: sanitize_sort(req.GET["sort"]), order: sanitize_order(req.GET["order"])
149
+ sort: sanitize_sort(req.GET["sort"]), order: sanitize_order(req.GET["order"]),
150
+ exclude_delegates: falsy_param?(req.GET["delegates"])
148
151
  )
149
152
  json_response(200, rows.map(&:to_summary_h))
150
153
  end
@@ -499,8 +499,10 @@ module Samagotchi
499
499
  # session within the wait (STOP_WAIT_SECONDS, or the body's seconds up
500
500
  # to SessionManager::STOP_WAIT: chi sessions stop's two wordings); 409
501
501
  # owned_by_tui; 409 stop_held (another change held the session's
502
- # transition lock past the stop's wait: SessionTransition::Busy, its
503
- # words, and the kind and successor_id it is built from).
502
+ # transition lock: a continue naming its new link, a delete or an
503
+ # archive at once, a short hold past the stop's wait;
504
+ # SessionTransition::Busy, its words, and the kind and successor_id
505
+ # it is built from).
504
506
  def handle_stop(req, id)
505
507
  # Bounded, so a Rack thread isn't held long; a worker still exiting
506
508
  # after it just means an immediate resume finds it (rare).
@@ -17,6 +17,8 @@ require_relative "../session_setup"
17
17
  require_relative "../thinking"
18
18
  require_relative "../toolkit"
19
19
  require_relative "../turn_flow"
20
+ require_relative "ask_create"
21
+ require_relative "ask_routes"
20
22
  require_relative "request_body"
21
23
 
22
24
  module Samagotchi
@@ -37,10 +39,14 @@ module Samagotchi
37
39
  private
38
40
 
39
41
  def handle_create(req)
42
+ # A create that answers its first turn (AskCreate) draws on one
43
+ # deadline from the request's start, as an ask does.
44
+ deadline = ask_clock + AskRoutes::ASK_MAX_SECONDS
40
45
  body = parse_json(request_body(req, RequestBody::OWNER_TURN_BODY_LIMIT))
41
46
  unless body.is_a?(Hash)
42
47
  return error_response(400, "invalid_json", "invalid JSON body")
43
48
  end
49
+ return handle_ask_create(body, deadline) if AskCreate.inline?(body)
44
50
 
45
51
  prompt = body["prompt"] || body[:prompt]
46
52
  # idle: a session with no first turn, for a first message with
@@ -56,16 +62,48 @@ module Samagotchi
56
62
  dir, error = scope_dir(body["dir"])
57
63
  return error if error
58
64
 
65
+ folder, parent_answers, error = create_fields(body, idle ? body["preview"] : prompt, dir: dir || start_dir)
66
+ return error if error
67
+
68
+ # preview: an idle session's first message, sent as its first turn
69
+ # next; the list and the notifications name the session by it
70
+ # until that turn is saved.
71
+ preview = idle ? body["preview"].to_s.strip : ""
72
+ folder[:preview] = preview unless preview.empty?
73
+ begin
74
+ session = @manager.spawn_session(prompt: idle ? nil : prompt.to_s,
75
+ client_id: body["client_id"] || ClientId::WEB_CREATE,
76
+ state_dir: @state_dir, **folder)
77
+ rescue ModelProfile::MissingModel => e
78
+ # No model configured, or one qualified with an unknown host.
79
+ return error_response(400, "invalid_model", e.message)
80
+ end
81
+ # The worker's Bridge is the single live transport: wait (bounded) for
82
+ # it so the client can attach without client-side polling.
83
+ port = await_worker_link(session.id).then { |link| link.live? ? link.port : nil }
84
+ # The projection holds it before the page hears back (no tick wait).
85
+ @hub&.touch(session.id)
86
+ record_history(body, prompt) if !idle && PromptHistory.shell_line?(prompt.to_s.strip)
87
+ json_response(201, session_to_json(session).merge(bridge_port: port, model_warning: session.model_warning,
88
+ parent_answers_warning: Guardrails::ParentPolicy.capped_note(parent_answers),
89
+ first_turn_id: session.first_turn_id, **create_token(session)))
90
+ end
91
+
92
+ # A new session's setup from the create body, each field checked
93
+ # before anything spawns (a bad one spawns nothing), and the create's
94
+ # refusals (#create_refusal, for its first +line+): [spawn_session's
95
+ # folder kwargs (working_directory: +dir+, driver, model_name, setup),
96
+ # parent_answers, nil] or [nil, nil, the response].
97
+ def create_fields(body, line, dir:)
59
98
  # llm_context: the session's own LLM context values before its first
60
- # turn (the start page's ⚙ panel; chi --llm-context), read
61
- # before anything spawns so a bad one spawns nothing.
99
+ # turn (the start page's ⚙ panel; chi --llm-context).
62
100
  llm_context, error = request_llm_context(body["llm_context"])
63
- return error if error
101
+ return [nil, nil, error] if error
64
102
 
65
103
  # thinking: the session's own thinking level (the start page's think
66
104
  # chip; chi --thinking), checked the same way.
67
105
  thinking, error = request_thinking(body["thinking"])
68
- return error if error
106
+ return [nil, nil, error] if error
69
107
 
70
108
  # settings: the session's own settings, flat as chi --set names
71
109
  # them ({"recap.enabled" => false, "cost-cap.cap" => 3}), checked
@@ -73,7 +111,7 @@ module Samagotchi
73
111
  begin
74
112
  settings = SessionConfig.from_request(body["settings"])
75
113
  rescue SessionConfig::Error => e
76
- return error_response(400, "invalid_settings", e.message)
114
+ return [nil, nil, error_response(400, "invalid_settings", e.message)]
77
115
  end
78
116
 
79
117
  # toolkit, tools, no_tools: its toolkit (chi send --new --toolkit,
@@ -82,54 +120,33 @@ module Samagotchi
82
120
  # (hard, standard or soft; a looser one than config.yml's is capped,
83
121
  # and the 201's parent_answers_warning says so).
84
122
  toolkit, error = request_toolkit(body)
85
- return error if error
123
+ return [nil, nil, error] if error
86
124
 
87
125
  parent_answers, error = request_parent_answers(body["parent_answers"])
88
- return error if error
126
+ return [nil, nil, error] if error
89
127
 
90
128
  # driver: the agent (agent:<name>) the owner names its driver (chi
91
129
  # send --new --driver); none: its creator when that is an agent.
92
130
  driver = body["driver"]
93
131
  unless driver.nil? || (ClientId.agent?(driver) && ClientId.agent(ClientId.agent_name(driver)) == driver)
94
- return error_response(400, "invalid_driver", "driver is an agent's id: agent:<name>")
132
+ return [nil, nil, error_response(400, "invalid_driver", "driver is an agent's id: agent:<name>")]
95
133
  end
96
134
 
97
135
  model = (body["model"] || body["model_name"]).to_s.strip
98
- refused = create_refusal(body, idle ? body["preview"] : prompt, values: [parent_answers], model: model)
99
- return refused if refused
136
+ refused = create_refusal(body, line, values: [parent_answers], model: model)
137
+ return [nil, nil, refused] if refused
100
138
 
101
- folder = { working_directory: dir || start_dir }
139
+ folder = { working_directory: dir }
102
140
  folder[:driver] = driver if driver
103
141
  # model: the model the session starts on (the start page's picker,
104
142
  # spelled as GET /api/models lists it); blank means the default.
105
143
  folder[:model_name] = model unless model.empty?
106
- # preview: an idle session's first message, sent as its first turn
107
- # next; the list and the notifications name the session by it
108
- # until that turn is saved.
109
- preview = idle ? body["preview"].to_s.strip : ""
110
- folder[:preview] = preview unless preview.empty?
111
144
  # A create takes no memories, mutes or prompt files (paths of this
112
145
  # machine's terminal), nor reasoning_history.
113
146
  setup = SessionSetup.from_request(llm_context: llm_context, thinking: thinking, settings: settings, toolkit: toolkit,
114
147
  parent_answers: parent_answers)
115
148
  folder[:setup] = setup unless setup.empty?
116
- begin
117
- session = @manager.spawn_session(prompt: idle ? nil : prompt.to_s,
118
- client_id: body["client_id"] || ClientId::WEB_CREATE,
119
- state_dir: @state_dir, **folder)
120
- rescue ModelProfile::MissingModel => e
121
- # No model configured, or one qualified with an unknown host.
122
- return error_response(400, "invalid_model", e.message)
123
- end
124
- # The worker's Bridge is the single live transport: wait (bounded) for
125
- # it so the client can attach without client-side polling.
126
- port = await_worker_link(session.id).then { |link| link.live? ? link.port : nil }
127
- # The projection holds it before the page hears back (no tick wait).
128
- @hub&.touch(session.id)
129
- record_history(body, prompt) if !idle && PromptHistory.shell_line?(prompt.to_s.strip)
130
- json_response(201, session_to_json(session).merge(bridge_port: port, model_warning: session.model_warning,
131
- parent_answers_warning: Guardrails::ParentPolicy.capped_note(parent_answers),
132
- first_turn_id: session.first_turn_id, **create_token(session)))
149
+ [folder, parent_answers, nil]
133
150
  end
134
151
 
135
152
  # POST /api/sessions with continues: <id, prefix or last:id>: the next