crewbus 10.0.7 → 10.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/lib/web.js CHANGED
@@ -16,14 +16,15 @@ import fs from "node:fs";
16
16
  import path from "node:path";
17
17
  import http from "node:http";
18
18
  import { fileURLToPath } from "node:url";
19
- import { boardDir, requireBoard, getFlag, fail, writeJson, listJson, cleanWebName, readJson, gitRevForBoard, newId, MAX_SPAWN, MAX_BODY_CHARS } from "./store.js";
20
- import { readAgent, agentTokenMatches, authorizeCheck, mintToken, newSalt, hashToken, touchAgent } from "./identity.js";
19
+ import { boardDir, requireBoard, getFlag, fail, writeJson, listJson, cleanWebName, readJson, readBoardMeta, writeBoardMeta, gitRevForBoard, newId, MAX_SPAWN, MAX_BODY_CHARS } from "./store.js";
20
+ import { readAgent, agentTokenMatches, authorizeCheck, ensureLoopbackOperator, mintToken, newSalt, hashToken, touchAgent } from "./identity.js";
21
21
  import { readDMs, readVisible, ackedIds, ackedIdSet, findMessageById, deliverDMs, parseRecipients } from "./mail.js";
22
22
  import { workerStatus, pidAlive, killWorkers, bootWorker, buildSpawnPrompt, buildSpawnTarget, formatSpawnCmd, installCliToUserPath, ensureBoardCliShim } from "./spawn.js";
23
23
  import { groupTelemetryData, collectBatch, gatherTelemetry, listBatches } from "./groups.js";
24
24
  import { httpJson } from "./sync.js";
25
25
  import { readChainRecords, verifyChainRecords, appendChainRecord, readHold, readBoardQuotas } from "./export.js";
26
- import { launchDrivers, detectHarnessBinaries, validateLaunchPlan, advertiseEnv, HARNESS_MODELS, getDiscoveredModels, refreshDiscoveredModels } from "./launch.js";
26
+ import { launchDrivers, detectHarnessBinaries, validateLaunchPlan, advertiseEnv, buildPairUrl, HARNESS_MODELS, getDiscoveredModels, refreshDiscoveredModels } from "./launch.js";
27
+ import { newPairToken, pairingPath, readRelayState } from "./relay.js";
27
28
 
28
29
  export function escapeHtml(s) {
29
30
  return String(s === undefined || s === null ? "" : s).replace(/[&<>"']/g, (c) => ({
@@ -424,8 +425,9 @@ export function renderBoardHtml(boardPath) {
424
425
  --panel:#ffffff;
425
426
  --ink:#14201a;
426
427
  --dim:#5b6a62;
427
- --acc:#0e8a55;
428
+ --acc:#5b6a62;
428
429
  --acc-ink:#ffffff;
430
+ --ok:#3d8f66;
429
431
  --warn:#b86e00;
430
432
  --line:#d5ddd7;
431
433
  --code:#0f1419;
@@ -444,13 +446,13 @@ export function renderBoardHtml(boardPath) {
444
446
  --radius-lg:12px;
445
447
  }
446
448
  @media (prefers-color-scheme:dark){:root:not([data-theme="light"]){
447
- --bg:#0f1419;--panel:#182028;--ink:#e3e9ee;--dim:#8b98a5;--acc:#4cc38a;--acc-ink:#07130d;--warn:#ffb454;--line:#2a343e;--code:#0b0f14;
449
+ --bg:#0f1419;--panel:#182028;--ink:#e3e9ee;--dim:#8b98a5;--acc:#8b98a5;--acc-ink:#07130d;--ok:#4fb07f;--warn:#ffb454;--line:#2a343e;--code:#0b0f14;
448
450
  --bg-card-hover:#222d37;
449
451
  --warn-bg:#241b0e;
450
452
  --scroll:rgba(255,255,255,.16);
451
453
  --scroll-hi:rgba(255,255,255,.32);
452
454
  }}
453
- :root[data-theme="dark"]{--bg:#0f1419;--panel:#182028;--ink:#e3e9ee;--dim:#8b98a5;--acc:#4cc38a;--acc-ink:#07130d;--warn:#ffb454;--line:#2a343e;--code:#0b0f14;--bg-card-hover:#222d37;--warn-bg:#241b0e;--scroll:rgba(255,255,255,.16);--scroll-hi:rgba(255,255,255,.32)}
455
+ :root[data-theme="dark"]{--bg:#0f1419;--panel:#182028;--ink:#e3e9ee;--dim:#8b98a5;--acc:#8b98a5;--acc-ink:#07130d;--ok:#4fb07f;--warn:#ffb454;--line:#2a343e;--code:#0b0f14;--bg-card-hover:#222d37;--warn-bg:#241b0e;--scroll:rgba(255,255,255,.16);--scroll-hi:rgba(255,255,255,.32)}
454
456
  *{box-sizing:border-box}
455
457
  * {
456
458
  scrollbar-width: thin;
@@ -575,6 +577,10 @@ button:disabled{opacity:.4;cursor:default}
575
577
 
576
578
  /* Log and terminal boxes */
577
579
  .log{font-family:var(--mono);font-size:11px;white-space:pre-wrap;background:var(--code);padding:8px 12px;border-radius:var(--radius-sm);border:1px solid var(--line);color:var(--code-ink);max-height:250px;overflow-y:auto}
580
+ /* Launch output is empty until an action writes to it — hide the black
581
+ terminal box entirely when blank instead of showing an empty bar. */
582
+ #launch-out:empty{display:none}
583
+ #chat-events:empty,#launch-diff:empty{display:none}
578
584
 
579
585
  /* Chat Thread & Launch UI */
580
586
  .thread-hero{margin-bottom:16px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px}
@@ -587,7 +593,7 @@ button:disabled{opacity:.4;cursor:default}
587
593
  .chat-time{color:var(--dim)}
588
594
 
589
595
  /* Composer / Launch Box */
590
- .composer-card{background:var(--panel);border:1px solid var(--line);border-radius:var(--radius-lg);padding:16px;margin-top:16px;box-shadow:0 4px 20px rgba(0,0,0,0.3)}
596
+ .composer-card{background:var(--panel);border:1px solid var(--line);border-radius:var(--radius-lg);padding:16px;margin-top:16px}
591
597
  .composer-harness-bar{margin-bottom:12px}
592
598
  .harness-pills{display:flex;gap:8px;flex-wrap:wrap}
593
599
  .harness-card{display:flex;flex-direction:column;gap:2px;padding:8px 12px;background:var(--panel);border:1px solid var(--line);border-radius:var(--radius-md);cursor:pointer;transition:all .15s ease;min-width:110px}
@@ -662,7 +668,10 @@ details.tech-details summary{cursor:pointer;font-weight:500;user-select:none}
662
668
  <div class="pop-label" style="margin-top:10px">Workspace Board (Bus DB)</div>
663
669
  <div class="pop-path" id="pop-board-path">${e(boardPath)}</div>
664
670
  <button type="button" id="copy-board-btn" class="pop-btn"><svg class="btn-ic" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg> Copy Board Path</button>
665
- <button type="button" class="pop-btn" id="pop-pair-btn" style="margin-top:8px"><svg class="btn-ic" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="2" width="14" height="20" rx="2" ry="2"/><line x1="12" y1="18" x2="12.01" y2="18"/></svg> Pair Mobile Client (QR)…</button>
671
+ <button type="button" class="pop-btn" id="switch-board-btn" title="Use another folder's board (e.g. a CLI project): restarts the sidecar against <folder>/.crewbus"><svg class="btn-ic" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 3 21 3 21 8"/><line x1="4" y1="20" x2="21" y2="3"/><polyline points="21 16 21 21 16 21"/><line x1="15" y1="15" x2="21" y2="21"/></svg> Switch Board…</button>
672
+ <button type="button" class="pop-btn" id="reset-board-btn" title="Back to the default desktop board"> Use Default Board</button>
673
+ <div class="pop-path dim" id="board-switch-msg" style="display:none"></div>
674
+ <button type="button" class="pop-btn" id="pop-pair-btn" style="margin-top:8px" title="One-click: mints a one-time pairing link and shows the QR automatically"><svg class="btn-ic" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="2" width="14" height="20" rx="2" ry="2"/><line x1="12" y1="18" x2="12.01" y2="18"/></svg> Pair Mobile Client (QR)…</button>
666
675
  <button type="button" class="pop-btn" id="pop-install-cli-btn" style="margin-top:8px"><svg class="btn-ic" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/></svg> Install 'crewbus' CLI in PATH</button>
667
676
  </div>
668
677
  </div>
@@ -732,24 +741,13 @@ details.tech-details summary{cursor:pointer;font-weight:500;user-select:none}
732
741
  </header>
733
742
 
734
743
  <main id="view-container">
735
- <!-- SECTION: LAUNCH & CHAT CONSOLE -->
744
+ <!-- SECTION: LAUNCH CONSOLE -->
736
745
  <section id="sec-launch" data-section="Launch">
737
- <div class="thread-hero">
738
- <div>
739
- <h2 style="margin:0">Launch &amp; Chat</h2>
740
- <div class="dim">Orchestrate coding agents with safety previews and real-time execution</div>
741
- </div>
746
+ <div class="thread-hero" style="justify-content:flex-end">
742
747
  <div id="routes-line" class="routes-badge">routes: loading…</div>
743
748
  </div>
744
749
 
745
750
  <div class="chat-stream" id="chat-feed">
746
- <div class="chat-msg system">
747
- <div class="chat-header">
748
- <span class="chat-author">CrewBus Studio</span>
749
- <span class="chat-time">Active</span>
750
- </div>
751
- <div>Ready to dispatch autonomous coding agents for <code>${e(boardPath)}</code>. Configure your task below and preview execution plans before live boot.</div>
752
- </div>
753
751
  <div id="chat-events"></div>
754
752
  <div id="launch-diff"></div>
755
753
  <div id="launch-out" class="log"></div>
@@ -763,13 +761,12 @@ details.tech-details summary{cursor:pointer;font-weight:500;user-select:none}
763
761
  </div>
764
762
 
765
763
  <div class="composer-config-row">
766
- <span class="dim">Target:</span>
767
- <input id="launch-to" size="14" placeholder="auto (or w-1)" title="Target worker name(s)">
768
- <span class="dim">Count:</span>
764
+ <input id="launch-to" type="hidden" value="">
765
+ <span class="dim">No. of Agents:</span>
769
766
  <div class="stepper-wrap">
770
- <button id="launch-count-minus" type="button" title="fewer workers">−</button>
771
- <input id="launch-count" size="2" value="1">
772
- <button id="launch-count-plus" type="button" title="more workers">+</button>
767
+ <button id="launch-count-minus" type="button" title="fewer agents">−</button>
768
+ <input id="launch-count" size="2" value="1" title="Number of agents">
769
+ <button id="launch-count-plus" type="button" title="more agents">+</button>
773
770
  </div>
774
771
  <span class="dim" style="margin-left:8px">Model:</span>
775
772
  <select id="launch-model" style="background:var(--panel);color:var(--ink);border:1px solid var(--line);border-radius:4px;padding:3px 8px;font-size:12px">
@@ -803,10 +800,16 @@ details.tech-details summary{cursor:pointer;font-weight:500;user-select:none}
803
800
  </div>
804
801
 
805
802
  <div class="composer-bottom">
806
- <div class="launch-identity">
807
- from <input id="launch-from" size="10" placeholder="agent name">
808
- token <input id="launch-token" type="password" size="18" placeholder="abt-…">
803
+ <div class="launch-identity" title="Desktop launches as the board owner (auto-provisioned) — no token step needed">
804
+ <span class="dim">launching as <b id="launch-as">lead</b> (auto)</span>
805
+ <input id="launch-from" type="hidden" value="">
806
+ <input id="launch-token" type="password" style="display:none" value="">
809
807
  </div>
808
+ <details class="tech-details" id="launch-identity-advanced" style="margin:0">
809
+ <summary class="dim" style="cursor:pointer;font-size:11px">advanced: use a different identity</summary>
810
+ <span class="dim" style="font-size:11px">from <input id="launch-from-manual" size="10" placeholder="agent name"></span>
811
+ <span class="dim" style="font-size:11px">token <input id="launch-token-manual" type="password" size="14" placeholder="abt-…"></span>
812
+ </details>
810
813
  <div class="launch-actions">
811
814
  <button id="launch-preview" type="button">Preview Plan</button>
812
815
  <button id="launch-go" type="button" class="btn-launch danger">Launch Agents</button>
@@ -1001,6 +1004,13 @@ function markIdent(){
1001
1004
  if(lf&&!lf.value&&c.from)lf.value=c.from;
1002
1005
  var lt=document.getElementById('launch-token');
1003
1006
  if(lt&&!lt.value&&c.token)lt.value=c.token;
1007
+ // Auto badge: reflect the effective launch identity (auto lead unless the
1008
+ // user typed a manual override in the advanced disclosure).
1009
+ try{
1010
+ var man=document.getElementById('launch-from-manual');
1011
+ var lbl=document.getElementById('launch-as');
1012
+ if(lbl)lbl.textContent=(man&&man.value.trim())||lf.value.trim()||c.from||'lead';
1013
+ }catch(_){}
1004
1014
  }
1005
1015
  async function autoLoadOperatorCreds(){
1006
1016
  var lf=document.getElementById('launch-from');
@@ -1015,11 +1025,15 @@ async function autoLoadOperatorCreds(){
1015
1025
  if(r.ok){
1016
1026
  var j=await r.json();
1017
1027
  if(j.ok&&j.from&&j.token){
1018
- if(lf&&!lf.value)lf.value=j.from;
1019
- if(lt&&!lt.value)lt.value=j.token;
1028
+ if(lf)lf.value=j.from;
1029
+ if(lt)lt.value=j.token;
1020
1030
  if(who&&!who.value)who.value=j.from;
1021
1031
  if(tok&&!tok.value)tok.value=j.token;
1022
- try{localStorage.setItem('ab-who',j.from);localStorage.setItem('ab-tok',j.token);}catch(_){}
1032
+ // NOTE: no localStorage write for the auto operator token.
1033
+ // The desktop sidecar binds --port 0 (random), so the origin
1034
+ // (127.0.0.1:PORT) changes every launch and per-origin
1035
+ // localStorage is wiped anyway. The server is the source of
1036
+ // truth: every launch re-fetches from /api/operator-creds.
1023
1037
  markIdent();
1024
1038
  }
1025
1039
  }
@@ -1029,10 +1043,14 @@ async function autoLoadOperatorCreds(){
1029
1043
  function say(t){document.getElementById('result').textContent=t;}
1030
1044
  document.getElementById('save').onclick=function(){var c=creds();try{localStorage.setItem('ab-who',c.from);localStorage.setItem('ab-tok',c.token);}catch(e){}markIdent();say('identity saved in this tab');};
1031
1045
  try{document.getElementById('who').value=localStorage.getItem('ab-who')||'';document.getElementById('tok').value=localStorage.getItem('ab-tok')||'';}catch(e){}markIdent();
1032
- var _lf=document.getElementById('launch-from');
1033
- if(_lf){_lf.oninput=function(){try{localStorage.setItem('ab-who',this.value.trim());}catch(_){}var w=document.getElementById('who');if(w)w.value=this.value.trim();markIdent();};}
1034
- var _lt=document.getElementById('launch-token');
1035
- if(_lt){_lt.oninput=function(){try{localStorage.setItem('ab-tok',this.value.trim());}catch(_){}var t=document.getElementById('tok');if(t)t.value=this.value.trim();markIdent();};}
1046
+ try{
1047
+ // Manual-override fields mirror into Settings identity (two-way sync),
1048
+ // same as the old visible from+token row did.
1049
+ var _mf=document.getElementById('launch-from-manual');
1050
+ var _mt=document.getElementById('launch-token-manual');
1051
+ if(_mf){_mf.oninput=function(){var w=document.getElementById('who');if(w&&!w.value)w.value=this.value.trim();markIdent();};}
1052
+ if(_mt){_mt.oninput=function(){var t=document.getElementById('tok');if(t&&!t.value)t.value=this.value.trim();markIdent();};}
1053
+ }catch(_){}
1036
1054
  autoLoadOperatorCreds();
1037
1055
  function stateOf(w){if(!w.known)return 'unknown';if(w.reply)return w.acked?'done · acked':'done · reply waiting';if(w.alive===true)return 'running';if(w.alive===false)return 'exited · no reply';return 'no pid';}
1038
1056
  var _fq=document.getElementById('feed-q');
@@ -1241,7 +1259,7 @@ async function refresh(){
1241
1259
  Array.prototype.forEach.call(document.querySelectorAll('[data-approve]'),function(b){b.onclick=function(){decide(b.getAttribute('data-approve'),'approved');};});
1242
1260
  Array.prototype.forEach.call(document.querySelectorAll('[data-deny]'),function(b){b.onclick=function(){decide(b.getAttribute('data-deny'),'denied');};});
1243
1261
  refreshLaunchMeta();
1244
- try{var _cd=document.getElementById('conn-dot');if(_cd){_cd.style.color='#38d39f';_cd.title='connected: last poll ok';}}catch(_){}
1262
+ try{var _cd=document.getElementById('conn-dot');if(_cd){_cd.style.color='var(--ok)';_cd.title='connected: last poll ok';}}catch(_){}
1245
1263
  }catch(e){try{var _cd2=document.getElementById('conn-dot');if(_cd2){_cd2.style.color='#f85149';_cd2.title='poll failed';}}catch(_){}say('refresh failed: '+e.message);}
1246
1264
  }
1247
1265
  async function ackOne(id){
@@ -1408,15 +1426,31 @@ if(_refBtn){
1408
1426
  }
1409
1427
  async function doLaunch(dry){
1410
1428
  var out=document.getElementById('launch-out');
1411
- var lf=document.getElementById('launch-from').value.trim()||creds().from;
1412
- var lt=document.getElementById('launch-token').value||creds().token;
1429
+ // Identity resolution: advanced manual override wins, else hidden
1430
+ // auto fields (populated from /api/operator-creds), else Settings creds.
1431
+ // Manual fields live in the "advanced" disclosure so non-technical users
1432
+ // never see a token step.
1433
+ function launchCreds(){
1434
+ var manFrom=document.getElementById('launch-from-manual');
1435
+ var manTok=document.getElementById('launch-token-manual');
1436
+ var mf=manFrom?manFrom.value.trim():'';
1437
+ var mt=manTok?manTok.value:'';
1438
+ if(mf||mt) return {from:mf,token:mt};
1439
+ return {
1440
+ from:document.getElementById('launch-from').value.trim()||creds().from,
1441
+ token:document.getElementById('launch-token').value||creds().token
1442
+ };
1443
+ }
1444
+ var lc=launchCreds();
1445
+ var lf=lc.from, lt=lc.token;
1413
1446
  if(!lf||!lt){
1414
1447
  await autoLoadOperatorCreds();
1415
- lf=document.getElementById('launch-from').value.trim()||creds().from;
1416
- lt=document.getElementById('launch-token').value||creds().token;
1448
+ lc=launchCreds();
1449
+ lf=lc.from; lt=lc.token;
1417
1450
  }
1418
- if(!lf||!lt){out.textContent='set launch from+token (or register via CLI: crewbus register --from lead) first';return;}
1419
- var to=document.getElementById('launch-to').value.trim();
1451
+ if(!lf||!lt){out.textContent='starting up — identity not ready yet, retry in a moment';return;}
1452
+ var toEl=document.getElementById('launch-to');
1453
+ var to=toEl?toEl.value.trim():'';
1420
1454
  var count=Number(document.getElementById('launch-count').value)||1;
1421
1455
  var selectedHarnesses = window.__selectedHarnesses && window.__selectedHarnesses.size ? Array.from(window.__selectedHarnesses) : (document.getElementById('launch-harness').value || 'claude').split(',').map(function(s){return s.trim();}).filter(Boolean);
1422
1456
  if(!selectedHarnesses.length)selectedHarnesses=['claude'];
@@ -1587,7 +1621,7 @@ function paletteActivate(m){
1587
1621
  else if(m.action==='copyboard'){copyBoardPath();}
1588
1622
  else if(m.action==='openfolder'){document.getElementById('open-folder-btn').click();}
1589
1623
  else if(m.action==='pairmobile'){
1590
- try{window.parent.postMessage({type:'crewbus:open-pair'},'*');}catch(_){}
1624
+ try{window.parent.postMessage({type:'crewbus:open-pair', dashboard: location.origin},'*');}catch(_){}
1591
1625
  try{window.open('./pair.html','_blank','width=420,height=560');}catch(_){}
1592
1626
  }
1593
1627
  else if(m.action==='refresh'){refresh();}
@@ -1819,7 +1853,7 @@ function copyBoardPath(){
1819
1853
  document.getElementById('copy-board-btn').onclick=copyBoardPath;
1820
1854
  var ppb=document.getElementById('pop-pair-btn');
1821
1855
  if(ppb){ppb.onclick=function(){
1822
- try{window.parent.postMessage({type:'crewbus:open-pair'},'*');}catch(_){}
1856
+ try{window.parent.postMessage({type:'crewbus:open-pair', dashboard: location.origin},'*');}catch(_){}
1823
1857
  try{window.open('./pair.html','_blank','width=420,height=560');}catch(_){}
1824
1858
  };}
1825
1859
  var picb=document.getElementById('pop-install-cli-btn');
@@ -1880,6 +1914,11 @@ function applyTargetCwd(pathStr, notify){
1880
1914
  }
1881
1915
  if(pathStr){
1882
1916
  try{localStorage.setItem('crewbus_last_cwd',pathStr);}catch(_){}
1917
+ // Server-side memory: survives the desktop random-port origin wipe.
1918
+ // Fire-and-forget (local apply above already updated the UI).
1919
+ try{
1920
+ fetch('/api/workspace',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({cwd:pathStr})}).catch(function(){});
1921
+ }catch(_){}
1883
1922
  if(notify)say('Target codebase set to: '+pathStr);
1884
1923
  }
1885
1924
  }
@@ -1910,12 +1949,86 @@ async function promptOrSelectProjectFolder(){
1910
1949
  document.getElementById('open-folder-btn').onclick=promptOrSelectProjectFolder;
1911
1950
  var lcBrowse=document.getElementById('launch-cwd-browse');
1912
1951
  if(lcBrowse)lcBrowse.onclick=promptOrSelectProjectFolder;
1952
+ // Phase-2 board switching (desktop): use another folder's board.
1953
+ // Under Tauri this invokes the switch_board command (validated restart);
1954
+ // everywhere else (plain crewbus web) it explains the CLI equivalent.
1955
+ // After a switch the iframe reloads (new random port) and the operator
1956
+ // token is re-fetched from the NEW board via /api/operator-creds.
1957
+ function boardSwitchMsg(t, isErr){
1958
+ var m=document.getElementById('board-switch-msg');
1959
+ if(!m)return;
1960
+ m.style.display=t?'block':'none';
1961
+ m.textContent=t||'';
1962
+ m.style.color=isErr?'var(--danger)':'var(--dim)';
1963
+ }
1964
+ async function doSwitchBoard(folderPath){
1965
+ var folder=String(folderPath||'').trim();
1966
+ if(!folder){
1967
+ folder=prompt('Switch board: enter the project folder (uses <folder>/.crewbus) or board dir directly:','');
1968
+ if(!folder||!folder.trim())return;
1969
+ folder=folder.trim();
1970
+ }
1971
+ try{
1972
+ var invoke=window.__TAURI__&&window.__TAURI__.core&&window.__TAURI__.core.invoke;
1973
+ if(typeof invoke!=='function'){
1974
+ boardSwitchMsg('Board switching needs the desktop app. CLI equivalent: crewbus serve --board '+folder+'/.crewbus',true);
1975
+ return;
1976
+ }
1977
+ boardSwitchMsg('Switching board — restarting sidecar…');
1978
+ var res=await invoke('switch_board',{path:folder});
1979
+ var board=(res&&res.board)||folder;
1980
+ boardSwitchMsg('Board switched to '+board+' — reloading…');
1981
+ // Clear per-origin identity: the new board has its own lead token.
1982
+ try{
1983
+ var lf=document.getElementById('launch-from');if(lf)lf.value='';
1984
+ var lt=document.getElementById('launch-token');if(lt)lt.value='';
1985
+ }catch(_){}
1986
+ setTimeout(function(){location.reload();},1200);
1987
+ }catch(e){
1988
+ boardSwitchMsg('Switch failed: '+String((e&&e.message)||e||e),true);
1989
+ }
1990
+ }
1991
+ var swBtn=document.getElementById('switch-board-btn');
1992
+ if(swBtn)swBtn.onclick=function(){doSwitchBoard('');};
1993
+ var rsBtn=document.getElementById('reset-board-btn');
1994
+ if(rsBtn)rsBtn.onclick=function(){
1995
+ // Reset = switch back via board_status defaultBoard (no hardcoded path).
1996
+ try{
1997
+ var invoke=window.__TAURI__&&window.__TAURI__.core&&window.__TAURI__.core.invoke;
1998
+ if(typeof invoke!=='function'){boardSwitchMsg('Reset needs the desktop app.',true);return;}
1999
+ boardSwitchMsg('Reading default board…');
2000
+ invoke('board_status').then(function(st){
2001
+ if(st&&st.defaultBoard)doSwitchBoard(st.defaultBoard);
2002
+ else boardSwitchMsg('No default board reported',true);
2003
+ }).catch(function(e){boardSwitchMsg('Reset failed: '+String((e&&e.message)||e),true);});
2004
+ }catch(e){boardSwitchMsg('Reset failed: '+String((e&&e.message)||e),true);}
2005
+ };
1913
2006
  var lcInp=document.getElementById('launch-cwd');
1914
2007
  if(lcInp)lcInp.oninput=function(){applyTargetCwd(this.value,false);};
1915
2008
  try{
1916
2009
  var lastCwd=localStorage.getItem('crewbus_last_cwd');
1917
2010
  if(lastCwd){applyTargetCwd(lastCwd,false);}
1918
2011
  }catch(_){}
2012
+ // Server memory wins over stale/absent localStorage: the desktop origin
2013
+ // (127.0.0.1:RANDOM) changes every launch, wiping per-origin storage.
2014
+ // The board remembers the workspace; a picked CLI folder like sandbox-1
2015
+ // survives restarts. localStorage-only values are pushed up so a fresh
2016
+ // board learns them too.
2017
+ try{
2018
+ fetch('/api/workspace').then(function(r){return r.ok?r.json():null;}).then(function(j){
2019
+ if(!j||!j.cwd)return;
2020
+ var cur=(document.getElementById('launch-cwd')?document.getElementById('launch-cwd').value.trim():'');
2021
+ try{
2022
+ var lsCwd=localStorage.getItem('crewbus_last_cwd')||'';
2023
+ if(lsCwd&&lsCwd!==j.cwd&&(!cur||cur===lsCwd)){
2024
+ // Fresh board that never saw our local pick: teach it.
2025
+ fetch('/api/workspace',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({cwd:lsCwd})}).catch(function(){});
2026
+ return;
2027
+ }
2028
+ }catch(_){}
2029
+ if(!cur)applyTargetCwd(j.cwd,false);
2030
+ }).catch(function(){});
2031
+ }catch(_){}
1919
2032
  document.getElementById('launch-brief').addEventListener('keydown',function(e){
1920
2033
  if((e.ctrlKey||e.metaKey)&&(e.key==='Enter')){
1921
2034
  e.preventDefault();
@@ -2110,15 +2223,67 @@ export async function handleWebDashboardRoute(req, res, url, d) {
2110
2223
  const tokenFile = path.join(d.root, "logs", "lead.token");
2111
2224
  let tok = "";
2112
2225
  try { tok = fs.readFileSync(tokenFile, "utf8").trim(); } catch {}
2226
+ // Verify the file token still matches the agent record: a stale file
2227
+ // (revoked/rotated lead) must not prefill a dead token.
2113
2228
  if (tok) {
2114
- res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2115
- res.end(JSON.stringify({ ok: true, from: "lead", token: tok }));
2116
- return true;
2229
+ try {
2230
+ const rec = readAgent(d, "lead");
2231
+ if (rec && agentTokenMatches(rec, tok)) {
2232
+ res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2233
+ res.end(JSON.stringify({ ok: true, from: "lead", token: tok }));
2234
+ return true;
2235
+ }
2236
+ } catch {}
2117
2237
  }
2118
2238
  res.writeHead(404, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2119
2239
  res.end(JSON.stringify({ ok: false, error: "no lead.token found" }));
2120
2240
  return true;
2121
2241
  }
2242
+ // Workspace memory (server-side, survives the random-port origin wipe):
2243
+ // GET returns the last-set target codebase dir (or default board parent);
2244
+ // POST { cwd } validates + persists it to board.json so desktop + web agree.
2245
+ if (req.method === "GET" && url.pathname === "/api/workspace") {
2246
+ let meta = {};
2247
+ try { meta = readBoardMeta(d) || {}; } catch {}
2248
+ const cwd = (meta && meta.workspaceCwd) || path.dirname(d.root);
2249
+ res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2250
+ res.end(JSON.stringify({ ok: true, cwd, board: d.root }));
2251
+ return true;
2252
+ }
2253
+ if (req.method === "POST" && url.pathname === "/api/workspace") {
2254
+ if (!String(req.headers["content-type"] || "").includes("application/json")) {
2255
+ res.writeHead(415, { "content-type": "application/json; charset=utf-8" });
2256
+ res.end(JSON.stringify({ error: "content-type must be application/json" }));
2257
+ return true;
2258
+ }
2259
+ const { body, error } = await readKillBody(req);
2260
+ if (error) {
2261
+ res.writeHead(error[0], { "content-type": "application/json; charset=utf-8" });
2262
+ res.end(JSON.stringify({ error: error[1] }));
2263
+ return true;
2264
+ }
2265
+ const raw = body && body.cwd !== undefined && body.cwd !== null ? String(body.cwd).trim() : "";
2266
+ const cwd = raw ? path.resolve(raw) : path.dirname(d.root);
2267
+ let ok = false;
2268
+ try { ok = fs.statSync(cwd).isDirectory(); } catch {}
2269
+ if (!ok) {
2270
+ res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
2271
+ res.end(JSON.stringify({ error: `cwd is not a directory: ${cwd}` }));
2272
+ return true;
2273
+ }
2274
+ try {
2275
+ const meta = readBoardMeta(d) || {};
2276
+ meta.workspaceCwd = cwd;
2277
+ writeBoardMeta(d, meta);
2278
+ } catch (e) {
2279
+ res.writeHead(500, { "content-type": "application/json; charset=utf-8" });
2280
+ res.end(JSON.stringify({ error: String((e && e.message) || e) }));
2281
+ return true;
2282
+ }
2283
+ res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2284
+ res.end(JSON.stringify({ ok: true, cwd, board: d.root }));
2285
+ return true;
2286
+ }
2122
2287
  if (req.method === "POST" && url.pathname === "/api/install-cli") {
2123
2288
  const ip = req.socket.remoteAddress || "";
2124
2289
  const isLoop = ip === "127.0.0.1" || ip === "::1" || ip === "::ffff:127.0.0.1";
@@ -2137,6 +2302,41 @@ export async function handleWebDashboardRoute(req, res, url, d) {
2137
2302
  }
2138
2303
  return true;
2139
2304
  }
2305
+ // One-click mobile pairing (plug-and-play): mint a one-time pair URL
2306
+ // server-side and return it for immediate QR render. Loopback-only;
2307
+ // same mint + audit as relay pair qr / serve --pair-qrcode. The dashboard
2308
+ // pair window calls this on open, so normies never touch a terminal.
2309
+ if (req.method === "POST" && url.pathname === "/api/pair-qr") {
2310
+ const ip = req.socket.remoteAddress || "";
2311
+ const isLoop = ip === "127.0.0.1" || ip === "::1" || ip === "::ffff:127.0.0.1" || ip === "localhost";
2312
+ if (!isLoop) {
2313
+ res.writeHead(403, { "content-type": "application/json; charset=utf-8" });
2314
+ res.end(JSON.stringify({ error: "loopback only" }));
2315
+ return true;
2316
+ }
2317
+ try {
2318
+ const token = newPairToken();
2319
+ const salt = newSalt();
2320
+ const now = Date.now();
2321
+ const ttlMs = 10 * 60 * 1000;
2322
+ const doc = {
2323
+ tokenHash: hashToken(token, salt), salt, label: "dashboard-oneclick",
2324
+ createdBy: "lead", createdAt: new Date(now).toISOString(),
2325
+ expiresAt: new Date(now + ttlMs).toISOString(),
2326
+ };
2327
+ fs.mkdirSync(path.join(d.root, "pairing"), { recursive: true });
2328
+ writeJson(pairingPath(d, doc.tokenHash), doc);
2329
+ try { appendChainRecord(d, "lead", "pair", { label: "dashboard-oneclick", expiresAt: doc.expiresAt }); } catch {}
2330
+ const envId = (readRelayState(d) && readRelayState(d).envId) || ("board:" + path.basename(d.root));
2331
+ const pairUrl = buildPairUrl({ envId, routes: [], caps: ["hlc", "tombstones", "channels", "revoked", "holds", "launch"], pairToken: token });
2332
+ res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2333
+ res.end(JSON.stringify({ ok: true, pairUrl, expiresAt: doc.expiresAt, envId }));
2334
+ } catch (err) {
2335
+ res.writeHead(500, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2336
+ res.end(JSON.stringify({ ok: false, error: String((err && err.message) || err) }));
2337
+ }
2338
+ return true;
2339
+ }
2140
2340
  return false;
2141
2341
  }
2142
2342
 
@@ -2146,6 +2346,9 @@ export async function cmdWeb(args) {
2146
2346
  ensureBoardCliShim(d);
2147
2347
  const host = getFlag(args, "--host") || "127.0.0.1";
2148
2348
  const port = Number(getFlag(args, "--port") || 0);
2349
+ // Desktop plug-and-play: same loopback auto-provision as `serve` (see
2350
+ // ensureLoopbackOperator in identity.js). First loopback boot mints `lead`.
2351
+ try { ensureLoopbackOperator(d, host); } catch {}
2149
2352
  if (!(port >= 0 && port < 65536)) fail("--port must be 0-65535 (0 = random)");
2150
2353
  if (host !== "127.0.0.1" && host !== "localhost" && host !== "::1") {
2151
2354
  process.stderr.write(`crewbus: warning: binding non-local ${host} — the dashboard has no auth, anyone who can reach it can read the board\n`);