@floless/app 0.84.0 → 0.86.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.
@@ -19,6 +19,9 @@
19
19
  if (!res.ok || body.ok === false) { const e = new Error(body.error || `HTTP ${res.status}`); e.body = body; throw e; }
20
20
  return body;
21
21
  });
22
+ // Product-analytics seam (analytics.js, loaded first). A no-op until PostHog is configured;
23
+ // itself already swallows errors, but guard the lookup too so a missing global never throws.
24
+ const track = (name, props) => { try { if (window.trackEvent) window.trackEvent(name, props || {}); } catch { /* analytics never breaks UX */ } };
22
25
 
23
26
  const $app = document.getElementById('app');
24
27
  const $switch = document.getElementById('mode-switch');
@@ -32,6 +35,8 @@
32
35
  const $projMenu = document.getElementById('ws-proj-menu');
33
36
  const $wsExports = document.getElementById('ws-exports');
34
37
  const $wsHistory = document.getElementById('ws-history');
38
+ const $wsKnowledge = document.getElementById('ws-knowledge');
39
+ const $wsKnowledgeFile = document.getElementById('ws-knowledge-file');
35
40
  const frames = {
36
41
  model: document.getElementById('ws-frame-model'),
37
42
  drawings: document.getElementById('ws-frame-drawings'),
@@ -39,17 +44,47 @@
39
44
  const $drawingsBar = document.getElementById('ws-drawings-bar');
40
45
  const $revisionCard = document.getElementById('ws-revision-card');
41
46
  const $revisionFile = document.getElementById('ws-revision-file');
47
+ const $sourcePlaceholder = document.getElementById('ws-source-placeholder'); // shown for a filter-less Source step
42
48
  let currentStep = 'model';
43
49
 
44
- // The Exports step's cards. `file:true` = writes a file on disk (shown with a "✓ exported HH:MM"
45
- // line + ⧉ Open / ▤ Reveal); `open:false` (IFC) = reveal-only (no OS default app for a .ifc).
46
- // Tekla is an ACTION (host mutation, no file). `kind` matches the server's export route + listing.
47
- const EXPORT_CARDS = [
48
- { kind: 'bom-csv', ico: '▤', name: 'Bill of materials', fmt: 'CSV', verb: 'Export CSV', file: true, open: true },
49
- { kind: 'bom-xlsx', ico: '▦', name: 'Bill of materials', fmt: 'XLSX', verb: 'Export Excel', file: true, open: true },
50
- { kind: 'ifc', ico: '◈', name: 'Model', fmt: 'IFC4', verb: 'Export IFC', file: true, open: false },
51
- { kind: 'tekla', ico: '◧', name: 'Tekla', fmt: '.ifc → Open API', verb: 'Send to Tekla', file: false },
52
- ];
50
+ // Shared drawing-file picker for both the new-project seed tile and the in-project
51
+ // "Attach revised drawings" button. Prefers the File System Access API so the native
52
+ // OS dialog shows a real "PDF or image" filter label (a plain <input accept=".pdf,
53
+ // image/*"> can't carry a custom label — Chromium shows it as generic "Custom Files").
54
+ // Falls back to the hidden <input type=file> on engines without the API. Returns []
55
+ // on cancel; never throws (AbortError from a user cancel is swallowed).
56
+ const DRAWING_FILE_TYPES = [{
57
+ description: 'PDF or image',
58
+ accept: { 'application/pdf': ['.pdf'], 'image/*': ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp'] },
59
+ }];
60
+ async function pickDrawingFiles(fallbackInput) {
61
+ if (window.showOpenFilePicker) {
62
+ try {
63
+ const handles = await window.showOpenFilePicker({ multiple: true, types: DRAWING_FILE_TYPES });
64
+ return Promise.all(handles.map((h) => h.getFile()));
65
+ } catch (err) {
66
+ if (err && err.name === 'AbortError') return []; // user cancelled — not an error
67
+ throw err;
68
+ }
69
+ }
70
+ return new Promise((resolve) => {
71
+ const cleanup = () => {
72
+ fallbackInput.removeEventListener('change', onChange);
73
+ fallbackInput.removeEventListener('cancel', onCancel);
74
+ };
75
+ const onChange = () => {
76
+ cleanup();
77
+ const files = Array.from(fallbackInput.files || []);
78
+ fallbackInput.value = ''; // clear so re-picking the same files re-fires change
79
+ resolve(files);
80
+ };
81
+ const onCancel = () => { cleanup(); resolve([]); };
82
+ fallbackInput.addEventListener('change', onChange);
83
+ fallbackInput.addEventListener('cancel', onCancel); // modern Chromium fires this on dialog dismiss
84
+ fallbackInput.click();
85
+ });
86
+ }
87
+
53
88
  let exportState = null; // kind → { path, exportedAt } after a successful list; null = unknown/failed
54
89
  if (!$switch || !$landing || !$app) return; // markup absent — nothing to wire
55
90
 
@@ -58,16 +93,122 @@
58
93
  const closeProjMenu = () => { $projMenu.hidden = true; $projMenu.classList.remove('show'); };
59
94
 
60
95
  const LS_MODE = 'floless:mode';
61
- const WORKSPACE_APP = 'steel-model'; // slice 1: the one workspace app; a manifest flag generalizes this in slice 5
96
+ // Per-app Workspaces presentation. The flag (floless.workspace, surfaced on /api/apps) says WHICH
97
+ // apps are workspaces; this map says HOW to render each (presentation is ours — spec §3.2). Two
98
+ // first-party apps today; promote to a .flo-declared descriptor when a user-authored one appears.
99
+ // NB: both apps keep the SAME data-step keys (drawings/model/exports/history) so setStep() and the
100
+ // frame slots are unchanged — only the first two LABELS and which HTML each frame loads differ.
101
+ //
102
+ // `exports`: the Exports-step cards for the app. `file:true` = writes a file on disk (shown with a
103
+ // "✓ exported HH:MM" line + ⧉ Open / ▤ Reveal); `open:false` (IFC) = reveal-only (no OS default app
104
+ // for a .ifc). Tekla is an ACTION (host mutation, no file). `kind` matches the server's export route
105
+ // + listing (projectExportFiles). renderExports()/exportUrl() read wsApp().exports — never a global.
106
+ const WORKSPACE_APPS = {
107
+ 'steel-model': {
108
+ displayName: 'Steel model',
109
+ seedLabel: 'steel model',
110
+ projectCapability: 'review, detail, export',
111
+ createActions: [
112
+ {
113
+ kind: 'drawing',
114
+ headline: 'Read steel drawings',
115
+ capability: 'Drawings to model, review, exports',
116
+ sub: 'Create a steel model from drawings.',
117
+ label: 'Pick drawings',
118
+ },
119
+ {
120
+ kind: 'current',
121
+ headline: 'Import current model',
122
+ capability: 'Open model to workspace context',
123
+ sub: 'Bring the open model into a new workspace.',
124
+ label: 'Import from Workflows',
125
+ },
126
+ ],
127
+ editor: '/steel-editor.html',
128
+ filter: '/steel-filter.html',
129
+ steps: [
130
+ { key: 'knowledge', label: 'Knowledge' }, // per-project KB — the job's context, consulted by everything
131
+ { key: 'drawings', label: 'Drawings' },
132
+ { key: 'model', label: 'Model' },
133
+ { key: 'exports', label: 'Exports' },
134
+ { key: 'history', label: 'History' },
135
+ ],
136
+ diff: true, // steel semantic diff expander
137
+ exports: [
138
+ { kind: 'bom-csv', ico: '▤', name: 'Bill of materials', fmt: 'CSV', verb: 'Export CSV', file: true, open: true },
139
+ { kind: 'bom-xlsx', ico: '▦', name: 'Bill of materials', fmt: 'XLSX', verb: 'Export Excel', file: true, open: true },
140
+ { kind: 'ifc', ico: '◈', name: 'Model', fmt: 'IFC4', verb: 'Export IFC', file: true, open: false },
141
+ { kind: 'tekla', ico: '◧', name: 'Tekla', fmt: '.ifc → Open API', verb: 'Send to Tekla', file: false },
142
+ ],
143
+ },
144
+ vectorize: {
145
+ displayName: 'Trace',
146
+ projectCapability: 'editable 2D drawing',
147
+ docGuide: true,
148
+ createActions: [
149
+ {
150
+ kind: 'drawing',
151
+ headline: 'Trace drawing',
152
+ capability: 'Drawing to vectors and editable shapes',
153
+ sub: 'Trace geometry into an editable canvas.',
154
+ label: 'Pick drawing',
155
+ },
156
+ ],
157
+ editor: '/vector-editor.html',
158
+ filter: null, // no filter step — Source shows a lightweight placeholder
159
+ steps: [
160
+ { key: 'knowledge', label: 'Knowledge' }, // KB is project-level — every workspace app gets it
161
+ { key: 'drawings', label: 'Source' }, // reuse the 'drawings' frame slot; label "Source"
162
+ { key: 'model', label: 'Traced' }, // reuse the 'model' frame slot; label "Traced"
163
+ { key: 'exports', label: 'Exports' },
164
+ { key: 'history', label: 'History' },
165
+ ],
166
+ diff: false,
167
+ exports: [
168
+ { kind: 'svg', ico: '▨', name: 'Traced drawing', fmt: 'SVG', verb: 'Export SVG', file: true, open: true },
169
+ ],
170
+ },
171
+ };
172
+ const wsApp = () => (current ? WORKSPACE_APPS[current.app] : null);
173
+ const appDisplayName = (id) => (WORKSPACE_APPS[id] && WORKSPACE_APPS[id].displayName) || id;
62
174
  let mode = 'workflows';
63
175
  try { if (localStorage.getItem(LS_MODE) === 'workspaces') mode = 'workspaces'; } catch { /* private mode */ }
64
176
  let projects = [];
177
+ // Installed workspace apps, in descriptor order. Populated from /api/apps in loadProjects():
178
+ // the set = apps flagged workspace===true that ALSO have a WORKSPACE_APPS descriptor (an app
179
+ // flagged workspace with no descriptor is skipped with a console note — never a broken open).
180
+ // Drives the per-app create cards. Falls back to the descriptor keys if /api/apps can't be read.
181
+ let wsAppIds = Object.keys(WORKSPACE_APPS);
65
182
  let current = null; // the open project (null = landing)
66
183
 
184
+ // The open app's visible label for a step key (Model→"Model" for steel, "Traced" for vectorize) —
185
+ // so shared chrome (banners, prompts) names the app's OWN step, never hard-coded steel vocabulary.
186
+ // Falls back to a capitalized key if the descriptor is missing a step.
187
+ const stepLabel = (key) => {
188
+ const d = wsApp();
189
+ const st = d && d.steps.find((s) => s.key === key);
190
+ return (st && st.label) || (key.charAt(0).toUpperCase() + key.slice(1));
191
+ };
192
+
193
+ // ── Workspaces guide beacon (aware.js owns #guide-beacon; we own project state) ──────
194
+ // The document-lifecycle guide (drop → review → approve → export) is for the lightweight
195
+ // Trace document archetype. Steel can now also start from drawings, but its guide/capability
196
+ // surface is broader and should not inherit Trace-specific SVG guidance.
197
+ const wsHasDocGuide = () => { const d = wsApp(); return !!(d && d.docGuide); };
198
+ function syncWorkspaceGuide() {
199
+ if (!bridge.setWorkspaceGuide) return; // older bridge — no-op (beacon simply stays hidden)
200
+ if (!current || !wsHasDocGuide()) { bridge.clearWorkspaceGuide && bridge.clearWorkspaceGuide(); return; }
201
+ // `exported` = an SVG export file exists (from the last export listing); best-known from
202
+ // exportState, which renderExports() populates. Unknown before Exports is opened → false.
203
+ const exported = !!(exportState && exportState.svg && exportState.svg.exportedAt);
204
+ bridge.setWorkspaceGuide({ app: current.app, name: current.name, displayName: appDisplayName(current.app), approved: !!current.approvedAt, exported });
205
+ }
206
+
67
207
  // ── mode ────────────────────────────────────────────────────────────────────
68
208
  function applyMode() {
69
209
  const ws = mode === 'workspaces';
70
210
  $app.classList.toggle('mode-workspaces', ws);
211
+ document.body.classList.toggle('mode-workspaces', ws);
71
212
  $switch.querySelectorAll('button').forEach((b) => {
72
213
  const on = b.dataset.mode === mode;
73
214
  b.classList.toggle('active', on);
@@ -78,11 +219,20 @@
78
219
  $spine.hidden = !ws || !current;
79
220
  if (!ws && !$projMenu.hidden) closeProjMenu();
80
221
  if (ws && !current) loadProjects();
222
+ // Keep the shared guide beacon in step with mode: in Workflows mode (or the Workspaces
223
+ // landing) it must NOT show a workspace guide — clear it so aware.js reverts to the
224
+ // workflow beacon; in a Workspaces project it points at that project's lifecycle.
225
+ if (!ws || !current) { if (bridge.clearWorkspaceGuide) bridge.clearWorkspaceGuide(); }
226
+ else syncWorkspaceGuide();
81
227
  }
82
228
  function setMode(m) {
83
- mode = m === 'workspaces' ? 'workspaces' : 'workflows';
229
+ const next = m === 'workspaces' ? 'workspaces' : 'workflows';
230
+ const changed = next !== mode;
231
+ mode = next;
84
232
  try { localStorage.setItem(LS_MODE, mode); } catch { /* private mode */ }
85
233
  applyMode();
234
+ // Real user intent: a mode toggle (not the boot/render applyMode). Only on an actual change.
235
+ if (changed) track('workspaces_mode_switched', { mode });
86
236
  }
87
237
  $switch.addEventListener('click', (e) => {
88
238
  const b = e.target.closest('button[data-mode]');
@@ -112,27 +262,87 @@
112
262
  // (the empty-state CTA would be a lie: "no projects yet" when the truth is "load failed").
113
263
  try { ({ projects } = await api('/api/projects')); }
114
264
  catch (err) { projects = []; showToast('Couldn’t load projects: ' + (err && err.message || err), 'warn'); }
265
+ // Which workspace apps to offer a create card for: those flagged workspace===true on /api/apps
266
+ // that we ALSO know how to render (have a WORKSPACE_APPS descriptor). Keep descriptor order for a
267
+ // stable card order. A load failure leaves wsAppIds at its descriptor-key fallback (still usable).
268
+ try {
269
+ const { apps } = await api('/api/apps');
270
+ const flagged = new Set((apps || []).filter((a) => a && a.workspace === true).map((a) => a.id));
271
+ wsAppIds = Object.keys(WORKSPACE_APPS).filter((id) => flagged.has(id));
272
+ // Hardening: /api/apps loaded but flagged NONE of our known workspace apps (a transient
273
+ // appWorkspace read blip returning false for all). Rather than render zero create cards, fall
274
+ // back to the descriptor keys — the same usable default a full /api/apps failure lands on.
275
+ if (wsAppIds.length === 0 && Object.keys(WORKSPACE_APPS).length > 0) {
276
+ wsAppIds = Object.keys(WORKSPACE_APPS);
277
+ }
278
+ for (const a of apps || []) {
279
+ if (a && a.workspace === true && !WORKSPACE_APPS[a.id]) {
280
+ console.warn(`[workspaces] app "${a.id}" is flagged workspace but has no client descriptor — skipping its create card`);
281
+ }
282
+ }
283
+ } catch { /* keep the descriptor-key fallback — the create cards still work */ }
115
284
  renderLanding();
116
285
  }
117
286
 
118
287
  function renderLanding() {
119
288
  let html = `<div class="ws-head"><h2>Workspaces</h2>` +
120
- `<div class="ws-sub">Live projects — open a document to keep working. No Run here.</div></div>` +
121
- `<div class="ws-grid">`;
289
+ `<div class="ws-sub">Live projects — open a document to keep working. No Run here.</div></div>`;
290
+ // Create affordances stay docked at the top, separate from existing projects. Drawing-first
291
+ // entries lead; importing the current Workflows model stays last because it is a different mode.
292
+ const createEntries = wsAppIds
293
+ .flatMap((id) => {
294
+ const d = WORKSPACE_APPS[id];
295
+ const actions = d && Array.isArray(d.createActions) ? d.createActions : [];
296
+ return actions.map((action) => ({ id, d, action }));
297
+ })
298
+ .sort((a, b) => {
299
+ if (a.action.kind === 'current' && b.action.kind !== 'current') return 1;
300
+ if (a.action.kind !== 'current' && b.action.kind === 'current') return -1;
301
+ return 0;
302
+ });
303
+ if (createEntries.length) {
304
+ html += `<div class="ws-create-grid">`;
305
+ for (const { id, action } of createEntries) {
306
+ const isDrawing = action.kind === 'drawing';
307
+ html += `<button type="button" class="ws-seed${isDrawing ? ' ws-seed-drop' : ''}" ` +
308
+ `aria-label="${escapeAttr(action.label || action.headline)}" ` +
309
+ `data-seed-app="${escapeAttr(id)}" data-seed-action="${escapeAttr(action.kind)}"` +
310
+ (isDrawing ? ` data-seed-drop="${escapeAttr(id)}"` : '') +
311
+ `>` +
312
+ `<span class="plus">+</span>` +
313
+ `<span class="ws-seed-headline">${escapeHtml(action.headline)}</span>` +
314
+ (action.capability ? `<span class="ws-seed-capability">${escapeHtml(action.capability)}</span>` : '') +
315
+ `<span class="ws-seed-sub">${escapeHtml(action.sub)}</span>` +
316
+ `</button>`;
317
+ }
318
+ html += `</div>`;
319
+ }
320
+ html += `<div class="ws-grid">`;
122
321
  for (const p of projects) {
322
+ const d = WORKSPACE_APPS[p.app];
323
+ const displayApp = appDisplayName(p.app);
324
+ const projectCapability = d && d.projectCapability ? d.projectCapability : '';
123
325
  html += `<div class="ws-card" role="button" tabindex="0" data-open="${escapeAttr(p.id)}">` +
124
- `<span class="ws-thumb"><span class="ws-kind">${escapeHtml(p.app)}</span>▦</span>` +
326
+ `<span class="ws-thumb"><span class="ws-kind">${escapeHtml(displayApp)}</span>▦</span>` +
125
327
  `<span class="ws-body"><span><span class="ws-name">${escapeHtml(p.name)}</span>` +
126
- `<span class="ws-meta">${escapeHtml(p.app)} · <span class="t">${escapeHtml(relAgo(p.updatedAt))}</span></span></span>` +
328
+ (projectCapability ? `<span class="ws-meta">${escapeHtml(projectCapability)}</span>` : '') +
329
+ `<span class="ws-meta">${escapeHtml(displayApp)} · <span class="t">${escapeHtml(relAgo(p.updatedAt))}</span></span></span>` +
127
330
  `<button type="button" class="ws-kebab" data-kebab="${escapeAttr(p.id)}" aria-label="Project actions" data-tip="Rename · Duplicate · Archive">⋯</button>` +
128
331
  `</span></div>`;
129
332
  }
130
- // Slice-1 creation path: seed a project from the app's current takeoff. The
131
- // compose-time "read a drawing set" flow is Slice 4 — this card is honest about that.
132
- html += `<button type="button" class="ws-seed" id="ws-seed">` +
133
- `<span class="plus">+</span><span>Import the current ${escapeHtml(WORKSPACE_APP)} takeoff as a project</span></button>`;
134
333
  html += `</div>`;
135
- if (!projects.length) html += `<div class="ws-empty-note">No projects yet — import your current takeoff above, or ask your terminal AI to read a drawing set.</div>`;
334
+ // Empty-note copy adapts to which create affordances are on screen.
335
+ if (!projects.length) {
336
+ const actions = createEntries.map((entry) => entry.action);
337
+ const hasDrawingSeed = actions.some((action) => action.kind === 'drawing');
338
+ const hasCurrentSeed = actions.some((action) => action.kind === 'current');
339
+ const note = hasDrawingSeed && hasCurrentSeed
340
+ ? 'No projects yet — drop drawings above, or import your current steel model.'
341
+ : hasDrawingSeed
342
+ ? 'No projects yet — drop a drawing above, or ask your terminal AI to trace a drawing set.'
343
+ : 'No projects yet — import your current steel model above, or ask your terminal AI to read a drawing set.';
344
+ html += `<div class="ws-empty-note">${escapeHtml(note)}</div>`;
345
+ }
136
346
  $landing.innerHTML = html;
137
347
  }
138
348
 
@@ -141,7 +351,15 @@
141
351
  if (kebab) { e.stopPropagation(); openProjMenu(kebab.dataset.kebab, kebab); return; }
142
352
  const card = e.target.closest('[data-open]');
143
353
  if (card) { openProject(card.dataset.open); return; }
144
- if (e.target.closest('#ws-seed')) createSeeded();
354
+ const seed = e.target.closest('[data-seed-app]');
355
+ if (seed) {
356
+ const id = seed.dataset.seedApp;
357
+ const d = WORKSPACE_APPS[id];
358
+ if (d && seed.dataset.seedAction === 'drawing') {
359
+ const files = await pickDrawingFiles($seedFile); // drop-a-drawing: open the picker
360
+ if (files.length) createFromDrawing(id, files);
361
+ } else createSeeded(id); // takeoff import
362
+ }
145
363
  });
146
364
  $landing.addEventListener('keydown', (e) => {
147
365
  if (e.key !== 'Enter' && e.key !== ' ') return;
@@ -149,49 +367,158 @@
149
367
  if (card) { e.preventDefault(); openProject(card.dataset.open); }
150
368
  });
151
369
 
370
+ // Drop-a-drawing dropzone. A single hidden picker (outside $landing so an innerHTML re-render can't
371
+ // wipe it) backs the click-to-pick; dragover/drop are delegated on $landing so they survive the
372
+ // re-render too. The dashed card lights up (.drag-over) while a file hovers it.
373
+ // Fallback-only hidden input (outside $landing so an innerHTML re-render can't wipe it) —
374
+ // driven by pickDrawingFiles() above when the File System Access API isn't available.
375
+ const $seedFile = document.createElement('input');
376
+ $seedFile.type = 'file'; $seedFile.accept = '.pdf,image/*'; $seedFile.multiple = true; $seedFile.hidden = true;
377
+ document.body.appendChild($seedFile);
378
+ $landing.addEventListener('dragover', (e) => {
379
+ const zone = e.target.closest('[data-seed-drop]');
380
+ if (!zone) return;
381
+ e.preventDefault();
382
+ zone.classList.add('drag-over');
383
+ });
384
+ $landing.addEventListener('dragleave', (e) => {
385
+ const zone = e.target.closest('[data-seed-drop]');
386
+ if (zone && !zone.contains(e.relatedTarget)) zone.classList.remove('drag-over');
387
+ });
388
+ $landing.addEventListener('drop', (e) => {
389
+ const zone = e.target.closest('[data-seed-drop]');
390
+ if (!zone) return;
391
+ e.preventDefault();
392
+ zone.classList.remove('drag-over');
393
+ const files = Array.from((e.dataTransfer && e.dataTransfer.files) || []);
394
+ if (files.length) createFromDrawing(zone.dataset.seedDrop, files);
395
+ });
396
+
152
397
  async function promptName(title, label, value) {
153
398
  if (!bridge.formModal) return null;
154
399
  const res = await bridge.formModal({ title, fields: [{ name: 'name', label, value, placeholder: 'e.g. Westfield Retail — Ph2' }], okLabel: 'Save' });
155
400
  return res && typeof res.name === 'string' && res.name.trim() ? res.name.trim() : null;
156
401
  }
157
402
 
158
- async function createSeeded() {
403
+ async function createSeeded(appId) {
159
404
  const name = await promptName('New project', 'Name this project', '');
160
405
  if (!name) return;
161
406
  try {
162
- const { project, seeded } = await api('/api/projects', { method: 'POST', body: JSON.stringify({ name, app: WORKSPACE_APP, seedFromApp: true }) });
163
- // Tell the truth about the import: seeded=false means there was no current takeoff to copy
164
- // (or it was unreadable) — the project is EMPTY, don't imply the takeoff came across.
165
- if (seeded) showToast(`Project "${project.name}" created from the current ${WORKSPACE_APP} takeoff`, 'ok');
166
- else showToast(`Project "${project.name}" created — empty (no current ${WORKSPACE_APP} takeoff to import)`, 'warn');
407
+ const { project, seeded } = await api('/api/projects', { method: 'POST', body: JSON.stringify({ name, app: appId, seedFromApp: true }) });
408
+ // Tell the truth about the import: seeded=false means there was no current model to copy
409
+ // (or it was unreadable) — the project is EMPTY, don't imply the model came across.
410
+ const seedLabel = (WORKSPACE_APPS[appId] && WORKSPACE_APPS[appId].seedLabel) || 'model';
411
+ if (seeded) showToast(`Project "${project.name}" created from the current ${seedLabel}`, 'ok');
412
+ else showToast(`Project "${project.name}" created — empty (no current ${seedLabel} to import)`, 'warn');
413
+ track('workspace_project_created', { app: appId }); // takeoff-import create path
167
414
  projects.unshift(project);
168
415
  openProject(project.id);
169
416
  } catch (err) { showToast('Couldn’t create the project: ' + (err && err.message || err), 'warn'); }
170
417
  }
171
418
 
419
+ // Drop-a-drawing create. No new server verb: create an EMPTY project, then fire the
420
+ // existing revision pipeline (attachRevision) with the dropped file so the terminal AI reads it into
421
+ // v1. ROLLBACK on cancel/error — if the user cancels the name prompt, or the file can't be read,
422
+ // AFTER the row is created, archive the empty project so no dead, openable project is left
423
+ // behind (the row is created before the source exists — spec §4.1).
424
+ async function createFromDrawing(appId, files) {
425
+ // Ask for the name FIRST (before creating a row) so the common "cancel the prompt" path never
426
+ // creates anything to roll back.
427
+ const name = await promptName(`New ${appDisplayName(appId)} project`, 'Name this project', '');
428
+ if (!name) return;
429
+ let project;
430
+ try {
431
+ ({ project } = await api('/api/projects', { method: 'POST', body: JSON.stringify({ name, app: appId, seedFromApp: false }) }));
432
+ } catch (err) {
433
+ showToast('Couldn’t create the project: ' + (err && err.message || err), 'warn');
434
+ return;
435
+ }
436
+ // Validate the files are actually readable BEFORE queuing — a read failure here (after the row
437
+ // exists) must roll the empty project back rather than leave a dead one openable. attachRevision
438
+ // re-reads the files for the real pipeline; a tiny second read of the same files is harmless.
439
+ try { await readFileAsSnapshot(files[0]); }
440
+ catch {
441
+ // Tailor the toast to what actually happened server-side: only claim the empty project was
442
+ // removed if the archive POST succeeded — otherwise it's still there and we must say so.
443
+ const removed = await archiveEmptyProject(project.id);
444
+ showToast(
445
+ removed
446
+ ? 'Couldn’t read the dropped drawing — the empty project was removed.'
447
+ : 'Couldn’t read the dropped drawing — an empty project was left behind; archive it from the ⋯ menu.',
448
+ 'warn',
449
+ );
450
+ return;
451
+ }
452
+ track('workspace_project_created', { app: appId }); // drop-a-drawing create path (only once the row is kept, not rolled back)
453
+ projects.unshift(project);
454
+ openProject(project.id, 'drawings'); // show the queued drawing read before a model contract exists
455
+ attachRevision(files); // reads the file → POSTs the revision-read Request for THIS project (self-toasting)
456
+ }
457
+
458
+ // Best-effort rollback of a just-created empty project (the existing archive path — recoverable).
459
+ // Returns true if the archive POST succeeded (removed server-side), false if it failed (a dead
460
+ // empty project was left behind) so the caller can tell the truth in its toast. Either way the
461
+ // local row is dropped so the landing doesn't keep showing it.
462
+ async function archiveEmptyProject(id) {
463
+ let removed = true;
464
+ try { await api(`/api/projects/${encodeURIComponent(id)}/archive`, { method: 'POST', body: '{}' }); }
465
+ catch { removed = false; /* leave it — the landing simply shows an empty project the user can archive manually */ }
466
+ projects = projects.filter((p) => p.id !== id);
467
+ return removed;
468
+ }
469
+
172
470
  // ── open project ────────────────────────────────────────────────────────────
173
- async function openProject(id) {
471
+ async function openProject(id, initialStep = 'model') {
174
472
  let p = projects.find((x) => x.id === id);
175
473
  if (!p) { try { p = (await api('/api/projects')).projects.find((x) => x.id === id); } catch { /* fall through */ } }
176
474
  if (!p) { showToast('Project not found — it may have been archived.', 'warn'); return loadProjects(); }
475
+ // Never a broken open (spec §3.2): a project whose app has no client descriptor (uninstalled or
476
+ // renamed workspace app) can't be rendered — toast and bail BEFORE mutating any view state,
477
+ // matching the create-card skip. wsApp() would return null for it and the frame wiring would fail.
478
+ if (!WORKSPACE_APPS[p.app]) { showToast('This project’s app isn’t available as a workspace.', 'warn'); return; }
177
479
  current = p;
480
+ track('workspace_project_opened', { app: p.app }); // a real open (card click or post-create landing)
178
481
  lastRevState = 'none'; stopRevisionPoll(); // fresh project — drop any prior revision-poll state
179
482
  $projName.textContent = p.name;
180
483
  $crumbName.textContent = p.name;
181
- $status.textContent = p.app;
484
+ $status.textContent = appDisplayName(p.app);
182
485
  // Lazily src the frames once per project; switching steps only toggles hidden so the
183
- // editor's 3D state survives a Drawings⇄Model round-trip.
486
+ // editor's state survives a Source⇄Traced round-trip. Frame URLs come from the app descriptor:
487
+ // the 'model' frame loads the app's editor; the 'drawings' frame loads its filter (steel) OR is
488
+ // left empty when the app has no filter step (vectorize — its Source step shows a placeholder).
489
+ const d = WORKSPACE_APPS[p.app]; // guaranteed present — the guard above bailed on an unknown app
184
490
  const qs = `?app=${encodeURIComponent(p.app)}&project=${encodeURIComponent(p.id)}`;
185
- frames.model.dataset.want = `/steel-editor.html${qs}`;
186
- frames.drawings.dataset.want = `/steel-filter.html${qs}`;
491
+ frames.model.dataset.want = `${d.editor}${qs}`;
492
+ frames.drawings.dataset.want = d.filter ? `${d.filter}${qs}` : '';
493
+ renderStepTabs(); // paint the tab labels for THIS app before the first step shows
187
494
  frames.model.src = 'about:blank'; frames.drawings.src = 'about:blank'; // reset any previous project
188
495
  frames.model.dataset.loaded = ''; frames.drawings.dataset.loaded = '';
189
- setStep('model');
496
+ setStep(initialStep);
190
497
  applyMode();
498
+ syncWorkspaceGuide(); // point the shared beacon at THIS project's document lifecycle
499
+ }
500
+ function closeProject() {
501
+ current = null;
502
+ stopRevisionPoll();
503
+ stopKnowledgePoll(); kbCloseConfirm(); kbResetViewer(); knowledgeState = null; // the KB pane is per-project — never carry it across
504
+ lastRevState = 'none'; $revisionCard.hidden = true; closeProjMenu(); applyMode(); syncWorkspaceGuide();
191
505
  }
192
- function closeProject() { current = null; stopRevisionPoll(); lastRevState = 'none'; $revisionCard.hidden = true; closeProjMenu(); applyMode(); }
193
506
  document.getElementById('ws-back').addEventListener('click', closeProject);
194
507
 
508
+ // Paint the step-tab LABELS from the current app's descriptor (Source/Traced for vectorize,
509
+ // Drawings/Model for steel). The data-step KEYS stay stable (drawings/model/exports/history) so
510
+ // setStep() and the frame slots are untouched — only the visible text differs. Label is set via
511
+ // textContent (never innerHTML) — it's a descriptor string, but textContent is the safe default.
512
+ function renderStepTabs() {
513
+ const d = wsApp();
514
+ if (!d) return;
515
+ const byKey = new Map(d.steps.map((st) => [st.key, st.label]));
516
+ $stepTabs.querySelectorAll('button[data-step]').forEach((b) => {
517
+ const label = byKey.get(b.dataset.step);
518
+ if (label) b.textContent = label;
519
+ });
520
+ }
521
+
195
522
  function setStep(s) {
196
523
  currentStep = s;
197
524
  $stepTabs.querySelectorAll('button').forEach((b) => {
@@ -199,11 +526,16 @@
199
526
  b.classList.toggle('active', on);
200
527
  b.setAttribute('aria-selected', String(on));
201
528
  });
529
+ // An app with no filter (vectorize) has an empty `drawings` frame URL — never src it; its Source
530
+ // step shows a lightweight placeholder pane instead of an about:blank iframe.
531
+ const d = wsApp();
532
+ const drawingsHasFrame = !!(d && d.filter);
202
533
  for (const [k, f] of Object.entries(frames)) {
203
- const show = k === s;
534
+ const show = k === s && (k !== 'drawings' || drawingsHasFrame);
204
535
  f.hidden = !show;
205
- if (show && !f.dataset.loaded) { f.src = f.dataset.want; f.dataset.loaded = '1'; }
536
+ if (show && !f.dataset.loaded && f.dataset.want) { f.src = f.dataset.want; f.dataset.loaded = '1'; }
206
537
  }
538
+ if ($sourcePlaceholder) $sourcePlaceholder.hidden = !(s === 'drawings' && !drawingsHasFrame);
207
539
  $drawingsBar.hidden = s !== 'drawings';
208
540
  renderRevisionCard(); // reflect any pending/failed revision read (card shows only on the Drawings step)
209
541
  // Exports is a shell-rendered pane (not an iframe): show/hide + (re)paint on open.
@@ -215,6 +547,14 @@
215
547
  $wsHistory.hidden = !showHistory;
216
548
  if (showHistory) renderHistory();
217
549
  else { closeRollbackConfirm(); closeBaseMenu(); } // don't leave a popover open behind a step switch
550
+ // Knowledge is a shell-rendered pane too: the project's Knowledge Base (References column).
551
+ const showKnowledge = s === 'knowledge';
552
+ $wsKnowledge.hidden = !showKnowledge;
553
+ if (showKnowledge) renderKnowledge();
554
+ // Leaving the step: drop the in-flight poll + any open confirm, close the viewer (aborting an
555
+ // in-flight preview read), and forget the cached state so re-entering re-reads rather than
556
+ // flashing a stale column.
557
+ else { stopKnowledgePoll(); kbCloseConfirm(); kbResetViewer(); knowledgeState = null; }
218
558
  }
219
559
  $stepTabs.addEventListener('click', (e) => {
220
560
  const b = e.target.closest('button[data-step]');
@@ -222,7 +562,7 @@
222
562
  });
223
563
 
224
564
  // ── Approve (per-project) ───────────────────────────────────────────────────
225
- // Shared by the header ✓ Approve and the Exports-tab gate link ("Approve the model"), so the
565
+ // Shared by the header ✓ Approve and the Exports-tab gate link ("Approve this version"), so the
226
566
  // sign-off is one flow. On success it stamps current.approvedAt (server returns it) so the
227
567
  // Exports gate unlocks without a reload.
228
568
  async function approveProject() {
@@ -239,7 +579,12 @@
239
579
  if (win && typeof win.flushContract === 'function') await win.flushContract();
240
580
  const res = await api(`/api/contract/${encodeURIComponent(current.app)}/approve?project=${encodeURIComponent(current.id)}`, { method: 'POST' });
241
581
  if (res && res.approvedAt) current.approvedAt = res.approvedAt; // unlock exports
242
- showToast(`Approved — "${current.name}" is baked into ${current.app}`, 'ok');
582
+ showToast(`Approved — "${current.name}" is baked into ${appDisplayName(current.app)}`, 'ok');
583
+ track('workspace_project_approved', { app: current.app }); // a successful sign-off
584
+ // First Approve for this app calms the "✦ Start here" beacon (the document-archetype
585
+ // analog of a workflow's first Run); ticks the Review + Approve guide rows.
586
+ if (bridge.markWorkspaceApproved && wsHasDocGuide()) bridge.markWorkspaceApproved(current.app);
587
+ syncWorkspaceGuide();
243
588
  if (!$wsExports.hidden) renderExports(); // reflect the unlocked gate immediately if it's open
244
589
  if (!$wsHistory.hidden) renderHistory(); // a new version was recorded — reflect it + clear the banner
245
590
  } catch (err) {
@@ -285,6 +630,763 @@
285
630
  // (find methods are exposed on the canonical window.flolessWorkspaces export below — a separate
286
631
  // assignment here would be clobbered by that later `= { setMode, … }`.)
287
632
 
633
+ // ── Knowledge step (Slice 8 Stage B) ──────────────────────────────────────────
634
+ // The per-project Knowledge Base, References column: drop references → per-source useAsKb
635
+ // toggle → remove → Organize. The UI NEVER parses a source or edits the wiki — Organize queues a
636
+ // `knowledge-organize` Request that the terminal AI drains with the floless-app-knowledge skill
637
+ // (start → compile into the server-minted wikiDir → finish). Routes: server/knowledge-routes.ts.
638
+ // The graph + note columns are Stage C/D; their area shows a forthcoming placeholder.
639
+ //
640
+ // Upload caps MIRROR the server's decodeUpload (knowledge-store.ts:145-147) so a hopeless batch is
641
+ // rejected before the browser allocates base64 data URLs. The server re-checks everything and stays
642
+ // the source of truth (it also magic-byte sniffs, which the client cannot).
643
+ const KB_MAX_FILES = 50;
644
+ const KB_MAX_FILE_BYTES = 100 * 1024 * 1024;
645
+ const KB_MAX_TOTAL_BYTES = 150 * 1024 * 1024;
646
+ const KB_LOCK_STALE_MS = 10 * 60 * 1000; // = knowledge-store.ts LOCK_STALE_MS; when to warn "taking longer"
647
+ const KB_MB = (n) => Math.round(n / (1024 * 1024));
648
+ let knowledgePoll = null;
649
+ let knowledgeState = null;
650
+
651
+ // ── Stage B2: the content-switched viewer ────────────────────────────────────
652
+ // The pane right of References holds exactly one of: 'graph' (today the Stage-C placeholder),
653
+ // 'file' (this slice), 'note' (Stage D). Stage C swaps only what 'graph' renders.
654
+ const KB_TEXT_CAP = 256 * 1024; // load-bearing: the upload cap is 100 MB, and a 100 MB <pre> hangs the tab
655
+ let viewer = { mode: 'graph', sourceId: null };
656
+ let viewEpoch = 0; // invalidates in-flight preview loads
657
+ let knowledgeRenderEpoch = 0; // invalidates in-flight /status loads (poll ticks race verbs)
658
+ let kbTextAbort = null; // AbortController for the in-flight preview fetch
659
+ let lastRefsHtml = null; // exact rendered HTML of the refs host, or null to force a repaint
660
+ let lastViewKey = null; // identity of what the viewer host is currently showing
661
+ let kbFocusSourceId = null; // consumed once after a repaint, to restore focus to a filename button
662
+
663
+ const kbUrl = (id, tail = '') => `/api/projects/${encodeURIComponent(id)}/knowledge${tail}`;
664
+ const kbRawUrl = (id, sourceId) => kbUrl(id, `/sources/${encodeURIComponent(sourceId)}/raw`);
665
+
666
+ /** Any IMPERATIVE mutation of the refs DOM must invalidate the cache, or the next render — which
667
+ * compares rendered HTML against `lastRefsHtml` — will skip a repaint that is actually needed.
668
+ * The optimistic toggle is the dangerous one: on a failed PATCH the model never changed, so the
669
+ * freshly rendered HTML would EQUAL the cache and the wrong optimistic state would persist. */
670
+ const kbInvalidateRefs = () => { lastRefsHtml = null; };
671
+
672
+ /** Bump the epoch (so in-flight loads drop their DOM writes) and abort the in-flight fetch. Called by
673
+ * setViewer, and ALSO when the view key changes with no setViewer() — a poll can swap a row's
674
+ * blobSha256 under an open preview, and without this the superseded text download keeps streaming
675
+ * while its replacement starts. */
676
+ function kbAbortPreview() {
677
+ viewEpoch += 1;
678
+ if (kbTextAbort) { try { kbTextAbort.abort(); } catch { /* already settled */ } kbTextAbort = null; }
679
+ }
680
+
681
+ /** THE one place `viewer` changes. Detaches native `src` (an already-started iframe/image load
682
+ * ignores AbortController, so the attribute must go) and then EMPTIES the host — a leftover
683
+ * <pre>/error pane would otherwise survive a step change and stay visible, permanently so if the
684
+ * /status read fails on re-entry. Nulling `lastViewKey` matters for Retry: retrying the same source
685
+ * reproduces an identical key, and a key-guarded repaint would paint nothing into the emptied host. */
686
+ function setViewer(next) {
687
+ kbAbortPreview();
688
+ const host = $wsKnowledge.querySelector('.kb-view-host');
689
+ if (host) {
690
+ host.querySelectorAll('iframe, img').forEach((n) => { n.removeAttribute('src'); });
691
+ host.innerHTML = '';
692
+ }
693
+ lastViewKey = null;
694
+ viewer = next;
695
+ }
696
+
697
+ /** Leaving the project or the step: close the viewer and drop every cache. */
698
+ function kbResetViewer() {
699
+ setViewer({ mode: 'graph', sourceId: null });
700
+ lastRefsHtml = null;
701
+ kbFocusSourceId = null;
702
+ }
703
+
704
+ function stopKnowledgePoll() { if (knowledgePoll) { clearInterval(knowledgePoll); knowledgePoll = null; } }
705
+ function startKnowledgePoll() {
706
+ if (knowledgePoll) return; // already ticking — don't stack intervals across re-renders
707
+ knowledgePoll = setInterval(() => {
708
+ if (!current || $wsKnowledge.hidden) { stopKnowledgePoll(); return; }
709
+ renderKnowledge();
710
+ }, 3000);
711
+ }
712
+
713
+ // ONE freshness contract for the whole column. A just-queued organize exists ONLY in /api/requests
714
+ // (the store writes organize.json at `start`), so "pending" must be the UNION of both reads — never
715
+ // /status alone. The request queue is advisory: a blip there must not blank the sources column.
716
+ async function loadKnowledgeState(proj) {
717
+ const [status, reqs] = await Promise.all([
718
+ api(kbUrl(proj.id, '/status')),
719
+ api('/api/requests').catch(() => []),
720
+ ]);
721
+ const list = Array.isArray(reqs) ? reqs : (reqs.requests || []);
722
+ const manifest = status.manifest || { revision: 0, currentGeneration: null, sources: [] };
723
+ return {
724
+ manifest,
725
+ sources: Array.isArray(manifest.sources) ? manifest.sources : [],
726
+ currentGeneration: status.currentGeneration || null,
727
+ organize: status.organize || null,
728
+ queued: list.filter((r) => r && r.type === 'knowledge-organize' && r.project === proj.id),
729
+ };
730
+ }
731
+
732
+ // Pending = started (organize.json, has startedAt) OR merely queued (a request, has createdAt).
733
+ function kbPending(st) {
734
+ if (st.organize) return { started: true, since: Date.parse(st.organize.startedAt) };
735
+ const q = st.queued[0];
736
+ if (q) return { started: false, since: Date.parse(q.createdAt) };
737
+ return null;
738
+ }
739
+ const kbAgo = (ms) => {
740
+ if (!Number.isFinite(ms) || ms < 0) return '';
741
+ const m = Math.floor(ms / 60000);
742
+ if (m < 1) return 'just now';
743
+ if (m < 60) return `${m}m ago`;
744
+ return `${Math.floor(m / 60)}h ago`;
745
+ };
746
+ const kbBytes = (n) => (!Number.isFinite(n) ? '—'
747
+ : n < 1024 ? `${n} B`
748
+ : n < 1024 * 1024 ? `${Math.round(n / 1024)} KB`
749
+ : `${(n / (1024 * 1024)).toFixed(1)} MB`);
750
+ function kbIcon(mime) {
751
+ const m = String(mime || '');
752
+ if (m.includes('pdf')) return { cls: 'pdf', glyph: '▤' };
753
+ if (m.startsWith('image/')) return { cls: 'img', glyph: '▣' };
754
+ if (m.includes('csv')) return { cls: 'sheet', glyph: '◧' };
755
+ return { cls: 'txt', glyph: '▦' };
756
+ }
757
+ // Literal chip copy per state (never interpolated from the server); unknown state falls back escaped.
758
+ const KB_CHIP = {
759
+ new: ['new', 'new'],
760
+ organizing: ['run', 'organizing'],
761
+ organized: ['ok', 'organized ✓'],
762
+ error: ['err', 'failed'],
763
+ };
764
+
765
+ // SECURITY: every value below is server/AI/user-derived — escapeHtml for text, escapeAttr for
766
+ // attributes. Nothing reaches innerHTML raw (design §6: never raw LLM HTML).
767
+ function kbSourceRow(s) {
768
+ const on = !!s.useAsKb;
769
+ const ico = kbIcon(s.mime);
770
+ const chip = KB_CHIP[s.state] || ['new', escapeHtml(String(s.state || 'new'))];
771
+ const name = s.filename || 'untitled';
772
+ const meta = s.kind === 'observation' ? 'note' : kbBytes(s.bytes);
773
+ const imported = s.importedFrom ? '<span class="kb-chip">imported</span>' : '';
774
+ const err = s.state === 'error' && s.error
775
+ ? `<div class="kb-err"><b>Couldn’t organize.</b> ${escapeHtml(s.error)} Organize again to retry.</div>`
776
+ : '';
777
+ // The FILENAME is the trigger, rendered as a real <button>. Making the whole row clickable would
778
+ // nest the toggle and ✕ inside an interactive element — an a11y problem needing click-target
779
+ // exclusions. `aria-current` (not `aria-selected`, which is invalid on a generic role and would
780
+ // fail aria-allowed-attr) marks the row whose file is on screen.
781
+ const isOpen = viewer.mode === 'file' && viewer.sourceId === s.sourceId;
782
+ return `<div class="kb-src${on ? '' : ' off'}${s.state === 'error' ? ' state-error' : ''}"` +
783
+ ` data-source-id="${escapeAttr(s.sourceId)}"${isOpen ? ' aria-current="true"' : ''}>` +
784
+ `<span class="kb-fico ${ico.cls}" aria-hidden="true">${ico.glyph}</span>` +
785
+ `<div class="kb-fbody">` +
786
+ `<button type="button" class="kb-fname" data-kb-open="${escapeAttr(s.sourceId)}" ` +
787
+ `data-tip="Preview “${escapeAttr(name)}”">${escapeHtml(name)}</button>` +
788
+ `<div class="kb-fmeta">${escapeHtml(meta)}<span class="kb-chip ${chip[0]}">${chip[1]}</span>${imported}</div>` +
789
+ err +
790
+ `</div>` +
791
+ `<button type="button" class="kb-toggle" role="switch" aria-checked="${on ? 'true' : 'false'}" data-kb-toggle ` +
792
+ `aria-label="Use “${escapeAttr(name)}” as knowledge" ` +
793
+ `data-tip="${on ? 'Included in the knowledge base — click to exclude' : 'Excluded from the knowledge base — click to include'}"></button>` +
794
+ `<button type="button" class="kb-x" data-kb-remove aria-label="Remove “${escapeAttr(name)}”" data-tip="Remove this reference">✕</button>` +
795
+ `</div>`;
796
+ }
797
+
798
+ function kbFoot(st) {
799
+ const enabled = st.sources.filter((s) => s.useAsKb).length;
800
+ const pending = kbPending(st);
801
+ const gen = st.currentGeneration;
802
+
803
+ // Queued ≠ running. Only a `started` pass (organize.json exists) may claim to be organizing;
804
+ // before that the terminal AI hasn't picked the request up yet, so no spinner.
805
+ let pendingLine = '';
806
+ if (pending) {
807
+ const age = kbAgo(Date.now() - pending.since);
808
+ const stale = pending.started && Date.now() - pending.since > KB_LOCK_STALE_MS;
809
+ const cls = stale ? 'kb-pending stale' : pending.started ? 'kb-pending' : 'kb-pending queued';
810
+ const ico = stale ? '<span class="kb-ico" aria-hidden="true">⚠</span>'
811
+ : pending.started ? '<span class="kb-spin" aria-hidden="true"></span>'
812
+ : '<span class="kb-ico" aria-hidden="true">◷</span>';
813
+ const lead = pending.started
814
+ ? `Organizing…${age ? ` started ${escapeHtml(age)}` : ''}`
815
+ : 'Queued for your terminal AI — waiting to start…';
816
+ pendingLine = `<div class="${cls}">${ico}<span>${lead}` +
817
+ (stale ? ' <span class="kb-stale">taking longer than expected — check your terminal AI is running.</span>' : '') +
818
+ '</span></div>';
819
+ }
820
+
821
+ let status;
822
+ if (st.sources.some((s) => s.state === 'error')) status = '<span class="err">✕ last organize failed</span>';
823
+ else if (gen) {
824
+ status = `<span class="ok">✓ organized</span> · ${escapeHtml(kbAgo(Date.now() - Date.parse(gen.publishedAt)))}` +
825
+ (st.manifest.lastLintSummary ? ` · ${escapeHtml(st.manifest.lastLintSummary)}` : '');
826
+ } else status = st.sources.length ? 'Not yet organized — press Organize when you’re ready.' : '';
827
+
828
+ // Organize is this panel's ONE persistent primary action — always visible, even at zero sources,
829
+ // because its presence teaches the two-step model (collect, then Organize). When unavailable it
830
+ // uses aria-disabled + a data-tip that SAYS WHY, never a mystery-disabled control and never a
831
+ // native title= (verify:no-title). aria-disabled (not `disabled`) keeps hover/focus alive so the
832
+ // tooltip actually fires; the click handler no-ops on it.
833
+ // The label stays plain "Organize": a pass is a FULL recompile from the truth set, so "Organize
834
+ // new" would misdescribe it.
835
+ const why = pending ? 'An organize is already queued for your terminal AI'
836
+ : !st.sources.length ? 'Drop a reference above to get started'
837
+ : enabled === 0 ? 'Turn on at least one reference to organize'
838
+ : 'Queue an organize — your terminal AI compiles these references into this project’s wiki';
839
+ const off = !!pending || enabled === 0 || !st.sources.length;
840
+ const organizeBtn = `<button type="button" class="primary kb-organize" id="kb-organize"` +
841
+ `${off ? ' aria-disabled="true"' : ''} data-tip="${escapeAttr(why)}">✦ Organize</button>`;
842
+
843
+ return `<div class="kb-refs-foot">${pendingLine}` +
844
+ (status ? `<div class="kb-status">${status}</div>` : '') + organizeBtn + '</div>';
845
+ }
846
+
847
+ // Stage C/D live here. After a real Organize the user's eye lands on this big empty canvas, so it
848
+ // must CONFIRM the action worked rather than look unchanged. Glyph reuses the app's existing ✦
849
+ // vocabulary — no new iconography.
850
+ // The copy also teaches the Stage-B2 affordance: this pane is where a clicked filename opens, and
851
+ // it is the first thing the eye lands on when the viewer closes.
852
+ const kbPlaceholder = (st) => {
853
+ const done = st && st.currentGeneration;
854
+ return '<section class="kb-col kb-placeholder"><div class="kb-ph-inner">' +
855
+ '<span class="kb-ph-ico" aria-hidden="true">✦</span>' +
856
+ '<div class="kb-ph-title">Graph &amp; Notes — coming soon</div>' +
857
+ '<div class="kb-ph-sub">' +
858
+ (done
859
+ ? 'This project’s references are organized. The visual graph — sources, concepts and people, ' +
860
+ 'linked — opens here in a later update. Click any file on the left to preview it in the meantime.'
861
+ : 'Once references are organized, this space maps your knowledge base — sources, concepts and ' +
862
+ 'people, linked — and lets you open any note. For now, click a file on the left to preview it, ' +
863
+ 'or add references and Organize.') +
864
+ '</div></div></section>';
865
+ };
866
+
867
+ // ── The file viewer ───────────────────────────────────────────────────────────
868
+ // SECURITY: `filename` is user-authored and every state below interpolates it — escapeHtml for text,
869
+ // escapeAttr for attributes. The file's own BYTES never reach innerHTML: text is written with
870
+ // textContent into a <pre>, and is never rendered as markdown or HTML (that would be stored XSS for
871
+ // zero benefit). PDFs and images go to the browser's own renderers via src=.
872
+ const kbViewHost = () => $wsKnowledge.querySelector('.kb-view-host');
873
+
874
+ function kbViewShell(row, bodyHtml) {
875
+ const name = row.filename || 'untitled';
876
+ // ✕ only. On a two-state viewer with no history stack a ← would fire the identical action.
877
+ // It gets its OWN hover colour: .kb-x's hover→--err is this pane's destructive "Remove" signal.
878
+ return '<section class="kb-col kb-viewer">' +
879
+ '<div class="kb-view-head">' +
880
+ `<span class="kb-view-name" data-tip="${escapeAttr(name)}">${escapeHtml(name)}</span>` +
881
+ '<button type="button" class="kb-view-x" data-kb-close aria-label="Close preview" data-tip="Close the preview">✕</button>' +
882
+ '</div>' +
883
+ `<div class="kb-view-body">${bodyHtml}</div>` +
884
+ '</section>';
885
+ }
886
+
887
+ const kbPaintView = (row, bodyHtml) => {
888
+ const host = kbViewHost();
889
+ if (host) host.innerHTML = kbViewShell(row, bodyHtml);
890
+ };
891
+
892
+ const kbViewLoading = (row) =>
893
+ '<div class="kb-view-msg"><span class="kb-view-spin" aria-hidden="true"></span>' +
894
+ `<div class="kb-view-msg-sub">Opening “${escapeHtml(row.filename || 'untitled')}”…</div></div>`;
895
+
896
+ /** No previewable bytes. Never offers a bare "Retry" without meaning: a missing blob CAN come back
897
+ * (blobs are content-addressed, so re-dropping the identical file recreates it), so Retry is real —
898
+ * but Remove is the honest primary next step. */
899
+ function kbPaintNoPreview(row, reason) {
900
+ const why = reason === 'decode'
901
+ ? 'This image couldn’t be displayed — the stored file may be incomplete.'
902
+ : reason === 'nofile'
903
+ ? 'This reference has no file to preview.'
904
+ : 'The stored file is missing. Re-add the file, or remove this reference.';
905
+ kbPaintView(row,
906
+ '<div class="kb-view-msg"><span class="kb-view-ico" aria-hidden="true">▦</span>' +
907
+ '<div class="kb-view-msg-title">No preview for this item.</div>' +
908
+ `<div class="kb-view-msg-sub">${escapeHtml(why)}</div>` +
909
+ '<div class="kb-view-act">' +
910
+ (reason === 'nofile' ? '' : '<button type="button" class="primary" data-kb-retry>↻ Retry</button>') +
911
+ `<button type="button" class="kb-view-remove" data-kb-remove-src="${escapeAttr(row.sourceId)}">Remove reference</button>` +
912
+ '</div></div>');
913
+ }
914
+
915
+ /** A retryable failure (5xx, 402, a dropped connection) — distinct from a 404, where retrying the
916
+ * same immutable answer would just fail again. */
917
+ function kbPaintError(row, reason) {
918
+ kbPaintView(row,
919
+ '<div class="kb-view-msg"><span class="kb-view-ico err" aria-hidden="true">⚠</span>' +
920
+ '<div class="kb-view-msg-title">Couldn’t open this file.</div>' +
921
+ `<div class="kb-view-msg-sub">${escapeHtml(reason)}</div>` +
922
+ '<div class="kb-view-act"><button type="button" class="primary" data-kb-retry>↻ Retry</button></div></div>');
923
+ }
924
+
925
+ /** Load and render one source. HEAD-preflights FIRST: an <iframe> fires `load`, not `error`, on a
926
+ * 404, so a bare src= would paint the server's JSON error body — or the licensing 402 — into the
927
+ * pane. The server answers HEAD from one GET+HEAD handler, so this costs headers, not a file read. */
928
+ async function kbLoadPreview(proj, row) {
929
+ const epoch = viewEpoch;
930
+ const key = lastViewKey;
931
+ // A poll can change a row's blobSha256 with no setViewer() call and no epoch bump, so the KEY must
932
+ // be re-checked too — the epoch alone would let an older load overwrite a newer render.
933
+ const alive = () => epoch === viewEpoch && key === lastViewKey &&
934
+ current && current.id === proj.id && !$wsKnowledge.hidden;
935
+
936
+ const url = kbRawUrl(proj.id, row.sourceId);
937
+ const ac = new AbortController();
938
+ kbTextAbort = ac;
939
+
940
+ let head;
941
+ try {
942
+ head = await fetch(url, { method: 'HEAD', signal: ac.signal, cache: 'no-store' });
943
+ } catch (err) {
944
+ if (err && err.name === 'AbortError') return; // superseded — never paint
945
+ if (alive()) kbPaintError(row, 'Lost the connection while loading it.');
946
+ return;
947
+ }
948
+ if (!alive()) return;
949
+
950
+ if (head.status === 404) { await kbHandleMissing(proj, row, alive); return; }
951
+ if (!head.ok) {
952
+ kbPaintError(row, head.status === 402
953
+ ? 'Your session needs refreshing — sign in again and retry.'
954
+ : 'The server hit an error trying to read it.');
955
+ return;
956
+ }
957
+
958
+ if (row.mime === 'application/pdf') kbPaintPdf(row, url);
959
+ else if (row.mime === 'image/png' || row.mime === 'image/jpeg') kbPaintImage(row, url, alive);
960
+ else kbPaintText(row, url, ac, alive);
961
+ }
962
+
963
+ /** Accept a freshly-read /status as the current truth. EVERY writer of `knowledgeState` goes through
964
+ * here, because committing state also decides whether the poll runs: a caller that claims the render
965
+ * epoch can supersede the very render that would have discovered a newly queued organize, and
966
+ * polling would then never start. */
967
+ function kbCommitState(st) {
968
+ knowledgeState = st;
969
+ paintKnowledge(st);
970
+ if (kbPending(st)) startKnowledgePoll(); else stopKnowledgePoll();
971
+ }
972
+
973
+ /** A 404 means EITHER the bytes are gone OR the row itself was deleted server-side. The client can't
974
+ * tell from cached state — the preview always started from a manifest that contained the row, and
975
+ * polling is off outside an organize — so re-read /status before choosing which story to tell. */
976
+ async function kbHandleMissing(proj, row, alive) {
977
+ // Claim the newest /status read: this refresh writes knowledgeState, so it must not be overwritten
978
+ // by an older in-flight renderKnowledge(), nor overwrite a newer one.
979
+ const rEpoch = ++knowledgeRenderEpoch;
980
+ const stillOurs = () => alive() && rEpoch === knowledgeRenderEpoch;
981
+ let st;
982
+ try { st = await loadKnowledgeState(proj); }
983
+ catch {
984
+ // The epoch guard belongs here too: a superseded refresh that FAILS must not paint its error
985
+ // over the newer render that succeeded.
986
+ if (stillOurs()) kbPaintError(row, 'Couldn’t check whether this reference still exists.');
987
+ return;
988
+ }
989
+ if (!stillOurs()) return;
990
+
991
+ const fresh = st.sources.find((s) => s.sourceId === row.sourceId);
992
+ if (!fresh) {
993
+ // The row is gone. Repaint the column too — merely closing the viewer would leave it listed,
994
+ // because nothing else is polling.
995
+ setViewer({ mode: 'graph', sourceId: null });
996
+ kbCommitState(st);
997
+ showToast('That reference was removed', 'warn');
998
+ return;
999
+ }
1000
+
1001
+ if (fresh.blobSha256 !== row.blobSha256) {
1002
+ // The bytes were replaced while we were asking. Don't strand a "missing" pane over a row that
1003
+ // now has content: the changed key makes kbCommitState's repaint reload it.
1004
+ kbCommitState(st);
1005
+ return;
1006
+ }
1007
+ kbCommitState(st); // the column may have moved on (states, revision, pending)
1008
+ kbPaintNoPreview(fresh, fresh.kind === 'file' ? 'missing' : 'nofile');
1009
+ }
1010
+
1011
+ function kbPaintPdf(row, url) {
1012
+ const name = row.filename || 'untitled';
1013
+ // The iframe `title` is the ONE native title= the codebase allows (it is the accessible name);
1014
+ // verify-no-title.mjs only exempts it when `<iframe` and `title=` sit on the SAME source line.
1015
+ kbPaintView(row,
1016
+ `<iframe class="kb-view-pdf" src="${escapeAttr(url)}" title="${escapeAttr(name)}"></iframe>`);
1017
+ }
1018
+
1019
+ /** A 200 does NOT imply a decodable image: sniffMime matches a 3-byte JPEG (FF D8 FF) and the upload
1020
+ * path rejects only zero-length files, so a truncated image stores and HEADs fine. */
1021
+ function kbPaintImage(row, url, alive) {
1022
+ kbPaintView(row, '<div class="kb-view-img-wrap"><img class="kb-view-img" alt=""></div>');
1023
+ const img = kbViewHost() && kbViewHost().querySelector('.kb-view-img');
1024
+ if (!img) return;
1025
+ img.alt = row.filename || 'untitled'; // property, not innerHTML — no escaping needed
1026
+ img.onerror = () => { if (alive()) kbPaintNoPreview(row, 'decode'); };
1027
+ img.src = url;
1028
+ }
1029
+
1030
+ /** Text is read as a stream and STOPPED at 256 KB. The upload cap is 100 MB per file, so an uncapped
1031
+ * <pre> would hang the tab; cancelling the reader also stops the server-side read. The bytes go in
1032
+ * with textContent — never innerHTML, never markdown, never a parsed CSV table. */
1033
+ async function kbPaintText(row, url, ac, alive) {
1034
+ let res;
1035
+ try { res = await fetch(url, { signal: ac.signal, cache: 'no-store' }); }
1036
+ catch (err) {
1037
+ if (err && err.name === 'AbortError') return;
1038
+ if (alive()) kbPaintError(row, 'Lost the connection while loading it.');
1039
+ return;
1040
+ }
1041
+ if (!alive()) return;
1042
+ if (!res.ok) { kbPaintError(row, 'The server hit an error trying to read it.'); return; }
1043
+
1044
+ const chunks = [];
1045
+ let total = 0;
1046
+ let truncated = false;
1047
+ try {
1048
+ const reader = res.body.getReader();
1049
+ for (;;) {
1050
+ const { done, value } = await reader.read();
1051
+ if (done) break;
1052
+ chunks.push(value);
1053
+ total += value.length;
1054
+ if (total >= KB_TEXT_CAP) { truncated = true; await reader.cancel(); break; }
1055
+ }
1056
+ } catch (err) {
1057
+ if (err && err.name === 'AbortError') return;
1058
+ if (alive()) kbPaintError(row, 'Lost the connection while reading it.');
1059
+ return;
1060
+ }
1061
+ if (!alive()) return;
1062
+
1063
+ const flat = new Uint8Array(Math.min(total, KB_TEXT_CAP));
1064
+ let at = 0;
1065
+ for (const c of chunks) {
1066
+ if (at >= flat.length) break;
1067
+ flat.set(c.subarray(0, Math.min(c.length, flat.length - at)), at);
1068
+ at += c.length;
1069
+ }
1070
+ const text = new TextDecoder('utf-8').decode(flat);
1071
+
1072
+ // The notice is a SIBLING of the <pre>, never appended into it: the <pre> holds the user's literal
1073
+ // bytes and nothing we invented. Byte total comes from the manifest row, not Content-Length.
1074
+ const notice = truncated
1075
+ ? `<div class="kb-view-note">Showing the first ${escapeHtml(kbBytes(KB_TEXT_CAP))} of ${escapeHtml(kbBytes(row.bytes))}.</div>`
1076
+ : '';
1077
+ kbPaintView(row, `<pre class="kb-view-pre"></pre>${notice}`);
1078
+ const pre = kbViewHost() && kbViewHost().querySelector('.kb-view-pre');
1079
+ if (pre) pre.textContent = text; // THE escaping guarantee — `<img src=x onerror=…>` stays literal
1080
+ }
1081
+
1082
+ function kbColumn(st) {
1083
+ const n = st.sources.length;
1084
+ const body = n
1085
+ ? st.sources.map(kbSourceRow).join('')
1086
+ : '<div class="kb-empty">No references yet — drop files above, or ask your terminal AI to add them.</div>';
1087
+ return '<section class="kb-col">' +
1088
+ `<div class="kb-head"><span>References</span><span class="h-end">${n ? `${n} source${n === 1 ? '' : 's'}` : ''}</span></div>` +
1089
+ '<div class="kb-refs-body">' +
1090
+ '<button type="button" class="kb-drop" id="kb-drop" data-tip="Drop files here, or click to pick them">' +
1091
+ '<span class="di" aria-hidden="true">⤓</span><span class="dt">Drop references here</span>' +
1092
+ '<span class="ds">PDF · images · text · CSV</span>' +
1093
+ '</button>' + body +
1094
+ '</div>' + kbFoot(st) + '</section>';
1095
+ }
1096
+
1097
+ // Never repaint over an open remove-confirm: it is anchored to a row that a repaint destroys.
1098
+ // Checked BOTH before the fetch (cheap early-out) and again after it — the user can open the
1099
+ // confirm while a poll tick's fetch is still in flight, and the post-await paint would then yank
1100
+ // the popover out from under them. Bailing is safe: knowledgeState is left untouched, the running
1101
+ // poll keeps ticking, and the next tick after the confirm closes paints fresh state.
1102
+ const kbConfirmOpen = () => !!$wsKnowledge.querySelector('.hist-confirm');
1103
+
1104
+ /** The split is built ONCE; the refs column and the viewer then repaint independently. A wholesale
1105
+ * innerHTML would destroy an open PDF <iframe> on every 3 s poll tick. Recreating the shell must
1106
+ * drop both caches — they describe DOM nodes that no longer exist. */
1107
+ function kbEnsureShell() {
1108
+ if ($wsKnowledge.querySelector('.kb-split')) return;
1109
+ $wsKnowledge.innerHTML = '<div class="kb-split"><div class="kb-refs-host"></div><div class="kb-view-host"></div></div>';
1110
+ lastRefsHtml = null;
1111
+ lastViewKey = null;
1112
+ }
1113
+
1114
+ /** Identity of what the viewer host is showing. `blobSha256` is in the key because a hand-edited
1115
+ * manifest (and, later, Stage D) can swap a row's bytes without changing its sourceId. */
1116
+ function kbViewKey(st) {
1117
+ const row = viewer.mode === 'file' ? st.sources.find((s) => s.sourceId === viewer.sourceId) : null;
1118
+ const gen = viewer.mode === 'graph' && st.currentGeneration ? st.currentGeneration.generationId : '';
1119
+ return [current && current.id, viewer.mode, viewer.sourceId || '', row ? row.blobSha256 : '', gen].join('|');
1120
+ }
1121
+
1122
+ function paintKnowledge(st) {
1123
+ // The previewed source may have been removed under us (by this tab or the terminal AI).
1124
+ if (viewer.mode === 'file' && !st.sources.some((s) => s.sourceId === viewer.sourceId)) {
1125
+ setViewer({ mode: 'graph', sourceId: null });
1126
+ }
1127
+ kbEnsureShell();
1128
+ const refsHost = $wsKnowledge.querySelector('.kb-refs-host');
1129
+ const viewHost = kbViewHost();
1130
+
1131
+ // Repaint the column iff its RENDERED OUTPUT changed. Comparing the HTML is exact by construction:
1132
+ // a signature enumerating inputs would rot as kbColumn grows, and would miss the footer's
1133
+ // time-dependent parts (pending age, the 10-minute stale flip, publishedAt, lastLintSummary).
1134
+ const html = kbColumn(st);
1135
+ if (html !== lastRefsHtml) {
1136
+ const oldBody = refsHost.querySelector('.kb-refs-body');
1137
+ const scrollTop = oldBody ? oldBody.scrollTop : 0;
1138
+ refsHost.innerHTML = html;
1139
+ lastRefsHtml = html;
1140
+ const newBody = refsHost.querySelector('.kb-refs-body');
1141
+ if (newBody) newBody.scrollTop = scrollTop;
1142
+ // Selecting a row changes its HTML (it gains aria-current), so the repaint destroys the very
1143
+ // button the user just clicked. Put focus back — but only when a handler asked for it, never on
1144
+ // a poll tick, which must not steal focus.
1145
+ if (kbFocusSourceId) {
1146
+ const btn = refsHost.querySelector(`[data-kb-open="${CSS.escape(kbFocusSourceId)}"]`);
1147
+ if (btn) btn.focus();
1148
+ kbFocusSourceId = null;
1149
+ }
1150
+ }
1151
+
1152
+ const key = kbViewKey(st);
1153
+ if (key !== lastViewKey) {
1154
+ // The key can change WITHOUT setViewer() — e.g. a poll swaps a row's blobSha256 under an open
1155
+ // preview. Abort and bump the epoch here too, or the superseded download keeps streaming (its
1156
+ // paint would be dropped by the key guard, but the bytes would still be pulled).
1157
+ kbAbortPreview();
1158
+ lastViewKey = key;
1159
+ if (viewer.mode === 'file') {
1160
+ const row = st.sources.find((s) => s.sourceId === viewer.sourceId);
1161
+ if (row) {
1162
+ if (viewHost) viewHost.innerHTML = kbViewShell(row, kbViewLoading(row));
1163
+ kbLoadPreview(current, row);
1164
+ }
1165
+ } else if (viewHost) {
1166
+ viewHost.innerHTML = kbPlaceholder(st);
1167
+ }
1168
+ }
1169
+ }
1170
+
1171
+ /** Paint a bare References column (loading / load-failed) into the shell without touching the viewer:
1172
+ * a failed /status poll is no reason to tear down a file the user is reading. Nulls the cache so the
1173
+ * next successful render always repaints. */
1174
+ function kbPaintRefsMessage(inner) {
1175
+ kbEnsureShell();
1176
+ const refsHost = $wsKnowledge.querySelector('.kb-refs-host');
1177
+ refsHost.innerHTML = '<section class="kb-col"><div class="kb-head"><span>References</span></div>' +
1178
+ `<div class="kb-refs-body">${inner}</div></section>`;
1179
+ lastRefsHtml = null;
1180
+ const host = kbViewHost();
1181
+ if (host && viewer.mode === 'graph' && !host.innerHTML) host.innerHTML = kbPlaceholder(null);
1182
+ }
1183
+
1184
+ async function renderKnowledge() {
1185
+ const proj = current;
1186
+ if (!proj || kbConfirmOpen()) return;
1187
+ // Poll ticks and verb-triggered loads race; an older /status response must never repaint over a
1188
+ // newer one.
1189
+ const epoch = ++knowledgeRenderEpoch;
1190
+ const stale = () => epoch !== knowledgeRenderEpoch || !current || current.id !== proj.id ||
1191
+ $wsKnowledge.hidden || kbConfirmOpen();
1192
+
1193
+ if (!knowledgeState) kbPaintRefsMessage('<div class="kb-empty">Loading…</div>');
1194
+
1195
+ let st;
1196
+ try { st = await loadKnowledgeState(proj); }
1197
+ catch (err) {
1198
+ if (stale()) return;
1199
+ stopKnowledgePoll();
1200
+ kbPaintRefsMessage(
1201
+ `<div class="kb-empty">Couldn’t load the knowledge base: ${escapeHtml(String((err && err.message) || err))}</div>`);
1202
+ return;
1203
+ }
1204
+ if (stale()) return; // switched project/step — or opened a confirm — during the fetch
1205
+ kbCommitState(st);
1206
+ }
1207
+
1208
+ // ── Knowledge verbs (each captures `proj` — the user may switch projects mid-await) ──
1209
+ async function kbUpload(fileList) {
1210
+ const proj = current;
1211
+ const files = Array.from(fileList || []);
1212
+ if (!proj || !files.length) return;
1213
+ // Preflight the SERVER's caps before allocating base64 data URLs in the browser.
1214
+ if (files.length > KB_MAX_FILES) { showToast(`Too many files at once (max ${KB_MAX_FILES})`, 'warn'); return; }
1215
+ const big = files.find((f) => f.size > KB_MAX_FILE_BYTES);
1216
+ if (big) { showToast(`“${big.name}” is too large (max ${KB_MB(KB_MAX_FILE_BYTES)} MB)`, 'warn'); return; }
1217
+ if (files.reduce((n, f) => n + f.size, 0) > KB_MAX_TOTAL_BYTES) {
1218
+ showToast(`That drop is too large (total max ${KB_MB(KB_MAX_TOTAL_BYTES)} MB)`, 'warn'); return;
1219
+ }
1220
+ let uploads;
1221
+ try { uploads = await Promise.all(files.map(readFileAsSnapshot)); }
1222
+ catch { showToast('Could not read the selected files', 'warn'); return; }
1223
+ if (current !== proj) return; // switched projects mid-read — never upload against the wrong KB
1224
+ try {
1225
+ const res = await api(kbUrl(proj.id, '/sources'), { method: 'POST', body: JSON.stringify({ files: uploads }) });
1226
+ if (current !== proj) return;
1227
+ const n = (res.sources || []).length;
1228
+ showToast(`Added ${n} reference${n === 1 ? '' : 's'}`, 'ok');
1229
+ track('kb_sources_added', { app: proj.app, n });
1230
+ } catch (err) {
1231
+ // The server rejects archives (xlsx/docx are zips), oversize and unknown types — say so, never swallow.
1232
+ showToast('Couldn’t add: ' + ((err && err.message) || err), 'warn');
1233
+ }
1234
+ if (current === proj) renderKnowledge();
1235
+ }
1236
+
1237
+ async function kbToggle(sourceId, next) {
1238
+ const proj = current;
1239
+ if (!proj) return;
1240
+ try { await api(kbUrl(proj.id, `/sources/${encodeURIComponent(sourceId)}`), { method: 'PATCH', body: JSON.stringify({ useAsKb: next }) }); }
1241
+ catch (err) { showToast('Couldn’t update: ' + ((err && err.message) || err), 'warn'); }
1242
+ if (current === proj) renderKnowledge(); // re-render reconciles the optimistic flip either way
1243
+ }
1244
+
1245
+ async function kbRemove(sourceId) {
1246
+ const proj = current;
1247
+ if (!proj) return;
1248
+ kbCloseConfirm();
1249
+ try {
1250
+ await api(kbUrl(proj.id, `/sources/${encodeURIComponent(sourceId)}`), { method: 'DELETE' });
1251
+ showToast('Reference removed', 'ok');
1252
+ } catch (err) { showToast('Couldn’t remove: ' + ((err && err.message) || err), 'warn'); }
1253
+ if (current === proj) renderKnowledge();
1254
+ }
1255
+
1256
+ async function kbOrganize() {
1257
+ const proj = current;
1258
+ if (!proj) return;
1259
+ try {
1260
+ await api(kbUrl(proj.id, '/organize'), { method: 'POST', body: '{}' });
1261
+ // Refresh the footer Requests counter in THIS tab — there is no server `request-added`
1262
+ // broadcast, so nothing else would move the badge.
1263
+ if (bridge.loadRequests) await bridge.loadRequests();
1264
+ showToast('Organize queued for your terminal AI', 'ok');
1265
+ track('kb_organize_queued', { app: proj.app });
1266
+ } catch (err) { showToast('Couldn’t queue organize: ' + ((err && err.message) || err), 'warn'); }
1267
+ if (current === proj) renderKnowledge();
1268
+ }
1269
+
1270
+ // Remove confirm — the themed anchored popover (.hist-confirm), NEVER a native confirm().
1271
+ function kbCloseConfirm() {
1272
+ const pop = $wsKnowledge.querySelector('.hist-confirm');
1273
+ if (pop) pop.remove();
1274
+ document.removeEventListener('mousedown', kbOnDocDown, true);
1275
+ }
1276
+ function kbOnDocDown(e) {
1277
+ if (!e.target.closest('.hist-confirm') && !e.target.closest('[data-kb-remove]')) kbCloseConfirm();
1278
+ }
1279
+ // Anchored to the SCROLL container (.kb-refs-body, position:relative) — .kb-col is overflow:hidden
1280
+ // and would clip the popover. Same anchoring as .ws-history's rollback confirm.
1281
+ function kbShowRemoveConfirm(btn, sourceId, name) {
1282
+ kbCloseConfirm();
1283
+ const box = btn.closest('.kb-refs-body');
1284
+ if (!box) return;
1285
+ const pop = document.createElement('div');
1286
+ pop.className = 'hist-confirm';
1287
+ // Honest about timing: removing a source does NOT retroactively purge notes already compiled
1288
+ // from it — only the next Organize rebuilds the wiki without it.
1289
+ pop.innerHTML =
1290
+ `<div class="hc-title">Remove “${escapeHtml(name)}”?</div>` +
1291
+ '<div class="hc-body">It won’t be included in future Organize runs. Notes already compiled from it ' +
1292
+ 'stay in the knowledge base until you Organize again.</div>' +
1293
+ '<div class="hc-act"><button type="button" class="hc-cancel">Cancel</button>' +
1294
+ `<button type="button" class="hc-go danger" data-kb-remove-go="${escapeAttr(sourceId)}">✕ Remove</button></div>`;
1295
+ box.appendChild(pop);
1296
+ const cr = box.getBoundingClientRect();
1297
+ const br = btn.getBoundingClientRect();
1298
+ pop.style.top = `${br.bottom - cr.top + box.scrollTop + 6}px`;
1299
+ pop.style.left = `${Math.max(8, Math.min(br.right - cr.left - pop.offsetWidth, box.clientWidth - pop.offsetWidth - 8))}px`;
1300
+ document.addEventListener('mousedown', kbOnDocDown, true);
1301
+ }
1302
+
1303
+ // One delegated listener for the whole pane — the column is re-rendered wholesale on every state
1304
+ // change, so per-render wiring would leak handlers.
1305
+ $wsKnowledge.addEventListener('click', (e) => {
1306
+ const go = e.target.closest('[data-kb-remove-go]');
1307
+ if (go) { kbRemove(go.dataset.kbRemoveGo); return; }
1308
+ if (e.target.closest('.hc-cancel')) { kbCloseConfirm(); return; }
1309
+ const rm = e.target.closest('[data-kb-remove]');
1310
+ if (rm) {
1311
+ const row = rm.closest('.kb-src');
1312
+ const nameEl = row && row.querySelector('.kb-fname');
1313
+ kbShowRemoveConfirm(rm, row.dataset.sourceId, (nameEl && nameEl.textContent) || 'this reference');
1314
+ return;
1315
+ }
1316
+ const tog = e.target.closest('[data-kb-toggle]');
1317
+ if (tog) {
1318
+ const row = tog.closest('.kb-src');
1319
+ const next = tog.getAttribute('aria-checked') !== 'true';
1320
+ tog.setAttribute('aria-checked', String(next)); // optimistic — reconciled by the re-render
1321
+ row.classList.toggle('off', !next);
1322
+ // The DOM now disagrees with the model. If the PATCH fails, the re-rendered HTML would EQUAL the
1323
+ // cache and the repaint would be skipped, stranding the wrong optimistic state on screen.
1324
+ kbInvalidateRefs();
1325
+ kbToggle(row.dataset.sourceId, next);
1326
+ return;
1327
+ }
1328
+ // Preview a source: the filename button. Re-clicking the open one is a no-op, not a reload.
1329
+ const open = e.target.closest('[data-kb-open]');
1330
+ if (open) {
1331
+ const sourceId = open.dataset.kbOpen;
1332
+ if (viewer.mode === 'file' && viewer.sourceId === sourceId) return;
1333
+ setViewer({ mode: 'file', sourceId });
1334
+ kbFocusSourceId = sourceId; // the repaint below destroys this button; put focus back
1335
+ if (knowledgeState) paintKnowledge(knowledgeState);
1336
+ return;
1337
+ }
1338
+ if (e.target.closest('[data-kb-close]')) {
1339
+ const wasOpen = viewer.sourceId;
1340
+ setViewer({ mode: 'graph', sourceId: null });
1341
+ kbFocusSourceId = wasOpen; // return focus to the filename the preview came from
1342
+ if (knowledgeState) paintKnowledge(knowledgeState);
1343
+ return;
1344
+ }
1345
+ if (e.target.closest('[data-kb-retry]')) {
1346
+ // setViewer emptied the host and nulled lastViewKey, so the identical key repaints.
1347
+ const sourceId = viewer.sourceId;
1348
+ if (sourceId) { setViewer({ mode: 'file', sourceId }); if (knowledgeState) paintKnowledge(knowledgeState); }
1349
+ return;
1350
+ }
1351
+ // "Remove reference" inside the viewer. kbShowRemoveConfirm anchors its popover to .kb-refs-body,
1352
+ // which this button is NOT inside — so delegate to the row's own ✕ rather than duplicate the
1353
+ // popover or let it silently fail to anchor.
1354
+ const rmSrc = e.target.closest('[data-kb-remove-src]');
1355
+ if (rmSrc) {
1356
+ const rowEl = $wsKnowledge.querySelector(`.kb-src[data-source-id="${CSS.escape(rmSrc.dataset.kbRemoveSrc)}"]`);
1357
+ const x = rowEl && rowEl.querySelector('[data-kb-remove]');
1358
+ if (x) { rowEl.scrollIntoView({ block: 'nearest' }); x.click(); }
1359
+ return;
1360
+ }
1361
+ const org = e.target.closest('#kb-organize');
1362
+ if (org) { if (org.getAttribute('aria-disabled') !== 'true') kbOrganize(); return; } // aria-disabled still receives clicks
1363
+ if (e.target.closest('#kb-drop')) $wsKnowledgeFile.click();
1364
+ });
1365
+ $wsKnowledgeFile.addEventListener('change', () => {
1366
+ kbUpload($wsKnowledgeFile.files);
1367
+ $wsKnowledgeFile.value = ''; // let the same file be picked twice in a row
1368
+ });
1369
+ // Drag/drop is bound to the WHOLE pane, not just the drop zone: a file dropped a few pixels wide of
1370
+ // the target would otherwise be opened by the browser, navigating away from the app.
1371
+ // `.drag-over` is another imperative refs-DOM mutation the HTML-equality guard cannot see.
1372
+ const kbClearDrag = () => {
1373
+ const cur = $wsKnowledge.querySelector('.kb-drop.drag-over');
1374
+ if (cur) { cur.classList.remove('drag-over'); kbInvalidateRefs(); }
1375
+ };
1376
+ $wsKnowledge.addEventListener('dragover', (e) => {
1377
+ e.preventDefault();
1378
+ const dz = e.target.closest('#kb-drop');
1379
+ const cur = $wsKnowledge.querySelector('.kb-drop.drag-over');
1380
+ if (cur && cur !== dz) cur.classList.remove('drag-over');
1381
+ if (dz && !dz.classList.contains('drag-over')) { dz.classList.add('drag-over'); kbInvalidateRefs(); }
1382
+ });
1383
+ $wsKnowledge.addEventListener('dragleave', (e) => { if (!$wsKnowledge.contains(e.relatedTarget)) kbClearDrag(); });
1384
+ $wsKnowledge.addEventListener('drop', (e) => {
1385
+ e.preventDefault();
1386
+ kbClearDrag();
1387
+ if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length) kbUpload(e.dataTransfer.files);
1388
+ });
1389
+
288
1390
  // ── Exports step ──────────────────────────────────────────────────────────────
289
1391
  const hhmm = (iso) => {
290
1392
  const d = new Date(iso);
@@ -300,6 +1402,7 @@
300
1402
  if (kind === 'bom-csv') return `${base}/export-bom/csv${qs}`;
301
1403
  if (kind === 'bom-xlsx') return `${base}/export-bom/xlsx${qs}`;
302
1404
  if (kind === 'ifc') return `${base}/export-ifc${qs}`;
1405
+ if (kind === 'svg') return `${base}/export-svg${qs}`;
303
1406
  return `${base}/export-tekla${qs}`; // tekla
304
1407
  }
305
1408
 
@@ -326,7 +1429,7 @@
326
1429
  }
327
1430
  const exported = approved && c.file && exportState && exportState[c.kind] && exportState[c.kind].exportedAt;
328
1431
  const label = exported ? 'Re-export' : c.verb;
329
- const dis = approved ? '' : ' disabled data-tip="Approve the model first"';
1432
+ const dis = approved ? '' : ' disabled data-tip="Approve this version first"';
330
1433
  return `<div class="ecard">` +
331
1434
  `<div class="e-top"><div class="e-ico">${escapeHtml(c.ico)}</div>` +
332
1435
  `<div><div class="e-name">${escapeHtml(c.name)}</div><div class="e-fmt">${escapeHtml(c.fmt)}</div></div></div>` +
@@ -357,25 +1460,29 @@
357
1460
  // The user may have switched project/step during the await — don't paint stale.
358
1461
  if (!current || current.id !== id || $wsExports.hidden) return;
359
1462
  exportState = state;
1463
+ syncWorkspaceGuide(); // fresh approve/export state → tick the Export (and re-sync Approve) guide rows
360
1464
  const approved = !!approvedAt;
361
1465
  let html = '';
362
1466
  if (!approved) {
363
1467
  html += `<div class="ws-exports-gate">Exports go out after sign-off — ` +
364
- `<button type="button" id="ws-exports-approve">Approve the model</button> to enable them.</div>`;
1468
+ `<button type="button" id="ws-exports-approve">Approve this version</button> to enable them.</div>`;
365
1469
  }
366
1470
  html += `<div class="exports-note"><b>Export at any stage</b> — polishing is optional. ` +
367
1471
  `Each writes to this project’s <code>exports</code> folder.</div>`;
368
- html += '<div class="export-grid">' + EXPORT_CARDS.map((c) => cardHtml(c, approved)).join('') + '</div>';
1472
+ const cards = (wsApp() && wsApp().exports) || [];
1473
+ html += '<div class="export-grid">' + cards.map((c) => cardHtml(c, approved)).join('') + '</div>';
369
1474
  $wsExports.innerHTML = html;
370
1475
  }
371
1476
 
372
1477
  async function doExport(kind) {
373
1478
  if (!current) return;
1479
+ const app = current.app; // capture — the user may switch projects during the await
374
1480
  const btn = $wsExports.querySelector(`[data-export="${kind}"]`);
375
1481
  const prev = btn ? btn.textContent : '';
376
1482
  if (btn) { btn.disabled = true; btn.textContent = kind === 'tekla' ? 'Baking…' : 'Exporting…'; }
377
1483
  try {
378
1484
  const res = await api(exportUrl(kind), { method: 'POST' });
1485
+ track('workspace_export', { app, kind }); // a successful export/bake (e.g. { app:'vectorize', kind:'svg' })
379
1486
  if (kind === 'tekla') {
380
1487
  const dropped = Array.isArray(res.skipped) ? res.skipped.length : 0;
381
1488
  showToast((res.message || 'Baked into the Tekla model.') + (dropped ? ` · ${dropped} RFI member(s) skipped` : ''), 'ok');
@@ -422,6 +1529,7 @@
422
1529
  let revBaseVersion = 0; // the ledger head captured at attach — success = the head advances past it
423
1530
  let revCardReq = null;
424
1531
  let revisionPoll = null;
1532
+ const isInitialRevisionRead = (req) => !req || !req.baseVersion || req.baseVersion <= 0;
425
1533
  function stopRevisionPoll() { if (revisionPoll) { clearInterval(revisionPoll); revisionPoll = null; } }
426
1534
  function startRevisionPoll() {
427
1535
  stopRevisionPoll();
@@ -446,6 +1554,7 @@
446
1554
  async function attachRevision(files) {
447
1555
  const proj = current; // capture — the user may switch projects during the async file reads / POST
448
1556
  if (!proj || !files.length) return;
1557
+ const returnFocus = document.activeElement;
449
1558
  let snapshots;
450
1559
  try { snapshots = await Promise.all(files.map(readFileAsSnapshot)); }
451
1560
  catch { showToast('Could not read the selected files', 'warn'); return; }
@@ -458,30 +1567,32 @@
458
1567
  } catch (err) { showToast('Attach failed: ' + ((err && err.message) || err), 'warn'); return; }
459
1568
  const req = res && res.request;
460
1569
  // Copy the paste-ready instruction so the user can hand it to their terminal AI (best-effort).
1570
+ let copied = false;
461
1571
  if (req && bridge.markedInstruction && bridge.copyToClipboard) {
462
- try { await bridge.copyToClipboard(bridge.markedInstruction(req)); } catch { /* clipboard blocked */ }
1572
+ try { copied = await bridge.copyToClipboard(bridge.markedInstruction(req)); } catch { copied = false; }
463
1573
  }
464
1574
  if (bridge.loadRequests) bridge.loadRequests().catch(() => {}); // refresh the footer Requests popover
465
1575
  if (current !== proj) return; // switched away while posting — don't drive the wrong project's card/poll
466
- showToast(`Revised set queued — ${files.length} file${files.length > 1 ? 's' : ''} for your terminal AI`, 'ok');
467
1576
  revBaseVersion = (req && typeof req.baseVersion === 'number') ? req.baseVersion : 0;
1577
+ showToast(`${revBaseVersion <= 0 ? 'Initial' : 'Revised'} set queued — ${files.length} file${files.length > 1 ? 's' : ''} for your terminal AI`, 'ok');
468
1578
  lastRevState = 'pending';
469
1579
  startRevisionPoll();
470
1580
  renderRevisionCard();
1581
+ if (req && bridge.showRequestQueuedModal) {
1582
+ bridge.showRequestQueuedModal(req, { copied, fileCount: files.length, returnFocus });
1583
+ }
471
1584
  }
472
1585
 
473
- document.getElementById('ws-attach-revision').addEventListener('click', () => $revisionFile.click());
474
- $revisionFile.addEventListener('change', () => {
475
- const files = [...($revisionFile.files || [])];
476
- $revisionFile.value = ''; // clear so re-picking the same file re-fires change
477
- attachRevision(files);
1586
+ document.getElementById('ws-attach-revision').addEventListener('click', async () => {
1587
+ const files = await pickDrawingFiles($revisionFile);
1588
+ if (files.length) attachRevision(files);
478
1589
  });
479
1590
 
480
1591
  function buildPendingCard(req) {
481
1592
  const n = (req.sourceRefs && req.sourceRefs.length) || (req.snapshots && req.snapshots.length) || 1;
482
1593
  const spin = revEl('span', 'wrc-spin'); spin.setAttribute('aria-hidden', 'true');
483
1594
  const txt = revEl('span', 'wrc-text');
484
- txt.appendChild(revEl('b', null, 'Reading the revised set…'));
1595
+ txt.appendChild(revEl('b', null, `Reading the ${isInitialRevisionRead(req) ? 'initial' : 'revised'} set…`));
485
1596
  txt.appendChild(document.createTextNode(` ${n} file${n > 1 ? 's' : ''} queued for your terminal AI — paste the copied instruction there, or say “apply my floless request”.`));
486
1597
  const copy = revEl('button', 'btn-mini', '⧉ Copy');
487
1598
  copy.type = 'button'; copy.dataset.revcopy = ''; copy.setAttribute('data-tip', 'Copy the instruction again');
@@ -560,11 +1671,11 @@
560
1671
  author === 'You'
561
1672
  ? '<span class="avatar you">YOU</span>'
562
1673
  : `<span class="avatar ai">${escapeHtml((author || '?').replace(/[^A-Za-z0-9]/g, '').slice(0, 2).toUpperCase() || 'AI')}</span>`;
563
- const gateBadge = (gate, kind) => {
1674
+ const gateBadge = (gate, kind, n) => {
564
1675
  if (gate === 'model')
565
- return '<span class="gate-badge model" data-tip="Model gate — the geometry was signed off">Model</span>';
1676
+ return '<span class="gate-badge model" data-tip="Sign-off gate — this version was approved">Model</span>';
566
1677
  if (kind === 'revision-read')
567
- return '<span class="gate-badge ai-read" data-tip="AI read — the terminal AI composed this version from a revised drawing set; Approve to sign it off">AI read</span>';
1678
+ return `<span class="gate-badge ai-read" data-tip="AI read — the terminal AI composed this version from ${Number(n) <= 1 ? 'the initial' : 'a revised'} drawing set; Approve to sign it off">AI read</span>`;
568
1679
  return '<span class="gate-badge" data-tip="Unsigned — a working-tree restore, not a sign-off">unsigned</span>';
569
1680
  };
570
1681
 
@@ -575,9 +1686,10 @@
575
1686
  const action = v.current
576
1687
  ? ''
577
1688
  : `<button type="button" class="btn-mini" data-rollback="${escapeAttr(String(v.n))}" data-tip="Restore this version as a new version">↺ Rollback</button>`;
578
- // "What changed" disclosure — only for a version that HAS a predecessor (n>1). v1 is the baseline,
579
- // so it gets NO toggle at all (an ABSENT control, never a disabled one).
580
- const canDiff = Number(v.n) > 1;
1689
+ // "What changed" disclosure — only when the app HAS a semantic diff (steel; wsApp().diff) AND the
1690
+ // version has a predecessor (n>1). v1 is the baseline, and a no-diff app (vectorize) gets NO toggle
1691
+ // on ANY row — an ABSENT control, never a disabled one (spec §4.4, mirroring the v1-baseline branch).
1692
+ const canDiff = !!(wsApp() && wsApp().diff) && Number(v.n) > 1;
581
1693
  const toggle = canDiff
582
1694
  ? `<button type="button" class="hd-toggle" data-diff="${escapeAttr(String(v.n))}" aria-expanded="false" data-tip="What changed vs the previous version"><span class="hd-caret">▸</span></button>`
583
1695
  : '';
@@ -586,7 +1698,7 @@
586
1698
  `<td><span class="ver${v.current ? ' cur' : ''}">v${escapeHtml(String(v.n))}</span></td>` +
587
1699
  `<td class="htime">${escapeHtml(histWhen(v.ts))}</td>` +
588
1700
  `<td><span class="hby">${avatarFor(v.author)}${escapeHtml(v.author)}</span></td>` +
589
- `<td>${gateBadge(v.gate, v.kind)}</td>` +
1701
+ `<td>${gateBadge(v.gate, v.kind, v.n)}</td>` +
590
1702
  `<td class="change">${escapeHtml(v.message)}</td>` +
591
1703
  `<td>${action}</td></tr>`;
592
1704
  // The disclosure row is always emitted (hidden) so toggling is a pure show/hide + lazy fetch.
@@ -620,17 +1732,18 @@
620
1732
  if (!rows.length) {
621
1733
  // Empty = an inline-action banner (never a bare header row that reads as broken/loading).
622
1734
  $wsHistory.innerHTML =
623
- '<div class="hist-empty">No versions yet — <button type="button" id="hist-approve">Approve the model</button> ' +
1735
+ '<div class="hist-empty">No versions yet — <button type="button" id="hist-approve">Approve this version</button> ' +
624
1736
  'to create <b>v1</b> and start the ledger.</div>';
625
1737
  return;
626
1738
  }
627
1739
  // Working copy = the draft; when it isn't signed off (approvedAt cleared by an edit or a
628
1740
  // rollback) surface it honestly ABOVE the table (not as a fake row) and name the Exports lock.
629
1741
  const headKind = rows.length && rows[0].current ? rows[0].kind : undefined;
1742
+ const headIsInitialRead = headKind === 'revision-read' && Number(rows[0].n) <= 1;
630
1743
  const working = !approvedAt
631
1744
  ? (headKind === 'revision-read'
632
- ? '<div class="hist-working">● <b>The AI read a revised drawing set — review it before signing.</b> ' +
633
- 'Open <b>Model</b> to check the change, then <button type="button" id="hist-approve">Approve</button> to sign off. Exports stay locked until you do.</div>'
1745
+ ? `<div class="hist-working">● <b>The AI read ${headIsInitialRead ? 'the initial' : 'a revised'} drawing set — review it before signing.</b> ` +
1746
+ `Open <b>${escapeHtml(stepLabel('model'))}</b> to check the change, then <button type="button" id="hist-approve">Approve</button> to sign off. Exports stay locked until you do.</div>`
634
1747
  : '<div class="hist-working">● <b>Working copy isn’t signed off.</b> ' +
635
1748
  '<button type="button" id="hist-approve">Approve</button> to sign off this version. Exports stay locked until you do.</div>')
636
1749
  : '';
@@ -703,7 +1816,7 @@
703
1816
  { key: 'connections', label: 'Connections' },
704
1817
  ];
705
1818
  const diffBase = new Map(); // "<projectId>\0<n>" → chosen baseline (undefined = compare to the previous version)
706
- const baseKeyFor = (n) => (current && current.id ? current.id : '?') + '' + n; // project-scoped so a base pick can't bleed across projects sharing a version number
1819
+ const baseKeyFor = (n) => (current && current.id ? current.id : '?') + '\0' + n; // project-scoped so a base pick can't bleed across projects sharing a version number
707
1820
  const el = (tag, cls, text) => {
708
1821
  const n = document.createElement(tag);
709
1822
  if (cls) n.className = cls;
@@ -913,17 +2026,16 @@
913
2026
  if (dr) { const n = Number(dr.dataset.diffRetry); loadDiff(n, diffBase.get(baseKeyFor(n))); return; }
914
2027
  });
915
2028
 
916
- // ── project picker + lifecycle (full set lives HERE; ≡ carries nothing) ────
2029
+ // ── project card kebab menu (landing grid "⋯" — Rename/Duplicate/Archive on ONE
2030
+ // project; the header project picker below is a separate, richer combo mirroring
2031
+ // the workflow picker). ───────────────────────────────────────────────
917
2032
  let menuFor = null;
918
2033
  function menuItem(action, label) {
919
2034
  return `<button class="menu-item" data-act="${action}" role="menuitem"><span class="menu-label">${escapeHtml(label)}</span></button>`;
920
2035
  }
921
2036
  function openProjMenu(id, anchor) {
922
2037
  menuFor = id;
923
- const others = projects.filter((p) => p.id !== id);
924
- $projMenu.innerHTML =
925
- (others.length ? others.map((p) => `<button class="menu-item" data-goto="${escapeAttr(p.id)}" role="menuitem"><span class="menu-label">Open: ${escapeHtml(p.name)}</span></button>`).join('') + '<div class="menu-divider"></div>' : '') +
926
- menuItem('rename', 'Rename…') + menuItem('duplicate', 'Duplicate') +
2038
+ $projMenu.innerHTML = menuItem('rename', 'Rename…') + menuItem('duplicate', 'Duplicate') +
927
2039
  '<div class="menu-divider"></div>' + menuItem('archive', 'Archive');
928
2040
  const r = anchor.getBoundingClientRect();
929
2041
  $projMenu.style.left = Math.round(Math.max(8, Math.min(r.left, window.innerWidth - 260))) + 'px';
@@ -931,40 +2043,157 @@
931
2043
  $projMenu.hidden = false;
932
2044
  $projMenu.classList.add('show');
933
2045
  }
934
- document.getElementById('ws-proj-trigger').addEventListener('click', (e) => {
935
- if (!current) return;
936
- e.stopPropagation();
937
- if ($projMenu.hidden) openProjMenu(current.id, e.currentTarget); else closeProjMenu();
938
- });
939
2046
  document.addEventListener('click', (e) => {
940
2047
  if ($projMenu.hidden) return;
941
- if (!$projMenu.contains(e.target) && !e.target.closest('#ws-proj-trigger') && !e.target.closest('[data-kebab]')) closeProjMenu();
2048
+ if (!$projMenu.contains(e.target) && !e.target.closest('[data-kebab]')) closeProjMenu();
942
2049
  });
943
- $projMenu.addEventListener('click', async (e) => {
944
- const goto = e.target.closest('[data-goto]');
945
- if (goto) { closeProjMenu(); return openProject(goto.dataset.goto); }
2050
+ $projMenu.addEventListener('click', (e) => {
946
2051
  const act = e.target.closest('[data-act]');
947
2052
  if (!act || !menuFor) return;
948
2053
  closeProjMenu();
949
- const id = menuFor;
2054
+ doProjectAction(act.dataset.act, menuFor);
2055
+ });
2056
+
2057
+ // Shared rename/duplicate/archive — used by both the kebab menu (one project, from the
2058
+ // landing grid) and the header project-picker's inline row actions below (any project,
2059
+ // from anywhere). Never switches projects itself — the caller decides navigation.
2060
+ async function doProjectAction(action, id) {
950
2061
  const proj = projects.find((p) => p.id === id);
951
2062
  try {
952
- if (act.dataset.act === 'rename') {
2063
+ if (action === 'rename') {
953
2064
  const name = await promptName('Rename project', 'New name', proj ? proj.name : '');
954
2065
  if (!name) return;
955
2066
  const { project } = await api(`/api/projects/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify({ name }) });
956
2067
  if (current && current.id === id) { current = project; $projName.textContent = project.name; $crumbName.textContent = project.name; }
957
2068
  showToast('Renamed', 'ok');
958
- } else if (act.dataset.act === 'duplicate') {
2069
+ } else if (action === 'duplicate') {
959
2070
  const { project } = await api(`/api/projects/${encodeURIComponent(id)}/duplicate`, { method: 'POST', body: '{}' });
960
2071
  showToast(`Duplicated as "${project.name}"`, 'ok');
961
- } else if (act.dataset.act === 'archive') {
2072
+ } else if (action === 'archive') {
962
2073
  await api(`/api/projects/${encodeURIComponent(id)}/archive`, { method: 'POST', body: '{}' });
963
2074
  showToast('Archived — recoverable from ~/.floless/projects/.archive', 'ok');
964
2075
  if (current && current.id === id) { closeProject(); return; }
965
2076
  }
966
2077
  } catch (err) { showToast('Action failed: ' + (err && err.message || err), 'warn'); }
967
2078
  loadProjects();
2079
+ }
2080
+
2081
+ // ── header project picker ── mirrors #wf-combo/#wf-popover exactly (same DOM shape, same
2082
+ // CSS classes): search + flat list of ALL projects, each row showing name + app ·
2083
+ // last-touched, with inline Rename/Duplicate/Archive icons. Clicking a row opens/switches
2084
+ // to that project (a no-op close if it's already current, matching selectComboById);
2085
+ // clicking an icon acts on that row's project WITHOUT switching — same row-vs-icon split
2086
+ // as the workflow picker (#85). ─────────────────────────────────────────────────────
2087
+ const $projCombo = document.getElementById('ws-proj-combo');
2088
+ const $projTrigger = document.getElementById('ws-proj-trigger');
2089
+ const $projPopover = document.getElementById('ws-proj-popover');
2090
+ const $projSearch = document.getElementById('ws-proj-search');
2091
+ const $projList = document.getElementById('ws-proj-list');
2092
+ let projComboHi = -1;
2093
+
2094
+ function buildProjList() {
2095
+ if (!$projList) return;
2096
+ const rows = projects.slice().sort((a, b) => a.name.localeCompare(b.name));
2097
+ let html = rows.map((p) => {
2098
+ const pid = escapeAttr(p.id);
2099
+ const displayApp = appDisplayName(p.app);
2100
+ const meta = `${escapeHtml(displayApp)} · ${escapeHtml(relAgo(p.updatedAt))}`;
2101
+ return `<div class="wf-option" role="option" id="ws-proj-opt-${pid}" data-id="${pid}" data-search="${escapeAttr((p.name + ' ' + displayApp + ' ' + p.app).toLowerCase())}" tabindex="-1" aria-selected="${current && current.id === p.id ? 'true' : 'false'}">`
2102
+ + `<span class="wf-option-name">${escapeHtml(p.name)}</span><span class="wf-option-meta">${meta}</span>`
2103
+ + `<span class="wf-option-actions">`
2104
+ + `<button type="button" class="wf-act act-edit" data-act="rename" data-id="${pid}" tabindex="-1" data-tip="Rename" aria-label="Rename ${escapeAttr(p.name)}">✎</button>`
2105
+ + `<button type="button" class="wf-act act-dup" data-act="duplicate" data-id="${pid}" tabindex="-1" data-tip="Duplicate" aria-label="Duplicate ${escapeAttr(p.name)}">⧉</button>`
2106
+ + `<button type="button" class="wf-act act-archive" data-act="archive" data-id="${pid}" tabindex="-1" data-tip="Archive — recoverable" aria-label="Archive ${escapeAttr(p.name)}">⏏</button>`
2107
+ + `</span></div>`;
2108
+ }).join('');
2109
+ html += `<div class="wf-empty-search" hidden>No projects match '<span class="wf-empty-term"></span>'</div>`;
2110
+ $projList.innerHTML = html;
2111
+ }
2112
+ function projComboVisible() { return [...$projList.querySelectorAll('.wf-option')].filter((o) => !o.hidden); }
2113
+ function projComboClearHighlight() {
2114
+ $projList.querySelectorAll('.wf-option.highlighted').forEach((o) => o.classList.remove('highlighted'));
2115
+ projComboHi = -1;
2116
+ if ($projSearch) $projSearch.removeAttribute('aria-activedescendant');
2117
+ }
2118
+ function projComboFilter(q) {
2119
+ q = (q || '').toLowerCase().trim();
2120
+ let any = false;
2121
+ $projList.querySelectorAll('.wf-option').forEach((o) => {
2122
+ const match = !q || o.dataset.search.includes(q);
2123
+ o.hidden = !match;
2124
+ if (match) any = true;
2125
+ });
2126
+ const empty = $projList.querySelector('.wf-empty-search');
2127
+ if (empty) { empty.hidden = any; empty.querySelector('.wf-empty-term').textContent = q; }
2128
+ projComboClearHighlight();
2129
+ }
2130
+ function projComboMove(delta) {
2131
+ const vis = projComboVisible();
2132
+ if (!vis.length) return;
2133
+ projComboHi = projComboHi < 0 ? (delta > 0 ? 0 : vis.length - 1) : Math.max(0, Math.min(vis.length - 1, projComboHi + delta));
2134
+ vis.forEach((o, i) => o.classList.toggle('highlighted', i === projComboHi));
2135
+ const hi = vis[projComboHi];
2136
+ hi.scrollIntoView({ block: 'nearest' });
2137
+ if ($projSearch) $projSearch.setAttribute('aria-activedescendant', hi.id);
2138
+ }
2139
+ function openProjCombo() {
2140
+ if (!current || !$projPopover) return;
2141
+ buildProjList();
2142
+ $projPopover.hidden = false;
2143
+ $projTrigger.classList.add('open');
2144
+ $projTrigger.setAttribute('aria-expanded', 'true');
2145
+ if ($projSearch) $projSearch.value = '';
2146
+ projComboFilter('');
2147
+ const sel = $projList.querySelector(`[data-id="${escapeAttr(current.id)}"]`);
2148
+ if (sel) sel.scrollIntoView({ block: 'nearest' });
2149
+ setTimeout(() => { if ($projSearch) $projSearch.focus(); }, 0);
2150
+ }
2151
+ function closeProjCombo(focusTrigger) {
2152
+ if (!$projPopover || $projPopover.hidden) return;
2153
+ $projPopover.hidden = true;
2154
+ $projTrigger.classList.remove('open');
2155
+ $projTrigger.setAttribute('aria-expanded', 'false');
2156
+ projComboClearHighlight();
2157
+ if (focusTrigger && $projTrigger) $projTrigger.focus();
2158
+ }
2159
+ function selectProjById(id) {
2160
+ closeProjCombo(true);
2161
+ if (current && current.id === id) return; // already open — no-op, matches selectComboById
2162
+ openProject(id);
2163
+ }
2164
+ if ($projTrigger) {
2165
+ $projTrigger.addEventListener('click', (e) => {
2166
+ if (!current) return;
2167
+ e.stopPropagation();
2168
+ $projPopover.hidden ? openProjCombo() : closeProjCombo(false);
2169
+ });
2170
+ $projTrigger.addEventListener('keydown', (e) => {
2171
+ if (e.key === 'ArrowDown' || e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openProjCombo(); }
2172
+ });
2173
+ }
2174
+ if ($projSearch) {
2175
+ $projSearch.addEventListener('input', () => projComboFilter($projSearch.value));
2176
+ $projSearch.addEventListener('keydown', (e) => {
2177
+ if (e.key === 'ArrowDown') { e.preventDefault(); projComboMove(1); }
2178
+ else if (e.key === 'ArrowUp') { e.preventDefault(); projComboMove(-1); }
2179
+ else if (e.key === 'Enter') {
2180
+ e.preventDefault();
2181
+ const vis = projComboVisible();
2182
+ const pick = projComboHi >= 0 ? vis[projComboHi] : (vis.length === 1 ? vis[0] : null);
2183
+ if (pick) selectProjById(pick.dataset.id);
2184
+ } else if (e.key === 'Escape') { e.preventDefault(); closeProjCombo(true); }
2185
+ });
2186
+ }
2187
+ if ($projList) {
2188
+ $projList.addEventListener('click', (e) => {
2189
+ const act = e.target.closest('[data-act]');
2190
+ if (act) { closeProjCombo(false); doProjectAction(act.dataset.act, act.dataset.id); return; }
2191
+ const o = e.target.closest('.wf-option');
2192
+ if (o) selectProjById(o.dataset.id);
2193
+ });
2194
+ }
2195
+ document.addEventListener('mousedown', (e) => {
2196
+ if ($projPopover && !$projPopover.hidden && $projCombo && !$projCombo.contains(e.target)) closeProjCombo(false);
968
2197
  });
969
2198
 
970
2199
  window.flolessWorkspaces = { setMode, refresh: loadProjects, findActive: wsFindActive, find: wsFind, clearFind: wsClearFind };