@floless/app 0.152.1 → 0.154.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 (32) hide show
  1. package/dist/floless-server.cjs +5913 -3408
  2. package/dist/internal-workflows/floless-rfi-gmail-send/.floless-owner.json +1 -1
  3. package/dist/internal-workflows/floless-rfi-gmail-send/floless-rfi-gmail-send.flo +4 -2
  4. package/dist/schemas/revit.model.v1.schema.json +5 -0
  5. package/dist/schemas/steel.model.v2.schema.json +1 -1
  6. package/dist/skills/floless-app-new-workflow/SKILL.md +8 -2
  7. package/dist/skills/floless-app-onboarding/SKILL.md +8 -5
  8. package/dist/skills/floless-app-onboarding/references/floless-surfaces.md +8 -3
  9. package/dist/skills/floless-app-queue/SKILL.md +23 -4
  10. package/dist/skills/floless-app-steel-takeoff/SKILL.md +18 -2
  11. package/dist/web/agents.js +8 -1
  12. package/dist/web/app.css +107 -5
  13. package/dist/web/app.js +106 -12
  14. package/dist/web/aware.js +424 -57
  15. package/dist/web/chat.css +60 -13
  16. package/dist/web/chat.js +814 -148
  17. package/dist/web/commands-shell.js +200 -21
  18. package/dist/web/commands-steel.js +78 -3
  19. package/dist/web/guide.js +213 -13
  20. package/dist/web/index.html +16 -9
  21. package/dist/web/instructor.js +2 -1
  22. package/dist/web/leave-guard.js +51 -7
  23. package/dist/web/left-pane.js +251 -46
  24. package/dist/web/model-editor-steel-adapter.js +3 -0
  25. package/dist/web/model-viewport.js +14 -6
  26. package/dist/web/revit-editor.js +1 -0
  27. package/dist/web/steel-3d-view.js +15 -7
  28. package/dist/web/steel-editor.html +367 -54
  29. package/dist/web/tekla-structural-grid-adapter.js +7 -1
  30. package/dist/web/tool-updates.js +141 -33
  31. package/dist/web/workspaces.js +125 -21
  32. package/package.json +1 -1
package/dist/web/aware.js CHANGED
@@ -1832,12 +1832,37 @@
1832
1832
  // ≡ menu "New workflow…" — create the durable owner BEFORE asking the terminal AI to author.
1833
1833
  // The UI chooses only a display name and owner; the server mints the UUID and derives the actual
1834
1834
  // directory. That makes a queued request project-safe without turning the browser into an author.
1835
+ /**
1836
+ * ≡ New workflow, and a Guide card's Edit details (#2185): name it, choose where it belongs, and it starts building in its
1837
+ * own AI Chat conversation. Only ≡ New workflow offers the terminal instead (the earlier hand-off, unchanged). A Guide
1838
+ * card passes `prefill.guide` and gets the build back (or its error), so the card can show what happened.
1839
+ */
1840
+ // #2185: each ≡ New workflow start that has not answered yet, by its name and place, so the same name and place
1841
+ // resumes it (see requestNewWorkflow). Kept across a reload and shared by tabs: the server may have made the draft
1842
+ // before its answer was lost. One stored item per start, so a tab only ever touches its own: no shared list for
1843
+ // another tab to overwrite between a read and a write.
1844
+ const UNFINISHED_MENU_BUILD = 'floless.unfinishedMenuBuild:';
1845
+ // ponytail: no storage (a private window) only means a reload starts afresh.
1846
+ const unfinishedMenuBuilds = {
1847
+ get(key) { try { return localStorage.getItem(UNFINISHED_MENU_BUILD + key) || null; } catch { return null; } },
1848
+ keep(key, buildId) { try { localStorage.setItem(UNFINISHED_MENU_BUILD + key, buildId); } catch { /* see above */ } },
1849
+ /** Only while it still holds this build's id: a newer start under the same name and place is not forgotten for it. */
1850
+ // ponytail: the check and the removal are two calls, and storage offers nothing atomic. Two tabs pressing the very
1851
+ // same name and place at the same instant can still lose one start (two presses, two drafts at worst). If that
1852
+ // ever matters, let the server find an unfinished build by its name and place instead.
1853
+ done(key, buildId) {
1854
+ try { if (localStorage.getItem(UNFINISHED_MENU_BUILD + key) === buildId) localStorage.removeItem(UNFINISHED_MENU_BUILD + key); }
1855
+ catch { /* see above */ }
1856
+ },
1857
+ };
1835
1858
  async function requestNewWorkflow(prefill = {}) {
1859
+ const guide = prefill.guide && typeof prefill.guide.moveId === 'string' && typeof prefill.guide.chatId === 'string' ? prefill.guide : null;
1860
+ let building = false;
1836
1861
  try {
1837
1862
  const { projects = [] } = await api('/api/projects');
1838
1863
  const ownerOptions = workflowOwnerOptions(projects);
1839
1864
  const result = await formModal({
1840
- title: 'Start a workflow',
1865
+ title: guide ? 'Build this workflow' : 'Start a workflow',
1841
1866
  sub: 'Choose where it belongs. Its files, chat, history and AI working folder stay with that location.',
1842
1867
  fields: [
1843
1868
  {
@@ -1850,29 +1875,74 @@
1850
1875
  name: 'owner', label: 'Location', type: 'select', value: 'standalone',
1851
1876
  commandId: 'shell.new-workflow-location', options: ownerOptions,
1852
1877
  },
1878
+ ...(guide ? [] : [{
1879
+ name: 'terminal', type: 'checkbox', commandId: 'shell.new-workflow-terminal',
1880
+ label: 'Build it with my terminal AI instead (FloLess copies a prompt for it)',
1881
+ }]),
1853
1882
  ],
1854
- okLabel: 'Start workflow',
1883
+ okLabel: 'Start building',
1884
+ footnote: guide
1885
+ ? 'The AI starts building it in the workflow’s own chat on the left, and asks you before any run that sends data off this computer.'
1886
+ : 'The AI starts building it in the workflow’s own chat on the left, unless you choose your terminal AI. Either way it asks you before any run that sends data off this computer.',
1855
1887
  });
1856
- if (!result) return;
1888
+ if (!result) return null;
1857
1889
  const name = String(result.name || '').trim();
1858
- if (!name) { showToast('Enter a workflow name', 'warn'); return; }
1890
+ if (!name) { showToast('Enter a workflow name', 'warn'); return null; }
1859
1891
  const owner = String(result.owner || '').startsWith('project:')
1860
1892
  ? { kind: 'project', projectId: String(result.owner).slice('project:'.length) }
1861
1893
  : { kind: 'standalone' };
1862
- const { workflow } = await api('/api/workflows/owned', {
1863
- method: 'POST', body: JSON.stringify({ name, owner }),
1864
- });
1865
- const { request } = await api('/api/guide-new', {
1866
- method: 'POST', body: JSON.stringify({ workflowId: workflow.workflowId }),
1867
- });
1868
- const copied = await copyToClipboard(markedInstruction(request));
1869
- showToast(copied ? `${name} is ready · prompt copied` : `${name} is ready to discuss`, 'ok');
1870
- // #1890 PR 3b-0: the new draft opens, so it is somewhere to come back to — not only a toast.
1871
- try { ({ workflows: wfOwned } = await api('/api/workflows/owned')); openDraftWorkflow(workflow.workflowId); }
1872
- catch { /* the draft is still on the Workflows page after the next refresh */ }
1873
- appendNarration(`Created <strong>${escapeHtml(name)}</strong> in its chosen location and asked your terminal AI to start there — watch the glowing <strong>requests</strong> pill (bottom-right), or switch to your terminal.${copied ? ' The prompt is also on your clipboard.' : ''}`);
1874
- loadRequests();
1875
- } catch (e) { reportErr(e); }
1894
+ if (!guide && result.terminal) { await startWorkflowInTerminal(name, owner); return null; }
1895
+ if (guide) return await buildWorkflowInChat({ buildId: guide.moveId, payload: { source: 'guide', guideChatId: guide.chatId, moveId: guide.moveId, name, owner } });
1896
+ // A start that has not answered keeps its build id, written down before it is sent: trying again with the same name
1897
+ // and place (after a reload too) picks up the draft it may already have saved, never a second one.
1898
+ const key = `${name}\n${owner.kind === 'project' ? owner.projectId : ''}`;
1899
+ const buildId = unfinishedMenuBuilds.get(key) ?? crypto.randomUUID();
1900
+ unfinishedMenuBuilds.keep(key, buildId);
1901
+ building = true;
1902
+ const built = await buildWorkflowInChat({ buildId, payload: { source: 'menu', name, owner } });
1903
+ unfinishedMenuBuilds.done(key, buildId);
1904
+ return built;
1905
+ } catch (e) {
1906
+ if (guide) throw e;
1907
+ if (!building) { reportErr(e); return null; }
1908
+ // Every message on this path is written for people (ours, the AI setup's, the build route's); the toast's own
1909
+ // filter still catches anything technical.
1910
+ showToast(`${e?.message || 'FloLess couldn’t start building it.'} To try again, use ≡ → New workflow with the same name and place; FloLess picks up the same draft.`, 'warn', { persistent: true });
1911
+ return null;
1912
+ }
1913
+ }
1914
+
1915
+ /**
1916
+ * #2185: one build, set up first (#1607) and then started, landing on the workflow with its conversation working. A
1917
+ * Guide build uses the AI its Guide conversation uses; ≡ New workflow uses the AI Chat's own choice.
1918
+ */
1919
+ async function buildWorkflowInChat({ buildId, payload, reopen = false }) {
1920
+ if (typeof window.flolessChat?.startWorkflowBuild !== 'function') throw new Error('AI Chat is still starting. Try again in a moment.');
1921
+ const provider = payload.source === 'guide' ? (window.flolessChat.currentProvider?.() || preferredChatProvider()) : preferredChatProvider();
1922
+ if (!provider) throw new Error('Sign in to Claude or Codex in AI Chat, then build the workflow again.');
1923
+ // Reopening a started build needs no AI set up first: the conversation opens either way, and says if it can't send.
1924
+ const ready = reopen ? { ok: true } : await ensureChatRuntimeReady(provider);
1925
+ if (!ready.ok) throw Object.assign(new Error(ready.reason || 'Claude or Codex could not be set up for AI Chat. Try again in a moment.'), { code: 'chat-runtime-not-ready' });
1926
+ const result = await window.flolessChat.startWorkflowBuild(buildId, payload.source === 'menu' ? { ...payload, provider } : payload);
1927
+ try { ({ workflows: wfOwned } = await api('/api/workflows/owned')); } catch { /* the next refresh lists it */ }
1928
+ return result;
1929
+ }
1930
+
1931
+ /** ≡ New workflow → "Build it with my terminal AI instead": the earlier hand-off, unchanged. */
1932
+ async function startWorkflowInTerminal(name, owner) {
1933
+ const { workflow } = await api('/api/workflows/owned', {
1934
+ method: 'POST', body: JSON.stringify({ name, owner }),
1935
+ });
1936
+ const { request } = await api('/api/guide-new', {
1937
+ method: 'POST', body: JSON.stringify({ workflowId: workflow.workflowId }),
1938
+ });
1939
+ const copied = await copyToClipboard(markedInstruction(request));
1940
+ showToast(copied ? `${name} is ready · prompt copied` : `${name} is ready to discuss`, 'ok');
1941
+ // #1890 PR 3b-0: the new draft opens, so it is somewhere to come back to — not only a toast.
1942
+ try { ({ workflows: wfOwned } = await api('/api/workflows/owned')); openDraftWorkflow(workflow.workflowId); }
1943
+ catch { /* the draft is still on the Workflows page after the next refresh */ }
1944
+ appendNarration(`Created <strong>${escapeHtml(name)}</strong> in its chosen location and asked your terminal AI to start there — watch the glowing <strong>requests</strong> pill (bottom-right), or switch to your terminal.${copied ? ' The prompt is also on your clipboard.' : ''}`);
1945
+ loadRequests();
1876
1946
  }
1877
1947
 
1878
1948
  // ── First-open spotlight (one-time per workflow) ────────────────────────────
@@ -2115,6 +2185,7 @@
2115
2185
  list = list.filter((a) => a.execution !== 'internal');
2116
2186
  rememberWorkflowOwners(list);
2117
2187
  wfLibrary = list;
2188
+ globalThis.dispatchEvent?.(new CustomEvent('floless:workflows-listed')); // the Tool updates dialog gives its Open workflow buttons to rows painted before this list loaded (globalThis: the catalogue tests run this function without a window)
2118
2189
  wfUnreadable = Array.isArray(unreadable) ? unreadable.filter((row) => row && typeof row.id === 'string') : [];
2119
2190
  } catch (e) {
2120
2191
  // Usable before THIS refresh, or built by an earlier one (an overlapping refresh disabled it first, and its
@@ -5260,7 +5331,7 @@
5260
5331
  // A consent checkbox renders inline (label beside the box, not above) — used for the
5261
5332
  // fork liability terms. `required: true` gates the OK button until it's ticked.
5262
5333
  if (f.type === 'checkbox') {
5263
- return `<label class="modal-check" for="${id}"><input type="checkbox" id="${id}" data-fm-check="${escapeHtml(f.name)}"${f.value ? ' checked' : ''}><span>${escapeHtml(f.label || f.name)}</span></label>`;
5334
+ return `<label class="modal-check" for="${id}"><input type="checkbox" id="${id}" data-fm-check="${escapeHtml(f.name)}"${f.commandId === 'shell.new-workflow-terminal' ? ' data-command-id="shell.new-workflow-terminal"' : ''}${f.value ? ' checked' : ''}><span>${escapeHtml(f.label || f.name)}</span></label>`;
5264
5335
  }
5265
5336
  // A tick-list where each row carries its OWN state and, when it is not pickable, its own
5266
5337
  // way out. `select multiple` cannot do this: its rows are `role=option`, which may hold no
@@ -9555,6 +9626,20 @@
9555
9626
  }
9556
9627
  }
9557
9628
 
9629
+ // #2185: the server events that change what is connected or installed — a sign-in finished, a credential file changed,
9630
+ // a tool was installed or updated, an account was chosen. Relayed as ONE in-page event so AI Chat's and the Guide's
9631
+ // connection and install cards can tick themselves off without a reload (Integrations is a modal, so the window never
9632
+ // regains focus when the person comes back from it). Null for anything else.
9633
+ function connectionsChangeOf(m) {
9634
+ if (!m || typeof m !== 'object') return null;
9635
+ if (m.type === 'connect-result' && m.status === 'connected') return { reason: 'connected', id: typeof m.id === 'string' ? m.id : null };
9636
+ if (m.type === 'fs-change' && m.kind === 'credential') return { reason: 'credential', id: null };
9637
+ if (m.type === 'agent-install-result' && m.ok) return { reason: 'installed', id: typeof m.id === 'string' ? m.id : null };
9638
+ if (m.type === 'connections-changed') return { reason: 'tool-ready', id: typeof m.id === 'string' ? m.id : null };
9639
+ if (m.type === 'account-choice') return { reason: 'account-choice', id: typeof m.integration === 'string' ? m.integration : null };
9640
+ return null;
9641
+ }
9642
+
9558
9643
  function connectSse() {
9559
9644
  const es = new EventSource('/api/events');
9560
9645
  let reloadTimer = null;
@@ -9593,6 +9678,8 @@
9593
9678
  let m;
9594
9679
  try { m = JSON.parse(e.data); } catch { return; }
9595
9680
  if (!m || typeof m !== 'object') return; // valid non-object JSON (null/number) has no .type
9681
+ const connectionsChange = connectionsChangeOf(m);
9682
+ if (connectionsChange) window.dispatchEvent(new CustomEvent('floless:connections-changed', { detail: connectionsChange }));
9596
9683
  if (m.type === 'bootstrap') {
9597
9684
  // First-run AWARE setup state machine. `line` carries an npm ticker line
9598
9685
  // (installing only) → dim ticker; `status`/`reason` drive the card state.
@@ -10523,14 +10610,14 @@
10523
10610
  requestStartWaits.set(request.id, setTimeout(tick, REQUEST_START_WAIT_MS));
10524
10611
  }
10525
10612
 
10526
- async function startRequestChatWithSetup(requestId, provider, mode, { onSetup, isCancelled = () => false } = {}) {
10613
+ async function startRequestChatWithSetup(requestId, provider, mode, { onSetup, isCancelled = () => false, ownChat = false, restoreFirst = false } = {}) {
10527
10614
  if (typeof window.flolessChat?.startRequest !== 'function') throw new Error('AI Chat is still starting. Try again in a moment.');
10528
10615
  if (mode === 'start') {
10529
10616
  const ready = await ensureChatRuntimeReady(provider, { onProgress: (status) => onSetup?.(status), isCancelled });
10530
10617
  if (ready.cancelled || isCancelled()) throw Object.assign(new Error('The start was cancelled.'), { code: 'chat-start-cancelled' });
10531
10618
  if (!ready.ok) throw Object.assign(new Error(ready.reason), { code: 'chat-runtime-not-ready' });
10532
10619
  }
10533
- return window.flolessChat.startRequest(requestId, provider, mode);
10620
+ return window.flolessChat.startRequest(requestId, provider, mode, { ownChat, restoreFirst });
10534
10621
  }
10535
10622
  // Requests being started in AI Chat while FloLess sets their AI up, by request id → { label } of the
10536
10623
  // busy button. Kept outside the list, so a repaint during a long setup shows the same busy button
@@ -10812,7 +10899,8 @@
10812
10899
  return;
10813
10900
  }
10814
10901
  if (holder.kind === 'chat' && holder.chatId && holder.owner && typeof window.flolessChat?.openConversationIn === 'function') {
10815
- const opened = await window.flolessChat.openConversationIn({ owner: holder.owner }, holder.chatId).catch(() => false);
10902
+ const scope = holder.label ? { owner: holder.owner, label: holder.label } : { owner: holder.owner };
10903
+ const opened = await window.flolessChat.openConversationIn(scope, holder.chatId).catch(() => false);
10816
10904
  if (!opened) showToast('FloLess couldn’t open that conversation. It may have finished or moved; check AI Chat.', 'warn');
10817
10905
  return;
10818
10906
  }
@@ -11222,7 +11310,7 @@
11222
11310
  const provider = canChat ? preferredChatProvider() : null;
11223
11311
  $chatMeta.hidden = !provider;
11224
11312
  $chatMeta.textContent = provider
11225
- ? `Starts with ${runtimeLabel(provider)} · ${requestHelpReq.type === 'guide' ? 'Read only' : 'Working folder write'}`
11313
+ ? `Starts with ${runtimeLabel(provider)} · ${requestHelpReq.type === 'guide' ? 'Read only' : 'Auto'}`
11226
11314
  : '';
11227
11315
  $open.classList.toggle('primary', !canChat);
11228
11316
  }
@@ -11410,9 +11498,15 @@
11410
11498
  const provider = preferredChatProvider();
11411
11499
  const inScope = Boolean(r.project || r.workflowId) && requestMatchesChatScope(r);
11412
11500
  const chatLabel = `${label}${owner ? ` for ${owner}` : ''}`;
11501
+ // #2185: a request that was set aside (not deleted) says why, and can be brought back exactly as it was.
11502
+ const soft = r.lifecycle && typeof r.lifecycle === 'object' ? r.lifecycle : null;
11503
+ const softWord = soft ? ({ dismissed: 'Dismissed', expired: 'Expired', settled: 'Done' }[soft.state] || 'Set aside') : '';
11504
+ const restoreBtn = soft && r.canRestore === true
11505
+ ? `<button class="req-chat-action" data-done-restore data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-done-restore#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" aria-label="Restore ${escapeAttr(chatLabel)} to Requests" data-tip="Put this request back in Requests, exactly as it was">Restore</button>`
11506
+ : '';
11413
11507
  let action = '';
11414
11508
  if (provider && inScope) {
11415
- action = `<button class="req-chat-action" data-done-chat="${linked ? 'open' : 'discuss'}" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-done-discuss#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" aria-label="${linked ? 'Open' : 'Discuss'} ${escapeAttr(chatLabel)} in AI Chat" data-tip="${linked ? 'Open this request’s conversation in AI Chat' : 'Start a conversation about this request in AI Chat. Nothing runs.'}">${linked ? 'Open AI Chat' : 'Discuss in AI Chat'}</button>`;
11509
+ action = `<button class="req-chat-action" data-done-chat="${linked ? 'open' : 'discuss'}" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-done-discuss#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" aria-label="${linked ? 'Open the chat for' : 'Discuss'} ${escapeAttr(chatLabel)} in AI Chat" data-tip="${linked ? 'Open this request’s conversation in AI Chat' : 'Start a conversation about this request in AI Chat. Nothing runs.'}">${linked ? 'Open chat' : 'Discuss in AI Chat'}</button>`;
11416
11510
  } else if (provider && (r.project || r.workflowId)) {
11417
11511
  action = `<span class="req-chat-elsewhere" data-tip="Open ${escapeAttr(owner)} to open this request’s conversation">Open ${escapeHtml(owner)} for AI Chat</span>`;
11418
11512
  } else if (!provider) {
@@ -11426,11 +11520,12 @@
11426
11520
  return `
11427
11521
  <div class="req-item req-done-item" data-id="${escapeAttr(r.id)}">
11428
11522
  <div class="req-info">
11429
- <div class="req-head"><span class="${badgeCls}">${escapeHtml(label)}</span> ${owner ? `<span class="req-owner">${highlightQuery(owner, query)}</span>` : ''}${leftLabel ? `<span class="req-time" data-tip="Left the queue ${escapeAttr(leftLabel)}">${escapeHtml(leftLabel)}</span>` : ''}</div>
11523
+ <div class="req-head"><span class="${badgeCls}">${escapeHtml(label)}</span> ${owner ? `<span class="req-owner">${highlightQuery(owner, query)}</span>` : ''}${leftLabel ? `<span class="req-time" data-tip="${soft ? 'Set aside' : 'Left the queue'} ${escapeAttr(leftLabel)}">${escapeHtml(leftLabel)}</span>` : ''}${soft ? `<span class="req-state" data-state="${escapeAttr(soft.state)}">${escapeHtml(softWord)}</span>` : ''}</div>
11430
11524
  <div class="req-instruction">${highlightQuery(r.summary || '', query) || 'This request kept no words to show.'}</div>
11525
+ ${soft && soft.reason ? `<p class="req-done-why">${escapeHtml(soft.reason)}</p>` : ''}
11431
11526
  ${runHtml}${unreadableNote}
11432
11527
  </div>
11433
- <div class="req-actions">${action}</div>
11528
+ <div class="req-actions">${action}${restoreBtn}</div>
11434
11529
  </div>`;
11435
11530
  }
11436
11531
  /** Requests → Done: what left the queue, newest first. Read-only apart from opening or discussing a conversation. */
@@ -11487,6 +11582,14 @@
11487
11582
  if ($showAll) $showAll.onclick = () => setRequestScopeAll(true);
11488
11583
  const $retry = $list.querySelector('[data-done-retry]');
11489
11584
  if ($retry) $retry.onclick = async () => { await loadDoneRequests(); renderRequests(); };
11585
+ $list.querySelectorAll('[data-done-restore]').forEach((button) => {
11586
+ button.onclick = async () => {
11587
+ button.disabled = true;
11588
+ button.setAttribute('aria-busy', 'true');
11589
+ const restored = await restoreSetAsideRequest(button.dataset.id);
11590
+ if (!restored && button.isConnected) { button.disabled = false; button.removeAttribute('aria-busy'); }
11591
+ };
11592
+ });
11490
11593
  $list.querySelectorAll('[data-done-chat]').forEach((button) => {
11491
11594
  button.onclick = async () => {
11492
11595
  const request = (doneRequests || []).find((candidate) => candidate?.id === button.dataset.id);
@@ -11543,13 +11646,17 @@
11543
11646
  if ($queued) $queued.textContent = pendingRequests.length ? `Queued (${pendingRequests.length})` : 'Queued';
11544
11647
  const $sub = document.getElementById('requests-sub');
11545
11648
  if ($sub) $sub.textContent = done
11546
- ? 'Requests that left the queue in the last 30 days. Open their conversation or discuss them in AI Chat. Nothing here runs again.'
11547
- : 'Start queued work in AI Chat or run it in the background with your terminal AI.';
11649
+ ? 'Requests that left the queue in the last 30 days, and every one you set aside. Open their conversation, or restore one to Requests. Nothing here runs again by itself.'
11650
+ : 'Work on a request in AI Chat, or run it in the background with your terminal AI. ✕ sets one aside; Done keeps it.';
11548
11651
  const $note = document.getElementById('requests-done-note');
11549
11652
  if ($note) $note.hidden = !done;
11550
11653
  }
11551
11654
  let previousRequestCount = 0;
11552
11655
  let previousRequestIds = null;
11656
+ // #2185: the one-time tidy of old requests, shown above the list with Undo until it is undone or closed.
11657
+ let requestsBacklog = null;
11658
+ /** Does this request need the person (the REQUESTS pill), by the server's own projection? A row without one counts. */
11659
+ function requestNeedsPerson(r) { return r?.attention?.state !== 'not-now'; }
11553
11660
  let reqPulseTimer = null;
11554
11661
  let revealFlashTimer = null;
11555
11662
  let revealArriveCleanup = null;
@@ -11577,9 +11684,10 @@
11577
11684
  try {
11578
11685
  // Bounded: every later read waits behind this one, so a response that never arrives must not
11579
11686
  // freeze the list for good. The route's own lock waits give up after 60 s.
11580
- const { requests, chatPublications = [] } = await api('/api/requests', { signal: AbortSignal.timeout(90_000) });
11687
+ const { requests, chatPublications = [], needsYou, backlog = null } = await api('/api/requests', { signal: AbortSignal.timeout(90_000) });
11581
11688
  reconcileActiveInstructorRuns(requests, chatPublications);
11582
11689
  pendingRequests = requests;
11690
+ requestsBacklog = backlog && typeof backlog === 'object' ? backlog : null;
11583
11691
  // A Request leaving the queue arrives in Done: re-read it while Done is what the open window shows.
11584
11692
  // Not awaited: the queue's own update never waits on the Done read.
11585
11693
  if (requestViewMode === 'done' && document.getElementById('requests-modal')?.classList.contains('show')) {
@@ -11624,21 +11732,32 @@
11624
11732
  }
11625
11733
  const $rc = document.getElementById('req-count');
11626
11734
  const $rs = document.getElementById('req-stat');
11627
- if ($rc) $rc.textContent = requests.length;
11628
- if ($rs) $rs.classList.toggle('has-pending', requests.length > 0);
11629
- const ids = new Set(requests.map((r) => r && r.id).filter(Boolean));
11735
+ // #2185: the pill counts what needs the person, as the server decided it - not everything that exists. Work the AI
11736
+ // is doing, and anything set aside, is in Requests but is not a thing for you to do.
11737
+ const needing = requests.filter((r) => r && requestNeedsPerson(r));
11738
+ const needCount = Number.isFinite(needsYou) ? needsYou : needing.length;
11739
+ if ($rc) $rc.textContent = needCount;
11740
+ if ($rs) {
11741
+ $rs.classList.toggle('has-pending', needCount > 0);
11742
+ $rs.setAttribute('aria-label', `Open Requests. ${needCount} ${needCount === 1 ? 'needs' : 'need'} you`);
11743
+ const withAi = requests.length - needing.length;
11744
+ $rs.setAttribute('data-tip', needCount
11745
+ ? `${needCount} request${needCount === 1 ? ' needs' : 's need'} you${withAi ? ` · ${withAi} with the AI` : ''} — click to view & manage`
11746
+ : withAi ? `Nothing needs you · ${withAi} with the AI — click to view` : 'Nothing needs you — click to view & manage');
11747
+ }
11748
+ const ids = new Set(needing.map((r) => r && r.id).filter(Boolean));
11630
11749
  const hasNewId = previousRequestIds
11631
- ? requests.some((r) => r && r.id && !previousRequestIds.has(r.id))
11632
- : requests.length > previousRequestCount;
11633
- // Add the shake animation when a new request appears in the poll/SSE refresh.
11634
- if ((hasNewId || requests.length > previousRequestCount) && $rs) {
11750
+ ? needing.some((r) => r && r.id && !previousRequestIds.has(r.id))
11751
+ : needCount > previousRequestCount;
11752
+ // Add the shake animation when a request that needs you appears in the poll/SSE refresh.
11753
+ if ((hasNewId || needCount > previousRequestCount) && $rs) {
11635
11754
  $rs.classList.remove('req-pulse'); // force reflow to restart animation
11636
11755
  void $rs.offsetWidth; // trigger reflow
11637
11756
  $rs.classList.add('req-pulse');
11638
11757
  if (reqPulseTimer) clearTimeout(reqPulseTimer);
11639
11758
  reqPulseTimer = setTimeout(() => { $rs.classList.remove('req-pulse'); reqPulseTimer = null; }, 2100);
11640
11759
  }
11641
- previousRequestCount = requests.length;
11760
+ previousRequestCount = needCount;
11642
11761
  previousRequestIds = ids;
11643
11762
  const $rm = document.getElementById('requests-modal');
11644
11763
  if ($rm && $rm.classList.contains('show')) renderRequests(); // keep an open list live
@@ -11706,6 +11825,8 @@
11706
11825
  */
11707
11826
  function requestOwnerName(r) {
11708
11827
  if (!r) return '';
11828
+ // #2185: a build's conversation is its workflow's, so "Open … for AI Chat" names the workflow, not its project.
11829
+ if (r.type === 'new-workflow' && r.buildId && r.workflowName) return r.workflowName;
11709
11830
  if (r.project) return r.projectName || r.project;
11710
11831
  if (r.appId) return r.appId;
11711
11832
  return r.type === 'ui-customize' ? 'your dashboard' : r.type === 'new-workflow' ? (r.workflowName || 'a new workflow') : '';
@@ -11714,6 +11835,10 @@
11714
11835
  function requestMatchesChatScope(request) {
11715
11836
  const scope = currentChatScope();
11716
11837
  if (!scope?.owner || !request) return false;
11838
+ // #2185: a build's Request lives in its workflow's own conversation even inside a project (server requestChatOwner).
11839
+ if (request.type === 'new-workflow' && request.buildId && request.workflowId) {
11840
+ return scope.owner.kind === 'workflow' && request.workflowId === scope.owner.workflowId;
11841
+ }
11717
11842
  return scope.owner.kind === 'project'
11718
11843
  ? request.project === scope.owner.projectId
11719
11844
  : request.workflowId === scope.owner.workflowId;
@@ -12531,6 +12656,186 @@
12531
12656
  window.addEventListener('blur', () => release(null)); // the release may happen in another window
12532
12657
  }
12533
12658
 
12659
+ // ── #2185: Requests stop piling up ───────────────────────────────────────────────────────────────────────────────
12660
+ // ✕ sets a request aside; nothing is deleted. Done keeps it with the reason, and Restore brings back the same request.
12661
+ // When the AI is working on it the server refuses, and the click ASKS - stop that work first, or keep the request.
12662
+ const REQUEST_SET_ASIDE_CODES = new Set(['request-dismissed', 'request-expired', 'request-settled']);
12663
+ const requestDismissals = new Map();
12664
+ const requestWords = (r) => { const owner = requestOwnerName(r); return `${requestLabel(r)}${owner ? ` for ${owner}` : ''}`; };
12665
+
12666
+ async function restoreSetAsideRequest(id, { quiet = false } = {}) {
12667
+ try {
12668
+ await api(`/api/requests/${encodeURIComponent(id)}/restore`, { method: 'POST', body: '{}' });
12669
+ } catch (error) {
12670
+ showToast(error?.body?.error || 'FloLess couldn’t restore that request. It is still in Done; try again.', 'warn');
12671
+ return false;
12672
+ }
12673
+ await loadRequests().catch(() => {});
12674
+ if (requestViewMode === 'done') await loadDoneRequests();
12675
+ renderRequests();
12676
+ if (!quiet) showToast('Restored. It is back in Requests.', 'ok');
12677
+ return true;
12678
+ }
12679
+
12680
+ /** A dialog title starts with a capital, however the request's own words begin. */
12681
+ const sentenceStart = (text) => { const s = String(text || ''); return s.charAt(0).toUpperCase() + s.slice(1); };
12682
+
12683
+ /** The ✕. Resolves to 'dismissed' | 'kept' | 'gone' | 'error'. */
12684
+ async function dismissQueuedRequest(r) {
12685
+ if (requestDismissals.has(r.id)) return requestDismissals.get(r.id);
12686
+ const task = (async () => {
12687
+ try {
12688
+ await api(`/api/requests/${encodeURIComponent(r.id)}/dismiss`, { method: 'POST', body: '{}' });
12689
+ } catch (error) {
12690
+ const body = error?.body;
12691
+ if (body?.code === 'request-held' && body.hold) return askDismissHeld(r, body.hold);
12692
+ if (body?.code === 'request-already-set-aside' || error?.status === 404) { await loadRequests().catch(() => {}); renderRequests(); return 'gone'; }
12693
+ showToast(body?.error || 'FloLess couldn’t set that request aside. It is still in Requests; try again.', 'warn');
12694
+ return 'error';
12695
+ }
12696
+ return afterDismissed(r);
12697
+ })().finally(() => requestDismissals.delete(r.id));
12698
+ requestDismissals.set(r.id, task);
12699
+ return task;
12700
+ }
12701
+
12702
+ async function afterDismissed(r) {
12703
+ await loadRequests().catch(() => {});
12704
+ renderRequests();
12705
+ showToast(`Dismissed ${requestWords(r)}. It is kept in Done.`, 'ok', {
12706
+ action: { label: 'Undo', commandId: 'shell.requests-dismiss-undo', onClick: () => { void restoreSetAsideRequest(r.id); } },
12707
+ });
12708
+ return 'dismissed';
12709
+ }
12710
+
12711
+ /** The AI is working on this request: say what, and offer to stop it first. Never only "can't". */
12712
+ async function askDismissHeld(r, hold) {
12713
+ const stop = hold.stop && typeof hold.stop === 'object' ? hold.stop : null;
12714
+ // The chat to open: a recovery has nothing to stop from here, but the ask tells the person to finish it there.
12715
+ const chat = [hold.open, stop].find((c) => c && typeof c === 'object' && c.kind === 'chat' && c.chatId && c.owner) || null;
12716
+ const actions = [{ id: null, label: 'Keep it', commandId: 'shell.requests-dismiss-keep' }];
12717
+ if (chat) actions.push({ id: 'open', label: 'Open the chat', commandId: 'shell.requests-dismiss-open' });
12718
+ if (stop) actions.push({ id: 'stop', label: 'Stop it and dismiss', commandId: 'shell.requests-dismiss-stop', className: 'req-busy-stop' });
12719
+ const choice = await busyChoiceDialog({
12720
+ title: `${sentenceStart(requestWords(r))} is being worked on`,
12721
+ sub: `${hold.why || 'Something is working on this request, so it was not dismissed.'} Nothing was changed.`,
12722
+ actions, focusId: 'shell.requests-dismiss-keep',
12723
+ });
12724
+ if (choice === 'open') {
12725
+ // Out of the way first, so the conversation it opens is what the person sees; named, so AI Chat can say whose it is.
12726
+ closeRequests();
12727
+ if (chat) await openProjectWaitHolder({ projectWait: { holder: { kind: 'chat', owner: chat.owner, chatId: chat.chatId, turnId: chat.turnId, title: chat.title, label: requestOwnerName(r) } } });
12728
+ return 'kept';
12729
+ }
12730
+ if (choice !== 'stop' || !stop) return 'kept';
12731
+ // Only a stop that went through may be reported as "stopped"; a stale one means the work had already ended or changed.
12732
+ let stopped = true;
12733
+ try {
12734
+ if (stop.kind === 'chat') {
12735
+ await api(`/api/chat/conversations/${encodeURIComponent(stop.chatId)}/stop`, { method: 'POST', body: JSON.stringify({ owner: stop.owner, expectTurnId: stop.turnId || undefined }) });
12736
+ } else if (stop.kind === 'wait') {
12737
+ await api(`/api/requests/${encodeURIComponent(stop.requestId)}/run/stop`, { method: 'POST', body: JSON.stringify({ waitId: stop.waitId }) });
12738
+ } else {
12739
+ await api(`/api/requests/${encodeURIComponent(stop.requestId)}/run/stop`, { method: 'POST', body: JSON.stringify(stop.leaseId ? { expectLeaseId: stop.leaseId } : {}) });
12740
+ }
12741
+ } catch (error) {
12742
+ // Already finished is fine - the dismissal below decides. Anything else leaves the request exactly as it was.
12743
+ if (error?.body?.code !== 'stop-stale') {
12744
+ console.warn('[requests] could not stop the work holding a request:', error);
12745
+ showToast('FloLess couldn’t stop that work, so the request was not dismissed.', 'warn');
12746
+ return 'kept';
12747
+ }
12748
+ stopped = false;
12749
+ }
12750
+ try {
12751
+ await api(`/api/requests/${encodeURIComponent(r.id)}/dismiss`, { method: 'POST', body: '{}' });
12752
+ } catch (error) {
12753
+ await loadRequests().catch(() => {}); renderRequests();
12754
+ // A stop that went through is said, so the person does not think the AI is still working; a stale one is not claimed.
12755
+ showToast(error?.body?.code === 'request-held'
12756
+ ? (stopped ? 'The work was stopped and is still winding down. Try dismissing it again in a moment.' : 'Something is still working on this request. Try dismissing it again in a moment.')
12757
+ : `${stopped ? 'The work was stopped, but the request' : 'The request'} couldn’t be set aside. It is still in Requests; try ✕ again.`, 'warn');
12758
+ return 'kept';
12759
+ }
12760
+ return afterDismissed(r);
12761
+ }
12762
+
12763
+ /** A start reached a request that was set aside meanwhile: say so, and offer to bring it back and start it in one step. */
12764
+ async function askRestoreAndStart(request, provider, code) {
12765
+ const settled = code === 'request-settled';
12766
+ const why = code === 'request-dismissed' ? 'You dismissed this request.'
12767
+ : code === 'request-expired' ? 'This request sat untouched for 14 days, so FloLess set it aside.'
12768
+ : 'This request was already answered.';
12769
+ const actions = [{ id: null, label: settled ? 'Close' : 'Cancel', commandId: 'shell.requests-restore-cancel' }];
12770
+ if (!settled) {
12771
+ actions.push({ id: 'restore', label: 'Restore', commandId: 'shell.requests-restore' });
12772
+ actions.push({ id: 'start', label: 'Restore and start', commandId: 'shell.requests-restore-start', className: 'primary' });
12773
+ }
12774
+ const choice = await busyChoiceDialog({
12775
+ title: `${sentenceStart(requestWords(request))} is set aside`,
12776
+ sub: `${why} Nothing was started.${settled ? ' Its answer is in AI Chat. To ask again, make a new request.' : ' Restore it to put it back in Requests, or restore it and start the AI on it now.'}`,
12777
+ actions, focusId: settled ? 'shell.requests-restore-cancel' : 'shell.requests-restore-start',
12778
+ });
12779
+ if (choice === 'restore') { await restoreSetAsideRequest(request.id); return; }
12780
+ if (choice !== 'start') return;
12781
+ try {
12782
+ await startRequestChatWithSetup(request.id, provider, 'start', { ownChat: true, restoreFirst: true });
12783
+ await loadRequests().catch(() => {});
12784
+ closeRequests();
12785
+ } catch (error) {
12786
+ if (error?.code === 'chat-start-cancelled') return;
12787
+ // Refused after Restore: say why in the list as well, exactly as the other start surfaces do.
12788
+ const notReady = error?.code === 'chat-runtime-not-ready';
12789
+ const explained = notReady ? '' : chatStartErrorText(error);
12790
+ if (notReady) showToast(error.message, 'warn');
12791
+ else reportChatStartErr(error);
12792
+ await loadRequests().catch(() => {}); renderRequests();
12793
+ const actionStatus = document.getElementById('requests-action-status');
12794
+ if (actionStatus) actionStatus.textContent = notReady ? error.message : explained || `Couldn’t start ${requestLabel(request)} in AI Chat. Try again.`;
12795
+ }
12796
+ }
12797
+
12798
+ // The one-time tidy of old requests: said once, above the list, with Undo.
12799
+ function renderRequestsBacklog() {
12800
+ const line = document.getElementById('requests-backlog');
12801
+ if (!line) return;
12802
+ const summary = requestViewMode === 'queued' ? requestsBacklog : null;
12803
+ const total = summary ? (Number(summary.settled) || 0) + (Number(summary.expired) || 0) : 0;
12804
+ line.hidden = !summary || total === 0;
12805
+ if (line.hidden) { line.replaceChildren(); return; }
12806
+ const parts = [];
12807
+ if (summary.settled) parts.push(`${summary.settled} already answered`);
12808
+ if (summary.expired) parts.push(`${summary.expired} untouched for 14 days`);
12809
+ const text = document.createElement('span');
12810
+ text.className = 'req-backlog-text';
12811
+ text.textContent = `Tidied ${total} old request${total === 1 ? '' : 's'}: ${parts.join(' and ')}. They are kept in Done.`;
12812
+ const undo = document.createElement('button');
12813
+ undo.type = 'button'; undo.className = 'req-backlog-undo'; undo.textContent = 'Undo';
12814
+ undo.setAttribute('data-command-id', 'shell.requests-backlog-undo');
12815
+ undo.setAttribute('data-tip', 'Put every one of those requests back in Requests');
12816
+ undo.onclick = async () => {
12817
+ undo.disabled = true;
12818
+ try {
12819
+ const result = await api('/api/requests/backlog/undo', { method: 'POST', body: '{}' });
12820
+ const put = `Put ${result.restored} request${result.restored === 1 ? '' : 's'} back in Requests.`;
12821
+ if (result.failed > 0) {
12822
+ showToast(`${result.restored ? `${put} ` : ''}${result.failed} couldn’t be put back, so ${result.failed === 1 ? 'it is' : 'they are'} still in Done. Press Undo again to retry.`, 'warn');
12823
+ } else showToast(put, 'ok');
12824
+ } catch (error) { showToast(error?.body?.error || 'FloLess couldn’t undo that. The requests are still in Done.', 'warn'); }
12825
+ await loadRequests().catch(() => {}); renderRequests();
12826
+ };
12827
+ const close = document.createElement('button');
12828
+ close.type = 'button'; close.className = 'req-backlog-close'; close.textContent = '×';
12829
+ close.setAttribute('aria-label', 'Close this note');
12830
+ close.setAttribute('data-command-id', 'shell.requests-backlog-close');
12831
+ close.setAttribute('data-tip', 'Close this note. The requests stay in Done');
12832
+ close.onclick = async () => {
12833
+ requestsBacklog = null; renderRequestsBacklog();
12834
+ try { await api('/api/requests/backlog/ack', { method: 'POST', body: '{}' }); } catch { /* it shows again next time, which is harmless */ }
12835
+ };
12836
+ line.replaceChildren(text, undo, close);
12837
+ }
12838
+
12534
12839
  // The Requests window: every queued change in a list, with only the actions the server says are
12535
12840
  // currently safe, plus bulk actions over the available rows. The server-composed prompt (which embeds file-derived
12536
12841
  // appId/nodeId/instruction) is rendered via textContent-equivalent escaping — which matters MORE
@@ -12545,6 +12850,7 @@
12545
12850
  // Everything waits, not only the rows, so the bulk actions keep acting on what is on screen.
12546
12851
  if ($list.__requestsHeld) { $list.__requestsOwed = true; return; }
12547
12852
  paintRequestViewChrome();
12853
+ renderRequestsBacklog();
12548
12854
  if (requestViewMode === 'done') { renderDoneRequests($list); return; }
12549
12855
  // Search is pointless over an empty queue, and over a single request it is just clutter.
12550
12856
  // Drop the query WITH the box, and before anything is filtered by it: a hidden filter still
@@ -12684,17 +12990,20 @@
12684
12990
  // and the run then lands in `exited-unresolved` for a reason the user caused and cannot see.
12685
12991
  // #1874: a read nobody can say is discarded or not offers only Keep / Discard, in its own block.
12686
12992
  const discardQuestion = requestHasDiscardQuestion(r);
12687
- const del = lifecycleOwned
12993
+ // #2185: ✕ is always there. It sets the request aside (kept in Done, Restore brings it back); when the AI is working on
12994
+ // it the server says so and the click asks - stop that work first, or keep it - instead of the button vanishing.
12995
+ const heldNote = lifecycleOwned
12688
12996
  ? '<span class="req-lifecycle" data-tip="This clears itself when your terminal AI finishes or fails the organize">finishing in your terminal</span>'
12689
12997
  : projectWaiting
12690
- ? '<span class="req-lifecycle" data-tip="Stop waiting first if you want to clear this request">waiting</span>'
12998
+ ? '<span class="req-lifecycle" data-tip="Waiting for its project to be free. Dismiss asks whether to stop waiting first">waiting</span>'
12691
12999
  : inFlight || desktopClaimed
12692
- ? '<span class="req-lifecycle" data-tip="Stop the run if you need to pause it. Clear stays unavailable until the saved session is continued and finished">running</span>'
13000
+ ? '<span class="req-lifecycle" data-tip="Running. Dismiss asks whether to stop it first">running</span>'
12693
13001
  : !canClear && r.clearState === 'session-saved'
12694
- ? `<span class="req-lifecycle" role="status" aria-live="polite" data-tip="${escapeAttr(r.clearWhy || 'This stopped session is saved so you can continue where you left off. Continue or finish it before clearing this request.')}"><span aria-hidden="true">session saved</span><span class="sr-only">Session saved. Continue or finish it before clearing this request.</span></span>`
13002
+ ? `<span class="req-lifecycle" role="status" aria-live="polite" data-tip="${escapeAttr(r.clearWhy || 'This stopped session is saved so you can continue where you left off. Continue or finish it before dismissing this request.')}"><span aria-hidden="true">session saved</span><span class="sr-only">Session saved. Continue or finish it before dismissing this request.</span></span>`
12695
13003
  : !canClear
12696
- ? `<span class="req-lifecycle" data-tip="${escapeAttr(r.clearWhy || 'This request cannot be cleared yet.')}">kept</span>`
12697
- : `<button class="req-del" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-clear#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" data-tip="${resumeCommand ? 'Clear this request and discard its saved terminal session' : 'Clear this request'}">×</button>`;
13004
+ ? `<span class="req-lifecycle" data-tip="${escapeAttr(r.clearWhy || 'This request cannot be dismissed yet.')}">kept</span>`
13005
+ : '';
13006
+ const del = `${heldNote}<button class="req-del" aria-label="Dismiss ${escapeAttr(`${label}${owner ? ` for ${owner}` : ''}`)}" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-dismiss#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" data-tip="Dismiss this request. It stays in Done, and you can restore it">×</button>`;
12698
13007
  // A server-stamped handoff gets NO re-run. The original terminal session may already be live;
12699
13008
  // starting a second headless agent would put two writers in one folder. The server still owns
12700
13009
  // run policy; this row repeats only the lifecycle-integrity guards needed to fail closed on a
@@ -12721,15 +13030,23 @@
12721
13030
  const inChatScope = hasChatOwner && requestMatchesChatScope(r);
12722
13031
  const chatLabel = `${label}${owner ? ` for ${owner}` : ''}`;
12723
13032
  const hasLinkedChat = Boolean(r.chatConversation?.chatId);
12724
- const discussBtn = chatProvider && inChatScope && !discardQuestion
12725
- ? `<button class="req-chat-action" data-request-chat="discuss" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-discuss#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" aria-label="${hasLinkedChat ? 'Open' : 'Discuss'} ${escapeAttr(chatLabel)} in AI Chat" data-tip="${hasLinkedChat ? 'Open the linked conversation in AI Chat' : 'Open this request in AI Chat without starting the AI'}">${hasLinkedChat ? 'Open AI Chat' : 'Discuss in AI Chat'}</button>`
13033
+ // #2185: "Work on it" is the one button that puts the AI to work - in THIS request's own conversation, never in whatever
13034
+ // chat happens to be open. A conversation that has only been opened (Discuss) owns nothing yet, so it still starts.
13035
+ // What a chat can do is the server's verdict (`chatCanStart`), not the background-run policy.
13036
+ const canWorkOnIt = Boolean(chatProvider && inChatScope && !filterGuide && !discardQuestion
13037
+ && r.status === 'pending' && r.chatCanStart !== false
13038
+ && (!chatExecutionOwner || chatExecutionOwner === 'discussion')
13039
+ && !inFlight && !desktopHandoffs && !resumeCommand && !revisionReadHasTerminalOwner(r));
13040
+ // Read-only: opens the conversation that already holds this request (or, if none can start it, says what it would be).
13041
+ const discussBtn = chatProvider && inChatScope && !discardQuestion && !canWorkOnIt
13042
+ ? `<button class="req-chat-action" data-request-chat="discuss" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-discuss#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" aria-label="${hasLinkedChat ? 'Open the chat for' : 'Discuss'} ${escapeAttr(chatLabel)} in AI Chat" data-tip="${hasLinkedChat ? 'Open the conversation that holds this request' : 'Open this request in AI Chat. Nothing runs'}">${hasLinkedChat ? 'Open chat' : 'Discuss in AI Chat'}</button>`
12726
13043
  : '';
12727
13044
  const starting = requestChatStarts.get(r.id)?.label;
12728
- const startChatBtn = chatProvider && inChatScope && canRunNow && !filterGuide
12729
- ? `<button class="req-chat-action primary" data-request-chat="start" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-start-chat#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" aria-label="Start ${escapeAttr(chatLabel)} in AI Chat" data-tip="Start this request in AI Chat and continue there"${starting ? ' disabled aria-busy="true"' : ''}>${escapeHtml(starting || 'Start in AI Chat')}</button>`
13045
+ const startChatBtn = canWorkOnIt
13046
+ ? `<button class="req-chat-action primary" data-request-chat="start" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-start-chat#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" aria-label="Work on ${escapeAttr(chatLabel)} in AI Chat" data-tip="The AI starts on this now, in this request’s own conversation in AI Chat"${starting ? ' disabled aria-busy="true"' : ''}>${escapeHtml(starting || 'Work on it')}</button>`
12730
13047
  : '';
12731
13048
  const chatMeta = discardQuestion ? '' : chatProvider && inChatScope
12732
- ? `<span class="req-chat-meta">AI Chat · ${escapeHtml(runtimeLabel(chatProvider))} · ${r.type === 'guide' || (r.type === 'tweak-contract' && r.mode === 'query') ? 'Read only' : 'Working folder write'}</span>`
13049
+ ? `<span class="req-chat-meta">AI Chat · ${escapeHtml(runtimeLabel(chatProvider))} · ${r.type === 'guide' || (r.type === 'tweak-contract' && r.mode === 'query') ? 'Read only' : 'Auto'}</span>`
12733
13050
  : chatProvider && hasChatOwner
12734
13051
  ? `<span class="req-chat-elsewhere" data-tip="Open ${escapeAttr(owner)} to discuss or start this request in AI Chat">Open ${escapeHtml(owner)} for AI Chat</span>`
12735
13052
  : '';
@@ -12756,7 +13073,7 @@
12756
13073
  ${discussBtn}
12757
13074
  ${runBtn}
12758
13075
  ${desktopHandoffs || resumeCommand || !requestCanCopy(r) ? '' : `<button class="req-copy" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-copy#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" data-tip="${r.preparationRetryable ? 'Copy this retry request for your terminal AI' : 'Copy this request for your terminal AI'}" aria-label="${r.preparationRetryable ? 'Copy retry request' : 'Copy this request for your terminal AI'}">⧉</button>`}
12759
- ${discardQuestion ? '' : del.replace('<button class="req-del"', '<button aria-label="Clear this request" class="req-del"')}
13076
+ ${discardQuestion ? '' : del}
12760
13077
  ${startChatBtn}
12761
13078
  </div>
12762
13079
  </div>`;
@@ -12781,12 +13098,19 @@
12781
13098
  const endStart = () => {
12782
13099
  if (startEntry && requestChatStarts.get(request.id) === startEntry) requestChatStarts.delete(request.id);
12783
13100
  };
13101
+ // #2199: this start clears the line where it goes stale (it went through, or was cancelled) — but only while the
13102
+ // line is still its own: it tags what it writes, and the text must be unchanged too. Never on opening Requests:
13103
+ // another start (even one showing the same words) or a wait owns its own line.
12784
13104
  const actionStatus = document.getElementById('requests-action-status');
12785
- if (actionStatus) actionStatus.textContent = `${button.textContent} ${requestLabel(request)} for ${requestOwnerName(request)}.`;
13105
+ const mine = {};
13106
+ let said = null;
13107
+ const say = (text) => { if (actionStatus) { actionStatus.textContent = said = text; actionStatus.__statusOwner = mine; } };
13108
+ const unsay = () => { if (actionStatus?.__statusOwner === mine && actionStatus.textContent === said) actionStatus.textContent = ''; };
13109
+ say(`${button.textContent} ${requestLabel(request)} for ${requestOwnerName(request)}.`);
12786
13110
  let settingUp = false;
12787
13111
  const slowTimer = setTimeout(() => {
12788
13112
  if (!settingUp && button.disabled && button.isConnected && actionStatus) {
12789
- actionStatus.textContent = `Still opening ${requestLabel(request)} in AI Chat… FloLess is taking longer than expected.`;
13113
+ say(`Still opening ${requestLabel(request)} in AI Chat… FloLess is taking longer than expected.`);
12790
13114
  }
12791
13115
  }, 4000);
12792
13116
  const requestsModal = document.getElementById('requests-modal');
@@ -12796,6 +13120,7 @@
12796
13120
  || !pendingRequests.some((candidate) => candidate && candidate.id === request.id && candidate.status === 'pending');
12797
13121
  try {
12798
13122
  await startRequestChatWithSetup(request.id, provider, starting ? 'start' : 'discuss', {
13123
+ ownChat: starting,
12799
13124
  isCancelled: cancelled,
12800
13125
  // FloLess is installing its own copy of this AI first (#1607): say so, once per state.
12801
13126
  onSetup: (status) => {
@@ -12806,13 +13131,20 @@
12806
13131
  // The list may have been repainted meanwhile: label whichever button shows this Request now.
12807
13132
  const live = $list.querySelector(`[data-request-chat="start"][data-id="${CSS.escape(request.id)}"]`);
12808
13133
  if (live) live.textContent = label;
12809
- if (actionStatus && (!settingUp || actionStatus.textContent !== text)) actionStatus.textContent = text;
13134
+ if (actionStatus && (!settingUp || actionStatus.textContent !== text)) say(text);
12810
13135
  settingUp = true;
12811
13136
  },
12812
13137
  });
13138
+ unsay();
12813
13139
  closeRequests();
12814
13140
  } catch (error) {
12815
- if (error?.code === 'chat-start-cancelled') return;
13141
+ if (error?.code === 'chat-start-cancelled') { unsay(); return; }
13142
+ // #2185: it was set aside (dismissed in another window, or expired) after this list was painted - ask, never only fail.
13143
+ if (starting && REQUEST_SET_ASIDE_CODES.has(String(error?.code || ''))) {
13144
+ if (actionStatus) actionStatus.textContent = '';
13145
+ void askRestoreAndStart(request, provider, error.code);
13146
+ return;
13147
+ }
12816
13148
  // #2061: the project is busy — ask (wait and start by itself / open it / stop it), never only "failed".
12817
13149
  if (starting && REQUEST_START_BUSY_CODES.has(String(error?.code || '')) && error?.holder) {
12818
13150
  if (actionStatus) actionStatus.textContent = '';
@@ -12974,7 +13306,12 @@
12974
13306
  } catch (e) { reportErr(e); }
12975
13307
  };
12976
13308
  });
12977
- $list.querySelectorAll('.req-del').forEach((b) => { b.onclick = () => deleteOneRequest(b.dataset.id); });
13309
+ $list.querySelectorAll('.req-del').forEach((b) => {
13310
+ b.onclick = () => {
13311
+ const request = pendingRequests.find((candidate) => candidate && candidate.id === b.dataset.id);
13312
+ if (request) void dismissQueuedRequest(request);
13313
+ };
13314
+ });
12978
13315
  wireDiscardRecordQuestions($list);
12979
13316
  $list.querySelectorAll('.req-thumb').forEach((b) => {
12980
13317
  b.onclick = () => window.open(`/api/requests/${encodeURIComponent(b.dataset.id)}/snapshot/${b.dataset.n}`, '_blank');
@@ -16731,6 +17068,11 @@
16731
17068
  const clearFocused = document.activeElement?.id === 'wf-search-clear';
16732
17069
  const focusedDraft = document.activeElement?.closest?.('#wf-landing [data-wf-draft]')?.dataset.wfDraft || null;
16733
17070
  const focusedRestore = document.activeElement?.closest?.('[data-wf-restore]')?.dataset.wfRestore || null;
17071
+ // The Archived disclosure keeps its open state across repaints (apps-changed, search, restore); focus inside it implies open.
17072
+ // Focus on the summary alone must NOT force it open (the person just closed it); focus on a card inside must.
17073
+ const keepArchivedOpen = !!$wfLanding.querySelector('.wf-archived')?.open || !!document.activeElement?.closest?.('.wf-archived > .ws-grid');
17074
+ const keepSearchOpened = !!$wfLanding.querySelector('.wf-archived')?.dataset.searchOpened;
17075
+ const archivedSummaryFocused = !!document.activeElement?.closest?.('.wf-archived > summary');
16734
17076
  const focusedRestored = document.activeElement?.closest?.('[data-wf-restored]')?.dataset.wfRestored || null;
16735
17077
  const esc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
16736
17078
  const restoredRows = wfOwned.filter((row) => row.status !== 'archived' && row.restoreRefreshState);
@@ -16797,7 +17139,9 @@
16797
17139
  ? yoursGroup + group('Installed', installed, both)
16798
17140
  + '<div class="ws-empty-note ws-search-empty" id="wf-search-empty" role="status" aria-live="polite"></div>'
16799
17141
  : '<div class="ws-empty-note">No active workflows yet. Start with New workflow, or ask AI Chat on the left.</div>')
16800
- + (archived.length ? `<div class="wf-group-label">Archived (${archived.length})</div><div class="ws-grid">${archived.map(archivedCard).join('')}</div>` : '');
17142
+ + (archived.length ? `<details class="ws-archived wf-archived"><summary class="ws-archived-summary" data-command-id="shell.workflows-landing-archived"><span class="ws-archived-caret hd-caret" aria-hidden="true">▸</span>Archived <span class="ws-archived-count">${archived.length}</span></summary><div class="ws-grid">${archived.map(archivedCard).join('')}</div></details>` : '');
17143
+ if (keepArchivedOpen) { const d = $wfLanding.querySelector('.wf-archived'); if (d) { d.open = true; if (keepSearchOpened) d.dataset.searchOpened = '1'; } }
17144
+ if (archivedSummaryFocused) $wfLanding.querySelector('.wf-archived > summary')?.focus();
16801
17145
  if (focusedId) $wfLanding.querySelector(`[data-wf-id="${CSS.escape(focusedId)}"]`)?.focus();
16802
17146
  if (focusedDraft) $wfLanding.querySelector(`[data-wf-draft="${CSS.escape(focusedDraft)}"]`)?.focus();
16803
17147
  if (focusedRestore) $wfLanding.querySelector(`[data-wf-restore="${CSS.escape(focusedRestore)}"]:not(:disabled)`)?.focus();
@@ -16824,6 +17168,18 @@
16824
17168
  card.hidden = !terms.every((t) => hay.includes(t));
16825
17169
  if (!card.hidden) shown++;
16826
17170
  }
17171
+ const archivedBox = grid.closest('.wf-archived');
17172
+ if (archivedBox) {
17173
+ // The Archived disclosure counts in its summary; a search that matches opens it, an empty match hides all of it,
17174
+ // and clearing the search closes it again only if the search was what opened it.
17175
+ archivedBox.hidden = !shown;
17176
+ const count = archivedBox.querySelector('.ws-archived-count');
17177
+ if (count) count.textContent = terms.length ? `${shown} of ${cards.length}` : String(cards.length);
17178
+ if (terms.length && shown && !archivedBox.open) { archivedBox.open = true; archivedBox.dataset.searchOpened = '1'; }
17179
+ else if (!terms.length && archivedBox.dataset.searchOpened) { archivedBox.open = false; delete archivedBox.dataset.searchOpened; }
17180
+ shownAll += shown;
17181
+ continue;
17182
+ }
16827
17183
  grid.hidden = !shown;
16828
17184
  const label = grid.previousElementSibling?.classList.contains('wf-group-label') ? grid.previousElementSibling : null;
16829
17185
  if (label) {
@@ -16969,7 +17325,8 @@
16969
17325
  if (!d.hasSource) {
16970
17326
  body = d.recompile
16971
17327
  ? 'This workflow’s file is missing. Ask the AI in this chat to write it again.'
16972
- : 'This workflow has no workflow file yet. Ask the AI in this chat to write it.';
17328
+ // #2185: a next step that is true for every draft — one building in its chat, one handed to a terminal, one never started.
17329
+ : 'No steps yet. Build it with the AI in this workflow’s chat on the left; its steps appear here as soon as the AI saves them.';
16973
17330
  } else {
16974
17331
  body = d.recompile
16975
17332
  ? 'The compiled copy of this workflow is missing or no longer matches. Compile it again to run it.'
@@ -17074,6 +17431,8 @@
17074
17431
 
17075
17432
  if ($wfLanding) {
17076
17433
  $wfLanding.addEventListener('click', (event) => {
17434
+ // A hand toggle of Archived means the person owns its state now: clearing the search must not undo it.
17435
+ if (event.target.closest('.wf-archived > summary')) delete event.target.closest('.wf-archived').dataset.searchOpened;
17077
17436
  const restore = event.target.closest('[data-wf-restore]');
17078
17437
  if (restore) {
17079
17438
  if (!restore.disabled) {
@@ -17118,6 +17477,8 @@
17118
17477
  api,
17119
17478
  /** #2046: the ≡ menu's New workflow, opened from a Guide suggestion with its name filled in. */
17120
17479
  newWorkflow: (prefill) => requestNewWorkflow(prefill),
17480
+ // #2185: a Guide card's Build it — straight to its own conversation, no dialog.
17481
+ buildWorkflow: (input) => buildWorkflowInChat(input),
17121
17482
  requestScopeLabel(projectId) {
17122
17483
  return wsRequestScope?.kind === 'project' && wsRequestScope.project === projectId
17123
17484
  ? wsRequestScope.label : null;
@@ -17164,6 +17525,11 @@
17164
17525
  showWorkflowsLanding(false);
17165
17526
  return true;
17166
17527
  }
17528
+ // #2185: a draft built a moment ago is not in the cached list yet: read it once more before saying it is gone.
17529
+ if (!wfOwned.some((row) => row.workflowId === workflowId)) {
17530
+ try { ({ workflows: wfOwned } = await api('/api/workflows/owned')); }
17531
+ catch { throw new Error('FloLess couldn’t load your workflows just now. Try again, or open it from the Workflows page.'); }
17532
+ }
17167
17533
  if (wfOwned.some((row) => row.workflowId === workflowId && row.status !== 'archived')) {
17168
17534
  openDraftWorkflow(workflowId);
17169
17535
  return true;
@@ -17307,7 +17673,8 @@
17307
17673
  revealAiChat() {
17308
17674
  window.flolessLeftPane?.showSection?.('narrative');
17309
17675
  if (state.collapse.left) {
17310
- document.querySelector('.collapsed-stub .panel-toggle[data-side="left"]')?.click();
17676
+ // The toggle lives in the pane rail, outside the collapsed stub (#2185: the old selector matched nothing).
17677
+ document.querySelector('.panel-toggle[data-side="left"]')?.click();
17311
17678
  }
17312
17679
  },
17313
17680
  isRequestChatBlocked(requestId) {