samagotchi 0.182.0 → 0.183.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 +68 -1
- data/bin/chi +3 -1
- data/docs/architecture.md +16 -6
- data/docs/bundle-authoring.md +1 -1
- data/docs/bundles.md +103 -4
- data/docs/cli.md +28 -6
- data/docs/configuration.md +2 -1
- data/docs/guardrails.md +16 -1
- data/docs/internals/block-renderers.md +58 -3
- data/docs/internals/bridge.md +13 -5
- data/docs/internals/bundles.md +21 -4
- data/docs/internals/engine.md +18 -8
- data/docs/internals/remote-sessions.md +24 -5
- data/docs/internals/web-frontend.md +88 -28
- data/docs/internals/working-set.md +1 -1
- data/docs/mcp-server.md +80 -0
- data/docs/plugins.md +308 -21
- data/docs/sessions.md +3 -3
- data/docs/sub-agent.md +9 -0
- data/docs/testing.md +3 -1
- data/docs/thin-clients.md +146 -0
- data/lib/samagotchi/bridge/pending_card.rb +4 -3
- data/lib/samagotchi/bridge/sse_writer.rb +16 -15
- data/lib/samagotchi/bridge.rb +59 -68
- data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
- data/lib/samagotchi/bundle_command/check.rb +36 -19
- data/lib/samagotchi/bundle_command.rb +50 -21
- data/lib/samagotchi/bundle_manifest.rb +101 -4
- data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
- data/lib/samagotchi/bundles/mcp/client.rb +260 -0
- data/lib/samagotchi/bundles/mcp/content.rb +107 -0
- data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
- data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
- data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
- data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
- data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
- data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
- data/lib/samagotchi/bundles/system/manifest.yml +2 -2
- data/lib/samagotchi/cli/parent_wait.rb +5 -3
- data/lib/samagotchi/command_intake.rb +7 -0
- data/lib/samagotchi/commands/registry.rb +8 -3
- data/lib/samagotchi/continue_offer.rb +24 -15
- data/lib/samagotchi/engine/block_fix.rb +4 -4
- data/lib/samagotchi/engine/cards.rb +14 -5
- data/lib/samagotchi/engine/events.rb +10 -15
- data/lib/samagotchi/engine/models.rb +1 -1
- data/lib/samagotchi/engine/plugins.rb +3 -0
- data/lib/samagotchi/engine/recap.rb +1 -1
- data/lib/samagotchi/engine/side_requests.rb +1 -1
- data/lib/samagotchi/engine/sign_in.rb +142 -0
- data/lib/samagotchi/engine/turn_end.rb +3 -3
- data/lib/samagotchi/engine.rb +43 -27
- data/lib/samagotchi/engine_snapshots.rb +1 -1
- data/lib/samagotchi/guardrail_wiring.rb +3 -1
- data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
- data/lib/samagotchi/guardrails/verdict.rb +3 -2
- data/lib/samagotchi/hold_stop.rb +4 -4
- data/lib/samagotchi/idle_recap.rb +19 -11
- data/lib/samagotchi/idle_reminders.rb +7 -5
- data/lib/samagotchi/idle_scheduler.rb +7 -10
- data/lib/samagotchi/installed_bundles/dir.rb +37 -0
- data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
- data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
- data/lib/samagotchi/installed_bundles/record.rb +3 -2
- data/lib/samagotchi/installed_bundles/standing.rb +3 -1
- data/lib/samagotchi/llm/http.rb +96 -5
- data/lib/samagotchi/mcp_command.rb +110 -0
- data/lib/samagotchi/mcp_server/http.rb +112 -0
- data/lib/samagotchi/mcp_server/protocol.rb +244 -0
- data/lib/samagotchi/mcp_server/stdio.rb +92 -0
- data/lib/samagotchi/mcp_server/text.rb +155 -0
- data/lib/samagotchi/mcp_server/tools.rb +245 -0
- data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
- data/lib/samagotchi/memory_bundle/builder.rb +20 -2
- data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
- data/lib/samagotchi/memory_bundle/installer.rb +16 -3
- data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
- data/lib/samagotchi/memory_bundle/shas.rb +6 -4
- data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
- data/lib/samagotchi/memory_bundle/status.rb +15 -6
- data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
- data/lib/samagotchi/plugin/api.rb +6 -1
- data/lib/samagotchi/plugin/card.rb +36 -11
- data/lib/samagotchi/plugin/context.rb +63 -6
- data/lib/samagotchi/plugin/http.rb +40 -15
- data/lib/samagotchi/plugin/http_errors.rb +15 -0
- data/lib/samagotchi/plugin/http_stream.rb +86 -0
- data/lib/samagotchi/plugin/http_transport.rb +58 -16
- data/lib/samagotchi/plugin/loader.rb +18 -11
- data/lib/samagotchi/plugin/secrets.rb +266 -0
- data/lib/samagotchi/plugin/sign_in.rb +392 -0
- data/lib/samagotchi/plugin/sse_reader.rb +103 -0
- data/lib/samagotchi/queued_command.rb +28 -4
- data/lib/samagotchi/recap_setup.rb +13 -4
- data/lib/samagotchi/ref.rb +3 -2
- data/lib/samagotchi/relay_verifier.rb +8 -7
- data/lib/samagotchi/relay_watcher.rb +4 -4
- data/lib/samagotchi/run_options.rb +2 -1
- data/lib/samagotchi/send_command.rb +54 -41
- data/lib/samagotchi/session_access/ask.rb +244 -0
- data/lib/samagotchi/session_access/contract.rb +5 -0
- data/lib/samagotchi/session_access/exchange/token.rb +101 -0
- data/lib/samagotchi/session_access/exchange.rb +173 -0
- data/lib/samagotchi/session_access/local.rb +25 -6
- data/lib/samagotchi/session_access/remote.rb +4 -1
- data/lib/samagotchi/session_command_catalog.rb +10 -0
- data/lib/samagotchi/session_commands.rb +17 -0
- data/lib/samagotchi/session_config.rb +4 -4
- data/lib/samagotchi/session_observer.rb +27 -0
- data/lib/samagotchi/steer_cut.rb +4 -3
- data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
- data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
- data/lib/samagotchi/testing/boundary.rb +4 -0
- data/lib/samagotchi/testing/bundle.rb +48 -2
- data/lib/samagotchi/testing/fake_http.rb +60 -15
- data/lib/samagotchi/testing/host.rb +4 -1
- data/lib/samagotchi/testing/recorder.rb +45 -5
- data/lib/samagotchi/tools/tool_index.rb +14 -3
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +8 -6
- data/lib/samagotchi/web/ask_routes.rb +292 -0
- data/lib/samagotchi/web/mcp_route.rb +88 -0
- data/lib/samagotchi/web/public/app.js +2 -3
- data/lib/samagotchi/web/public/block_frame.js +72 -11
- data/lib/samagotchi/web/public/block_host.js +44 -8
- data/lib/samagotchi/web/public/block_regions.js +126 -0
- data/lib/samagotchi/web/public/card.js +22 -9
- data/lib/samagotchi/web/public/card_actions.js +21 -0
- data/lib/samagotchi/web/public/card_kinds.js +1 -1
- data/lib/samagotchi/web/public/card_registry.js +3 -2
- data/lib/samagotchi/web/public/data.js +15 -12
- data/lib/samagotchi/web/public/delete_sheet.js +222 -162
- data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
- data/lib/samagotchi/web/public/format.js +3 -0
- data/lib/samagotchi/web/public/index.html +52 -7
- data/lib/samagotchi/web/public/more_sheet.js +6 -4
- data/lib/samagotchi/web/public/picture_regions.js +243 -0
- data/lib/samagotchi/web/public/picture_viewer.js +113 -12
- data/lib/samagotchi/web/public/refs.js +5 -3
- data/lib/samagotchi/web/public/region_hit.js +144 -0
- data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
- data/lib/samagotchi/web/public/running_tasks.js +6 -4
- data/lib/samagotchi/web/public/session_actions.js +105 -100
- data/lib/samagotchi/web/session_access_routes.rb +14 -11
- data/lib/samagotchi/web/session_control.rb +31 -9
- data/lib/samagotchi/web/session_create.rb +2 -2
- data/lib/samagotchi/worker/child_side.rb +3 -2
- data/lib/samagotchi/worker/command_queue.rb +13 -13
- data/lib/samagotchi/worker/leave.rb +3 -3
- data/lib/samagotchi/worker/scratch.rb +6 -6
- data/lib/samagotchi/worker/signal_grace.rb +6 -5
- data/lib/samagotchi/worker/startup.rb +3 -3
- data/lib/samagotchi/worker/wake_turns.rb +4 -4
- data/lib/samagotchi/worker.rb +32 -21
- data/lib/samagotchi/worker_exit_claim.rb +1 -1
- data/lib/samagotchi/worker_idle_exit.rb +18 -9
- data/lib/samagotchi/worker_inbound.rb +12 -7
- data/lib/samagotchi/worker_participant_gate.rb +9 -7
- data/lib/samagotchi/worker_task_wakes.rb +7 -5
- metadata +31 -1
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "../mcp_server/protocol"
|
|
4
|
+
require_relative "../mcp_server/http"
|
|
5
|
+
require_relative "../mcp_server/tools"
|
|
6
|
+
require_relative "../mcp_server/text"
|
|
7
|
+
require_relative "../session_inbox"
|
|
8
|
+
require_relative "ask_routes"
|
|
9
|
+
require_relative "request_body"
|
|
10
|
+
|
|
11
|
+
module Samagotchi
|
|
12
|
+
module Web
|
|
13
|
+
# POST /api/mcp: chi as an MCP server on chi web (McpServer::Http, one
|
|
14
|
+
# JSON answer a POST, each call within McpServer::Tools::SLICE), for an
|
|
15
|
+
# MCP host that speaks HTTP. Behind the gates every owner route has
|
|
16
|
+
# (the Host check, a foreign Origin's 403, the token: none on loopback
|
|
17
|
+
# without web.public_url, Bearer on the LAN or a public URL; a
|
|
18
|
+
# participant's token is refused), with chi web's own {error, detail}
|
|
19
|
+
# bodies there; a tokenless request's 401 adds WWW-Authenticate:
|
|
20
|
+
# Bearer, so a host says it needs a token rather than look for OAuth.
|
|
21
|
+
# GET 405 (no stream), DELETE 200 (a legacy host closing its session).
|
|
22
|
+
# Included in App through SessionAccessRoutes; its helpers
|
|
23
|
+
# (request_body, session_access, live_bridge_client, error_response)
|
|
24
|
+
# and ivars (@manager, @hub, @wait_poll_interval, @server_running)
|
|
25
|
+
# answer. See docs/mcp-server.md.
|
|
26
|
+
module McpRoute
|
|
27
|
+
# GET /api/info's feature: this chi web serves POST /api/mcp.
|
|
28
|
+
FEATURE = "mcp"
|
|
29
|
+
PATH = %r{\A/api/mcp\z}
|
|
30
|
+
# A POST's body cap: a chi_ask prompt at its 16 KiB limit, every byte
|
|
31
|
+
# JSON-escaped (a control character's \u0000 is 6 bytes), plus the
|
|
32
|
+
# envelope, so a host gets the tool's "the message is N bytes" over
|
|
33
|
+
# the limit, not chi web's 413.
|
|
34
|
+
BODY_LIMIT = (6 * SessionInbox::NOTE_MAX_BYTES) + (16 * 1024)
|
|
35
|
+
# App::ROUTES' rows for the path (all :owner).
|
|
36
|
+
ROUTES = [["POST", PATH, :handle_mcp, :owner], ["GET", PATH, :handle_mcp_get, :owner],
|
|
37
|
+
["DELETE", PATH, :handle_mcp_delete, :owner]].freeze
|
|
38
|
+
|
|
39
|
+
# The tools' backend on chi web: the ask's (its manager and Bridge),
|
|
40
|
+
# whose answer also closes the page's card once the worker took it,
|
|
41
|
+
# as POST …/answer does.
|
|
42
|
+
class McpAccess < AskRoutes::AskAccess
|
|
43
|
+
def initialize(access, hub:, **)
|
|
44
|
+
super(access, **)
|
|
45
|
+
@hub = hub
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def answer(id, question_id:, **)
|
|
49
|
+
reply = __getobj__.answer(id, question_id: question_id, **)
|
|
50
|
+
@hub&.resolve_question(id, question_id: question_id) if reply&.status == 200
|
|
51
|
+
reply
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
private
|
|
56
|
+
|
|
57
|
+
def handle_mcp(req)
|
|
58
|
+
body = request_body(req, BODY_LIMIT, what: "an MCP request")
|
|
59
|
+
McpServer::Http.new(mcp_protocol).call(req.env, body)
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
def handle_mcp_get(_req)
|
|
63
|
+
text = JSON.generate({ error: "method_not_allowed", detail: "POST an MCP request; this server opens no stream" })
|
|
64
|
+
[405, { "Content-Type" => "application/json", "Allow" => "POST, DELETE", "Content-Length" => text.bytesize.to_s }, [text]]
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# Nothing is kept for a legacy session id: nothing to end.
|
|
68
|
+
def handle_mcp_delete(_req) = [200, { "Content-Length" => "0" }, []]
|
|
69
|
+
|
|
70
|
+
def mcp_protocol
|
|
71
|
+
bridge = ->(sid) { live_bridge_client(sid, within: McpServer::Tools::CAP) }
|
|
72
|
+
access = McpAccess.new(session_access, hub: @hub, manager: @manager, bridge: bridge, poll_interval: @wait_poll_interval)
|
|
73
|
+
stopping = -> { !@server_running.call }
|
|
74
|
+
exchange = ->(backend) { SessionAccess::Exchange.new(backend, cancelled: stopping) }
|
|
75
|
+
tools = McpServer::Tools.new(access, exchange: exchange, cancelled: stopping)
|
|
76
|
+
McpServer::Protocol.new(tools: tools, instructions: McpServer::Text::INSTRUCTIONS)
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
# The /api/ 401 (App#unauthorized's), with WWW-Authenticate: Bearer
|
|
80
|
+
# on this path.
|
|
81
|
+
def api_unauthorized(req, detail)
|
|
82
|
+
status, headers, body = error_response(401, "unauthorized", detail)
|
|
83
|
+
headers = headers.merge("WWW-Authenticate" => "Bearer") if PATH.match?(req.path_info)
|
|
84
|
+
[status, headers, body]
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
end
|
|
@@ -68,7 +68,7 @@ import { parsePresets } from "./annotate_presets.js";
|
|
|
68
68
|
import { createAnnotateBar } from "./annotate_bar.js";
|
|
69
69
|
import { VERIFY_PRESET, VERIFY_UNAVAILABLE, verifyWorkerUnavailable, withVerify } from "./verify_preset.js";
|
|
70
70
|
import { actionLine, annotationActions, composerWithAction } from "./annotate_actions.js";
|
|
71
|
-
import {
|
|
71
|
+
import { wireDiagrams } from "./diagram_wiring.js";
|
|
72
72
|
import { wireBlockFix } from "./block_fix.js";
|
|
73
73
|
import { createWidgetDrawer } from "./inline_widgets.js";
|
|
74
74
|
import { copyText, installCopy } from "./copy.js";
|
|
@@ -1542,9 +1542,8 @@ turnRoots().forEach((root) => installCopy(root));
|
|
|
1542
1542
|
// chi-ui blocks (inline_widgets.js) are a core drawer, ahead of the bundles'
|
|
1543
1543
|
// renderers; a picks' Fill reply only fills the composer.
|
|
1544
1544
|
const widgets = createWidgetDrawer({ roots: turnRoots(), composerText: () => promptEl.value, fillComposer });
|
|
1545
|
-
|
|
1545
|
+
wireDiagrams({ roots: turnRoots(), sessionId: () => store.selected, drawers: [widgets], renderers: viewer.can("block_renderers"), pictures });
|
|
1546
1546
|
const blockFix = wireBlockFix({ viewer, roots: turnRoots(), store, getSession, composerText: () => promptEl.value, fillComposer, linkTextRefs: markdownPlace.linkTextRefs });
|
|
1547
|
-
window.matchMedia?.("(prefers-color-scheme: dark)").addEventListener?.("change", () => pictures.close()); // a redrawn diagram's old picture
|
|
1548
1547
|
// A steps block, a thinking block and the recap open and close by hand
|
|
1549
1548
|
// with their height animated (details_motion.js), in the history and on
|
|
1550
1549
|
// the stage.
|
|
@@ -9,19 +9,36 @@
|
|
|
9
9
|
// the frame's error event). The protocol, the handshake first:
|
|
10
10
|
//
|
|
11
11
|
// frame → loaded, page → code {files}, frame → ready | failed {message}
|
|
12
|
-
// page → render {id, source, theme}, frame → done {id, svg} | error {id, message}
|
|
12
|
+
// page → render {id, source, theme}, frame → done {id, svg, regions?} | error {id, message, bundle?}
|
|
13
13
|
//
|
|
14
|
+
// A renderer's render returns the SVG, or {svg, regions} when the page says it
|
|
15
|
+
// takes regions (chi.features.regions; an older chi's bootstrap refuses anything
|
|
16
|
+
// but a string, so a bundle checks). Regions are capped here and copied bounded,
|
|
17
|
+
// before any of them is cloned to the page (block_regions.js cleans them there). An object without a
|
|
18
|
+
// string svg is the bundle's bug, error {bundle: true}: not the model's, so no fix
|
|
19
|
+
// is asked (block_fix.js). No object at all (undefined, null, a number) is as an
|
|
20
|
+
// older chi took it: a failed render, the model's like a throw (so fixable): a
|
|
21
|
+
// renderer may return nothing for a source it can't draw. draw resolves {svg, regions} (regions raw, or null);
|
|
22
|
+
// render is its SVG.
|
|
14
23
|
// One render at a time. A timer can't fire while the renderer hangs (the frame
|
|
15
24
|
// shares the page's thread): block_host.js's mark is for that.
|
|
16
25
|
//
|
|
17
26
|
// A module of its own: static JS is cached at unversioned URLs.
|
|
18
27
|
|
|
28
|
+
import { MAX_REGIONS } from "./block_regions.js";
|
|
29
|
+
|
|
19
30
|
// Same words as the spike that tested them; the page's frame-src 'none' covers
|
|
20
31
|
// what this doesn't (navigation).
|
|
21
32
|
export const FRAME_CSP = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; form-action 'none'";
|
|
22
33
|
export const FRAME_TIMEOUT_MS = 15000;
|
|
23
34
|
// An SVG this size isn't a diagram anyone reads, and it would sit in the DOM.
|
|
24
35
|
export const MAX_SVG_CHARS = 8 * 1024 * 1024;
|
|
36
|
+
// The error a bundle's bug gets: its render returned an object without a string svg.
|
|
37
|
+
const NO_SVG = "the renderer returned no SVG";
|
|
38
|
+
// The frame's copy of a region keeps a string this long at most, and this many
|
|
39
|
+
// points (the page cuts to 80 / 120 characters and 16 points).
|
|
40
|
+
const FRAME_TEXT_CHARS = 200;
|
|
41
|
+
const FRAME_POINTS = 16;
|
|
25
42
|
|
|
26
43
|
// Runs in the frame, before any bundle code. CSP doesn't stop WebRTC, so its
|
|
27
44
|
// constructors go (a nested srcdoc frame gets a fresh one: the residual risk,
|
|
@@ -33,7 +50,7 @@ const BOOTSTRAP = `(() => {
|
|
|
33
50
|
const words = (e) => String((e && e.message) || e).split("\\n")[0].slice(0, 300);
|
|
34
51
|
let renderer = null;
|
|
35
52
|
let loadError = null;
|
|
36
|
-
window.chi = { defineRenderer(r) { renderer = r; } };
|
|
53
|
+
window.chi = { defineRenderer(r) { renderer = r; }, features: { regions: true } };
|
|
37
54
|
addEventListener("error", (e) => { loadError = loadError || words(e.message || e.error); });
|
|
38
55
|
async function load(files) {
|
|
39
56
|
for (const code of files) {
|
|
@@ -47,14 +64,54 @@ const BOOTSTRAP = `(() => {
|
|
|
47
64
|
try { await (renderer.init && renderer.init()); } catch (e) { return send({ type: "failed", message: words(e) }); }
|
|
48
65
|
send({ type: "ready" });
|
|
49
66
|
}
|
|
67
|
+
// Regions only as an array of at most ${MAX_REGIONS}, each posted as a bounded copy
|
|
68
|
+
// of its known keys (strings cut to ${FRAME_TEXT_CHARS}, a box of 4 and up to ${FRAME_POINTS} points):
|
|
69
|
+
// so nothing vast is ever cloned on the page's thread (600 one-megabyte labels
|
|
70
|
+
// crashed a Chromium tab), and nothing uncloneable. Else none. The page cleans
|
|
71
|
+
// the copy again (block_regions.js).
|
|
72
|
+
const cut = (v) => (typeof v === "string" ? v.slice(0, ${FRAME_TEXT_CHARS}) : "");
|
|
73
|
+
const num = (v) => (typeof v === "number" ? v : NaN);
|
|
74
|
+
function copyRegion(r) {
|
|
75
|
+
if (!r || typeof r !== "object") return null;
|
|
76
|
+
const c = { kind: cut(r.kind), id: cut(r.id), label: cut(r.label), from: cut(r.from), to: cut(r.to) };
|
|
77
|
+
const box = r.box;
|
|
78
|
+
if (Array.isArray(box) && box.length === 4) c.box = [num(box[0]), num(box[1]), num(box[2]), num(box[3])];
|
|
79
|
+
const points = r.points;
|
|
80
|
+
if (Array.isArray(points) && points.length <= ${FRAME_POINTS}) {
|
|
81
|
+
c.points = [];
|
|
82
|
+
for (let i = 0; i < points.length; i++) {
|
|
83
|
+
const p = points[i];
|
|
84
|
+
c.points.push(Array.isArray(p) && p.length === 2 ? [num(p[0]), num(p[1])] : null);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return c;
|
|
88
|
+
}
|
|
89
|
+
function regionsOf(out) {
|
|
90
|
+
try {
|
|
91
|
+
const r = out.regions;
|
|
92
|
+
if (!Array.isArray(r) || r.length > ${MAX_REGIONS}) return null;
|
|
93
|
+
const copy = [];
|
|
94
|
+
for (let i = 0; i < r.length; i++) copy.push(copyRegion(r[i]));
|
|
95
|
+
return copy;
|
|
96
|
+
} catch (_) { return null; }
|
|
97
|
+
}
|
|
50
98
|
async function render(m) {
|
|
99
|
+
let out;
|
|
51
100
|
try {
|
|
52
|
-
|
|
53
|
-
if (typeof svg !== "string") throw new Error("the renderer returned no SVG");
|
|
54
|
-
send({ type: "done", id: m.id, svg });
|
|
101
|
+
out = await renderer.render(m.source, m.theme);
|
|
55
102
|
} catch (e) {
|
|
56
|
-
send({ type: "error", id: m.id, message: words(e) });
|
|
103
|
+
return send({ type: "error", id: m.id, message: words(e) });
|
|
104
|
+
}
|
|
105
|
+
if (typeof out === "string") return send({ type: "done", id: m.id, svg: out });
|
|
106
|
+
if (!out || typeof out !== "object") return send({ type: "error", id: m.id, message: ${JSON.stringify(NO_SVG)} });
|
|
107
|
+
let svg;
|
|
108
|
+
try { svg = out.svg; } catch (_) { svg = null; }
|
|
109
|
+
if (typeof svg !== "string") return send({ type: "error", id: m.id, message: ${JSON.stringify(NO_SVG)}, bundle: true });
|
|
110
|
+
const regions = regionsOf(out);
|
|
111
|
+
if (regions) {
|
|
112
|
+
try { return send({ type: "done", id: m.id, svg, regions }); } catch (_) { /* uncloneable: sent without them */ }
|
|
57
113
|
}
|
|
114
|
+
send({ type: "done", id: m.id, svg });
|
|
58
115
|
}
|
|
59
116
|
addEventListener("message", (e) => {
|
|
60
117
|
if (e.source !== parent) return;
|
|
@@ -97,7 +154,8 @@ export class FrameError extends Error {
|
|
|
97
154
|
|
|
98
155
|
// @param files the renderer's file names, in load order
|
|
99
156
|
// @param fetchFile (file) => a promise of its text (block_host.js fetchRendererFile)
|
|
100
|
-
// @return {
|
|
157
|
+
// @return {draw(source, theme, {onStart}) → Promise<{svg, regions}> (regions raw: block_regions.js cleans them),
|
|
158
|
+
// render(...) → Promise<svg> (draw's SVG alone), drop(), dead()}
|
|
101
159
|
export function createBlockFrame({ files, fetchFile, doc = document, win = window, timeoutMs = FRAME_TIMEOUT_MS }) {
|
|
102
160
|
const iframe = doc.createElement("iframe");
|
|
103
161
|
iframe.setAttribute("sandbox", "allow-scripts");
|
|
@@ -147,9 +205,11 @@ export function createBlockFrame({ files, fetchFile, doc = document, win = windo
|
|
|
147
205
|
settle((w) => w.reject(new FrameError(String(m.message ?? "load failed"), { load: true })));
|
|
148
206
|
} else if (m.type === "done" && m.id === waiting.id) {
|
|
149
207
|
if (typeof m.svg !== "string" || m.svg.length > MAX_SVG_CHARS) settle((w) => w.reject(new FrameError("the renderer's SVG is too large or not text")));
|
|
150
|
-
else settle((w) => w.resolve(m.svg));
|
|
208
|
+
else settle((w) => w.resolve({ svg: m.svg, regions: m.regions ?? null }));
|
|
151
209
|
} else if (m.type === "error" && m.id === waiting.id) {
|
|
152
|
-
|
|
210
|
+
// A bundle's bug (its render's object had no svg) isn't the model's: no fix.
|
|
211
|
+
const renderer = m.bundle !== true;
|
|
212
|
+
settle((w) => w.reject(new FrameError(String(m.message ?? "render failed"), { renderer })));
|
|
153
213
|
}
|
|
154
214
|
}
|
|
155
215
|
|
|
@@ -184,7 +244,7 @@ export function createBlockFrame({ files, fetchFile, doc = document, win = windo
|
|
|
184
244
|
// One render at a time, whatever the last one came to.
|
|
185
245
|
let queue = ready.catch(() => {});
|
|
186
246
|
|
|
187
|
-
function
|
|
247
|
+
function draw(source, theme, { onStart = () => {} } = {}) {
|
|
188
248
|
const run = async () => {
|
|
189
249
|
await ready;
|
|
190
250
|
if (dead) throw new FrameError("the frame is gone", { dropped: true });
|
|
@@ -202,7 +262,8 @@ export function createBlockFrame({ files, fetchFile, doc = document, win = windo
|
|
|
202
262
|
|
|
203
263
|
return {
|
|
204
264
|
ready,
|
|
205
|
-
|
|
265
|
+
draw,
|
|
266
|
+
render: (source, theme, opts) => draw(source, theme, opts).then((r) => r.svg),
|
|
206
267
|
dead: () => dead,
|
|
207
268
|
drop: () => die(new FrameError("dropped", { dropped: true })),
|
|
208
269
|
};
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
|
|
14
14
|
import { html, render as litRender } from "./vendor/lit-html.js";
|
|
15
15
|
import { createBlockFrame, FRAME_TIMEOUT_MS } from "./block_frame.js";
|
|
16
|
+
import { cleanRegions } from "./block_regions.js";
|
|
16
17
|
import { DRAWN, figureOf, setSourceShown } from "./block_source.js";
|
|
17
18
|
import { createBlockWatch, failBlock, holdingView } from "./block_watch.js";
|
|
18
19
|
import { copyText } from "./copy.js";
|
|
@@ -155,6 +156,8 @@ export function createFrameDrawer({
|
|
|
155
156
|
// render has its blocks wait for that one, and each draws into whichever is connected.
|
|
156
157
|
const coming = new Map();
|
|
157
158
|
const retries = new WeakMap();
|
|
159
|
+
// The languages whose regions were cleaned away whole once: said once each.
|
|
160
|
+
const regionsDropped = new Set();
|
|
158
161
|
// What needsDraw checked, so draw draws that: pre => {lang, source, renderer}.
|
|
159
162
|
const checked = new WeakMap();
|
|
160
163
|
let list = null;
|
|
@@ -294,7 +297,12 @@ export function createFrameDrawer({
|
|
|
294
297
|
async function rendered(key, lang, source, renderer, now) {
|
|
295
298
|
const mark = markKey(lang, source);
|
|
296
299
|
try {
|
|
297
|
-
const
|
|
300
|
+
const frame = frameFor(lang, renderer);
|
|
301
|
+
const onStart = () => setMark(mark);
|
|
302
|
+
// draw: {svg, regions}; an older cached block_frame.js has render alone.
|
|
303
|
+
const out = frame.draw ? await frame.draw(source, now, { onStart }) : { svg: await frame.render(source, now, { onStart }) };
|
|
304
|
+
const svg = out.svg;
|
|
305
|
+
const regions = keptRegions(lang, out.regions);
|
|
298
306
|
const started = inFlight.get(mark);
|
|
299
307
|
const picture = pictureOf(svg, win);
|
|
300
308
|
const tooLarge = oversize(picture.width, picture.height);
|
|
@@ -305,7 +313,9 @@ export function createFrameDrawer({
|
|
|
305
313
|
if (tooLargeShown) throw new Error(tooLargeShown);
|
|
306
314
|
if (Date.now() - started > SLOW_RENDER_MS) inFlight.delete(mark);
|
|
307
315
|
else clearMark(mark);
|
|
308
|
-
const
|
|
316
|
+
const sized = picture.width ? picture : { ...picture, width: natural.width, height: natural.height };
|
|
317
|
+
// Only when there are some: a picture without regions has no such field.
|
|
318
|
+
const shown = regions ? { ...sized, regions } : sized;
|
|
309
319
|
remember(key, shown);
|
|
310
320
|
return shown;
|
|
311
321
|
} catch (e) {
|
|
@@ -316,6 +326,19 @@ export function createFrameDrawer({
|
|
|
316
326
|
}
|
|
317
327
|
}
|
|
318
328
|
|
|
329
|
+
// The renderer's regions, cleaned (block_regions.js), or null; a list cleaned
|
|
330
|
+
// away whole is said once per language, with its count and no model text.
|
|
331
|
+
function keptRegions(lang, raw) {
|
|
332
|
+
if (raw == null) return null;
|
|
333
|
+
const regions = cleanRegions(raw);
|
|
334
|
+
if (regions?.length) return regions;
|
|
335
|
+
if (!regions && !regionsDropped.has(lang)) {
|
|
336
|
+
regionsDropped.add(lang);
|
|
337
|
+
console.warn(`chi: the ${lang} renderer's regions were dropped (${Array.isArray(raw) ? raw.length : typeof raw} reported, over the caps or not a list)`);
|
|
338
|
+
}
|
|
339
|
+
return null;
|
|
340
|
+
}
|
|
341
|
+
|
|
319
342
|
// A claimed language has a renderer: the list is loaded by then.
|
|
320
343
|
function needsDraw(pre, figure) {
|
|
321
344
|
const lang = langOf(pre);
|
|
@@ -359,19 +382,32 @@ export function createFrameDrawer({
|
|
|
359
382
|
else failBlock(pre, lang, "its renderer keeps stopping");
|
|
360
383
|
}
|
|
361
384
|
|
|
385
|
+
// A figure's picture for the viewer: its <img>'s URL, size from the viewBox
|
|
386
|
+
// (showPicture's attributes) and alt, plus what else the cache holds for that
|
|
387
|
+
// URL (a data: URL reads back from img.src as it was set; a Revise clone has
|
|
388
|
+
// the same). An evicted entry, or a figure an older page drew: the picture alone.
|
|
389
|
+
// At most CACHE_SIZE compares, on a click only.
|
|
390
|
+
function pictureOfFigure(figure) {
|
|
391
|
+
const img = figure?.querySelector(".block-img");
|
|
392
|
+
if (!img) return null;
|
|
393
|
+
const size = (name) => Number(img.getAttribute(name)) || null;
|
|
394
|
+
const picture = { url: img.src, width: size("width"), height: size("height"), alt: img.alt };
|
|
395
|
+
const held = [...cache.values()].find((p) => p.url === picture.url);
|
|
396
|
+
for (const [key, value] of Object.entries(held || {})) if (!(key in picture)) picture[key] = value;
|
|
397
|
+
return picture;
|
|
398
|
+
}
|
|
399
|
+
|
|
362
400
|
for (const root of roots) {
|
|
363
401
|
root.addEventListener("mousedown", (e) => {
|
|
364
402
|
if (e.target.closest?.(".block-zoom")) e.preventDefault();
|
|
365
403
|
});
|
|
366
|
-
// Delegated, so a Revise clone's work too: the picture in the viewer,
|
|
367
|
-
//
|
|
404
|
+
// Delegated, so a Revise clone's work too: the picture in the viewer, the
|
|
405
|
+
// focus back on the button.
|
|
368
406
|
root.addEventListener("click", (e) => {
|
|
369
407
|
if (!openPicture || !e.target.closest?.(".block-zoom, .block-img")) return;
|
|
370
408
|
const figure = e.target.closest(`.${DRAWN}`);
|
|
371
|
-
const
|
|
372
|
-
if (
|
|
373
|
-
const size = (name) => Number(img.getAttribute(name)) || null;
|
|
374
|
-
openPicture({ url: img.src, width: size("width"), height: size("height"), alt: img.alt }, { opener: figure.querySelector(":scope > .block-zoom") });
|
|
409
|
+
const picture = pictureOfFigure(figure);
|
|
410
|
+
if (picture) openPicture(picture, { opener: figure.querySelector(":scope > .block-zoom") });
|
|
375
411
|
});
|
|
376
412
|
}
|
|
377
413
|
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// A drawn diagram's regions, cleaned: what a renderer reported beside its SVG
|
|
2
|
+
// (block_frame.js), made safe to keep. Pure: no DOM, `node --test`.
|
|
3
|
+
// docs/internals/block-renderers.md, Regions.
|
|
4
|
+
//
|
|
5
|
+
// A region: {kind, id, label, box?, points?, from?, to?}; boxes and points are
|
|
6
|
+
// fractions of the picture (0..1). The bundle is trusted, its input is
|
|
7
|
+
// model-written: so nothing here stringifies the raw data (structured clone keeps
|
|
8
|
+
// cycles and BigInt), only an own key of a known name is read, strings are only
|
|
9
|
+
// ever strings, and the result is new objects. Over the caps the list goes whole
|
|
10
|
+
// (null), never cut: a picture with half its nodes tappable lies.
|
|
11
|
+
//
|
|
12
|
+
// What the page may do with a region's text: textContent, an aria-label, and
|
|
13
|
+
// composer text. Never markup, a selector, a URL, a data-* value another module
|
|
14
|
+
// reads back, or a key into an object.
|
|
15
|
+
//
|
|
16
|
+
// A module of its own: its exports are new (docs/internals/web-frontend.md).
|
|
17
|
+
|
|
18
|
+
export const REGION_KINDS = new Set(["node", "group", "edge", "note"]);
|
|
19
|
+
export const MAX_REGIONS = 600;
|
|
20
|
+
// The budget over the cleaned fields: the kept strings' lengths, plus 12 per number.
|
|
21
|
+
export const MAX_REGION_BYTES = 128 * 1024;
|
|
22
|
+
const NUMBER_BYTES = 12;
|
|
23
|
+
const ID_CHARS = 80;
|
|
24
|
+
const LABEL_CHARS = 120;
|
|
25
|
+
const MIN_POINTS = 2;
|
|
26
|
+
const MAX_POINTS = 16;
|
|
27
|
+
|
|
28
|
+
const own = (obj, key) => (Object.hasOwn(obj, key) ? obj[key] : undefined);
|
|
29
|
+
|
|
30
|
+
function plainObject(v) {
|
|
31
|
+
if (v === null || typeof v !== "object" || Array.isArray(v)) return false;
|
|
32
|
+
const proto = Object.getPrototypeOf(v);
|
|
33
|
+
return proto === null || proto === Object.prototype || Object.getPrototypeOf(proto) === null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const clamp = (n) => Math.min(1, Math.max(0, n));
|
|
37
|
+
const finite = (n) => typeof n === "number" && Number.isFinite(n);
|
|
38
|
+
|
|
39
|
+
// One line of text, or "": controls and line separators a space, bidi and
|
|
40
|
+
// zero-width format characters and lone surrogates gone, whitespace runs one
|
|
41
|
+
// space, cut by code points (a cut never splits a pair: Ruby's JSON refuses a
|
|
42
|
+
// lone surrogate, and the text can reach a prompt). The raw string is sliced
|
|
43
|
+
// first, so a megabyte label costs what a short one does.
|
|
44
|
+
export function cleanText(raw, max) {
|
|
45
|
+
if (typeof raw !== "string") return "";
|
|
46
|
+
const text = raw.slice(0, max * 8)
|
|
47
|
+
.replace(/[\p{Cc}\p{Zl}\p{Zp}]/gu, " ")
|
|
48
|
+
.replace(/[\p{Cf}\p{Cs}]/gu, "")
|
|
49
|
+
.replace(/\s+/gu, " ")
|
|
50
|
+
.trim();
|
|
51
|
+
const points = Array.from(text);
|
|
52
|
+
return points.length > max ? points.slice(0, max).join("").trimEnd() : text;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// [x, y, w, h] clamped and cut to the picture, or null: no area, or not 4
|
|
56
|
+
// finite numbers.
|
|
57
|
+
function cleanBox(raw) {
|
|
58
|
+
if (!Array.isArray(raw) || raw.length !== 4 || !raw.every(finite)) return null;
|
|
59
|
+
const x = clamp(raw[0]);
|
|
60
|
+
const y = clamp(raw[1]);
|
|
61
|
+
const w = Math.min(clamp(raw[2]), 1 - x);
|
|
62
|
+
const h = Math.min(clamp(raw[3]), 1 - y);
|
|
63
|
+
return w > 0 && h > 0 ? [x, y, w, h] : null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function cleanPoints(raw) {
|
|
67
|
+
if (!Array.isArray(raw) || raw.length < MIN_POINTS || raw.length > MAX_POINTS) return null;
|
|
68
|
+
const out = [];
|
|
69
|
+
for (const p of raw) {
|
|
70
|
+
if (!Array.isArray(p) || p.length !== 2 || !finite(p[0]) || !finite(p[1])) return null;
|
|
71
|
+
out.push([clamp(p[0]), clamp(p[1])]);
|
|
72
|
+
}
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function cleanRegion(raw) {
|
|
77
|
+
if (!plainObject(raw)) return null;
|
|
78
|
+
const kind = own(raw, "kind");
|
|
79
|
+
if (typeof kind !== "string" || !REGION_KINDS.has(kind)) return null;
|
|
80
|
+
const region = { kind, id: cleanText(own(raw, "id"), ID_CHARS), label: cleanText(own(raw, "label"), LABEL_CHARS) };
|
|
81
|
+
const box = cleanBox(own(raw, "box"));
|
|
82
|
+
if (kind !== "edge") {
|
|
83
|
+
if (!box) return null;
|
|
84
|
+
region.box = box;
|
|
85
|
+
return region;
|
|
86
|
+
}
|
|
87
|
+
const points = cleanPoints(own(raw, "points"));
|
|
88
|
+
if (!points) return null;
|
|
89
|
+
region.points = points;
|
|
90
|
+
if (box) region.box = box;
|
|
91
|
+
region.from = cleanText(own(raw, "from"), ID_CHARS);
|
|
92
|
+
region.to = cleanText(own(raw, "to"), ID_CHARS);
|
|
93
|
+
return region;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Something the card and a button can call it by, from the diagram's own text: a
|
|
97
|
+
// node, note or group its label or id, an edge its label or both its ends. A
|
|
98
|
+
// nameless one is skipped: the page never makes up a name ("node 3" means
|
|
99
|
+
// nothing in the source, nor to the model in composer text).
|
|
100
|
+
function namedRegion(r) {
|
|
101
|
+
return r.kind === "edge" ? !!(r.label || (r.from && r.to)) : !!(r.label || r.id);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function weight(region) {
|
|
105
|
+
const texts = region.id.length + region.label.length + (region.from?.length ?? 0) + (region.to?.length ?? 0);
|
|
106
|
+
const numbers = (region.box ? 4 : 0) + (region.points ? region.points.length * 2 : 0);
|
|
107
|
+
return texts + numbers * NUMBER_BYTES;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// @param raw what the frame's done carried (any value)
|
|
111
|
+
// @return a new array of clean regions, or null: none sent, not an array, over
|
|
112
|
+
// MAX_REGIONS entries or past MAX_REGION_BYTES; entries that aren't regions, or
|
|
113
|
+
// are nameless (namedRegion), are skipped
|
|
114
|
+
export function cleanRegions(raw) {
|
|
115
|
+
if (!Array.isArray(raw) || raw.length > MAX_REGIONS) return null;
|
|
116
|
+
const out = [];
|
|
117
|
+
let budget = MAX_REGION_BYTES;
|
|
118
|
+
for (let i = 0; i < raw.length; i++) {
|
|
119
|
+
const region = cleanRegion(raw[i]);
|
|
120
|
+
if (!region || !namedRegion(region)) continue;
|
|
121
|
+
budget -= weight(region);
|
|
122
|
+
if (budget < 0) return null;
|
|
123
|
+
out.push(region);
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
// A plugin's card (docs/plugins.md, Cards): a title, a body and actions,
|
|
2
|
-
// each action a command line the session runs
|
|
3
|
-
//
|
|
4
|
-
//
|
|
2
|
+
// each action a command line the session runs or an address opened in a new
|
|
3
|
+
// tab (a url action, card_actions.js: it sends nothing to the session).
|
|
4
|
+
// app.js places and updates the element; this module draws it (lit-html
|
|
5
|
+
// templates) and says where it goes.
|
|
5
6
|
import { html, nothing, render } from "./vendor/lit-html.js";
|
|
6
7
|
import { unsafeHTML } from "./vendor/directives/unsafe-html.js";
|
|
7
8
|
import { recapPlace } from "./format.js";
|
|
9
|
+
import { cardActions, cardActionUrl } from "./card_actions.js";
|
|
8
10
|
|
|
9
11
|
// The card's class: a warn card wears the warning colour; a notice is a
|
|
10
12
|
// one-line row.
|
|
@@ -22,7 +24,7 @@ export const NOTICE_CHARS = 160;
|
|
|
22
24
|
// one that asks (actions) and one with more to read stay cards.
|
|
23
25
|
export function isNoticeCard(card) {
|
|
24
26
|
if (!card || card.level === "warn") return false;
|
|
25
|
-
if ((card
|
|
27
|
+
if (cardActions(card).length) return false;
|
|
26
28
|
const body = String(card.body ?? "").trim();
|
|
27
29
|
return !body.includes("\n") && body.length <= NOTICE_CHARS;
|
|
28
30
|
}
|
|
@@ -69,17 +71,28 @@ export function cardBodyTemplate(card) {
|
|
|
69
71
|
|
|
70
72
|
// The card: its head (title, the command that showed it after a reload,
|
|
71
73
|
// source), body and one button per action (the command as its tooltip and
|
|
72
|
-
// data
|
|
74
|
+
// data; a url action an anchor to a new tab, its host as the tooltip, with
|
|
75
|
+
// a line under the row naming each host the url actions open, so a label
|
|
76
|
+
// can't hide where it leads), then the line a failed action writes. The
|
|
77
|
+
// anchor is .card-link, never .card-action: what selects .card-action posts
|
|
78
|
+
// the command or counts the card as asking.
|
|
73
79
|
export function cardTemplate(card) {
|
|
74
80
|
const source = card.source ? html`<span class="card-source">${card.source}</span>` : nothing;
|
|
75
81
|
const label = card.label ? html`<span class="card-label">${card.label}</span>` : nothing;
|
|
76
82
|
const body = cardBodyTemplate(card);
|
|
77
|
-
const actions = (card
|
|
83
|
+
const actions = cardActions(card);
|
|
84
|
+
const hosts = [];
|
|
78
85
|
const buttons = actions.length
|
|
79
|
-
? html`<div class="card-actions">${actions.map((a) =>
|
|
80
|
-
html`<button type="button" class="card-action ghost" data-command=${a.command} title=${a.command}>${a.label || a.command}</button
|
|
86
|
+
? html`<div class="card-actions">${actions.map((a) => {
|
|
87
|
+
if (a.command) return html`<button type="button" class="card-action ghost" data-command=${a.command} title=${a.command}>${a.label || a.command}</button>`;
|
|
88
|
+
const url = cardActionUrl(a);
|
|
89
|
+
const host = new URL(url).host;
|
|
90
|
+
if (!hosts.includes(host)) hosts.push(host);
|
|
91
|
+
return html`<a class="card-link ghost" href=${url} target="_blank" rel="noopener noreferrer" title=${host}>${a.label}</a>`;
|
|
92
|
+
})}</div>`
|
|
81
93
|
: nothing;
|
|
82
|
-
|
|
94
|
+
const opens = hosts.length ? html`<div class="card-opens">opens ${hosts.join(", ")}</div>` : nothing;
|
|
95
|
+
return html`<div class="card-head"><span class="card-title">${card.title || ""}</span>${label}${source}</div>${body ? html`<div class="card-body">${body}</div>` : nothing}${buttons}${opens}<div class="card-error hidden"></div>`;
|
|
83
96
|
}
|
|
84
97
|
|
|
85
98
|
// A card element → the card it shows, as drawCard drew it.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// A card's actions as the page draws them (card.js): a command one, which
|
|
2
|
+
// the session runs, or a url one, an address opened in a new tab.
|
|
3
|
+
import { httpUrl } from "./refs.js";
|
|
4
|
+
|
|
5
|
+
// The longest address a card's url action opens: the server's
|
|
6
|
+
// Plugin::Card::MAX_URL (an authorize address can be long).
|
|
7
|
+
export const CARD_MAX_URL = 4096;
|
|
8
|
+
|
|
9
|
+
// A url action's address as the page opens it, else null: re-checked here,
|
|
10
|
+
// as a saved cards.json is seeded without the server's check and lit-html
|
|
11
|
+
// doesn't sanitize href. A url action needs its label (never the address).
|
|
12
|
+
export function cardActionUrl(action) {
|
|
13
|
+
if (!action || action.command || !String(action.label ?? "").trim()) return null;
|
|
14
|
+
return httpUrl(action.url, { max: CARD_MAX_URL });
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// The card's actions the page draws: a command one, or a url one whose
|
|
18
|
+
// address passes cardActionUrl.
|
|
19
|
+
export function cardActions(card) {
|
|
20
|
+
return (card?.actions || []).filter((a) => a && (a.command || cardActionUrl(a)));
|
|
21
|
+
}
|
|
@@ -33,7 +33,7 @@ export function continueWait() {
|
|
|
33
33
|
return { kind: "continue", approval: false, summary: "" };
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
-
// A plugin card's wait: a running turn's card with
|
|
36
|
+
// A plugin card's wait: a running turn's card with a command action asks (as
|
|
37
37
|
// check-in's), a warning stays in sight; null: it doesn't wait. The one rule
|
|
38
38
|
// cards_place.js upsertCard and turn_block.js drawnTurnNodes ask; the DOM
|
|
39
39
|
// readers (stage_cards.js, stage_waiting.js waitingKind, card.js
|
|
@@ -45,8 +45,9 @@ export const CARD_EVENTS = [
|
|
|
45
45
|
"continue_offered", "continue_resolved", "card",
|
|
46
46
|
];
|
|
47
47
|
|
|
48
|
-
// A card's actions as the entry keeps them: label and command
|
|
49
|
-
|
|
48
|
+
// A card's actions as the entry keeps them: label and command, or label
|
|
49
|
+
// and url for a url action.
|
|
50
|
+
const actionsOf = (card) => (Array.isArray(card?.actions) ? card.actions.filter(Boolean).map((a) => (a.url && !a.command ? { label: a.label ?? null, url: a.url } : { label: a.label ?? null, command: a.command ?? null })) : []);
|
|
50
51
|
|
|
51
52
|
export function createCardRegistry() {
|
|
52
53
|
const entries = new Map();
|
|
@@ -271,10 +271,11 @@ export function restartSession(id, opts = {}) {
|
|
|
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
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)
|
|
274
|
+
// (without it, a session whose tasks still run is refused: 409 tasks_running);
|
|
275
|
+
// with +tasks+ (the ids the sheet named) only those, and a refusal on another.
|
|
275
276
|
export function archiveSession(id, opts = {}) {
|
|
276
|
-
const { stopTasks, ...apiOpts } = opts;
|
|
277
|
-
const body = JSON.stringify(stopTasks ? { stop_tasks: true } : {});
|
|
277
|
+
const { stopTasks, tasks, ...apiOpts } = opts;
|
|
278
|
+
const body = JSON.stringify(stopTasks ? { stop_tasks: true, ...(Array.isArray(tasks) ? { tasks } : {}) } : {});
|
|
278
279
|
return api(`/api/sessions/${encodeURIComponent(id)}/archive`, { method: "POST", body, ...apiOpts });
|
|
279
280
|
}
|
|
280
281
|
|
|
@@ -285,30 +286,32 @@ export function unarchiveSession(id, opts = {}) {
|
|
|
285
286
|
|
|
286
287
|
// A delete's query after force=true: the plan digest the user confirmed
|
|
287
288
|
// (expect), and stop_tasks (stop the background tasks the deleted sessions
|
|
288
|
-
// started first; without it, 409 tasks_running while one runs)
|
|
289
|
-
|
|
289
|
+
// started first; without it, 409 tasks_running while one runs); +tasks+ (the
|
|
290
|
+
// ids the sheet named, "tasks=" for none) has the stop take only those.
|
|
291
|
+
function deleteQuery({ expect, stopTasks, tasks }) {
|
|
290
292
|
const plan = expect == null ? "" : `&expect=${encodeURIComponent(expect)}`;
|
|
291
|
-
|
|
293
|
+
const named = stopTasks && Array.isArray(tasks) ? `&tasks=${tasks.map(encodeURIComponent).join(",")}` : "";
|
|
294
|
+
return `${plan}${stopTasks ? "&stop_tasks=true" : ""}${named}`;
|
|
292
295
|
}
|
|
293
296
|
|
|
294
297
|
// Deletes the session for good; force=true has the server stop a live
|
|
295
298
|
// worker first (the page's confirm says so; without it, 409 worker_running).
|
|
296
299
|
export function deleteSession(id, opts = {}) {
|
|
297
|
-
const { expect, stopTasks, ...apiOpts } = opts;
|
|
298
|
-
return api(`/api/sessions/${encodeURIComponent(id)}?force=true${deleteQuery({ expect, stopTasks })}`,
|
|
300
|
+
const { expect, stopTasks, tasks, ...apiOpts } = opts;
|
|
301
|
+
return api(`/api/sessions/${encodeURIComponent(id)}?force=true${deleteQuery({ expect, stopTasks, tasks })}`,
|
|
299
302
|
{ method: "DELETE", ...apiOpts });
|
|
300
303
|
}
|
|
301
304
|
|
|
302
305
|
// Deletes every link of the session's chain with their delegates (running
|
|
303
306
|
// ones are left running); force: the links' workers are stopped first.
|
|
304
307
|
export function deleteChain(id, opts = {}) {
|
|
305
|
-
const { expect, stopTasks, ...apiOpts } = opts;
|
|
306
|
-
return api(`/api/sessions/${encodeURIComponent(id)}/chain?force=true${deleteQuery({ expect, stopTasks })}`,
|
|
308
|
+
const { expect, stopTasks, tasks, ...apiOpts } = opts;
|
|
309
|
+
return api(`/api/sessions/${encodeURIComponent(id)}/chain?force=true${deleteQuery({ expect, stopTasks, tasks })}`,
|
|
307
310
|
{ method: "DELETE", ...apiOpts });
|
|
308
311
|
}
|
|
309
312
|
|
|
310
|
-
// What deleting a
|
|
311
|
-
//
|
|
313
|
+
// What deleting a session would do, for the delete sheet (delete_sheet.js):
|
|
314
|
+
// the server's own plan and refusals, read now.
|
|
312
315
|
export function deletePlan(id, opts = {}) {
|
|
313
316
|
return api(`/api/sessions/${encodeURIComponent(id)}/delete_plan`, opts);
|
|
314
317
|
}
|