@floless/app 0.141.0 → 0.141.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/web/aware.js CHANGED
@@ -42,6 +42,9 @@
42
42
  // type→view registry lives in renderers.js (a global, loaded before this file).
43
43
  const $contractEditor = document.getElementById('contract-editor');
44
44
  const $contractEditorFrame = document.getElementById('contract-editor-frame');
45
+ // The full-window editor overlay (model/drawing editor or Drawing Filter) — probed for unsaved work
46
+ // before Stop FloLess / Sign Out (web/leave-guard.js).
47
+ if (window.flolessLeaveGuard) window.flolessLeaveGuard.registerFrame($contractEditorFrame, 'editor-overlay');
45
48
  const $contractEditorTitle = document.getElementById('contract-editor-title');
46
49
 
47
50
  // One persistent array the inspect Execution tab reads; we mutate in place so
@@ -2747,8 +2750,42 @@
2747
2750
  // Refresh/close guard: unsaved input values live only in memory, so warn before
2748
2751
  // the page unloads while dirty (the browser shows its own generic confirm).
2749
2752
  window.addEventListener('beforeunload', (e) => {
2753
+ // __flolessLeaving / __flolessStopped: the user already answered the leave guard's question
2754
+ // (Sign Out, Stop FloLess) — asking again with the browser's own prompt would be a second,
2755
+ // uglier copy of the same decision.
2756
+ if (window.__flolessLeaving || window.__flolessStopped) return;
2750
2757
  if (!selfUpdating && isInputsDirty(currentId)) { e.preventDefault(); e.returnValue = ''; }
2751
2758
  });
2759
+ // Unsaved workflow inputs, for the leave guard (Stop FloLess / Sign Out). Every open workflow
2760
+ // with edits is listed — not only the one on screen — and "Save" writes each one the same way
2761
+ // Ctrl+S does for the current workflow.
2762
+ if (window.flolessLeaveGuard) {
2763
+ window.flolessLeaveGuard.register(() => [...dirtyBaseline.keys()].filter((id) => isInputsDirty(id)).map((id) => {
2764
+ const app = apps.get(id);
2765
+ return {
2766
+ id: `inputs:${id}`,
2767
+ label: `Workflow inputs for “${(app && app.displayName) || id}”`,
2768
+ detail: 'have changes that are not saved yet.',
2769
+ save: async () => {
2770
+ try {
2771
+ localStorage.setItem(lsInputsKey(id), JSON.stringify(appInputValues.get(id) || {}));
2772
+ setInputBaseline(id);
2773
+ refreshDirtyIndicator();
2774
+ } catch { return false; }
2775
+ return !isInputsDirty(id);
2776
+ },
2777
+ };
2778
+ }));
2779
+ // A workflow run in progress is warned about, never "saved".
2780
+ window.flolessLeaveGuard.register(leaveGuardRunItems);
2781
+ }
2782
+ // Read from the run-in-flight flags — the same ones that show the header ■ Stop run — never
2783
+ // from the painted run-state label, which can already read "Ready" while a run is still going
2784
+ // (seen in the browser QA after the HTML Viewer opened and was closed mid-run).
2785
+ function leaveGuardRunItems() {
2786
+ const inFlight = reportRunning || state.running || foregroundStarting || foregroundStopping || !!foregroundTrigger;
2787
+ return inFlight ? [{ id: 'run', kind: 'running', label: 'A workflow run' }] : [];
2788
+ }
2752
2789
  // Persist the active app's inputs to localStorage (the new build restores them on load).
2753
2790
  // Used before a self-update reload so an in-place adoption never drops unsaved edits.
2754
2791
  function persistCurrentInputs() {
@@ -7997,6 +8034,7 @@
7997
8034
  stat.appendChild(btn);
7998
8035
  }
7999
8036
  function setServerStatus(online) {
8037
+ if (window.__flolessStopped) return; // stopped on purpose — the "FloLess has stopped" screen owns the page
8000
8038
  if (online === serverOnline) return;
8001
8039
  const wasOnline = serverOnline;
8002
8040
  serverOnline = online;
@@ -8021,10 +8059,22 @@
8021
8059
  let awareRuntimeVersion = null; // installed AWARE version (from /api/health) — gates the freeze menu
8022
8060
  let freezeHintAppended = false; // append the right-click-to-freeze canvas hint once, when supported
8023
8061
  function startHealthPoll() {
8062
+ // One health check at a time (#1604). When the server answered slower than this 5-second poll, each
8063
+ // tick added another open request, and the pile held the browser's ~6 connections to this server —
8064
+ // AI Chat and every other request then waited behind it. Skip a tick instead. The check still gives
8065
+ // up after 45 s — past the licence check's own bounds — so a request that never answers cannot stop
8066
+ // the poll for good.
8067
+ let healthInFlight = false;
8024
8068
  const tick = async () => {
8069
+ if (window.__flolessStopped) return; // nothing to poll: the user stopped FloLess
8070
+ if (healthInFlight) return;
8071
+ healthInFlight = true;
8072
+ try { await healthTick(); } finally { healthInFlight = false; }
8073
+ };
8074
+ const healthTick = async () => {
8025
8075
  let ok = false;
8026
8076
  try {
8027
- const r = await fetch('/api/health', { cache: 'no-store' });
8077
+ const r = await fetch('/api/health', { cache: 'no-store', signal: AbortSignal.timeout(45_000) });
8028
8078
  ok = r.ok;
8029
8079
  if (ok) {
8030
8080
  const h = await r.json();
@@ -8659,6 +8709,12 @@
8659
8709
  // failure, or an unfamiliar terminal state after its Copy carrier rendered. The row already uses
8660
8710
  // requestCanCopy; enforcing it again here prevents a stale click from claiming obsolete
8661
8711
  // instructions were copied successfully.
8712
+ // AI Chat ownership gets its OWN result, because it is not an absence. Falling through to
8713
+ // `empty` told the user "this request has no instruction" about a request whose instruction is
8714
+ // complete and simply already held — and `settled` would claim it had moved on. For a revision
8715
+ // read the check runs against the freshly re-read row above, so a conversation another tab
8716
+ // started between paint and click is caught here rather than handed a second writer.
8717
+ if (requestRunsInChat(current)) return 'chat-owned';
8662
8718
  if (!requestCanCopy(current)) return revisionReadCannotRestart(current) ? 'settled' : 'empty';
8663
8719
  const line = current ? markedInstruction(current) : '';
8664
8720
  if (!line) return 'empty';
@@ -8673,6 +8729,8 @@
8673
8729
  ? ['This drawing read has moved on — open Requests for the next step', 'warn']
8674
8730
  : res === 'unavailable'
8675
8731
  ? ['FloLess couldn’t check the latest drawing-read state — open Requests and try again', 'warn']
8732
+ : res === 'chat-owned'
8733
+ ? ['AI Chat holds this request — open AI Chat on the left (expand that panel if it is collapsed) to see where it stands', 'warn']
8676
8734
  : res === 'empty'
8677
8735
  ? ['Nothing to copy — this request has no instruction', 'err']
8678
8736
  : ['copy failed', 'err']);
@@ -8710,32 +8768,230 @@
8710
8768
  // from is cached 10 s server-side (one CLI status call per provider per window at most), so an
8711
8769
  // open is still cheap.
8712
8770
  let headlessInfo = null;
8771
+ // Several surfaces read the runtimes at once, and their answers can arrive in any order. Every read
8772
+ // claims the next epoch BEFORE it asks (`headlessFetchEpoch`), and its answer is published to the
8773
+ // shared rows only when it is newer than the answer they already hold (`headlessPublishedEpoch`).
8774
+ // So the newest answer always wins, and a slow older one never overwrites it. A launch read or a
8775
+ // keeping-last re-read that fails publishes nothing, so it buries nothing: an older read that did get
8776
+ // an answer is still shared. refreshHeadless is the one exception, on purpose: it publishes its
8777
+ // failure (null) as the newest thing known, because a detection failure hides the feature (#1621).
8713
8778
  let headlessFetchEpoch = 0;
8779
+ let headlessPublishedEpoch = 0;
8780
+ function publishHeadless(epoch, info) {
8781
+ if (epoch <= headlessPublishedEpoch) return false;
8782
+ headlessPublishedEpoch = epoch;
8783
+ headlessInfo = info;
8784
+ return true;
8785
+ }
8714
8786
  async function refreshHeadless() {
8715
8787
  // A detection failure HIDES the feature rather than leaving a button that cannot work. There is
8716
- // no honest middle: without the runtime list we do not know that anything is installed.
8788
+ // no honest middle: without the runtime list we do not know that anything is installed. So this
8789
+ // read publishes its failure too, as the newest thing known, unless a newer answer is already in.
8717
8790
  const epoch = ++headlessFetchEpoch;
8718
8791
  let next;
8719
8792
  try { next = await api('/api/terminal-runtimes'); }
8720
8793
  catch { next = null; }
8721
- // Several surfaces can ask at once. A slow earlier probe must not overwrite a newer answer and
8722
- // leave the visible Start guidance disagreeing with the shared runtime state.
8723
- if (epoch !== headlessFetchEpoch) return headlessInfo;
8724
- headlessInfo = next;
8794
+ publishHeadless(epoch, next);
8725
8795
  return headlessInfo;
8726
8796
  }
8797
+ // The New project dialog's read (#1605), also the re-read after a setup that did not finish (#1607).
8798
+ // NOT refreshHeadless(): that one NULLS the shared runtime state on a failed read, so one blip while
8799
+ // the dialog is open would hide its chat path and every Start affordance in Requests with it. Only a
8800
+ // well-formed answer is published; a failed read publishes nothing, says so in the console, and
8801
+ // returns false so the dialog can ask again.
8802
+ async function refreshChatProvidersKeepingLast() {
8803
+ const epoch = ++headlessFetchEpoch;
8804
+ try {
8805
+ const info = await api('/api/terminal-runtimes');
8806
+ if (info && Array.isArray(info.runtimes)) {
8807
+ publishHeadless(epoch, info);
8808
+ return true;
8809
+ }
8810
+ console.warn('floless: a re-read of the terminal runtimes had no runtime list', info);
8811
+ } catch (error) {
8812
+ console.warn('floless: could not re-read the terminal runtimes', error);
8813
+ }
8814
+ return false;
8815
+ }
8727
8816
  const headlessRuntimes = () => (headlessInfo && Array.isArray(headlessInfo.runtimes) ? headlessInfo.runtimes : []);
8728
- /** Zero runtimes found ⇒ no run affordance anywhere (§E4). Hidden, never disabled. */
8729
- const headlessReady = () => headlessRuntimes().some((r) => r && r.state === 'found');
8817
+ /**
8818
+ * Whether FloLess can start Claude or Codex from one of its runtime rows — THE one answer every
8819
+ * way into a conversation or a run shares (#1607): 'ready', 'setup' (FloLess sets up its own copy
8820
+ * when the conversation opens, and the chat waits for it), or 'unavailable'.
8821
+ *
8822
+ * It follows what FloLess would LAUNCH. A row carries `managed` exactly when FloLess launches its
8823
+ * own tested copy (`isManagedLaunch`, server/terminal-runtime.ts); then the user's own install is
8824
+ * irrelevant and only that copy's state counts. Without managed launch, the user's install is what
8825
+ * runs, so `state: 'found'` is the test. Anything this build cannot name fails closed.
8826
+ */
8827
+ function chatRuntimeReadiness(runtime) {
8828
+ if (!runtime || (runtime.id !== 'claude' && runtime.id !== 'codex')) return 'unavailable';
8829
+ const managed = runtime.managed;
8830
+ if (managed && typeof managed === 'object') {
8831
+ if (managed.state === 'installed') return 'ready';
8832
+ if (managed.state === 'not-installed' || managed.state === 'preparing') return 'setup';
8833
+ if (managed.state === 'failed') return managed.retryable === true ? 'setup' : 'unavailable';
8834
+ return 'unavailable';
8835
+ }
8836
+ return runtime.state === 'found' ? 'ready' : 'unavailable';
8837
+ }
8838
+ const chatRuntimeCanStart = (runtime) => chatRuntimeReadiness(runtime) !== 'unavailable';
8839
+ const chatRuntimeRow = (id) => headlessRuntimes().find((runtime) => runtime && runtime.id === id) || null;
8840
+ /** No AI FloLess can start ⇒ no run affordance anywhere (§E4). Hidden, never disabled. */
8841
+ const headlessReady = () => headlessRuntimes().some(chatRuntimeCanStart);
8842
+ // Which AI a new conversation or run starts with: the open conversation's AI, then the default,
8843
+ // then an AI that is ready now before one FloLess still has to set up. Each is checked against
8844
+ // what can start — the open conversation's AI may since have become unable to (#1607).
8730
8845
  const preferredChatProvider = () => {
8731
8846
  const current = window.flolessChat?.currentProvider?.();
8732
- if (current === 'claude' || current === 'codex') return current;
8847
+ if ((current === 'claude' || current === 'codex') && chatRuntimeCanStart(chatRuntimeRow(current))) return current;
8733
8848
  const chosen = headlessInfo?.provider;
8734
- if ((chosen === 'claude' || chosen === 'codex')
8735
- && headlessRuntimes().some((runtime) => runtime?.id === chosen && runtime.state === 'found')) return chosen;
8736
- return headlessRuntimes().find((runtime) => (runtime?.id === 'claude' || runtime?.id === 'codex')
8737
- && runtime.state === 'found')?.id || null;
8849
+ if ((chosen === 'claude' || chosen === 'codex') && chatRuntimeCanStart(chatRuntimeRow(chosen))) return chosen;
8850
+ const rows = headlessRuntimes();
8851
+ return rows.find((runtime) => chatRuntimeReadiness(runtime) === 'ready')?.id
8852
+ || rows.find((runtime) => chatRuntimeReadiness(runtime) === 'setup')?.id || null;
8738
8853
  };
8854
+
8855
+ // ── Set up first, then start (#1607) ────────────────────────────────────────
8856
+ // A project intake or a Request started in AI Chat sends its first message the moment the
8857
+ // conversation exists. If FloLess's own copy of that AI is not installed yet, that message is
8858
+ // refused ("Not sent") and nothing re-sends it after setup. So an entry point that starts a chat
8859
+ // with an AI in the 'setup' state first has FloLess set it up, waits for it, and only then starts.
8860
+ // Nothing is created while waiting, so a setup that fails or is cancelled leaves nothing behind.
8861
+ const CHAT_RUNTIME_NAMES = { claude: 'Claude', codex: 'Codex' };
8862
+ const CHAT_RUNTIME_POLL_MS = 2000;
8863
+ const CHAT_RUNTIME_READ_FAILURES = 3;
8864
+ // Why this AI could not be set up, in the AI Chat panel's own words when it can give them.
8865
+ function chatRuntimeSetupFailure(provider, status) {
8866
+ const name = CHAT_RUNTIME_NAMES[provider] || 'This AI';
8867
+ const notice = status ? window.flolessChat?.runtimeNotice?.(provider, status) : null;
8868
+ return notice && notice.title && notice.body
8869
+ ? `${notice.title}. ${notice.body}`
8870
+ : `${name} couldn’t be set up. Open AI Chat with ${name} to see why and try again.`;
8871
+ }
8872
+ /**
8873
+ * Resolves `{ ok: true }` once `provider` can take a first message, or `{ ok: false, reason }`
8874
+ * (`cancelled: true` when the caller gave up). `onProgress(status)` reports each setup status;
8875
+ * `isCancelled()` is checked between reads, so a late finish after Cancel starts nothing. The
8876
+ * install itself carries on server-side either way, as it does when AI Chat is left.
8877
+ */
8878
+ async function ensureChatRuntimeReady(provider, options = {}) {
8879
+ const result = await waitForChatRuntime(provider, options);
8880
+ // A setup that did not finish changed this AI's state: re-read it, so every Start and the
8881
+ // New project dialog show where it now stands (for example "couldn't be set up").
8882
+ if (!result.ok && !result.cancelled) await refreshChatProvidersKeepingLast();
8883
+ return result;
8884
+ }
8885
+ // What launching `provider` would see now, from a read of its own. It answers with exactly one of:
8886
+ // { row } the AI's row from THIS read's answer, whether or not that answer is published;
8887
+ // { missing: true } the read answered but lists no row for this AI, which asking again cannot fix;
8888
+ // { failed: true } the read failed, or answered without a runtime list.
8889
+ // No start decision is ever taken from the shared rows: they can predate a change, and a surface can
8890
+ // stay open for a long time between its read and the start (#1607, #1621). The answer is published
8891
+ // like every read's (publishHeadless); a failed launch read publishes nothing, so it buries nothing,
8892
+ // and every failure is logged.
8893
+ async function readChatRuntimeLaunch(provider) {
8894
+ const epoch = ++headlessFetchEpoch;
8895
+ let fresh;
8896
+ try { fresh = await api('/api/terminal-runtimes'); }
8897
+ catch (error) {
8898
+ console.warn(`floless: could not read whether ${provider} can start`, error);
8899
+ return { failed: true };
8900
+ }
8901
+ if (!fresh || !Array.isArray(fresh.runtimes)) {
8902
+ console.warn(`floless: the read of whether ${provider} can start had no runtime list`, fresh);
8903
+ return { failed: true };
8904
+ }
8905
+ publishHeadless(epoch, fresh);
8906
+ const row = fresh.runtimes.find((candidate) => candidate && candidate.id === provider) || null;
8907
+ if (!row) {
8908
+ console.warn(`floless: the runtimes read lists no ${provider} row`, fresh.runtimes.map((candidate) => candidate?.id));
8909
+ return { missing: true };
8910
+ }
8911
+ return { row };
8912
+ }
8913
+ async function waitForChatRuntime(provider, { isCancelled = () => false, onProgress = () => {} } = {}) {
8914
+ const name = CHAT_RUNTIME_NAMES[provider] || 'This AI';
8915
+ const cancelled = { ok: false, cancelled: true, reason: '' };
8916
+ const unchecked = { ok: false, reason: `FloLess couldn’t check the ${name} setup. Try again.` };
8917
+ // The server lists every AI FloLess can run, so a missing row is no blip a retry would fix.
8918
+ const unlisted = { ok: false, reason: `FloLess can’t offer ${name} right now. Choose the other AI, or restart FloLess and try again.` };
8919
+ // A cancel is honoured before and after every wait below: once the caller has given up, nothing more
8920
+ // is asked, set up or started.
8921
+ if (isCancelled()) return cancelled;
8922
+ // Decided from a fresh read, never the rows a surface was painted from: those may say "ready" for a
8923
+ // copy that has failed or gone since, and starting on them sends a first message that comes back
8924
+ // "Not sent" (#1621).
8925
+ const launch = await readChatRuntimeLaunch(provider);
8926
+ if (isCancelled()) return cancelled;
8927
+ if (launch.failed) return unchecked;
8928
+ if (launch.missing) return unlisted;
8929
+ const readiness = chatRuntimeReadiness(launch.row);
8930
+ if (readiness === 'ready') return { ok: true };
8931
+ if (readiness !== 'setup') return { ok: false, reason: `${name} can’t start on this computer. Choose the other AI, or open AI Chat with ${name} to see why.` };
8932
+ let status;
8933
+ try {
8934
+ // The Retry route: idempotent, and it retries a failed setup at once (a press is explicit intent).
8935
+ status = (await api(`/api/managed-runtimes/${encodeURIComponent(provider)}/prepare`, { method: 'POST', body: '{}' }))?.runtime;
8936
+ } catch (error) {
8937
+ console.warn(`floless: could not ask FloLess to set up ${provider}`, error);
8938
+ // A wait that ends in an error still ends after a cancel: honour it, or the re-read that follows a
8939
+ // failed setup would still be asked for a start nobody is waiting for.
8940
+ if (isCancelled()) return cancelled;
8941
+ return { ok: false, reason: `FloLess couldn’t start setting up ${name}. Try again.` };
8942
+ }
8943
+ let failedReads = 0;
8944
+ for (;;) {
8945
+ if (isCancelled()) return cancelled;
8946
+ if (status && status.state === 'installed') break;
8947
+ if (status && status.state === 'failed') return { ok: false, reason: chatRuntimeSetupFailure(provider, status), status };
8948
+ if (status) onProgress(status);
8949
+ await new Promise((resolve) => setTimeout(resolve, CHAT_RUNTIME_POLL_MS));
8950
+ if (isCancelled()) return cancelled;
8951
+ try {
8952
+ const body = await api('/api/managed-runtimes');
8953
+ const next = Array.isArray(body?.runtimes) ? body.runtimes.find((row) => row && row.runtime === provider) : null;
8954
+ if (!next) throw new Error('no status for this AI');
8955
+ status = next;
8956
+ failedReads = 0;
8957
+ } catch (error) {
8958
+ failedReads += 1;
8959
+ console.warn(`floless: could not read how the ${provider} setup is going`, error);
8960
+ if (failedReads >= CHAT_RUNTIME_READ_FAILURES) return isCancelled() ? cancelled : unchecked;
8961
+ }
8962
+ }
8963
+ // Installed is not yet launchable: read what launching would see NOW, and start only on 'ready'.
8964
+ // Published like any read, so every Start and the New project dialog see the post-install rows too.
8965
+ const installed = await readChatRuntimeLaunch(provider);
8966
+ if (isCancelled()) return cancelled;
8967
+ if (installed.failed) return unchecked;
8968
+ if (installed.missing) return unlisted;
8969
+ if (chatRuntimeReadiness(installed.row) === 'ready') return { ok: true };
8970
+ return installed.row.managed?.state === 'failed'
8971
+ ? { ok: false, reason: chatRuntimeSetupFailure(provider, installed.row.managed) }
8972
+ : unchecked;
8973
+ }
8974
+ // The one way a Request is started in AI Chat: sets the AI up first when it needs it (`discuss`
8975
+ // sends nothing, so it never waits). A setup that does not finish throws with its reason, marked
8976
+ // `chat-runtime-not-ready` so callers can show that reason instead of a generic failure. The
8977
+ // caller's `isCancelled()` (the surface closed, or the Request changed) stops it before anything is
8978
+ // started, with `chat-start-cancelled`, which callers drop silently.
8979
+ async function startRequestChatWithSetup(requestId, provider, mode, { onSetup, isCancelled = () => false } = {}) {
8980
+ if (typeof window.flolessChat?.startRequest !== 'function') throw new Error('AI Chat is still starting. Try again in a moment.');
8981
+ if (mode === 'start') {
8982
+ const ready = await ensureChatRuntimeReady(provider, { onProgress: (status) => onSetup?.(status), isCancelled });
8983
+ if (ready.cancelled || isCancelled()) throw Object.assign(new Error('The start was cancelled.'), { code: 'chat-start-cancelled' });
8984
+ if (!ready.ok) throw Object.assign(new Error(ready.reason), { code: 'chat-runtime-not-ready' });
8985
+ }
8986
+ return window.flolessChat.startRequest(requestId, provider, mode);
8987
+ }
8988
+ // Requests being started in AI Chat while FloLess sets their AI up, by request id → { label } of the
8989
+ // busy button. Kept outside the list, so a repaint during a long setup shows the same busy button
8990
+ // instead of a fresh one that invites a second start (#1607). Each Start sets its own entry object and
8991
+ // clears the entry only while it is still that object, so nothing else (a failing Discuss on the
8992
+ // same request, #1651) can end a Start that is still running.
8993
+ const requestChatStarts = new Map();
8994
+ const chatRuntimeSetupLabel = (provider) => `Setting up ${CHAT_RUNTIME_NAMES[provider] || 'AI'}…`;
8739
8995
  const runtimeLabel = (id) => {
8740
8996
  const m = headlessRuntimes().find((r) => r && r.id === id);
8741
8997
  return (m && m.label) || String(id || 'your terminal AI');
@@ -8827,8 +9083,16 @@
8827
9083
  return copied ? 'ok' : 'denied';
8828
9084
  }
8829
9085
 
8830
- function runStatusHtml(run, stampedResumeCommand, desktopHandoffs, requestId, commandInstance, ownRecoverySurface, filterGuide = null) {
9086
+ function runStatusHtml(run, stampedResumeCommand, desktopHandoffs, requestId, commandInstance, ownRecoverySurface, filterGuide = null, filterNotStarted = false) {
8831
9087
  if (!run || !run.state) return '';
9088
+ // A Drawing Filter message the run route refused before anything started (#1650). Its row already
9089
+ // says so (filterGuideRequestNote); the failed run a late refusal leaves behind adds no second note,
9090
+ // badge or private folder, only what the refused attempt printed.
9091
+ if (filterGuide && filterNotStarted) {
9092
+ return run.lastOutput
9093
+ ? `<div class="req-run-status"><details class="req-run-output"><summary>Show what it printed</summary><pre>${escapeHtml(run.lastOutput)}</pre></details></div>`
9094
+ : '';
9095
+ }
8832
9096
  const v = RUN_VIEW[run.state] || { badge: String(run.state), cls: 'muted', note: () => '' };
8833
9097
  const rt = runtimeLabel(run.runtime);
8834
9098
  // `resumeCommand` belongs to the SERVER'S request view, not persisted `run` metadata: the
@@ -8975,7 +9239,8 @@
8975
9239
  let info;
8976
9240
  try { info = await api(`/api/terminal-runtimes${key ? `?project=${encodeURIComponent(key)}` : ''}`); }
8977
9241
  catch (e) { reportErr(e); return null; }
8978
- const found = (info.runtimes || []).filter((r) => r && r.state === 'found');
9242
+ // Every AI FloLess can start (#1607): a copy FloLess sets up itself counts, as it does for ▶.
9243
+ const found = (info.runtimes || []).filter((r) => chatRuntimeCanStart(r));
8979
9244
  if (!found.length) { showToast('No supported AI provider is installed on this computer.', 'warn'); return null; }
8980
9245
  let folder = info.folder || '';
8981
9246
  let sub = problem || '';
@@ -9109,6 +9374,31 @@
9109
9374
  return requestHelpEpoch === epoch && !requestHelpReq && !modal.classList.contains('show');
9110
9375
  }
9111
9376
 
9377
+ // Who is driving a Request. `chatConversation` is server-owned: `executionOwner: 'chat'` is
9378
+ // stamped only when the read was really STARTED in the AI Chat panel ('discussion' means a
9379
+ // conversation is open but nothing was started). Ownership never expires, so it cannot say
9380
+ // whether AI Chat is working RIGHT NOW — the conversation's own state is the part that moves, and
9381
+ // an unrecognised state counts as not working so no surface claims motion nothing can see.
9382
+ // WORKING means the conversation is moving on its own. `awaiting-approval` (parked on an approval
9383
+ // only the person can answer) and `recovery` (the turn broke; AI Chat disables its own composer and
9384
+ // shows a recovery control) are the opposite of that, and calling them working told someone to
9385
+ // leave a stalled read running. Kept byte-identical to web/workspaces.js — a drift guard compares
9386
+ // the two declarations, because the banner and this window paint the same request on one screen.
9387
+ const CHAT_WORKING_STATES = ['starting', 'running'];
9388
+ const CHAT_BLOCKED_ACTIONS = { 'awaiting-approval': 'answer the question it is waiting on', recovery: 'use its recovery control' };
9389
+ const requestRunsInChat = (req) => req?.chatConversation?.executionOwner === 'chat';
9390
+ const requestChatStateOf = (req) => (requestRunsInChat(req) ? req?.chatConversation?.chatState ?? null : null);
9391
+ const requestWorkingInChat = (req) => CHAT_WORKING_STATES.includes(requestChatStateOf(req));
9392
+ const requestChatBlockedAction = (req) => CHAT_BLOCKED_ACTIONS[requestChatStateOf(req)] || '';
9393
+ const requestChatUnreadable = (req) => requestChatStateOf(req) === 'unreadable';
9394
+ /** One conversation can hold several Requests, so a moving chat is not proof THIS read is moving. */
9395
+ const requestChatBusyElsewhere = (req) => requestChatStateOf(req) === 'busy-elsewhere';
9396
+ // A failed or interrupted reply is not merely paused (#1611) — each names its own next step.
9397
+ const requestChatFailed = (req) => requestChatStateOf(req) === 'failed';
9398
+ const requestChatInterrupted = (req) => requestChatStateOf(req) === 'interrupted';
9399
+ /** An archived conversation's composer is disabled, so "tell it to continue" needs a restore first. */
9400
+ const requestChatArchived = (req) => requestChatStateOf(req) === 'archived';
9401
+
9112
9402
  /** Keep the upload handoff's words on the exact same runtime gate as its Start control. */
9113
9403
  function renderRequestHelpGuidance(req) {
9114
9404
  if (!req) return;
@@ -9124,14 +9414,41 @@
9124
9414
  const retainedRevisionWhy = retainedRevisionRecovery
9125
9415
  ? (req.clearWhy || 'FloLess cannot safely release this drawing read yet. Restart FloLess and open Requests again.')
9126
9416
  : '';
9417
+ // A Request AI Chat already owns must not be offered a second start: `status` stays 'pending'
9418
+ // while the conversation works, because it tracks the server-side read and not who is executing
9419
+ // it. Without this the modal re-offered "Start in AI Chat" on a read already running there.
9420
+ // ONLY while the request is still pending. `executionOwner` never expires — that is this work's
9421
+ // own premise — so a read AI Chat started and then finished, failed, or left in a status this
9422
+ // build does not know still satisfies it. Leading with the chat arm replaced "the drawing read
9423
+ // is complete, choose Review changes" with "go and nag that conversation", and dropped the
9424
+ // failed/unrecognised recovery instructions entirely.
9425
+ const chatOwnsRequest = requestRunsInChat(req) && (!isRevisionRead || isPendingRevisionRead);
9127
9426
  const canStartInChat = Boolean((req.project || req.workflowId) && preferredChatProvider()
9128
- && (!isRevisionRead || req.status === 'pending'));
9427
+ && !chatOwnsRequest && (!isRevisionRead || req.status === 'pending'));
9129
9428
  const ownerNoun = req.project ? 'project' : 'workflow';
9130
9429
  const canStartUpdatedRead = isRevisionRead && req.status === 'pending' && !isInitial && req.canRun && headlessReady();
9131
9430
  const $steps = document.getElementById('request-help-steps');
9132
9431
  const $note = document.getElementById('request-help-note');
9133
9432
  if ($steps) {
9134
- $steps.innerHTML = canStartInChat
9433
+ $steps.innerHTML = chatOwnsRequest
9434
+ ? `<div class="request-help-step"><span>1</span><p>This request is already ${requestWorkingInChat(req) ? 'running' : requestChatBusyElsewhere(req) ? 'waiting on a reply' : 'open'} in AI Chat, in the panel on the left.</p></div>`
9435
+ + `<div class="request-help-step"><span>2</span><p>${requestChatBlockedAction(req)
9436
+ ? `That conversation is waiting for you: ${escapeHtml(requestChatBlockedAction(req))}.`
9437
+ : requestChatUnreadable(req)
9438
+ ? 'FloLess could not read that conversation. Open it to check; if it will not open, use Report an issue.'
9439
+ : requestChatArchived(req)
9440
+ ? 'That conversation is archived, so its composer is disabled. Restore it first, then tell it to continue.'
9441
+ : requestChatBusyElsewhere(req)
9442
+ ? escapeHtml(requestChatBusyNextStep(req))
9443
+ : requestWorkingInChat(req)
9444
+ ? 'Continue there — there is nothing to start in this window.'
9445
+ : requestChatFailed(req)
9446
+ ? 'AI Chat’s last reply ended with an error. Open that conversation to see what went wrong, then ask it to try again — do not start this request again here.'
9447
+ : requestChatInterrupted(req)
9448
+ ? 'AI Chat’s reply stopped before it finished. Open that conversation and tell it to continue — do not start this request again here.'
9449
+ : 'Open AI Chat and tell it to continue — do not start this request again here.'}</p></div>`
9450
+ + '<div class="request-help-step"><span>3</span><p>FloLess updates the project as that conversation makes progress. A drawing read still needs you to review the Drawing Filter and press Save filter.</p></div>'
9451
+ : canStartInChat
9135
9452
  ? `<div class="request-help-step"><span>1</span><p>Choose Start in AI Chat below. The conversation opens in this ${ownerNoun}’s folder.</p></div>`
9136
9453
  + `<div class="request-help-step"><span>2</span><p>Continue in AI Chat while Claude or Codex reads the ${allPdf ? 'PDF set' : 'drawing files'}.</p></div>`
9137
9454
  + '<div class="request-help-step"><span>3</span><p>Review any question or proposed change in the same conversation before it continues.</p></div>'
@@ -9148,14 +9465,30 @@
9148
9465
  : '<div class="request-help-step"><span>1</span><p>This drawing read failed. Attach the drawing set again from Drawing Filter to retry safely.</p></div>'
9149
9466
  : '<div class="request-help-step"><span>1</span><p>Open Requests to inspect this drawing request. Update FloLess before retrying a status this version does not recognize.</p></div>'
9150
9467
  : isRevisionRead
9151
- ? '<div class="request-help-step"><span>1</span><p>Open Claude Code, Codex, or OpenCode in your project folder.</p></div>'
9468
+ ? '<div class="request-help-step"><span>1</span><p>Open Claude Code or Codex in your project folder.</p></div>'
9152
9469
  + `<div class="request-help-step"><span>2</span><p>Paste the copied request. It will read the ${allPdf ? 'PDF' : 'drawing file'} and prepare the Drawing Filter.</p></div>`
9153
9470
  + '<div class="request-help-step"><span>3</span><p>When it stops, open Drawing Filter. Check steel, member marks, grids, dimensions, and relevant callouts; ask in AI Chat on the left if you are unsure. Then press Save filter in the top-right corner. After Save, return to the same terminal AI and tell it to continue the drawing read.</p></div>'
9154
- : '<div class="request-help-step"><span>1</span><p>Open Claude Code, Codex, or OpenCode in your project folder.</p></div>'
9471
+ : '<div class="request-help-step"><span>1</span><p>Open Claude Code or Codex in your project folder.</p></div>'
9155
9472
  + '<div class="request-help-step"><span>2</span><p>Paste the copied request and let your terminal AI apply it.</p></div>'
9156
9473
  + '<div class="request-help-step"><span>3</span><p>Return here to check the result in FloLess.</p></div>';
9157
9474
  }
9158
- if ($note) $note.textContent = canStartInChat
9475
+ if ($note) $note.textContent = chatOwnsRequest
9476
+ ? requestChatBlockedAction(req)
9477
+ ? `AI Chat on the left owns this request and is waiting for you: open that conversation and ${requestChatBlockedAction(req)}. It carries on once you do.`
9478
+ : requestChatUnreadable(req)
9479
+ ? 'AI Chat on the left owns this request, but FloLess could not read that conversation. Open it to check. If it will not open, use Report an issue rather than starting the request again.'
9480
+ : requestChatArchived(req)
9481
+ ? 'AI Chat on the left owns this request, and that conversation is archived — its composer is disabled until you restore it. Restore it and tell it to continue, rather than starting the request again.'
9482
+ : requestChatBusyElsewhere(req)
9483
+ ? `AI Chat on the left owns this request. ${requestChatBusyNextStep(req)}`
9484
+ : requestWorkingInChat(req)
9485
+ ? 'AI Chat on the left already owns this request and is working on it. Leave it running; FloLess updates the project as it goes.'
9486
+ : requestChatFailed(req)
9487
+ ? 'AI Chat on the left owns this request, but its last reply ended with an error. Open that conversation to see what went wrong and ask it to try again, rather than starting the request again.'
9488
+ : requestChatInterrupted(req)
9489
+ ? 'AI Chat on the left owns this request, but its reply stopped before it finished. Open that conversation and tell it to continue, rather than starting the request again.'
9490
+ : 'AI Chat on the left owns this request but is not working on it right now. Open that conversation and tell it to continue, rather than starting the request again.'
9491
+ : canStartInChat
9159
9492
  ? `The request and its conversation stay with this ${ownerNoun}. If chat cannot start, the request remains queued and the terminal copy remains available.`
9160
9493
  : isUnknownRevisionStatus
9161
9494
  ? retainedRevisionRecovery
@@ -9173,7 +9506,7 @@
9173
9506
  : canStartUpdatedRead
9174
9507
  ? 'If a supported terminal AI is available, choose Start automatically. You can also paste the request into your terminal AI. After Save, return to that same terminal AI and tell it to continue; FloLess will show the result here.'
9175
9508
  : req.canRun
9176
- ? 'No supported terminal AI is available for automatic start here. Paste this request into Claude Code, Codex, or OpenCode. After Save, return to that same terminal AI and tell it to continue.'
9509
+ ? 'No supported terminal AI is available for automatic start here. Paste this request into Claude Code or Codex. After Save, return to that same terminal AI and tell it to continue.'
9177
9510
  : `Paste this request into your terminal AI to continue.${req.runWhy ? ` ${req.runWhy}` : ''}`
9178
9511
  : 'FloLess queues the request; your terminal AI applies it and reports the result back here.';
9179
9512
  }
@@ -9185,11 +9518,14 @@
9185
9518
  const $chat = document.getElementById('request-help-chat');
9186
9519
  const $chatMeta = document.getElementById('request-help-chat-meta');
9187
9520
  if (!$split || !$open || !$chat || !$chatMeta) return;
9188
- const can = !!(!requestHelpBusyMode && !requestHelpRunActive && requestHelpReq && requestHelpReq.canRun
9521
+ // Same gate as the wording above, for the same reason: `status` stays 'pending' while AI Chat
9522
+ // works the request, so neither start control may key off it alone.
9523
+ const chatOwns = requestRunsInChat(requestHelpReq);
9524
+ const can = !!(!requestHelpBusyMode && !requestHelpRunActive && requestHelpReq && requestHelpReq.canRun && !chatOwns
9189
9525
  && (requestHelpReq.type !== 'revision-read' || requestHelpReq.status === 'pending') && headlessReady());
9190
9526
  $split.hidden = !can;
9191
9527
  const canChat = Boolean(!requestHelpRunActive && requestHelpReq && (requestHelpReq.project || requestHelpReq.workflowId)
9192
- && preferredChatProvider() && requestHelpReq.status === 'pending');
9528
+ && preferredChatProvider() && !chatOwns && requestHelpReq.status === 'pending');
9193
9529
  $chat.hidden = !canChat;
9194
9530
  $chat.disabled = !!requestHelpBusyMode;
9195
9531
  const provider = canChat ? preferredChatProvider() : null;
@@ -9225,8 +9561,13 @@
9225
9561
  /** Fields whose change makes the upload handoff modal's guidance or Start policy stale. */
9226
9562
  function requestHelpStateKey(r) {
9227
9563
  if (!r) return '';
9564
+ // Who owns the request, and whether that conversation is working, decide this modal's steps, its
9565
+ // note AND whether its two Start controls render. Without them another tab starting the request
9566
+ // in AI Chat leaves the old handoff modal open with a live Start button on a request that now
9567
+ // has an owner — the same stale-repaint defect the revision card's key exists to stop.
9228
9568
  return [r.status, !!r.prepassReady, !!r.filterCheckpointCurrent, !!r.canRun, r.runWhy || '',
9229
- r.run && r.run.state || '', r.resumeCommand || '', !!r.desktopHandoffs].join('|');
9569
+ r.run && r.run.state || '', r.resumeCommand || '', !!r.desktopHandoffs,
9570
+ r.chatConversation?.executionOwner || '', r.chatConversation?.chatState || ''].join('|');
9230
9571
  }
9231
9572
 
9232
9573
  /**
@@ -9535,6 +9876,12 @@
9535
9876
  // The Drawing Filter's read-only AI protocol (sent from AI Chat) must never turn into a terminal copy/retry path,
9536
9877
  // even when an older Requests response still carries canCopy: true.
9537
9878
  if (isFilterAiGuideRequest(r)) return false;
9879
+ // Nor may a request AI Chat is EXECUTING. `canCopy` is server policy about the request's
9880
+ // lifecycle and says nothing about who holds it, so it stays true throughout a chat-driven read;
9881
+ // the row button, the bulk copy and the help modal's own Copy all funnel through here. Pasting
9882
+ // that instruction into a terminal is how a second reader lands in one project folder — the
9883
+ // exact handoff this work removed from the cards. 'discussion' is not execution and keeps Copy.
9884
+ if (requestRunsInChat(r)) return false;
9538
9885
  // Current servers own this lifecycle decision together with automatic Retry and the manifest
9539
9886
  // route. The fallback is only for an older server response already cached in this tab.
9540
9887
  if (typeof r?.canCopy === 'boolean') return r.canCopy;
@@ -9568,9 +9915,19 @@
9568
9915
  && r?.preparationState !== 'blocked'
9569
9916
  && !(r?.preparationState === 'manifest-published' && !r?.prepassReady)
9570
9917
  && revisionReadCannotRestart(r)).length;
9918
+ // A request AI Chat is EXECUTING needs its own category, because `incompleteSkipped` is the
9919
+ // arithmetic remainder: without this it lands there and the toast says "did not have a complete
9920
+ // instruction", which is untrue — the instruction is complete, it is simply already held. The
9921
+ // categories stay disjoint in the same order the others do, active run first.
9922
+ const chatOwnedSkipped = shown.filter((r) => !requestHasActiveRun(r)
9923
+ && r?.preparationState !== 'blocked'
9924
+ && !(r?.preparationState === 'manifest-published' && !r?.prepassReady)
9925
+ && !revisionReadCannotRestart(r)
9926
+ && requestRunsInChat(r)).length;
9571
9927
  return {
9572
- lines, dropped, drawingSkipped, activeSkipped, preparationBlockedSkipped, preparationPublishedSkipped,
9573
- incompleteSkipped: dropped - drawingSkipped - activeSkipped - preparationBlockedSkipped - preparationPublishedSkipped,
9928
+ lines, dropped, drawingSkipped, activeSkipped, preparationBlockedSkipped, preparationPublishedSkipped, chatOwnedSkipped,
9929
+ incompleteSkipped: dropped - drawingSkipped - activeSkipped - preparationBlockedSkipped
9930
+ - preparationPublishedSkipped - chatOwnedSkipped,
9574
9931
  };
9575
9932
  }
9576
9933
 
@@ -9602,15 +9959,15 @@
9602
9959
  // request with no instruction body, and reporting the list length over that is the
9603
9960
  // original bug wearing a bulk hat: the user pastes, the AI applies the ones that copied, and the
9604
9961
  // dropped request never reaches the terminal while the toast said it did.
9605
- const { lines, dropped, drawingSkipped, activeSkipped, preparationBlockedSkipped, preparationPublishedSkipped, incompleteSkipped } = bulkCopyPlan(current);
9962
+ const { lines, dropped, drawingSkipped, activeSkipped, preparationBlockedSkipped, preparationPublishedSkipped, chatOwnedSkipped, incompleteSkipped } = bulkCopyPlan(current);
9606
9963
  if (!lines.length) {
9607
- showToast(bulkCopyEmptyMessage({ drawingSkipped, activeSkipped, preparationBlockedSkipped, preparationPublishedSkipped, incompleteSkipped }, shown.length), 'warn');
9964
+ showToast(bulkCopyEmptyMessage({ drawingSkipped, activeSkipped, preparationBlockedSkipped, preparationPublishedSkipped, chatOwnedSkipped, incompleteSkipped }, shown.length), 'warn');
9608
9965
  return;
9609
9966
  }
9610
9967
  const copied = await copyToClipboard(lines.join('\n\n'));
9611
9968
  if (!copied) { showToast('We couldn’t copy that request. Select the text and copy it manually.', 'err'); return; }
9612
9969
  showToast(
9613
- bulkCopySuccessMessage({ lines, dropped, drawingSkipped, activeSkipped, preparationBlockedSkipped, preparationPublishedSkipped, incompleteSkipped }, shown.length),
9970
+ bulkCopySuccessMessage({ lines, dropped, drawingSkipped, activeSkipped, preparationBlockedSkipped, preparationPublishedSkipped, chatOwnedSkipped, incompleteSkipped }, shown.length),
9614
9971
  dropped ? 'warn' : 'ok',
9615
9972
  );
9616
9973
  }
@@ -9620,6 +9977,7 @@
9620
9977
  if (plan.preparationPublishedSkipped === total) return 'Nothing to copy — drawing preparation is complete. Continue in the same AI conversation.';
9621
9978
  if (plan.drawingSkipped === total) return 'Nothing to copy — these drawing reads need review, continuation, or reattachment';
9622
9979
  if (plan.activeSkipped === total) return 'Nothing to copy — these requests are already running';
9980
+ if (plan.chatOwnedSkipped === total) return 'Nothing to copy — AI Chat holds these. Open AI Chat on the left (expand that panel if it is collapsed) to see where each one stands.';
9623
9981
  const blocked = plan.preparationBlockedSkipped
9624
9982
  ? `${plan.preparationBlockedSkipped} drawing preparation${plan.preparationBlockedSkipped === 1 ? ' needs' : 's need'} FloLess to be restarted`
9625
9983
  : '';
@@ -9630,8 +9988,11 @@
9630
9988
  ? `${plan.drawingSkipped} drawing read${plan.drawingSkipped === 1 ? ' needs' : 's need'} review, continuation, or reattachment`
9631
9989
  : '';
9632
9990
  const active = plan.activeSkipped ? `${plan.activeSkipped} already running` : '';
9991
+ const chatOwned = plan.chatOwnedSkipped
9992
+ ? `${plan.chatOwnedSkipped} ${plan.chatOwnedSkipped === 1 ? 'is' : 'are'} held by AI Chat`
9993
+ : '';
9633
9994
  const incomplete = plan.incompleteSkipped ? `${plan.incompleteSkipped} did not have a complete instruction` : '';
9634
- const reasons = [blocked, published, drawing, active, incomplete].filter(Boolean);
9995
+ const reasons = [blocked, published, drawing, active, chatOwned, incomplete].filter(Boolean);
9635
9996
  return reasons.length
9636
9997
  ? `Nothing to copy — ${reasons.join(', ')}`
9637
9998
  : 'Nothing to copy — no complete instruction is available';
@@ -9649,8 +10010,11 @@
9649
10010
  const published = plan.preparationPublishedSkipped
9650
10011
  ? `${plan.preparationPublishedSkipped} drawing preparation${plan.preparationPublishedSkipped === 1 ? ' is' : 's are'} complete and can continue in the same AI conversation`
9651
10012
  : '';
10013
+ const chatOwned = plan.chatOwnedSkipped
10014
+ ? `${plan.chatOwnedSkipped} ${plan.chatOwnedSkipped === 1 ? 'is' : 'are'} held by AI Chat`
10015
+ : '';
9652
10016
  const incomplete = plan.incompleteSkipped ? `${plan.incompleteSkipped} did not have a complete instruction` : '';
9653
- return `Copied ${plan.lines.length} of ${total} — ${[drawing, active, blocked, published, incomplete].filter(Boolean).join(', ')}`;
10017
+ return `Copied ${plan.lines.length} of ${total} — ${[drawing, active, blocked, published, chatOwned, incomplete].filter(Boolean).join(', ')}`;
9654
10018
  }
9655
10019
 
9656
10020
  /** The sentence a steel detailer needs first; the exact API handoff stays available below it. */
@@ -9663,13 +10027,28 @@
9663
10027
  return 'Return to the same terminal AI session that prepared it and tell it to continue the drawing read.';
9664
10028
  }
9665
10029
 
10030
+ /**
10031
+ * AI Chat is replying on something FloLess cannot prove is this request's (#1610): the person may
10032
+ * have asked it to continue, or asked something else. After a Drawing Filter Save, though, FloLess
10033
+ * itself queues the continuation and retries it once the conversation is free — then the queued
10034
+ * next step is the true one, and "it will not resume on its own" would contradict it. Only QUEUED:
10035
+ * every other saved-filter answer either names a person's action or, with no continuation at all,
10036
+ * falls back to the terminal-AI sentence, which is wrong for a request AI Chat owns.
10037
+ */
10038
+ function requestChatBusyNextStep(req) {
10039
+ if (req?.filterSaveContinuation?.state === 'queued') {
10040
+ return `${savedDrawingFilterNextStep(req)} Do not start it again here.`;
10041
+ }
10042
+ return 'If you already asked AI Chat to continue, the request is moving forward and this updates on its own. If not, tell it to continue once the current reply is done — it will not resume on its own. Do not start it again here.';
10043
+ }
10044
+
9666
10045
  function requestSummary(r) {
9667
10046
  if (!r || r.type !== 'revision-read') return '';
9668
10047
  if (r.preparationState === 'blocked') {
9669
10048
  return 'FloLess could not finish drawing preparation because it could not confirm that an earlier drawing reader stopped. Your drawings are still attached. Restart FloLess; if this remains blocked, open Requests and follow the detailed instructions.';
9670
10049
  }
9671
10050
  if (r.preparationState === 'manifest-published' && !r.prepassReady) {
9672
- return 'Drawing preparation is complete and the prepared data is saved. Return to the same terminal AI session and tell it to continue creating the Drawing Filter. Do not start or copy this request again.';
10051
+ return `Drawing preparation is complete and the prepared data is saved. Return to the same ${requestRunsInChat(r) ? 'AI Chat conversation' : 'terminal AI session'} and tell it to continue creating the Drawing Filter. Do not start or copy this request again.`;
9673
10052
  }
9674
10053
  if (r.status === 'pending' && r.filterSaveContinuation?.state === 'recovery-needed') {
9675
10054
  return `Drawing Filter needs attention. ${savedDrawingFilterNextStep(r)}`;
@@ -9685,7 +10064,7 @@
9685
10064
  ? 'Retrying Steel Filter preparation with the attached drawings.'
9686
10065
  : r.canRun
9687
10066
  ? 'Steel Filter preparation was interrupted. Your drawings are still attached. Choose Retry preparation to continue this same request.'
9688
- : 'Steel Filter preparation was interrupted. Your drawings are still attached. Return to the same terminal AI and retry preparation for this same request.';
10067
+ : `Steel Filter preparation was interrupted. Your drawings are still attached. Return to the same ${requestRunsInChat(r) ? 'AI Chat conversation' : 'terminal AI'} and retry preparation for this same request.`;
9689
10068
  }
9690
10069
  // A durable terminal attempt can own a pending row while automatic start is intentionally
9691
10070
  // unavailable. Its server-owned recovery is the primary summary; generic "read the drawing"
@@ -9849,7 +10228,7 @@
9849
10228
  return `Next step: ${savedDrawingFilterNextStep(r)} Do not start the request again.`;
9850
10229
  }
9851
10230
  if (r.prepassReady) {
9852
- return r.chatConversation?.executionOwner === 'chat'
10231
+ return requestRunsInChat(r)
9853
10232
  ? 'Next step: return to Drawing Filter, check steel, member marks, grids, dimensions, and relevant callouts, then press Save filter in the top-right corner. FloLess will continue the drawing read in this linked AI Chat. Do not start it again.'
9854
10233
  : 'Next step: return to Drawing Filter, check steel, member marks, grids, dimensions, and relevant callouts, then press Save filter in the top-right corner. After Save, return to the terminal AI that prepared it and tell it to continue. Do not start the drawing read again.';
9855
10234
  }
@@ -9861,9 +10240,30 @@
9861
10240
  ? 'Next step: choose Retry preparation on this request. FloLess kept the attached drawings and will continue the same request.'
9862
10241
  : 'Next step: return to the same terminal AI and retry preparation for this same request, or copy the retry request here. FloLess kept the attached drawings.';
9863
10242
  }
10243
+ if (requestRunsInChat(r)) {
10244
+ if (requestChatBlockedAction(r)) {
10245
+ return `This drawing read is waiting for you in AI Chat: open that conversation and ${requestChatBlockedAction(r)}. It carries on once you do.`;
10246
+ }
10247
+ if (requestChatUnreadable(r)) {
10248
+ return 'This drawing read is in an AI Chat conversation FloLess could not read. Open it to check; if it will not open, use Report an issue rather than starting the request again.';
10249
+ }
10250
+ if (requestChatArchived(r)) {
10251
+ return 'This drawing read is in an archived AI Chat conversation, whose composer is disabled. Restore that conversation, then tell it to continue the read.';
10252
+ }
10253
+ if (requestChatBusyElsewhere(r)) {
10254
+ return 'This drawing read is waiting on a reply in AI Chat. If you already asked it to continue, the read is moving forward and this updates. If not, tell it to continue once that reply is done — the read will not resume on its own.';
10255
+ }
10256
+ return requestWorkingInChat(r)
10257
+ ? 'This drawing read is running in AI Chat. Leave it running; when the Drawing Filter is ready, review the selected lines and press Save filter in the top-right corner.'
10258
+ : requestChatFailed(r)
10259
+ ? 'This drawing read stopped with an error in AI Chat. Open that conversation to see what went wrong, then ask it to try again, rather than starting the request again.'
10260
+ : requestChatInterrupted(r)
10261
+ ? 'This drawing read was interrupted in AI Chat — its reply stopped before it finished. Open that conversation and tell it to continue, rather than starting the request again.'
10262
+ : 'This drawing read is open in AI Chat but is not running. Open that conversation and tell it to continue, rather than starting the request again.';
10263
+ }
9864
10264
  const start = r.canRun && headlessReady()
9865
- ? 'copy this request into Claude Code, Codex, or OpenCode, or press Start'
9866
- : 'copy this request into Claude Code, Codex, or OpenCode';
10265
+ ? 'copy this request into Claude Code or Codex, or press Start'
10266
+ : 'copy this request into Claude Code or Codex';
9867
10267
  return `Next step: ${start}. When the Drawing Filter is ready, check steel, member marks, grids, dimensions, and relevant callouts, then press Save filter in the top-right corner.`;
9868
10268
  }
9869
10269
 
@@ -9950,6 +10350,10 @@
9950
10350
  }
9951
10351
 
9952
10352
  function filterGuideRequestNote(request) {
10353
+ // The run route refused it before anything started, and recorded that (#1650).
10354
+ if (request.filterAiNotStarted === true) {
10355
+ return 'AI did not start on this Drawing Filter message, so nothing changed. Clear it here, and send it again from AI Chat while the Drawing Filter is open.';
10356
+ }
9953
10357
  if (request.filterAiAdmissionUnconfirmed) {
9954
10358
  return 'FloLess could not confirm whether AI started. A late answer may appear here or in AI Chat. If none appears, clear this request and ask again in AI Chat while the Drawing Filter is open.';
9955
10359
  }
@@ -9964,6 +10368,150 @@
9964
10368
  return 'For reference only. It cannot be applied here; ask again in AI Chat while the Drawing Filter is open.';
9965
10369
  }
9966
10370
 
10371
+ // ── Repainting the Requests list without undoing what the user was doing (#1594) ──
10372
+ //
10373
+ // renderRequests() rebuilds the list from markup, and while the window is open it runs on every
10374
+ // request event: during an active run, every few hundred milliseconds. Markup alone cannot say which
10375
+ // disclosures the user opened ("Show detailed instructions", what a run printed), where they had
10376
+ // scrolled inside one, or which control had keyboard focus, so each rebuild snapped the panel shut,
10377
+ // jumped its scroller back to the top and dropped focus out of the window. It also ate clicks: a click
10378
+ // is a press and a release on the SAME element, and a row rebuilt between the two takes the click
10379
+ // with it. paintRequestList() is the one place the list's markup is replaced, and it carries the
10380
+ // first three across; holdRequestListRepaints() keeps a repaint from landing mid-click.
10381
+
10382
+ /** A control's tag and class under its parent's: what "the same kind of control" means in a row. */
10383
+ function requestListShape(el) {
10384
+ const of = (node) => `${node.tagName}.${node.getAttribute('class') || ''}`;
10385
+ return el.parentElement ? `${of(el.parentElement)}>${of(el)}` : of(el);
10386
+ }
10387
+
10388
+ /**
10389
+ * Names an element of the list so the SAME one can be found again after a repaint. A control with
10390
+ * an Instructor id is named by it, because that id already means "this action, on this request".
10391
+ * Anything else (a disclosure, a scroller, a thumbnail) is named by its row, its shape, and its
10392
+ * position among the elements of that shape in the row.
10393
+ */
10394
+ function requestListKey($list, el) {
10395
+ if (el.dataset && el.dataset.commandId) return { cmd: el.dataset.commandId };
10396
+ const row = el.closest('.req-item');
10397
+ const shape = requestListShape(el);
10398
+ const peers = Array.from((row || $list).querySelectorAll(el.tagName)).filter((node) => requestListShape(node) === shape);
10399
+ return { row: row ? row.dataset.id : null, tag: el.tagName, shape, n: peers.indexOf(el) };
10400
+ }
10401
+
10402
+ /** The element a requestListKey names in the list as it is now, or null when it is gone. */
10403
+ function requestListFind($list, key) {
10404
+ if (key.cmd) return Array.from($list.querySelectorAll('[data-command-id]')).find((el) => el.dataset.commandId === key.cmd) || null;
10405
+ const scope = key.row === null ? $list : Array.from($list.querySelectorAll('.req-item')).find((row) => row.dataset.id === key.row);
10406
+ if (!scope || key.n < 0) return null;
10407
+ return Array.from(scope.querySelectorAll(key.tag)).filter((el) => requestListShape(el) === key.shape)[key.n] || null;
10408
+ }
10409
+
10410
+ // Only focus the keyboard can see is carried. A mouse click focuses its button too, and handing
10411
+ // that focus back after every repaint would reopen the button's tooltip each time, wherever the
10412
+ // pointer had gone. An engine that cannot answer is treated as keyboard focus.
10413
+ function requestListFocusVisible(el) {
10414
+ try { return el.matches(':focus-visible'); } catch { return true; }
10415
+ }
10416
+
10417
+ /**
10418
+ * Replace the Requests list's markup with `html`, keeping what the user was doing. It always
10419
+ * repaints, even when nothing changed, exactly as the list did before #1594: row handlers that
10420
+ * change their row in place (a busy Start, a launch status line) rely on the next renderRequests()
10421
+ * to put it back from markup.
10422
+ *
10423
+ * While the search is unchanged, every disclosure keeps the open or closed state the user left it
10424
+ * in, and every scroller inside the list keeps its offset. A different search is the one repaint
10425
+ * that re-decides them, even when it happens to paint the same markup: the markup opens exactly the
10426
+ * disclosures whose text matches, as it always has. Search is case-blind ("held" and "HELD" find
10427
+ * and open the same rows), so the search is compared the same way. Keyboard focus is always carried
10428
+ * (see requestListFocusVisible): to the same control, else to its row, else to the row that took
10429
+ * that row's place, else to the dialog, so it never falls out of the window.
10430
+ */
10431
+ function paintRequestList($list, html, query) {
10432
+ const search = String(query || '').toLowerCase();
10433
+ const previous = $list.__requestsPaint;
10434
+ const carry = !!previous && previous.search === search;
10435
+ const disclosures = carry
10436
+ ? Array.from($list.querySelectorAll('details')).map((el) => ({ key: requestListKey($list, el), open: el.open }))
10437
+ : [];
10438
+ const scrolled = carry
10439
+ ? Array.from($list.querySelectorAll('*')).filter((el) => el.scrollTop > 0)
10440
+ .map((el) => ({ key: requestListKey($list, el), top: el.scrollTop }))
10441
+ : [];
10442
+ const active = document.activeElement;
10443
+ let focus = null;
10444
+ if (active && active !== $list && $list.contains(active) && requestListFocusVisible(active)) {
10445
+ const row = active.closest('.req-item');
10446
+ focus = {
10447
+ key: requestListKey($list, active), row: row ? row.dataset.id : null,
10448
+ index: row ? Array.from($list.querySelectorAll('.req-item')).indexOf(row) : -1,
10449
+ onRow: active === row, // the row itself held focus (a control of it went on an earlier repaint)
10450
+ };
10451
+ }
10452
+ $list.innerHTML = html;
10453
+ $list.__requestsPaint = { search };
10454
+ // Object identity is a cheap render generation: every repaint replaces this token. Async row
10455
+ // actions capture it, so a poll/search/scope repaint retires their completion even if another
10456
+ // row later reuses the same request id.
10457
+ $list.__requestPaintOwner = {};
10458
+ for (const { key, open } of disclosures) {
10459
+ const el = requestListFind($list, key);
10460
+ if (el && el.tagName === 'DETAILS') el.open = open;
10461
+ }
10462
+ for (const { key, top } of scrolled) {
10463
+ const el = requestListFind($list, key);
10464
+ if (el) el.scrollTop = top;
10465
+ }
10466
+ if (focus) {
10467
+ const same = requestListFind($list, focus.key);
10468
+ if (same) same.focus({ preventScroll: true });
10469
+ if (!same || document.activeElement !== same) {
10470
+ const rows = Array.from($list.querySelectorAll('.req-item'));
10471
+ const row = rows.find((candidate) => candidate.dataset.id === focus.row)
10472
+ || (focus.index >= 0 ? rows[Math.min(focus.index, rows.length - 1)] : null);
10473
+ if (row) {
10474
+ row.setAttribute('tabindex', '-1');
10475
+ row.addEventListener('blur', () => row.removeAttribute('tabindex'), { once: true });
10476
+ row.focus({ preventScroll: true });
10477
+ // Bring the row into view only when focus has just MOVED to it. A row that already held
10478
+ // focus stays where the user scrolled it: bringing it back on every repaint would pin the
10479
+ // list to it for as long as a running request keeps sending events.
10480
+ if (!focus.onRow || row.dataset.id !== focus.row) row.scrollIntoView({ block: 'nearest' });
10481
+ } else {
10482
+ const dialog = $list.closest('[role="dialog"]');
10483
+ if (dialog) dialog.focus({ preventScroll: true });
10484
+ }
10485
+ }
10486
+ }
10487
+ }
10488
+
10489
+ /**
10490
+ * A repaint that arrives while the primary pointer, or the Space key (a button fires on its
10491
+ * release), is held inside the list waits for the release, and then runs once, after the click that
10492
+ * release produces. Wired once, on the list element itself, which outlives every repaint.
10493
+ */
10494
+ function holdRequestListRepaints($list) {
10495
+ // Each press is held on its own (every pointer by its id, and Space): letting go of one, or of a
10496
+ // pointer that began elsewhere, must not repaint under a press still held on a row.
10497
+ const holds = new Set();
10498
+ const hold = (input) => { holds.add(input); $list.__requestsHeld = true; };
10499
+ const release = (input) => {
10500
+ if (input) holds.delete(input); else holds.clear();
10501
+ if (holds.size || !$list.__requestsHeld) return;
10502
+ $list.__requestsHeld = false;
10503
+ if (!$list.__requestsOwed) return;
10504
+ $list.__requestsOwed = false;
10505
+ setTimeout(renderRequests, 0); // a new task, so it lands after this release's click
10506
+ };
10507
+ $list.addEventListener('pointerdown', (e) => { if (e.isPrimary && e.button === 0) hold(`pointer ${e.pointerId}`); });
10508
+ $list.addEventListener('keydown', (e) => { if (e.key === ' ') hold('space'); });
10509
+ window.addEventListener('pointerup', (e) => release(`pointer ${e.pointerId}`), true);
10510
+ window.addEventListener('pointercancel', (e) => release(`pointer ${e.pointerId}`), true); // a touch scroll or a drag took the press
10511
+ window.addEventListener('keyup', (e) => { if (e.key === ' ') release('space'); }, true);
10512
+ window.addEventListener('blur', () => release(null)); // the release may happen in another window
10513
+ }
10514
+
9967
10515
  // The Requests window: every queued change in a list, with only the actions the server says are
9968
10516
  // currently safe, plus bulk actions over the available rows. The server-composed prompt (which embeds file-derived
9969
10517
  // appId/nodeId/instruction) is rendered via textContent-equivalent escaping — which matters MORE
@@ -9974,11 +10522,9 @@
9974
10522
  const $copy = document.getElementById('requests-copy');
9975
10523
  const $search = document.getElementById('requests-search');
9976
10524
  if (!$list) return;
9977
- // Object identity is a cheap render generation: every repaint replaces this token. Async row
9978
- // actions capture it, so a poll/search/scope repaint retires their completion even if another
9979
- // row later reuses the same request id.
9980
- const paintOwner = {};
9981
- $list.__requestPaintOwner = paintOwner;
10525
+ // A press still held inside the list: paint once it is released (see holdRequestListRepaints).
10526
+ // Everything waits, not only the rows, so the bulk actions keep acting on what is on screen.
10527
+ if ($list.__requestsHeld) { $list.__requestsOwed = true; return; }
9982
10528
  // Search is pointless over an empty queue, and over a single request it is just clutter.
9983
10529
  // Drop the query WITH the box, and before anything is filtered by it: a hidden filter still
9984
10530
  // filtering is how a list ends up inexplicably empty (the last two requests clear while a
@@ -10055,7 +10601,7 @@
10055
10601
  : normalizedRequestQuery
10056
10602
  ? `No request matches “${escapeHtml(normalizedRequestQuery)}”.${!requestScopeAll && inScope.length < pendingRequests.length ? ' Try All to search everything.' : ''}`
10057
10603
  : `Nothing queued for ${escapeHtml(scope ? scope.label : 'this')} — ${pendingRequests.length} item${pendingRequests.length === 1 ? '' : 's'} waiting elsewhere. <button type="button" class="req-showall">Show all</button>`;
10058
- $list.innerHTML = `<div class="empty-state">${msg}</div>`;
10604
+ paintRequestList($list, `<div class="empty-state">${msg}</div>`, normalizedRequestQuery);
10059
10605
  const $showAll = $list.querySelector('.req-showall');
10060
10606
  if ($showAll) $showAll.onclick = () => setRequestScopeAll(true);
10061
10607
  return;
@@ -10147,8 +10693,9 @@
10147
10693
  const discussBtn = chatProvider && inChatScope
10148
10694
  ? `<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>`
10149
10695
  : '';
10696
+ const starting = requestChatStarts.get(r.id)?.label;
10150
10697
  const startChatBtn = chatProvider && inChatScope && canRunNow && !filterGuide
10151
- ? `<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">Start in AI Chat</button>`
10698
+ ? `<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>`
10152
10699
  : '';
10153
10700
  const chatMeta = chatProvider && inChatScope
10154
10701
  ? `<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>`
@@ -10167,7 +10714,7 @@
10167
10714
  ${r.snapshots && r.snapshots.length ? `<div class="req-thumbs">${r.snapshots.map((sp, i) => { const pdf = /\.pdf$/i.test(String(sp)); return `<button type="button" class="req-thumb" data-id="${escapeAttr(r.id)}" data-n="${i}" aria-label="View ${pdf ? 'PDF' : 'screenshot'} ${i + 1}">${pdf ? '<span class="req-thumb-pdf">PDF</span>' : `<img src="/api/requests/${encodeURIComponent(r.id)}/snapshot/${i}" alt="">`}</button>`; }).join('')}</div>` : ''}
10168
10715
  ${runStatusHtml(run, resumeCommand, desktopHandoffs, r.id, commandInstance, ownRecoverySurface,
10169
10716
  filterGuide
10170
- ? (r.instructorContext.commandId === 'filter.ask-ai-change' ? 'change' : 'question') : null)}
10717
+ ? (r.instructorContext.commandId === 'filter.ask-ai-change' ? 'change' : 'question') : null, r.filterAiNotStarted === true)}
10171
10718
  ${r.status === 'pending' && !revisionReadHasTerminalOwner(r) && !r.canRun && r.runWhy && (anyRunnable || r.type === 'revision-read') ? `<div class="req-why-not">Why there is no automatic start: ${escapeHtml(r.runWhy)}</div>` : ''}
10172
10719
  ${auditRefusalHtml(r)}
10173
10720
  </div>
@@ -10180,35 +10727,75 @@
10180
10727
  </div>
10181
10728
  </div>`;
10182
10729
  }).join('');
10183
- $list.innerHTML = queuedHtml;
10730
+ paintRequestList($list, queuedHtml, normalizedRequestQuery);
10731
+ const paintOwner = $list.__requestPaintOwner;
10184
10732
  $list.querySelectorAll('[data-request-chat]').forEach((button) => {
10185
10733
  button.onclick = async () => {
10186
10734
  const request = pendingRequests.find((candidate) => candidate?.id === button.dataset.id);
10187
10735
  const provider = preferredChatProvider();
10188
10736
  if (!request || !provider || typeof window.flolessChat?.startRequest !== 'function') return;
10189
10737
  const original = button.textContent;
10738
+ const starting = button.dataset.requestChat === 'start';
10739
+ if (starting && requestChatStarts.has(request.id)) return;
10190
10740
  button.disabled = true;
10191
10741
  button.setAttribute('aria-busy', 'true');
10192
- button.textContent = button.dataset.requestChat === 'start' ? 'Starting…' : 'Opening…';
10742
+ button.textContent = starting ? 'Starting…' : 'Opening…';
10743
+ const startEntry = starting ? { label: button.textContent } : null;
10744
+ if (startEntry) requestChatStarts.set(request.id, startEntry);
10745
+ // Only the Start that set the entry may clear it; a Discuss never owns one (#1651).
10746
+ const endStart = () => {
10747
+ if (startEntry && requestChatStarts.get(request.id) === startEntry) requestChatStarts.delete(request.id);
10748
+ };
10193
10749
  const actionStatus = document.getElementById('requests-action-status');
10194
10750
  if (actionStatus) actionStatus.textContent = `${button.textContent} ${requestLabel(request)} for ${requestOwnerName(request)}.`;
10751
+ let settingUp = false;
10195
10752
  const slowTimer = setTimeout(() => {
10196
- if (button.disabled && button.isConnected && actionStatus) {
10753
+ if (!settingUp && button.disabled && button.isConnected && actionStatus) {
10197
10754
  actionStatus.textContent = `Still opening ${requestLabel(request)} in AI Chat… FloLess is taking longer than expected.`;
10198
10755
  }
10199
10756
  }, 4000);
10757
+ const requestsModal = document.getElementById('requests-modal');
10758
+ // Closing Requests cancels a start that is still waiting for setup, as does the Request
10759
+ // leaving the queue (cleared, or started somewhere else meanwhile).
10760
+ const cancelled = () => !requestsModal?.classList.contains('show')
10761
+ || !pendingRequests.some((candidate) => candidate && candidate.id === request.id && candidate.status === 'pending');
10200
10762
  try {
10201
- await window.flolessChat.startRequest(request.id, provider, button.dataset.requestChat === 'start' ? 'start' : 'discuss');
10763
+ await startRequestChatWithSetup(request.id, provider, starting ? 'start' : 'discuss', {
10764
+ isCancelled: cancelled,
10765
+ // FloLess is installing its own copy of this AI first (#1607): say so, once per state.
10766
+ onSetup: (status) => {
10767
+ const notice = window.flolessChat?.runtimeNotice?.(provider, status);
10768
+ const text = notice?.body || `FloLess is setting up ${runtimeLabel(provider)} before it starts this request.`;
10769
+ const label = chatRuntimeSetupLabel(provider);
10770
+ if (startEntry) startEntry.label = label;
10771
+ // The list may have been repainted meanwhile: label whichever button shows this Request now.
10772
+ const live = $list.querySelector(`[data-request-chat="start"][data-id="${CSS.escape(request.id)}"]`);
10773
+ if (live) live.textContent = label;
10774
+ if (actionStatus && (!settingUp || actionStatus.textContent !== text)) actionStatus.textContent = text;
10775
+ settingUp = true;
10776
+ },
10777
+ });
10202
10778
  closeRequests();
10203
10779
  } catch (error) {
10204
- reportErr(error);
10205
- if (actionStatus) actionStatus.textContent = `Couldn’t ${button.dataset.requestChat === 'start' ? 'start' : 'open'} ${requestLabel(request)} in AI Chat. Try again.`;
10780
+ if (error?.code === 'chat-start-cancelled') return;
10781
+ const notReady = error?.code === 'chat-runtime-not-ready';
10782
+ if (notReady) showToast(error.message, 'warn');
10783
+ else reportErr(error);
10784
+ if (actionStatus) actionStatus.textContent = notReady
10785
+ ? error.message
10786
+ : `Couldn’t ${starting ? 'start' : 'open'} ${requestLabel(request)} in AI Chat. Try again.`;
10787
+ if (notReady || !button.isConnected) {
10788
+ endStart();
10789
+ renderRequests();
10790
+ return;
10791
+ }
10206
10792
  button.disabled = false;
10207
10793
  button.removeAttribute('aria-busy');
10208
10794
  button.textContent = original;
10209
10795
  button.focus();
10210
10796
  } finally {
10211
10797
  clearTimeout(slowTimer);
10798
+ endStart();
10212
10799
  }
10213
10800
  };
10214
10801
  });
@@ -10417,6 +11004,10 @@
10417
11004
  : document.activeElement instanceof HTMLElement ? document.activeElement : null;
10418
11005
  $requestsModal.classList.add('show');
10419
11006
  if ($requestsDialog) $requestsDialog.focus();
11007
+ // A fresh open is a fresh list, like the scope and search above: nothing a previous visit opened
11008
+ // or scrolled carries into it (#1594).
11009
+ const $list = document.getElementById('requests-list');
11010
+ if ($list) $list.__requestsPaint = null;
10420
11011
  renderRequests(); // paint the cache immediately — no empty flash
10421
11012
  // Scroll off the CACHED paint, before the refetch. Gating the reveal on `/api/requests` means an
10422
11013
  // arbitrarily slow response leaves the list sitting at the top — precisely the state this feature
@@ -10967,13 +11558,60 @@
10967
11558
  });
10968
11559
 
10969
11560
  function runtimeSectionSummary(runtimes, active, folder) {
10970
- const installed = runtimes.filter((runtime) => runtime.state === 'found');
10971
- const selected = installed.find((runtime) => runtime.id === active);
11561
+ // What FloLess would LAUNCH (#1622): its own copy where it runs one, else the user's install.
11562
+ const installed = runtimes.filter(runtimeCopyInstalled);
11563
+ // The default is whichever AI FloLess would start (#1607): on a computer where FloLess runs its
11564
+ // own copy that need not be a user install, and the server's default already follows that.
11565
+ const selected = runtimes.find((runtime) => runtime.id === active && chatRuntimeCanStart(runtime));
10972
11566
  const provider = selected ? `${selected.label} default` : 'No default terminal AI';
10973
11567
  const count = `${installed.length} installed`;
10974
11568
  return `${provider} · ${count} · ${folder ? `Runs in ${folder}` : 'Folder not chosen'}`;
10975
11569
  }
10976
11570
 
11571
+ // FloLess's own copy's launch status, when FloLess runs its own copy of this AI (#1607), else null.
11572
+ const runtimeManagedStatus = (runtime) => (runtime && runtime.managed && typeof runtime.managed === 'object' ? runtime.managed : null);
11573
+ // Whether the copy FloLess would launch is on this computer now: its own copy where it runs one,
11574
+ // else the user's install.
11575
+ function runtimeCopyInstalled(runtime) {
11576
+ const managed = runtimeManagedStatus(runtime);
11577
+ return managed ? managed.state === 'installed' : runtime.state === 'found';
11578
+ }
11579
+
11580
+ /**
11581
+ * What a Terminal AI card says about the copy FloLess actually runs (#1622), when that is FloLess's
11582
+ * own copy: the badge, one plain-English line, and whether the badge is a warning. The state is
11583
+ * `chatRuntimeReadiness`'s, so the card cannot disagree with Default, Use this one or any Start.
11584
+ * A failure is worded by the AI Chat panel's own runtimeNotice, the sentence the chat shows for it.
11585
+ * Returns null without managed launch: then the user's own install is what runs, and the card
11586
+ * describes that.
11587
+ */
11588
+ function managedRuntimeCard(runtime) {
11589
+ const managed = runtimeManagedStatus(runtime);
11590
+ if (!managed) return null;
11591
+ const readiness = chatRuntimeReadiness(runtime);
11592
+ if (readiness === 'ready') return { badge: 'Installed', line: `FloLess runs its own tested copy of ${runtime.label}.`, warn: false };
11593
+ if (managed.state === 'preparing') {
11594
+ return {
11595
+ badge: 'Setting up…',
11596
+ line: managed.owner === 'another-process'
11597
+ ? 'Another FloLess window is setting up its own tested copy.'
11598
+ : 'FloLess is setting up its own tested copy now.',
11599
+ warn: false,
11600
+ };
11601
+ }
11602
+ if (managed.state === 'not-installed') {
11603
+ return { badge: 'Not set up yet', line: 'FloLess sets up its own tested copy the first time you start a chat with it.', warn: false };
11604
+ }
11605
+ // Any other state (unsupported here, or one a newer FloLess reports) says nothing about a setup
11606
+ // having been tried, so it is not called a failure — only that FloLess cannot start this copy.
11607
+ if (managed.state !== 'failed') {
11608
+ return { badge: 'Unavailable', line: `FloLess can’t run its own copy of ${runtime.label} on this computer.`, warn: false };
11609
+ }
11610
+ const why = window.flolessChat?.runtimeNotice?.(runtime.id, managed)?.body;
11611
+ const line = why || 'FloLess couldn’t set up its own copy on this computer.';
11612
+ return { badge: 'Setup failed', line: readiness === 'setup' ? `${line} Starting a chat tries again.` : line, warn: true };
11613
+ }
11614
+
10977
11615
  function setRuntimeSectionExpanded(expanded) {
10978
11616
  runtimeSectionExpanded = !!expanded;
10979
11617
  const $toggle = document.getElementById('int-runtimes-toggle');
@@ -11082,12 +11720,20 @@
11082
11720
  const signInTip = 'FloLess uses whichever account is signed in to the Claude Code or Codex CLI on this computer. Signing in to the Claude desktop app or claude.ai does not change it. Switch account signs that CLI out first, then opens a window where you sign in.';
11083
11721
  $list.innerHTML = rts.map((r) => {
11084
11722
  const found = r.state === 'found';
11085
- const isDefault = found && r.id === active;
11723
+ // Default and "Use this one" follow what FloLess can start (#1607), like the server's default.
11724
+ const canStart = chatRuntimeCanStart(r);
11725
+ const isDefault = canStart && r.id === active;
11726
+ // Where FloLess runs its own copy, the badge and the line under the name describe THAT copy
11727
+ // (#1622): the user's own install says nothing about what a chat would launch. Otherwise they
11728
+ // describe the user's install, which is then what runs.
11729
+ const managedCard = managedRuntimeCard(r);
11730
+ // Dimmed only when FloLess cannot start it: a copy FloLess has yet to set up is not missing.
11731
+ const dimmed = managedCard ? !canStart : !found;
11086
11732
  const answer = runtimeSignInAnswer(r.account);
11087
- // A missing user install can still have a managed copy that signs in: the account line
11088
- // follows the account, not the badge. An answer that names one — or says it is signed in with
11089
- // nothing to name — is such a copy; "signed out" and "could not check" are not.
11090
- const showsAccount = found || answer.state === 'signed-in' || answer.state === 'no-identity';
11733
+ // The account is read through whatever FloLess would launch, so the line shows once that copy
11734
+ // is on this computer. An answer that names an account — or says it is signed in with nothing
11735
+ // to name — is shown whatever the badge says; "signed out" and "could not check" are not.
11736
+ const showsAccount = runtimeCopyInstalled(r) || answer.state === 'signed-in' || answer.state === 'no-identity';
11091
11737
  const pending = pendingRuntimeSignIn.has(r.id);
11092
11738
  // Both cards render the same visible "Switch account…", so without a runtime-specific
11093
11739
  // accessible name a screen reader (and Instructor's focus proof) cannot tell them apart.
@@ -11096,21 +11742,23 @@
11096
11742
  // The sign-in sits on the account line it acts on. The side column is a flex row already
11097
11743
  // holding the badge and, on the non-default card, "Use this one" — a third control wraps.
11098
11744
  return `
11099
- <div class="int-rt${isDefault ? ' is-default' : ''}${found ? '' : ' is-missing'}">
11745
+ <div class="int-rt${isDefault ? ' is-default' : ''}${dimmed ? ' is-missing' : ''}">
11100
11746
  <div class="int-rt-main">
11101
11747
  <div class="int-rt-name">${escapeHtml(r.label)}${isDefault ? '<span class="int-rt-pill">Default</span>' : ''}</div>
11102
11748
  <div class="int-rt-blurb">${escapeHtml(r.blurb)} · <code>${escapeHtml(r.command)}</code></div>
11103
- <div class="int-rt-where">${found
11104
- ? `Found at ${escapeHtml(r.path || '')}`
11105
- : `Not installed — floless looks for <code>${escapeHtml(r.command)}</code>`}</div>
11749
+ ${managedCard
11750
+ ? `<div class="int-rt-copy">${escapeHtml(managedCard.line)}</div>`
11751
+ : `<div class="int-rt-where">${found
11752
+ ? `Found at ${escapeHtml(r.path || '')}`
11753
+ : `Not installed — floless looks for <code>${escapeHtml(r.command)}</code>`}</div>`}
11106
11754
  ${showsAccount ? `<div class="int-rt-signin">
11107
11755
  <div class="int-rt-account" aria-live="polite" data-tip="${escapeAttr(signInTip)}">${escapeHtml(runtimeAccountLabel(r.account))}</div>
11108
11756
  <button class="int-action" data-sign-in="${escapeAttr(r.id)}" data-command-id="shell.headless-sign-in#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(r.label)}" aria-label="${escapeAttr(signInName)}" data-tip="${escapeAttr(signInTip)}"${pending ? ' disabled data-blocked-reason="Waiting for the sign-in window."' : ''}>${pending ? 'Waiting for sign-in…' : answer.state === 'signed-out' ? 'Sign in…' : 'Switch account…'}</button>
11109
11757
  </div>` : ''}
11110
11758
  </div>
11111
11759
  <div class="int-rt-side">
11112
- <span class="int-rt-badge">${found ? 'Installed' : 'Not installed'}</span>
11113
- ${found && !isDefault ? `<button class="int-action" data-rt="${escapeAttr(r.id)}" data-command-id="shell.headless-runtime#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(r.label)}">Use this one</button>` : ''}
11760
+ <span class="int-rt-badge${managedCard?.warn ? ' is-warn' : ''}">${escapeHtml(managedCard ? managedCard.badge : found ? 'Installed' : 'Not installed')}</span>
11761
+ ${canStart && !isDefault ? `<button class="int-action" data-rt="${escapeAttr(r.id)}" data-command-id="shell.headless-runtime#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(r.label)}">Use this one</button>` : ''}
11114
11762
  </div>
11115
11763
  </div>`;
11116
11764
  }).join('');
@@ -12624,6 +13272,8 @@
12624
13272
  };
12625
13273
  const $reqSearch = document.getElementById('requests-search');
12626
13274
  if ($reqSearch) $reqSearch.oninput = () => { requestQuery = $reqSearch.value; renderRequests(); };
13275
+ const $reqList = document.getElementById('requests-list');
13276
+ if ($reqList) holdRequestListRepaints($reqList);
12627
13277
  const $requestHelpModal = document.getElementById('request-help-modal');
12628
13278
  const $requestHelpOpen = document.getElementById('request-help-open');
12629
13279
  const $requestHelpKeep = document.getElementById('request-help-keep');
@@ -12671,16 +13321,32 @@
12671
13321
  const provider = preferredChatProvider();
12672
13322
  if (!req || !provider || typeof window.flolessChat?.startRequest !== 'function') return;
12673
13323
  setRequestHelpBusy('chat');
13324
+ const epoch = requestHelpEpoch;
13325
+ // Closing or reusing the modal cancels a start that is still waiting for setup (#1607).
13326
+ const gone = () => requestHelpEpoch !== epoch || requestHelpReq !== req;
12674
13327
  try {
12675
- await window.flolessChat.startRequest(req.id, provider, 'start');
13328
+ await startRequestChatWithSetup(req.id, provider, 'start', {
13329
+ isCancelled: gone,
13330
+ // FloLess is installing its own copy of this AI first (#1607).
13331
+ onSetup: (status) => {
13332
+ if (gone()) return;
13333
+ $requestHelpChat.textContent = chatRuntimeSetupLabel(provider);
13334
+ const sub = document.getElementById('request-help-sub');
13335
+ const text = window.flolessChat?.runtimeNotice?.(provider, status)?.body;
13336
+ if (sub && text && sub.textContent !== text) sub.textContent = text;
13337
+ },
13338
+ });
12676
13339
  closeRequestHelp({ restoreFocus: false });
12677
13340
  showToast(`Started in ${runtimeLabel(provider)} — continue in AI Chat`, 'ok');
12678
13341
  await loadRequests();
12679
13342
  } catch (error) {
12680
- reportErr(error);
13343
+ if (error?.code === 'chat-start-cancelled' || gone()) return;
13344
+ const notReady = error?.code === 'chat-runtime-not-ready';
13345
+ if (notReady) showToast(error.message, 'warn');
13346
+ else reportErr(error);
12681
13347
  setRequestHelpBusy(null);
12682
13348
  const sub = document.getElementById('request-help-sub');
12683
- if (sub) sub.textContent = requestHelpCopied
13349
+ if (sub) sub.textContent = notReady ? error.message : requestHelpCopied
12684
13350
  ? 'The request is still in Requests. Try again, start it in the background, or use the copied instruction in your terminal.'
12685
13351
  : 'The request is still in Requests. Try again, start it in the background, or copy the terminal instruction.';
12686
13352
  if ($requestHelpCopy && !requestHelpCopied) $requestHelpCopy.hidden = false;
@@ -13107,13 +13773,22 @@
13107
13773
  return openRequests(requestId || null);
13108
13774
  },
13109
13775
  preferredChatProvider,
13776
+ // The New project dialog's AI choice (#1605): the installed Claude/Codex rows as last read, and
13777
+ // a fresh read of them. The same shared runtime state preferredChatProvider() answers from, so
13778
+ // the dialog's default and its options can never disagree.
13779
+ chatProviderRuntimes: () => headlessRuntimes().filter((runtime) => runtime && (runtime.id === 'claude' || runtime.id === 'codex')),
13780
+ // The one shared "can this AI start" answer (#1607), so the dialog cannot re-derive its own.
13781
+ chatRuntimeReadiness,
13782
+ // Set FloLess's own copy of an AI up before a start sends its first message (#1607).
13783
+ ensureChatRuntimeReady,
13784
+ refreshChatProviders: () => refreshChatProvidersKeepingLast(),
13110
13785
  async startRequestInChat(requestId, mode = 'start') {
13111
13786
  const provider = preferredChatProvider();
13112
13787
  if (!provider || typeof window.flolessChat?.startRequest !== 'function') {
13113
13788
  throw new Error('Sign in to Claude or Codex before starting this request in AI Chat.');
13114
13789
  }
13115
13790
  await window.flolessChat.refreshScope?.();
13116
- return window.flolessChat.startRequest(requestId, provider, mode);
13791
+ return startRequestChatWithSetup(requestId, provider, mode);
13117
13792
  },
13118
13793
  async startProjectChatIntake(submissionId, payload) {
13119
13794
  if (typeof window.flolessChat?.startProjectIntake !== 'function') {
@@ -13178,6 +13853,9 @@
13178
13853
  await loadRequests();
13179
13854
  return copied;
13180
13855
  },
13856
+ // The steel editor's Ask AI list: an AI the user installed that the server approved for read-only runs
13857
+ // (`canRunReadOnly`). Its start sets nothing up first, so FloLess's own copy is not offered there yet
13858
+ // (#1652). The Drawing Filter decides with `filterRuntimeLaunch` below, not with this list (#1650).
13181
13859
  async readOnlyRequestOptions() {
13182
13860
  const info = await refreshHeadless();
13183
13861
  return {
@@ -13185,6 +13863,22 @@
13185
13863
  found: headlessRuntimes().filter((runtime) => runtime && runtime.state === 'found' && runtime.canRunReadOnly === true),
13186
13864
  };
13187
13865
  },
13866
+ // The Drawing Filter's read before it sends (#1650): what launching the conversation's OWN AI would
13867
+ // see now, from a read of its own (readChatRuntimeLaunch), never the shared rows a surface was painted
13868
+ // from, which can predate FloLess's own copy going away. One read, as before, so Send waits no longer.
13869
+ // 'ready' it can start;
13870
+ // 'setup' FloLess has to set its own copy up first (not installed, being set up, gone, or a
13871
+ // failure it can retry);
13872
+ // 'unavailable' it cannot answer Drawing Filter messages on this computer (nothing FloLess can
13873
+ // start, or not approved for read-only runs);
13874
+ // 'unchecked' the read failed, so nothing is known.
13875
+ async filterRuntimeLaunch(provider) {
13876
+ const launch = await readChatRuntimeLaunch(provider);
13877
+ if (launch.failed) return { readiness: 'unchecked' };
13878
+ if (launch.missing) return { readiness: 'unavailable' };
13879
+ const readiness = chatRuntimeReadiness(launch.row);
13880
+ return { readiness: readiness !== 'unavailable' && launch.row.canRunReadOnly === true ? readiness : 'unavailable' };
13881
+ },
13188
13882
  showRequestQueuedModal,
13189
13883
  formModal, // the shared styled prompt/form modal — workspaces.js reuses it (never a native prompt)
13190
13884
  // One owner for runtime upgrades. Workspaces may open this surface but must