samagotchi 0.177.1 → 0.178.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +27 -1
- data/docs/cli.md +27 -5
- data/docs/guardrails.md +1 -1
- data/docs/internals/background-tasks.md +23 -2
- data/docs/internals/bridge.md +17 -6
- data/docs/internals/remote-sessions.md +6 -1
- data/docs/internals/session-lifecycle.md +17 -8
- data/docs/internals/web-frontend.md +7 -3
- data/docs/internals/working-set.md +31 -5
- data/docs/scheduling.md +8 -1
- data/docs/sessions.md +9 -5
- data/lib/samagotchi/bridge/card_store.rb +2 -19
- data/lib/samagotchi/bridge.rb +38 -6
- data/lib/samagotchi/bundles/system/manifest.yml +1 -1
- data/lib/samagotchi/compat.rb +0 -7
- data/lib/samagotchi/engine/events.rb +43 -0
- data/lib/samagotchi/engine.rb +9 -3
- data/lib/samagotchi/event_fanout.rb +56 -0
- data/lib/samagotchi/guardrails/approvals.rb +0 -4
- data/lib/samagotchi/schedules.rb +9 -4
- data/lib/samagotchi/session_access/contract.rb +4 -0
- data/lib/samagotchi/session_access/local.rb +16 -4
- data/lib/samagotchi/session_access/remote.rb +42 -9
- data/lib/samagotchi/session_archive_command.rb +38 -10
- data/lib/samagotchi/session_chain/delete.rb +75 -25
- data/lib/samagotchi/session_delete_command.rb +33 -10
- data/lib/samagotchi/session_lifecycle/allowed.rb +12 -9
- data/lib/samagotchi/session_manager/lifecycle.rb +12 -26
- data/lib/samagotchi/session_manager/removal.rb +109 -25
- data/lib/samagotchi/session_manager/running_tasks.rb +334 -0
- data/lib/samagotchi/sessions_command.rb +1 -1
- data/lib/samagotchi/task_files.rb +37 -4
- data/lib/samagotchi/terminal_ui/attached_loop/exit_commands.rb +7 -1
- data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
- data/lib/samagotchi/terminal_ui/local_link.rb +11 -3
- data/lib/samagotchi/tools/task_runtime.rb +25 -6
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +5 -1
- data/lib/samagotchi/web/public/data.js +19 -7
- data/lib/samagotchi/web/public/delete_sheet.js +26 -7
- data/lib/samagotchi/web/public/running_tasks.js +73 -0
- data/lib/samagotchi/web/public/session_actions.js +57 -8
- data/lib/samagotchi/web/public/stop_sheet.js +3 -2
- data/lib/samagotchi/web/public/working_set.js +3 -28
- data/lib/samagotchi/web/public/working_set_view.js +5 -2
- data/lib/samagotchi/web/public/ws_item_sig.js +51 -0
- data/lib/samagotchi/web/public/ws_peek.js +23 -13
- data/lib/samagotchi/web/public/ws_reader.js +22 -12
- data/lib/samagotchi/web/public/ws_timeline.js +9 -6
- data/lib/samagotchi/web/session_control.rb +65 -16
- data/lib/samagotchi/web/working_set_routes.rb +29 -8
- data/lib/samagotchi/worker_link.rb +9 -1
- data/lib/samagotchi/working_set.rb +26 -0
- data/lib/samagotchi/working_set_command.rb +9 -6
- metadata +4 -1
|
@@ -20,26 +20,59 @@ module Samagotchi
|
|
|
20
20
|
# A task id as task_create makes them: no path parts.
|
|
21
21
|
TASK_ID = /\A[A-Za-z0-9_-]+\z/
|
|
22
22
|
|
|
23
|
+
# The thread-local root #with_root sets.
|
|
24
|
+
ROOT_KEY = :samagotchi_task_root
|
|
25
|
+
|
|
23
26
|
module_function
|
|
24
27
|
|
|
28
|
+
# Runs the block with this thread's task paths under +root+ (a
|
|
29
|
+
# session's working directory) instead of the cwd: chi web and the CLI
|
|
30
|
+
# stop a session's tasks this way (SessionManager::RunningTasks.stop!).
|
|
31
|
+
# Per thread: a thread the block starts doesn't inherit it (only
|
|
32
|
+
# create_task starts waiters, and nothing calls it under a root).
|
|
33
|
+
# Without a root every path is the relative one it always was.
|
|
34
|
+
# A nil or empty +root+ is no root (the cwd's relative paths).
|
|
35
|
+
def with_root(root)
|
|
36
|
+
before = Thread.current[ROOT_KEY]
|
|
37
|
+
Thread.current[ROOT_KEY] = root.nil? || root.to_s.empty? ? nil : root.to_s
|
|
38
|
+
yield
|
|
39
|
+
ensure
|
|
40
|
+
Thread.current[ROOT_KEY] = before
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# This thread's #with_root, or nil (the cwd).
|
|
44
|
+
def root = Thread.current[ROOT_KEY]
|
|
45
|
+
|
|
46
|
+
# +path+ under this thread's root when it is relative and a root is
|
|
47
|
+
# set; else +path+ unchanged.
|
|
48
|
+
def rooted(path)
|
|
49
|
+
base = root
|
|
50
|
+
return path if base.nil? || path.nil? || path.to_s.empty? || File.absolute_path?(path.to_s)
|
|
51
|
+
|
|
52
|
+
File.join(base, path.to_s)
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# tmp/tasks, under this thread's root when one is set.
|
|
56
|
+
def tasks_dir = rooted(TASKS_DIR)
|
|
57
|
+
|
|
25
58
|
def metadata_path(task_id)
|
|
26
59
|
File.join(task_dir_for(task_id), METADATA_FILENAME)
|
|
27
60
|
end
|
|
28
61
|
|
|
29
62
|
def task_dir_for(task_id)
|
|
30
|
-
File.join(
|
|
63
|
+
File.join(tasks_dir, task_id.to_s)
|
|
31
64
|
end
|
|
32
65
|
|
|
33
66
|
# The command of the task +task_id+ under +root+ (a session's working
|
|
34
|
-
# directory) as its record has it, for a UI row's title; nil for no
|
|
67
|
+
# directory; by default this thread's root, else the cwd) as its record has it, for a UI row's title; nil for no
|
|
35
68
|
# such task or an unreadable record. Reads the record only (no
|
|
36
69
|
# refresh), so it is cheap and never fails.
|
|
37
70
|
# @return [String, nil]
|
|
38
|
-
def command_of(task_id, root:
|
|
71
|
+
def command_of(task_id, root: nil)
|
|
39
72
|
id = task_id.to_s.strip
|
|
40
73
|
return nil unless id.match?(TASK_ID)
|
|
41
74
|
|
|
42
|
-
path = File.join(root || Dir.pwd, TASKS_DIR, id, METADATA_FILENAME)
|
|
75
|
+
path = File.join(root || self.root || Dir.pwd, TASKS_DIR, id, METADATA_FILENAME)
|
|
43
76
|
return nil unless File.file?(path)
|
|
44
77
|
|
|
45
78
|
command = Tools::TaskRecord.from_file(JSON.parse(File.read(path)))&.command
|
|
@@ -104,6 +104,11 @@ module Samagotchi
|
|
|
104
104
|
rescue SystemCallError, IOError => e
|
|
105
105
|
detach("#{ExitLines.exit_failed_line(e.message, via: via, session_id: id)} Not deleted.")
|
|
106
106
|
rescue SessionManager::DeleteRefused, SessionManager::OwnedByTUI, ArgumentError => e
|
|
107
|
+
if e.is_a?(SessionManager::DeleteRefused) && e.reason == :tasks_running
|
|
108
|
+
return detach("Detached; the worker is stopping, but session #{id} was not deleted (#{e.message}; " \
|
|
109
|
+
"#{SessionManager::RunningTasks.hint(via, "delete", id)}).")
|
|
110
|
+
end
|
|
111
|
+
|
|
107
112
|
detach("Detached; the worker is stopping, but session #{id} was not deleted (#{e.message}): " \
|
|
108
113
|
"#{via.command("sessions delete #{id}")}")
|
|
109
114
|
end
|
|
@@ -147,7 +152,8 @@ module Samagotchi
|
|
|
147
152
|
rescue SystemCallError, IOError => e
|
|
148
153
|
detach("#{ExitLines.exit_failed_line(e.message, via: via, session_id: id)} Not archived.")
|
|
149
154
|
rescue SessionManager::ArchiveRefused, SessionManager::OwnedByTUI, ArgumentError => e
|
|
150
|
-
|
|
155
|
+
hint = "; #{SessionManager::RunningTasks.hint(via, "archive", id)}" if e.is_a?(SessionManager::ArchiveRefused) && e.reason == :tasks_running
|
|
156
|
+
detach("Detached; session #{id} was not archived (#{e.message}#{hint}). Re-attach with: #{via.attach(id)}")
|
|
151
157
|
end
|
|
152
158
|
end
|
|
153
159
|
end
|
|
@@ -119,7 +119,7 @@ module Samagotchi
|
|
|
119
119
|
default_input: false, wait_at_eof: false, as_parent: false, scratch: false,
|
|
120
120
|
clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }, now: -> { MessageTime.now },
|
|
121
121
|
delete_session: LocalLink::DELETE,
|
|
122
|
-
archive_session:
|
|
122
|
+
archive_session: LocalLink::ARCHIVE,
|
|
123
123
|
installed_version: -> { InstalledVersions.new.newest },
|
|
124
124
|
state_dir: Session.default_state_dir,
|
|
125
125
|
children_counts: ->(id) { ChildrenStatus.counts(id, state_dir: state_dir) }, link: nil)
|
|
@@ -28,9 +28,17 @@ module Samagotchi
|
|
|
28
28
|
DELETE_WAIT = 10
|
|
29
29
|
# /exit --delete on this machine (LocalLink's and AttachedLoop's
|
|
30
30
|
# default): a user's delete, so a chain's newest link is undone and the
|
|
31
|
-
# previous one comes back (SessionManager.delete_session's keywords)
|
|
31
|
+
# previous one comes back (SessionManager.delete_session's keywords),
|
|
32
|
+
# and background tasks still running refuse it (RunningTasks REFUSE:
|
|
33
|
+
# the line names chi sessions delete --stop-tasks).
|
|
32
34
|
DELETE = lambda do |id|
|
|
33
|
-
SessionManager.delete_session(id, stop: true, wait: DELETE_WAIT, revive_previous: true, refuse_continuing: true
|
|
35
|
+
SessionManager.delete_session(id, stop: true, wait: DELETE_WAIT, revive_previous: true, refuse_continuing: true,
|
|
36
|
+
running_tasks: SessionManager::RunningTasks::Policy::REFUSE)
|
|
37
|
+
end
|
|
38
|
+
# /archive on this machine (LocalLink's and AttachedLoop's default):
|
|
39
|
+
# refused while background tasks it or a delegate started still run.
|
|
40
|
+
ARCHIVE = lambda do |id|
|
|
41
|
+
SessionManager.archive_session(id, wait: DELETE_WAIT, running_tasks: SessionManager::RunningTasks::Policy::REFUSE)
|
|
34
42
|
end
|
|
35
43
|
|
|
36
44
|
attr_reader :client
|
|
@@ -44,7 +52,7 @@ module Samagotchi
|
|
|
44
52
|
# @param children_counts [#call] session id -> ChildrenStatus::Counts
|
|
45
53
|
def initialize(client:, state_dir: Session.default_state_dir,
|
|
46
54
|
delete_session: DELETE,
|
|
47
|
-
archive_session:
|
|
55
|
+
archive_session: ARCHIVE,
|
|
48
56
|
installed_version: -> { InstalledVersions.new.newest },
|
|
49
57
|
children_counts: ->(id) { ChildrenStatus.counts(id, state_dir: state_dir) })
|
|
50
58
|
@client = client
|
|
@@ -39,6 +39,7 @@ module Samagotchi
|
|
|
39
39
|
# signals, since two held? probes at once read each other as holders.
|
|
40
40
|
LEFTOVER_GRACE_SEC = Leftovers::GRACE_SEC
|
|
41
41
|
LEFTOVER_STOP_GRACE_SEC = 1.0
|
|
42
|
+
SETTLE_ON_EXIT_SECONDS = LEFTOVER_GRACE_SEC + LEFTOVER_STOP_GRACE_SEC + ProcessGroup::KILL_WAIT_SEC + 0.5
|
|
42
43
|
REFRESH_STOP_GRACE_SEC = 0.5
|
|
43
44
|
REFRESH_KILL_WAIT_SEC = 0.5
|
|
44
45
|
HELD_RECHECK_SEC = 0.05
|
|
@@ -148,7 +149,7 @@ module Samagotchi
|
|
|
148
149
|
forget_waiter(task_id, Thread.current)
|
|
149
150
|
end
|
|
150
151
|
thread.name = EXIT_STATUS_THREAD
|
|
151
|
-
remember_waiter(task_id, thread, started&.pid)
|
|
152
|
+
remember_waiter(task_id, thread, started&.pid, waiter)
|
|
152
153
|
thread
|
|
153
154
|
end
|
|
154
155
|
|
|
@@ -167,8 +168,8 @@ module Samagotchi
|
|
|
167
168
|
end
|
|
168
169
|
end
|
|
169
170
|
|
|
170
|
-
def remember_waiter(task_id, thread, pid)
|
|
171
|
-
@waiters_lock.synchronize { @waiters[task_id] = [thread, pid] if thread.alive? }
|
|
171
|
+
def remember_waiter(task_id, thread, pid, detach)
|
|
172
|
+
@waiters_lock.synchronize { @waiters[task_id] = [thread, pid, detach] if thread.alive? }
|
|
172
173
|
end
|
|
173
174
|
|
|
174
175
|
def forget_waiter(task_id, thread)
|
|
@@ -212,7 +213,9 @@ module Samagotchi
|
|
|
212
213
|
def log_paths(record)
|
|
213
214
|
return [] unless record
|
|
214
215
|
|
|
215
|
-
|
|
216
|
+
# A relative log (create_task's output_path) is read under the
|
|
217
|
+
# thread's root (TaskFiles.with_root); the record keeps it as is.
|
|
218
|
+
[record.output_path, record.stderr_path].filter_map { |log| TaskFiles.rooted(log.to_s) unless log.to_s.empty? }
|
|
216
219
|
end
|
|
217
220
|
|
|
218
221
|
# The one line task_get, task_wait (and the finish note) and task_list
|
|
@@ -233,6 +236,22 @@ module Samagotchi
|
|
|
233
236
|
# record_exit_status's threads' name.
|
|
234
237
|
EXIT_STATUS_THREAD = "task_exit_status"
|
|
235
238
|
|
|
239
|
+
# Join this process's already-reaped tasks, sharing one timeout. A
|
|
240
|
+
# shell that exits after the snapshot is not included.
|
|
241
|
+
# @return [Array<Thread>] the selected waiters still alive at the deadline
|
|
242
|
+
def settle_pending!(timeout:)
|
|
243
|
+
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
|
|
244
|
+
threads = @waiters_lock.synchronize do
|
|
245
|
+
@waiters.values.filter_map do |thread, _pid, detach|
|
|
246
|
+
thread if thread != Thread.current && thread.alive? && (!detach.alive? || thread[SETTLING])
|
|
247
|
+
end
|
|
248
|
+
end
|
|
249
|
+
threads.each { |thread| thread.join([deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC), 0].max) }
|
|
250
|
+
alive = threads.select(&:alive?)
|
|
251
|
+
Log.warn(:turn, "task_leftovers_unsettled", count: alive.size) unless alive.empty?
|
|
252
|
+
alive
|
|
253
|
+
end
|
|
254
|
+
|
|
236
255
|
# Joins every live EXIT_STATUS_THREAD, for up to +timeout+ s in all: a
|
|
237
256
|
# spec calls it (with_task_dir) after stopping its tasks and before it
|
|
238
257
|
# removes their folder, which a recorder may still write into. chi
|
|
@@ -306,7 +325,7 @@ module Samagotchi
|
|
|
306
325
|
|
|
307
326
|
def list_records
|
|
308
327
|
ensure_tasks_dir
|
|
309
|
-
task_dirs = Dir.glob(File.join(TaskFiles
|
|
328
|
+
task_dirs = Dir.glob(File.join(TaskFiles.tasks_dir, "*"))
|
|
310
329
|
.select { |path| File.directory?(path) }
|
|
311
330
|
|
|
312
331
|
task_dirs.map do |task_dir|
|
|
@@ -504,7 +523,7 @@ module Samagotchi
|
|
|
504
523
|
def record_json(record) = JSON.pretty_generate(record.to_file) + "\n"
|
|
505
524
|
|
|
506
525
|
def ensure_tasks_dir
|
|
507
|
-
FileUtils.mkdir_p(TaskFiles
|
|
526
|
+
FileUtils.mkdir_p(TaskFiles.tasks_dir)
|
|
508
527
|
end
|
|
509
528
|
|
|
510
529
|
def generate_task_id
|
data/lib/samagotchi/version.rb
CHANGED
data/lib/samagotchi/web/app.rb
CHANGED
|
@@ -1109,8 +1109,12 @@ module Samagotchi
|
|
|
1109
1109
|
# DELETE …/chain, and the plain delete's revive and undo (D2/D5): chi
|
|
1110
1110
|
# --remote sessions delete --chain asks for this first.
|
|
1111
1111
|
CHAIN_DELETE_FEATURE = "chain_delete"
|
|
1112
|
+
# Delete and archive refuse on running background tasks (409
|
|
1113
|
+
# tasks_running) and take stop_tasks: chi --remote sessions
|
|
1114
|
+
# delete|archive --stop-tasks asks for this first.
|
|
1115
|
+
STOP_TASKS_FEATURE = "stop_tasks"
|
|
1112
1116
|
INFO_FEATURES = ["dir", "newest_workers", SessionAccessRoutes::FEATURE, SessionAccessRoutes::ATTACH_FEATURE,
|
|
1113
|
-
BOUND_FEATURE, CHAIN_DELETE_FEATURE].freeze
|
|
1117
|
+
BOUND_FEATURE, CHAIN_DELETE_FEATURE, STOP_TASKS_FEATURE].freeze
|
|
1114
1118
|
|
|
1115
1119
|
# The models a new session can start on, spelled as chi spells them
|
|
1116
1120
|
# elsewhere: bare for the default host (what default.model holds), and
|
|
@@ -270,8 +270,12 @@ export function restartSession(id, opts = {}) {
|
|
|
270
270
|
|
|
271
271
|
// Hides the session (and its delegates) from the lists, kept for good; the
|
|
272
272
|
// server stops a live idle worker first and answers 409 while a turn runs.
|
|
273
|
+
// stopTasks: stop the background tasks it and its delegates started first
|
|
274
|
+
// (without it, a session whose tasks still run is refused: 409 tasks_running).
|
|
273
275
|
export function archiveSession(id, opts = {}) {
|
|
274
|
-
|
|
276
|
+
const { stopTasks, ...apiOpts } = opts;
|
|
277
|
+
const body = JSON.stringify(stopTasks ? { stop_tasks: true } : {});
|
|
278
|
+
return api(`/api/sessions/${encodeURIComponent(id)}/archive`, { method: "POST", body, ...apiOpts });
|
|
275
279
|
}
|
|
276
280
|
|
|
277
281
|
// Back to the lists, delegates too.
|
|
@@ -279,20 +283,28 @@ export function unarchiveSession(id, opts = {}) {
|
|
|
279
283
|
return api(`/api/sessions/${encodeURIComponent(id)}/unarchive`, { method: "POST", body: JSON.stringify({}), ...opts });
|
|
280
284
|
}
|
|
281
285
|
|
|
286
|
+
// A delete's query after force=true: the plan digest the user confirmed
|
|
287
|
+
// (expect), and stop_tasks (stop the background tasks the deleted sessions
|
|
288
|
+
// started first; without it, 409 tasks_running while one runs).
|
|
289
|
+
function deleteQuery({ expect, stopTasks }) {
|
|
290
|
+
const plan = expect == null ? "" : `&expect=${encodeURIComponent(expect)}`;
|
|
291
|
+
return `${plan}${stopTasks ? "&stop_tasks=true" : ""}`;
|
|
292
|
+
}
|
|
293
|
+
|
|
282
294
|
// Deletes the session for good; force=true has the server stop a live
|
|
283
295
|
// worker first (the page's confirm says so; without it, 409 worker_running).
|
|
284
296
|
export function deleteSession(id, opts = {}) {
|
|
285
|
-
const { expect, ...apiOpts } = opts;
|
|
286
|
-
|
|
287
|
-
|
|
297
|
+
const { expect, stopTasks, ...apiOpts } = opts;
|
|
298
|
+
return api(`/api/sessions/${encodeURIComponent(id)}?force=true${deleteQuery({ expect, stopTasks })}`,
|
|
299
|
+
{ method: "DELETE", ...apiOpts });
|
|
288
300
|
}
|
|
289
301
|
|
|
290
302
|
// Deletes every link of the session's chain with their delegates (running
|
|
291
303
|
// ones are left running); force: the links' workers are stopped first.
|
|
292
304
|
export function deleteChain(id, opts = {}) {
|
|
293
|
-
const { expect, ...apiOpts } = opts;
|
|
294
|
-
|
|
295
|
-
|
|
305
|
+
const { expect, stopTasks, ...apiOpts } = opts;
|
|
306
|
+
return api(`/api/sessions/${encodeURIComponent(id)}/chain?force=true${deleteQuery({ expect, stopTasks })}`,
|
|
307
|
+
{ method: "DELETE", ...apiOpts });
|
|
296
308
|
}
|
|
297
309
|
|
|
298
310
|
// What deleting a chained session would do, for the delete sheet
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
import { html, nothing, render } from "./vendor/lit-html.js";
|
|
21
21
|
import { createChipPopover } from "./chip_popover.js";
|
|
22
22
|
import { cardName, clip, normalize } from "./format.js";
|
|
23
|
+
import { tasksCount, tasksLine } from "./running_tasks.js";
|
|
23
24
|
|
|
24
25
|
const short = (id) => String(id ?? "").slice(0, 8);
|
|
25
26
|
const count = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
@@ -166,10 +167,22 @@ export function loadingTemplate({ back = false } = {}) {
|
|
|
166
167
|
|
|
167
168
|
// A refused delete, in the sheet: a moved delegate that can't go back
|
|
168
169
|
// (delegate_unmovable: "Stop its worker, then delete" only when the page
|
|
169
|
-
// can stop it, not a one-turn run's),
|
|
170
|
-
//
|
|
170
|
+
// can stop it, not a one-turn run's), background tasks the delete takes
|
|
171
|
+
// still running (tasks_running: "Stop them and delete"), or any other
|
|
172
|
+
// refusal's own words.
|
|
173
|
+
// @param refusal {reason, message, ids, stoppable, tasks, sessionId}
|
|
171
174
|
// @param previousId the link the delegate would go back to
|
|
172
175
|
export function refusalModel(refusal, previousId = null) {
|
|
176
|
+
if (refusal?.reason === "tasks_running") {
|
|
177
|
+
const n = tasksCount(refusal.tasks);
|
|
178
|
+
return {
|
|
179
|
+
title: "Background tasks still running",
|
|
180
|
+
text: `${count(n, "background task")} this delete takes ${n === 1 ? "is" : "are"} still running: ` +
|
|
181
|
+
`${tasksLine(refusal.tasks, refusal.sessionId)}. Nothing was deleted.`,
|
|
182
|
+
stop: { label: n === 1 ? "Stop it and delete" : "Stop them and delete",
|
|
183
|
+
line: `${n === 1 ? "It is" : "They are"} stopped (TERM, then KILL after 3 s), then the session goes.` },
|
|
184
|
+
};
|
|
185
|
+
}
|
|
173
186
|
if (refusal?.reason === "delegate_unmovable") {
|
|
174
187
|
const id = (refusal.ids || [])[0];
|
|
175
188
|
const back = previousId ? short(previousId) : "the previous link";
|
|
@@ -263,19 +276,24 @@ export function runDeleteFlow({ id, session, host, api, done, plain, failed }) {
|
|
|
263
276
|
|
|
264
277
|
// The refusal as the delete's 409 says it; whether the page can stop a
|
|
265
278
|
// moved delegate's worker is its +stoppable+, as the delete saw it.
|
|
266
|
-
|
|
267
|
-
|
|
279
|
+
// A tasks_running refusal keeps its tasks and the choice it refused
|
|
280
|
+
// (+which+), so "Stop them and delete" sends that choice again.
|
|
281
|
+
function refused(error, which) {
|
|
282
|
+
refusal = { reason: error.code, message: error.message, ids: error.body?.ids || [], stoppable: error.body?.stoppable === true,
|
|
283
|
+
tasks: error.body?.tasks || null, sessionId: id, which };
|
|
268
284
|
busy = false;
|
|
269
285
|
showRefusal();
|
|
270
286
|
}
|
|
271
287
|
|
|
272
|
-
|
|
288
|
+
// +stopTasks+: the same choice and digest, the tasks stopped first.
|
|
289
|
+
async function run(which, { stopTasks = false } = {}) {
|
|
273
290
|
if (busy || !live()) return;
|
|
274
291
|
busy = true;
|
|
275
292
|
showChoices();
|
|
276
293
|
try {
|
|
277
294
|
const digest = which === "chain" ? plan?.chain?.digest : plan?.link?.digest;
|
|
278
|
-
const
|
|
295
|
+
const opts = stopTasks ? { expect: digest, stopTasks: true } : { expect: digest };
|
|
296
|
+
const result = which === "chain" ? await api.deleteChain(id, opts) : await api.deleteSession(id, opts);
|
|
279
297
|
if (live()) host.close();
|
|
280
298
|
done(which, result, plan);
|
|
281
299
|
} catch (error) {
|
|
@@ -283,7 +301,7 @@ export function runDeleteFlow({ id, session, host, api, done, plain, failed }) {
|
|
|
283
301
|
await refreshPlan();
|
|
284
302
|
return;
|
|
285
303
|
}
|
|
286
|
-
refused(error);
|
|
304
|
+
refused(error, which);
|
|
287
305
|
}
|
|
288
306
|
}
|
|
289
307
|
|
|
@@ -331,6 +349,7 @@ export function runDeleteFlow({ id, session, host, api, done, plain, failed }) {
|
|
|
331
349
|
if (!live()) return;
|
|
332
350
|
if (name === "cancel") host.close();
|
|
333
351
|
else if (name === "this" || name === "chain") run(name);
|
|
352
|
+
else if (name === "stop" && refusal?.reason === "tasks_running") run(refusal.which, { stopTasks: true });
|
|
334
353
|
else if (name === "stop") stopThenDelete();
|
|
335
354
|
},
|
|
336
355
|
};
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// A session's background tasks a delete or an archive was refused for
|
|
2
|
+
// (the 409 tasks_running, SessionManager::RunningTasks), in the page's
|
|
3
|
+
// words: their one line, the second confirm, the toast's suffix after a
|
|
4
|
+
// stop. DOM-free (no lit-html): format.js-style text helpers, a module of
|
|
5
|
+
// their own (docs/internals/web-frontend.md, "New exports go in new modules").
|
|
6
|
+
// session_actions.js asks the confirm; delete_sheet.js' refusal view and
|
|
7
|
+
// stop_sheet.js' cut share NAMED_MAX and cutCommand.
|
|
8
|
+
|
|
9
|
+
// At most this many tasks (or holds of a kind) named in a line; the rest
|
|
10
|
+
// are one "+N more" (stop_sheet.js MAX_NAMED, RunningTasks::MAX_NAMED).
|
|
11
|
+
export const NAMED_MAX = 3;
|
|
12
|
+
|
|
13
|
+
// A command (a task's, a hold's label) cut short to fit a phone line
|
|
14
|
+
// (RunningTasks::COMMAND_CHARS).
|
|
15
|
+
export function cutCommand(label) {
|
|
16
|
+
return label.length > 42 ? `${label.slice(0, 42)}…` : label;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// The background tasks a delete or an archive was refused for (the 409
|
|
20
|
+
// tasks_running's tasks: {running, unverified, unreadable}, each
|
|
21
|
+
// [{session_id, id, command}]; a plain array reads as running), as one line:
|
|
22
|
+
// "npm run dev · rspec", at most NAMED_MAX named then "+N more". A task of
|
|
23
|
+
// another session than +sessionId+ (a delegate's, another link's) carries
|
|
24
|
+
// its short id ("9d0e1f2a: rspec"); one chi can't verify or read is named by
|
|
25
|
+
// its id. SessionManager::RunningTasks.words is the CLI's twin.
|
|
26
|
+
export function tasksLine(listing, sessionId = null) {
|
|
27
|
+
const names = taskEntries(listing).map(({ task, kind }) => {
|
|
28
|
+
const hex = String(task?.id ?? "").split("-").pop().slice(0, 8);
|
|
29
|
+
let name;
|
|
30
|
+
if (kind === "unverified") name = `task ${hex} (may still be running)`;
|
|
31
|
+
else if (kind === "unreadable") name = `task ${hex} (record unreadable)`;
|
|
32
|
+
else name = String(task?.command ?? "").trim() ? cutCommand(String(task.command).trim()) : `task ${hex}`;
|
|
33
|
+
const owner = String(task?.session_id ?? "");
|
|
34
|
+
return sessionId && owner && owner !== sessionId ? `${owner.slice(0, 8)}: ${name}` : name;
|
|
35
|
+
});
|
|
36
|
+
const more = names.length - NAMED_MAX;
|
|
37
|
+
return `${names.slice(0, NAMED_MAX).join(" · ")}${more > 0 ? ` +${more} more` : ""}`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// How many tasks +listing+ (as tasksLine's) holds.
|
|
41
|
+
export function tasksCount(listing) {
|
|
42
|
+
return taskEntries(listing).length;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function taskEntries(listing) {
|
|
46
|
+
if (Array.isArray(listing)) return listing.map((task) => ({ task, kind: "running" }));
|
|
47
|
+
return ["running", "unverified", "unreadable"].flatMap((kind) =>
|
|
48
|
+
(Array.isArray(listing?.[kind]) ? listing[kind] : []).map((task) => ({ task, kind })));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// The second confirm of a delete or an archive refused for background tasks
|
|
52
|
+
// still running (409 tasks_running): which, and whether to stop them and
|
|
53
|
+
// +verb+ ("delete" / "archive") the session. +listing+ is the 409's tasks.
|
|
54
|
+
export function tasksConfirmText(id, listing, verb) {
|
|
55
|
+
const n = tasksCount(listing);
|
|
56
|
+
const one = n === 1;
|
|
57
|
+
return [
|
|
58
|
+
`Session ${String(id).slice(0, 8)} started ${n} background task${one ? "" : "s"} that ${one ? "is" : "are"} still running:`,
|
|
59
|
+
tasksLine(listing, id),
|
|
60
|
+
`Stop ${one ? "it" : "them"} and ${verb} the session?`,
|
|
61
|
+
].join("\n");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// What a delete's or an archive's toast adds for the tasks it stopped (its
|
|
65
|
+
// 200's tasks_stopped / tasks_not_stopped): " · stopped 2 background tasks",
|
|
66
|
+
// " · 1 not stopped: npm run dev"; "" when it stopped none.
|
|
67
|
+
export function tasksStoppedSuffix(result) {
|
|
68
|
+
const stopped = (result?.tasks_stopped || []).length;
|
|
69
|
+
const left = result?.tasks_not_stopped || [];
|
|
70
|
+
let text = stopped ? ` · stopped ${stopped} background task${stopped === 1 ? "" : "s"}` : "";
|
|
71
|
+
if (left.length) text += ` · ${left.length} not stopped: ${tasksLine(left, result?.session_id ?? null)}`;
|
|
72
|
+
return text;
|
|
73
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { continueRefusal, continuedText, openChildrenTemplate, openerText } from "./chains.js";
|
|
2
2
|
import { cantText, deleteConfirmText, goneSessionNotice } from "./format.js";
|
|
3
|
+
import { tasksConfirmText, tasksCount, tasksStoppedSuffix } from "./running_tasks.js";
|
|
3
4
|
import { sessionHash } from "./route.js";
|
|
4
5
|
import { inTree } from "./sessions_list.js";
|
|
5
6
|
import { isChained, listAfterDelete, deleteToast, runDeleteFlow } from "./delete_sheet.js";
|
|
@@ -84,23 +85,55 @@ export function createSessionActions({
|
|
|
84
85
|
if (gone.has(selected())) clearSelection();
|
|
85
86
|
if (!eventsLive()) refresh();
|
|
86
87
|
const { text, back } = deleteToast(which, result, plan, id);
|
|
87
|
-
toast(text
|
|
88
|
+
toast(`${text}${tasksStoppedSuffix(result)}`, back ? { label: `Open ${back.slice(0, 8)}`, run: () => select(back) } : null);
|
|
88
89
|
}
|
|
89
90
|
|
|
90
|
-
// Today's confirm: a session in no chain.
|
|
91
|
+
// Today's confirm: a session in no chain. A session whose background
|
|
92
|
+
// tasks still run is refused (409 tasks_running, nothing deleted): a
|
|
93
|
+
// second confirm names them, and OK sends the delete again with
|
|
94
|
+
// stopTasks (they are stopped, then the session goes).
|
|
91
95
|
async function plainDelete(id, sess) {
|
|
92
96
|
if (!confirm(deleteConfirmText(sess))) return;
|
|
93
97
|
try {
|
|
94
98
|
await api.deleteSession(id);
|
|
95
99
|
} catch (e) {
|
|
96
|
-
|
|
97
|
-
|
|
100
|
+
if (e.code === "tasks_running") { await deleteStoppingTasks(id, e.body?.tasks); return; }
|
|
101
|
+
deleteFailed(id, e);
|
|
98
102
|
return;
|
|
99
103
|
}
|
|
104
|
+
dropDeleted(id);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function deleteStoppingTasks(id, listing) {
|
|
108
|
+
if (!confirm(tasksConfirmText(id, listing, "delete"))) return;
|
|
109
|
+
toast(stoppingText(listing));
|
|
110
|
+
let result;
|
|
111
|
+
try {
|
|
112
|
+
result = await api.deleteSession(id, { stopTasks: true });
|
|
113
|
+
} catch (e) {
|
|
114
|
+
deleteFailed(id, e);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
dropDeleted(id);
|
|
118
|
+
toast(`Deleted ${id.slice(0, 8)}${tasksStoppedSuffix(result)}`);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function deleteFailed(id, e) {
|
|
122
|
+
alert(`Could not delete session ${id.slice(0, 8)}: ${e.message}`);
|
|
123
|
+
if (!eventsLive()) refresh();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function dropDeleted(id) {
|
|
100
127
|
setSessions(sessions().filter((s) => s.id !== id));
|
|
101
128
|
if (selected() === id) clearSelection();
|
|
102
129
|
}
|
|
103
130
|
|
|
131
|
+
// The toast while a delete or an archive stops the tasks (about 4 s at most).
|
|
132
|
+
function stoppingText(listing) {
|
|
133
|
+
const n = tasksCount(listing);
|
|
134
|
+
return `Stopping ${n} background task${n === 1 ? "" : "s"}…`;
|
|
135
|
+
}
|
|
136
|
+
|
|
104
137
|
// The open session no longer exists: back to the start page, saying why.
|
|
105
138
|
function leaveGoneSession(id, why) {
|
|
106
139
|
if (selected() !== id) return;
|
|
@@ -248,15 +281,20 @@ export function createSessionActions({
|
|
|
248
281
|
// and a batch share. The ids in the answer flip in the list at once. When
|
|
249
282
|
// the open session's worker was stopped (it, or a delegate of the archived
|
|
250
283
|
// one), its stream ending is a stop, not a lost worker.
|
|
284
|
+
// +stopTasks+: the archive stops the background tasks the tree started
|
|
285
|
+
// first (else a session whose tasks still run is refused: 409
|
|
286
|
+
// tasks_running; a batch passes nothing, and skips it with that reason).
|
|
251
287
|
// @return {ok: true, result} | {ok: false, error}
|
|
252
|
-
async function archiveOne(id, archive) {
|
|
288
|
+
async function archiveOne(id, archive, { stopTasks = false } = {}) {
|
|
253
289
|
// A live worker in the tree is stopped by the archive: the open
|
|
254
290
|
// session's stream ending then is a stop.
|
|
255
291
|
const open = selected();
|
|
256
292
|
const mine = archive && open && inTree(sessions(), id, open) ? open : null;
|
|
257
293
|
if (mine) stoppingId = mine;
|
|
258
294
|
try {
|
|
259
|
-
const result = archive
|
|
295
|
+
const result = archive
|
|
296
|
+
? await api.archiveSession(id, ...(stopTasks ? [{ stopTasks: true }] : []))
|
|
297
|
+
: await api.unarchiveSession(id);
|
|
260
298
|
markArchived(archive ? result.archived : result.unarchived, archive);
|
|
261
299
|
if (mine && mine === selected() && (result.stopped || []).includes(mine)) stoppedWorker(mine);
|
|
262
300
|
return { ok: true, result };
|
|
@@ -268,9 +306,20 @@ export function createSessionActions({
|
|
|
268
306
|
}
|
|
269
307
|
}
|
|
270
308
|
|
|
309
|
+
// No confirm, unless background tasks the tree started still run (409
|
|
310
|
+
// tasks_running): then the confirm names them, and OK archives again with
|
|
311
|
+
// stopTasks. Undo only unarchives: stopped tasks stay stopped.
|
|
271
312
|
async function setArchived(id, archive, { undo = true } = {}) {
|
|
272
313
|
const short = id.slice(0, 8);
|
|
273
|
-
|
|
314
|
+
let answer = await archiveOne(id, archive);
|
|
315
|
+
let suffix = "";
|
|
316
|
+
if (!answer.ok && archive && answer.error?.code === "tasks_running") {
|
|
317
|
+
const listing = answer.error.body?.tasks;
|
|
318
|
+
if (!confirm(tasksConfirmText(id, listing, "archive"))) return;
|
|
319
|
+
toast(stoppingText(listing));
|
|
320
|
+
answer = await archiveOne(id, true, { stopTasks: true });
|
|
321
|
+
if (answer.ok) suffix = tasksStoppedSuffix(answer.result);
|
|
322
|
+
}
|
|
274
323
|
if (!answer.ok) {
|
|
275
324
|
alert(`Could not ${archive ? "archive" : "unarchive"} session ${short}: ${answer.error.message}`);
|
|
276
325
|
return;
|
|
@@ -278,7 +327,7 @@ export function createSessionActions({
|
|
|
278
327
|
// markArchived's list redrew the lists and the bar already.
|
|
279
328
|
if (!eventsLive()) refresh();
|
|
280
329
|
const what = archive ? "Archived" : "Unarchived";
|
|
281
|
-
toast(`${what} ${short}`, undo ? { label: "Undo", run: () => setArchived(id, !archive, { undo: false }) } : null);
|
|
330
|
+
toast(`${what} ${short}${suffix}`, undo ? { label: "Undo", run: () => setArchived(id, !archive, { undo: false }) } : null);
|
|
282
331
|
}
|
|
283
332
|
|
|
284
333
|
// The info bar's Archive / Unarchive: the open session's, by its state.
|
|
@@ -16,9 +16,10 @@
|
|
|
16
16
|
|
|
17
17
|
import { html, nothing, render } from "./vendor/lit-html.js";
|
|
18
18
|
import { createChipPopover } from "./chip_popover.js";
|
|
19
|
+
import { cutCommand, NAMED_MAX } from "./running_tasks.js";
|
|
19
20
|
|
|
20
21
|
// At most this many of a kind named in the sheet; the rest are one "+N more".
|
|
21
|
-
export const MAX_NAMED =
|
|
22
|
+
export const MAX_NAMED = NAMED_MAX;
|
|
22
23
|
|
|
23
24
|
// The Stop button the sheet opens at.
|
|
24
25
|
export const STOP_ANCHOR = "#infoStopBtn";
|
|
@@ -35,7 +36,7 @@ const KIND_WORDS = {
|
|
|
35
36
|
function itemWords(item, kind) {
|
|
36
37
|
const label = String(item?.label ?? item?.id ?? "").trim();
|
|
37
38
|
const detail = String(item?.detail ?? "").trim();
|
|
38
|
-
const cut = label
|
|
39
|
+
const cut = cutCommand(label);
|
|
39
40
|
if (kind === "delegates") {
|
|
40
41
|
const id = String(item?.id ?? "").slice(0, 8);
|
|
41
42
|
return `${id} "${cut || "untitled"}"${detail ? ` ${detail}` : ""}`;
|
|
@@ -23,6 +23,8 @@
|
|
|
23
23
|
// until the next turn sends its note (the server's adds). Pins show only
|
|
24
24
|
// under a strategy with the forget layer (forgetOn).
|
|
25
25
|
|
|
26
|
+
import { ITEM_STATES, serverIndex, serverItem } from "./ws_item_sig.js";
|
|
27
|
+
|
|
26
28
|
export const FLASH_MS = 4000;
|
|
27
29
|
// Labels per form: the rail's four lines, the row's and the footprint's
|
|
28
30
|
// three, the collapsed head's newest one.
|
|
@@ -197,34 +199,7 @@ export function sessionItems({ turns = [], live = [], preloaded = [], notes = []
|
|
|
197
199
|
|
|
198
200
|
// ── the server's truth ────────────────────────────────────────────────────
|
|
199
201
|
|
|
200
|
-
export const STATES =
|
|
201
|
-
const ELLIPSIS = "\u2026";
|
|
202
|
-
|
|
203
|
-
// The server's items by "kind:key", and its URLs (a cut row key matches one
|
|
204
|
-
// by prefix).
|
|
205
|
-
function serverIndex(server) {
|
|
206
|
-
const byKey = new Map();
|
|
207
|
-
const urls = [];
|
|
208
|
-
for (const it of server?.items || []) {
|
|
209
|
-
if (!it || !STATES.includes(it.state)) continue;
|
|
210
|
-
byKey.set(`${it.kind}:${it.key}`, it);
|
|
211
|
-
if (it.kind === "url") urls.push(it);
|
|
212
|
-
}
|
|
213
|
-
return { byKey, urls };
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
// The server's item for +item+: files by absolute path (a title fallback
|
|
217
|
-
// won't match), memories by name, URLs by the row's key (its params
|
|
218
|
-
// preview: cut at 80 characters with a "…", whose head must start the
|
|
219
|
-
// server's URL). null when the server doesn't know it (a running call).
|
|
220
|
-
function serverItem(index, item) {
|
|
221
|
-
const exact = index.byKey.get(`${item.kind}:${item.key}`);
|
|
222
|
-
if (exact || item.kind !== "url") return exact || null;
|
|
223
|
-
const key = String(item.key);
|
|
224
|
-
if (!key.endsWith(ELLIPSIS)) return null;
|
|
225
|
-
const head = key.slice(0, -1);
|
|
226
|
-
return index.urls.find((it) => String(it.key).startsWith(head)) || null;
|
|
227
|
-
}
|
|
202
|
+
export const STATES = ITEM_STATES;
|
|
228
203
|
|
|
229
204
|
// +items+ with the server's state, tokens, pinned, hasDrop (its
|
|
230
205
|
// has_drop: some output holds the user's drop) and a memory's scope (the
|
|
@@ -52,6 +52,7 @@ import {
|
|
|
52
52
|
labelTitle, lensItem, newerSnapshot, opsText, overlay, parseSteerLine, pendingSteers, pinnable, refreshable, serverAddIds, sessionItems, STEER_OPS,
|
|
53
53
|
steerId, steerLine, stepRange, stepTag, tokensText, turnLens, undroppable,
|
|
54
54
|
} from "./working_set.js";
|
|
55
|
+
import { serverSig } from "./ws_item_sig.js";
|
|
55
56
|
|
|
56
57
|
// The popover's files fold to this many lines (groups open in place, one at
|
|
57
58
|
// a time), its memories past this many to one group.
|
|
@@ -626,8 +627,8 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
|
|
|
626
627
|
changed();
|
|
627
628
|
refreshFootprints();
|
|
628
629
|
for (const fn of listeners) fn();
|
|
629
|
-
// An open peek asks again on an event (a GET answers the open itself)
|
|
630
|
-
//
|
|
630
|
+
// An open peek asks again on an event (a GET answers the open itself),
|
|
631
|
+
// when its item's server signature changed (ws_peek.js refresh).
|
|
631
632
|
if (how?.event && popover.isOpen()) peek?.refresh();
|
|
632
633
|
}
|
|
633
634
|
|
|
@@ -765,6 +766,8 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
|
|
|
765
766
|
jump,
|
|
766
767
|
// The session's set as the list shows it (overlaid), for the reader.
|
|
767
768
|
items: () => sessionSet().items,
|
|
769
|
+
// +item+'s server signature (working_set.js serverSig), for the peek and the reader.
|
|
770
|
+
serverSig: (item) => serverSig(server, item),
|
|
768
771
|
// The list opened at the session bar's chip (the reader's ‹ Set).
|
|
769
772
|
openList() {
|
|
770
773
|
const chip = infoEl.querySelector(".ws-chip");
|