@tjakoen/grain 0.1.12
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.
- package/LICENSE +202 -0
- package/PLAN.md +27 -0
- package/README.md +243 -0
- package/ai/accepts.test.ts +69 -0
- package/ai/accepts.ts +57 -0
- package/ai/ai.css +127 -0
- package/ai/client-door.test.ts +70 -0
- package/ai/client-door.ts +56 -0
- package/ai/contract.test.ts +158 -0
- package/ai/contract.ts +285 -0
- package/ai/interaction-layer.test.ts +270 -0
- package/ai/interaction-layer.ts +138 -0
- package/ai/manifest-dom.test.ts +176 -0
- package/ai/manifest-dom.ts +187 -0
- package/ai/manifest.test.ts +71 -0
- package/ai/manifest.ts +57 -0
- package/ai/markdown.test.ts +68 -0
- package/ai/markdown.ts +74 -0
- package/ai/model-chat.test.ts +131 -0
- package/ai/model-chat.ts +151 -0
- package/ai/model-reasoner.test.ts +152 -0
- package/ai/model-reasoner.ts +146 -0
- package/ai/model.test.ts +148 -0
- package/ai/model.ts +200 -0
- package/ai/reasoner-kit.test.ts +142 -0
- package/ai/reasoner-kit.ts +159 -0
- package/ai/reasoner.test.ts +227 -0
- package/ai/reasoner.ts +446 -0
- package/ai/timeline-log.test.ts +55 -0
- package/ai/timeline-log.ts +50 -0
- package/ai/vocab-reference.test.ts +43 -0
- package/ai/vocab-reference.ts +107 -0
- package/ai/webllm.test.ts +79 -0
- package/ai/webllm.ts +125 -0
- package/assets/figure-sample.svg +14 -0
- package/assets/sprite.svg +22 -0
- package/catalog/catalog.test.ts +37 -0
- package/catalog/catalog.ts +424 -0
- package/components/atoms/action-badge/action-badge.css +17 -0
- package/components/atoms/action-badge/action-badge.html +6 -0
- package/components/atoms/action-badge/action-badge.md +23 -0
- package/components/atoms/b-badge/b-badge.css +15 -0
- package/components/atoms/b-badge/b-badge.html +2 -0
- package/components/atoms/b-badge/b-badge.md +16 -0
- package/components/atoms/b-button/b-button.ai.md +22 -0
- package/components/atoms/b-button/b-button.css +87 -0
- package/components/atoms/b-button/b-button.html +5 -0
- package/components/atoms/b-button/b-button.md +77 -0
- package/components/atoms/b-icon/b-icon.css +10 -0
- package/components/atoms/b-icon/b-icon.html +5 -0
- package/components/atoms/b-icon/b-icon.md +36 -0
- package/components/atoms/b-icon-button/b-icon-button.ai.md +11 -0
- package/components/atoms/b-icon-button/b-icon-button.css +43 -0
- package/components/atoms/b-icon-button/b-icon-button.html +8 -0
- package/components/atoms/b-icon-button/b-icon-button.md +33 -0
- package/components/atoms/b-input/b-input.css +36 -0
- package/components/atoms/b-input/b-input.html +8 -0
- package/components/atoms/b-input/b-input.md +59 -0
- package/components/atoms/b-kbd/b-kbd.css +11 -0
- package/components/atoms/b-kbd/b-kbd.html +3 -0
- package/components/atoms/b-kbd/b-kbd.md +13 -0
- package/components/atoms/b-list/b-list.css +21 -0
- package/components/atoms/b-list/b-list.html +6 -0
- package/components/atoms/b-list/b-list.md +24 -0
- package/components/atoms/b-meter/b-meter.css +39 -0
- package/components/atoms/b-meter/b-meter.md +44 -0
- package/components/atoms/b-select/b-select.css +35 -0
- package/components/atoms/b-select/b-select.md +75 -0
- package/components/atoms/b-switch/b-switch.css +61 -0
- package/components/atoms/b-switch/b-switch.html +6 -0
- package/components/atoms/b-switch/b-switch.md +40 -0
- package/components/atoms/b-text/b-text.ai.md +29 -0
- package/components/atoms/b-text/b-text.css +2 -0
- package/components/atoms/b-text/b-text.html +3 -0
- package/components/atoms/b-text/b-text.md +23 -0
- package/components/atoms/code-block/code-block.css +42 -0
- package/components/atoms/code-block/code-block.md +23 -0
- package/components/examples.test.ts +23 -0
- package/components/molecules/callout/callout.css +19 -0
- package/components/molecules/callout/callout.md +15 -0
- package/components/molecules/card/card.css +28 -0
- package/components/molecules/card/card.md +30 -0
- package/components/molecules/chat-message/chat-message.css +83 -0
- package/components/molecules/chat-message/chat-message.md +52 -0
- package/components/molecules/chip-group/chip-group.css +35 -0
- package/components/molecules/chip-group/chip-group.md +42 -0
- package/components/molecules/content-index/content-index.css +87 -0
- package/components/molecules/content-index/content-index.md +27 -0
- package/components/molecules/content-source/content-source.css +6 -0
- package/components/molecules/content-source/content-source.md +13 -0
- package/components/molecules/figure/figure.css +19 -0
- package/components/molecules/figure/figure.md +20 -0
- package/components/molecules/lede/lede.css +17 -0
- package/components/molecules/lede/lede.md +17 -0
- package/components/molecules/made-with/made-with.css +25 -0
- package/components/molecules/made-with/made-with.md +35 -0
- package/components/molecules/nav-item/nav-item.css +19 -0
- package/components/molecules/nav-item/nav-item.md +21 -0
- package/components/molecules/stat-tile/stat-tile.css +34 -0
- package/components/molecules/stat-tile/stat-tile.md +50 -0
- package/components/molecules/status-list/status-list.css +47 -0
- package/components/molecules/status-list/status-list.md +62 -0
- package/components/molecules/tab/tab.css +32 -0
- package/components/molecules/tab/tab.md +27 -0
- package/components/molecules/table/table.css +23 -0
- package/components/molecules/table/table.md +18 -0
- package/components/organisms/activity-bar/activity-bar.css +36 -0
- package/components/organisms/activity-bar/activity-bar.md +43 -0
- package/components/organisms/app-shell/app-shell.css +193 -0
- package/components/organisms/app-shell/app-shell.md +58 -0
- package/components/organisms/app-shell/app-shell.test.ts +74 -0
- package/components/organisms/app-window/app-window.css +111 -0
- package/components/organisms/app-window/app-window.md +53 -0
- package/components/organisms/chat-log/chat-log.css +5 -0
- package/components/organisms/chat-log/chat-log.md +14 -0
- package/components/organisms/code-editor/code-editor.ai.md +31 -0
- package/components/organisms/code-editor/code-editor.css +111 -0
- package/components/organisms/code-editor/code-editor.md +122 -0
- package/components/organisms/console/console.css +112 -0
- package/components/organisms/console/console.md +66 -0
- package/components/organisms/file-tree/file-tree.css +85 -0
- package/components/organisms/file-tree/file-tree.md +49 -0
- package/components/organisms/note/note.css +19 -0
- package/components/organisms/note/note.md +20 -0
- package/components/organisms/notepad/notepad.css +60 -0
- package/components/organisms/notepad/notepad.md +40 -0
- package/components/organisms/side-rail/side-rail.css +55 -0
- package/components/organisms/side-rail/side-rail.md +24 -0
- package/components/organisms/sidebar-panel/sidebar-panel.css +69 -0
- package/components/organisms/sidebar-panel/sidebar-panel.md +47 -0
- package/components/organisms/status-bar/status-bar.css +33 -0
- package/components/organisms/status-bar/status-bar.md +28 -0
- package/components/organisms/tab-bar/tab-bar.css +48 -0
- package/components/organisms/tab-bar/tab-bar.md +26 -0
- package/components/organisms/timeline/timeline.css +51 -0
- package/components/organisms/timeline/timeline.md +42 -0
- package/components/organisms/topbar/topbar.css +8 -0
- package/components/organisms/topbar/topbar.md +26 -0
- package/components/responsive-polish.test.ts +43 -0
- package/components/tokens.test.ts +39 -0
- package/fonts/redaction-35-400.woff2 +0 -0
- package/fonts/redaction-400.woff2 +0 -0
- package/fonts/redaction-50-400.woff2 +0 -0
- package/fonts/redaction-70-400.woff2 +0 -0
- package/package.json +46 -0
- package/scripts/ai-dispatch.js +583 -0
- package/scripts/ai-dispatch.test.ts +85 -0
- package/scripts/ai-spotlight.d.ts +23 -0
- package/scripts/ai-spotlight.js +139 -0
- package/scripts/ai-spotlight.test.ts +31 -0
- package/scripts/catalog-peek.js +156 -0
- package/scripts/catalog-peek.test.ts +31 -0
- package/scripts/cmdk.js +159 -0
- package/scripts/demo-box.js +53 -0
- package/scripts/handoff.js +64 -0
- package/scripts/handoff.test.ts +36 -0
- package/scripts/lightbox.js +144 -0
- package/scripts/lightbox.test.ts +23 -0
- package/scripts/made-with.d.ts +2 -0
- package/scripts/made-with.js +22 -0
- package/scripts/made-with.test.ts +25 -0
- package/scripts/notepad.js +100 -0
- package/scripts/shell.js +204 -0
- package/scripts/shell.test.ts +50 -0
- package/scripts/tabs.js +127 -0
- package/scripts/tabs.test.ts +40 -0
- package/scripts/terminal.js +271 -0
- package/scripts/terminal.test.ts +36 -0
- package/scripts/theme-boot.js +15 -0
- package/scripts/theme.js +87 -0
- package/scripts/type-effect.js +25 -0
- package/scripts/xray.js +79 -0
- package/scripts/xray.test.ts +43 -0
- package/styles/cmdk.css +65 -0
- package/styles/global.css +80 -0
- package/styles/grain.css +47 -0
- package/styles/lightbox.css +78 -0
- package/styles/themes/_template.css +48 -0
- package/styles/themes/baguette.css +30 -0
- package/styles/themes/brioche.css +30 -0
- package/styles/variables.css +217 -0
|
@@ -0,0 +1,583 @@
|
|
|
1
|
+
// /frontend/scripts/ai-dispatch.js — the dispatcher island (docs/AI-INTERFACE.md §3).
|
|
2
|
+
//
|
|
3
|
+
// The ONE accepted bit of client JS. Two jobs:
|
|
4
|
+
// 1. Turn [data-action] interactions (click, or Enter in an input) into POST /intent
|
|
5
|
+
// (the one door), applying the optimistic "pending" (grain) state on the target.
|
|
6
|
+
// 2. Open an SSE stream and apply RenderOps the server PUSHES, addressed by the
|
|
7
|
+
// semantic surface (data-surface) — never by tag or CSS class.
|
|
8
|
+
// It knows render ops + the door; nothing about specific verbs.
|
|
9
|
+
//
|
|
10
|
+
// The "AI is acting" spotlight (backdrop / label / lit surface / click pulse) is GRAIN's shared
|
|
11
|
+
// primitive — grain/scripts/ai-spotlight.js. This dispatcher keeps the product ORCHESTRATION around
|
|
12
|
+
// it (surface-address resolution, per-kind AI-mode, scroll-into-view, the pending-trigger lifecycle,
|
|
13
|
+
// the app-shell takeover, the 20s safety timeout, and the mediated interrupt) and delegates only the
|
|
14
|
+
// raw DOM to createSpotlight — so the demo and the dispatcher light the page the same way.
|
|
15
|
+
import { createSpotlight } from "/scripts/ai-spotlight.js";
|
|
16
|
+
|
|
17
|
+
(() => {
|
|
18
|
+
"use strict";
|
|
19
|
+
|
|
20
|
+
// A stable session id for this tab; the server pushes results back on it.
|
|
21
|
+
const session =
|
|
22
|
+
(crypto && crypto.randomUUID && crypto.randomUUID()) ||
|
|
23
|
+
"s-" + Math.random().toString(36).slice(2) + performance.now();
|
|
24
|
+
|
|
25
|
+
const screen = document.body.dataset.screen || "";
|
|
26
|
+
|
|
27
|
+
// ---- find an element by its semantic surface address -------------------------
|
|
28
|
+
const find = (surface) =>
|
|
29
|
+
document.querySelector(`[data-surface="${(window.CSS && CSS.escape) ? CSS.escape(surface) : surface}"]`);
|
|
30
|
+
|
|
31
|
+
// The surface a trigger acts on: explicit data-target, else the nearest surface.
|
|
32
|
+
function targetOf(trigger) {
|
|
33
|
+
const explicit = trigger.getAttribute("data-target");
|
|
34
|
+
if (explicit) return explicit;
|
|
35
|
+
const host = trigger.closest("[data-surface]");
|
|
36
|
+
return host ? host.getAttribute("data-surface") : null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const ACTING_LABEL = "✶ the AI is acting…";
|
|
40
|
+
|
|
41
|
+
// ---- navigate: same-origin, root-relative hrefs only ---------------------------
|
|
42
|
+
// Mirrors ai/contract.ts's `isSafeNavigateHref` EXACTLY (same regex, same reasons — see that
|
|
43
|
+
// file's comment). Duplicated here on purpose: this script is grain's "ONE accepted bit of
|
|
44
|
+
// client JS" (file header) and stays self-contained, no cross-module import of ai/*.ts into the
|
|
45
|
+
// browser. ai-dispatch.test.ts drift-guards this literal against contract.ts's so the two can't
|
|
46
|
+
// silently diverge (CLAUDE.md lesson #5) — the dispatcher is the LAST line of defense before an
|
|
47
|
+
// actual browser navigation, so it re-checks even though the reasoner already validated.
|
|
48
|
+
const SAFE_NAV_HREF = /^\/(?!\/)[^\s\\]*$/;
|
|
49
|
+
|
|
50
|
+
// ---- fill: a field.set value's guard — mirrors ai/contract.ts's isSafeFieldValue EXACTLY -------
|
|
51
|
+
// Same intentional self-contained copy as SAFE_NAV_HREF above (this file imports no ai/*.ts);
|
|
52
|
+
// ai-dispatch.test.ts drift-guards the cap + the control-char regex against contract.ts's. The
|
|
53
|
+
// dispatcher is the LAST line of defense before a value lands in a real form field, so it
|
|
54
|
+
// re-checks even though the reasoner already validated.
|
|
55
|
+
const FIELD_VALUE_CAP = 2000;
|
|
56
|
+
const FIELD_VALUE_BAD_CHARS = /[\x00-\x08\x0b\x0c\x0e-\x1f]/;
|
|
57
|
+
const SAFE_FIELD_VALUE = (v) => typeof v === "string" && v.length <= FIELD_VALUE_CAP && !FIELD_VALUE_BAD_CHARS.test(v);
|
|
58
|
+
// A `navigate` op tears the page down — irreversible, so give any in-flight settle (the
|
|
59
|
+
// spotlight's glide off, a caret's last frame) a beat to read before that happens, instead of a
|
|
60
|
+
// bare synchronous location.assign mid-render. Named per CLAUDE.md lesson #9 (a magic number
|
|
61
|
+
// with no name can't be tuned) — a consumer wanting a snappier or gentler hand-off tunes this.
|
|
62
|
+
const NAVIGATE_SETTLE_MS = 220;
|
|
63
|
+
|
|
64
|
+
// ---- settle-time sanitizing markdown (mirrors ai/markdown.ts's renderMarkdown) -------------
|
|
65
|
+
// Streaming stays textContent (safe by construction — see applyType). Once a message SETTLES,
|
|
66
|
+
// re-render its accumulated plain text through this SMALL allowlist renderer so **bold**,
|
|
67
|
+
// `code`, and links read as formatting. Escapes every character FIRST, then builds ONLY the
|
|
68
|
+
// allowlisted tags around the escaped text, so raw <script>/HTML in the source is always inert —
|
|
69
|
+
// the only markup that can appear in the output is markup this function wrote. No innerHTML is
|
|
70
|
+
// ever set from unsanitized text. Kept an intentional, drift-guarded copy of ai/markdown.ts (see
|
|
71
|
+
// that file's header) for the same self-contained reason as SAFE_NAV_HREF above.
|
|
72
|
+
const mdEsc = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
73
|
+
const MD_CODE_RE = /`([^`]+)`/g;
|
|
74
|
+
const MD_LINK_RE = /\[([^\]]+)\]\(([^)]+)\)/g;
|
|
75
|
+
const MD_STRONG_RE = /\*\*([^*]+)\*\*/g;
|
|
76
|
+
const MD_EM_RE = /(?:\*([^*]+)\*|_([^_]+)_)/g;
|
|
77
|
+
const MD_LIST_ITEM_RE = /^[-*]\s+/;
|
|
78
|
+
const MD_BLOCK_SPLIT_RE = /\n{2,}/;
|
|
79
|
+
// Placeholder delimiter for pulled-out code spans (below) — \x00 can't occur in real chat text.
|
|
80
|
+
const MD_CODE_PLACEHOLDER_RE = /\x00(\d+)\x00/g;
|
|
81
|
+
function mdInline(escaped) {
|
|
82
|
+
// Code spans are pulled OUT first (placeholdered), so their literal contents can never be
|
|
83
|
+
// re-interpreted by strong/em/links below — spliced back in verbatim at the end.
|
|
84
|
+
const codeSpans = [];
|
|
85
|
+
let out = escaped.replace(MD_CODE_RE, (_m, code) => {
|
|
86
|
+
codeSpans.push(`<code>${code}</code>`);
|
|
87
|
+
return `\x00${codeSpans.length - 1}\x00`;
|
|
88
|
+
});
|
|
89
|
+
out = out.replace(MD_LINK_RE, (_m, text, href) => (SAFE_NAV_HREF.test(href) ? `<a href="${href}">${text}</a>` : text));
|
|
90
|
+
out = out.replace(MD_STRONG_RE, (_m, t) => `<strong>${t}</strong>`);
|
|
91
|
+
out = out.replace(MD_EM_RE, (_m, a, b) => `<em>${a ?? b}</em>`);
|
|
92
|
+
out = out.replace(MD_CODE_PLACEHOLDER_RE, (_m, i) => codeSpans[Number(i)]);
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
function renderMarkdown(text) {
|
|
96
|
+
const blocks = text.split(MD_BLOCK_SPLIT_RE);
|
|
97
|
+
const out = [];
|
|
98
|
+
for (const block of blocks) {
|
|
99
|
+
const lines = block.split("\n").filter((l) => l.length > 0);
|
|
100
|
+
if (!lines.length) continue;
|
|
101
|
+
if (lines.every((l) => MD_LIST_ITEM_RE.test(l))) {
|
|
102
|
+
const items = lines.map((l) => `<li>${mdInline(mdEsc(l.replace(MD_LIST_ITEM_RE, "")))}</li>`).join("");
|
|
103
|
+
out.push(`<ul>${items}</ul>`);
|
|
104
|
+
} else {
|
|
105
|
+
out.push(`<p>${lines.map((l) => mdInline(mdEsc(l))).join("<br>")}</p>`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return out.join("");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ---- "the AI is acting": spotlight the surface the AI is touching --------------
|
|
112
|
+
// The backdrop/label/lit/pulse DOM is grain's shared createSpotlight; the orchestration below is
|
|
113
|
+
// this dispatcher's. clicking the veil → interrupt (ask, don't force-kill).
|
|
114
|
+
const spotlight = createSpotlight({ onInterrupt: interrupt });
|
|
115
|
+
let confirmEl = null;
|
|
116
|
+
let spotlit = null, spotlightTimer = null;
|
|
117
|
+
const isActing = () => spotlight.isOn();
|
|
118
|
+
|
|
119
|
+
// release a surface from the spotlight. A control the AI is "using" keeps its
|
|
120
|
+
// working state (data-commit) until its OUTPUT completes — held in pendingTriggers,
|
|
121
|
+
// released by clearTrigger on the output's committed op — so it isn't dropped here.
|
|
122
|
+
const savedPlaceholder = new WeakMap(); // restore a field's placeholder after AI typing
|
|
123
|
+
function clearActing(el) {
|
|
124
|
+
if (!el) return;
|
|
125
|
+
el.classList.remove("ai-spotlit", "is-click");
|
|
126
|
+
if (el.tagName === "INPUT" || el.tagName === "TEXTAREA") {
|
|
127
|
+
if (savedPlaceholder.has(el)) { el.placeholder = savedPlaceholder.get(el); savedPlaceholder.delete(el); }
|
|
128
|
+
// drop only the forced-clean "smooth" spotlightOn set — a `fill` op's "grain" (AI ink on a
|
|
129
|
+
// prefilled field) must SURVIVE the spotlight release, settling only on trusted human input.
|
|
130
|
+
if (el.getAttribute("data-grade") === "smooth") el.removeAttribute("data-grade");
|
|
131
|
+
el.blur();
|
|
132
|
+
}
|
|
133
|
+
const held = [...pendingTriggers.values()].includes(el);
|
|
134
|
+
if (!held) el.removeAttribute("data-commit");
|
|
135
|
+
}
|
|
136
|
+
function spotlightOn(target, click) {
|
|
137
|
+
spotlight.on(ACTING_LABEL); // grain's backdrop + label
|
|
138
|
+
// shell takeover (if the page uses the app-shell): the chat retracts + the console narrates
|
|
139
|
+
document.querySelector(".app-shell")?.setAttribute("data-acting", "true");
|
|
140
|
+
const el = find(target);
|
|
141
|
+
if (spotlit && spotlit !== el) clearActing(spotlit); // moving on → release the previous surface
|
|
142
|
+
if (el) {
|
|
143
|
+
spotlight.move(el, { click }); // the lamp glides onto it (pulse only on a real click)
|
|
144
|
+
// Keep the lit surface comfortably in view WITHIN the scroll region — below the top bar and
|
|
145
|
+
// above the docked terminal (separate grid rows, so scrolling main can't hide behind them).
|
|
146
|
+
// Land it about a THIRD of the way down — between the top and the centre — so the AI's focus
|
|
147
|
+
// sits in reading space, not jammed under the top bar (owner 2026-07-17). A surface TALLER than
|
|
148
|
+
// the viewport still top-aligns so it reads top-down. Scroll only when it isn't already fully
|
|
149
|
+
// visible (a needless scroll cuts the lamp's glide short).
|
|
150
|
+
const main = el.closest(".app-shell__main");
|
|
151
|
+
const region = main ? main.getBoundingClientRect() : { top: 0, bottom: innerHeight, height: innerHeight };
|
|
152
|
+
const r = el.getBoundingClientRect();
|
|
153
|
+
const tallerThanView = r.height > region.height - 8;
|
|
154
|
+
if (r.top < region.top + 4 || r.bottom > region.bottom - 4 || tallerThanView) {
|
|
155
|
+
if (tallerThanView) {
|
|
156
|
+
el.scrollIntoView({ block: "start" }); // tall surface: top-align, readable top-down
|
|
157
|
+
} else {
|
|
158
|
+
const lead = region.height * 0.3; // ~a third down = halfway between top and centre
|
|
159
|
+
(main || document.scrollingElement || document.documentElement)
|
|
160
|
+
.scrollBy({ top: (r.top - region.top) - lead }); // smoothness owned by CSS scroll-behavior
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
// each KIND of surface reads AI-mode its own way:
|
|
164
|
+
const tag = el.tagName, out = el.getAttribute("data-target");
|
|
165
|
+
if (tag === "INPUT" || tag === "TEXTAREA") {
|
|
166
|
+
// the AI composes like a human: clean ink from the first frame (no grain→smooth
|
|
167
|
+
// flash), no grey placeholder ghost, the field's own caret.
|
|
168
|
+
el.setAttribute("data-grade", "smooth");
|
|
169
|
+
if (el.placeholder) { savedPlaceholder.set(el, el.placeholder); el.placeholder = ""; }
|
|
170
|
+
el.focus();
|
|
171
|
+
} else if (el.hasAttribute("data-action") && out) {
|
|
172
|
+
clearTrigger(out); // drop any stale holder of this target first
|
|
173
|
+
el.setAttribute("data-commit", "pending"); // a control being USED → working until its output finishes…
|
|
174
|
+
pendingTriggers.set(out, el); // …held, then released by the output's committed op
|
|
175
|
+
armWatchdog(); // bound its lifetime (dropped-op safety)
|
|
176
|
+
} else if (target !== "screen") {
|
|
177
|
+
el.setAttribute("data-commit", "pending"); // a text region the AI writes in → grain
|
|
178
|
+
}
|
|
179
|
+
spotlit = el;
|
|
180
|
+
}
|
|
181
|
+
clearTimeout(spotlightTimer);
|
|
182
|
+
spotlightTimer = setTimeout(spotlightOff, 20000); // safety: never stay stuck
|
|
183
|
+
}
|
|
184
|
+
function spotlightOff() {
|
|
185
|
+
clearTimeout(spotlightTimer);
|
|
186
|
+
hideConfirm();
|
|
187
|
+
spotlight.off(); // drop grain's backdrop + label
|
|
188
|
+
const sh = document.querySelector(".app-shell");
|
|
189
|
+
if (sh) { sh.removeAttribute("data-acting"); sh.removeAttribute("data-chat-open"); sh.removeAttribute("data-console-open"); } // hand back: everything resets
|
|
190
|
+
clearActing(spotlit); spotlit = null;
|
|
191
|
+
for (const t of [...pendingTriggers.keys()]) clearTrigger(t); // backstop: turn over → nothing stays "working"
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// ---- interrupt: pause, ask, and (if confirmed) ask the AI to stop --------------
|
|
195
|
+
// We never abort the AI's write from the client — the user expresses "stop" and the
|
|
196
|
+
// single writer halts itself gracefully (AI-INTERFACE §5c / PROJECT-PLAN §9).
|
|
197
|
+
function interrupt() {
|
|
198
|
+
if (!isActing()) return; // ask; the AI keeps working behind the modal
|
|
199
|
+
showConfirm();
|
|
200
|
+
}
|
|
201
|
+
function ensureConfirm() {
|
|
202
|
+
if (confirmEl) return;
|
|
203
|
+
// a native modal <dialog>: focus-trap, Escape-to-close, ::backdrop, and top-layer
|
|
204
|
+
// come free — no manual overlay/keydown plumbing. Escape = "let it finish" (the
|
|
205
|
+
// AI keeps working behind it), which is the safe default.
|
|
206
|
+
confirmEl = document.createElement("dialog");
|
|
207
|
+
confirmEl.className = "ai-confirm";
|
|
208
|
+
confirmEl.innerHTML =
|
|
209
|
+
'<div class="ai-confirm__card">' +
|
|
210
|
+
'<p class="ai-confirm__msg">The AI is working. Ask it to stop?</p>' +
|
|
211
|
+
'<div class="ai-confirm__actions">' +
|
|
212
|
+
'<button class="btn" data-confirm="resume">Let it finish</button>' +
|
|
213
|
+
'<button class="btn" data-confirm="stop">Ask it to stop</button>' +
|
|
214
|
+
'</div>' +
|
|
215
|
+
'</div>';
|
|
216
|
+
confirmEl.addEventListener("click", (e) => {
|
|
217
|
+
const b = e.target.closest("[data-confirm]");
|
|
218
|
+
if (!b) return;
|
|
219
|
+
if (b.dataset.confirm === "resume") resume();
|
|
220
|
+
else requestStop();
|
|
221
|
+
});
|
|
222
|
+
document.body.appendChild(confirmEl);
|
|
223
|
+
}
|
|
224
|
+
function showConfirm() { ensureConfirm(); if (!confirmEl.open) confirmEl.showModal(); }
|
|
225
|
+
function hideConfirm() { if (confirmEl && confirmEl.open) confirmEl.close(); }
|
|
226
|
+
function resume() { hideConfirm(); } // "let it finish" — it never actually stopped
|
|
227
|
+
function requestStop() { // ask the AI to stop (mediated, graceful)
|
|
228
|
+
hideConfirm();
|
|
229
|
+
sendIntent({ source: "user", session, screen, surface: "screen", action: "desk.stop", payload: {} })
|
|
230
|
+
.catch(() => spotlightOff()); // if we can't even ask, release locally
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// triggers (buttons/inputs) held in their own grain state until their action commits
|
|
234
|
+
const pendingTriggers = new Map(); // target surface → the element that fired it
|
|
235
|
+
|
|
236
|
+
function clearTrigger(target) {
|
|
237
|
+
const trg = pendingTriggers.get(target);
|
|
238
|
+
if (trg) { trg.removeAttribute("data-commit"); pendingTriggers.delete(target); }
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// ---- pending-trigger WATCHDOG: every pending trigger has a BOUNDED lifetime -----------------
|
|
242
|
+
// The 20s spotlight timer only arms once spotlightOn runs — but if the `spotlight` op itself is
|
|
243
|
+
// DROPPED (SSE has no replay; AI-INTERFACE §3), the trigger goes pending in submit() and nothing
|
|
244
|
+
// ever releases it. This watchdog is independent of the spotlight path: it (re)arms whenever a
|
|
245
|
+
// trigger is pending and is REFRESHED on every received op (ops flowing = channel alive), so it
|
|
246
|
+
// never trips during a healthy multi-second run — only on genuine silence (dropped ops / a hung
|
|
247
|
+
// request). On fire: release every pending trigger, surface the failure on it (the existing flash
|
|
248
|
+
// affordance — data-state="error" + title, no new toast system), and go honestly offline.
|
|
249
|
+
const WATCHDOG_MS = 15000;
|
|
250
|
+
let watchdogTimer = null;
|
|
251
|
+
function armWatchdog() { // call after a trigger goes pending, and on each op
|
|
252
|
+
clearTimeout(watchdogTimer); watchdogTimer = null;
|
|
253
|
+
if (pendingTriggers.size) watchdogTimer = setTimeout(watchdogFire, WATCHDOG_MS);
|
|
254
|
+
}
|
|
255
|
+
function watchdogFire() {
|
|
256
|
+
for (const [target, trg] of [...pendingTriggers.entries()]) {
|
|
257
|
+
trg.removeAttribute("data-state"); void trg.offsetWidth; // restart the flash
|
|
258
|
+
trg.setAttribute("data-state", "error");
|
|
259
|
+
trg.setAttribute("title", "The AI didn't respond — released.");
|
|
260
|
+
clearTrigger(target);
|
|
261
|
+
}
|
|
262
|
+
markOnline(false); // the channel is evidently down → honest presence
|
|
263
|
+
spotlightOff(); // drop any veil + reset the shell
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// ---- apply one render op -----------------------------------------------------
|
|
267
|
+
// Every received op REFRESHES the watchdog (channel is alive) — done in the wrapper AFTER the op
|
|
268
|
+
// is applied, so an op that clears the last pending trigger correctly stands the watchdog down.
|
|
269
|
+
function applyOp(op) { applyOneOp(op); armWatchdog(); }
|
|
270
|
+
function applyOneOp(op) {
|
|
271
|
+
const el = find(op.target);
|
|
272
|
+
// a committed op (or a flash/rollback) ends the interaction → release its trigger
|
|
273
|
+
if (op.commit === "committed" || op.op === "flash") clearTrigger(op.target);
|
|
274
|
+
switch (op.op) {
|
|
275
|
+
case "remove":
|
|
276
|
+
if (el) el.remove();
|
|
277
|
+
return;
|
|
278
|
+
case "replace":
|
|
279
|
+
if (el && typeof op.html === "string") el.outerHTML = op.html; // confirmed (clean) fragment
|
|
280
|
+
return;
|
|
281
|
+
case "append":
|
|
282
|
+
case "choices": // an AI bubble with pick-one buttons — rendered like any append (the kit prebuilt op.html); the buttons are normal chat.send triggers
|
|
283
|
+
if (el && typeof op.html === "string") {
|
|
284
|
+
el.insertAdjacentHTML("beforeend", op.html);
|
|
285
|
+
const oy = getComputedStyle(el).overflowY; // a scrolling log (chat / terminal) stays pinned to newest
|
|
286
|
+
if (oy === "auto" || oy === "scroll") el.scrollTo({ top: el.scrollHeight }); // honors CSS scroll-behavior (gentle)
|
|
287
|
+
}
|
|
288
|
+
return;
|
|
289
|
+
case "flash":
|
|
290
|
+
if (!el) return;
|
|
291
|
+
el.removeAttribute("data-commit"); // clear optimistic grain → rollback
|
|
292
|
+
el.removeAttribute("data-state");
|
|
293
|
+
void el.offsetWidth; // restart the animation
|
|
294
|
+
el.setAttribute("data-state", "error"); // transient UI state (CONVENTIONS: data-state)
|
|
295
|
+
if (op.message) el.setAttribute("title", op.message);
|
|
296
|
+
return;
|
|
297
|
+
case "type": // streamed AI text (grain → settles clean)
|
|
298
|
+
if (!el) return;
|
|
299
|
+
applyType(el, op);
|
|
300
|
+
return;
|
|
301
|
+
case "spotlight": // the AI as actor: dim + light the target
|
|
302
|
+
op.active ? spotlightOn(op.target, op.click) : spotlightOff();
|
|
303
|
+
return;
|
|
304
|
+
case "navigate": // AI-directed browser navigation (contract.ts's `navigate` op)
|
|
305
|
+
if (typeof op.href !== "string" || !SAFE_NAV_HREF.test(op.href)) {
|
|
306
|
+
console.error("[ai-dispatch] rejected navigate op with an unsafe href", op.href);
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
// through the normal op/settle flow, not a bare synchronous assign mid-render: let the
|
|
310
|
+
// op's own "committed" handling above (clearTrigger) and any spotlight release the
|
|
311
|
+
// reasoner already emitted read first, THEN leave the page.
|
|
312
|
+
setTimeout(() => { location.assign(op.href); }, NAVIGATE_SETTLE_MS);
|
|
313
|
+
return;
|
|
314
|
+
case "fill": // AI prefills a form field; value PERSISTS for human review (never a submit)
|
|
315
|
+
// `"value" in el` keeps the op inert on a non-field element even if a page mislabels a
|
|
316
|
+
// surface. No focus steal, no submit, no form access — el.value and nothing else.
|
|
317
|
+
if (el && ("value" in el) && typeof op.text === "string" && SAFE_FIELD_VALUE(op.text)) {
|
|
318
|
+
el.value = op.text;
|
|
319
|
+
el.setAttribute("data-grade", "grain"); // AI ink until the human touches it (trusted-input settle below)
|
|
320
|
+
el.dispatchEvent(new Event("input", { bubbles: true })); // page validation/counters stay honest
|
|
321
|
+
}
|
|
322
|
+
return;
|
|
323
|
+
case "log": // one entry into the interaction TIMELINE (§5g)
|
|
324
|
+
if (el && typeof op.html === "string") {
|
|
325
|
+
el.insertAdjacentHTML("beforeend", op.html);
|
|
326
|
+
while (el.children.length > 80) el.removeChild(el.firstElementChild); // cap the DOM — a log, not a leak
|
|
327
|
+
const oy = getComputedStyle(el).overflowY;
|
|
328
|
+
if (oy === "auto" || oy === "scroll") el.scrollTo({ top: el.scrollHeight }); // pin to newest
|
|
329
|
+
}
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// Stream a token into a target: lazily build a grain text body + blinking caret,
|
|
335
|
+
// append tokens as they arrive. On `done` the caret goes and it's marked committed,
|
|
336
|
+
// but it STAYS grain — this is AI speech, and grain = AI (provenance persists).
|
|
337
|
+
function applyType(el, op) {
|
|
338
|
+
// the AI composing in a real form field: drive .value (no caret/stream-body),
|
|
339
|
+
// and clear on `done` — exactly what pressing Enter does for a human.
|
|
340
|
+
if (el.tagName === "INPUT" || el.tagName === "TEXTAREA") {
|
|
341
|
+
if (typeof op.text === "string") {
|
|
342
|
+
if (document.activeElement !== el) el.focus(); // human-like: focused → clean ink + real caret
|
|
343
|
+
el.value += op.text;
|
|
344
|
+
}
|
|
345
|
+
if (op.done) { el.value = ""; el.blur(); } // "submit" clears the field, like Enter
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
let body = el.querySelector(".stream-body");
|
|
349
|
+
if (!body) {
|
|
350
|
+
const prev = el.textContent || ""; // capture current text before we rebuild
|
|
351
|
+
el.innerHTML = '<span class="stream-body"></span><span class="caret"></span>';
|
|
352
|
+
el.setAttribute("data-grade", "grain"); // AI / in-transit = grain (DESIGN-SYSTEM §3)
|
|
353
|
+
el.setAttribute("data-commit", "pending");
|
|
354
|
+
body = el.querySelector(".stream-body");
|
|
355
|
+
// OVERWRITE (op.back) re-enters an already-written surface → keep its text so the
|
|
356
|
+
// the AI can backspace it. A fresh write (text, no back) starts empty (wipes any placeholder).
|
|
357
|
+
if (typeof op.back === "number") body.textContent = prev;
|
|
358
|
+
}
|
|
359
|
+
if (typeof op.back === "number" && op.back > 0) // the AI revising: delete trailing chars
|
|
360
|
+
body.textContent = [...body.textContent].slice(0, -op.back).join("");
|
|
361
|
+
else if (typeof op.text === "string") body.textContent += op.text; // text only — no injection
|
|
362
|
+
if (op.done) {
|
|
363
|
+
const caret = el.querySelector(".caret");
|
|
364
|
+
if (caret) caret.remove();
|
|
365
|
+
// Re-render the ACCUMULATED plain text through the sanitizing markdown renderer above —
|
|
366
|
+
// never innerHTML from the raw stream. renderMarkdown only ever emits its own allowlisted
|
|
367
|
+
// tags around escaped text, so this is safe even though body.textContent is untrusted
|
|
368
|
+
// (AI-composed, and AI-composed text may itself echo user input).
|
|
369
|
+
body.innerHTML = renderMarkdown(body.textContent);
|
|
370
|
+
el.setAttribute("data-commit", "committed"); // finished — but grade stays grain (it's AI)
|
|
371
|
+
el.classList.add("settled"); // subtle fade-in; grade unchanged
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// ---- the reply channel: server door (SSE) or client door (loopback, §19.3) ----
|
|
376
|
+
// `sendIntent(intent)` is the ONE wire out; which transport backs it is the page's choice
|
|
377
|
+
// (<body data-ai-transport="client"> — set by a composition root / the static export).
|
|
378
|
+
// Server transport: POST /intent + SSE push. Ops are pushed to a SUBSCRIBED session only — SSE
|
|
379
|
+
// has NO replay. So an Intent must not be sent before this stream's subscriber is registered
|
|
380
|
+
// SERVER-SIDE, or the first RenderOps are lost: typically the `spotlight` op that makes the page
|
|
381
|
+
// "acting". Then the demo appears to do nothing AND can't be interrupted (isActing() stays false,
|
|
382
|
+
// so clicks/Escape never raise the "stop?" prompt). The native `open` event is NOT enough — it
|
|
383
|
+
// fires on response headers, which can precede the server registering the subscriber. We wait for
|
|
384
|
+
// the server's `ready` handshake (emitted from inside the stream's start(), after registration).
|
|
385
|
+
// Contract: AI-INTERFACE §3 — the door's reply channel must be LIVE before an intent is raised.
|
|
386
|
+
// Client transport: the same door composed IN the page (static hosts have no backend); its
|
|
387
|
+
// loopback channel hands ops straight to applyOp, so the reply channel is live by construction.
|
|
388
|
+
const clientMode = document.body.dataset.aiTransport === "client";
|
|
389
|
+
// HONEST presence: <body data-ai-online="true|false"> reflects whether the door's reply
|
|
390
|
+
// channel actually came up (server `ready` handshake / client door loaded). Consumers style
|
|
391
|
+
// their presence indicator + degraded mode off this — it is set by outcome, never assumed.
|
|
392
|
+
const markOnline = (ok) => { document.body.dataset.aiOnline = ok ? "true" : "false"; };
|
|
393
|
+
let sseIsOpen = false, markSseReady;
|
|
394
|
+
const sseReady = new Promise((res) => { markSseReady = res; });
|
|
395
|
+
let sendIntent; // (intent) => Promise — set per transport
|
|
396
|
+
if (clientMode) {
|
|
397
|
+
// Which door module? A page may bring its OWN (data-ai-door — e.g. a consumer's scripted
|
|
398
|
+
// scenario module exporting createClientDoor); default is grain's. Resolved against this
|
|
399
|
+
// script's own URL so it works unchanged on a subpath host (no base-path rewrite needed).
|
|
400
|
+
const assetBase = new URL("..", import.meta.url).pathname.replace(/\/$/, "");
|
|
401
|
+
const doorPath = document.body.dataset.aiDoor || "/modules/grain/ai/client-door.js";
|
|
402
|
+
const doorReady = import(assetBase + doorPath)
|
|
403
|
+
.then((m) => { const door = m.createClientDoor(applyOp); markOnline(true); return door; })
|
|
404
|
+
.catch((err) => { console.error("[ai-dispatch] client door failed to load", err); markOnline(false); return null; });
|
|
405
|
+
sendIntent = (intent) => doorReady.then((door) => {
|
|
406
|
+
if (!door) throw new Error("client door unavailable");
|
|
407
|
+
return door.handleIntent(intent);
|
|
408
|
+
});
|
|
409
|
+
sseIsOpen = true; markSseReady(); // loopback: nothing to wait for
|
|
410
|
+
} else {
|
|
411
|
+
const es = new EventSource(`/stream?session=${encodeURIComponent(session)}`);
|
|
412
|
+
let offlineTimer = null;
|
|
413
|
+
// NOT { once: true }: EventSource auto-reconnects after a drop, and the server re-emits `ready`
|
|
414
|
+
// from the fresh stream's start() — so a re-fired `ready` flips presence back ONLINE and cancels
|
|
415
|
+
// any pending offline. (Presence = transport health, set by outcome on every up/down transition.)
|
|
416
|
+
es.addEventListener("ready", () => { sseIsOpen = true; clearTimeout(offlineTimer); offlineTimer = null; markOnline(true); markSseReady(); });
|
|
417
|
+
// SSE `error`. Two SEPARATE concerns, deliberately handled differently:
|
|
418
|
+
// (1) A LIVE run: SSE has no replay, so ops sent during the drop are lost and the run can't
|
|
419
|
+
// recover — release it NOW so it never hangs (mirrors the pre-debounce safety). Releasing
|
|
420
|
+
// the veil does NOT gate future clicks, so it's safe to do on any blip. Only when a run is
|
|
421
|
+
// actually live (guarded) — otherwise a benign nav-teardown error would reset persisted
|
|
422
|
+
// chrome (e.g. the terminal open-state).
|
|
423
|
+
// (2) PRESENCE/gating: the browser AUTO-RECONNECTS, so a transient blip is NOT "the door is
|
|
424
|
+
// down" — flipping offline instantly would spuriously gate a click made during the blip
|
|
425
|
+
// (and `submit()` no-ops offline). DEBOUNCE it: go offline only if still down after the
|
|
426
|
+
// reconnect grace; a re-fired `ready` cancels the timer. Presence stays "true" through a blip.
|
|
427
|
+
es.onerror = () => {
|
|
428
|
+
sseIsOpen = false;
|
|
429
|
+
if (isActing() || pendingTriggers.size) spotlightOff(); // (1) release a live run immediately
|
|
430
|
+
if (offlineTimer) return; // (2) grace already ticking
|
|
431
|
+
offlineTimer = setTimeout(() => {
|
|
432
|
+
offlineTimer = null;
|
|
433
|
+
if (sseIsOpen) return; // reconnected in the meantime (`ready` re-fired)
|
|
434
|
+
console.warn("[ai-dispatch] /stream down past reconnect grace — going offline");
|
|
435
|
+
markOnline(false);
|
|
436
|
+
markSseReady(); // unblock any waiter (degraded, like the 3s fallback)
|
|
437
|
+
}, 4000);
|
|
438
|
+
};
|
|
439
|
+
// Degraded-mode fallback: never hang a click if the handshake never lands. This DOES re-open
|
|
440
|
+
// the early-op-drop window (AI-INTERFACE §3 wants the channel live first) — deliberately, and
|
|
441
|
+
// loudly: a submit that goes out un-acked means the stream is broken and ops may be lost.
|
|
442
|
+
setTimeout(() => {
|
|
443
|
+
if (!sseIsOpen) {
|
|
444
|
+
console.warn("[ai-dispatch] no `ready` handshake after 3s — submitting anyway; early RenderOps may be dropped (broken /stream?)");
|
|
445
|
+
markOnline(false);
|
|
446
|
+
}
|
|
447
|
+
markSseReady();
|
|
448
|
+
}, 3000);
|
|
449
|
+
es.addEventListener("op", (e) => {
|
|
450
|
+
try { applyOp(JSON.parse(e.data)); } catch (err) { console.error("[ai-dispatch] bad op", err); }
|
|
451
|
+
});
|
|
452
|
+
sendIntent = (intent) => {
|
|
453
|
+
// Bounded request: a hung POST /intent would pin the trigger forever (no ops come back). Abort
|
|
454
|
+
// after 10s → the fetch rejects → submit()'s .catch releases the trigger + marks offline.
|
|
455
|
+
const ctl = new AbortController();
|
|
456
|
+
const to = setTimeout(() => ctl.abort(), 10000);
|
|
457
|
+
return fetch("/intent", {
|
|
458
|
+
method: "POST",
|
|
459
|
+
headers: { "Content-Type": "application/json" },
|
|
460
|
+
body: JSON.stringify(intent),
|
|
461
|
+
signal: ctl.signal,
|
|
462
|
+
}).then((res) => {
|
|
463
|
+
// fetch resolves on 4xx/5xx: a door-level error pushes no ops, so the trigger's pending
|
|
464
|
+
// state would stick until the safety timeout — surface it to the caller's catch instead
|
|
465
|
+
if (!res.ok) throw new Error(`/intent ${res.status}`);
|
|
466
|
+
return res;
|
|
467
|
+
}).finally(() => clearTimeout(to));
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// ---- send an intent through the one door -------------------------------------
|
|
472
|
+
function submit(action, target, payload, trigger) {
|
|
473
|
+
// Belt-and-braces presence gate: if the door's reply channel is known-down, don't pretend —
|
|
474
|
+
// no-op (the CSS already disables [data-ai-run]/[data-ai-gate] controls; this covers the public
|
|
475
|
+
// window.grain.door seam + any control that isn't gated). "waking" (undefined) still goes.
|
|
476
|
+
if (document.body.dataset.aiOnline === "false") {
|
|
477
|
+
console.info("[ai-dispatch] door offline — submit ignored (presence gating)");
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
// Optimistic grain goes on the TRIGGER the user touched (a button "working") — NOT
|
|
481
|
+
// the target. The target's grade is driven by the server's render ops (type → grain,
|
|
482
|
+
// replace → committed). Pre-graining the target wrongly grained whole regions like
|
|
483
|
+
// the screen and left them stuck, since nothing cleared it.
|
|
484
|
+
if (trigger) { clearTrigger(target); trigger.setAttribute("data-commit", "pending"); pendingTriggers.set(target, trigger); armWatchdog(); }
|
|
485
|
+
const send = () => sendIntent({ source: "user", session, screen, surface: target, action, payload })
|
|
486
|
+
.catch(() => { clearTrigger(target); markOnline(false); }); // couldn't reach the door (timeout/network) → undo + honest offline
|
|
487
|
+
sseIsOpen ? send() : sseReady.then(send); // wait for the stream so no early ops are lost
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// fire a [data-action] trigger (a button/link with a verb) through the ONE door. Shared by page
|
|
491
|
+
// controls AND "actionable chat dialogs" — buttons the AI offers inside a chat message, and the
|
|
492
|
+
// composer's Send — so a control in the chat goes through exactly the same path as one on the page.
|
|
493
|
+
function fireTrigger(ev, trig) {
|
|
494
|
+
const action = trig.getAttribute("data-action");
|
|
495
|
+
const target = targetOf(trig);
|
|
496
|
+
if (!action || !target) return;
|
|
497
|
+
ev.preventDefault();
|
|
498
|
+
// a control may pull its payload text from an input surface (data-from) — e.g. a Send button —
|
|
499
|
+
// or carry a STATIC answer as data-payload-text (a choice button: the value it submits when
|
|
500
|
+
// picked). data-from (a live field) wins if both are present.
|
|
501
|
+
const from = trig.getAttribute("data-from");
|
|
502
|
+
const src = from ? find(from) : null;
|
|
503
|
+
const staticText = trig.getAttribute("data-payload-text");
|
|
504
|
+
const payload = src && "value" in src ? { text: src.value }
|
|
505
|
+
: staticText !== null ? { text: staticText } : {};
|
|
506
|
+
// a picked choice RESOLVES its group: mark the chosen one, retire the rest — a decision, not a
|
|
507
|
+
// re-openable menu (only once; a second click on an already-resolved group does nothing).
|
|
508
|
+
const group = trig.closest && trig.closest("[data-choices]");
|
|
509
|
+
if (group && !group.hasAttribute("data-resolved")) {
|
|
510
|
+
group.setAttribute("data-resolved", "");
|
|
511
|
+
trig.setAttribute("data-chosen", "");
|
|
512
|
+
for (const b of group.querySelectorAll("button")) b.disabled = true;
|
|
513
|
+
} else if (group) {
|
|
514
|
+
return; // group already answered — ignore stray clicks
|
|
515
|
+
}
|
|
516
|
+
submit(action, target, payload, trig);
|
|
517
|
+
if (src && "value" in src) src.value = "";
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// click a button/link with a verb
|
|
521
|
+
document.addEventListener("click", (ev) => {
|
|
522
|
+
if (ev.target.closest(".ai-confirm")) return; // the confirm popup handles its own clicks
|
|
523
|
+
const inOwnSurface = ev.target.closest(".app-shell__aside, .app-shell__console");
|
|
524
|
+
const trig = ev.target.closest && ev.target.closest("[data-action]");
|
|
525
|
+
const actionTrig = trig && trig.tagName !== "INPUT" && trig.tagName !== "TEXTAREA" ? trig : null;
|
|
526
|
+
|
|
527
|
+
// The AI's OWN surfaces (chat + console): interacting there — typing, scrolling, switching
|
|
528
|
+
// panes — is NEVER an interrupt. But an ACTION control living there still fires: a button the
|
|
529
|
+
// AI offered in a chat message (an ACTIONABLE CHAT DIALOG), or the composer's Send. The chat
|
|
530
|
+
// is exempt from the "click = interrupt" rule, not from the action vocabulary.
|
|
531
|
+
if (inOwnSurface) { if (actionTrig) fireTrigger(ev, actionTrig); return; }
|
|
532
|
+
|
|
533
|
+
// On the working PAGE: while the AI acts, a click asks it to stop — even on a control, so you
|
|
534
|
+
// never kick off a second run mid-flight. Otherwise a verb control fires normally.
|
|
535
|
+
if (isActing()) { ev.preventDefault(); interrupt(); return; }
|
|
536
|
+
if (actionTrig) fireTrigger(ev, actionTrig);
|
|
537
|
+
});
|
|
538
|
+
|
|
539
|
+
// Escape while the AI is acting → interrupt (ask to stop), don't force-kill
|
|
540
|
+
document.addEventListener("keydown", (ev) => {
|
|
541
|
+
if (ev.key === "Escape" && isActing()) { ev.preventDefault(); interrupt(); }
|
|
542
|
+
});
|
|
543
|
+
|
|
544
|
+
// A `fill`ed field wears data-grade="grain" (AI ink) until the human TOUCHES it: the first
|
|
545
|
+
// TRUSTED input event settles it clean (the human edited — the ink is theirs now). Synthetic
|
|
546
|
+
// events (including fill's own bubbling `input` above) are not a human touch, so they never
|
|
547
|
+
// settle it. Delegated once — grain's grade-as-signal reaching a form control (DESIGN-SYSTEM §3).
|
|
548
|
+
document.addEventListener("input", (ev) => {
|
|
549
|
+
if (!ev.isTrusted) return;
|
|
550
|
+
const el = ev.target;
|
|
551
|
+
if (el && el.getAttribute && el.getAttribute("data-grade") === "grain" && ("value" in el))
|
|
552
|
+
el.removeAttribute("data-grade");
|
|
553
|
+
});
|
|
554
|
+
|
|
555
|
+
// Enter in an input with a verb → send its value as payload.text
|
|
556
|
+
document.addEventListener("keydown", (ev) => {
|
|
557
|
+
if (ev.key !== "Enter" || ev.shiftKey) return;
|
|
558
|
+
const inp = ev.target;
|
|
559
|
+
if (!inp.matches || !inp.matches("input[data-action]")) return;
|
|
560
|
+
const action = inp.getAttribute("data-action");
|
|
561
|
+
const target = targetOf(inp);
|
|
562
|
+
if (!action || !target) return;
|
|
563
|
+
ev.preventDefault();
|
|
564
|
+
submit(action, target, { text: inp.value }, inp);
|
|
565
|
+
inp.value = "";
|
|
566
|
+
});
|
|
567
|
+
|
|
568
|
+
// ---- the door, as a public seam (window.grain.door) --------------------------
|
|
569
|
+
// A THIRD client of the one door, alongside human clicks (above) and the AI: any island can
|
|
570
|
+
// raise an Intent through the SAME submit() — so it inherits the pending-trigger lifecycle and
|
|
571
|
+
// the sse-ready gate for free, no parallel wire. The terminal is the first user (its `ask`/
|
|
572
|
+
// `tour`/`stop` commands call this). Same idiom as window.grain.theme. (AI-INTERFACE §3.)
|
|
573
|
+
window.grain = window.grain || {};
|
|
574
|
+
window.grain.door = {
|
|
575
|
+
/** Raise an Intent: (action, targetSurface, payload?, triggerEl?). The trigger, if given,
|
|
576
|
+
* wears data-commit="pending" until the action's output commits (control lifecycle). */
|
|
577
|
+
submit: (action, target, payload = {}, trigger = null) => submit(action, target, payload, trigger),
|
|
578
|
+
/** The current screen name (<body data-screen>), for callers building their own intents. */
|
|
579
|
+
screen,
|
|
580
|
+
/** Did the reply channel actually come up? (honest, set by outcome — never assumed.) */
|
|
581
|
+
online: () => document.body.dataset.aiOnline === "true",
|
|
582
|
+
};
|
|
583
|
+
})();
|