@floless/app 0.131.1 → 0.132.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/floless-server.cjs +2374 -1901
  2. package/dist/schemas/steel.model.v2.schema.json +3 -1
  3. package/dist/skills/floless-app-onboarding/SKILL.md +12 -2
  4. package/dist/skills/floless-app-queue/SKILL.md +2 -2
  5. package/dist/web/app.css +359 -0
  6. package/dist/web/app.js +22 -0
  7. package/dist/web/aware.js +121 -13
  8. package/dist/web/commands-filter.js +157 -0
  9. package/dist/web/commands-shell.js +1316 -0
  10. package/dist/web/commands-steel.js +1829 -0
  11. package/dist/web/commands-vector.js +154 -0
  12. package/dist/web/commands-vector3d.js +96 -0
  13. package/dist/web/commands.js +316 -0
  14. package/dist/web/grid-core.js +124 -23
  15. package/dist/web/index.html +269 -164
  16. package/dist/web/instructor-reporter.js +201 -0
  17. package/dist/web/instructor.js +1178 -0
  18. package/dist/web/reference-geometry-worker.js +194 -0
  19. package/dist/web/steel-3d-core.js +486 -107
  20. package/dist/web/steel-3d-view.js +847 -204
  21. package/dist/web/steel-canvas-guidance.js +7 -4
  22. package/dist/web/steel-editor.html +1620 -1799
  23. package/dist/web/steel-filter-core.js +13 -5
  24. package/dist/web/steel-filter.html +36 -22
  25. package/dist/web/steel-model-adapter.js +17 -22
  26. package/dist/web/steel-model-commands.js +23 -10
  27. package/dist/web/steel-model-v2-client-validation.js +20 -3
  28. package/dist/web/steel-model-v2-commands.js +91 -3
  29. package/dist/web/steel-model-v2-projection.js +4 -5
  30. package/dist/web/steel-plan-transform.js +4 -8
  31. package/dist/web/steel-split-view.js +33 -0
  32. package/dist/web/vector-3d.html +19 -7
  33. package/dist/web/vector-editor.html +21 -8
  34. package/dist/web/workspaces.js +12 -25
  35. package/package.json +10 -1
@@ -0,0 +1,1178 @@
1
+ /* ──────────────────────────────────────────────────────────────────────────
2
+ The Instructor — a docked band that narrates what you are doing.
3
+
4
+ VERTICAL SLICE (shell only). Proves the interaction model in the real app:
5
+ an idle readout of your own project state, a plain-English reason when a
6
+ control is blocked, and `?` to explain any control on demand.
7
+
8
+ Design contract this slice honours (docs/plans/2026-08-17-instructor-dynamic-docs.md):
9
+
10
+ • ONE PURE PRODUCER. `guidanceFor(snapshot)` is a pure function — no DOM
11
+ reads, no side effects — so it is testable and so consumers cannot drift
12
+ apart. Rendering is a separate step that only paints what it is handed.
13
+ • NO ECHO. An entry must carry at least one derived, non-visible fact (what
14
+ it acts on, where it sits, its keyboard route, whether it applies right
15
+ now). A line that would merely restate the control's own label is
16
+ suppressed — silence beats an echo.
17
+ • NOT A SECOND LIVE REGION. #run-state already announces gate changes to
18
+ screen readers. The band is aria-live="off" so hovering a toolbar cannot
19
+ flood the queue; `?` is an explicit user action, so it announces via the
20
+ existing status element instead.
21
+
22
+ NOT in this slice, deliberately: the command registry, the cross-frame
23
+ reporter, the steel editor, the CI guards. See phase 0 in the plan.
24
+ ────────────────────────────────────────────────────────────────────────── */
25
+ (function () {
26
+ 'use strict';
27
+
28
+ var COLLAPSE_KEY = 'floless:instructor:collapsed';
29
+ /* On/off is a SEPARATE key from collapsed, because they are different questions:
30
+ collapsed keeps a thin rail and remembers where you were, off reclaims the grid
31
+ row entirely. A user who turns the strip off and later back on should find their
32
+ collapse preference where they left it. Default ON — only the literal '0' turns
33
+ it off, so a new user (null) gets the Instructor. */
34
+ var ENABLED_KEY = 'floless:instructor:enabled';
35
+
36
+ /* ── the producer ─────────────────────────────────────────────────────────
37
+ snapshot → structured guidance. Pure. Everything the band shows comes
38
+ from here, and nothing else in this file authors narration text. */
39
+
40
+ /* Shown when a surface arms a command the registry does not know. The
41
+ alternative — falling back to a generic "something is armed" — would let a
42
+ missing registration ship looking like a design choice, and phase 3's
43
+ coverage gate would be the first thing to notice. This is the one string
44
+ the producer owns, and it exists to make a gap visible. */
45
+ var UNREGISTERED = 'This command has no entry yet — please report it';
46
+
47
+ function guidanceFor(snapshot) {
48
+ var s = snapshot || {};
49
+
50
+ // An armed command in a child surface always wins — you cannot abandon a
51
+ // multi-click sequence to read about a button the cursor crossed.
52
+ if (s.child && s.child.armed) return commandGuidance(s.child);
53
+
54
+ // A focused/queried control wins over the idle readout, but never over a
55
+ // blocked gate the user is actively looking at.
56
+ if (s.focus) return controlGuidance(s.focus, s.workflow);
57
+ if (s.workspace) return workspaceGuidance(s.workspace);
58
+ return workflowGuidance(s.workflow);
59
+ }
60
+
61
+ /* PHASE 2: step text comes from the REGISTRY, not from a table in here.
62
+ The phase-0 scaffolding table is gone: a second list of step prose living
63
+ beside the producer is exactly the drift this design exists to prevent, and
64
+ it could only ever describe commands the shell happened to know about.
65
+
66
+ `steps` is authored once, next to the surface that owns the command
67
+ (commands-steel.js), and the child reports which index it is on. */
68
+
69
+ function commandGuidance(child) {
70
+ var id = child.armed;
71
+ var meta = window.Commands ? window.Commands.get(id) : null;
72
+
73
+ // No definition — the surface armed something that never registered, or its
74
+ // registrations did not load here. Say so plainly rather than inventing a
75
+ // step: a wrong instruction is worse than an admitted gap, and this reads as
76
+ // a bug report to whoever sees it.
77
+ if (!meta) return { tone: 'armed', chip: id, parts: [UNREGISTERED], ask: id, unregistered: true, surface: child.surface || 'shell' };
78
+
79
+ var steps = meta.steps || [];
80
+ var chip = meta.label;
81
+ var parts = [];
82
+
83
+ if (steps.length) {
84
+ var i = typeof child.step === 'number' && child.step >= 0 ? Math.min(child.step, steps.length - 1) : 0;
85
+ // A one-step command has no sequence to count through, so counting at it
86
+ // is noise — "step 1 of 1" tells the user nothing they cannot see.
87
+ if (steps.length > 1) chip = meta.label + ' · step ' + (i + 1) + ' of ' + steps.length;
88
+ parts.push(steps[i]);
89
+ } else {
90
+ parts.push(meta.label + ' is armed');
91
+ }
92
+
93
+ // Appended once here rather than repeated on every registration: how you get
94
+ // out of an armed command is the producer's business, not each command's.
95
+ parts.push('Esc to cancel');
96
+
97
+ return { tone: 'armed', chip: chip, parts: parts, ask: meta.label, commandId: id, surface: child.surface || 'shell' };
98
+ }
99
+
100
+ function workspaceGuidance(workspace) {
101
+ var landing = workspace.landing === true;
102
+ return {
103
+ tone: 'idle',
104
+ chip: landing ? 'Workspaces' : 'Project',
105
+ parts: landing ? ['Choose or create a project'] : [workspace.name, 'Project workspace open'],
106
+ ask: workspace.name,
107
+ surface: 'workspaces',
108
+ };
109
+ }
110
+
111
+ function workflowGuidance(wf) {
112
+ if (!wf || !wf.name) {
113
+ return {
114
+ tone: 'idle',
115
+ chip: 'No workflow',
116
+ parts: ['Open a workflow to see where it stands'],
117
+ ask: null,
118
+ surface: 'shell',
119
+ };
120
+ }
121
+
122
+ var parts = [];
123
+ var tone = 'idle';
124
+ var chip = wf.statusLabel || 'Ready';
125
+
126
+ if (wf.runState === 'drift') {
127
+ tone = 'blocked';
128
+ chip = 'Run blocked';
129
+ parts.push(wf.name);
130
+ parts.push('changed since the last Compile, so its approved lock is out of date');
131
+ parts.push('Compile to re-enable Run');
132
+ } else if (wf.runState === 'uncompiled') {
133
+ tone = 'blocked';
134
+ chip = 'Not set up';
135
+ parts.push(wf.name);
136
+ parts.push('has no approved lock yet, so Run is off');
137
+ parts.push('Compile to freeze one');
138
+ } else {
139
+ parts.push(wf.name);
140
+ if (wf.totalInputs) {
141
+ parts.push(
142
+ wf.inputsSet === wf.totalInputs
143
+ ? 'all inputs set'
144
+ : wf.inputsSet + ' of ' + wf.totalInputs + ' inputs set'
145
+ );
146
+ }
147
+ parts.push('in sync');
148
+ parts.push(nextStep(wf));
149
+ }
150
+
151
+ return { tone: tone, chip: chip, parts: parts, ask: wf.name, surface: 'shell' };
152
+ }
153
+
154
+ function nextStep(wf) {
155
+ if (wf.totalInputs && wf.inputsSet < wf.totalInputs) return 'Next: set the remaining inputs';
156
+ return 'Next: Run';
157
+ }
158
+
159
+ /* A control's entry. Returns null-ish guidance when every fact it could show
160
+ is already visible on screen — the No-Echo rule, enforced here rather than
161
+ left to the caller. */
162
+ function controlGuidance(focus, wf) {
163
+ var facts = [];
164
+
165
+ if (focus.acts) facts.push(focus.acts);
166
+ if (focus.group) facts.push(focus.group);
167
+ if (focus.key) facts.push(focus.key);
168
+
169
+ if (focus.disabled) {
170
+ facts.push(focus.disabledReason || 'Not available right now');
171
+ } else if (facts.length) {
172
+ facts.push('Available now');
173
+ }
174
+
175
+ // No derived fact → nothing worth saying beyond what the screen shows.
176
+ if (!facts.length) {
177
+ if (focus.tip) return { tone: 'idle', chip: focus.label, parts: [focus.tip], ask: focus.label, surface: focus.originSurface || 'shell' };
178
+ return { tone: 'silent', chip: null, parts: [], ask: null, fallback: workflowGuidance(wf) };
179
+ }
180
+
181
+ return {
182
+ tone: focus.disabled ? 'blocked' : 'idle',
183
+ chip: focus.label,
184
+ parts: facts,
185
+ ask: focus.label,
186
+ commandId: focus.commandId || null,
187
+ instance: focus.instance || null,
188
+ surface: focus.originSurface || 'shell',
189
+ };
190
+ }
191
+
192
+ /* ── derivation: a control → the focus half of a snapshot ─────────────────
193
+ Metadata (data-acts / data-group / data-key) is authored beside the
194
+ control; everything else is read live. */
195
+
196
+ function accessibleName(el) {
197
+ var aria = el.getAttribute('aria-label');
198
+ if (aria && aria.trim()) return aria.trim();
199
+ var text = (el.textContent || '').replace(/\s+/g, ' ').trim();
200
+ if (text) return text;
201
+ var tip = el.getAttribute('data-tip');
202
+ if (tip) return tip.split('\n')[0].split('—')[0].trim();
203
+ return el.id || 'This control';
204
+ }
205
+
206
+ function groupOf(el) {
207
+ var owner = el.closest('[data-group]');
208
+ if (owner) return owner.getAttribute('data-group');
209
+ if (el.closest('header')) return 'In the header';
210
+ if (el.closest('footer')) return 'In the footer';
211
+ if (el.closest('#chat-panel')) return 'In the Narrative panel';
212
+ if (el.closest('.canvas')) return 'On the workflow canvas';
213
+ if (el.closest('.inspect')) return 'In the Inspect panel';
214
+ return null;
215
+ }
216
+
217
+ /* ── command templates (PHASE 0b) ─────────────────────────────────────────
218
+ Runtime-generated rows are MANY INSTANCES OF ONE CAPABILITY. Registering
219
+ each instance would make the registry churn with project data and make the
220
+ checked-in id inventory unstable — the objection raised in review.
221
+
222
+ So the registry holds TEMPLATES only, and the DOM carries a parameterized
223
+ id: data-command-id="workflow.rename#my-app"
224
+ └ template ──┘ └ instance key ┘
225
+
226
+ A template is registered once, beside the code that generates the rows.
227
+ Instances register nothing: they are resolved by splitting on '#'. That
228
+ makes teardown free — instances die with the DOM that held them, and the
229
+ template's lifetime is the document's. */
230
+
231
+ /* Storage and resolution belong to commands.js — the single authority on what
232
+ a capability is. instructor.js only READS it, so there is exactly one place
233
+ a definition can live. */
234
+ function resolveCommand(el) {
235
+ return window.Commands ? window.Commands.resolve(el) : null;
236
+ }
237
+
238
+ function focusFor(el) {
239
+ if (!el || el === document.body) return null;
240
+ var target = el.closest('button, [role="button"], a[href], input, select, textarea');
241
+ if (!target) return null;
242
+
243
+ var tip = target.getAttribute('data-tip') || '';
244
+ var disabled = !!(target.disabled || target.getAttribute('aria-disabled') === 'true');
245
+ var cmd = resolveCommand(target);
246
+
247
+ // A registered template supplies the facts; the instance key supplies the
248
+ // subject, so one authored entry serves every generated row.
249
+ if (cmd && cmd.meta) {
250
+ return {
251
+ label: cmd.meta.label || accessibleName(target),
252
+ acts: cmd.instance && cmd.meta.actsOn
253
+ ? cmd.meta.actsOn.replace('{instance}', cmd.instance)
254
+ : cmd.meta.actsOn || null,
255
+ group: cmd.meta.group || groupOf(target),
256
+ key: cmd.meta.key || target.getAttribute('data-key'),
257
+ tip: tip ? tip.split('\n')[0] : '',
258
+ disabled: disabled,
259
+ disabledReason: target.getAttribute('data-blocked-reason'),
260
+ commandId: cmd.id,
261
+ instance: cmd.instance,
262
+ };
263
+ }
264
+
265
+ return {
266
+ label: accessibleName(target),
267
+ acts: target.getAttribute('data-acts'),
268
+ group: groupOf(target),
269
+ key: target.getAttribute('data-key'),
270
+ tip: tip ? tip.split('\n')[0] : '',
271
+ disabled: disabled,
272
+ disabledReason: target.getAttribute('data-blocked-reason'),
273
+ commandId: cmd ? cmd.id : null,
274
+ instance: cmd ? cmd.instance : null,
275
+ };
276
+ }
277
+
278
+ /* ── rendering ────────────────────────────────────────────────────────────
279
+ The only place that touches the DOM. Paints exactly what the producer
280
+ returned; authors nothing. */
281
+
282
+ var $band, $chip, $parts, $ask, $toggle;
283
+ var snapshot = { surface: 'shell', workflow: null, workspace: null, focus: null, child: null };
284
+ var collapsed = false;
285
+ var enabled = true;
286
+
287
+ function seg(cls, text) {
288
+ var el = document.createElement('span');
289
+ el.className = cls;
290
+ el.textContent = text;
291
+ return el;
292
+ }
293
+
294
+ function paint() {
295
+ if (!$band) return;
296
+
297
+ var g = guidanceFor(snapshot);
298
+ if (g.tone === 'silent' && g.fallback) g = g.fallback;
299
+
300
+ $band.className = 'instructor tone-' + g.tone;
301
+ if (collapsed) $band.classList.add('collapsed');
302
+
303
+ $chip.textContent = g.chip || '';
304
+ $chip.hidden = !g.chip;
305
+
306
+ $parts.textContent = '';
307
+ g.parts.forEach(function (part, i) {
308
+ if (i) $parts.appendChild(seg('ix-sep', '·'));
309
+ $parts.appendChild(seg(i === 0 ? 'ix-val' : 'ix-seg', part));
310
+ });
311
+
312
+ $ask.hidden = !g.ask;
313
+ if (g.ask) $ask.dataset.subject = g.ask;
314
+ }
315
+
316
+ function setCollapsed(next) {
317
+ collapsed = !!next;
318
+ try { localStorage.setItem(COLLAPSE_KEY, collapsed ? '1' : '0'); } catch (e) { /* private mode */ }
319
+ $toggle.setAttribute('aria-expanded', String(!collapsed));
320
+ $toggle.dataset.tip = collapsed ? 'Show the Instructor' : 'Hide the Instructor';
321
+ paint();
322
+ }
323
+
324
+ /* ── on/off ───────────────────────────────────────────────────────────────
325
+ Collapsing keeps a rail; turning the Instructor OFF takes the row out of
326
+ the .app grid so the space is genuinely reclaimed. Both the class and the
327
+ element's own hide are needed: the class is what defines the grid row, and
328
+ without hiding the element too it would be auto-placed into an implicit
329
+ one — the reserved space this setting exists to remove. */
330
+
331
+ function applyEnabled() {
332
+ var app = document.getElementById('app');
333
+ if (app) app.classList.toggle('has-instructor', enabled);
334
+ if ($band) $band.hidden = !enabled;
335
+
336
+ var item = document.getElementById('menu-instructor-toggle');
337
+ if (item) item.setAttribute('aria-checked', String(enabled));
338
+
339
+ // Restoring must not need a reload: repaint from the state we kept while off.
340
+ if (enabled) paint();
341
+ }
342
+
343
+ function setEnabled(next) {
344
+ enabled = !!next;
345
+ try { localStorage.setItem(ENABLED_KEY, enabled ? '1' : '0'); } catch (e) { /* private mode */ }
346
+ /* Turning the Instructor off while its sheet is open would hide the band and
347
+ leave the dialog on screen over an inert app — reachable today, because the
348
+ ≡ menu is still clickable from inside the sheet's own backdrop click-out.
349
+ Close it first, which also releases inertness and restores focus. */
350
+ if (!enabled) closeSheet();
351
+ applyEnabled();
352
+ }
353
+
354
+ /* ── `?` — explain what has focus, or what the pointer is over ────────────
355
+ Scoped off while typing. This is a prompt-native product; a bare-key
356
+ binding must never eat a literal "?" the user meant to type. */
357
+
358
+ var lastHovered = null;
359
+ var lastHoveredAt = 0;
360
+
361
+ function isTyping(el) {
362
+ if (!el) return false;
363
+ if (el.isContentEditable) return true;
364
+ var tag = el.tagName;
365
+ return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT';
366
+ }
367
+
368
+ /* Which target does the user mean — the focused control, or the one under the
369
+ pointer? Both are defensible and phase 0b measured both being wrong:
370
+
371
+ • Focus-first explained "Search workflows" while the pointer sat on a
372
+ row's Delete action, because every searchable popover parks focus in
373
+ its filter box.
374
+ • Hover-first would explain whatever the mouse was last parked over,
375
+ which is meaningless for someone tabbing through with the keyboard.
376
+
377
+ The rule: a RECENT pointer movement means the user is pointing at what they
378
+ mean; otherwise they are navigating by keyboard and focus wins. */
379
+ var HOVER_INTENT_MS = 3000;
380
+
381
+ function explainCurrent() {
382
+ // The band is the only thing that renders an explanation, so with the
383
+ // Instructor off `?` and F1 must do nothing at all — and must not swallow
384
+ // the keystroke either (explainCurrent's return value is what decides
385
+ // whether the handler calls preventDefault).
386
+ if (!enabled) return false;
387
+
388
+ var active = document.activeElement;
389
+ var hasActive = active && active !== document.body;
390
+ var pointerIsFresh = lastHovered && (Date.now() - lastHoveredAt) < HOVER_INTENT_MS;
391
+
392
+ var el = hasActive ? active : lastHovered;
393
+ if (pointerIsFresh && lastHovered !== active && focusFor(lastHovered)) {
394
+ el = lastHovered;
395
+ }
396
+
397
+ var f = focusFor(el);
398
+ var origin = el && el.ownerDocument === document
399
+ ? (snapshot.workspace ? 'workspaces' : 'shell')
400
+ : activeSurface();
401
+ if (!setFocusEntry(f, origin)) return false;
402
+ if (collapsed) setCollapsed(false);
403
+ paint();
404
+ return true;
405
+ }
406
+
407
+ /* The ONE way an on-demand entry gets into the band.
408
+ *
409
+ * It stamps where the entry came from, because the entry OUTLIVES the thing it
410
+ * describes otherwise. Escape used to be the only thing that cleared it, so
411
+ * asking about a control in a child surface, closing that surface and switching
412
+ * workflow left the band still reading "Save filter · In the Drawing Filter
413
+ * header · Not available right now" over a canvas with no filter on it — and
414
+ * because guidanceFor checks `focus` BEFORE the workflow readout, it did not
415
+ * merely linger, it suppressed the correct line underneath.
416
+ *
417
+ * That is the same defect the reporter contract was built to close (a band
418
+ * narrating a torn-down surface); the teardown cleared `snapshot.child` and
419
+ * nobody cleared this. Worse, "Not available right now" is read off the real
420
+ * element at capture time, so it silently became a fact about a dead document.
421
+ */
422
+ function setFocusEntry(f, origin) {
423
+ if (!f) return false;
424
+ /* The ORIGIN IS PASSED IN, never guessed from activeSurface(). The two differ:
425
+ the contract-editor overlay covers the shell without unmounting it, so while a
426
+ child is open a shell button is still found and still focusable — and guessing
427
+ would file that entry under the child, then throw it away when the child
428
+ closed even though the button is right there. Callers know the truth:
429
+ activate() knows which document it found the element in, and the registry
430
+ fallback has `cmd.surface`. Defaults to the shell only for a caller that has
431
+ nothing better, which is explain()'s hover/focus path — where a child overlay
432
+ means the pointer cannot be on a shell control anyway. */
433
+ f.originSurface = origin || 'shell';
434
+ snapshot.focus = f;
435
+ return true;
436
+ }
437
+
438
+ function clearFocusEntry() {
439
+ if (!snapshot.focus) return;
440
+ snapshot.focus = null;
441
+ paint();
442
+ }
443
+
444
+ /* ── the `?` command sheet ────────────────────────────────────────────────
445
+ `?`/F1 explain the ONE control you are on. This is the other half: every
446
+ command the registry knows, searchable. It opens on the same key when there
447
+ is no control to explain — asking for help while pointing at nothing is a
448
+ reasonable way to say "show me everything" — and from the strip's "see all".
449
+
450
+ Rows are DERIVED, never authored: label, what it acts on, its keyboard
451
+ route, its tier. Nothing here restates the label (No Echo). */
452
+
453
+ var $sheet, $sheetList, $sheetFilter, $sheetSub;
454
+ var sheetOpen = false;
455
+ var returnFocusTo = null; // where focus came from, so Escape can give it back
456
+ var sheetRows = [];
457
+ var activeRow = -1;
458
+
459
+ function sheetEntries() {
460
+ if (!window.Commands) return [];
461
+ return window.Commands.all().slice().sort(function (a, b) {
462
+ // What is on screen comes first. Nothing is hidden — the sheet is also how
463
+ // you find out what FloLess can do somewhere else, and its zero-result copy
464
+ // calls a miss "a gap worth reporting", which would be a lie if the
465
+ // catalogue were quietly trimmed to the current screen.
466
+ var sa = onScreen(a) ? 0 : 1, sb = onScreen(b) ? 0 : 1;
467
+ if (sa !== sb) return sa - sb;
468
+ var ga = a.group || 'Elsewhere', gb = b.group || 'Elsewhere';
469
+ if (ga !== gb) {
470
+ var ra = groupRank(ga), rb = groupRank(gb);
471
+ if (ra !== rb) return ra - rb;
472
+ return ga < gb ? -1 : 1;
473
+ }
474
+ return a.label < b.label ? -1 : a.label > b.label ? 1 : 0;
475
+ });
476
+ }
477
+
478
+ /* What a row says BESIDES its label. An entry with nothing to add says
479
+ nothing — silence beats an echo, and a row that reads "Compile — compiles"
480
+ would cost the whole surface its credibility. */
481
+ function factsFor(cmd) {
482
+ var facts = [];
483
+ /* actsOn may carry the {instance} placeholder one authored entry uses to
484
+ serve every generated row. The sheet lists TEMPLATES, so there is no
485
+ instance to fill it with — and shipping the literal braces to a user is
486
+ the kind of leak that costs a documentation surface its credibility. */
487
+ if (cmd.actsOn) facts.push(cmd.actsOn.replace(/\{instance\}/g, 'the one you pick'));
488
+ if (cmd.risk && cmd.risk.indexOf('destructive') !== -1) facts.push('cannot be undone');
489
+ if (cmd.risk && cmd.risk.indexOf('costs-money') !== -1) facts.push('costs money');
490
+ if (cmd.persistence === 'external') facts.push('reaches outside FloLess');
491
+ return facts.join(' · ');
492
+ }
493
+
494
+ /* The risk pill, in plain English rather than the vocabulary's own words. Only
495
+ T2 gets one: T3 is roughly two-thirds of the list, and badging the majority
496
+ is its own kind of noise. */
497
+ function tagFor(cmd) {
498
+ var risk = cmd.risk || [];
499
+ if (risk.indexOf('destructive') !== -1) return { text: 'Irreversible', tone: 'destructive' };
500
+ if (risk.indexOf('costs-money') !== -1) return { text: 'Costs money', tone: 'costly' };
501
+ if (cmd.persistence === 'external') return { text: 'Leaves FloLess', tone: 'costly' };
502
+ if (cmd.persistence === 'approved') return { text: 'Changes the lock', tone: 'costly' };
503
+ return null;
504
+ }
505
+
506
+ /* What a search reads. The step text is included so "click the member end"
507
+ finds Add member — the sentences ARE how a user remembers a tool. The
508
+ internal vocabulary (id, persistence, interaction, guidance) is NOT: those
509
+ are our words, and matching them would surface hits a user cannot explain to
510
+ themselves. Risk flags are in, so "destructive" finds what it should. */
511
+ function matches(cmd, q) {
512
+ if (!q) return true;
513
+ var hay = [cmd.label, cmd.actsOn, cmd.group, cmd.key, cmd.why]
514
+ .concat(cmd.steps || [])
515
+ .concat(cmd.risk || [])
516
+ .join(' ').toLowerCase();
517
+ return hay.indexOf(q) !== -1;
518
+ }
519
+
520
+ /* Groups in the order the user meets them on screen, not alphabetically —
521
+ "where am I, what is near me" is the model the band's own hover explanations
522
+ already use. Anything unlisted sorts after, alphabetically.
523
+
524
+ This is the WITHIN-SURFACE order. Which surface comes first is decided at
525
+ render time from what is actually on screen (see onScreen/sheetEntries) —
526
+ a static array cannot express that, because "active" is runtime state. */
527
+ var GROUP_ORDER = [
528
+ // the shell
529
+ 'In the header', 'In the workflow picker', 'In the project picker',
530
+ 'In the project workspace', 'On the workflow canvas',
531
+ 'In the Narrative panel', 'In the node Inspect panel', 'In the Instructor strip',
532
+ 'In the ≡ menu', 'In the footer',
533
+ 'In the contract editor', 'In the report viewer', 'In the guide',
534
+ 'In the agent library', 'In the requests list', 'In the Routines dialog',
535
+ 'In the Report an issue dialog', 'In the Build an agent dialog', 'In the Bake dialog',
536
+ 'In the FloLess dialogs',
537
+ /* the steel editor — read top-left down, then the menus, then the dialogs.
538
+ The ⋯ menu is six groups rather than one because it is six accordion
539
+ sections on screen: a single 'In the ⋯ menu' would have been about thirty
540
+ rows under one heading, which is a scroll rather than a list. */
541
+ 'In the steel editor header', 'On the steel canvas', 'In the Copy panel', 'In the Copy array panel', 'On the 2D zoom bar',
542
+ 'In the 3D toolbar', 'In the 3D side panel', 'On the snap bar',
543
+ 'In the grid panel', 'In the Inspect panel',
544
+ 'In the Properties popup', 'In the snap override menu', 'In the dimension value popup', 'In the selection filter',
545
+ 'In the ⋯ menu',
546
+ 'In the ⋯ menu — Snapping', 'In the ⋯ menu — Display', 'In the ⋯ menu — Detailing',
547
+ 'In the ⋯ menu — Model checks', 'In the ⋯ menu — Coordinate system', 'In the ⋯ menu — Session',
548
+ 'In the steel editor dialogs', 'In the Generate views dialog', 'In the Details dialog', 'In the RFI dialog',
549
+ 'In the Connections dialog', 'In the reference-model dialogs', 'In the connection-import dialog',
550
+ 'In the confidence report', 'In the Ask AI dialog', 'In the Favourites dialog',
551
+ // the drawing filter
552
+ 'In the Drawing Filter header', 'In the Drawing Filter panel', 'On the Drawing Filter canvas',
553
+ // the vector editor, and its 3D viewer
554
+ 'In the Trace header', 'In the Trace panel', 'On the Trace canvas',
555
+ 'In the Trace — 3D header', 'On the Trace — 3D view',
556
+ ];
557
+ function groupRank(g) {
558
+ var i = GROUP_ORDER.indexOf(g);
559
+ return i === -1 ? GROUP_ORDER.length : i;
560
+ }
561
+
562
+ /* Which surface the user is looking at. A child reporter names itself; with no
563
+ child live, the shell is what is on screen.
564
+
565
+ Only ONE surface is ever visible: the contract-editor overlay that hosts
566
+ every child is `position: fixed; inset: 0` (app.css), so an open child hides
567
+ the shell's own header, picker and canvas entirely. That is why an on-screen
568
+ test is `surface === live` and not "shell plus the live child". */
569
+ function activeSurface() {
570
+ return (snapshot.child && snapshot.child.surface) || (snapshot.workspace ? 'workspaces' : 'shell');
571
+ }
572
+ function onScreen(cmd) {
573
+ /* A command registered before `surface` existed would have none. Treating
574
+ that as on-screen keeps it visible rather than silently exiling it, and
575
+ verify-command-registry is what stops one being added. */
576
+ return !cmd.surface || cmd.surface === activeSurface();
577
+ }
578
+
579
+ function renderSheet() {
580
+ var q = ($sheetFilter.value || '').trim().toLowerCase();
581
+ var all = sheetEntries();
582
+ var hits = all.filter(function (c) { return matches(c, q); });
583
+
584
+ $sheetList.textContent = '';
585
+ sheetRows = [];
586
+ activeRow = -1;
587
+
588
+ if (!hits.length) {
589
+ var empty = document.createElement('div');
590
+ empty.className = 'cmd-sheet-empty';
591
+ // A zero-result search names a coverage gap, so it says so rather than
592
+ // shrugging — this is the one place a user can tell us what is missing.
593
+ empty.appendChild(document.createTextNode('Nothing matches '));
594
+ var b = document.createElement('b');
595
+ b.textContent = '“' + ($sheetFilter.value || '').trim() + '”';
596
+ empty.appendChild(b);
597
+ empty.appendChild(document.createTextNode('. If FloLess does this and it is not listed, that is a gap worth reporting.'));
598
+ $sheetList.appendChild(empty);
599
+ $sheetSub.textContent = 'No matches of ' + all.length;
600
+ return;
601
+ }
602
+
603
+ var lastGroup = null;
604
+ var dividedYet = false;
605
+ hits.forEach(function (cmd) {
606
+ /* One divider, at the first command that is not on this screen. The sort
607
+ has already put every on-screen command ahead of every other, so a
608
+ single boundary is all there is. */
609
+ if (!dividedYet && !onScreen(cmd)) {
610
+ dividedYet = true;
611
+ lastGroup = null; // the first group below the rule still needs its heading
612
+ var sep = document.createElement('div');
613
+ sep.className = 'cmd-elsewhere';
614
+ /* role=presentation: ARIA permits only option/group as owned children of a
615
+ listbox, and the per-row sr-only span is already how "where does this live"
616
+ is announced. Without it an AT can surface this text out of order, between
617
+ options it does not belong to. */
618
+ sep.setAttribute('role', 'presentation');
619
+ sep.textContent = 'Elsewhere in FloLess';
620
+ $sheetList.appendChild(sep);
621
+ }
622
+ var group = cmd.group || 'Elsewhere';
623
+ if (group !== lastGroup) {
624
+ lastGroup = group;
625
+ var h = document.createElement('div');
626
+ h.className = 'cmd-group';
627
+ h.setAttribute('role', 'presentation'); // same reason as the divider below
628
+ h.textContent = group;
629
+ $sheetList.appendChild(h);
630
+ }
631
+
632
+ var row = document.createElement('button');
633
+ row.type = 'button';
634
+ row.className = 'cmd-row';
635
+ row.id = 'cmd-row-' + cmd.id; // the aria-activedescendant target
636
+ row.setAttribute('role', 'option');
637
+ row.setAttribute('aria-selected', 'false');
638
+ row.dataset.commandId = cmd.id;
639
+
640
+ var label = document.createElement('span');
641
+ label.className = 'cmd-row-label';
642
+ label.textContent = cmd.label;
643
+ row.appendChild(label);
644
+
645
+ /* Where this command lives, for screen readers only. Arrow-key navigation
646
+ moves aria-activedescendant between rows, and a reader announces just the
647
+ focused option — never the .cmd-group heading or the divider beside it. So
648
+ a sighted user can see "this one is somewhere else" and a screen-reader
649
+ user could not. Folded into every row rather than only the ones below the
650
+ rule, because the orientation gap is the same for the existing groups. */
651
+ if (cmd.group) {
652
+ var where = document.createElement('span');
653
+ where.className = 'sr-only';
654
+ where.textContent = ' — ' + cmd.group;
655
+ row.appendChild(where);
656
+ }
657
+
658
+ var facts = factsFor(cmd);
659
+ if (facts) {
660
+ var f = document.createElement('span');
661
+ f.className = 'cmd-row-facts';
662
+ f.textContent = facts;
663
+ row.appendChild(f);
664
+ }
665
+
666
+ // T1: how many steps, in the muted mono register the app already uses for
667
+ // row metadata. Not a badge — it is information, not a warning.
668
+ if (cmd.tier === 'T1' && cmd.steps && cmd.steps.length > 1) {
669
+ var t = document.createElement('span');
670
+ t.className = 'cmd-row-tier';
671
+ t.textContent = cmd.steps.length + ' steps';
672
+ row.appendChild(t);
673
+ }
674
+
675
+ var tag = tagFor(cmd);
676
+ if (tag) {
677
+ var g = document.createElement('span');
678
+ g.className = 'cmd-row-tag';
679
+ g.dataset.tone = tag.tone;
680
+ g.textContent = tag.text;
681
+ row.appendChild(g);
682
+ }
683
+
684
+ if (cmd.key) {
685
+ var k = document.createElement('span');
686
+ k.className = 'cmd-row-key';
687
+ k.textContent = cmd.key.replace(/^Also:\s*/, '');
688
+ row.appendChild(k);
689
+ }
690
+
691
+ row.addEventListener('click', function () { activate(cmd); });
692
+ $sheetList.appendChild(row);
693
+ sheetRows.push(row);
694
+ });
695
+
696
+ $sheetSub.textContent = q
697
+ ? hits.length + ' of ' + all.length + ' commands'
698
+ : all.length + ' commands — this screen first';
699
+ }
700
+
701
+ /* Choosing a row takes you TO the control, when one is on screen. A list that
702
+ only described things would make the user find them again by hand. */
703
+ function activate(cmd) {
704
+ /* Look for the control OUTSIDE the sheet. The rows carry data-command-id
705
+ themselves (that is how a row knows what it is), so a naive query matches
706
+ the row you just clicked — and for any command with no live control on this
707
+ surface, such as every steel.* one while the editor is in an iframe, the
708
+ row is the ONLY match. The result was focusing a row inside a dialog that
709
+ had just been hidden. Visibility is checked too: a control in a closed
710
+ panel is found by a selector but cannot be focused. */
711
+ /* Concatenated, not escaped, and that is safe for a specific reason worth
712
+ stating: `cmd.id` can only be a registered id, and commands.js refuses to
713
+ register anything outside lowercase dotted-kebab — so it cannot contain a
714
+ quote to close the string or a backslash to start an escape.
715
+
716
+ The INSTANCE key is the half that comes from data (a member mark, a level
717
+ elevation like 16'-6"), and it deliberately never appears here: the second
718
+ arm matches on the `id#` PREFIX and lets the attribute selector's own
719
+ quoting cover whatever follows. So an instance containing a quote is a
720
+ problem only where it is WRITTEN INTO markup, never where it is read back.
721
+ Keep it that way — building a selector from a raw instance is the shape
722
+ that would break. */
723
+ var sel = '[data-command-id="' + cmd.id + '"], [data-command-id^="' + cmd.id + '#"]';
724
+ var live = null;
725
+ /* Which document the control was found in — carried so the entry can be stamped
726
+ with where the control LIVES rather than with whatever surface happened to be
727
+ on screen. A shell button stays alive (and focusable) under the child overlay,
728
+ so those two are genuinely different answers. */
729
+ var liveOrigin = 'shell';
730
+ Array.prototype.forEach.call(document.querySelectorAll(sel), function (el) {
731
+ if (live || (el.closest && el.closest('#command-sheet'))) return;
732
+ if (el.offsetParent || (el.getClientRects && el.getClientRects().length)) live = el;
733
+ });
734
+
735
+ /* Then the live child surface, if one is up. Searching only this document used
736
+ to be survivable because the unreachable commands sat at the BOTTOM of the
737
+ list — but the on-screen-first sort now hoists exactly those to the top
738
+ whenever a child is open, which would turn a documented tail case into the
739
+ first thing the user meets. The frame is same-origin and the shell already
740
+ holds a reference to it, so this is a lookup, not a new channel. */
741
+ /* `snapshot.child` is the guard, not just a null-check: it is the SAME report the
742
+ sort ordered by, so the frame searched here is always the surface whose commands
743
+ were promoted. Between a new frame's ready and its first report, activeReporterWindow
744
+ has moved on while snapshot.child is still null — ordering falls back to the shell,
745
+ and so must this. */
746
+ if (!live && activeReporterWindow && snapshot.child) {
747
+ try {
748
+ var doc = activeReporterWindow.document;
749
+ Array.prototype.forEach.call(doc.querySelectorAll(sel), function (el) {
750
+ // Same exclusion as above. No child renders a sheet today, but the rows are
751
+ // the one place a data-command-id describes a LIST ENTRY rather than a control,
752
+ // and half a rule is how that distinction gets lost.
753
+ if (live || (el.closest && el.closest('#command-sheet'))) return;
754
+ if (el.offsetParent || (el.getClientRects && el.getClientRects().length)) {
755
+ live = el;
756
+ liveOrigin = snapshot.child.surface || 'shell';
757
+ }
758
+ });
759
+ } catch (e) { /* torn down mid-lookup, or cross-origin one day */ }
760
+ }
761
+
762
+ closeSheet();
763
+ if (live && live.focus) {
764
+ if (live.scrollIntoView) live.scrollIntoView({ block: 'center' });
765
+ live.focus();
766
+ /* FALLS THROUGH when the control cannot be described, rather than returning.
767
+ focusFor() resolves upward through
768
+ `closest('button, [role="button"], a[href], input, select, textarea')`, and
769
+ three registered commands carry their id on a <label> whose <input> is a
770
+ DESCENDANT — filter.match-on and vector.show-kind — so the walk finds
771
+ nothing and it returns null. (That shape is deliberate: the id sits on the
772
+ label because that is what a screen reader names the control from.)
773
+
774
+ Returning here on a null entry would have left the PREVIOUS entry standing,
775
+ since setFocusEntry declines rather than assigning — reintroducing exactly
776
+ the stale-narration bug this commit exists to fix, one level down. Falling
777
+ through instead means the registry describes the command, which is a better
778
+ answer than the blank the old `snapshot.focus = focusFor(live)` produced. */
779
+ if (setFocusEntry(focusFor(live), liveOrigin)) {
780
+ paint();
781
+ return;
782
+ }
783
+ }
784
+
785
+ /* No control on screen — which is the NORMAL case for most of the list: every
786
+ menu.* command (the ≡ menu is display:none until opened), every steel.*
787
+ one (they live in an iframe), and anything registered without a
788
+ data-command-id in markup. Closing and doing nothing would make the
789
+ footer's "Enter — go to it" a promise the sheet breaks ~35 times out of 53.
790
+ So it puts the command's own entry in the band instead: the user still
791
+ learns what it does and where it lives, which is what they asked for. */
792
+ setFocusEntry({
793
+ label: cmd.label,
794
+ acts: cmd.actsOn ? cmd.actsOn.replace(/\{instance\}/g, 'the one you pick') : null,
795
+ group: cmd.group,
796
+ key: cmd.key,
797
+ tip: cmd.why || '',
798
+ disabled: false,
799
+ disabledReason: null,
800
+ commandId: cmd.id,
801
+ instance: null,
802
+ }, cmd.surface || 'shell');
803
+ paint();
804
+ }
805
+
806
+ function setActiveRow(next) {
807
+ if (!sheetRows.length) return;
808
+ if (activeRow >= 0 && sheetRows[activeRow]) {
809
+ sheetRows[activeRow].classList.remove('active');
810
+ sheetRows[activeRow].setAttribute('aria-selected', 'false');
811
+ }
812
+ activeRow = (next + sheetRows.length) % sheetRows.length;
813
+ var row = sheetRows[activeRow];
814
+ row.classList.add('active');
815
+ row.setAttribute('aria-selected', 'true');
816
+ // Focus stays in the filter box while the arrows move a highlight, so the
817
+ // only way a screen reader learns what is selected is activedescendant.
818
+ $sheetFilter.setAttribute('aria-activedescendant', row.id);
819
+ if (row.scrollIntoView) row.scrollIntoView({ block: 'nearest' });
820
+ }
821
+
822
+ /* Inertness. `inert` removes a subtree from the tab order, from pointer input
823
+ AND from the accessibility tree in one attribute — the aria-hidden +
824
+ pointer-events pair this app used before `inert` existed leaves the
825
+ background reachable by keyboard.
826
+
827
+ EVERY body child except the sheet, not just #app: #toast-container is a body
828
+ sibling too, and a toast carries a focusable close button, so inerting only
829
+ #app would let Tab walk out of the dialog into a toast. */
830
+ /* Restoring, not clearing. An earlier version set `inert = false` on every body
831
+ sibling when closing, which would have un-inerted anything that was ALREADY
832
+ inert before the sheet opened — this sheet is currently the only thing in the
833
+ app using `inert`, so it is latent rather than live, but "the second user of
834
+ inert silently breaks the first" is a bad thing to leave lying around. */
835
+ var inertBefore = null;
836
+
837
+ function setBackgroundInert(on) {
838
+ if (on) {
839
+ inertBefore = [];
840
+ Array.prototype.forEach.call(document.body.children, function (el) {
841
+ if (el === $sheet) return;
842
+ inertBefore.push([el, el.inert]);
843
+ el.inert = true;
844
+ });
845
+ return;
846
+ }
847
+ if (!inertBefore) return;
848
+ inertBefore.forEach(function (pair) { pair[0].inert = pair[1]; });
849
+ inertBefore = null;
850
+ }
851
+
852
+ function openSheet() {
853
+ if (!$sheet || sheetOpen || !enabled) return false;
854
+ /* Never stack on another dialog. Every .modal-backdrop here sits at the same
855
+ z-index (app.css records the bugs that caused), so a second one would be
856
+ ordered by DOM position rather than by what the user opened last. Declining
857
+ is the honest behaviour — `?` while a dialog is open is not a request to
858
+ bury it. */
859
+ if (document.querySelector('.modal-backdrop.show')) return false;
860
+
861
+ returnFocusTo = document.activeElement;
862
+ sheetOpen = true;
863
+ $sheet.hidden = false;
864
+ $sheet.classList.add('show');
865
+ setBackgroundInert(true);
866
+
867
+ /* If building the list throws, the background is already inert — and an app
868
+ nobody can focus is a far worse failure than a missing help sheet. So the
869
+ open unwinds itself rather than leaving the page dead to the keyboard. */
870
+ try {
871
+ $sheetFilter.value = '';
872
+ renderSheet();
873
+ $sheetFilter.focus();
874
+ } catch (e) {
875
+ closeSheet();
876
+ throw e; // still a bug worth seeing in the console, just not a fatal one
877
+ }
878
+ return true;
879
+ }
880
+
881
+ function closeSheet() {
882
+ if (!sheetOpen) return;
883
+ sheetOpen = false;
884
+ $sheet.classList.remove('show');
885
+ $sheet.hidden = true;
886
+ setBackgroundInert(false);
887
+ // Focus goes back where it came from. Dropping it on <body> is how a keyboard
888
+ // user gets stranded at the top of the document with no idea what happened.
889
+ if (returnFocusTo && returnFocusTo.focus && document.contains(returnFocusTo)) returnFocusTo.focus();
890
+ returnFocusTo = null;
891
+ }
892
+
893
+ function mountSheet() {
894
+ $sheet = document.getElementById('command-sheet');
895
+ if (!$sheet) return;
896
+ $sheetList = document.getElementById('cmd-sheet-list');
897
+ $sheetFilter = document.getElementById('cmd-sheet-filter');
898
+ $sheetSub = document.getElementById('cmd-sheet-sub');
899
+
900
+ document.getElementById('cmd-sheet-close').addEventListener('click', closeSheet);
901
+ var seeAll = document.getElementById('ix-all');
902
+ if (seeAll) seeAll.addEventListener('click', openSheet);
903
+
904
+ // Clicking the backdrop closes; clicking the dialog must not.
905
+ $sheet.addEventListener('mousedown', function (e) { if (e.target === $sheet) closeSheet(); });
906
+
907
+ $sheetFilter.addEventListener('input', renderSheet);
908
+
909
+ $sheet.addEventListener('keydown', function (e) {
910
+ if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); closeSheet(); return; }
911
+ if (e.key === 'ArrowDown') { e.preventDefault(); setActiveRow(activeRow + 1); return; }
912
+ if (e.key === 'ArrowUp') { e.preventDefault(); setActiveRow(activeRow - 1); return; }
913
+ if (e.key === 'Enter' && activeRow >= 0 && sheetRows[activeRow]) {
914
+ e.preventDefault();
915
+ sheetRows[activeRow].click();
916
+ return;
917
+ }
918
+ /* Tab trapping. `inert` on the regions behind is what makes this short:
919
+ the only focusable things left are inside the dialog, so the trap only
920
+ has to wrap the two ends. */
921
+ if (e.key === 'Tab') {
922
+ var focusable = $sheet.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');
923
+ if (!focusable.length) return;
924
+ var first = focusable[0], last = focusable[focusable.length - 1];
925
+ if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
926
+ else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
927
+ }
928
+ });
929
+ }
930
+
931
+ /* ── public surface ───────────────────────────────────────────────────────
932
+ aware.js pushes live state in. On mount, the band reads back only the last
933
+ Workspaces title because that surface can restore before this script loads. */
934
+
935
+ var Instructor = {
936
+ guidanceFor: guidanceFor, // exported for tests — pure
937
+ setWorkflow: function (wf) {
938
+ var was = (snapshot.workflow && snapshot.workflow.name) || null;
939
+ var now = (wf && wf.name) || null;
940
+ snapshot.workflow = wf || null;
941
+ /* Only on a real CHANGE OF WORKFLOW, never on a status repaint. aware.js
942
+ calls this from paintRunState, which fires on every run-state tick — so
943
+ clearing unconditionally would yank an entry out from under someone the
944
+ moment a run progressed. Comparing the name is what makes it "you moved
945
+ on" rather than "something ticked".
946
+
947
+ `was` must be non-null too: the FIRST paint of the session goes null → a
948
+ name, which is the app arriving rather than the user leaving anything.
949
+ Someone who pressed `?` in that window (the band mounts on
950
+ DOMContentLoaded, before aware.js has painted run state) would otherwise
951
+ watch their answer vanish as the page finished loading.
952
+
953
+ Known limit, deliberately not chased: two workflows sharing a display
954
+ name read as "no change". aware.js sends only `name`, so telling them
955
+ apart would mean widening the payload for a case whose whole cost is one
956
+ stale entry the user can dismiss with Escape. */
957
+ if (snapshot.focus && was && was !== now) { snapshot.focus = null; }
958
+ paint();
959
+ },
960
+ setWorkspace: function (context) {
961
+ var next = context && context.name
962
+ ? { name: context.name, landing: context.landing === true, projectId: context.projectId || null }
963
+ : null;
964
+ var was = snapshot.workspace;
965
+ snapshot.workspace = next;
966
+ if ((was && was.name) !== (next && next.name)
967
+ || (was && was.landing) !== (next && next.landing)
968
+ || (was && was.projectId) !== (next && next.projectId)) snapshot.focus = null;
969
+ paint();
970
+ },
971
+ explain: explainCurrent,
972
+ clear: clearFocusEntry,
973
+ childSnapshot: function () { return snapshot.child; },
974
+ isEnabled: function () { return enabled; },
975
+ setEnabled: setEnabled,
976
+ toggleEnabled: function () { setEnabled(!enabled); return enabled; },
977
+
978
+ /* Thin pass-throughs to commands.js, kept so callers and tests have one
979
+ import surface. The data lives there, not here. */
980
+ registerTemplate: function (id, meta) { return window.Commands && window.Commands.define(id, meta); },
981
+ templateIds: function () { return window.Commands ? window.Commands.ids() : []; },
982
+ resolve: function (el) { return resolveCommand(el); },
983
+ inventory: function (root) { return window.Commands ? window.Commands.inventory(root) : null; },
984
+ };
985
+
986
+ /* ── the bidirectional reporter seam ──────────────────────────────────────
987
+ A child surface (steel-editor.html and friends, same-origin iframes)
988
+ publishes a typed snapshot; the shell produces guidance and hands the
989
+ payload back. The child never derives guidance and never imports the
990
+ producer — that is what stops a second narrator appearing. */
991
+
992
+ var activeReporterWindow = null;
993
+
994
+ window.__instructorReady = function (childWin) {
995
+ /* Drop the outgoing frame's snapshot in the SAME step as adopting the new
996
+ reporter, so `activeReporterWindow` and `snapshot.child` always describe the
997
+ same document. In practice the old frame's pagehide has already cleared it —
998
+ but that is an ordering guarantee, and everything reading these two together
999
+ (the sheet's surface ordering, activate()'s child lookup and the origin it
1000
+ stamps) would silently attribute the NEW frame's controls to the OLD surface
1001
+ if it ever did not hold. One assignment is cheaper than depending on it.
1002
+ Nothing is lost: the new reporter's first report is one macrotask away. */
1003
+ if (childWin !== activeReporterWindow) snapshot.child = null;
1004
+ activeReporterWindow = childWin;
1005
+ };
1006
+
1007
+ window.__instructorReport = function (childSnap, childWin) {
1008
+ // A stale frame must never narrate. Ignore anything that is no longer the
1009
+ // live reporter, or whose document has been torn down / replaced.
1010
+ if (activeReporterWindow && childWin !== activeReporterWindow) return;
1011
+ try {
1012
+ if (!childWin || childWin.closed) return;
1013
+ if (!childWin.document || childWin.location.href === 'about:blank') return;
1014
+ } catch (e) { return; }
1015
+
1016
+ snapshot.child = childSnap || null;
1017
+ paint();
1018
+
1019
+ // shell → child: hand back what the producer made.
1020
+ try {
1021
+ var payload = guidanceFor(snapshot);
1022
+ if (childWin.__instructor && typeof childWin.__instructor.receiveGuidance === 'function') {
1023
+ childWin.__instructor.receiveGuidance(payload);
1024
+ }
1025
+ } catch (e) { /* frame went away mid-publish */ }
1026
+ };
1027
+
1028
+ /* `?` / F1 pressed inside a child frame. A keydown in an iframe never reaches
1029
+ this document, so a child forwards the key here rather than rendering a
1030
+ second sheet of its own — one producer, one sheet, one list showing every
1031
+ command instead of two showing half each. Returns whether it was handled,
1032
+ so the child knows whether to preventDefault. */
1033
+ window.__instructorKey = function (key) {
1034
+ if (!enabled) return false;
1035
+ if (key !== '?' && key !== 'F1') return false;
1036
+ // A child's armed command already owns the band, so explaining a control the
1037
+ // shell has focus on would be the wrong answer — go straight to the list.
1038
+ return openSheet();
1039
+ };
1040
+
1041
+ // A frame that unloads stops being the reporter, so its last snapshot cannot
1042
+ // keep painting a surface the user has left.
1043
+ window.__instructorReporterGone = function (childWin) {
1044
+ if (childWin === activeReporterWindow) {
1045
+ // Read BEFORE clearing: this is the surface that just died, and the entry is
1046
+ // dropped only if it came from THAT one. "Anything not the shell" would also
1047
+ // throw away an answer about a different child, which cannot happen today but
1048
+ // is a rule that stops being true the moment two frames can be up at once.
1049
+ var gone = (snapshot.child && snapshot.child.surface) || null;
1050
+ activeReporterWindow = null;
1051
+ snapshot.child = null;
1052
+ /* An on-demand entry captured while that surface was up describes a control
1053
+ that has just gone with it — including a `disabled` flag read off the real
1054
+ element, which would otherwise keep asserting "Not available right now"
1055
+ about a document that no longer exists. Clearing `child` alone was not
1056
+ enough, because guidanceFor consults `focus` FIRST: the stale entry did
1057
+ not merely linger, it hid the workflow readout underneath it.
1058
+ Entries captured on the shell are left alone — nothing about them died, and
1059
+ a shell button stays live under the overlay, so this really is a different
1060
+ set from "captured while a child happened to be open".
1061
+
1062
+ Clearing SILENTLY, with no "what you were reading is gone" note, because the
1063
+ user pressed Close and the cause is already plain — the strip's own No-Echo
1064
+ rule (see controlGuidance) says not to state what the screen makes obvious.
1065
+ The accepted trade-off: a teardown the user did NOT initiate (an external
1066
+ write invalidating the surface, a forced reload) reads the same way, and
1067
+ nothing here can tell the two apart. Named rather than fixed — a
1068
+ "that vanished" notice would be new UI for a rare case. */
1069
+ if (snapshot.focus && gone && snapshot.focus.originSurface === gone) {
1070
+ snapshot.focus = null;
1071
+ }
1072
+ paint();
1073
+ }
1074
+ };
1075
+
1076
+ function mount() {
1077
+ $band = document.getElementById('instructor');
1078
+ if (!$band) return;
1079
+ $chip = $band.querySelector('.ix-chip');
1080
+ $parts = $band.querySelector('.ix-parts');
1081
+ $ask = $band.querySelector('.ix-ask');
1082
+ $toggle = $band.querySelector('.ix-toggle');
1083
+
1084
+ // Default ON: only the literal '0' turns it off, so a brand-new user (no key
1085
+ // at all) and a user whose storage is unreadable both get the Instructor.
1086
+ try { enabled = localStorage.getItem(ENABLED_KEY) !== '0'; } catch (e) { enabled = true; }
1087
+
1088
+ try { collapsed = localStorage.getItem(COLLAPSE_KEY) === '1'; } catch (e) { collapsed = false; }
1089
+ setCollapsed(collapsed);
1090
+ applyEnabled();
1091
+
1092
+ $toggle.addEventListener('click', function () { setCollapsed(!collapsed); });
1093
+
1094
+ $ask.addEventListener('click', async function () {
1095
+ if ($ask.getAttribute('aria-busy') === 'true') return;
1096
+ var bridge = window.flolessBridge;
1097
+ if (!bridge || typeof bridge.requestInstructorHelp !== 'function') return;
1098
+
1099
+ // Capture the producer's complete answer at click time. Duplicate labels are common, so the
1100
+ // terminal AI gets the resolved command/instance and every visible fact, not a label-only ask.
1101
+ var g = guidanceFor(snapshot);
1102
+ if (g.tone === 'silent' && g.fallback) g = g.fallback;
1103
+ var context = {
1104
+ subject: g.ask || g.chip || $ask.dataset.subject || 'this FloLess context',
1105
+ commandId: g.commandId || undefined,
1106
+ instance: g.instance || undefined,
1107
+ tone: g.tone,
1108
+ facts: g.parts.slice(),
1109
+ surface: g.surface || snapshot.surface || 'shell',
1110
+ };
1111
+ var idleLabel = $ask.textContent;
1112
+ $ask.setAttribute('aria-busy', 'true');
1113
+ $ask.setAttribute('data-blocked-reason', 'Sending this request…');
1114
+ $ask.disabled = true;
1115
+ $ask.textContent = 'Sending…';
1116
+ try {
1117
+ await bridge.requestInstructorHelp(context);
1118
+ } finally {
1119
+ $ask.disabled = false;
1120
+ $ask.removeAttribute('aria-busy');
1121
+ $ask.removeAttribute('data-blocked-reason');
1122
+ $ask.textContent = idleLabel;
1123
+ try { $ask.focus(); } catch (e) { /* focus restoration is best-effort */ }
1124
+ }
1125
+ });
1126
+
1127
+ document.addEventListener('mouseover', function (e) {
1128
+ var t = e.target instanceof Element ? e.target : null;
1129
+ if (t) { lastHovered = t; lastHoveredAt = Date.now(); }
1130
+ }, true);
1131
+
1132
+ document.addEventListener('keydown', function (e) {
1133
+ // `?` is the everyday route, but it MUST yield to typing — this is a
1134
+ // prompt-native product and a literal "?" in a search box wins.
1135
+ if (e.key === '?' && !e.ctrlKey && !e.metaKey && !e.altKey) {
1136
+ if (isTyping(e.target) || isTyping(document.activeElement)) return;
1137
+ // Explain what you are on; with nothing to explain, show everything.
1138
+ // Asking for help while pointing at nothing in particular is a
1139
+ // reasonable way to say "what CAN I do here?".
1140
+ if (explainCurrent() || openSheet()) e.preventDefault();
1141
+ return;
1142
+ }
1143
+
1144
+ // PHASE 0b finding: yielding to typing makes `?` unreachable inside every
1145
+ // searchable popover — including the workflow picker, which is exactly
1146
+ // where the generated rows live. F1 is unbound app-wide and is safe to
1147
+ // press while a text field has focus, so it is the second route.
1148
+ if (e.key === 'F1' && !e.ctrlKey && !e.metaKey && !e.altKey) {
1149
+ if (explainCurrent() || openSheet()) e.preventDefault();
1150
+ }
1151
+ });
1152
+
1153
+ // Escape drops the on-demand entry and returns to the project readout. The
1154
+ // sheet handles its own Escape and stops it here, so one press never both
1155
+ // closes the sheet and clears the entry behind it.
1156
+ document.addEventListener('keydown', function (e) {
1157
+ if (e.key === 'Escape' && !sheetOpen && snapshot.focus) clearFocusEntry();
1158
+ });
1159
+
1160
+ mountSheet();
1161
+ // Workspaces restores its persisted mode before instructor.js loads. Its original
1162
+ // setWorkspaceTitle push therefore has no receiver; replay the bridge's stored visible
1163
+ // state now so the band never falls back to the hidden workflow after a reload.
1164
+ var bridge = window.flolessBridge;
1165
+ if (bridge && typeof bridge.getWorkspaceContext === 'function') {
1166
+ Instructor.setWorkspace(bridge.getWorkspaceContext());
1167
+ }
1168
+ paint();
1169
+ }
1170
+
1171
+ if (document.readyState === 'loading') {
1172
+ document.addEventListener('DOMContentLoaded', mount);
1173
+ } else {
1174
+ mount();
1175
+ }
1176
+
1177
+ window.Instructor = Instructor;
1178
+ })();