@floless/app 0.155.2 → 0.157.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/cli-actions.mjs +392 -0
  2. package/dist/floless-server.cjs +182734 -141519
  3. package/dist/schemas/drawing-check.profile.v1.schema.json +15 -2
  4. package/dist/schemas/steel.model.v2.schema.json +25 -1
  5. package/dist/skills/floless-app-actions/SKILL.md +199 -0
  6. package/dist/skills/floless-app-approval/SKILL.md +8 -5
  7. package/dist/skills/floless-app-bridge/SKILL.md +12 -9
  8. package/dist/skills/floless-app-knowledge/SKILL.md +50 -14
  9. package/dist/skills/floless-app-new-workflow/SKILL.md +26 -10
  10. package/dist/skills/floless-app-onboarding/SKILL.md +31 -1
  11. package/dist/skills/floless-app-onboarding/references/aware-runtime.md +4 -4
  12. package/dist/skills/floless-app-queue/SKILL.md +10 -6
  13. package/dist/skills/floless-app-report-issue/SKILL.md +15 -12
  14. package/dist/skills/floless-app-rfi/SKILL.md +98 -73
  15. package/dist/skills/floless-app-routines/SKILL.md +27 -15
  16. package/dist/skills/floless-app-routines/references/routines-api.md +8 -2
  17. package/dist/skills/floless-app-steel-model/SKILL.md +1 -1
  18. package/dist/skills/floless-app-steel-model/references/detail-from-a-screenshot.md +4 -2
  19. package/dist/skills/floless-app-tweak-contract/SKILL.md +25 -5
  20. package/dist/skills/floless-app-workflows/SKILL.md +50 -13
  21. package/dist/skills/floless-app-workflows/references/agent-steps.md +119 -0
  22. package/dist/web/agent-steps.js +1750 -0
  23. package/dist/web/agents.js +33 -8
  24. package/dist/web/app.css +681 -4
  25. package/dist/web/app.js +111 -11
  26. package/dist/web/aware-update-client.js +1 -0
  27. package/dist/web/aware.js +1257 -202
  28. package/dist/web/chat-landing-scene.js +372 -0
  29. package/dist/web/chat.css +254 -1
  30. package/dist/web/chat.js +2657 -87
  31. package/dist/web/commands-drawing-check.js +17 -0
  32. package/dist/web/commands-shell.js +1108 -4
  33. package/dist/web/commands-steel.js +6 -0
  34. package/dist/web/connections.js +1 -0
  35. package/dist/web/drawing-check-editor.html +33 -5
  36. package/dist/web/drawing-check-editor.js +538 -22
  37. package/dist/web/drawing-check-overlay.js +13 -0
  38. package/dist/web/flo-avatar.js +28 -3
  39. package/dist/web/guide.js +7 -2
  40. package/dist/web/index.html +171 -7
  41. package/dist/web/instructor.js +6 -4
  42. package/dist/web/leave-guard.js +4 -2
  43. package/dist/web/left-pane.js +8 -3
  44. package/dist/web/model-revit-module.js +15 -0
  45. package/dist/web/model-view-query.js +12 -2
  46. package/dist/web/model-viewport-revit-adapter.js +3 -1
  47. package/dist/web/pages.js +891 -36
  48. package/dist/web/panels.js +8 -5
  49. package/dist/web/parser-setup-recovery.js +12 -4
  50. package/dist/web/project-access.js +549 -0
  51. package/dist/web/project-reconciliation.js +357 -0
  52. package/dist/web/report-files.js +50 -0
  53. package/dist/web/revit-editor.js +116 -27
  54. package/dist/web/startup-admission.js +132 -0
  55. package/dist/web/steel-3d-core.js +9 -0
  56. package/dist/web/steel-editor.html +642 -22
  57. package/dist/web/steel-model-v2-commands.js +63 -5
  58. package/dist/web/step-rename.js +287 -0
  59. package/dist/web/terminal-requests.js +590 -0
  60. package/dist/web/tool-updates.js +148 -13
  61. package/dist/web/workspace-root-management.js +39 -0
  62. package/dist/web/workspaces.js +1879 -74
  63. package/launch.mjs +82 -2
  64. package/package.json +3 -1
@@ -0,0 +1,590 @@
1
+ /*
2
+ * Requests from your terminal (#2248).
3
+ *
4
+ * `floless-app do <action>` runs reads and reversible changes straight away, but anything it may not do on its
5
+ * own — a real workflow run, anything destructive, a step only a person does — becomes a one-use request that
6
+ * the person answers HERE (the owner's ruling: the terminal has no `--yes`). A chat's requests show as cards in
7
+ * its conversation; a terminal has no conversation, so this file is where they appear:
8
+ *
9
+ * - a quiet notice (bottom right, never steals focus) when one arrives or is waiting when the page opens;
10
+ * - a dialog, opened from the notice or from the link the terminal printed (`/?proposal=<id>`), showing each
11
+ * request as the same card the chat uses: what it will do, why it asks first, Not now / Run it, then
12
+ * Running → Done (View report) / Not done.
13
+ *
14
+ * Nothing runs from the terminal's side: only a click on Run it here does it, and FloLess re-checks first that
15
+ * the approved version is still the one shown. Opening the link never confirms anything. Esc closes the dialog
16
+ * and leaves every request waiting.
17
+ */
18
+ (() => {
19
+ 'use strict';
20
+
21
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
22
+ const CONFIRM_VERBS = { 'workflows.run': 'Run it', 'routines.run': 'Run it', 'projects.archive': 'Archive it', 'projects.unarchive': 'Bring it back',
23
+ // #2363: what each step does on the window's side, so none of them says a bare "Do it".
24
+ 'models.start-import': 'Choose the file', 'tekla.start-upload': 'Choose the source', 'models.retry-import': 'Try it again',
25
+ 'models.cancel-import': 'Cancel it', 'tekla.cancel-import': 'Cancel it', 'parser-setup.start-fresh': 'Open the review',
26
+ 'models.retry-revit-setup': 'Try setup again', 'models.retry-tekla-setup': 'Try setup again',
27
+ 'workspace-root.review-retirement': 'Open the review', 'workspace-root.confirm-retirement': 'Record it' };
28
+ const EYEBROWS = { write: 'Needs your OK', destructive: 'Needs your OK', 'human-only': 'Your decision' };
29
+ const FINAL = new Set(['done', 'failed', 'cancelled', 'declined', 'expired', 'superseded', 'unknown']);
30
+
31
+ /** Requests shown in the dialog, by id, in the order they arrived. */
32
+ const shown = new Map();
33
+ let backdrop = null;
34
+ let list = null;
35
+ let live = null;
36
+ let returnFocus = null;
37
+ let notice = null;
38
+ let noticeRetry = 0;
39
+ let focusId = null;
40
+ /** The request the terminal's link named: outlined so the person sees which one the link meant. */
41
+ let linkedId = null;
42
+
43
+ const api = async (method, path) => {
44
+ await globalThis.flolessStartupAdmission?.admit(path, { method });
45
+ const res = await fetch(path, { method, credentials: 'same-origin', headers: method === 'POST' ? { 'content-type': 'application/json' } : {}, body: method === 'POST' ? '{}' : undefined });
46
+ let body = null;
47
+ try { body = await res.json(); } catch { body = null; }
48
+ return { status: res.status, ok: res.ok && body?.ok === true, body: body || {} };
49
+ };
50
+
51
+ const button = (label, commandId, proposalId, summary, className = '') => {
52
+ const node = document.createElement('button');
53
+ node.type = 'button';
54
+ node.textContent = label;
55
+ if (className) node.className = className;
56
+ node.dataset.commandId = proposalId ? `${commandId}#${proposalId}` : commandId;
57
+ if (summary) node.dataset.commandInstanceLabel = summary;
58
+ return node;
59
+ };
60
+
61
+ const ago = (iso) => {
62
+ const mins = Math.max(0, Math.round((Date.now() - Date.parse(iso)) / 60000));
63
+ return mins < 1 ? 'Asked just now' : mins === 1 ? 'Asked 1 minute ago' : mins < 60 ? `Asked ${mins} minutes ago` : 'Asked over an hour ago';
64
+ };
65
+
66
+ // A route's refusal can be a bare fragment; a card shows it as a sentence, with the next step after it.
67
+ const asSentence = (text) => { const t = String(text || '').trim(); return t ? t.charAt(0).toUpperCase() + t.slice(1) + (/[.!?…]$/.test(t) ? '' : '.') : ''; };
68
+ const verbFor = (p) => (p.risk === 'human-only' ? 'wants you to' : 'wants to');
69
+ const whatFor = (p) => (p.actionId === 'workflows.run' && /^Run /.test(p.summary || '') ? String(p.summary).replace(/^Run (\S+).*$/, 'run $1') : String(p.title || 'do something').replace(/^[A-Z](?![A-Z])/, (c) => c.toLowerCase()));
70
+
71
+ // ── The dialog ────────────────────────────────────────────────────────────────────────────────────
72
+
73
+ function ensureDialog() {
74
+ if (backdrop) return;
75
+ backdrop = document.createElement('div');
76
+ backdrop.className = 'modal-backdrop terminal-requests-backdrop';
77
+ backdrop.id = 'terminal-requests-modal';
78
+ backdrop.setAttribute('role', 'dialog');
79
+ backdrop.setAttribute('aria-modal', 'true');
80
+ backdrop.setAttribute('aria-labelledby', 'terminal-requests-title');
81
+ backdrop.setAttribute('aria-describedby', 'terminal-requests-sub');
82
+ const modal = document.createElement('div');
83
+ modal.className = 'modal terminal-requests';
84
+ const title = document.createElement('div');
85
+ title.className = 'modal-title';
86
+ title.id = 'terminal-requests-title';
87
+ title.tabIndex = -1;
88
+ title.textContent = 'From your terminal';
89
+ const sub = document.createElement('div');
90
+ sub.className = 'modal-sub';
91
+ sub.id = 'terminal-requests-sub';
92
+ sub.textContent = 'Your terminal asked FloLess to do this. Nothing runs until you click.';
93
+ list = document.createElement('div');
94
+ list.className = 'terminal-requests-list';
95
+ live = document.createElement('p');
96
+ live.className = 'sr-only';
97
+ live.setAttribute('aria-live', 'polite');
98
+ const actions = document.createElement('div');
99
+ actions.className = 'modal-actions terminal-requests-foot';
100
+ const hint = document.createElement('span');
101
+ hint.className = 'terminal-requests-hint';
102
+ hint.textContent = 'Esc closes this. Your requests stay waiting.';
103
+ const close = button('Close', 'shell.terminal-request-close', '', '');
104
+ close.addEventListener('click', closeDialog);
105
+ actions.append(hint, close);
106
+ modal.append(title, sub, list, live, actions);
107
+ backdrop.append(modal);
108
+ backdrop.addEventListener('mousedown', (event) => { if (event.target === backdrop) closeDialog(); });
109
+ backdrop.addEventListener('keydown', (event) => {
110
+ if (event.key === 'Escape') { event.stopPropagation(); closeDialog(); return; }
111
+ if (event.key === 'Tab') trapTab(event, modal);
112
+ });
113
+ document.body.append(backdrop);
114
+ }
115
+
116
+ function trapTab(event, modal) {
117
+ const focusable = [...modal.querySelectorAll('button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])')].filter((n) => n.offsetParent !== null);
118
+ if (!focusable.length) return;
119
+ const first = focusable[0];
120
+ const last = focusable[focusable.length - 1];
121
+ if (event.shiftKey && (document.activeElement === first || !modal.contains(document.activeElement))) { event.preventDefault(); last.focus(); }
122
+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
123
+ }
124
+
125
+ function openDialog(focusProposal, fromLink = false) {
126
+ ensureDialog();
127
+ hideNotice();
128
+ focusId = focusProposal || null;
129
+ if (fromLink) linkedId = focusId;
130
+ const wasOpen = backdrop.classList.contains('show');
131
+ if (!wasOpen) returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
132
+ backdrop.classList.add('show');
133
+ paint();
134
+ if (!wasOpen) {
135
+ const card = focusId ? list.querySelector(`[data-proposal-id="${CSS.escape(focusId)}"] .terminal-request-title`) : null;
136
+ (card || backdrop.querySelector('#terminal-requests-title'))?.focus({ preventScroll: false });
137
+ }
138
+ }
139
+
140
+ function closeDialog() {
141
+ if (!backdrop?.classList.contains('show')) return;
142
+ backdrop.classList.remove('show');
143
+ // Finished requests leave the list once the person has seen them; waiting ones stay for next time.
144
+ for (const [id, entry] of shown) if (entry.gone || FINAL.has(entry.p.state) || (entry.p.state === 'proposed' && !answerable(entry.p))) shown.delete(id);
145
+ const target = returnFocus && document.contains(returnFocus) ? returnFocus : null;
146
+ returnFocus = null;
147
+ target?.focus({ preventScroll: true });
148
+ if (waiting().length || running().length) showNotice();
149
+ }
150
+
151
+ const dialogOpen = () => Boolean(backdrop?.classList.contains('show'));
152
+ // #2420: one asked before FloLess restarted is answerable too, until its own time runs out (answering shows it again).
153
+ const answerable = (p) => p.state === 'proposed' && Date.parse(p.expiresAt) > Date.now();
154
+ // A step only a person does is never "done" in FloLess's records: once its screen was opened here, it has done its
155
+ // job in this window and stops asking (it still expires on the server, and the terminal was told so).
156
+ const waiting = () => [...shown.values()].filter((e) => !e.gone && !e.opened && answerable(e.p)).map((e) => e.p);
157
+ // What the notice speaks of besides requests still waiting: a request the person confirmed that is running, and one that
158
+ // ended while the dialog was closed (its result is still one click away).
159
+ const running = () => [...shown.values()].filter((e) => !e.gone && e.p.state === 'executing').map((e) => e.p);
160
+ const finished = () => [...shown.values()].filter((e) => !e.gone && ['done', 'failed'].includes(e.p.state)).map((e) => e.p);
161
+
162
+ /** Repaint the list. Repainting destroys the focused control, so focus is put back (on the same control, else its card,
163
+ * else the dialog's title): otherwise Esc and Tab, which are heard on the dialog, would stop working after a click. */
164
+ function paint() {
165
+ if (!list) return;
166
+ const active = document.activeElement;
167
+ const had = active && active !== document.body && list.contains(active)
168
+ ? { command: active.dataset?.commandId || '', card: active.closest?.('[data-proposal-id]')?.dataset.proposalId || '' } : null;
169
+ paintList();
170
+ if (!had) return;
171
+ const target = (had.command && [...list.querySelectorAll('[data-command-id]')].find((n) => n.dataset.commandId === had.command && !n.disabled))
172
+ || (had.card && list.querySelector(`[data-proposal-id="${CSS.escape(had.card)}"] .terminal-request-title`))
173
+ || backdrop.querySelector('#terminal-requests-title');
174
+ target?.focus({ preventScroll: true });
175
+ }
176
+
177
+ function paintList() {
178
+ list.replaceChildren();
179
+ if (!shown.size) {
180
+ const empty = document.createElement('p');
181
+ empty.className = 'terminal-requests-empty';
182
+ empty.textContent = 'Nothing is waiting. Requests from your terminal show here.';
183
+ list.append(empty);
184
+ return;
185
+ }
186
+ const entries = [...shown.values()];
187
+ // The request the link named goes first.
188
+ if (focusId) entries.sort((a, b) => (a.p.id === focusId ? -1 : b.p.id === focusId ? 1 : 0));
189
+ for (const entry of entries) list.append(card(entry));
190
+ }
191
+
192
+ function card(entry) {
193
+ const p = entry.p;
194
+ const risk = ['write', 'destructive', 'human-only'].includes(p.risk) ? p.risk : 'destructive';
195
+ const summary = String(p.summary || p.title || 'A FloLess action');
196
+ const node = document.createElement('section');
197
+ node.className = `ai-chat-filter-card ai-chat-action-card terminal-request risk-${risk}`;
198
+ node.dataset.proposalId = p.id;
199
+ node.dataset.state = entry.gone ? 'gone' : p.state;
200
+ if (p.id === linkedId) node.classList.add('is-linked');
201
+ node.setAttribute('role', 'group');
202
+ const titleId = `terminal-request-title-${p.id}`;
203
+ node.setAttribute('aria-labelledby', titleId);
204
+ const status = document.createElement('p');
205
+ status.className = 'ai-chat-filter-note ai-chat-action-status';
206
+ status.setAttribute('role', 'status');
207
+
208
+ const stale = entry.gone ? ['FloLess can’t find that request', 'It may be from before FloLess last restarted. Nothing ran. Ask your terminal to try again.']
209
+ : p.state === 'expired' && p.restarted && p.supersededBy
210
+ ? ['Shown again', 'FloLess restarted after your terminal asked, so the request is shown again as it works now. Nothing ran.']
211
+ : p.state === 'expired' && p.result?.code === 'asked-again'
212
+ ? ['Your terminal asked for this again', 'FloLess restarted after it first asked, so the newer request is shown instead. Nothing ran.']
213
+ : p.state === 'expired' || (p.state === 'proposed' && Date.parse(p.expiresAt) <= Date.now())
214
+ ? ['This request expired', 'It waited too long, so FloLess dropped it. Nothing ran. Ask your terminal again if you still want it.']
215
+ : p.state === 'superseded' ? ['Your terminal’s request was replaced', `${p.changedNote || 'Something changed after it was asked.'} This one can’t be run. Nothing ran.`]
216
+ : p.state === 'declined' ? [`Not run: ${summary}`, 'You chose Not now. Nothing happened. Ask your terminal again if you change your mind.']
217
+ : p.state === 'cancelled' ? [`Stopped: ${summary}`, 'Work already sent to the host may remain.']
218
+ : null;
219
+ if (stale) {
220
+ node.classList.add('is-collapsed');
221
+ const head = document.createElement('strong');
222
+ head.className = 'terminal-request-title';
223
+ head.id = titleId;
224
+ head.tabIndex = -1;
225
+ head.textContent = stale[0];
226
+ const line = document.createElement('p');
227
+ line.className = 'ai-chat-action-line';
228
+ line.textContent = stale[1];
229
+ node.append(head, line);
230
+ return node;
231
+ }
232
+
233
+ const head = document.createElement('div');
234
+ head.className = 'ai-chat-filter-card-head';
235
+ const named = document.createElement('div');
236
+ named.className = 'ai-chat-action-named';
237
+ const eyebrow = document.createElement('span');
238
+ eyebrow.className = 'guide-move-eyebrow';
239
+ eyebrow.textContent = p.state === 'proposed' ? EYEBROWS[risk] : 'From your terminal';
240
+ const strong = document.createElement('strong');
241
+ strong.className = 'terminal-request-title';
242
+ strong.id = titleId;
243
+ strong.tabIndex = -1;
244
+ strong.textContent = String(p.title || 'A FloLess action');
245
+ named.append(eyebrow, strong);
246
+ head.append(named);
247
+ const badge = { executing: 'Running', done: 'Done', failed: 'Not done', unknown: 'Unknown' }[p.state];
248
+ if (badge) {
249
+ const b = document.createElement('span');
250
+ b.className = 'ai-chat-filter-state';
251
+ b.textContent = badge;
252
+ head.append(b);
253
+ }
254
+ node.append(head);
255
+ // A step only a person does has no confirm to show again: its screen opens as it is now either way.
256
+ const askedBeforeRestart = p.state === 'proposed' && p.restarted && risk !== 'human-only';
257
+ if (askedBeforeRestart) {
258
+ const before = document.createElement('p');
259
+ before.className = 'ai-chat-filter-note ai-chat-action-changed terminal-request-restarted';
260
+ before.textContent = 'Your terminal asked for this before FloLess restarted. FloLess may have changed since, so it will show the request again as it works now. Nothing runs until you confirm that one.';
261
+ node.append(before);
262
+ }
263
+ if (p.changedNote && p.state === 'proposed') {
264
+ const changed = document.createElement('p');
265
+ changed.className = 'ai-chat-filter-note ai-chat-action-changed';
266
+ changed.textContent = String(p.changedNote);
267
+ node.append(changed);
268
+ }
269
+ const sum = document.createElement('p');
270
+ sum.className = 'ai-chat-action-summary';
271
+ sum.textContent = summary;
272
+ node.append(sum);
273
+
274
+ if (p.state === 'done') {
275
+ node.classList.add('is-done');
276
+ // A step this window was handed but could not take is said here, never left reading as done.
277
+ status.textContent = entry.error || (p.next ? 'Done. Its result is ready to view.' : String(p.doneNote || 'Done.'));
278
+ if (p.next) {
279
+ const actions = document.createElement('div');
280
+ actions.className = 'ai-chat-filter-actions';
281
+ const view = button(String(p.next.label || 'View result'), 'shell.terminal-request-view', p.id, summary);
282
+ view.dataset.tip = 'Opens what this made. Nothing runs again.';
283
+ view.addEventListener('click', () => {
284
+ view.disabled = true;
285
+ view.setAttribute('aria-busy', 'true');
286
+ void openScreen(p.next, status, true).finally(() => { view.disabled = false; view.removeAttribute('aria-busy'); });
287
+ });
288
+ actions.append(view);
289
+ node.append(actions);
290
+ }
291
+ node.append(status);
292
+ return node;
293
+ }
294
+ if (p.state === 'failed') {
295
+ node.classList.add('is-failed');
296
+ status.textContent = `${asSentence(p.result?.message) || 'It did not complete.'} Ask your terminal to try again if you still want it.`;
297
+ node.append(status);
298
+ return node;
299
+ }
300
+ if (p.state === 'unknown') {
301
+ status.textContent = 'FloLess restarted while this was running, so how it ended is not known. Check the result before asking again.';
302
+ node.append(status);
303
+ return node;
304
+ }
305
+
306
+ const meta = document.createElement('p');
307
+ meta.className = 'ai-chat-filter-note terminal-request-meta';
308
+ meta.textContent = `${ago(p.createdAt)} · ${p.riskReason || ''}`.replace(/ · $/, '');
309
+ node.append(meta);
310
+ const actions = document.createElement('div');
311
+ actions.className = 'ai-chat-filter-actions';
312
+ if (p.state === 'executing') {
313
+ status.textContent = p.actionId === 'workflows.run' || p.actionId === 'routines.run' ? 'Running…' : 'Working…';
314
+ if (p.actionId === 'workflows.run') {
315
+ const stop = button('Stop', 'shell.terminal-request-stop', p.id, summary);
316
+ stop.dataset.tip = 'Asks the run to stop. Work already sent to the host may remain.';
317
+ stop.disabled = Boolean(entry.busy);
318
+ stop.addEventListener('click', () => { void answer(entry, 'cancel'); });
319
+ actions.append(stop);
320
+ }
321
+ node.append(actions, status);
322
+ return node;
323
+ }
324
+ const later = button('Not now', 'shell.terminal-request-not-now', p.id, summary);
325
+ later.dataset.tip = risk === 'human-only' ? 'Sets this request aside. Nothing changes.' : 'Sets this request aside. Nothing runs.';
326
+ later.disabled = Boolean(entry.busy);
327
+ later.addEventListener('click', () => { void answer(entry, 'decline'); });
328
+ if (risk === 'human-only') {
329
+ const screen = p.screen || {};
330
+ const open = button(String(screen.label || 'Open it'), 'shell.terminal-request-open', p.id, summary, 'ai-chat-filter-apply');
331
+ open.dataset.tip = 'Opens the screen where you do this yourself. Nothing runs from here.';
332
+ open.addEventListener('click', async () => { if (await openScreen(screen, status, false)) { entry.opened = true; closeDialog(); } });
333
+ actions.append(later, open);
334
+ const note = document.createElement('p');
335
+ note.className = 'ai-chat-filter-note';
336
+ note.textContent = 'Only you can do this. Nothing has been done.';
337
+ status.textContent = entry.error || '';
338
+ node.append(actions, note, status);
339
+ return node;
340
+ }
341
+ const verbLabel = askedBeforeRestart ? 'Check it again' : (CONFIRM_VERBS[p.actionId] || 'Do it');
342
+ const confirm = button(entry.busy === 'confirm' ? (askedBeforeRestart ? 'Checking…' : 'Starting…') : verbLabel,
343
+ askedBeforeRestart ? 'shell.terminal-request-check-again' : 'shell.terminal-request-confirm', p.id, summary, 'ai-chat-filter-apply');
344
+ confirm.dataset.tip = askedBeforeRestart ? 'Shows this request again as it works now. Nothing runs yet.'
345
+ : risk === 'destructive' ? 'Runs it now, for real. FloLess checks first that nothing changed since your terminal asked.'
346
+ : 'Makes this change now. FloLess checks first that nothing changed since your terminal asked.';
347
+ confirm.disabled = Boolean(entry.busy);
348
+ if (entry.busy === 'confirm') confirm.setAttribute('aria-busy', 'true');
349
+ confirm.addEventListener('click', () => { void answer(entry, 'confirm'); });
350
+ actions.append(later, confirm);
351
+ const pending = document.createElement('p');
352
+ pending.className = 'ai-chat-filter-note';
353
+ pending.textContent = entry.busy === 'confirm' ? (askedBeforeRestart ? 'Checking it now…' : 'Starting it now…') : askedBeforeRestart ? 'Nothing has run yet.' : p.expected ? 'Nothing has run yet. It uses this as it is now. If it changes before you confirm, you will be asked again.'
354
+ : 'Nothing has run yet.';
355
+ status.textContent = entry.error || '';
356
+ node.append(actions, pending, status);
357
+ return node;
358
+ }
359
+
360
+ /** Open a screen a request names (a step only a person does, or what a finished run made). Nothing runs. */
361
+ async function openScreen(screen, status, close) {
362
+ let opened = false;
363
+ let why = '';
364
+ // Opening can take a few seconds (FloLess reads the workflow list first); say so, so the click is never silent.
365
+ status.textContent = 'Opening it…';
366
+ try {
367
+ if (screen?.view === 'workflow-report' && screen.workflowId && typeof window.flolessBridge?.openAppReport === 'function') {
368
+ await window.flolessBridge.openAppReport(screen.workflowId, screen.runId || null); opened = true;
369
+ } else if (screen?.view === 'workflow' && screen.workflowId && typeof window.flolessBridge?.openApp === 'function') {
370
+ await window.flolessBridge.openApp(screen.workflowId); opened = true;
371
+ } else if (screen?.view === 'project' && screen.projectId && typeof window.flolessWorkspaces?.openChatOwner === 'function') {
372
+ await window.flolessWorkspaces.openChatOwner({ kind: 'project', projectId: screen.projectId }); opened = true;
373
+ } else if (['workspaces', 'workflows'].includes(screen?.view) && typeof window.flolessWorkspaces?.setMode === 'function') {
374
+ await window.flolessWorkspaces.setMode(screen.view); opened = true;
375
+ } else if (screen?.view === 'tool-update-policy' && typeof window.openToolUpdatePolicy === 'function') {
376
+ window.openToolUpdatePolicy(); opened = true;
377
+ }
378
+ } catch (error) {
379
+ // The bridge throws sentences written for the person (e.g. "This window no longer holds that run's report…").
380
+ opened = false;
381
+ why = typeof error?.message === 'string' ? error.message : '';
382
+ }
383
+ if (!opened) { status.textContent = why || 'FloLess couldn’t open that from here. Open it from Workflows or Workspaces instead.'; announce(status.textContent); return false; }
384
+ if (close) closeDialog();
385
+ return true;
386
+ }
387
+
388
+ async function answer(entry, verb) {
389
+ if (entry.busy) return;
390
+ entry.busy = verb;
391
+ entry.error = '';
392
+ paint();
393
+ const title = String(entry.p.title || 'the request');
394
+ // A fresh card offered in its place is where the person answers next, so focus goes to its button.
395
+ let freshId = '';
396
+ try {
397
+ const { ok, body, status } = await api('POST', `/api/actions/proposals/${encodeURIComponent(entry.p.id)}/${verb}`);
398
+ if (ok && body.proposal) {
399
+ entry.p = body.proposal;
400
+ announce(verb === 'confirm' ? `${title}: started.` : verb === 'decline' ? 'Nothing ran.' : `Asked ${title} to stop.`);
401
+ // A step only this window may take (a model source, the setup review, Stop FloLess) is taken here once confirmed,
402
+ // exactly as a chat card does: the request stays running until this window says how the step went.
403
+ if (verb === 'confirm' && entry.p.browserStep) {
404
+ entry.error = typeof window.flolessRunBrowserStep === 'function'
405
+ ? await window.flolessRunBrowserStep(entry.p.browserStep)
406
+ : 'FloLess could not take this step from here. Open the project or screen it names and do it there.';
407
+ // A Stop FloLess that went ahead is settled by the server when it accepts the stop; this window can no longer report.
408
+ const stopped = entry.p.browserStep.flow === 'stop-app' && !entry.error;
409
+ const settled = !stopped && typeof window.flolessReportBrowserStep === 'function' ? await window.flolessReportBrowserStep(entry.p.id, entry.error) : null;
410
+ if (settled) entry.p = settled;
411
+ // The step opened something in this window (a project, a review). This dialog sits over it, so step aside.
412
+ if (!entry.error) closeDialog();
413
+ }
414
+ } else if (body.fresh) {
415
+ // It changed or expired: the old card says so, and the fresh one is listed first to answer instead.
416
+ const restarted = Boolean(entry.p.restarted);
417
+ if (body.proposal) entry.p = body.proposal;
418
+ shown.set(body.fresh.id, { p: body.fresh, busy: '', error: '' });
419
+ focusId = body.fresh.id;
420
+ freshId = body.fresh.id;
421
+ announce(restarted ? 'Request shown again as it works now. Nothing has run.' : body.error || 'It changed after your terminal asked. The current request is shown first.');
422
+ } else {
423
+ if (body.proposal) entry.p = body.proposal;
424
+ entry.error = status === 404 ? 'FloLess no longer has that request. Ask your terminal to try again.'
425
+ : (typeof body.error === 'string' && body.error) || 'FloLess could not do that just now. Try again in a moment.';
426
+ }
427
+ } catch {
428
+ entry.error = 'FloLess could not be reached. Check that it is still running, then try again.';
429
+ } finally {
430
+ entry.busy = '';
431
+ paint();
432
+ if (freshId && dialogOpen()) {
433
+ const fresh = list.querySelector(`[data-proposal-id="${CSS.escape(freshId)}"]`);
434
+ (fresh?.querySelector('.ai-chat-filter-apply') || fresh?.querySelector('.terminal-request-title'))?.focus({ preventScroll: true });
435
+ }
436
+ // #2318: the card's status line is created afresh on every repaint, and a live region that is inserted (not
437
+ // changed) is often not read out. The dialog's own live region is what says it.
438
+ if (entry.error) announce(entry.error);
439
+ // Esc while it was starting: the dialog is gone, so the notice carries "running" instead.
440
+ if (!dialogOpen()) showNotice();
441
+ // A last "Not now" leaves nothing to decide: close and say so.
442
+ if (verb === 'decline' && !entry.error && !waiting().length && ![...shown.values()].some((e) => e.p.state === 'executing')) closeDialog();
443
+ }
444
+ }
445
+
446
+ function announce(text) { if (live) live.textContent = text; }
447
+
448
+ // ── Keeping up with the server ────────────────────────────────────────────────────────────────────
449
+
450
+ async function load(id) {
451
+ if (!UUID.test(id)) return null;
452
+ const { status, ok, body } = await api('GET', `/api/actions/proposals/${encodeURIComponent(id)}`);
453
+ if (ok && body.proposal?.origin?.kind === 'cli') return { p: body.proposal };
454
+ if (status === 404) return { gone: true };
455
+ return null;
456
+ }
457
+
458
+ /** A request changed (SSE names it by id): read it back and repaint, or tell the person a new one arrived. */
459
+ async function refresh(id) {
460
+ const got = await load(id).catch(() => null);
461
+ if (!got || got.gone) return;
462
+ const known = shown.get(id);
463
+ const before = known?.p.state;
464
+ if (known) { if (!adopt(known, got.p)) return; }
465
+ else if (got.p.state === 'proposed') shown.set(id, { p: got.p, busy: '', error: '' });
466
+ else return;
467
+ if (dialogOpen()) {
468
+ paint();
469
+ if (!known) announce('1 more request from your terminal.');
470
+ else if (got.p.state === 'done') announce(`${got.p.title}: done.`);
471
+ // A notice the person set aside with × stays set aside; one that is showing is redrawn (or removed once nothing waits).
472
+ } else if (!known || notice || known.p.state !== before) showNotice();
473
+ }
474
+
475
+ /** Take a newer copy of a request; an older answer arriving late (a slow read, a click's own reply) never wins. */
476
+ function adopt(entry, p) {
477
+ if (entry.p.updatedAt && p.updatedAt && p.updatedAt < entry.p.updatedAt) return false;
478
+ entry.p = p;
479
+ return true;
480
+ }
481
+
482
+ /** Every request still waiting (on first load and after a reconnect, which may have missed events). */
483
+ async function resync() {
484
+ let body;
485
+ try { ({ body } = await api('GET', '/api/actions/proposals')); } catch { return; }
486
+ const open = Array.isArray(body.proposals) ? body.proposals : [];
487
+ let added = 0;
488
+ for (const p of open) {
489
+ if (shown.has(p.id)) adopt(shown.get(p.id), p);
490
+ else { shown.set(p.id, { p, busy: '', error: '' }); added++; }
491
+ }
492
+ // One this window knew as waiting or running that is no longer open was answered while it was not listening
493
+ // (a reconnect misses events): read it back, so no stale Run it stays on screen.
494
+ const openIds = new Set(open.map((p) => p.id));
495
+ const missed = [...shown.values()].filter((e) => !e.gone && !openIds.has(e.p.id) && (e.p.state === 'proposed' || e.p.state === 'executing'));
496
+ await Promise.all(missed.map(async (e) => {
497
+ const got = await load(e.p.id).catch(() => null);
498
+ if (got?.p) adopt(e, got.p);
499
+ else if (got?.gone) e.gone = true;
500
+ }));
501
+ if (dialogOpen()) paint();
502
+ else if (added || (missed.length && notice)) showNotice();
503
+ }
504
+
505
+ // ── The quiet notice ──────────────────────────────────────────────────────────────────────────────
506
+
507
+ function hideNotice() { notice?.remove(); notice = null; }
508
+
509
+ function showNotice() {
510
+ const open = waiting();
511
+ const going = running();
512
+ const ended = finished();
513
+ if ((!open.length && !going.length && !ended.length) || dialogOpen()) { hideNotice(); return; }
514
+ // Never on top of another dialog the person is in the middle of: try again once it has closed.
515
+ if (document.querySelector('.modal-backdrop.show')) {
516
+ hideNotice();
517
+ clearTimeout(noticeRetry);
518
+ noticeRetry = setTimeout(showNotice, 3000);
519
+ return;
520
+ }
521
+ const container = document.getElementById('toast-container') || document.body;
522
+ hideNotice();
523
+ notice = document.createElement('div');
524
+ notice.className = 'toast info terminal-request-notice';
525
+ notice.setAttribute('role', 'status');
526
+ const text = document.createElement('span');
527
+ text.className = 'toast-msg';
528
+ const kinds = [open.length, going.length, ended.length].filter(Boolean).length;
529
+ const one = open.length === 1 ? open[0] : null;
530
+ let target = null;
531
+ if (kinds > 1) {
532
+ // Mixed: say all of it, so a run that is going (or done) is never hidden behind a request that waits.
533
+ const parts = [];
534
+ if (going.length) parts.push(`${going.length} running`);
535
+ if (open.length) parts.push(`${open.length} ${open.length === 1 ? 'needs' : 'need'} you`);
536
+ if (ended.length) parts.push(`${ended.length} finished`);
537
+ text.textContent = `From your terminal: ${parts.join(' · ')}.`;
538
+ } else if (open.length) {
539
+ const head = one ? `Your terminal ${verbFor(one)} ${whatFor(one)}.` : `${open.length} requests from your terminal.`;
540
+ text.textContent = `${head} ${one?.risk === 'human-only' ? 'Only you can do this. Nothing is done yet.' : 'Nothing has run yet.'}`;
541
+ target = one;
542
+ } else if (going.length) {
543
+ text.textContent = going.length === 1 ? `Running what your terminal asked: ${String(going[0].summary || going[0].title || 'a request')}.` : `${going.length} requests from your terminal are running.`;
544
+ target = going.length === 1 ? going[0] : null;
545
+ } else {
546
+ text.textContent = ended.length === 1 ? `${ended[0].state === 'done' ? 'Done' : 'Not done'}: ${String(ended[0].summary || ended[0].title || 'a request')}.` : `${ended.length} requests from your terminal have finished.`;
547
+ target = ended.length === 1 ? ended[0] : null;
548
+ }
549
+ const review = button('Review', 'shell.terminal-request-review', '', '', 'toast-action');
550
+ review.addEventListener('click', () => openDialog(target?.id || null));
551
+ const later = button('×', 'shell.terminal-request-later', '', '', 'toast-close');
552
+ later.setAttribute('aria-label', 'Later');
553
+ later.dataset.tip = 'Later. Your terminal’s requests stay where they are.';
554
+ later.addEventListener('click', hideNotice);
555
+ notice.append(text, review, later);
556
+ container.append(notice);
557
+ }
558
+
559
+ // ── Wiring ────────────────────────────────────────────────────────────────────────────────────────
560
+
561
+ window.addEventListener('floless:action-proposal', (event) => {
562
+ const d = event.detail || {};
563
+ if (d.resync) { void resync(); return; }
564
+ if (typeof d.proposalId === 'string') void refresh(d.proposalId);
565
+ });
566
+
567
+ async function boot() {
568
+ // The terminal's link: open the request it names. It only shows it; nothing is confirmed by opening it.
569
+ const params = new URLSearchParams(window.location.search);
570
+ const linked = params.get('proposal');
571
+ if (linked !== null) {
572
+ params.delete('proposal');
573
+ const rest = params.toString();
574
+ history.replaceState(history.state, '', `${window.location.pathname}${rest ? `?${rest}` : ''}${window.location.hash}`);
575
+ }
576
+ await resync();
577
+ if (linked !== null) {
578
+ const got = UUID.test(linked) ? await load(linked).catch(() => null) : { gone: true };
579
+ if (got?.p) shown.set(got.p.id, { p: got.p, busy: '', error: '' });
580
+ else shown.set(linked, { p: { id: String(linked).slice(0, 64), state: 'gone' }, gone: true, busy: '', error: '' });
581
+ openDialog(got?.p?.id || String(linked).slice(0, 64), true);
582
+ }
583
+ }
584
+
585
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => { void boot(); });
586
+ else void boot();
587
+
588
+ // For the Instructor and tests: what is shown, without reaching into the DOM.
589
+ window.flolessTerminalRequests = { open: openDialog, resync, waiting: () => waiting().map((p) => p.id) };
590
+ })();