@gwro/codeaside 0.1.2 → 0.2.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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,39 @@ from [GlanceCode](https://github.com/sousyllc/glancecode) 0.6.2 (glasses app 0.3
5
5
  and does not track later upstream releases. Upstream's own history up to the fork
6
6
  is kept at the end for reference.
7
7
 
8
+ ## 0.2.0
9
+
10
+ A prompt from the glasses now interrupts a working session by default, and three
11
+ faults found against Claude Code 2.1.328 are fixed. Restart the hub to take the
12
+ update (`codeaside service restart`); the fix to the session host loads when its
13
+ last session has ended.
14
+
15
+ - `sendNowWhenWorking`, on by default. A prompt sent from the glasses to a session
16
+ that is working no longer waits in Claude Code's queue for the turn to end: the
17
+ hub submits it with Claude Code's send-now keys (Ctrl+X then Ctrl+S) in place of
18
+ Enter, which stops the turn in progress and sends the prompt at once. It is a
19
+ hub setting, so it works with any build of the glasses app.
20
+ - A session started from the glasses in a folder Claude Code had not been told to
21
+ trust stayed at the trust dialog. Recent versions of Claude Code (seen in
22
+ 2.1.328) move that dialog with the arrow key and no longer with `j`, the key
23
+ the hub pressed. The hub now tries both and confirms only once "Yes, I trust
24
+ this folder" has the focus.
25
+ - The hub did not recognise Claude Code's input box in a session that runs in
26
+ the host: the screen read returns the full-width rule above the box and the
27
+ box as one line, and the hub looked for `❯` at the start of a line. A session
28
+ started from the glasses with a prompt therefore waited 20 seconds before the
29
+ prompt was typed, and a dialog answered or declined at the desk could stay on
30
+ the glasses until the session's next hook. Both now clear as intended. When
31
+ such a dialog is cleared, the session shows as working while the footer says
32
+ a turn is running, and as idle otherwise.
33
+ - A dialog's options could reach the glasses as one option, "Yes 2. No", with
34
+ nothing to choose between. The host read a row as the continuation of the one
35
+ above whenever the terminal had it marked as wrapped, and the mark stays on a
36
+ row after Claude Code redraws it with a line of its own. The host now joins a
37
+ row only to one that is filled to its end. A host that is already running
38
+ keeps the old code until its last session ends, so the hub also separates
39
+ numbered options that arrive on one line.
40
+
8
41
  ## 0.1.2
9
42
 
10
43
  - A message sent with a pasted image while Claude was busy showed on the glasses
package/README.md CHANGED
@@ -240,7 +240,9 @@ being published:
240
240
  | Tap then hold | menu | interrupt, jump to latest, switch model, compact |
241
241
 
242
242
  After a hold, the transcript of what you said waits on screen: tap sends it, hold
243
- records again, double-tap discards it.
243
+ records again, double-tap discards it. Sent to a session that is working, it
244
+ stops the turn in progress and is taken at once; set `sendNowWhenWorking` to
245
+ `false` to have it wait for the turn to end instead.
244
246
 
245
247
  In a session's transcript, `»` marks your prompts and `▷` a tool call; calls to the
246
248
  same tool in a row collapse into one line (`Read ×3`), and only the last three
@@ -315,6 +317,7 @@ See [SECURITY.md](SECURITY.md) and [docs/privacy.md](docs/privacy.md).
315
317
  | `ntfyTopic` | empty | optional phone push through ntfy when a session finishes or needs you |
316
318
  | `preventSleep` | true | keep the PC awake (not the display) while the hub runs and the PC is on AC power |
317
319
  | `bindTailscaleIP` | false | also listen on the raw Tailscale IP over plain HTTP, for development |
320
+ | `sendNowWhenWorking` | true | send a prompt from the glasses at once when its session is working. Claude Code stops the turn in progress and takes the prompt, as it does when you press its send-now keys, Ctrl+X then Ctrl+S; the hub presses those in place of Enter. With `false`, the prompt waits in Claude Code's queue until the turn ends. Set it to `false` if you have bound those keys to something else in Claude Code's `keybindings.json` |
318
321
  | `replyFromStart` | true | on the glasses, hold a reply that arrives while a session is open, and is too long for the screen, at its first line, so you read it from the start; swipe down to read on, tap for the latest. A session you open always starts on its latest lines. With `false`, a session always shows its latest lines, as upstream's app does |
319
322
  | `workingBrightness` | 0 | on the glasses, the text brightness of a session's screen while it is working, from 0 (dimmest) to 4 (full). Below 4, the screen dims while Claude works and returns to full when it finishes or needs you; text you have scrolled to, a held reply, and what you dictate stay at full. With `4`, nothing dims, as in upstream's app |
320
323
  | `latestOnTalk` | true | on the glasses, when you hold to talk in a session that is scrolled up or held at the start of a reply, jump to its latest lines before listening. With `false`, the view stays where it was, as in upstream's app |
@@ -11,7 +11,7 @@ The guide now opens with the one-line setup, then covers:
11
11
 
12
12
  - requirements
13
13
  - pairing the glasses
14
- - troubleshooting`,void 0,40*6e4)])}tick(){const e="00000000-0000-4000-8000-000000000001",t=this.sessions.get(e),n=this.items.get(e);if(!t||!n)return;const r=v1[this.step%v1.length];this.step++,"state"in r?(t.state=r.state,t.activity=r.activity||""):(n.push({...r,key:j1(),ts:T1()}),n.length>40&&n.splice(0,n.length-40)),t.lastActivity=T(),this.notify()}add(e,t){const n=this.items.get(e)||[];n.push(t),this.items.set(e,n)}async loadItems(e){this.items.has(e)||this.items.set(e,[]),this.notify()}async prompt(e,t){const n=this.sessions.get(e);if(!n)throw new Error("no such session");return this.add(e,L("user",t)),n.state="working",n.activity="Thinking",this.notify(),Y(()=>{this.add(e,L("assistant","This is the demo, so nothing ran. Pair the app with your own PC to talk to real Claude Code sessions.")),n.state="idle",n.activity="",n.lastActivity=T(),this.notify()},1500),{}}async interrupt(e){const t=this.sessions.get(e);return t&&(t.state="idle",t.activity="",this.add(e,L("notice","Interrupted")),this.notify()),{}}async choose(e,t,n){const r=this.sessions.get(e),i=["Yes","Yes, and don't ask again for this command","No"];if(!r?.waiting)throw new Error("nothing to answer");return r.waiting=null,n===2?(this.add(e,L("notice","Interrupted")),r.state="idle"):(r.state="working",Y(()=>{this.add(e,L("assistant","Deployed to staging. Open staging.example.com on your phone to check the new onboarding.")),r.state="idle",r.lastActivity=T(),this.notify()},1800)),this.notify(),{chosen:i[n]||"Yes"}}async answer(e,t){return this.prompt(e,t)}async dialog(e){return{dialog:{kind:"permission",options:["Yes","Yes, and don't ask again for this command","No"]}}}async command(e,t){return this.add(e,L("notice",t)),this.notify(),{}}async models(e){const t=this.sessions.get(e)?.agent;return t==="gemini"?[]:t==="codex"?[{id:"gpt-5.5",name:"GPT-5.5"},{id:"gpt-5.5-mini",name:"GPT-5.5 mini"}]:[{id:"opus",name:"Opus"},{id:"sonnet",name:"Sonnet"},{id:"haiku",name:"Haiku"}]}async recent(){return{agents:this.agents,projects:["api-server","mobile-app","docs-site","infra"].map((e,t)=>({cwd:`~/code/${e}`,project:e,mtime:T()-t*36e5})),sessions:[{id:"00000000-0000-4000-8000-000000000010",cwd:"~/code/infra",project:"infra",title:"Rotate the staging certificates",mtime:T()-26*36e5},{id:"00000000-0000-4000-8000-000000000011",cwd:"~/code/api-server",project:"api-server",title:"Add rate limits to the public API",mtime:T()-50*36e5}]}}async launch(e,t,n){const r=e.split("/").pop()||"project",i=n==="codex"||n==="gemini"?n:"claude",s={claude:"claude-opus-5",codex:"gpt-5.5",gemini:"gemini-3.5-flash"}[i],x=Q({id:`00000000-0000-4000-8000-${String(T()).slice(-12)}`,project:r,agent:i,model:s,title:t?"Resumed session":null});return this.sessions.set(x.id,x),this.items.set(x.id,[L("notice",t?"Resumed (demo)":"New session (demo)")]),this.notify(),{session:x}}presence(){return Promise.resolve()}log(e){return Promise.resolve()}async transcribe(e,t=!1){const n="Run the signup tests again and tell me what fails";if(await new Promise(i=>Y(i,t?150:600)),!t)return this.partialCalls=0,n;const r=n.split(" ");return this.partialCalls=Math.min(r.length,this.partialCalls+3),r.slice(0,this.partialCalls).join(" ")}}function H4(o){return o?o.eventType??z.CLICK_EVENT:null}class t2{constructor(e,t){this.emit=e,this.lastDisplayWrite=t}last=new Map;holdEndedAt=0;holding=!1;handle(e){if(e.audioEvent?.audioPcm){this.emit({type:"audio",pcm:e.audioEvent.audioPcm});return}if(e.menuItemClickEvent?.itemID){this.emit({type:"menu",id:e.menuItemClickEvent.itemID});return}const t=H4(e.sysEvent),n=H4(e.textEvent),r=H4(e.listEvent),i=[t,n,r].find(s=>s!==null&&s!==z.CLICK_EVENT)??t??n??r;if(i!=null)switch(i){case z.DOUBLE_CLICK_EVENT:this.debounce("double",350)&&this.emit({type:"doubleTap"});return;case z.SCROLL_TOP_EVENT:case z.SCROLL_BOTTOM_EVENT:{if(Date.now()-this.lastDisplayWrite()<120)return;const s=i===z.SCROLL_TOP_EVENT?"up":"down";this.debounce(`scroll-${s}`,220)&&this.emit({type:s});return}case z.LONG_PRESS_EVENT:!this.holding&&this.debounce("hold",300)&&(this.holding=!0,this.emit({type:"holdStart"}));return;case z.LONG_PRESS_RELEASE_EVENT:this.holding&&(this.holding=!1,this.holdEndedAt=Date.now(),this.emit({type:"holdEnd"}));return;case z.FOREGROUND_ENTER_EVENT:this.debounce("fg",600)&&this.emit({type:"foreground"});return;case z.FOREGROUND_EXIT_EVENT:this.debounce("bg",600)&&this.emit({type:"background"});return;case z.SYSTEM_EXIT_EVENT:case z.ABNORMAL_EXIT_EVENT:this.emit({type:"exit"});return;case z.CLICK_EVENT:if(Date.now()-this.holdEndedAt<500)return;this.debounce("tap",250)&&this.emit({type:"tap"});return}}debounce(e,t){const n=Date.now();return n-(this.last.get(e)||0)<t?!1:(this.last.set(e,n),!0)}}const T4="codeaside.hub",O1=[],e2="0.1.0",n2="CodeAside";async function r2(o){const e=new URLSearchParams(location.search),t=e.get("token")?{url:e.get("hub")||location.origin,token:e.get("token")}:null;if(t)return await o.setLocalStorage(T4,JSON.stringify(t)).catch(()=>!1),history.replaceState(null,"",location.pathname),t;for(const n of[T4,...O1]){const r=await o.getLocalStorage(n).catch(()=>"");if(r)try{const i=JSON.parse(r);if(i.url&&i.token)return i}catch{}}return null}function i2(o){const e=/^\s*(https?:\/\/[^\s#]+)#(\S+)\s*$/.exec(o);return e?{url:e[1].replace(/\/$/,""),token:e[2]}:null}function W(o){return document.getElementById(o)}async function s2(){const o=await D0(),e=await r2(o),t=new URLSearchParams(location.search).has("demo"),n=W("status"),r=W("mirror"),i=W("pair"),s=W("pair-code"),x=W("demo"),c=W("unpair");W("version").textContent=`v${e2} · built Nov 19, 7:19 PM`,i.addEventListener("submit",async v=>{v.preventDefault();const y=i2(s.value);if(!y){n.textContent="That doesn't look like a pairing code. It starts with https:// and has a # before the token.";return}await o.setLocalStorage(T4,JSON.stringify(y)),location.href=location.pathname}),c.addEventListener("click",async()=>{await o.setLocalStorage(T4,"");for(const v of O1)await o.setLocalStorage(v,"").catch(()=>!1);location.href=location.pathname});const a=new N0(o);a.onFrame=v=>{r.textContent=`${v.header}
14
+ - troubleshooting`,void 0,40*6e4)])}tick(){const e="00000000-0000-4000-8000-000000000001",t=this.sessions.get(e),n=this.items.get(e);if(!t||!n)return;const r=v1[this.step%v1.length];this.step++,"state"in r?(t.state=r.state,t.activity=r.activity||""):(n.push({...r,key:j1(),ts:T1()}),n.length>40&&n.splice(0,n.length-40)),t.lastActivity=T(),this.notify()}add(e,t){const n=this.items.get(e)||[];n.push(t),this.items.set(e,n)}async loadItems(e){this.items.has(e)||this.items.set(e,[]),this.notify()}async prompt(e,t){const n=this.sessions.get(e);if(!n)throw new Error("no such session");return this.add(e,L("user",t)),n.state="working",n.activity="Thinking",this.notify(),Y(()=>{this.add(e,L("assistant","This is the demo, so nothing ran. Pair the app with your own PC to talk to real Claude Code sessions.")),n.state="idle",n.activity="",n.lastActivity=T(),this.notify()},1500),{}}async interrupt(e){const t=this.sessions.get(e);return t&&(t.state="idle",t.activity="",this.add(e,L("notice","Interrupted")),this.notify()),{}}async choose(e,t,n){const r=this.sessions.get(e),i=["Yes","Yes, and don't ask again for this command","No"];if(!r?.waiting)throw new Error("nothing to answer");return r.waiting=null,n===2?(this.add(e,L("notice","Interrupted")),r.state="idle"):(r.state="working",Y(()=>{this.add(e,L("assistant","Deployed to staging. Open staging.example.com on your phone to check the new onboarding.")),r.state="idle",r.lastActivity=T(),this.notify()},1800)),this.notify(),{chosen:i[n]||"Yes"}}async answer(e,t){return this.prompt(e,t)}async dialog(e){return{dialog:{kind:"permission",options:["Yes","Yes, and don't ask again for this command","No"]}}}async command(e,t){return this.add(e,L("notice",t)),this.notify(),{}}async models(e){const t=this.sessions.get(e)?.agent;return t==="gemini"?[]:t==="codex"?[{id:"gpt-5.5",name:"GPT-5.5"},{id:"gpt-5.5-mini",name:"GPT-5.5 mini"}]:[{id:"opus",name:"Opus"},{id:"sonnet",name:"Sonnet"},{id:"haiku",name:"Haiku"}]}async recent(){return{agents:this.agents,projects:["api-server","mobile-app","docs-site","infra"].map((e,t)=>({cwd:`~/code/${e}`,project:e,mtime:T()-t*36e5})),sessions:[{id:"00000000-0000-4000-8000-000000000010",cwd:"~/code/infra",project:"infra",title:"Rotate the staging certificates",mtime:T()-26*36e5},{id:"00000000-0000-4000-8000-000000000011",cwd:"~/code/api-server",project:"api-server",title:"Add rate limits to the public API",mtime:T()-50*36e5}]}}async launch(e,t,n){const r=e.split("/").pop()||"project",i=n==="codex"||n==="gemini"?n:"claude",s={claude:"claude-opus-5",codex:"gpt-5.5",gemini:"gemini-3.5-flash"}[i],x=Q({id:`00000000-0000-4000-8000-${String(T()).slice(-12)}`,project:r,agent:i,model:s,title:t?"Resumed session":null});return this.sessions.set(x.id,x),this.items.set(x.id,[L("notice",t?"Resumed (demo)":"New session (demo)")]),this.notify(),{session:x}}presence(){return Promise.resolve()}log(e){return Promise.resolve()}async transcribe(e,t=!1){const n="Run the signup tests again and tell me what fails";if(await new Promise(i=>Y(i,t?150:600)),!t)return this.partialCalls=0,n;const r=n.split(" ");return this.partialCalls=Math.min(r.length,this.partialCalls+3),r.slice(0,this.partialCalls).join(" ")}}function H4(o){return o?o.eventType??z.CLICK_EVENT:null}class t2{constructor(e,t){this.emit=e,this.lastDisplayWrite=t}last=new Map;holdEndedAt=0;holding=!1;handle(e){if(e.audioEvent?.audioPcm){this.emit({type:"audio",pcm:e.audioEvent.audioPcm});return}if(e.menuItemClickEvent?.itemID){this.emit({type:"menu",id:e.menuItemClickEvent.itemID});return}const t=H4(e.sysEvent),n=H4(e.textEvent),r=H4(e.listEvent),i=[t,n,r].find(s=>s!==null&&s!==z.CLICK_EVENT)??t??n??r;if(i!=null)switch(i){case z.DOUBLE_CLICK_EVENT:this.debounce("double",350)&&this.emit({type:"doubleTap"});return;case z.SCROLL_TOP_EVENT:case z.SCROLL_BOTTOM_EVENT:{if(Date.now()-this.lastDisplayWrite()<120)return;const s=i===z.SCROLL_TOP_EVENT?"up":"down";this.debounce(`scroll-${s}`,220)&&this.emit({type:s});return}case z.LONG_PRESS_EVENT:!this.holding&&this.debounce("hold",300)&&(this.holding=!0,this.emit({type:"holdStart"}));return;case z.LONG_PRESS_RELEASE_EVENT:this.holding&&(this.holding=!1,this.holdEndedAt=Date.now(),this.emit({type:"holdEnd"}));return;case z.FOREGROUND_ENTER_EVENT:this.debounce("fg",600)&&this.emit({type:"foreground"});return;case z.FOREGROUND_EXIT_EVENT:this.debounce("bg",600)&&this.emit({type:"background"});return;case z.SYSTEM_EXIT_EVENT:case z.ABNORMAL_EXIT_EVENT:this.emit({type:"exit"});return;case z.CLICK_EVENT:if(Date.now()-this.holdEndedAt<500)return;this.debounce("tap",250)&&this.emit({type:"tap"});return}}debounce(e,t){const n=Date.now();return n-(this.last.get(e)||0)<t?!1:(this.last.set(e,n),!0)}}const T4="codeaside.hub",O1=[],e2="0.1.0",n2="CodeAside";async function r2(o){const e=new URLSearchParams(location.search),t=e.get("token")?{url:e.get("hub")||location.origin,token:e.get("token")}:null;if(t)return await o.setLocalStorage(T4,JSON.stringify(t)).catch(()=>!1),history.replaceState(null,"",location.pathname),t;for(const n of[T4,...O1]){const r=await o.getLocalStorage(n).catch(()=>"");if(r)try{const i=JSON.parse(r);if(i.url&&i.token)return i}catch{}}return null}function i2(o){const e=/^\s*(https?:\/\/[^\s#]+)#(\S+)\s*$/.exec(o);return e?{url:e[1].replace(/\/$/,""),token:e[2]}:null}function W(o){return document.getElementById(o)}async function s2(){const o=await D0(),e=await r2(o),t=new URLSearchParams(location.search).has("demo"),n=W("status"),r=W("mirror"),i=W("pair"),s=W("pair-code"),x=W("demo"),c=W("unpair");W("version").textContent=`v${e2} · built Nov 19, 9:22 PM`,i.addEventListener("submit",async v=>{v.preventDefault();const y=i2(s.value);if(!y){n.textContent="That doesn't look like a pairing code. It starts with https:// and has a # before the token.";return}await o.setLocalStorage(T4,JSON.stringify(y)),location.href=location.pathname}),c.addEventListener("click",async()=>{await o.setLocalStorage(T4,"");for(const v of O1)await o.setLocalStorage(v,"").catch(()=>!1);location.href=location.pathname});const a=new N0(o);a.onFrame=v=>{r.textContent=`${v.header}
15
15
  ${"─".repeat(40)}
16
16
  ${v.body.join(`
17
17
  `)}`};let h=!1;const l=async v=>{if(h)return;h=!0;const y=new U0(o,a,v);f.target=g=>void y.handle(g),v.subscribe(()=>{v instanceof w1?n.textContent="Demo mode: sample sessions, nothing runs. Pair to use your own machine.":n.textContent=v.connected?`Connected to ${v.cfg.url} · ${v.sessions.size} session(s)`:`Hub unreachable at ${v.cfg.url}${v.lastError?` (${v.lastError})`:""}`}),await v.connect(),v.presence(),l4(()=>void v.presence(),3e4),_1()&&v.log("timers: SDK shadow timers active, using native timers alongside")},f={target:v=>{v.type==="tap"&&w(),v.type==="doubleTap"&&o.shutDownPageContainer(1)}},d=new t2(v=>f.target(v),()=>a.lastWriteAt);o.onEvenHubEvent(v=>d.handle(v));const w=async()=>{i.hidden=!0,x.hidden=!0,c.hidden=!0,await l(new w1)};if(x.addEventListener("click",()=>void w()),e&&!t){x.hidden=!0,await l(new N1(e));return}if(t){await w();return}c.hidden=!0,i.hidden=!1,x.hidden=!1,n.textContent="Not paired. On your computer run `codeaside pair` and paste the code below, or try the demo.",a.show({header:k(n2,"not paired",U),body:j(`Pair with the hub on your computer: run codeaside pair and paste the code on your phone.
@@ -17,7 +17,7 @@
17
17
  .help { color: #8a8a8a; font-size: 13px; }
18
18
  .help b { color: #bdbdbd; font-weight: 600; }
19
19
  </style>
20
- <script type="module" crossorigin src="./assets/index-BSC7KG_n.js"></script>
20
+ <script type="module" crossorigin src="./assets/index-kVuHuJ35.js"></script>
21
21
  </head>
22
22
  <body>
23
23
  <main>
@@ -385,6 +385,9 @@ Things the implementation learned that the design above didn't predict:
385
385
  model picker) don't move. The vi keys `j`/`k` do. The host exposes them as
386
386
  `MenuDown`/`MenuUp`, and the trust handler checks that "Yes, I trust" has the
387
387
  focus before pressing Enter. Only menus use them; in the prompt box they'd type.
388
+ Later versions turned this round: in Claude Code 2.1.328 the trust dialog moves
389
+ on the arrow key and ignores `j`. The trust handler now tries the arrow and
390
+ then the vi key, looking at the focus before each press, since the menu wraps.
388
391
  - **A lone Escape is delayed.** conhost holds a bare ESC on the input pipe waiting
389
392
  for a sequence, about a second. Sent as a win32-input-mode key record
390
393
  (`ESC [ 27;1;27;1;0;1 _` down, then up) it is delivered at once, so `Escape` in
@@ -520,8 +523,36 @@ when the process id saved for it had exited, and came back, as "starting", only
520
523
  its next hook. A pane session is now restored whatever that id says, and the first
521
524
  sweep asks the host, as the sweep itself already did.
522
525
 
526
+ **Sending over a turn in progress** (`sendNowWhenWorking`). Enter in Claude Code's
527
+ input box queues a prompt while a turn runs, and the prompt is only read when the
528
+ turn ends. Claude Code has a second way to submit, `chat:sendNow`, bound to Ctrl+X
529
+ then Ctrl+S: it stops the turn and sends what is in the box. For a session the hub
530
+ has as working, the hub ends the prompt with those two bytes (`0x18 0x13`) in
531
+ place of Enter, and ConPTY delivers them as the key presses. On an idle session
532
+ the chord submits as Enter does, so a state that is a moment out of date costs
533
+ nothing. They go through the host's `write`, not its key table, so a host that is
534
+ already running needs no new code.
535
+
523
536
  Smaller findings:
524
537
 
538
+ - A rule that fills the row comes back from the host's screen read joined to the
539
+ row under it, as one wrapped row, so the input box reads `────…────❯ text`.
540
+ `readDialog` looked for `❯` at the start of a line and never saw the box:
541
+ `waitForInput` always ran out its 20 seconds, and the sweep never cleared a
542
+ dialog answered at the desk. It now puts the line break back before reading.
543
+ The input box is also on screen during a turn, so the sweep takes "esc to
544
+ interrupt" in the footer as the sign that the session is working, not idle.
545
+ - The terminal's "wrapped" mark on a row can't be trusted on its own. It is set
546
+ when text runs over from the row above, and a redraw that moves the cursor to
547
+ the row and writes a short line of its own leaves it set. Claude Code redraws
548
+ that way, and its input box sets the mark twice a frame, under each full-width
549
+ rule. The host's screen read joined every marked row to the one above, so a
550
+ dialog drawn where the box had been came back as `❯ 1. Yes 2. No` and the
551
+ glasses showed one option. The read now joins a row only when the one above is
552
+ filled to its end, allowing one blank cell: ConPTY pads a short row with
553
+ spaces, so more than one is the end of a line. Because a running host keeps
554
+ its code, `readDialog` also splits numbered options that arrive on one line.
555
+
525
556
  - `cmd.exe` splits an unquoted argument at `&`. The sideload QR code lost the token
526
557
  that way, and the shell tried to run `token=...`. Commands that go through the
527
558
  shell on Windows, as `npx` must, are built as one quoted line.
package/host/client.mjs CHANGED
@@ -29,9 +29,10 @@ export const KEYS = {
29
29
  // Application cursor mode (DECCKM) variants; the host picks by the terminal's mode.
30
30
  "Up:app": "\x1bOA",
31
31
  "Down:app": "\x1bOB",
32
- // Claude Code's menus (the trust dialog, model picker) ignore arrow keys that
33
- // arrive through a ConPTY input pipe, but take vi keys. Only for menus: in the
34
- // prompt box these type letters.
32
+ // Claude Code's menus (the trust dialog, model picker) used to ignore arrow keys
33
+ // that arrive through a ConPTY input pipe and take vi keys. By 2.1.328 the trust
34
+ // dialog is the other way round, so its handler tries both. Only for menus: in
35
+ // the prompt box these type letters.
35
36
  MenuUp: "k",
36
37
  MenuDown: "j",
37
38
  };
package/host/host.mjs CHANGED
@@ -1,336 +1,347 @@
1
- // The session host: the tmux server of this port. Runs Claude Code in ConPTY
2
- // pseudo-consoles, keeps a headless terminal screen for each, and lets the hub
3
- // and the CLI type into them, read them back, and attach a console, over a
4
- // user-private named pipe. Kept small and separate from the hub so a hub restart
5
- // never ends a session.
6
- import { createServer } from "node:net";
7
- import { appendFileSync, mkdirSync } from "node:fs";
8
- import { dirname, resolve } from "node:path";
9
- import { randomBytes } from "node:crypto";
10
- import { fileURLToPath } from "node:url";
11
- import pty from "@lydell/node-pty";
12
- import xterm from "@xterm/headless";
13
- import serialize from "@xterm/addon-serialize";
14
- import { KEYS, defaultPipe } from "./client.mjs";
15
-
16
- const { Terminal } = xterm;
17
- const { SerializeAddon } = serialize;
18
-
19
- const SCROLLBACK = 5000;
20
- const DEFAULT_SIZE = { cols: 200, rows: 50 }; // for sessions nobody is attached to
21
- const MIN_SIZE = { cols: 20, rows: 5 };
22
- const IDLE_EXIT_MS = 10_000; // no sessions and no clients for this long: exit, like tmux
23
- // A host started from inside a Claude Code session (a hub run from Claude's shell)
24
- // would pass these on, and Claude Code then treats the new session as a nested
25
- // child: no transcript, different hooks. Each session is its own.
26
- const NESTED_SESSION_MARKERS = /^(CLAUDECODE|CLAUDE_CODE_(CHILD_SESSION|SESSION_ID|SESSION_ATTENDED|ENTRYPOINT|EXECPATH|MESSAGING_SOCKET|MESSAGING_TOKEN|BRIDGE_SESSION_ID|SSE_PORT))$/;
27
- const STARTUP_GRACE_MS = 30_000;
28
-
29
- export function startHost({ pipe = defaultPipe(), log = () => {}, exitWhenIdle = true } = {}) {
30
- /** @type {Map<string, Session>} */
31
- const sessions = new Map();
32
- const connections = new Set();
33
- let lastActivity = Date.now();
34
- let everHadSession = false;
35
-
36
- class Session {
37
- constructor({ name, cwd, cmd, args, env, cols, rows }) {
38
- this.id = randomBytes(4).toString("hex");
39
- this.name = name;
40
- this.cwd = cwd;
41
- this.cmd = cmd;
42
- this.args = args;
43
- this.title = "";
44
- this.startedAt = Date.now();
45
- this.exitCode = null;
46
- this.cols = cols;
47
- this.rows = rows;
48
- /** @type {Set<import("node:net").Socket>} */
49
- this.attached = new Set();
50
- this.term = new Terminal({ cols, rows, scrollback: SCROLLBACK, allowProposedApi: true });
51
- this.serializer = new SerializeAddon();
52
- this.term.loadAddon(this.serializer);
53
- this.term.onTitleChange((t) => {
54
- this.title = t;
55
- });
56
- const fullEnv = {};
57
- for (const [k, v] of Object.entries({ ...process.env, ...env })) if (v !== undefined && v !== null && !NESTED_SESSION_MARKERS.test(k)) fullEnv[k] = String(v);
58
- fullEnv.CODEASIDE_HOST = pipe;
59
- fullEnv.CODEASIDE_PANE = this.id;
60
- this.pty = pty.spawn(cmd, args, { name: "xterm-256color", cols, rows, cwd, env: fullEnv, useConpty: true });
61
- this.pty.onData((data) => {
62
- this.term.write(data);
63
- for (const s of this.attached) if (!s.destroyed) s.write(data);
64
- });
65
- this.pty.onExit(({ exitCode }) => {
66
- this.exitCode = exitCode ?? 0;
67
- log(`session ${this.name} (${this.id}) exited ${this.exitCode}`);
68
- if (this.exitCode !== 0) {
69
- // A failed start is only ever diagnosable from what it printed.
70
- const tail = this.screen(12).split("\n").filter((l) => l.trim());
71
- if (tail.length) log(` last lines:\n ${tail.join("\n ")}`);
72
- }
73
- for (const s of this.attached) {
74
- if (s.destroyed) continue;
75
- s.write(`\r\n\x1b[0m[codeaside] session ended (exit ${this.exitCode})\r\n`);
76
- s.end();
77
- }
78
- this.attached.clear();
79
- sessions.delete(this.id);
80
- touch();
81
- // node-pty leaves the input pipe and its conout worker open after a natural
82
- // exit; kill() on the finished pty releases them.
83
- setTimeout(() => {
84
- try {
85
- this.pty.kill();
86
- } catch {
87
- /* already released */
88
- }
89
- }, 50).unref?.();
90
- });
91
- }
92
-
93
- get pid() {
94
- return this.pty.pid || null;
95
- }
96
-
97
- get alive() {
98
- return this.exitCode === null;
99
- }
100
-
101
- /** The last `lines` logical lines of the screen and scrollback, wrapped rows joined. */
102
- screen(lines = 60) {
103
- // Scrollback plus the viewport, like `capture-pane -J`, minus the blank
104
- // rows under the last thing drawn, so a short screen isn't all blanks.
105
- const b = this.term.buffer.active;
106
- const out = [];
107
- for (let i = 0; i < b.length; i++) {
108
- const line = b.getLine(i);
109
- if (!line) continue;
110
- const text = line.translateToString(true).replace(/\s+$/, "");
111
- if (line.isWrapped && out.length) out[out.length - 1] += text;
112
- else out.push(text);
113
- }
114
- while (out.length && !out[out.length - 1]) out.pop();
115
- return out.slice(-lines).join("\n");
116
- }
117
-
118
- write(data) {
119
- this.pty.write(data);
120
- }
121
-
122
- key(name) {
123
- let seq = KEYS[name];
124
- if (seq === undefined) throw hostError(400, `key not allowed: ${name}`);
125
- if ((name === "Up" || name === "Down") && this.term.modes.applicationCursorKeysMode) seq = KEYS[`${name}:app`];
126
- this.pty.write(seq);
127
- }
128
-
129
- resize(cols, rows) {
130
- cols = Math.max(MIN_SIZE.cols, Math.floor(cols) || DEFAULT_SIZE.cols);
131
- rows = Math.max(MIN_SIZE.rows, Math.floor(rows) || DEFAULT_SIZE.rows);
132
- if (cols === this.cols && rows === this.rows) return;
133
- this.cols = cols;
134
- this.rows = rows;
135
- this.term.resize(cols, rows);
136
- this.pty.resize(cols, rows);
137
- }
138
-
139
- attach(socket, cols, rows) {
140
- this.attached.add(socket);
141
- // Paint the current screen, then let ConPTY repaint for the client's size.
142
- socket.write("\x1b[H\x1b[2J" + this.serializer.serialize({ scrollback: 0 }));
143
- if (this.title) socket.write(`\x1b]0;${this.title}\x07`);
144
- this.resize(cols, rows);
145
- socket.on("close", () => this.attached.delete(socket));
146
- }
147
-
148
- kill() {
149
- try {
150
- this.pty.kill();
151
- } catch {
152
- /* already gone */
153
- }
154
- }
155
-
156
- summary() {
157
- return { id: this.id, name: this.name, cwd: this.cwd, pid: this.pid, title: this.title, attached: this.attached.size, alive: this.alive, startedAt: this.startedAt, cols: this.cols, rows: this.rows };
158
- }
159
- }
160
-
161
- function hostError(code, message) {
162
- return Object.assign(new Error(message), { code });
163
- }
164
-
165
- function touch() {
166
- lastActivity = Date.now();
167
- }
168
-
169
- function uniqueName(base) {
170
- const clean = (base || "claude").replace(/[^A-Za-z0-9_-]/g, "-").slice(0, 24) || "claude";
171
- const taken = new Set([...sessions.values()].map((s) => s.name));
172
- let name = clean;
173
- for (let n = 2; taken.has(name); n++) name = `${clean}-${n}`;
174
- return name;
175
- }
176
-
177
- function sessionOr404(id) {
178
- const s = sessions.get(id) || [...sessions.values()].find((x) => x.name === id);
179
- if (!s) throw hostError(404, `no session ${id}`);
180
- return s;
181
- }
182
-
183
- const ops = {
184
- ping: () => ({ pid: process.pid, sessions: sessions.size }),
185
- list: () => ({ sessions: [...sessions.values()].map((s) => s.summary()) }),
186
- new({ name, cwd, cmd, args = [], env = {}, cols, rows }) {
187
- if (!cmd) throw hostError(400, "cmd required");
188
- if (!cwd) throw hostError(400, "cwd required");
189
- const s = new Session({ name: uniqueName(name), cwd, cmd, args, env, cols: cols || DEFAULT_SIZE.cols, rows: rows || DEFAULT_SIZE.rows });
190
- sessions.set(s.id, s);
191
- everHadSession = true;
192
- touch();
193
- log(`new session ${s.name} (${s.id}): ${cmd} ${args.join(" ")} in ${cwd}`);
194
- return { id: s.id, name: s.name, pid: s.pid };
195
- },
196
- alive({ session }) {
197
- const s = sessions.get(session);
198
- return { alive: !!s && s.alive, name: s?.name, pid: s?.pid ?? null };
199
- },
200
- screen({ session, lines = 60 }) {
201
- return { text: sessionOr404(session).screen(Math.min(Number(lines) || 60, SCROLLBACK)) };
202
- },
203
- write({ session, data }) {
204
- sessionOr404(session).write(String(data ?? ""));
205
- return {};
206
- },
207
- key({ session, key }) {
208
- sessionOr404(session).key(String(key));
209
- return {};
210
- },
211
- resize({ session, cols, rows }) {
212
- sessionOr404(session).resize(Number(cols), Number(rows));
213
- return {};
214
- },
215
- kill({ session }) {
216
- sessionOr404(session).kill();
217
- return {};
218
- },
219
- };
220
-
221
- const server = createServer((socket) => {
222
- connections.add(socket);
223
- touch();
224
- let buf = "";
225
- let attachedTo = null;
226
- socket.setNoDelay?.(true);
227
- socket.on("data", (chunk) => {
228
- buf += chunk.toString("utf8");
229
- let idx;
230
- while ((idx = buf.indexOf("\n")) >= 0) {
231
- const line = buf.slice(0, idx);
232
- buf = buf.slice(idx + 1);
233
- if (!line.trim()) continue;
234
- let msg;
235
- try {
236
- msg = JSON.parse(line);
237
- } catch {
238
- continue;
239
- }
240
- if (attachedTo) {
241
- if (msg.op === "input" && typeof msg.data === "string") attachedTo.write(Buffer.from(msg.data, "base64").toString("utf8"));
242
- else if (msg.op === "resize") attachedTo.resize(Number(msg.cols), Number(msg.rows));
243
- else if (msg.op === "detach") socket.end();
244
- continue;
245
- }
246
- if (msg.op === "attach") {
247
- try {
248
- const s = sessionOr404(msg.session);
249
- socket.write(JSON.stringify({ id: msg.id, ok: true, name: s.name }) + "\n");
250
- attachedTo = s;
251
- s.attach(socket, Number(msg.cols) || s.cols, Number(msg.rows) || s.rows);
252
- } catch (err) {
253
- socket.end(JSON.stringify({ id: msg.id, ok: false, error: err.message, code: err.code }) + "\n");
254
- }
255
- continue;
256
- }
257
- const fn = ops[msg.op];
258
- let reply;
259
- try {
260
- if (!fn) throw hostError(400, `unknown op ${msg.op}`);
261
- reply = { id: msg.id, ok: true, result: fn(msg) };
262
- } catch (err) {
263
- reply = { id: msg.id, ok: false, error: err.message, code: err.code || 500 };
264
- }
265
- if (!socket.destroyed) socket.write(JSON.stringify(reply) + "\n");
266
- }
267
- });
268
- socket.on("close", () => {
269
- connections.delete(socket);
270
- touch();
271
- });
272
- socket.on("error", () => {});
273
- });
274
-
275
- server.listen(pipe, () => log(`host listening on ${pipe}`));
276
-
277
- let idleTimer = null;
278
- if (exitWhenIdle) {
279
- const started = Date.now();
280
- idleTimer = setInterval(() => {
281
- const quietFor = Date.now() - lastActivity;
282
- const pastGrace = everHadSession || Date.now() - started > STARTUP_GRACE_MS;
283
- // Control connections don't count: the hub keeps one open for as long as it
284
- // runs, and a host with nothing to hold should still make way for a newer one.
285
- if (sessions.size === 0 && quietFor > IDLE_EXIT_MS && pastGrace) {
286
- log("no sessions and no clients; exiting");
287
- close();
288
- process.exit(0);
289
- }
290
- }, 2000);
291
- }
292
-
293
- function close() {
294
- clearInterval(idleTimer);
295
- for (const s of connections) s.destroy();
296
- server.close();
297
- }
298
-
299
- return { server, sessions, pipe, close };
300
- }
301
-
302
- // ---------- standalone ----------
303
- const isMain = process.argv[1] && resolve(process.argv[1]).toLowerCase() === resolve(fileURLToPath(import.meta.url)).toLowerCase();
304
- if (isMain) {
305
- const argv = process.argv.slice(2);
306
- const arg = (flag) => {
307
- const i = argv.indexOf(flag);
308
- return i >= 0 ? argv[i + 1] : null;
309
- };
310
- const pipe = arg("--pipe") || defaultPipe();
311
- const logFile = arg("--log");
312
- const log = (msg) => {
313
- const line = `[${new Date().toISOString()}] ${msg}\n`;
314
- if (logFile) {
315
- try {
316
- mkdirSync(dirname(logFile), { recursive: true });
317
- appendFileSync(logFile, line);
318
- } catch {
319
- /* no log */
320
- }
321
- } else process.stdout.write(line);
322
- };
323
- const host = startHost({ pipe, log });
324
- host.server.on("error", (err) => {
325
- log(`cannot listen on ${pipe}: ${err.message}`);
326
- process.exit(1);
327
- });
328
- process.on("uncaughtException", (err) => log(`uncaught: ${err.stack || err.message}`));
329
- const stop = () => {
330
- for (const s of host.sessions.values()) s.kill();
331
- host.close();
332
- process.exit(0);
333
- };
334
- process.on("SIGINT", stop);
335
- process.on("SIGTERM", stop);
336
- }
1
+ // The session host: the tmux server of this port. Runs Claude Code in ConPTY
2
+ // pseudo-consoles, keeps a headless terminal screen for each, and lets the hub
3
+ // and the CLI type into them, read them back, and attach a console, over a
4
+ // user-private named pipe. Kept small and separate from the hub so a hub restart
5
+ // never ends a session.
6
+ import { createServer } from "node:net";
7
+ import { appendFileSync, mkdirSync } from "node:fs";
8
+ import { dirname, resolve } from "node:path";
9
+ import { randomBytes } from "node:crypto";
10
+ import { fileURLToPath } from "node:url";
11
+ import pty from "@lydell/node-pty";
12
+ import xterm from "@xterm/headless";
13
+ import serialize from "@xterm/addon-serialize";
14
+ import { KEYS, defaultPipe } from "./client.mjs";
15
+
16
+ const { Terminal } = xterm;
17
+ const { SerializeAddon } = serialize;
18
+
19
+ const SCROLLBACK = 5000;
20
+ const DEFAULT_SIZE = { cols: 200, rows: 50 }; // for sessions nobody is attached to
21
+ const MIN_SIZE = { cols: 20, rows: 5 };
22
+ const IDLE_EXIT_MS = 10_000; // no sessions and no clients for this long: exit, like tmux
23
+ // A host started from inside a Claude Code session (a hub run from Claude's shell)
24
+ // would pass these on, and Claude Code then treats the new session as a nested
25
+ // child: no transcript, different hooks. Each session is its own.
26
+ const NESTED_SESSION_MARKERS = /^(CLAUDECODE|CLAUDE_CODE_(CHILD_SESSION|SESSION_ID|SESSION_ATTENDED|ENTRYPOINT|EXECPATH|MESSAGING_SOCKET|MESSAGING_TOKEN|BRIDGE_SESSION_ID|SSE_PORT))$/;
27
+ const STARTUP_GRACE_MS = 30_000;
28
+
29
+ export function startHost({ pipe = defaultPipe(), log = () => {}, exitWhenIdle = true } = {}) {
30
+ /** @type {Map<string, Session>} */
31
+ const sessions = new Map();
32
+ const connections = new Set();
33
+ let lastActivity = Date.now();
34
+ let everHadSession = false;
35
+
36
+ class Session {
37
+ constructor({ name, cwd, cmd, args, env, cols, rows }) {
38
+ this.id = randomBytes(4).toString("hex");
39
+ this.name = name;
40
+ this.cwd = cwd;
41
+ this.cmd = cmd;
42
+ this.args = args;
43
+ this.title = "";
44
+ this.startedAt = Date.now();
45
+ this.exitCode = null;
46
+ this.cols = cols;
47
+ this.rows = rows;
48
+ /** @type {Set<import("node:net").Socket>} */
49
+ this.attached = new Set();
50
+ this.term = new Terminal({ cols, rows, scrollback: SCROLLBACK, allowProposedApi: true });
51
+ this.serializer = new SerializeAddon();
52
+ this.term.loadAddon(this.serializer);
53
+ this.term.onTitleChange((t) => {
54
+ this.title = t;
55
+ });
56
+ const fullEnv = {};
57
+ for (const [k, v] of Object.entries({ ...process.env, ...env })) if (v !== undefined && v !== null && !NESTED_SESSION_MARKERS.test(k)) fullEnv[k] = String(v);
58
+ fullEnv.CODEASIDE_HOST = pipe;
59
+ fullEnv.CODEASIDE_PANE = this.id;
60
+ this.pty = pty.spawn(cmd, args, { name: "xterm-256color", cols, rows, cwd, env: fullEnv, useConpty: true });
61
+ this.pty.onData((data) => {
62
+ this.term.write(data);
63
+ for (const s of this.attached) if (!s.destroyed) s.write(data);
64
+ });
65
+ this.pty.onExit(({ exitCode }) => {
66
+ this.exitCode = exitCode ?? 0;
67
+ log(`session ${this.name} (${this.id}) exited ${this.exitCode}`);
68
+ if (this.exitCode !== 0) {
69
+ // A failed start is only ever diagnosable from what it printed.
70
+ const tail = this.screen(12).split("\n").filter((l) => l.trim());
71
+ if (tail.length) log(` last lines:\n ${tail.join("\n ")}`);
72
+ }
73
+ for (const s of this.attached) {
74
+ if (s.destroyed) continue;
75
+ s.write(`\r\n\x1b[0m[codeaside] session ended (exit ${this.exitCode})\r\n`);
76
+ s.end();
77
+ }
78
+ this.attached.clear();
79
+ sessions.delete(this.id);
80
+ touch();
81
+ // node-pty leaves the input pipe and its conout worker open after a natural
82
+ // exit; kill() on the finished pty releases them.
83
+ setTimeout(() => {
84
+ try {
85
+ this.pty.kill();
86
+ } catch {
87
+ /* already released */
88
+ }
89
+ }, 50).unref?.();
90
+ });
91
+ }
92
+
93
+ get pid() {
94
+ return this.pty.pid || null;
95
+ }
96
+
97
+ get alive() {
98
+ return this.exitCode === null;
99
+ }
100
+
101
+ /** The last `lines` logical lines of the screen and scrollback, wrapped rows joined. */
102
+ screen(lines = 60) {
103
+ // Scrollback plus the viewport, like `capture-pane -J`, minus the blank
104
+ // rows under the last thing drawn, so a short screen isn't all blanks.
105
+ const b = this.term.buffer.active;
106
+ const out = [];
107
+ // A row's wrapped mark outlives the text that wrapped onto it: a redraw that
108
+ // moves the cursor there and writes a short line of its own leaves it set,
109
+ // and "1. Yes" and "2. No" would come back as one line. A row only continues
110
+ // the one above if that one is filled to its end. One blank cell there may be
111
+ // a space between words, or the cell a wide character didn't fit in; ConPTY
112
+ // pads a short row with spaces, so more than one is the end of a line.
113
+ let aboveIsFull = false;
114
+ let aboveSpaces = ""; // what the row above ends in, kept when its line goes on
115
+ for (let i = 0; i < b.length; i++) {
116
+ const line = b.getLine(i);
117
+ if (!line) continue;
118
+ const whole = line.translateToString(false);
119
+ const text = whole.replace(/\s+$/, "");
120
+ if (line.isWrapped && aboveIsFull && out.length) out[out.length - 1] += aboveSpaces + text;
121
+ else out.push(text);
122
+ aboveSpaces = whole.slice(text.length);
123
+ aboveIsFull = text !== "" && aboveSpaces.length <= 1;
124
+ }
125
+ while (out.length && !out[out.length - 1]) out.pop();
126
+ return out.slice(-lines).join("\n");
127
+ }
128
+
129
+ write(data) {
130
+ this.pty.write(data);
131
+ }
132
+
133
+ key(name) {
134
+ let seq = KEYS[name];
135
+ if (seq === undefined) throw hostError(400, `key not allowed: ${name}`);
136
+ if ((name === "Up" || name === "Down") && this.term.modes.applicationCursorKeysMode) seq = KEYS[`${name}:app`];
137
+ this.pty.write(seq);
138
+ }
139
+
140
+ resize(cols, rows) {
141
+ cols = Math.max(MIN_SIZE.cols, Math.floor(cols) || DEFAULT_SIZE.cols);
142
+ rows = Math.max(MIN_SIZE.rows, Math.floor(rows) || DEFAULT_SIZE.rows);
143
+ if (cols === this.cols && rows === this.rows) return;
144
+ this.cols = cols;
145
+ this.rows = rows;
146
+ this.term.resize(cols, rows);
147
+ this.pty.resize(cols, rows);
148
+ }
149
+
150
+ attach(socket, cols, rows) {
151
+ this.attached.add(socket);
152
+ // Paint the current screen, then let ConPTY repaint for the client's size.
153
+ socket.write("\x1b[H\x1b[2J" + this.serializer.serialize({ scrollback: 0 }));
154
+ if (this.title) socket.write(`\x1b]0;${this.title}\x07`);
155
+ this.resize(cols, rows);
156
+ socket.on("close", () => this.attached.delete(socket));
157
+ }
158
+
159
+ kill() {
160
+ try {
161
+ this.pty.kill();
162
+ } catch {
163
+ /* already gone */
164
+ }
165
+ }
166
+
167
+ summary() {
168
+ return { id: this.id, name: this.name, cwd: this.cwd, pid: this.pid, title: this.title, attached: this.attached.size, alive: this.alive, startedAt: this.startedAt, cols: this.cols, rows: this.rows };
169
+ }
170
+ }
171
+
172
+ function hostError(code, message) {
173
+ return Object.assign(new Error(message), { code });
174
+ }
175
+
176
+ function touch() {
177
+ lastActivity = Date.now();
178
+ }
179
+
180
+ function uniqueName(base) {
181
+ const clean = (base || "claude").replace(/[^A-Za-z0-9_-]/g, "-").slice(0, 24) || "claude";
182
+ const taken = new Set([...sessions.values()].map((s) => s.name));
183
+ let name = clean;
184
+ for (let n = 2; taken.has(name); n++) name = `${clean}-${n}`;
185
+ return name;
186
+ }
187
+
188
+ function sessionOr404(id) {
189
+ const s = sessions.get(id) || [...sessions.values()].find((x) => x.name === id);
190
+ if (!s) throw hostError(404, `no session ${id}`);
191
+ return s;
192
+ }
193
+
194
+ const ops = {
195
+ ping: () => ({ pid: process.pid, sessions: sessions.size }),
196
+ list: () => ({ sessions: [...sessions.values()].map((s) => s.summary()) }),
197
+ new({ name, cwd, cmd, args = [], env = {}, cols, rows }) {
198
+ if (!cmd) throw hostError(400, "cmd required");
199
+ if (!cwd) throw hostError(400, "cwd required");
200
+ const s = new Session({ name: uniqueName(name), cwd, cmd, args, env, cols: cols || DEFAULT_SIZE.cols, rows: rows || DEFAULT_SIZE.rows });
201
+ sessions.set(s.id, s);
202
+ everHadSession = true;
203
+ touch();
204
+ log(`new session ${s.name} (${s.id}): ${cmd} ${args.join(" ")} in ${cwd}`);
205
+ return { id: s.id, name: s.name, pid: s.pid };
206
+ },
207
+ alive({ session }) {
208
+ const s = sessions.get(session);
209
+ return { alive: !!s && s.alive, name: s?.name, pid: s?.pid ?? null };
210
+ },
211
+ screen({ session, lines = 60 }) {
212
+ return { text: sessionOr404(session).screen(Math.min(Number(lines) || 60, SCROLLBACK)) };
213
+ },
214
+ write({ session, data }) {
215
+ sessionOr404(session).write(String(data ?? ""));
216
+ return {};
217
+ },
218
+ key({ session, key }) {
219
+ sessionOr404(session).key(String(key));
220
+ return {};
221
+ },
222
+ resize({ session, cols, rows }) {
223
+ sessionOr404(session).resize(Number(cols), Number(rows));
224
+ return {};
225
+ },
226
+ kill({ session }) {
227
+ sessionOr404(session).kill();
228
+ return {};
229
+ },
230
+ };
231
+
232
+ const server = createServer((socket) => {
233
+ connections.add(socket);
234
+ touch();
235
+ let buf = "";
236
+ let attachedTo = null;
237
+ socket.setNoDelay?.(true);
238
+ socket.on("data", (chunk) => {
239
+ buf += chunk.toString("utf8");
240
+ let idx;
241
+ while ((idx = buf.indexOf("\n")) >= 0) {
242
+ const line = buf.slice(0, idx);
243
+ buf = buf.slice(idx + 1);
244
+ if (!line.trim()) continue;
245
+ let msg;
246
+ try {
247
+ msg = JSON.parse(line);
248
+ } catch {
249
+ continue;
250
+ }
251
+ if (attachedTo) {
252
+ if (msg.op === "input" && typeof msg.data === "string") attachedTo.write(Buffer.from(msg.data, "base64").toString("utf8"));
253
+ else if (msg.op === "resize") attachedTo.resize(Number(msg.cols), Number(msg.rows));
254
+ else if (msg.op === "detach") socket.end();
255
+ continue;
256
+ }
257
+ if (msg.op === "attach") {
258
+ try {
259
+ const s = sessionOr404(msg.session);
260
+ socket.write(JSON.stringify({ id: msg.id, ok: true, name: s.name }) + "\n");
261
+ attachedTo = s;
262
+ s.attach(socket, Number(msg.cols) || s.cols, Number(msg.rows) || s.rows);
263
+ } catch (err) {
264
+ socket.end(JSON.stringify({ id: msg.id, ok: false, error: err.message, code: err.code }) + "\n");
265
+ }
266
+ continue;
267
+ }
268
+ const fn = ops[msg.op];
269
+ let reply;
270
+ try {
271
+ if (!fn) throw hostError(400, `unknown op ${msg.op}`);
272
+ reply = { id: msg.id, ok: true, result: fn(msg) };
273
+ } catch (err) {
274
+ reply = { id: msg.id, ok: false, error: err.message, code: err.code || 500 };
275
+ }
276
+ if (!socket.destroyed) socket.write(JSON.stringify(reply) + "\n");
277
+ }
278
+ });
279
+ socket.on("close", () => {
280
+ connections.delete(socket);
281
+ touch();
282
+ });
283
+ socket.on("error", () => {});
284
+ });
285
+
286
+ server.listen(pipe, () => log(`host listening on ${pipe}`));
287
+
288
+ let idleTimer = null;
289
+ if (exitWhenIdle) {
290
+ const started = Date.now();
291
+ idleTimer = setInterval(() => {
292
+ const quietFor = Date.now() - lastActivity;
293
+ const pastGrace = everHadSession || Date.now() - started > STARTUP_GRACE_MS;
294
+ // Control connections don't count: the hub keeps one open for as long as it
295
+ // runs, and a host with nothing to hold should still make way for a newer one.
296
+ if (sessions.size === 0 && quietFor > IDLE_EXIT_MS && pastGrace) {
297
+ log("no sessions and no clients; exiting");
298
+ close();
299
+ process.exit(0);
300
+ }
301
+ }, 2000);
302
+ }
303
+
304
+ function close() {
305
+ clearInterval(idleTimer);
306
+ for (const s of connections) s.destroy();
307
+ server.close();
308
+ }
309
+
310
+ return { server, sessions, pipe, close };
311
+ }
312
+
313
+ // ---------- standalone ----------
314
+ const isMain = process.argv[1] && resolve(process.argv[1]).toLowerCase() === resolve(fileURLToPath(import.meta.url)).toLowerCase();
315
+ if (isMain) {
316
+ const argv = process.argv.slice(2);
317
+ const arg = (flag) => {
318
+ const i = argv.indexOf(flag);
319
+ return i >= 0 ? argv[i + 1] : null;
320
+ };
321
+ const pipe = arg("--pipe") || defaultPipe();
322
+ const logFile = arg("--log");
323
+ const log = (msg) => {
324
+ const line = `[${new Date().toISOString()}] ${msg}\n`;
325
+ if (logFile) {
326
+ try {
327
+ mkdirSync(dirname(logFile), { recursive: true });
328
+ appendFileSync(logFile, line);
329
+ } catch {
330
+ /* no log */
331
+ }
332
+ } else process.stdout.write(line);
333
+ };
334
+ const host = startHost({ pipe, log });
335
+ host.server.on("error", (err) => {
336
+ log(`cannot listen on ${pipe}: ${err.message}`);
337
+ process.exit(1);
338
+ });
339
+ process.on("uncaughtException", (err) => log(`uncaught: ${err.stack || err.message}`));
340
+ const stop = () => {
341
+ for (const s of host.sessions.values()) s.kill();
342
+ host.close();
343
+ process.exit(0);
344
+ };
345
+ process.on("SIGINT", stop);
346
+ process.on("SIGTERM", stop);
347
+ }
package/hub/config.mjs CHANGED
@@ -45,6 +45,9 @@ const DEFAULTS = {
45
45
  claudeArgs: [],
46
46
  // Keep the machine awake while the hub runs, so the glasses can reach it. Later milestone.
47
47
  preventSleep: true,
48
+ // Send a prompt from the glasses at once when its session is working, cutting the
49
+ // turn in progress short, instead of leaving it queued until that turn ends.
50
+ sendNowWhenWorking: true,
48
51
  // The rest are for the glasses display, and only this fork's build of the glasses
49
52
  // app reads them; upstream's build in Even Hub behaves as it always has.
50
53
  // Hold a reply too long for the screen at its first line instead of showing its end.
package/hub/pane.mjs CHANGED
@@ -63,12 +63,38 @@ export async function capture(target, lines = 60) {
63
63
  return text.replace(/\s+$/gm, "");
64
64
  }
65
65
 
66
+ /**
67
+ * Numbered options that came back as one line, each on a line of its own. A host
68
+ * started before it learned better joins a redrawn row to the one above (see
69
+ * screen() in host/host.mjs), and it keeps running while it has sessions:
70
+ * "❯ 1. Yes 2. No" would be read as a single option called "Yes 2. No".
71
+ */
72
+ function splitOptions(line) {
73
+ const out = [];
74
+ let rest = line;
75
+ for (;;) {
76
+ const n = /^\s*(?:❯\s*)?(\d+)\.\s/.exec(rest)?.[1];
77
+ // Only the next number, after the indent of an option's row or the cursor, so
78
+ // a number inside a label stays there.
79
+ const next = n && `${Number(n) + 1}\\.\\s`;
80
+ const gap = n && new RegExp(`\\s{2,}(?=${next})|\\s+(?=❯\\s*${next})`).exec(rest);
81
+ if (!gap) break;
82
+ out.push(rest.slice(0, gap.index));
83
+ rest = rest.slice(gap.index);
84
+ }
85
+ out.push(rest);
86
+ return out;
87
+ }
88
+
66
89
  /**
67
90
  * What is Claude Code showing at the bottom of the pane?
68
91
  * @returns {{kind: "permission"|"question"|"trust"|"input"|"unknown", options: string[]}}
69
92
  */
70
93
  export function readDialog(screen) {
71
- const tail = screen.split("\n").filter((l) => l.trim()).slice(-30);
94
+ // A rule that fills the row comes back joined to the row under it, as one wrapped
95
+ // row, so the input box reads "────…────❯ text". Put the line break back.
96
+ const rows = String(screen).replace(/^(─{20,})(?!─)(?=.*\S)/gm, "$1\n");
97
+ const tail = rows.split("\n").flatMap(splitOptions).filter((l) => l.trim()).slice(-30);
72
98
  const joined = tail.join("\n");
73
99
  const options = [];
74
100
  for (const l of tail) {
@@ -89,6 +115,15 @@ export function readDialog(screen) {
89
115
  return { kind: "unknown", options: clean };
90
116
  }
91
117
 
118
+ /**
119
+ * Whether the screen says a turn is running. The input box is on screen during a
120
+ * turn as well, and only the footer under it tells the two apart.
121
+ */
122
+ export function showsWorking(screen) {
123
+ const tail = String(screen).split("\n").filter((l) => l.trim()).slice(-4);
124
+ return /esc to interrupt/.test(tail.join("\n"));
125
+ }
126
+
92
127
  /** Whether text is dim after an SGR sequence with these parameters. */
93
128
  function dimAfter(params, dim) {
94
129
  const p = params.split(";");
@@ -150,13 +185,24 @@ export async function readDialogStable(target, { lines = 40, attempts = 6, gapMs
150
185
  return last;
151
186
  }
152
187
 
153
- /** Type a prompt into Claude Code's input box and submit it. */
154
- export async function sendPrompt(target, text) {
188
+ // Ctrl+X Ctrl+S, Claude Code's default chord for "send now" (chat:sendNow in its
189
+ // keybindings). Written as bytes rather than added to the host's key table: a host
190
+ // that is already running holds live sessions and keeps the table it started with.
191
+ const SEND_NOW = "\x18\x13";
192
+
193
+ /**
194
+ * Type a prompt into Claude Code's input box and submit it. Enter queues a prompt
195
+ * behind a turn in progress; with `now`, the send-now chord submits it instead,
196
+ * which cuts that turn short and sends the prompt at once. On an idle session the
197
+ * chord submits as Enter does.
198
+ */
199
+ export async function sendPrompt(target, text, { now = false } = {}) {
155
200
  const flat = String(text).replace(/\r?\n+/g, " ").trim();
156
201
  if (!flat) return;
157
202
  await host(target, "write", { data: flat });
158
203
  await sleep(120); // let the TUI absorb a paste-sized burst before submitting
159
- await host(target, "key", { key: "Enter" });
204
+ if (now) await host(target, "write", { data: SEND_NOW });
205
+ else await host(target, "key", { key: "Enter" });
160
206
  }
161
207
 
162
208
  const KEY_WHITELIST = new Set(["Escape", "Enter", "Up", "Down", "MenuUp", "MenuDown", "Tab", "BTab", "1", "2", "3", "4", "5", "6", "7", "8", "9"]);
@@ -276,15 +322,20 @@ export async function acceptTrustIfShown(target, waitMs = 8000) {
276
322
  }
277
323
  if (dialog.kind === "trust") {
278
324
  // The trust dialog is an unnumbered two-item menu with "No, exit" focused.
279
- // Arrow keys don't move it through ConPTY; the vi key does (see KEYS). A key
280
- // sent while the dialog is still mounting is dropped, so move, check that
281
- // "Yes" has the focus, and only then confirm.
282
- for (let attempt = 0; attempt < 4; attempt++) {
325
+ // Which key moves it depends on the Claude Code version: the arrow key in
326
+ // 2.1.328, the vi key and not the arrow before (see KEYS). So try them in
327
+ // turn. The menu wraps, and a key sent while the dialog is still mounting is
328
+ // dropped, so press only while "Yes" lacks the focus, and confirm only once
329
+ // it has it.
330
+ const yesFocused = async () => /Yes, I trust/.test((await capture(target, 20)).split("\n").find((l) => /❯/.test(l)) || "");
331
+ const moves = ["Down", "MenuDown"];
332
+ for (let attempt = 0; attempt < 6; attempt++) {
283
333
  await sleep(attempt ? 400 : 600);
284
- await sendKey(target, "MenuDown");
285
- await sleep(400);
286
- const focused = (await capture(target, 20)).split("\n").find((l) => /❯/.test(l)) || "";
287
- if (/Yes, I trust/.test(focused)) {
334
+ if (!(await yesFocused())) {
335
+ await sendKey(target, moves[attempt % moves.length]);
336
+ await sleep(400);
337
+ }
338
+ if (await yesFocused()) {
288
339
  await sendKey(target, "Enter");
289
340
  return true;
290
341
  }
package/hub/server.mjs CHANGED
@@ -285,12 +285,14 @@ export function startHub({ quiet = false, feed = true } = {}) {
285
285
  const { text } = await readJSON(req);
286
286
  if (!text || typeof text !== "string") throw new HttpError(400, "text required");
287
287
  await refuseIfDialog(s);
288
- await paneCtl.sendPrompt(controllable(s), text);
288
+ // Claude Code queues a prompt typed during a turn until the turn ends.
289
+ const now = cfg.sendNowWhenWorking === true && s.state === "working";
290
+ await paneCtl.sendPrompt(controllable(s), text, { now });
289
291
  if (!(await confirmDelivered(s, text))) {
290
292
  log(`✗ ${s.project}: typed but not seen in the terminal or transcript: ${text.slice(0, 80)}`);
291
293
  throw new HttpError(502, "Typed it, but Claude didn't show it. Is that terminal in another mode?");
292
294
  }
293
- log(`→ ${s.project}: ${text}`);
295
+ log(`→ ${s.project}: ${text}${now ? " (sent now, over the turn in progress)" : ""}`);
294
296
  return send(res, 200, { ok: true });
295
297
  }
296
298
  if (method === "POST" && action === "interrupt") {
package/hub/sessions.mjs CHANGED
@@ -5,7 +5,7 @@ import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "
5
5
  import { basename, join } from "node:path";
6
6
  import { CLAUDE_PROJECTS_DIR, STATE_FILE } from "./config.mjs";
7
7
  import { entryMeta, entryToItems, parseLine, readTailLines, toolLabel, TranscriptTail } from "./transcript.mjs";
8
- import { capture, paneAlive, paneKey, readDialog, readSuggestion, targetFromHook } from "./pane.mjs";
8
+ import { capture, paneAlive, paneKey, readDialog, readSuggestion, showsWorking, targetFromHook } from "./pane.mjs";
9
9
 
10
10
  const MAX_ITEMS = 300;
11
11
  const HISTORY_ITEMS = 150; // how much history to load when the hub starts watching a session
@@ -365,7 +365,8 @@ export class Registry extends EventEmitter {
365
365
  if (s.pane && !alive) s.pane = null;
366
366
  if (alive && s.pane) {
367
367
  try {
368
- const dialog = readDialog(await capture(s.pane, 40));
368
+ const screen = await capture(s.pane, 40);
369
+ const dialog = readDialog(screen);
369
370
  if (s.waiting) {
370
371
  // A waiting state with no dialog on screen is stale (answered at the desk,
371
372
  // declined, or interrupted without a hook). Clear it after two checks.
@@ -374,7 +375,8 @@ export class Registry extends EventEmitter {
374
375
  if (s.staleWaitingChecks >= 2) {
375
376
  s.waiting = null;
376
377
  s.staleWaitingChecks = 0;
377
- if (s.state === "waiting") s.state = dialog.kind === "input" ? "idle" : "working";
378
+ // Approved at the desk, the tool may still be running under the input box.
379
+ if (s.state === "waiting") s.state = dialog.kind === "input" && !showsWorking(screen) ? "idle" : "working";
378
380
  this.changed(s);
379
381
  }
380
382
  } else if (dialog.kind === "permission" || dialog.kind === "question") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gwro/codeaside",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "description": "Drive your Claude Code sessions from Even Realities G2 smart glasses, natively on Windows: live transcript, approvals, and hold-to-talk voice.",
5
5
  "type": "module",
6
6
  "bin": {