@floless/app 0.85.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.
@@ -35,6 +35,8 @@
35
35
  const $projMenu = document.getElementById('ws-proj-menu');
36
36
  const $wsExports = document.getElementById('ws-exports');
37
37
  const $wsHistory = document.getElementById('ws-history');
38
+ const $wsKnowledge = document.getElementById('ws-knowledge');
39
+ const $wsKnowledgeFile = document.getElementById('ws-knowledge-file');
38
40
  const frames = {
39
41
  model: document.getElementById('ws-frame-model'),
40
42
  drawings: document.getElementById('ws-frame-drawings'),
@@ -45,6 +47,44 @@
45
47
  const $sourcePlaceholder = document.getElementById('ws-source-placeholder'); // shown for a filter-less Source step
46
48
  let currentStep = 'model';
47
49
 
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
+
48
88
  let exportState = null; // kind → { path, exportedAt } after a successful list; null = unknown/failed
49
89
  if (!$switch || !$landing || !$app) return; // markup absent — nothing to wire
50
90
 
@@ -65,10 +105,29 @@
65
105
  // + listing (projectExportFiles). renderExports()/exportUrl() read wsApp().exports — never a global.
66
106
  const WORKSPACE_APPS = {
67
107
  'steel-model': {
68
- seed: 'takeoff', // "+ Import the current takeoff"
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
+ ],
69
127
  editor: '/steel-editor.html',
70
128
  filter: '/steel-filter.html',
71
129
  steps: [
130
+ { key: 'knowledge', label: 'Knowledge' }, // per-project KB — the job's context, consulted by everything
72
131
  { key: 'drawings', label: 'Drawings' },
73
132
  { key: 'model', label: 'Model' },
74
133
  { key: 'exports', label: 'Exports' },
@@ -83,22 +142,35 @@
83
142
  ],
84
143
  },
85
144
  vectorize: {
86
- seed: 'drawing', // drop-a-drawing (Task 6)
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
+ ],
87
157
  editor: '/vector-editor.html',
88
158
  filter: null, // no filter step — Source shows a lightweight placeholder
89
159
  steps: [
160
+ { key: 'knowledge', label: 'Knowledge' }, // KB is project-level — every workspace app gets it
90
161
  { key: 'drawings', label: 'Source' }, // reuse the 'drawings' frame slot; label "Source"
91
- { key: 'model', label: 'Vectors' }, // reuse the 'model' frame slot; label "Vectors"
162
+ { key: 'model', label: 'Traced' }, // reuse the 'model' frame slot; label "Traced"
92
163
  { key: 'exports', label: 'Exports' },
93
164
  { key: 'history', label: 'History' },
94
165
  ],
95
166
  diff: false,
96
167
  exports: [
97
- { kind: 'svg', ico: '▨', name: 'Vectors', fmt: 'SVG', verb: 'Export SVG', file: true, open: true },
168
+ { kind: 'svg', ico: '▨', name: 'Traced drawing', fmt: 'SVG', verb: 'Export SVG', file: true, open: true },
98
169
  ],
99
170
  },
100
171
  };
101
172
  const wsApp = () => (current ? WORKSPACE_APPS[current.app] : null);
173
+ const appDisplayName = (id) => (WORKSPACE_APPS[id] && WORKSPACE_APPS[id].displayName) || id;
102
174
  let mode = 'workflows';
103
175
  try { if (localStorage.getItem(LS_MODE) === 'workspaces') mode = 'workspaces'; } catch { /* private mode */ }
104
176
  let projects = [];
@@ -109,7 +181,7 @@
109
181
  let wsAppIds = Object.keys(WORKSPACE_APPS);
110
182
  let current = null; // the open project (null = landing)
111
183
 
112
- // The open app's visible label for a step key (Model→"Model" for steel, "Vectors" for vectorize) —
184
+ // The open app's visible label for a step key (Model→"Model" for steel, "Traced" for vectorize) —
113
185
  // so shared chrome (banners, prompts) names the app's OWN step, never hard-coded steel vocabulary.
114
186
  // Falls back to a capitalized key if the descriptor is missing a step.
115
187
  const stepLabel = (key) => {
@@ -119,24 +191,24 @@
119
191
  };
120
192
 
121
193
  // ── Workspaces guide beacon (aware.js owns #guide-beacon; we own project state) ──────
122
- // The document-lifecycle guide (drop → review → approve → export) is for the drop-a-drawing
123
- // DOCUMENT archetype (vectorize today, `seed:'drawing'`), not the pipeline-import archetype
124
- // (steel `seed:'takeoff'`, which already onboards via the Workflows beacon). Hand aware.js a
125
- // small snapshot of the open project's lifecycle state; it repaints the shared beacon/modal.
126
- const wsHasDocGuide = () => { const d = wsApp(); return !!(d && d.seed === 'drawing'); };
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); };
127
198
  function syncWorkspaceGuide() {
128
199
  if (!bridge.setWorkspaceGuide) return; // older bridge — no-op (beacon simply stays hidden)
129
200
  if (!current || !wsHasDocGuide()) { bridge.clearWorkspaceGuide && bridge.clearWorkspaceGuide(); return; }
130
201
  // `exported` = an SVG export file exists (from the last export listing); best-known from
131
202
  // exportState, which renderExports() populates. Unknown before Exports is opened → false.
132
203
  const exported = !!(exportState && exportState.svg && exportState.svg.exportedAt);
133
- bridge.setWorkspaceGuide({ app: current.app, name: current.name, approved: !!current.approvedAt, exported });
204
+ bridge.setWorkspaceGuide({ app: current.app, name: current.name, displayName: appDisplayName(current.app), approved: !!current.approvedAt, exported });
134
205
  }
135
206
 
136
207
  // ── mode ────────────────────────────────────────────────────────────────────
137
208
  function applyMode() {
138
209
  const ws = mode === 'workspaces';
139
210
  $app.classList.toggle('mode-workspaces', ws);
211
+ document.body.classList.toggle('mode-workspaces', ws);
140
212
  $switch.querySelectorAll('button').forEach((b) => {
141
213
  const on = b.dataset.mode === mode;
142
214
  b.classList.toggle('active', on);
@@ -214,41 +286,62 @@
214
286
 
215
287
  function renderLanding() {
216
288
  let html = `<div class="ws-head"><h2>Workspaces</h2>` +
217
- `<div class="ws-sub">Live projects — open a document to keep working. No Run here.</div></div>` +
218
- `<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">`;
219
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 : '';
220
325
  html += `<div class="ws-card" role="button" tabindex="0" data-open="${escapeAttr(p.id)}">` +
221
- `<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>` +
222
327
  `<span class="ws-body"><span><span class="ws-name">${escapeHtml(p.name)}</span>` +
223
- `<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>` +
224
330
  `<button type="button" class="ws-kebab" data-kebab="${escapeAttr(p.id)}" aria-label="Project actions" data-tip="Rename · Duplicate · Archive">⋯</button>` +
225
331
  `</span></div>`;
226
332
  }
227
- // One create card per installed workspace app, driven by its descriptor's seed behavior:
228
- // • seed:'takeoff' (steel-model) — click-to-import the app's current takeoff (Slice-1 flow, unchanged).
229
- // • seed:'drawing' (vectorize) — a drop/pick affordance that starts a project from a dropped file.
230
- for (const id of wsAppIds) {
231
- const d = WORKSPACE_APPS[id];
232
- if (!d) continue;
233
- if (d.seed === 'drawing') {
234
- html += `<button type="button" class="ws-seed ws-seed-drop" data-seed-app="${escapeAttr(id)}" data-seed-drop="${escapeAttr(id)}">` +
235
- `<span class="plus">+</span>` +
236
- `<span class="ws-seed-headline">Drop a drawing to start a new Vectorize project</span>` +
237
- `<span class="ws-seed-sub">PDF or image — vectors come out editable, ready to export as SVG.</span>` +
238
- `</button>`;
239
- } else {
240
- html += `<button type="button" class="ws-seed" data-seed-app="${escapeAttr(id)}">` +
241
- `<span class="plus">+</span><span>Import the current ${escapeHtml(id)} takeoff as a project</span></button>`;
242
- }
243
- }
244
333
  html += `</div>`;
245
- // Empty-note copy adapts to which create affordances are on screen: a vectorize card means the
246
- // user can drop a drawing right above; otherwise it's the steel import line.
334
+ // Empty-note copy adapts to which create affordances are on screen.
247
335
  if (!projects.length) {
248
- const hasDrawingSeed = wsAppIds.some((id) => WORKSPACE_APPS[id] && WORKSPACE_APPS[id].seed === 'drawing');
249
- html += hasDrawingSeed
250
- ? `<div class="ws-empty-note">No projects yet — drop a drawing above, or ask your terminal AI to vectorize a drawing set.</div>`
251
- : `<div class="ws-empty-note">No projects yet — import your current takeoff above, or ask your terminal AI to read a drawing set.</div>`;
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>`;
252
345
  }
253
346
  $landing.innerHTML = html;
254
347
  }
@@ -262,8 +355,10 @@
262
355
  if (seed) {
263
356
  const id = seed.dataset.seedApp;
264
357
  const d = WORKSPACE_APPS[id];
265
- if (d && d.seed === 'drawing') { seedPickApp = id; $seedFile.click(); } // drop-a-drawing: open the picker
266
- else createSeeded(id); // takeoff import
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
267
362
  }
268
363
  });
269
364
  $landing.addEventListener('keydown', (e) => {
@@ -275,15 +370,11 @@
275
370
  // Drop-a-drawing dropzone. A single hidden picker (outside $landing so an innerHTML re-render can't
276
371
  // wipe it) backs the click-to-pick; dragover/drop are delegated on $landing so they survive the
277
372
  // re-render too. The dashed card lights up (.drag-over) while a file hovers it.
278
- let seedPickApp = null; // which app the pending pick/drop is for (set on click/drop)
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.
279
375
  const $seedFile = document.createElement('input');
280
- $seedFile.type = 'file'; $seedFile.accept = '.pdf,image/*'; $seedFile.hidden = true;
376
+ $seedFile.type = 'file'; $seedFile.accept = '.pdf,image/*'; $seedFile.multiple = true; $seedFile.hidden = true;
281
377
  document.body.appendChild($seedFile);
282
- $seedFile.addEventListener('change', () => {
283
- const file = ($seedFile.files || [])[0];
284
- $seedFile.value = ''; // clear so re-picking the same file re-fires change
285
- if (file && seedPickApp) createFromDrawing(seedPickApp, file);
286
- });
287
378
  $landing.addEventListener('dragover', (e) => {
288
379
  const zone = e.target.closest('[data-seed-drop]');
289
380
  if (!zone) return;
@@ -299,8 +390,8 @@
299
390
  if (!zone) return;
300
391
  e.preventDefault();
301
392
  zone.classList.remove('drag-over');
302
- const file = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0];
303
- if (file) createFromDrawing(zone.dataset.seedDrop, file);
393
+ const files = Array.from((e.dataTransfer && e.dataTransfer.files) || []);
394
+ if (files.length) createFromDrawing(zone.dataset.seedDrop, files);
304
395
  });
305
396
 
306
397
  async function promptName(title, label, value) {
@@ -314,25 +405,26 @@
314
405
  if (!name) return;
315
406
  try {
316
407
  const { project, seeded } = await api('/api/projects', { method: 'POST', body: JSON.stringify({ name, app: appId, seedFromApp: true }) });
317
- // Tell the truth about the import: seeded=false means there was no current takeoff to copy
318
- // (or it was unreadable) — the project is EMPTY, don't imply the takeoff came across.
319
- if (seeded) showToast(`Project "${project.name}" created from the current ${appId} takeoff`, 'ok');
320
- else showToast(`Project "${project.name}" created — empty (no current ${appId} takeoff to import)`, 'warn');
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');
321
413
  track('workspace_project_created', { app: appId }); // takeoff-import create path
322
414
  projects.unshift(project);
323
415
  openProject(project.id);
324
416
  } catch (err) { showToast('Couldn’t create the project: ' + (err && err.message || err), 'warn'); }
325
417
  }
326
418
 
327
- // Drop-a-drawing create (vectorize). No new server verb: create an EMPTY project, then fire the
419
+ // Drop-a-drawing create. No new server verb: create an EMPTY project, then fire the
328
420
  // existing revision pipeline (attachRevision) with the dropped file so the terminal AI reads it into
329
421
  // v1. ROLLBACK on cancel/error — if the user cancels the name prompt, or the file can't be read,
330
- // AFTER the row is created, archive the empty project so no dead, openable vectorize project is left
422
+ // AFTER the row is created, archive the empty project so no dead, openable project is left
331
423
  // behind (the row is created before the source exists — spec §4.1).
332
- async function createFromDrawing(appId, file) {
424
+ async function createFromDrawing(appId, files) {
333
425
  // Ask for the name FIRST (before creating a row) so the common "cancel the prompt" path never
334
426
  // creates anything to roll back.
335
- const name = await promptName('New Vectorize project', 'Name this project', '');
427
+ const name = await promptName(`New ${appDisplayName(appId)} project`, 'Name this project', '');
336
428
  if (!name) return;
337
429
  let project;
338
430
  try {
@@ -341,10 +433,10 @@
341
433
  showToast('Couldn’t create the project: ' + (err && err.message || err), 'warn');
342
434
  return;
343
435
  }
344
- // Validate the file is actually readable BEFORE queuing — a read failure here (after the row
436
+ // Validate the files are actually readable BEFORE queuing — a read failure here (after the row
345
437
  // exists) must roll the empty project back rather than leave a dead one openable. attachRevision
346
- // re-reads the file for the real pipeline; a tiny second read of the same file is harmless.
347
- try { await readFileAsSnapshot(file); }
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]); }
348
440
  catch {
349
441
  // Tailor the toast to what actually happened server-side: only claim the empty project was
350
442
  // removed if the archive POST succeeded — otherwise it's still there and we must say so.
@@ -359,8 +451,8 @@
359
451
  }
360
452
  track('workspace_project_created', { app: appId }); // drop-a-drawing create path (only once the row is kept, not rolled back)
361
453
  projects.unshift(project);
362
- openProject(project.id); // opens onto the project; the revision card reflects the queued read
363
- attachRevision([file]); // reads the file → POSTs the revision-read Request for THIS project (self-toasting)
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)
364
456
  }
365
457
 
366
458
  // Best-effort rollback of a just-created empty project (the existing archive path — recoverable).
@@ -376,7 +468,7 @@
376
468
  }
377
469
 
378
470
  // ── open project ────────────────────────────────────────────────────────────
379
- async function openProject(id) {
471
+ async function openProject(id, initialStep = 'model') {
380
472
  let p = projects.find((x) => x.id === id);
381
473
  if (!p) { try { p = (await api('/api/projects')).projects.find((x) => x.id === id); } catch { /* fall through */ } }
382
474
  if (!p) { showToast('Project not found — it may have been archived.', 'warn'); return loadProjects(); }
@@ -389,9 +481,9 @@
389
481
  lastRevState = 'none'; stopRevisionPoll(); // fresh project — drop any prior revision-poll state
390
482
  $projName.textContent = p.name;
391
483
  $crumbName.textContent = p.name;
392
- $status.textContent = p.app;
484
+ $status.textContent = appDisplayName(p.app);
393
485
  // Lazily src the frames once per project; switching steps only toggles hidden so the
394
- // editor's state survives a Source⇄Vectors round-trip. Frame URLs come from the app descriptor:
486
+ // editor's state survives a Source⇄Traced round-trip. Frame URLs come from the app descriptor:
395
487
  // the 'model' frame loads the app's editor; the 'drawings' frame loads its filter (steel) OR is
396
488
  // left empty when the app has no filter step (vectorize — its Source step shows a placeholder).
397
489
  const d = WORKSPACE_APPS[p.app]; // guaranteed present — the guard above bailed on an unknown app
@@ -401,14 +493,19 @@
401
493
  renderStepTabs(); // paint the tab labels for THIS app before the first step shows
402
494
  frames.model.src = 'about:blank'; frames.drawings.src = 'about:blank'; // reset any previous project
403
495
  frames.model.dataset.loaded = ''; frames.drawings.dataset.loaded = '';
404
- setStep('model');
496
+ setStep(initialStep);
405
497
  applyMode();
406
498
  syncWorkspaceGuide(); // point the shared beacon at THIS project's document lifecycle
407
499
  }
408
- function closeProject() { current = null; stopRevisionPoll(); lastRevState = 'none'; $revisionCard.hidden = true; closeProjMenu(); applyMode(); syncWorkspaceGuide(); }
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();
505
+ }
409
506
  document.getElementById('ws-back').addEventListener('click', closeProject);
410
507
 
411
- // Paint the step-tab LABELS from the current app's descriptor (Source/Vectors for vectorize,
508
+ // Paint the step-tab LABELS from the current app's descriptor (Source/Traced for vectorize,
412
509
  // Drawings/Model for steel). The data-step KEYS stay stable (drawings/model/exports/history) so
413
510
  // setStep() and the frame slots are untouched — only the visible text differs. Label is set via
414
511
  // textContent (never innerHTML) — it's a descriptor string, but textContent is the safe default.
@@ -450,6 +547,14 @@
450
547
  $wsHistory.hidden = !showHistory;
451
548
  if (showHistory) renderHistory();
452
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; }
453
558
  }
454
559
  $stepTabs.addEventListener('click', (e) => {
455
560
  const b = e.target.closest('button[data-step]');
@@ -474,7 +579,7 @@
474
579
  if (win && typeof win.flushContract === 'function') await win.flushContract();
475
580
  const res = await api(`/api/contract/${encodeURIComponent(current.app)}/approve?project=${encodeURIComponent(current.id)}`, { method: 'POST' });
476
581
  if (res && res.approvedAt) current.approvedAt = res.approvedAt; // unlock exports
477
- showToast(`Approved — "${current.name}" is baked into ${current.app}`, 'ok');
582
+ showToast(`Approved — "${current.name}" is baked into ${appDisplayName(current.app)}`, 'ok');
478
583
  track('workspace_project_approved', { app: current.app }); // a successful sign-off
479
584
  // First Approve for this app calms the "✦ Start here" beacon (the document-archetype
480
585
  // analog of a workflow's first Run); ticks the Review + Approve guide rows.
@@ -525,6 +630,763 @@
525
630
  // (find methods are exposed on the canonical window.flolessWorkspaces export below — a separate
526
631
  // assignment here would be clobbered by that later `= { setMode, … }`.)
527
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
+
528
1390
  // ── Exports step ──────────────────────────────────────────────────────────────
529
1391
  const hhmm = (iso) => {
530
1392
  const d = new Date(iso);
@@ -667,6 +1529,7 @@
667
1529
  let revBaseVersion = 0; // the ledger head captured at attach — success = the head advances past it
668
1530
  let revCardReq = null;
669
1531
  let revisionPoll = null;
1532
+ const isInitialRevisionRead = (req) => !req || !req.baseVersion || req.baseVersion <= 0;
670
1533
  function stopRevisionPoll() { if (revisionPoll) { clearInterval(revisionPoll); revisionPoll = null; } }
671
1534
  function startRevisionPoll() {
672
1535
  stopRevisionPoll();
@@ -691,6 +1554,7 @@
691
1554
  async function attachRevision(files) {
692
1555
  const proj = current; // capture — the user may switch projects during the async file reads / POST
693
1556
  if (!proj || !files.length) return;
1557
+ const returnFocus = document.activeElement;
694
1558
  let snapshots;
695
1559
  try { snapshots = await Promise.all(files.map(readFileAsSnapshot)); }
696
1560
  catch { showToast('Could not read the selected files', 'warn'); return; }
@@ -703,30 +1567,32 @@
703
1567
  } catch (err) { showToast('Attach failed: ' + ((err && err.message) || err), 'warn'); return; }
704
1568
  const req = res && res.request;
705
1569
  // Copy the paste-ready instruction so the user can hand it to their terminal AI (best-effort).
1570
+ let copied = false;
706
1571
  if (req && bridge.markedInstruction && bridge.copyToClipboard) {
707
- try { await bridge.copyToClipboard(bridge.markedInstruction(req)); } catch { /* clipboard blocked */ }
1572
+ try { copied = await bridge.copyToClipboard(bridge.markedInstruction(req)); } catch { copied = false; }
708
1573
  }
709
1574
  if (bridge.loadRequests) bridge.loadRequests().catch(() => {}); // refresh the footer Requests popover
710
1575
  if (current !== proj) return; // switched away while posting — don't drive the wrong project's card/poll
711
- showToast(`Revised set queued — ${files.length} file${files.length > 1 ? 's' : ''} for your terminal AI`, 'ok');
712
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');
713
1578
  lastRevState = 'pending';
714
1579
  startRevisionPoll();
715
1580
  renderRevisionCard();
1581
+ if (req && bridge.showRequestQueuedModal) {
1582
+ bridge.showRequestQueuedModal(req, { copied, fileCount: files.length, returnFocus });
1583
+ }
716
1584
  }
717
1585
 
718
- document.getElementById('ws-attach-revision').addEventListener('click', () => $revisionFile.click());
719
- $revisionFile.addEventListener('change', () => {
720
- const files = [...($revisionFile.files || [])];
721
- $revisionFile.value = ''; // clear so re-picking the same file re-fires change
722
- attachRevision(files);
1586
+ document.getElementById('ws-attach-revision').addEventListener('click', async () => {
1587
+ const files = await pickDrawingFiles($revisionFile);
1588
+ if (files.length) attachRevision(files);
723
1589
  });
724
1590
 
725
1591
  function buildPendingCard(req) {
726
1592
  const n = (req.sourceRefs && req.sourceRefs.length) || (req.snapshots && req.snapshots.length) || 1;
727
1593
  const spin = revEl('span', 'wrc-spin'); spin.setAttribute('aria-hidden', 'true');
728
1594
  const txt = revEl('span', 'wrc-text');
729
- txt.appendChild(revEl('b', null, 'Reading the revised set…'));
1595
+ txt.appendChild(revEl('b', null, `Reading the ${isInitialRevisionRead(req) ? 'initial' : 'revised'} set…`));
730
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”.`));
731
1597
  const copy = revEl('button', 'btn-mini', '⧉ Copy');
732
1598
  copy.type = 'button'; copy.dataset.revcopy = ''; copy.setAttribute('data-tip', 'Copy the instruction again');
@@ -805,11 +1671,11 @@
805
1671
  author === 'You'
806
1672
  ? '<span class="avatar you">YOU</span>'
807
1673
  : `<span class="avatar ai">${escapeHtml((author || '?').replace(/[^A-Za-z0-9]/g, '').slice(0, 2).toUpperCase() || 'AI')}</span>`;
808
- const gateBadge = (gate, kind) => {
1674
+ const gateBadge = (gate, kind, n) => {
809
1675
  if (gate === 'model')
810
1676
  return '<span class="gate-badge model" data-tip="Sign-off gate — this version was approved">Model</span>';
811
1677
  if (kind === 'revision-read')
812
- 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>`;
813
1679
  return '<span class="gate-badge" data-tip="Unsigned — a working-tree restore, not a sign-off">unsigned</span>';
814
1680
  };
815
1681
 
@@ -832,7 +1698,7 @@
832
1698
  `<td><span class="ver${v.current ? ' cur' : ''}">v${escapeHtml(String(v.n))}</span></td>` +
833
1699
  `<td class="htime">${escapeHtml(histWhen(v.ts))}</td>` +
834
1700
  `<td><span class="hby">${avatarFor(v.author)}${escapeHtml(v.author)}</span></td>` +
835
- `<td>${gateBadge(v.gate, v.kind)}</td>` +
1701
+ `<td>${gateBadge(v.gate, v.kind, v.n)}</td>` +
836
1702
  `<td class="change">${escapeHtml(v.message)}</td>` +
837
1703
  `<td>${action}</td></tr>`;
838
1704
  // The disclosure row is always emitted (hidden) so toggling is a pure show/hide + lazy fetch.
@@ -873,9 +1739,10 @@
873
1739
  // Working copy = the draft; when it isn't signed off (approvedAt cleared by an edit or a
874
1740
  // rollback) surface it honestly ABOVE the table (not as a fake row) and name the Exports lock.
875
1741
  const headKind = rows.length && rows[0].current ? rows[0].kind : undefined;
1742
+ const headIsInitialRead = headKind === 'revision-read' && Number(rows[0].n) <= 1;
876
1743
  const working = !approvedAt
877
1744
  ? (headKind === 'revision-read'
878
- ? '<div class="hist-working">● <b>The AI read a revised drawing set — review it before signing.</b> ' +
1745
+ ? `<div class="hist-working">● <b>The AI read ${headIsInitialRead ? 'the initial' : 'a revised'} drawing set — review it before signing.</b> ` +
879
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>`
880
1747
  : '<div class="hist-working">● <b>Working copy isn’t signed off.</b> ' +
881
1748
  '<button type="button" id="hist-approve">Approve</button> to sign off this version. Exports stay locked until you do.</div>')
@@ -949,7 +1816,7 @@
949
1816
  { key: 'connections', label: 'Connections' },
950
1817
  ];
951
1818
  const diffBase = new Map(); // "<projectId>\0<n>" → chosen baseline (undefined = compare to the previous version)
952
- 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
953
1820
  const el = (tag, cls, text) => {
954
1821
  const n = document.createElement(tag);
955
1822
  if (cls) n.className = cls;
@@ -1159,17 +2026,16 @@
1159
2026
  if (dr) { const n = Number(dr.dataset.diffRetry); loadDiff(n, diffBase.get(baseKeyFor(n))); return; }
1160
2027
  });
1161
2028
 
1162
- // ── 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). ───────────────────────────────────────────────
1163
2032
  let menuFor = null;
1164
2033
  function menuItem(action, label) {
1165
2034
  return `<button class="menu-item" data-act="${action}" role="menuitem"><span class="menu-label">${escapeHtml(label)}</span></button>`;
1166
2035
  }
1167
2036
  function openProjMenu(id, anchor) {
1168
2037
  menuFor = id;
1169
- const others = projects.filter((p) => p.id !== id);
1170
- $projMenu.innerHTML =
1171
- (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>' : '') +
1172
- menuItem('rename', 'Rename…') + menuItem('duplicate', 'Duplicate') +
2038
+ $projMenu.innerHTML = menuItem('rename', 'Rename…') + menuItem('duplicate', 'Duplicate') +
1173
2039
  '<div class="menu-divider"></div>' + menuItem('archive', 'Archive');
1174
2040
  const r = anchor.getBoundingClientRect();
1175
2041
  $projMenu.style.left = Math.round(Math.max(8, Math.min(r.left, window.innerWidth - 260))) + 'px';
@@ -1177,40 +2043,157 @@
1177
2043
  $projMenu.hidden = false;
1178
2044
  $projMenu.classList.add('show');
1179
2045
  }
1180
- document.getElementById('ws-proj-trigger').addEventListener('click', (e) => {
1181
- if (!current) return;
1182
- e.stopPropagation();
1183
- if ($projMenu.hidden) openProjMenu(current.id, e.currentTarget); else closeProjMenu();
1184
- });
1185
2046
  document.addEventListener('click', (e) => {
1186
2047
  if ($projMenu.hidden) return;
1187
- 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();
1188
2049
  });
1189
- $projMenu.addEventListener('click', async (e) => {
1190
- const goto = e.target.closest('[data-goto]');
1191
- if (goto) { closeProjMenu(); return openProject(goto.dataset.goto); }
2050
+ $projMenu.addEventListener('click', (e) => {
1192
2051
  const act = e.target.closest('[data-act]');
1193
2052
  if (!act || !menuFor) return;
1194
2053
  closeProjMenu();
1195
- 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) {
1196
2061
  const proj = projects.find((p) => p.id === id);
1197
2062
  try {
1198
- if (act.dataset.act === 'rename') {
2063
+ if (action === 'rename') {
1199
2064
  const name = await promptName('Rename project', 'New name', proj ? proj.name : '');
1200
2065
  if (!name) return;
1201
2066
  const { project } = await api(`/api/projects/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify({ name }) });
1202
2067
  if (current && current.id === id) { current = project; $projName.textContent = project.name; $crumbName.textContent = project.name; }
1203
2068
  showToast('Renamed', 'ok');
1204
- } else if (act.dataset.act === 'duplicate') {
2069
+ } else if (action === 'duplicate') {
1205
2070
  const { project } = await api(`/api/projects/${encodeURIComponent(id)}/duplicate`, { method: 'POST', body: '{}' });
1206
2071
  showToast(`Duplicated as "${project.name}"`, 'ok');
1207
- } else if (act.dataset.act === 'archive') {
2072
+ } else if (action === 'archive') {
1208
2073
  await api(`/api/projects/${encodeURIComponent(id)}/archive`, { method: 'POST', body: '{}' });
1209
2074
  showToast('Archived — recoverable from ~/.floless/projects/.archive', 'ok');
1210
2075
  if (current && current.id === id) { closeProject(); return; }
1211
2076
  }
1212
2077
  } catch (err) { showToast('Action failed: ' + (err && err.message || err), 'warn'); }
1213
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);
1214
2197
  });
1215
2198
 
1216
2199
  window.flolessWorkspaces = { setMode, refresh: loadProjects, findActive: wsFindActive, find: wsFind, clearFind: wsClearFind };