fix(phone-host): Teams & swarm view, live terminal kept on a late cancel, chat fixes (1.2.0) + README phone connector (#5212)

* fix(phone-host): Teams & swarm view, live terminal kept on a late cancel, chat fixes in the phone screens (1.2.0)

- ruflo.teamSnapshot.read: the phone's Teams & swarm screen now works on a ruflo
  host. Read-only; swarms, hive-mind, agents, tasks and claims from each shared
  workspace's .claude-flow, plus Claude Code agent teams whose lead works in one.
  Allowlisted fields: names, statuses, counts, message summaries (280 chars) and
  task subjects; never tokens, agent prompts or claim notes.
- terminal.unsubscribe with a requestId ends only that request's stream, so a
  late cancel of an older stream no longer stops the phone's live one.
- A Claude tab reports its session to the phone only once Claude trusts the
  folder (its .claude.json) or has written its transcript, so a chat view never
  covers Claude's first-run trust prompt.
- Phone screens rebuilt from ruflo-ui fix/mobile-chat-ux-5211 (98448b90c): agent
  tabs open in chat once the agent has a session, and the @ file menu narrows as
  you type.

Refs #5211

Co-Authored-By: RuFlo <ruv@ruv.net>

* docs(readme): phone connector section with header picture

Co-Authored-By: RuFlo <ruv@ruv.net>

---------

Co-authored-by: r <r@x>
This commit is contained in:
rUvandr authored and GitHub committed 2026-12-01 00:19:09 -05:00
1 parent 718cdc6116
commit fa4efccb06
16 files changed
+450 -36

No files matched your search

+20
View File
@@ -195,6 +195,26 @@ The default is **read + ask**. Available levels are `read`, `write`, `manage`, a
[Watch the recorded Claude Haiku session](docs/assets/ruflo-console-claude-control.gif) to see mission creation, page navigation, a refused swarm stop, and control being taken back. The recording uses `write + auto`. Step 1 uses `ask` so you can approve creation yourself. [Recorded test findings](v3/docs/adr/ADR-444-claude-controls-the-console.md) · [Reproduction script](plugins/ruflo-console/scripts/e2e-control.sh)
<a id="phone-connector"></a>
## Phone connector
<p align="center"><img src="docs/assets/readme/phone.svg" alt="Pair a phone with the ruflo CLI: terminals, Claude and Codex tabs on the phone, end-to-end encrypted" width="100%"></p>
Pair the RuFlo or Orca phone app with this computer over your LAN or Tailscale. The link is end-to-end encrypted and needs no desktop app, relay or account. The connector is an opt-in add-on (`@claude-flow/phone-host`) that is installed only when you run setup:
```bash
ruflo phone setup # installs the add-on into ~/.ruflo/phone-host
ruflo phone daemon start --full # leave out --full for a read-only phone
ruflo phone pair --full # shows a QR code for one phone
```
- **Read-only by default.** A phone sees the shared workspaces and their status, and changes nothing.
- **With `--full`**, it opens terminals and Claude, Codex and other agent tabs that run as you, with a chat view for Claude and Codex.
- **A pairing code is a password.** Check `ruflo phone devices` and remove a phone with `ruflo phone revoke <id>`.
[Setup, access levels and security](phone-host/README.md)
<a id="what-you-get"></a>
## Choose your next capability
+32
View File
@@ -0,0 +1,32 @@
<svg xmlns="http://www.w3.org/2000/svg" width="960" height="234" viewBox="0 0 960 234" role="img" aria-labelledby="title desc">
<title id="title">Your agents, in your pocket.</title><desc id="desc">Pair a phone with the ruflo CLI. End-to-end encrypted, no desktop app, relay or account.</desc>
<defs><linearGradient id="heading"><stop stop-color="#e0d4ff"/><stop offset=".55" stop-color="#ac8fff"/><stop offset="1" stop-color="#edbaff"/></linearGradient></defs>
<style>@media(prefers-reduced-motion:no-preference){.pulse{animation:pulse 2.6s ease-in-out infinite}.flow{animation:flow 2.6s linear infinite}.type{animation:type 5.2s steps(1) infinite}@keyframes pulse{0%,100%{opacity:.35}50%{opacity:1}}@keyframes flow{0%{stroke-dashoffset:24}100%{stroke-dashoffset:0}}@keyframes type{0%,40%{opacity:0}45%,100%{opacity:1}}}</style>
<g font-family="Inter,Arial,sans-serif">
<rect x="0" y="0" width="960" height="234" rx="8" fill="#0c0f14"/>
<text x="26" y="34" font-size="13" font-weight="700" letter-spacing="1.6" fill="#bca6ff">RUFLO · PHONE CONNECTOR</text>
<text x="24" y="98" font-size="49" font-weight="700" letter-spacing="-1.8" fill="#f6f4fc">Your agents,</text>
<text x="24" y="150" font-size="49" font-weight="700" letter-spacing="-1.8" fill="url(#heading)">in your pocket.</text>
<text x="26" y="196" font-size="17" fill="#b3bdcc">Pair a phone with the CLI. No desktop app, relay or account.</text>
<!-- computer -->
<rect x="540" y="58" width="150" height="104" rx="10" fill="#0d0c14" stroke="#3b304f"/>
<circle cx="555" cy="72" r="3" fill="#ac817c"/><circle cx="566" cy="72" r="3" fill="#c3a66d"/><circle cx="577" cy="72" r="3" fill="#83ae97"/>
<text x="553" y="100" font-size="13" font-family="ui-monospace,Menlo,monospace" fill="#c6bddd">$ ruflo phone</text>
<text x="553" y="120" font-size="13" font-family="ui-monospace,Menlo,monospace" fill="#c6bddd"> pair --full</text>
<rect x="553" y="134" width="44" height="14" rx="3" fill="#191626" stroke="#282631"/><text x="560" y="145" font-size="10" fill="#bca6ff">QR</text>
<rect x="590" y="174" width="50" height="6" rx="3" fill="#22202a"/>
<!-- link -->
<path class="flow" d="M696 110 H770" stroke="#a88bdf" stroke-width="2" stroke-dasharray="6 6" fill="none"/>
<rect x="702" y="122" width="62" height="20" rx="10" fill="#191626" stroke="#3b304f"/><text x="712" y="136" font-size="11" fill="#c6bddd">E2EE</text>
<circle class="pulse" cx="733" cy="96" r="4" fill="#b191ff"/>
<!-- phone -->
<rect x="780" y="16" width="130" height="204" rx="20" fill="#0d0c14" stroke="#3b304f" stroke-width="1.5"/>
<rect x="826" y="24" width="38" height="6" rx="3" fill="#22202a"/>
<rect x="792" y="42" width="106" height="26" rx="7" fill="#191626" stroke="#282631"/><circle cx="804" cy="55" r="3" fill="#b191ff"/><text x="813" y="59" font-size="12" fill="#f6f4fc">Claude</text>
<rect x="792" y="74" width="106" height="26" rx="7" fill="#121119" stroke="#282631"/><circle cx="804" cy="87" r="3" fill="#83ae97"/><text x="813" y="91" font-size="12" fill="#f6f4fc">Codex</text>
<rect x="792" y="106" width="106" height="26" rx="7" fill="#121119" stroke="#282631"/><circle cx="804" cy="119" r="3" fill="#c3a66d"/><text x="813" y="123" font-size="12" fill="#f6f4fc">Terminal</text>
<rect x="792" y="142" width="80" height="20" rx="8" fill="#22202a"/><text x="800" y="156" font-size="10" fill="#b3bdcc">Fix the tests</text>
<g class="type"><rect x="818" y="168" width="80" height="20" rx="8" fill="#3b2f63"/><text x="826" y="182" font-size="10" fill="#f6f4fc">Done: 70 pass</text></g>
<rect x="826" y="206" width="38" height="4" rx="2" fill="#3b304f"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 3.5 KiB

+2 -1
View File
@@ -75,6 +75,7 @@ An agent can start the host and pair a phone, including a full-access phone when
- `status.get`;
- `repo.list`, `worktree.ps` and `worktree.show`, which list only what you chose to share;
- `github.repoSlug`, which reads the `origin` remote;
- `ruflo.teamSnapshot.read`, for the Teams & swarm screen. It reads the ruflo swarms, hive-mind, agents, tasks and claims in each shared workspace's `.claude-flow`, plus the Claude Code agent teams whose lead works in one. It sends names, statuses and counts, plus short text: the first 280 characters of each recent team message, and each task's subject or description (ruflo task descriptions are cut at 200). It never sends tokens, agent prompts or claim notes;
- `worktree.activate`, `ui.get`, `mobileRelay.projectSections`, `runtime.clientCapabilities.update` and `runtime.clientEvents.*`. These are the reads the workspace screen makes when it opens.
- the `mobileWeb.bundle.*` reads that load the app's screens.
@@ -97,7 +98,7 @@ A full-access phone can open terminal tabs and agent tabs in a shared workspace.
## Host screens
The app draws its host screens from a web bundle that the host serves. This package ships the RuFlo build in `bundle/`: about 15 MB unpacked, built from cognitum-one/ruflo-ui `phone/mobile-lanes-merged-20261130` (`ef1e43563`, Orca `98e7dbec`). It is used by default.
The app draws its host screens from a web bundle that the host serves. This package ships the RuFlo build in `bundle/`: about 15 MB unpacked, built from cognitum-one/ruflo-ui `fix/mobile-chat-ux-5211` (`98448b90c`, Orca `98e7dbec`). That is `phone/mobile-lanes-merged-20261130` (`ef1e43563`) plus two chat fixes. A tab set to chat waits in the terminal until its agent has a session, so a first-run prompt stays visible; with no stored choice, chat is the default. And the `@` file menu narrows as you type. It is used by default.
Every asset is checked against the manifest's SHA-256 before it is sent.
@@ -669,7 +669,7 @@ ${t} #selection-overlay, ${t} #scroll-indicator { position: absolute; }`,documen
`)||s?e:n.slice(0,n.endsWith(`\r
`)?-2:-1)}var vM=/^\[Image:\s*source:\s*(.+?)\]\s*$/,vR=/\[Image #\d+\]/,vI=/\[Image #\d+\]/g,vA=(RegExp(`(${ek.source})|\\[Image #(\\d+)\\]`,"g"),/^[^\S\r\n]*\[Image #\d+\]/),vP=/\[Image #\d+\][^\S\r\n]*$/,vE=/^[^\S\r\n]+/,vD=/[^\S\r\n]+$/;function vB(e){if("user"!==e.role||0===e.blocks.length)return[];let t=[];for(let r of e.blocks){var i;if(!g6(r))return[];let e=(i=r.text,i.match(vM)?.[1]?.trim()??null);if(null===e)return[];t.push(e)}return t}function vQ(e){return vB(e).length>0}function vj(e){var t=e.replace(vI,"");if(t===e)return e;let i=vA.test(e)?t.replace(vE,""):t;return vP.test(e)&&(i=i.replace(vD,"")),i}function vF(e){return vj(vT(vL(e)).replace(vb,"")).trim().replace(/\s+/g," ")}function vO(e){let t=!1,i=null;for(let r=0;r<e.length;r+=1){let n=e[r];if(!g6(n)){i?.push(n);continue}let s=!t;t=!0;let o=vj(n.text);if(!o.trim()&&(o!==n.text||s)){i??=e.slice(0,r);continue}if(o!==n.text){(i??=e.slice(0,r)).push({...n,text:o});continue}i?.push(n)}return i??e}function vW(e){return e.blocks.some(e=>g6(e)&&vR.test(e.text))}function vH(e){let t=null;for(let i=0;i<e.length;i+=1){let r=e[i];if("user"!==r.role){t?.push(r);continue}let n=vB(r);if(n.length>0){t??=e.slice(0,i);let s=[...n],o=i+1;for(;o<e.length;){let t=e[o],i=vB(t);if("user"!==t.role||t.source!==r.source||0===i.length)break;s.push(...i),o+=1}let a=e[o];if(a?.role==="user"&&a.source===r.source&&vW(a)){t.push({...a,blocks:[...s.map(e=>({type:"image-ref",path:e})),...vO(a.blocks)]}),i=o;continue}t.push({...r,blocks:n.map(e=>({type:"image-ref",path:e}))});continue}let s=vO(r.blocks);s===r.blocks?t?.push(r):(t??=e.slice(0,i)).push({...r,blocks:s})}return t??e}var vN=oa(os());function vz(e){let t=e?.replaceAll(/[^a-z0-9]/gi,"").toLowerCase();return"askuserquestion"===t||"requestuserinput"===t}var v$=new Map;function vq(e){return e?`question:${JSON.stringify(e.questions)}`:null}function vK(e){if(!e||"object"!=typeof e||!("questions"in e))return null;let t=e.questions;if(!Array.isArray(t)||0===t.length)return null;let i=[];for(let e of t){var r;if(!e||"object"!=typeof e)continue;let t="question"in e&&"string"==typeof e.question?e.question:"",n=Array.isArray(r="options"in e?e.options:void 0)?r.map(e=>"string"==typeof e?{label:e}:e&&"object"==typeof e&&"label"in e&&"string"==typeof e.label?{label:e.label,description:"description"in e&&"string"==typeof e.description?e.description:void 0}:null).filter(e=>null!==e):[];(t||n.length>0)&&i.push({question:t,header:"header"in e&&"string"==typeof e.header?e.header:void 0,multiSelect:"multiSelect"in e?!0===e.multiSelect:"multiple"in e&&!0===e.multiple,options:n})}return i.length>0?{questions:i}:null}for(let e of["AskUserQuestion","ask_user_question","askUserQuestion"])v$.set(e,vK);function vV(e,t){let i=e?v$.get(e):void 0;return(i?i(t):null)??vK(t)}function vU(e,t){if(!e)return null;try{return vV(t,JSON.parse(e))}catch{return null}}function vZ(e,t){return"string"==typeof t?vU(t,e):vV(e,t)}function vG(e,t){let i=(t?.indices??[]).map(t=>e.options[t]?.label??"").filter(e=>e.length>0),r=(t?.other??"").trim();return r?[...i,r]:i}function vY(e){return g4(e)&&"failed"!==e.state&&vz(e.name)}function vX(e){if(!e.some(vY))return{asks:[],unansweredAsks:[],work:e};let t=new Set,i=[],r=[];for(let{call:n,result:s}of bd(e))!n||!vY(n)||s?.isError||(i.push(n),s||r.push(n),t.add(n),s&&t.add(s));return{asks:i,unansweredAsks:r,work:t.size?e.filter(e=>!t.has(e)):e}}function vJ(e){if(!g4(e))return[];let t=vZ(e.name,e.input);return t?t.questions.map(e=>e.question.trim()).filter(e=>e.length>0):[]}var v0=new Set(["working","monitoring","waiting"]),v1=["agent","workflow","command","monitor","unknown"],v5={agent:"background agent",workflow:"background workflow",command:"background command",monitor:"background monitor",unknown:"background task"},v2={done:"finished",blocked:"failed",idle:"was stopped"};function v3(e){return e.map(e=>g6(e)?e.text:"").filter(e=>e.length>0).join(`
`)}var v6=new WeakMap;function v4(e){let t,i,r,n,s,o=v6.get(e);if(o)return o;let a=(i=b3((t=bg(e.filter(e=>!ba(e)))).prose),r=t.prose.filter(bt),n=function(e){let t=new Set,i=new Map,r=new Map,n=[];for(let[i,s]of(e.forEach((e,t)=>{if(bt(e)){let i=function(e){var t,i;let r=e.summary?.trim()||e.error?.trim();if(r)return r;let n=v5[t=e.kind,v1.find(e=>e===t)??"unknown"],s=e.label.trim()?`${n} "${e.label}"`:n;if(i=e.state,v0.has(i))return`Started ${s}`;let o=v2[e.state]??"stopped reporting";return`${s.charAt(0).toUpperCase()}${s.slice(1)} ${o}`}(e);n.push({index:t,sentence:i}),r.set(i,(r.get(i)??0)+1)}}),e.entries())){let e="text"===s.type?r.get(s.text)??0:0;"text"===s.type&&e>0&&(r.set(s.text,e-1),t.add(i))}for(let e of n){let t=r.get(e.sentence)??0;t>0&&(r.set(e.sentence,t-1),i.set(e.index,e.sentence))}return{twinTextIndexes:t,unpairedRows:i}}(t.prose),{prose:s=0===i.length&&0===r.length?t.prose:t.prose.filter((e,t)=>!g9(e)&&!bt(e)&&!n.twinTextIndexes.has(t)&&!b6(e,i.length>0)),tools:t.tools,subagentGroups:i,backgroundTasks:r,markdown:v3(s),hasImages:s.some(e=>"image-ref"===e.type)});return v6.set(e,a),a}function v7(e){let{markdown:t,hasImages:i,tools:r,subagentGroups:n,backgroundTasks:s}=v4(e);return t.length>0||i||r.length>0||n.length>0||s.length>0}var v8=/^[\s\S]{0,40}~orca-oversized~(?:[1-9]\d*)~[0-9a-f]{16}$/,v9=Symbol("parsedJournalItemKey");function ye(e,t){let i=t>>>0;for(let t=0;t<e.length;t+=1)i^=e.charCodeAt(t),i=Math.imul(i,0x1000193)>>>0;return i>>>0}function yt(e){let t=String(e),i=function(e){if(e.length<=1024&&!function(e){for(let t=0;t<e.length;t+=1){let i=e.charCodeAt(t);if(i>=55296&&i<=56319){let i=t+1<e.length?e.charCodeAt(t+1):0;if(i<56320||i>57343)return!0;t+=1}else if(i>=56320&&i<=57343)return!0}return!1}(e))return e;let t=ye(e,0x811c9dc5).toString(16).padStart(8,"0"),i=ye(e,0x1000193).toString(16).padStart(8,"0");return`${function(e){let t="",i=0;for(;i<e.length&&i<40;){let r=e.charCodeAt(i);if(r>=55296&&r<=56319){let r=i+1<e.length?e.charCodeAt(i+1):0;if(r>=56320&&r<=57343){if(i+1>=40)break;t+=e.charAt(i)+e.charAt(i+1),i+=2;continue}t+="�",i+=1;continue}t+=r>=56320&&r<=57343?"�":e.charAt(i),i+=1}return t}(e)}~orca-oversized~${e.length}~${t}${i}`}(t),r=encodeURIComponent(i);return t===i&&yi(t)?`%FF${r}`:r}function yi(e){return v8.test(e)}function yr(e){let t=e[v9];return void 0!==t?t:"codex"===e.provider?["codex",yt(e.threadId),yt(e.turnId),yt(e.ordinal)].join(":"):"claude"===e.provider?["claude",yt(e.sessionId),yt(e.uuid)].join(":"):"orca"===e.provider?["orca",yt(e.clientMessageId)].join(":"):["legacy",yt(e.agent),yt(e.sessionId),yt(e.recordId)].join(":")}function yn(e){return yr({provider:"orca",clientMessageId:e})}function ys(e){let t=[],i=!1;for(let r of e.split(":")){let e=function(e){let t=e.startsWith("%FF");try{let i=decodeURIComponent(t?e.slice(3):e);return!t||yi(i)?{value:i,tagged:t}:null}catch{return null}}(r);if(!e)return null;t.push(e.value),i||=e.tagged||yi(e.value)}let[r,...n]=t;if("codex"===r&&3===n.length){let t=Number(n[2]);return Number.isSafeInteger(t)&&t>=0?yo({provider:r,threadId:n[0],turnId:n[1],ordinal:t},e,i):null}return"claude"===r&&2===n.length?yo({provider:r,sessionId:n[0],uuid:n[1]},e,i):"orca"===r&&1===n.length?yo({provider:r,clientMessageId:n[0]},e,i):"legacy"===r&&3===n.length?yo({provider:r,agent:n[0],sessionId:n[1],recordId:n[2]},e,i):null}function yo(e,t,i){return i&&Object.defineProperty(e,v9,{value:t}),e}function ya(e){return{id:e.itemId,timestamp:e.observedAt,source:"transcript",journalPosition:yl(e)}}function yl(e){return{sequence:e.sequence,index:e.sequenceIndex??0}}function yc(e,t){return e.sequence-t.sequence||e.index-t.index}function yd(e,t){return e.sequence-t.sequence||(e.sequenceIndex??0)-(t.sequenceIndex??0)}function yu(e,t){let i=e.map(e=>{let{submittedSequence:i,submittedAt:r}=t(e);return{entry:e,submittedSequence:i,submittedAt:r}});return(i.every(e=>void 0!==e.submittedSequence)?[...i].sort((e,t)=>e.submittedSequence-t.submittedSequence):[...i].sort((e,t)=>e.submittedAt-t.submittedAt)).map(({entry:e})=>e)}function yh(e){return!0===e.handoverRecorded&&"pending"===e.dispatchState&&void 0===e.handedOverAt}var yf=["goal"],yp=["running","completed"],ym={kind:"thread"},yg=sF().finite().nonnegative(),yb=sF().finite().positive(),yv=sF().finite(),yy=sj().min(1).max(256),y_=sz({inputTokens:yg,cacheCreationInputTokens:yg,cacheReadInputTokens:yg,outputTokens:yg}),yw=sV("kind",[sz({kind:sY("report"),model:yy,usedTokens:yg,windowTokens:yb,percentage:sF().finite(),autoCompactAtTokens:yg.optional(),categories:sH(sz({name:sj().min(1).max(80),tokens:yg,deferred:sY(!0).optional()})).max(64),capturedAt:yv}),sz({kind:sY("estimate"),usage:y_,capturedAt:yv}),sz({kind:sY("unknown"),capturedAt:yv})]),yS=sz({window:sz({tokens:yb,capturedAt:yv}).optional(),used:yw.optional()});function yx(e){if(!e)return null;if("turn"===e.kind){let{kind:t,...i}=e;return i}return"status"===e.kind?e.turnLifecycle??null:null}function yT(e){let t=e?.outcome;return P.find(e=>e== Line truncated
`)}var v6=new WeakMap;function v4(e){let t,i,r,n,s,o=v6.get(e);if(o)return o;let a=(i=b3((t=bg(e.filter(e=>!ba(e)))).prose),r=t.prose.filter(bt),n=function(e){let t=new Set,i=new Map,r=new Map,n=[];for(let[i,s]of(e.forEach((e,t)=>{if(bt(e)){let i=function(e){var t,i;let r=e.summary?.trim()||e.error?.trim();if(r)return r;let n=v5[t=e.kind,v1.find(e=>e===t)??"unknown"],s=e.label.trim()?`${n} "${e.label}"`:n;if(i=e.state,v0.has(i))return`Started ${s}`;let o=v2[e.state]??"stopped reporting";return`${s.charAt(0).toUpperCase()}${s.slice(1)} ${o}`}(e);n.push({index:t,sentence:i}),r.set(i,(r.get(i)??0)+1)}}),e.entries())){let e="text"===s.type?r.get(s.text)??0:0;"text"===s.type&&e>0&&(r.set(s.text,e-1),t.add(i))}for(let e of n){let t=r.get(e.sentence)??0;t>0&&(r.set(e.sentence,t-1),i.set(e.index,e.sentence))}return{twinTextIndexes:t,unpairedRows:i}}(t.prose),{prose:s=0===i.length&&0===r.length?t.prose:t.prose.filter((e,t)=>!g9(e)&&!bt(e)&&!n.twinTextIndexes.has(t)&&!b6(e,i.length>0)),tools:t.tools,subagentGroups:i,backgroundTasks:r,markdown:v3(s),hasImages:s.some(e=>"image-ref"===e.type)});return v6.set(e,a),a}function v7(e){let{markdown:t,hasImages:i,tools:r,subagentGroups:n,backgroundTasks:s}=v4(e);return t.length>0||i||r.length>0||n.length>0||s.length>0}var v8=/^[\s\S]{0,40}~orca-oversized~(?:[1-9]\d*)~[0-9a-f]{16}$/,v9=Symbol("parsedJournalItemKey");function ye(e,t){let i=t>>>0;for(let t=0;t<e.length;t+=1)i^=e.charCodeAt(t),i=Math.imul(i,0x1000193)>>>0;return i>>>0}function yt(e){let t=String(e),i=function(e){if(e.length<=1024&&!function(e){for(let t=0;t<e.length;t+=1){let i=e.charCodeAt(t);if(i>=55296&&i<=56319){let i=t+1<e.length?e.charCodeAt(t+1):0;if(i<56320||i>57343)return!0;t+=1}else if(i>=56320&&i<=57343)return!0}return!1}(e))return e;let t=ye(e,0x811c9dc5).toString(16).padStart(8,"0"),i=ye(e,0x1000193).toString(16).padStart(8,"0");return`${function(e){let t="",i=0;for(;i<e.length&&i<40;){let r=e.charCodeAt(i);if(r>=55296&&r<=56319){let r=i+1<e.length?e.charCodeAt(i+1):0;if(r>=56320&&r<=57343){if(i+1>=40)break;t+=e.charAt(i)+e.charAt(i+1),i+=2;continue}t+="�",i+=1;continue}t+=r>=56320&&r<=57343?"�":e.charAt(i),i+=1}return t}(e)}~orca-oversized~${e.length}~${t}${i}`}(t),r=encodeURIComponent(i);return t===i&&yi(t)?`%FF${r}`:r}function yi(e){return v8.test(e)}function yr(e){let t=e[v9];return void 0!==t?t:"codex"===e.provider?["codex",yt(e.threadId),yt(e.turnId),yt(e.ordinal)].join(":"):"claude"===e.provider?["claude",yt(e.sessionId),yt(e.uuid)].join(":"):"orca"===e.provider?["orca",yt(e.clientMessageId)].join(":"):["legacy",yt(e.agent),yt(e.sessionId),yt(e.recordId)].join(":")}function yn(e){return yr({provider:"orca",clientMessageId:e})}function ys(e){let t=[],i=!1;for(let r of e.split(":")){let e=function(e){let t=e.startsWith("%FF");try{let i=decodeURIComponent(t?e.slice(3):e);return!t||yi(i)?{value:i,tagged:t}:null}catch{return null}}(r);if(!e)return null;t.push(e.value),i||=e.tagged||yi(e.value)}let[r,...n]=t;if("codex"===r&&3===n.length){let t=Number(n[2]);return Number.isSafeInteger(t)&&t>=0?yo({provider:r,threadId:n[0],turnId:n[1],ordinal:t},e,i):null}return"claude"===r&&2===n.length?yo({provider:r,sessionId:n[0],uuid:n[1]},e,i):"orca"===r&&1===n.length?yo({provider:r,clientMessageId:n[0]},e,i):"legacy"===r&&3===n.length?yo({provider:r,agent:n[0],sessionId:n[1],recordId:n[2]},e,i):null}function yo(e,t,i){return i&&Object.defineProperty(e,v9,{value:t}),e}function ya(e){return{id:e.itemId,timestamp:e.observedAt,source:"transcript",journalPosition:yl(e)}}function yl(e){return{sequence:e.sequence,index:e.sequenceIndex??0}}function yc(e,t){return e.sequence-t.sequence||e.index-t.index}function yd(e,t){return e.sequence-t.sequence||(e.sequenceIndex??0)-(t.sequenceIndex??0)}function yu(e,t){let i=e.map(e=>{let{submittedSequence:i,submittedAt:r}=t(e);return{entry:e,submittedSequence:i,submittedAt:r}});return(i.every(e=>void 0!==e.submittedSequence)?[...i].sort((e,t)=>e.submittedSequence-t.submittedSequence):[...i].sort((e,t)=>e.submittedAt-t.submittedAt)).map(({entry:e})=>e)}function yh(e){return!0===e.handoverRecorded&&"pending"===e.dispatchState&&void 0===e.handedOverAt}var yf=["goal"],yp=["running","completed"],ym={kind:"thread"},yg=sF().finite().nonnegative(),yb=sF().finite().positive(),yv=sF().finite(),yy=sj().min(1).max(256),y_=sz({inputTokens:yg,cacheCreationInputTokens:yg,cacheReadInputTokens:yg,outputTokens:yg}),yw=sV("kind",[sz({kind:sY("report"),model:yy,usedTokens:yg,windowTokens:yb,percentage:sF().finite(),autoCompactAtTokens:yg.optional(),categories:sH(sz({name:sj().min(1).max(80),tokens:yg,deferred:sY(!0).optional()})).max(64),capturedAt:yv}),sz({kind:sY("estimate"),usage:y_,capturedAt:yv}),sz({kind:sY("unknown"),capturedAt:yv})]),yS=sz({window:sz({tokens:yb,capturedAt:yv}).optional(),used:yw.optional()});function yx(e){if(!e)return null;if("turn"===e.kind){let{kind:t,...i}=e;return i}return"status"===e.kind?e.turnLifecycle??null:null}function yT(e){let t=e?.outcome;return P.find(e=>e== Line truncated
`)?`${s.current} `:s.current;let a=Number.parseFloat(o.borderTopWidth)+Number.parseFloat(o.borderBottomWidth);r(i.scrollHeight+a)},[e]);return(0,TR.useLayoutEffect)(()=>{let e=document.createElement("textarea");return e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e.readOnly=!0,e.rows=1,Object.assign(e.style,{position:"absolute",top:"0",left:"0",visibility:"hidden",pointerEvents:"none",overflow:"hidden",border:"0",margin:"0",boxSizing:"border-box"}),document.body.appendChild(e),n.current=e,()=>{e.remove(),n.current=null}},[]),(0,TR.useLayoutEffect)(()=>{s.current=t,o()},[t,o]),(0,TR.useEffect)(()=>{let t=e.current;if(!(t instanceof HTMLTextAreaElement))return;let i=t.clientWidth,r=new ResizeObserver(()=>{t.clientWidth!==i&&(i=t.clientWidth,o())});return r.observe(t),()=>r.disconnect()},[e,o]),i}(i,e.text),[n,s]=(0,TL.useState)(!1);(0,TL.useEffect)(()=>{i.current?.focus()},[]);let o=e.saving||!e.canSave,a=!e.canSave&&!e.saving;return(0,TA.jsxs)(TM.View,{style:TB.editor,testID:"queued-card-editor",children:[t?(0,TA.jsx)(TM.Text,{style:TB.attribution,numberOfLines:1,children:t}):null,(0,TA.jsxs)(TM.View,{style:TB.line,children:[(0,TA.jsx)(TM.TextInput,{ref:i,accessibilityLabel:"Edit queued message",value:e.text,editable:!e.saving,multiline:!0,selectionColor:s2.accentBlue,textAlignVertical:"top",style:[w9.freeInput,TB.field,void 0!==r&&{height:Math.min(96,Math.max(36,r))},n&&!e.saving&&TB.fieldFocused,e.saving&&TB.disabled],onChangeText:e.change,onFocus:()=>s(!0),onBlur:()=>s(!1)}),(0,TA.jsx)(TD,{label:"Cancel editing",disabled:e.saving,targetStyle:TB.cancelTarget,squareStyle:[TB.buttonRaised,e.saving&&TB.disabled],pressedStyle:TB.cancelPressed,onPress:e.cancel,children:(0,TA.jsx)(r7,{size:16,color:s2.textSecondary,strokeWidth:2})}),(0,TA.jsx)(TD,{label:"Save edited message",disabled:o,busy:e.saving,targetStyle:TB.saveTarget,squareStyle:a?TB.buttonRaised:TB.save,pressedStyle:TB.savePressed,onPress:()=>{e.save()},children:e.saving?(0,TA.jsx)(TM.ActivityIndicator,{size:"small",color:s2.bgBase}):(0,TA.jsx)(si,{size:16,color:a?s2.textMuted:s2.bgBase,strokeWidth:2.6})})]})]})}function TD({label:e,disabled:t,busy:i,targetStyle:r,squareStyle:n,pressedStyle:s,onPress:o,children:a}){let[l,c]=(0,TL.useState)(!1);return(0,TA.jsx)(TM.Pressable,{accessibilityRole:"button",accessibilityLabel:e,accessibilityState:{disabled:t},"aria-busy":i,disabled:t,style:[TB.target,r],onPress:o,onPressIn:()=>c(!0),onPressOut:()=>c(!1),children:(0,TA.jsx)(TM.View,{style:[TB.button,n,l&&!t&&s],children:a})})}var TB=TM.StyleSheet.create({editor:{paddingVertical:s6.sm,paddingLeft:s6.md,paddingRight:s6.sm,gap:s6.xs},attribution:{color:s2.textMuted,fontSize:s7.metaSize,lineHeight:s7.metaSize+s6.xs},line:{flexDirection:"row",alignItems:"flex-end",marginVertical:-4,marginRight:-s6.sm},field:{minHeight:36,maxHeight:96,lineHeight:20,paddingTop:7,paddingBottom:7,paddingHorizontal:10,borderWidth:1,borderColor:s2.borderSubtle,marginVertical:4},fieldFocused:{borderColor:s2.accentBlue},target:{height:44,justifyContent:"center"},cancelTarget:{paddingLeft:6,paddingRight:TP/2},saveTarget:{paddingLeft:TP/2,paddingRight:s6.sm},button:{width:28,height:28,borderRadius:s4.input,alignItems:"center",justifyContent:"center"},buttonRaised:{backgroundColor:s2.bgRaised,borderWidth:TM.StyleSheet.hairlineWidth,borderColor:s2.borderSubtle},cancelPressed:{backgroundColor:s2.bgPanel},save:{backgroundColor:s2.textPrimary},savePressed:{backgroundColor:s2.textSecondary},disabled:{opacity:.5}}),TQ=oa(os()),Tj=oa(oe()),TF=oa(oe()),TO=s6.xl+s6.sm,TW=s7.metaSize+s6.xs,TH=TF.StyleSheet.create({list:{marginHorizontal:s6.lg,marginTop:s6.xs,marginBottom:-18},box:{paddingBottom:12,backgroundColor:s2.bgPanel,borderTopLeftRadius:18,borderTopRightRadius:18,borderWidth:TF.StyleSheet.hairlineWidth,borderBottomWidth:0,borderColor:s2.composerBorder,overflow:"hidden"},header:{minHeight:TO,flexDirection:"row",alignItems:"center",gap:s6.xs,paddingLeft:s6.md},headerActionsLine:{flexDirection:"row",flexWrap:"wrap",justifyContent:"flex-end",gap:s6.xs,paddingHorizontal:s6.xs},headerToggle:{position:"absolute",top:0,right:0,bottom:0,left:0},headerLabels:{flex:1,minWidth:0,flexDirection:"row",alignItems:"center",gap:s6.xs},headerPaused:{backgroundColor:s2.bgRaised},headerLabel:{color:s2.textMuted,fontSize:s7.metaSize,lineHeight:TW,paddingVertical:s6.sm},headerLabelPaused:{color:s2.textPrimary,fontWeight:"500"},headerCount:{color:s2.textMuted,fontSize:s7.metaSize,lineHeight:TW,paddingVertical:s6.sm,fontVariant:["tabular-nums"]},headerCaption:{flex:1,minWidth:0,color:s2.statusRed,fontSize:s7.metaSize,lineHeight:TW,paddingVertical:s6.sm},headerAction:{minHeight:TO,minWidth:44,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:s6.xs,paddingHorizontal:s6.sm,borderRadius:s4.button},chevron:{width:36,minHeight:TO,alignItems:"center",justifyContent:"center"},card:{minHeight:44},row:{minHeight:44,flexDirection:"row",alignItems:"center",gap:s6.sm,paddingLeft:s6.md},divided:{borderTopWidth: Line truncated
`)}var kD=oa(os()),kB=oa(oe()),kQ=oa(oo());function kj({startedAt:e,workedSeconds:t,verdict:i,expanded:r=!1,onToggleExpanded:n}){let s=null!=t,o=J({workedSeconds:t,elapsedSeconds:function(e,t){let[i]=(0,kD.useState)(()=>Date.now()),[r,n]=(0,kD.useState)(()=>Date.now());return(0,kD.useEffect)(()=>{if(!t)return;n(Date.now());let e=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(e)},[t]),t?er(e,i,r):0}(e,!s),verdict:i});return s&&n?(0,kQ.jsxs)(kB.Pressable,{style:({pressed:e})=>[kF.row,kF.bar,e&&kF.pressed],onPress:n,hitSlop:6,accessibilityRole:"button",accessibilityState:{expanded:r},accessibilityLabel:U.toggleDetails,children:[(0,kQ.jsx)(kB.Text,{style:kF.label,children:o}),(0,kQ.jsx)(kB.View,{style:r?kF.caretOpen:void 0,children:(0,kQ.jsx)(rj,{size:14,color:s2.textMuted,strokeWidth:2})})]}):(0,kQ.jsx)(kB.View,{style:[kF.row,kF.bar],children:(0,kQ.jsx)(kB.Text,{style:kF.label,numberOfLines:1,children:o})})}var kF=kB.StyleSheet.create({row:{flexDirection:"row",alignItems:"center",gap:s6.xs,minHeight:28,paddingHorizontal:s6.md},bar:{borderBottomWidth:kB.StyleSheet.hairlineWidth,borderBottomColor:s2.borderSubtle},pressed:{opacity:.6},label:{color:s2.textMuted,fontSize:s7.bodySize,flexShrink:1},caretOpen:{transform:[{rotate:"90deg"}]}}),kO=oa(oe()),kW={compaction:"Context compacted",contextCleared:"Context cleared",plan:"Plan"},kH="This chat is still open in a terminal agent.",kN="Quit that agent to continue the chat here.",kz="Start a new chat to continue.",k$="Background tasks are still running.",kq="Wait for the background tasks to finish.",kK="The agent is still starting.",kV="Wait for the agent to finish starting.",kU="The agent is still working.",kZ={theAgent:"The agent",providerStartFailed:"{{agent}} stopped before it finished starting.",runCommandAgain:"Run /{{command}} again.",sendToTryAgain:"Send your message to try again.",sendAgainToTryOnceMore:"Send your message again to try once more.",couldNotStart:"{{agent}} couldn't start.",couldNotRestart:"{{agent}} couldn't restart.",startTimedOut:"{{agent}} took too long to start (no response to {{method}} after {{seconds}}s).",startTimedOutKeepsHappening:"If this keeps happening, the computer running this chat may be overloaded.",codexCliTooOld:"Codex {{installedVersion}} is too old for chats. Update to {{minimumVersion}} or newer.",argumentsUnsupportedOption:"Saved Arguments contain an unsupported option ({{option}}).",argumentsMissingValue:"Saved Arguments need a value for {{option}}.",argumentsMultipleValues:"Saved Arguments give {{option}} more than one value.",argumentsPositionalPrompt:"Saved Arguments include a prompt.",editSavedArguments:"Edit them in Settings > Agents > Arguments.",terminalAgentHoldsChat:kH,quitTerminalAgent:kN,startNewChat:kz,notSignedIn:"{{agent}} is not signed in.",claudeSystemNotSignedIn:"Claude isn't signed in. Run `{{loginCommand}}`, or choose an account in Claude Accounts settings.",claudeManagedNotSignedIn:"This Claude account isn't signed in. Sign in again in Claude Accounts settings.",codexSystemNotSignedIn:"Codex isn't signed in. Run `{{loginCommand}}`.",codexManagedNotSignedIn:"This Codex account isn't signed in. Sign in again in Codex Accounts settings.",antigravityNotSignedIn:"Antigravity isn't signed in. Sign in under Settings → Accounts → Antigravity. Then send your message again.",agentCommandNotSignedIn:"Sign in to {{agent}} with `{{loginCommand}}` on the computer running this chat.",interactiveAgentNotSignedIn:"Sign in to {{agent}} by running `{{loginCommand}}` and using `{{slashCommand}}` on the computer running this chat.",agentNotSignedIn:"Sign in to {{agent}}.",cliMissing:"{{agent}} wasn't found on the computer running this chat. Install it, or check its Command in Settings → Agents.",signInFirst:"Sign in first.",signInThenRunCommand:"Sign in, then run /{{command}} again.",signInThenSend:"Sign in, then send your message again.",thenSendAgain:"Then send your message again.",historyTooLarge:"This conversation's history is too large to restore here.",managedAccountEnvOverride:"This Claude launch sets its own Anthropic sign-in variables. Remove them to use a managed Claude account.",accountSwitchInProgress:"{{agent}}'s setup is changing on this host. Try again after it finishes.",managedAccountUnsupported:"While a Claude account is added in WSL, Claude chats need a Windows Claude account.",launchFolderMissing:"The folder this chat ran in no longer exists. Restore it to continue this chat.",historyInOtherAccount:"This chat's history is in another Claude account. Switch back to that account to continue it.",claudeAccountFolderMissing:"The selected Claude account's folder is missing. Sign in to it again or choose another account.",claudeAccountSetupFailed:"The selected Claude account could not be set up. Try again or choose another account.",agentCommandNotRunnable:"{{agent}}'s Command in Settings → Agents must be a program path or name RuFlo can find, with no arguments or variables. Change it or r Line truncated
@@ -1008,7 +1008,7 @@ ${e.content}`).join(`
`);eS.writeText(e).then(()=>{D(null),ee()}).catch(()=>{sy(),U("Couldn't copy drafts",1500)})}},{label:"Discard & Leave",destructive:!0,onPress:()=>{D(null),ee()}}],onClose:()=>D(null)}),(0,Bi.jsx)(iB,{visible:null!=A,title:"Discard Changes",message:"Replace the phone draft with the latest desktop file?",confirmLabel:"Discard",destructive:!0,onConfirm:ei,onCancel:()=>P(null)}),(0,Bi.jsx)(AK,{visible:null!=Q,title:"Rename Terminal",defaultValue:Q?.title||"Terminal",placeholder:"Terminal name",onSubmit:e=>{eu(e)},onCancel:()=>B(null)}),(0,Bi.jsx)(AK,{visible:v,title:"New Browser",message:!0===q?"Enter a URL, or leave blank for a desktop browser tab.":"Desktop streaming is unavailable. Enter a web URL to open on this phone.",defaultValue:"",placeholder:"https://example.com",submitLabel:!0===q?"Open":"Open on phone",allowEmpty:!0===q,selectTextOnFocus:!0,keyboardType:"ios"===EI.Platform.OS?"url":"default",onSubmit:e=>{if(!0!==q){let t=ai(e);return t&&/^https?:/i.test(t)?(sf(t),void b(!1)):void U("Enter an HTTP or HTTPS address.",1800)}ec(e).then(e=>{e&&b(!1)})},onCancel:()=>b(!1)}),(0,Bi.jsx)(Dj,{visible:F,onClose:()=>O(!1),onKeysChanged:j,onManageShortcuts:en}),(0,Bi.jsx)(D8,{visible:z,client:l,onClose:()=>$(!1),onReady:()=>$(!1)}),(0,Bi.jsx)(ik,{visible:null!=W,title:W?.label??"Shortcut",message:"Remove this custom shortcut?",actions:[{label:"Remove",destructive:!0,onPress:()=>{W&&er(W),H(null)}}],onClose:()=>H(null)})]})}var Bn=oa(oo());function Bs({controller:e}){let{setMobileSessionRootRef:t}=e,i=function(e){let{hostId:t,worktreeId:i,activeSessionTabId:r,activeHandle:n,showNativeChat:s,activeBrowserTab:o,activeFileTab:a,activeMarkdownTab:l,activePendingTerminalTab:c,showEmptyState:d,showLoadingState:u}=e,h=d||u||o||a||l||c?null:s?"chat":n?"terminal":null,f=h?JSON.stringify([t,i,r,h]):null,[p,m]=(0,oT.useState)(null),g=null!==f&&f===p;return(0,oT.useEffect)(()=>{m(e=>e===f?e:null)},[f]),rD(g?()=>(m(null),!0):null),{kind:h,expanded:g,toggle:()=>m(g?null:f)}}(e);return(0,Bn.jsx)(ox,{expanded:i.expanded,kind:i.kind,children:(0,Bn.jsxs)(oy.View,{ref:t,testID:"rupro-session-root",style:oE.container,children:[(0,Bn.jsxs)(oy.View,{style:oE.kavInner,children:[(0,Bn.jsx)(EM,{controller:e,focus:i}),(0,Bn.jsx)(PU,{controller:e,expanded:i.expanded,focusedTerminal:i.expanded&&"terminal"===i.kind})]}),(0,Bn.jsx)(Br,{controller:e})]})})}var Bo=oa(os()),Ba=oa(os()),Bl=oa(ot()),Bc=oa(oi()),Bd=oa(os());async function Bu(e,t){let i=await eJ(e,t);return{isGithubRepo:i.ok&&null!==i.result}}async function Bh(e,t){let[i,r]=await Promise.all([Bf(e,t),Bp(e,t).catch(()=>null)]);return{branch:i?.branch??null,headSha:i?.head??r?.summary.headOid??null,status:i}}async function Bf(e,t){let i=await eS.request(e,{worktree:`id:${t}`}),r=eS.interpret(i);return r.accepted?r.value:null}async function Bp(e,t){let i=await ts(e,t);if(!i)return null;let r=await ex.request(e,{worktree:`id:${t}`,baseRef:i}),n=ex.interpret(r);return n.accepted?n.value:null}var Bm=oa(os()),Bg=oa(oi()),Bb="selector_not_found",Bv=/(?:: |\n)[ \t]*$/,By=oa(os()),B_=oa(os()),Bw=oa(oe());function BS(){return D_.map(e=>e.id)}function Bx(e=BS()){return{version:2,orderedBuiltInIds:[...e],visibleBuiltInIds:[...e]}}function BT(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)?e:null}function Bk(e,t){let i=new Set,r=[];for(let n of e)!t.has(n)||i.has(n)||(i.add(n),r.push(n));return r}function BC(){return BS()}async function BL(){try{let e=await sh.getItem("orca:terminal-accessory-layout");return e?function(e,t=BS()){let i=Bx(t);if(!e||"object"!=typeof e)return i;let r=new Set(t);if(2===e.version){let n=BT(e.orderedBuiltInIds),s=BT(e.visibleBuiltInIds);if(!n||!s)return i;let{ordered:o,inserted:a}=function(e,t){let i=new Set(e),r=[...e],n=[];for(let e=0;e<t.length;e++){let s=t[e];if(i.has(s))continue;let o=0;for(let i=e-1;i>=0;i--){let e=r.indexOf(t[i]);if(-1!==e){o=e+1;break}}r.splice(o,0,s),i.add(s),n.push(s)}return{ordered:r,inserted:n}}(Bk(n,r),t),l=new Set(Bk(s,r));for(let e of a)l.add(e);return{version:2,orderedBuiltInIds:o,visibleBuiltInIds:o.filter(e=>l.has(e))}}if(1===e.version){let n=BT(e.visibleBuiltInIds),s=BT(e.knownBuiltInIds);if(!n||!s)return i;let o=new Set(s.filter(e=>r.has(e))),a=new Set(Bk(n,r));for(let e of t)o.has(e)||a.add(e);return{version:2,orderedBuiltInIds:[...t],visibleBuiltInIds:t.filter(e=>a.has(e))}}return i}(JSON.parse(e)):Bx()}catch{return Bx()}}var BM=oa(os()),BR=new TextEncoder,BI=new Map([["Escape","escape"],["Esc","escape"],["Tab","tab"],["Backspace","backspace"],["Delete","delete"],["Insert","insert"],["ArrowUp","arrowUp"],["ArrowDown","arrowDown"],["ArrowLeft","arrowLeft"],["ArrowRight","arrowRight"],["Home","home"],["End","end"],["PageUp","pageUp"],["PageDown","pageDown"],["F1","f1"],["F2","f2"],["F3","f3"],["F4","f4"],["F5","f5"],["F6","f6"],["F7","f7"],["F8","f8"],["F9","f9"],["F10","f10"],["F11","f11"],["F12","f12"]]);function BA(e){null!==e.current&&(clearTimeout(e.current),e.current=null)}function BP(e,t,i=50){BA(e),e.current=set Line truncated
`,t-1)+1,r=e.slice(i,t).trim();if(r)return T(r)||null;if(0===i)break;t=i-1}return null}function jd(e){return{currentRequests:e.currentRequests,requestMarker:e.requestMarker,requestAuthority:e.requestAuthority}}function ju(e,t){if(t.contract!==tM)return e;let i=e.requestMarker??e.requestAuthority;if(i?.publisher===t.publisher&&t.revision<=i.revision)return jd(e);let r=i?.publisher===t.publisher&&i.owner===t.owner&&i.epoch===t.epoch&&i.sessionId===t.sessionId;return{currentRequests:r?e.currentRequests:[],requestAuthority:r?e.requestAuthority:void 0,requestMarker:t}}function jh(e,t,i){if(t.currentRequests)return ju(e,t.currentRequests);if(i)return jd({});let r="batch"===t.type?t.batch.cursor.epoch:t.page.epoch;return e.requestMarker&&(r!==e.epoch||void 0!==t.fence&&t.fence!==e.fence)?{currentRequests:[],requestMarker:void 0,requestAuthority:void 0}:jd(e)}function jf(e){return(e.currentRequests??function(e,t=[],i=0){let r=Math.max(i,_R(e));return r>0?{items:e.filter(e=>e.sequence>r),submissions:t.filter(e=>(e.acceptedSequence??0)>r)}:{items:e,submissions:t}}(e.items).items).filter(e=>("approval"===e.body.kind||"question"===e.body.kind)&&"pending"===e.body.resolution.state)}var jp="structured-grouped-question:";function jm(e){return`${jp}${encodeURIComponent(JSON.stringify(e))}`}function jg(e){if(!e.startsWith(jp))return null;try{let t=JSON.parse(decodeURIComponent(e.slice(jp.length)));if("string"!=typeof t.promptKey||"string"!=typeof t.questionId)return null;if("option"===t.kind&&"string"==typeof t.optionId)return{kind:"option",promptKey:t.promptKey,questionId:t.questionId,optionId:t.optionId};if("free-text"===t.kind)return{kind:"free-text",promptKey:t.promptKey,questionId:t.questionId}}catch{}return null}function jb(e,t){return e&&e.promptKey===t?e.answers:[]}var jv="structured-agent-prompt:";function jy(e){return`${jv}${encodeURIComponent(JSON.stringify(e))}`}function j_(e){if(!e.startsWith(jv))return null;try{let t=JSON.parse(decodeURIComponent(e.slice(jv.length)));if("string"!=typeof t.itemId||"number"!=typeof t.revision||!Number.isFinite(t.revision))return null;if("approval"===t.kind&&"string"==typeof t.optionId)return{kind:t.kind,itemId:t.itemId,revision:t.revision,optionId:t.optionId};if("question-option"===t.kind&&"string"==typeof t.questionId&&"string"==typeof t.optionId)return{kind:t.kind,itemId:t.itemId,revision:t.revision,questionId:t.questionId,optionId:t.optionId};if("question-free-text"===t.kind&&"string"==typeof t.questionId)return{kind:t.kind,itemId:t.itemId,revision:t.revision,questionId:t.questionId}}catch{}return null}function jw(e){return jf(e).find(t=>"approval"===t.body.kind&&"pending"===t.body.resolution.state&&_E(t.itemId,e.actionablePromptIds))??null}function jS(e){return jf(e).find(t=>"question"===t.body.kind&&"pending"===t.body.resolution.state&&_E(t.itemId,e.actionablePromptIds))??null}var jx=oa(os()),jT="send_failed";function jk(e,t){return e===t||!!e&&!!t&&e.length===t.length&&e.every((e,i)=>{var r;return r=t[i],e.id===r.id&&e.kind===r.kind&&e.description===r.description&&e.name===r.name&&e.state===r.state&&e.startedAt===r.startedAt&&e.totalTokens===r.totalTokens&&e.stoppable===r.stoppable})}var jC=0;function jL(e){return e.reduce((e,t)=>bU(t)?e+1:e,0)}function jM(e,t,i){let r=new Map(e.map(e=>[e.clientMessageId,e]));for(let e of t)r.set(e.clientMessageId,e);let n=[...r.values()].sort((e,t)=>e.submittedAt-t.submittedAt),s=new Set(i.filter(e=>"message"===e.body.kind&&"user"===e.body.role).map(e=>e.itemId));return n.filter((e,t)=>t>=n.length-256||s.has(yn(e.clientMessageId)))}var jR=new Map;function jI(e,t,i=[],r=[]){let n={next:null},s=()=>n.next??=new Map(e);if(i.length>0){let t=new Set(i);for(let[i,r]of e)t.has(r.rosterItemId)&&s().delete(i)}for(let i of t){let t=function(e){if(!bU(e)||"message"!==e.body.kind)return null;let t=e.body.blocks.flatMap(b8);return 0===t.length?null:new Set(t.map(e=>e.id))}(i);if(null!==t)for(let[r,o]of n.next??e)o.rosterItemId===i.itemId&&i.revision>o.rosterRevision&&!t.has(r)&&s().delete(r)}let o=t=>{let i=(n.next??e).get(t.entry.id);((i?yc(t.rosterPosition,i.rosterPosition):-1)<0||i?.rosterItemId===t.rosterItemId&&t.rosterRevision>i.rosterRevision)&&s().set(t.entry.id,t)};for(let e of r)o({entry:e.entry,rosterItemId:e.itemId,rosterPosition:yl(e),rosterRevision:e.revision});for(let e of t)if(!(!bU(e)||"message"!==e.body.kind))for(let t of e.body.blocks.flatMap(b8))o({entry:t,rosterItemId:e.itemId,rosterPosition:yl(e),rosterRevision:e.revision});let a=n.next;return null===a?e:a.size>512?new Map([...a].sort(([,e],[,t])=>yc(t.rosterPosition,e.rosterPosition)).slice(0,512)):a}function jA(e,t){return jI(e??jR,t.items,t.removedItemIds,t.subagentRoster)}function jP(e,t){return e===t||!!e&&!!t&&e.state===t.state&&e.supportsTaskStop===t.supportsTaskStop&&e.supportsStopAll===t.supportsStopAll&&e.incomplete===t.incomplete&&jk(e.tasks,t.tasks)&&jk(e.settledTasks,t.settledTasks)&&x(e.children,t.children)}function jE(e,t){if(!e)return e;let{children:i,...r}=e,n=S Line truncated
`)}function FG(e,t){if(null===FZ(e)||new TextEncoder().encode(t).length>262144||!t.trim()&&!e.blocks.some(e=>"image-ref"===e.type))return null;if(t===FZ(e))return e;let i=[],r=!1;for(let n of e.blocks)"text"!==n.type?i.push(n):r||(i.push({type:"text",text:t}),r=!0);return r||i.unshift({type:"text",text:t}),{...e,blocks:i}}function FY(e,t){return e.current===t}sz({workspaceId:sj().min(1)}).strict(),FU.extend({observedCursor:Fj}),sz({}).strict(),s$({}),s$({agent:FW,sessionId:FB.optional(),worktree:FQ("Invalid worktree selector").optional(),waitForListing:sO().optional(),savedOnly:sO().optional()}),sz({envelope:FF,command:sZ(["clear","compact"]),delivery:sY("queue-if-active").optional()}).strict(),sz({envelope:FF,change:sV("kind",[sz({kind:sY("set"),objective:sj().max(4e3).refine(e=>e.trim().length>0,"Objective is empty")}).strict(),sz({kind:sY("status"),status:sZ(["active","paused"])}).strict(),sz({kind:sY("clear")}).strict()])}).strict(),sz({sessionId:FB,holderId:FQ("Invalid holder id")}).strict(),sz({sessionIds:sH(FB).max(512).optional()}).strict(),sz({sessionIds:sH(FB).max(512).optional()}).strict(),sz({sessionId:FB,direction:sZ(["tail","before","after"]),cursor:Fj.optional(),limit:sF().int().positive().max(200).optional()}).strict(),sz({sessionId:FB,cursor:Fj.optional()}).strict(),sz({includePrompts:sO().optional()}),sz({sessionId:FB,subscriptionId:FQ("Invalid subscription id").optional()}).strict(),sz({sessionId:FB}).strict(),sz({envelope:FF,itemId:FQ("Invalid item id",4096),expectedEpoch:FQ("Invalid journal epoch")}).strict();var FX=oa(os()),FJ=oa(os()),F0=[],F1={},F5=oa(os()),F2=oa(os());function F3(e,t){let i;if(!e)return null;try{i=JSON.parse(e)}catch{return null}if(!i||"object"!=typeof i)return null;let r=i.approval;if(!r||"object"!=typeof r)return null;let n=r.tool;if("string"!=typeof n||0===n.length)return null;let s=r.summary;return{title:`Allow ${n}?`,detail:"string"==typeof s&&s.length>0?s:void 0,options:[{label:"Allow",send:"opencode"===Am(t)?"\r":"1"},{label:"Deny",send:"\x1b"}]}}var F6=new Set(["blocked","waiting"]),F4=[/\bpermission\b/i,/\bapprove\b/i,/\bapproval\b/i,/\ballow\b/i,/\bdeny\b/i,/\bgrant\b/i,/\bauthorize\b/i,/\bdo you want to\b/i,/\bwould you like to\b/i,/\bproceed\?/i,/\bconfirm\b/i,/\(y\/n\)/i,/\by\/n\b/i,/\byes\/no\b/i,/\bplease confirm\b/i],F7=/(?:^|\n)\s*(\d+)[.)]\s*([^\n]+)/g;function F8(e,t=40){let i=e.replace(/\s+/g," ").trim();return i.length>t?`${i.slice(0,t-1)}…`:i}var F9=oa(os());function Oe(e,t){return(0,F9.useCallback)(async(...i)=>{let r=await e(...i);return r&&t(),r},[e,t])}var Ot=oa(os()),Oi=oa(os()),Or=oa(os()),On=oa(os()),Os=oa(os()),Oo=oa(os()),Oa=oa(os()),Ol=oa(oi()),Oc=new Map;function Od(e,t){return`orca:nativeChatTabs:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}async function Ou(){await null;try{let e=await sh.getItem("orca:defaultSessionView");return{value:"chat"===e||"terminal"===e?e:null,loaded:!0,hasStoredValue:null!==e}}catch{return{value:null,loaded:!1,hasStoredValue:!1}}}async function Oh(){return(await Ou()).value??"terminal"}async function Of(e){let t,i;try{t=await sh.getItem(e)}catch{return{overrides:new Map,loaded:!1}}if(!t)return{overrides:new Map,loaded:!0};try{i=JSON.parse(t)}catch{return{overrides:new Map,loaded:!0}}return Array.isArray(i)?{overrides:new Map(i.filter(e=>"string"==typeof e).map(e=>[e,"chat"])),loaded:!0}:i&&"object"==typeof i?{overrides:new Map(Object.entries(i).filter(e=>"terminal"===e[1]||"chat"===e[1])),loaded:!0}:{overrides:new Map,loaded:!0}}async function Op(e,t){let i=Od(e,t);return await Oc.get(i),Of(i)}async function Om(e,t,i,r){let n=Od(e,t),s=(Oc.get(n)??Promise.resolve()).then(async()=>{let e=await Of(n);if(!e.loaded)throw Error("Session view overrides could not be read");e.overrides.set(i,r);let t=JSON.stringify(Object.fromEntries(e.overrides));await tJ(n,t)}),o=s.catch(()=>{});Oc.set(n,o);try{await s}finally{Oc.get(n)===o&&Oc.delete(n)}}function Og(e,t,i){return e.hostId===t&&e.worktreeId===i}function Ob(e,t){let i=new Map(e);for(let[e,r]of t)i.set(e,r);return i}var Ov=oa(os()),Oy=oa(os()),O_=oa(os()),Ow=oa(os()),OS=oa(oi()),Ox=oa(os()),OT=oa(os());function Ok(e){return Array.isArray(e)&&e.every(e=>null!=e&&"object"==typeof e&&Number.isInteger(e.row)&&Number.isInteger(e.startCol)&&Number.isInteger(e.endCol)&&"string"==typeof e.uri)}var OC=sB-function(e="a".repeat(function(){let e=/\{(\d+)\}\$$/.exec(su.source);if(null===e)throw Error("the bridge id pattern is no longer a fixed length");return Number(e[1])}())){return JSON.stringify({v:sd,type:"event",id:e,seq:Number.MAX_SAFE_INTEGER,payload:0}).length}(),OL=oa(os()),OM=oa(os()),OR=oa(os());function OI(e,t){if(e===t)return!0;if(!e||!t||e.mode!==t.mode)return!1;let i=e.theme,r=t.theme;for(let e in i)if(Object.hasOwn(i,e)&&(!Object.hasOwn(r,e)||i[e]!==r[e]))return!1;for(let e in r)if(Object.hasOwn(r,e)&&!Object.hasOwn(i,e))return!1;return!0}function OA(e){return e.flatMap(e=>"terminal"!==e.type||"string"!=typeof e.terminal?[]:[{handle:e.terminal,title:e Line truncated
`)}function FG(e,t){if(null===FZ(e)||new TextEncoder().encode(t).length>262144||!t.trim()&&!e.blocks.some(e=>"image-ref"===e.type))return null;if(t===FZ(e))return e;let i=[],r=!1;for(let n of e.blocks)"text"!==n.type?i.push(n):r||(i.push({type:"text",text:t}),r=!0);return r||i.unshift({type:"text",text:t}),{...e,blocks:i}}function FY(e,t){return e.current===t}sz({workspaceId:sj().min(1)}).strict(),FU.extend({observedCursor:Fj}),sz({}).strict(),s$({}),s$({agent:FW,sessionId:FB.optional(),worktree:FQ("Invalid worktree selector").optional(),waitForListing:sO().optional(),savedOnly:sO().optional()}),sz({envelope:FF,command:sZ(["clear","compact"]),delivery:sY("queue-if-active").optional()}).strict(),sz({envelope:FF,change:sV("kind",[sz({kind:sY("set"),objective:sj().max(4e3).refine(e=>e.trim().length>0,"Objective is empty")}).strict(),sz({kind:sY("status"),status:sZ(["active","paused"])}).strict(),sz({kind:sY("clear")}).strict()])}).strict(),sz({sessionId:FB,holderId:FQ("Invalid holder id")}).strict(),sz({sessionIds:sH(FB).max(512).optional()}).strict(),sz({sessionIds:sH(FB).max(512).optional()}).strict(),sz({sessionId:FB,direction:sZ(["tail","before","after"]),cursor:Fj.optional(),limit:sF().int().positive().max(200).optional()}).strict(),sz({sessionId:FB,cursor:Fj.optional()}).strict(),sz({includePrompts:sO().optional()}),sz({sessionId:FB,subscriptionId:FQ("Invalid subscription id").optional()}).strict(),sz({sessionId:FB}).strict(),sz({envelope:FF,itemId:FQ("Invalid item id",4096),expectedEpoch:FQ("Invalid journal epoch")}).strict();var FX=oa(os()),FJ=oa(os()),F0=[],F1={},F5=oa(os()),F2=oa(os());function F3(e,t){let i;if(!e)return null;try{i=JSON.parse(e)}catch{return null}if(!i||"object"!=typeof i)return null;let r=i.approval;if(!r||"object"!=typeof r)return null;let n=r.tool;if("string"!=typeof n||0===n.length)return null;let s=r.summary;return{title:`Allow ${n}?`,detail:"string"==typeof s&&s.length>0?s:void 0,options:[{label:"Allow",send:"opencode"===Am(t)?"\r":"1"},{label:"Deny",send:"\x1b"}]}}var F6=new Set(["blocked","waiting"]),F4=[/\bpermission\b/i,/\bapprove\b/i,/\bapproval\b/i,/\ballow\b/i,/\bdeny\b/i,/\bgrant\b/i,/\bauthorize\b/i,/\bdo you want to\b/i,/\bwould you like to\b/i,/\bproceed\?/i,/\bconfirm\b/i,/\(y\/n\)/i,/\by\/n\b/i,/\byes\/no\b/i,/\bplease confirm\b/i],F7=/(?:^|\n)\s*(\d+)[.)]\s*([^\n]+)/g;function F8(e,t=40){let i=e.replace(/\s+/g," ").trim();return i.length>t?`${i.slice(0,t-1)}…`:i}var F9=oa(os());function Oe(e,t){return(0,F9.useCallback)(async(...i)=>{let r=await e(...i);return r&&t(),r},[e,t])}var Ot=oa(os()),Oi=oa(os()),Or=oa(os()),On=oa(os()),Os=oa(os()),Oo=oa(os()),Oa=oa(os()),Ol=oa(oi()),Oc=new Map;function Od(e,t){return`orca:nativeChatTabs:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}async function Ou(){await null;try{let e=await sh.getItem("orca:defaultSessionView");return{value:"chat"===e||"terminal"===e?e:null,loaded:!0,hasStoredValue:null!==e}}catch{return{value:null,loaded:!1,hasStoredValue:!1}}}async function Oh(){let e=await Ou();return e.value??(e.loaded?"chat":"terminal")}async function Of(e){let t,i;try{t=await sh.getItem(e)}catch{return{overrides:new Map,loaded:!1}}if(!t)return{overrides:new Map,loaded:!0};try{i=JSON.parse(t)}catch{return{overrides:new Map,loaded:!0}}return Array.isArray(i)?{overrides:new Map(i.filter(e=>"string"==typeof e).map(e=>[e,"chat"])),loaded:!0}:i&&"object"==typeof i?{overrides:new Map(Object.entries(i).filter(e=>"terminal"===e[1]||"chat"===e[1])),loaded:!0}:{overrides:new Map,loaded:!0}}async function Op(e,t){let i=Od(e,t);return await Oc.get(i),Of(i)}async function Om(e,t,i,r){let n=Od(e,t),s=(Oc.get(n)??Promise.resolve()).then(async()=>{let e=await Of(n);if(!e.loaded)throw Error("Session view overrides could not be read");e.overrides.set(i,r);let t=JSON.stringify(Object.fromEntries(e.overrides));await tJ(n,t)}),o=s.catch(()=>{});Oc.set(n,o);try{await s}finally{Oc.get(n)===o&&Oc.delete(n)}}function Og(e,t,i){return e.hostId===t&&e.worktreeId===i}function Ob(e,t){let i=new Map(e);for(let[e,r]of t)i.set(e,r);return i}var Ov=oa(os()),Oy=oa(os()),O_=oa(os()),Ow=oa(os()),OS=oa(oi()),Ox=oa(os()),OT=oa(os());function Ok(e){return Array.isArray(e)&&e.every(e=>null!=e&&"object"==typeof e&&Number.isInteger(e.row)&&Number.isInteger(e.startCol)&&Number.isInteger(e.endCol)&&"string"==typeof e.uri)}var OC=sB-function(e="a".repeat(function(){let e=/\{(\d+)\}\$$/.exec(su.source);if(null===e)throw Error("the bridge id pattern is no longer a fixed length");return Number(e[1])}())){return JSON.stringify({v:sd,type:"event",id:e,seq:Number.MAX_SAFE_INTEGER,payload:0}).length}(),OL=oa(os()),OM=oa(os()),OR=oa(os());function OI(e,t){if(e===t)return!0;if(!e||!t||e.mode!==t.mode)return!1;let i=e.theme,r=t.theme;for(let e in i)if(Object.hasOwn(i,e)&&(!Object.hasOwn(r,e)||i[e]!==r[e]))return!1;for(let e in r)if(Object.hasOwn(r,e)&&!Object.hasOwn(i,e))return!1;return!0}function OA(e){return e.flatMap(e=>"terminal"!==e.type||"string"!=typeof e.terminal?[]:[{ Line truncated
`)===e.actionablePromptIds?.join(`
`))&&(void 0===s.working||s.working===e.working)&&l?.turnId===e.activity?.turnId&&l?.text===e.activity?.text&&"ready"===e.status&&void 0===e.error&&o.currentRequests===e.currentRequests&&o.requestMarker===e.requestMarker&&o.requestAuthority===e.requestAuthority)return e;let h=u?e.items:jQ(e.items,c,s.batch.removedItemIds),f=function(e,t,i){let r=Math.max(0,e.length-i),n=0;for(let i=e.length-1;i>=r;i-=1)if(bU(e[i])&&(n+=1)>t){r=i+1;break}return 0===r?e:e.slice(r)}(h,e.retainedOwnItemLimit,e.retainedItemCap),p=[...c.length<s.batch.items.length?s.batch.items.filter(e=>!c.includes(e)):[],...h.slice(0,h.length-f.length)].some(e=>null!==yx(e.body));return{...e,...o,cursor:s.batch.cursor,fence:s.fence??e.fence,items:f,subagentRoster:d,hasOlder:_I(f,f.length<h.length||e.hasOlder),submissions:0===s.batch.submissions.length&&0===s.batch.removedItemIds.length?e.submissions:jM(e.submissions,s.batch.submissions,f),status:"ready",error:void 0,readRefusal:void 0,commands:void 0!==s.commands?s.commands:e.commands,latestTurn:function(e,t){let{items:i,removedItemIds:r,submissions:n}=t.batch;return i.length>0||r.length>0||n.length>0||void 0!==t.latestTurn?t.latestTurn:e}(e.latestTurn,s),actionablePromptIds:function(e,t){let{items:i,removedItemIds:r,submissions:n}=t.batch;return i.length>0||r.length>0||n.length>0||void 0!==t.actionablePromptIds?t.actionablePromptIds:e}(e.actionablePromptIds,s),working:function(e,t){let{items:i,removedItemIds:r,submissions:n}=t.batch;return i.length>0||r.length>0||n.length>0||void 0!==t.working?t.working:e}(e.working,s),...jj(s,e),backgroundTasks:a,...void 0!==l?{activity:l}:{},...p?{unloadedTurnRevisions:(e.unloadedTurnRevisions??0)+1}:{},...jD(s.hostNow,i,e.hostClock)}}(i,e,Date.now());if(r===i)return t;let n=new Map(t);for(n.delete(s),n.set(s,r);n.size>32;){let e=n.keys().next().value;if(void 0===e)break;n.delete(e)}return n})},[s]),v=(0,jx.useCallback)(e=>{let t,i=jH(e);b({type:"error",message:(t=jH(e))?Rv(Rb(Rn(t),"read-history")):e instanceof Error?e.message:"object"==typeof e&&null!==e?"message"in e?String(e.message??""):"":String(e),...i?{refusal:i}:{}})},[b]),y=(0,jx.useCallback)(e=>{s&&c(t=>{let i=t.get(s)??jK,r=function(e,t){if("end"===t.type||void 0===t.queuedMessages)return e;let i=t.queuedMessages??[];return 0===i.length&&null!==e&&0===e.length?e:[...i].sort((e,t)=>e.position-t.position)}(i.messages,e),n=function(e,t){if("end"===t.type||void 0===t.queuedMessages)return e;let i=t.queuePause??null;return null===i!=(null===e)?i:i?.reason===e?.reason?e:i}(i.pause,e);if(r===i.messages&&n===i.pause)return t;let o=new Map(t);for(o.delete(s),o.set(s,{messages:r,pause:n});o.size>32;){let e=o.keys().next().value;if(void 0===e)break;o.delete(e)}return o})},[s]);(0,jx.useEffect)(()=>{if(m(),!t||!n||!r||!i)return;b({type:"loading"});let e=!0,s=(jC+=1,`mobile-chat:${jC}`),o=jN(t,"agentSession.hold",{sessionId:n,holderId:s}),a=function(e){let t=!1,i=0,r=!1,n=()=>{},s=()=>!t&&e.isCurrent(),o=()=>{i+=1,a.invalidate();let e=n;n=()=>{},e()},a=function(e){let t=0,i,r=!1,n;async function s(){if(r||!i||n===i.version)return;r=!0;let o=t,a=i;n=a.version;let l=0,c=[],d=()=>t===o&&i?.version===a.version;try{for(;d();){let t=await e.read({sessionId:a.sessionId,version:a.version,cursor:l});if(!d())return;if(t.restart){if(t.marker.sessionId!==a.sessionId||t.marker.version===a.version||t.marker.contract!==tM)throw Error("Invalid request owner");i=a=t.marker,n=a.version,e.replaceMarker(a),c.length=0,l=0;continue}if(t.marker.version!==a.version||t.marker.owner!==a.owner||t.marker.epoch!==a.epoch||t.marker.sessionId!==a.sessionId)throw Error("Current-request version changed");if(c.push(t.json),null===t.nextCursor){let t=JSON.parse(c.join(""));if(!Array.isArray(t)||!t.every(y4)||!t.every(e=>("approval"===e.body.kind||"question"===e.body.kind)&&"pending"===e.body.resolution.state))throw Error("Invalid current requests");e.complete(a,t);return}if(!Number.isSafeInteger(t.nextCursor)||t.nextCursor<=l)throw Error("Invalid current-request cursor");l=t.nextCursor}}catch(t){d()&&e.error(t,a)}finally{r=!1,s()}}return{observe(e){e&&e.contract!==tM||i?.version!==e?.version&&(e&&i?.publisher===e.publisher&&e.revision<=i.revision||(i=e,s()))},invalidate(){t+=1,i=void 0,n=void 0}}}({read:e.read,complete:(t,i)=>{s()&&e.apply({type:"requests-complete",marker:t,items:i})},replaceMarker:t=>{s()&&e.apply({type:"requests-marker",marker:t})},error:i=>{s()&&(o(),e.error(i),r?t=!0:(r=!0,l()))}});function l(){let r=++i,l=!0;n=e.open(n=>{if(!(!s()||i!==r)){if("object"==typeof n&&null!==n&&"type"in n&&"error"===n.type){o(),t=!0,e.error(n);return}(function(e){if("object"!=typeof e||null===e)return!1;let t="type"in e?e.type:void 0;return"snapshot"===t||"batch"===t||"reset"===t||"end"===t})(n)&&(("snapshot"===n.type||"reset"===n.type)&&a.invalidate(),e.apply({type:"event",event:n,opensSubscription:l}),e.applyQueued(n),"end"===n.type?a.invalidate():(l=!1,n.currentRequests?.sessionId===e.sessionId&&a.observe(n.currentRequests)))}})}return l(), Line truncated
${i}`}(e,T),C=FS(k,x);if(0===C.blocks.length)return"rejected";let L={clientMessageId:tm(),body:C,queuedAt:Date.now(),...p?{sentWhileStopping:!0}:{}},M=u&&i?function(e,t){if("claude"!==e)return;let i=e=>{let i=t.find(t=>t.id===e)?.kind;return i?.type==="select"?i.currentValue:void 0},r=i("model"),n=i("effort");return r?{model:r,...n?{effort:n}:{}}:void 0}(i,o.snapshot):void 0,R=await Fk({client:r,sessionId:h,expectedRuntimeFence:y,text:k,attachments:x,...(v=f.current,d&&!xO(jf(v)))?{delivery:"queue-if-active"}:{},...M?{options:M}:{},deadline:g,clientMessageId:L.clientMessageId,onAccepted:e=>t({...L,...e?{recordedCursor:e}:{}},m),onError:c});return"unknown"===R&&l(L),R},[t,i,r,n,s,o,a,l,c,d,u,h,f,p])}({agent:n,client:o,sessionId:l,enabled:d,queueCapable:p,commandsWait:m,stateRef:x,stopping:Y,accept:W.accept,hold:W.hold,commandPending:_,controller:B,onSendError:h,carriesOptions:f?.sendOptions===!0}),ee=(0,Q4.useMemo)(()=>({thinking:K,activityText:q,stopping:Y,stopRequestInFlight:X,...Y?{afterStop:p&&!xO(jf(S))?"queue":"send"}:{}}),[K,q,Y,X,p,S]),{items:et,currentRequests:ei,actionablePromptIds:er,status:en}=S,[es,eo]=(0,Q4.useMemo)(()=>{let e={items:et,currentRequests:ei,actionablePromptIds:er};return[jw(e),jS(e)]},[et,ei,er]),ea=(0,Q4.useMemo)(()=>({working:null!==N,prompt:null!==es||null!==eo}),[es,eo,N]),el=function(e){let{appendComposerText:t,mutate:i,onActionResolved:r,onSendError:n,queuedMessages:s,queuePause:o,sessionKey:a,submissions:l}=e,c=!0===e.agentWorking,d=(0,FI.useMemo)(()=>(function(e,t,i={}){if(!e||0===e.length)return[];let r=new Set(t.flatMap(e=>void 0!==e.queuedMessageId&&"rejected"!==e.dispatchState?[e.queuedMessageId]:[])),n=!1,s=[];for(let t of e){var o,a;if("returned"!==t.state&&r.has(t.messageId))continue;let e=!0===t.paused,l="returned"===t.state?function(e,t,i=[]){let r=e.returnedReason??null,n=e.returnedRejection;return Rw(n,i)?Rv(Rm("send")):_C({dispatchState:"rejected",reason:r,rejection:n})?"Stopped before it was sent":Rv(function(e,t={},i){return RS(e.reason,"send",i,t)}({kind:"rejected",reason:r},{agentName:t,retryControl:!0},_b(n)))}(t,i.agentName,i.statedFailures):e?(o=t.pausedReason,a=void 0!==t.body.command&&!0===i.agentWorking,o===jT?a?"Couldn't send — tap Send to retry once the agent finishes":"Couldn't send — tap Send to retry":"Paused"):n?"Waiting — a message ahead needs attention":null;s.push({messageId:t.messageId,text:t.body.blocks.flatMap(e=>"text"===e.type?[e.text]:[]).join(`
@@ -621,4 +621,4 @@ Return JSON only. A person will review and explicitly apply the result to the de
padding-bottom:2px;
}
}
`;function rz({name:e}){return(0,ry.jsx)("span",{"data-tool-icon":!0,"aria-hidden":"true",children:(0,ry.jsx)("svg",{viewBox:"0 0 24 24",width:"22",height:"22",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:(0,ry.jsx)("path",{d:{help:"M16 10a6 6 0 1 0-12 0 6 6 0 0 0 12 0zM15 15l5 5",desktops:"M3 4h18v13H3zM8 21h8M12 17v4",account:"M20 21v-2a7 7 0 0 0-14 0v2M16 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0",ruflo:"M4 6h16M4 12h16M4 18h16M8 3v6M16 9v6M10 15v6",teams:"M12 7a3 3 0 1 0 0-6 3 3 0 0 0 0 6M5 21a7 7 0 0 1 14 0M4 13a2.5 2.5 0 1 0 0-5M20 13a2.5 2.5 0 1 0 0-5",walkthrough:"M5 3h14v18H5zM10 8l5 4-5 4z",demo:"M3 3h8v10H3zM15 3h6v6h-6zM3 17h8v4H3zM15 13h6v8h-6z"}[e]})})})}var rO=es(eo()),rA=es(X()),rM=es(ee()),rT=class{held=null;listeners=new Set;read(){return this.held}prime(e){let t=this.held?.state!==e.state;this.held=e,t&&this.fanOut(e.state)}apply(e){let t=this.held;return null===t?"unprimed":null!==t.generation&&null!==e.generation&&e.generation<t.generation?"stale":(this.held=e,this.fanOut(e.state),"applied")}onStateChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}close(){let e=this.held;null!==e&&"disconnected"!==e.state&&(this.held={...e,state:"disconnected"},this.fanOut("disconnected")),this.listeners.clear()}fanOut(e){for(let t of this.listeners)t(e)}},rP=class extends Error{constructor(){super("the page bridge has no session yet; wait for init before calling the client"),this.name="BridgeClientNotReadyError"}},r_=class extends Error{constructor(){super("the page bridge was closed"),this.name="BridgeClientClosedError"}},rL=class extends Error{constructor(){super("the shell behind this page was replaced"),this.name="BridgeShellReplacedError"}},rq=class extends Error{constructor(e){super(e),this.name="BridgeClientCapExceededError"}},rD=class extends Error{constructor(e){super(`the reply could not be read (${e})`),this.name="BridgeReplyRefusedError",M(this)}},rF=class extends Error{constructor(){super("the request could not be posted to the shell"),this.name="BridgeSendFailedError"}},rW=class extends Error{code="bridge_request_oversized";constructor(){super("This action sends too much at once to reach RuFlo. Try it on fewer files."),this.name="BridgeRequestOversizedError"}},rH=class extends Error{code="native_verb_not_a_verb";constructor(e){super(`${e} is not a native verb`),this.name="BridgeClientNotNativeVerbError"}},rU=class extends Error{code="bridge_rpc_envelope_ungranted";constructor(){super("this app version cannot send extra request fields; update the RuFlo app"),this.name="BridgeRpcEnvelopeUngrantedError"}},rB=class extends Error{code="bridge_rpc_envelope_invalid";constructor(){super("extra request fields must be a plain JSON object"),this.name="BridgeRpcEnvelopeInvalidError"}},r$=4*F,rV=class{pending=new Map;refused=new Map;accept(e){let t=this.refused.get(e.id);if(void 0!==t)return{status:"failed",refusal:t};if(!("part"in e))return this.pending.delete(e.id),{status:"complete",payload:e.payload};let{id:a,part:r,chunk:o}=e,n=this.pending.get(a);if(r.i>=r.of||void 0!==n&&n.of!==r.of)return this.fail(a,"inconsistent-part");if(void 0===n&&this.pending.size>=q)return this.fail(a,"too-many-pending");let s=n??{of:r.of,chunks:new Map,units:0};if(s.chunks.has(r.i))return this.fail(a,"duplicate-part");if(this.assemblingUnits()+o.length>r$)return this.fail(a,"too-many-pending");let i=s.units+o.length;return i>F?this.fail(a,"reply-too-large"):(s.chunks.set(r.i,o),s.units=i,this.pending.set(a,s),s.chunks.size<s.of?{status:"pending"}:(this.pending.delete(a),function(e){let t,a=[...e.chunks.entries()].sort(([e],[t])=>e-t).map(([,e])=>e).join("");if(W(a)>F)return{status:"failed",refusal:"reply-too-large"};try{t=JSON.parse(a)}catch{return{status:"failed",refusal:"malformed-json"}}let r=j.safeParse(t);return r.success?{status:"complete",payload:r.data}:{status:"failed",refusal:"unrecognised-message"}}(s)))}discard(e){this.pending.delete(e),this.refused.delete(e)}clear(){this.pending.clear(),this.refused.clear()}assemblingUnits(){let e=0;for(let t of this.pending.values())e+=t.units;return e}fail(e,t){if(this.pending.delete(e),this.refused.size>=q){let e=this.refused.keys().next();e.done||this.refused.delete(e.value)}return this.refused.set(e,t),{status:"failed",refusal:t}}},rG=class{pending=new Map;assembler=new rV;get size(){return this.pending.size}has(e){return this.pending.has(e)}open(e,t){this.pending.set(e,t)}abandon(e){this.pending.delete(e)}acceptReply(e){let t=this.assembler.accept(e);if("pending"===t.status){this.pending.has(e.id)||this.assembler.discard(e.id);return}"failed"===t.status?this.fail(e.id,new rD(t.refusal)):this.settle(e.id,e=>{e.resolve(t.payload)})}fail(e,t){this.settle(e,e=>{e.reject(t)})}closeAll(e=new r_){let t=M(e);for(let e of this.pending.values())e.reject(t);this.pending.clear(),this.assembler.clear()}settle(e,t){this.assembler.discard(e);let a=this.pending.get(e);void 0!==a&&(this.pending.delete(e),t(a))}};fu Line truncated
`;function rz({name:e}){return(0,ry.jsx)("span",{"data-tool-icon":!0,"aria-hidden":"true",children:(0,ry.jsx)("svg",{viewBox:"0 0 24 24",width:"22",height:"22",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:(0,ry.jsx)("path",{d:{help:"M16 10a6 6 0 1 0-12 0 6 6 0 0 0 12 0zM15 15l5 5",desktops:"M3 4h18v13H3zM8 21h8M12 17v4",account:"M20 21v-2a7 7 0 0 0-14 0v2M16 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0",ruflo:"M4 6h16M4 12h16M4 18h16M8 3v6M16 9v6M10 15v6",teams:"M12 7a3 3 0 1 0 0-6 3 3 0 0 0 0 6M5 21a7 7 0 0 1 14 0M4 13a2.5 2.5 0 1 0 0-5M20 13a2.5 2.5 0 1 0 0-5",walkthrough:"M5 3h14v18H5zM10 8l5 4-5 4z",demo:"M3 3h8v10H3zM15 3h6v6h-6zM3 17h8v4H3zM15 13h6v8h-6z"}[e]})})})}var rO=es(eo()),rA=es(X()),rM=es(ee()),rT=class{held=null;listeners=new Set;read(){return this.held}prime(e){let t=this.held?.state!==e.state;this.held=e,t&&this.fanOut(e.state)}apply(e){let t=this.held;return null===t?"unprimed":null!==t.generation&&null!==e.generation&&e.generation<t.generation?"stale":(this.held=e,this.fanOut(e.state),"applied")}onStateChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}close(){let e=this.held;null!==e&&"disconnected"!==e.state&&(this.held={...e,state:"disconnected"},this.fanOut("disconnected")),this.listeners.clear()}fanOut(e){for(let t of this.listeners)t(e)}},rP=class extends Error{constructor(){super("the page bridge has no session yet; wait for init before calling the client"),this.name="BridgeClientNotReadyError"}},r_=class extends Error{constructor(){super("the page bridge was closed"),this.name="BridgeClientClosedError"}},rL=class extends Error{constructor(){super("the shell behind this page was replaced"),this.name="BridgeShellReplacedError"}},rq=class extends Error{constructor(e){super(e),this.name="BridgeClientCapExceededError"}},rD=class extends Error{constructor(e){super(`the reply could not be read (${e})`),this.name="BridgeReplyRefusedError",M(this)}},rF=class extends Error{constructor(){super("the request could not be posted to the shell"),this.name="BridgeSendFailedError"}},rW=class extends Error{code="bridge_request_oversized";constructor(){super("This action sends too much at once to reach RuFlo. Try it on fewer files."),this.name="BridgeRequestOversizedError"}},rH=class extends Error{code="native_verb_not_a_verb";constructor(e){super(`${e} is not a native verb`),this.name="BridgeClientNotNativeVerbError"}},rU=class extends Error{code="bridge_rpc_envelope_ungranted";constructor(){super("this app version cannot send extra request fields; update the RuFlo app"),this.name="BridgeRpcEnvelopeUngrantedError"}},rB=class extends Error{code="bridge_rpc_envelope_invalid";constructor(){super("extra request fields must be a plain JSON object"),this.name="BridgeRpcEnvelopeInvalidError"}},r$=4*F,rV=class{pending=new Map;refused=new Map;accept(e){let t=this.refused.get(e.id);if(void 0!==t)return{status:"failed",refusal:t};if(!("part"in e))return this.pending.delete(e.id),{status:"complete",payload:e.payload};let{id:a,part:r,chunk:o}=e,n=this.pending.get(a);if(r.i>=r.of||void 0!==n&&n.of!==r.of)return this.fail(a,"inconsistent-part");if(void 0===n&&this.pending.size>=q)return this.fail(a,"too-many-pending");let s=n??{of:r.of,chunks:new Map,units:0};if(s.chunks.has(r.i))return this.fail(a,"duplicate-part");if(this.assemblingUnits()+o.length>r$)return this.fail(a,"too-many-pending");let i=s.units+o.length;return i>F?this.fail(a,"reply-too-large"):(s.chunks.set(r.i,o),s.units=i,this.pending.set(a,s),s.chunks.size<s.of?{status:"pending"}:(this.pending.delete(a),function(e){let t,a=[...e.chunks.entries()].sort(([e],[t])=>e-t).map(([,e])=>e).join("");if(W(a)>F)return{status:"failed",refusal:"reply-too-large"};try{t=JSON.parse(a)}catch{return{status:"failed",refusal:"malformed-json"}}let r=j.safeParse(t);return r.success?{status:"complete",payload:r.data}:{status:"failed",refusal:"unrecognised-message"}}(s)))}discard(e){this.pending.delete(e),this.refused.delete(e)}clear(){this.pending.clear(),this.refused.clear()}assemblingUnits(){let e=0;for(let t of this.pending.values())e+=t.units;return e}fail(e,t){if(this.pending.delete(e),this.refused.size>=q){let e=this.refused.keys().next();e.done||this.refused.delete(e.value)}return this.refused.set(e,t),{status:"failed",refusal:t}}},rG=class{pending=new Map;assembler=new rV;get size(){return this.pending.size}has(e){return this.pending.has(e)}open(e,t){this.pending.set(e,t)}abandon(e){this.pending.delete(e)}acceptReply(e){let t=this.assembler.accept(e);if("pending"===t.status){this.pending.has(e.id)||this.assembler.discard(e.id);return}"failed"===t.status?this.fail(e.id,new rD(t.refusal)):this.settle(e.id,e=>{e.resolve(t.payload)})}fail(e,t){this.settle(e,e=>{e.reject(t)})}closeAll(e=new r_){let t=M(e);for(let e of this.pending.values())e.reject(t);this.pending.clear(),this.assembler.clear()}settle(e,t){this.assembler.discard(e);let a=this.pending.get(e);void 0!==a&&(this.pending.delete(e),t(a))}};fu Line truncated
+1 -1
View File
@@ -70,6 +70,6 @@
</head>
<body>
<div id="root"></div>
<script type="module" src="/assets/48fae3d9447c3e75964d9031d9ede8a0d784d091f9c0b0625c12d3a73b621247.js"></script>
<script type="module" src="/assets/393753fcec4b8acaddf3b0214cba3fa3814b945530e46703eebfef26582ef924.js"></script>
</body>
</html>
+15 -15
View File
@@ -1,12 +1,12 @@
{
"schemaVersion": 1,
"buildId": "1dd1e40238ecaa5a0bf1fb723992f8461d814a1dd9e42690a05ca38be090c1f0",
"buildId": "a8732ed7cbe5be7ff01a9704c50270f7f58591c4902e92e99396775dcbe4e512",
"desktopVersion": "1.4.214",
"minCompatibleRuntimeProtocolVersion": 2,
"runtimeProtocolVersion": 3,
"pageVersion": 1,
"entrypoint": "index.html",
"totalBytes": 14972943,
"totalBytes": 14973499,
"assets": [
{
"path": "assets/023370fd50d18b0eca615bb6715d60291daf9e38df72e478878ac041efac4a8a.mp4",
@@ -44,6 +44,12 @@
"byteLength": 12012,
"contentType": "text/javascript; charset=utf-8"
},
{
"path": "assets/0812724a10c2f7e160171ae846c119900de484383435ea299085d7474108b765.js",
"sha256": "0812724a10c2f7e160171ae846c119900de484383435ea299085d7474108b765",
"byteLength": 1533941,
"contentType": "text/javascript; charset=utf-8"
},
{
"path": "assets/0944f11730bc7fe1d434b91a21a79c0d8badf70b9860bcbe0d8ef171ad16c70f.js",
"sha256": "0944f11730bc7fe1d434b91a21a79c0d8badf70b9860bcbe0d8ef171ad16c70f",
@@ -224,6 +230,12 @@
"byteLength": 7103,
"contentType": "text/javascript; charset=utf-8"
},
{
"path": "assets/393753fcec4b8acaddf3b0214cba3fa3814b945530e46703eebfef26582ef924.js",
"sha256": "393753fcec4b8acaddf3b0214cba3fa3814b945530e46703eebfef26582ef924",
"byteLength": 421872,
"contentType": "text/javascript; charset=utf-8"
},
{
"path": "assets/3cfddb6c48e4a53b864c10cb51b79d487f4fe7f2f5a468ef9f74e425f284a6e2.js",
"sha256": "3cfddb6c48e4a53b864c10cb51b79d487f4fe7f2f5a468ef9f74e425f284a6e2",
@@ -272,12 +284,6 @@
"byteLength": 2005,
"contentType": "text/javascript; charset=utf-8"
},
{
"path": "assets/48fae3d9447c3e75964d9031d9ede8a0d784d091f9c0b0625c12d3a73b621247.js",
"sha256": "48fae3d9447c3e75964d9031d9ede8a0d784d091f9c0b0625c12d3a73b621247",
"byteLength": 421872,
"contentType": "text/javascript; charset=utf-8"
},
{
"path": "assets/490dff5263bf369721e167cfeb10d4de9d64c24d33fdcd8a6f98be29f240f778.js",
"sha256": "490dff5263bf369721e167cfeb10d4de9d64c24d33fdcd8a6f98be29f240f778",
@@ -1034,12 +1040,6 @@
"byteLength": 10615,
"contentType": "text/javascript; charset=utf-8"
},
{
"path": "assets/ff5bafc87134b6a566c67255bb9546eabc92bd5b335b13af7d063abaa4a9fd20.js",
"sha256": "ff5bafc87134b6a566c67255bb9546eabc92bd5b335b13af7d063abaa4a9fd20",
"byteLength": 1533385,
"contentType": "text/javascript; charset=utf-8"
},
{
"path": "assets/ff7d075108ea20b3bd3c8ddf6d2dbd27e2369c32bfbf4d6c6afe3c33c794ec08.js",
"sha256": "ff7d075108ea20b3bd3c8ddf6d2dbd27e2369c32bfbf4d6c6afe3c33c794ec08",
@@ -1048,7 +1048,7 @@
},
{
"path": "index.html",
"sha256": "80612ab8dd761f948c90b2c30e3a2751893de67895145387078632cd1f36dffb",
"sha256": "78fdf65d33bf712407c399a4a7c7525f17ea1d531641db0a35455232589e0454",
"byteLength": 2720,
"contentType": "text/html; charset=utf-8"
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@claude-flow/phone-host",
"version": "1.1.1",
"version": "1.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@claude-flow/phone-host",
"version": "1.1.1",
"version": "1.2.0",
"license": "MIT",
"dependencies": {
"@lydell/node-pty": "1.2.0-beta.18",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@claude-flow/phone-host",
"version": "1.1.1",
"version": "1.2.0",
"description": "Opt-in add-on: pair the RuFlo or Orca phone app with this computer over LAN or Tailscale (end-to-end encrypted), with an optional full-access mode for terminals and agent tabs",
"type": "module",
"license": "MIT",
+25
View File
@@ -28,6 +28,31 @@ export function defaultChatRoots(env = process.env) {
};
}
const MAX_CLAUDE_CONFIG_BYTES = 32 * 1024 * 1024;
/**
* Whether Claude Code already trusts this exact folder (`projects[cwd].hasTrustDialogAccepted` in
* its `.claude.json`), so it will not stop at its first-run trust prompt. Anything unreadable, and
* a trust only a parent folder holds, counts as not trusted: the cost is that the phone shows the
* terminal a little longer, never that the prompt is hidden behind the chat view.
*/
export async function claudeFolderTrusted(cwd, env = process.env) {
const files = [...new Set([join(absOr(env.CLAUDE_CONFIG_DIR, homedir()), '.claude.json'), join(homedir(), '.claude.json')])];
let real;
try { real = await realpath(cwd); } catch { real = cwd; }
for (const file of files) {
try {
if ((await stat(file)).size > MAX_CLAUDE_CONFIG_BYTES) continue;
const fh = await open(file, 'r');
let text;
try { text = await fh.readFile('utf8'); } finally { await fh.close(); }
const projects = JSON.parse(text)?.projects;
if (projects && typeof projects === 'object' && [cwd, real].some((p) => Object.hasOwn(projects, p) && projects[p]?.hasTrustDialogAccepted === true)) return true;
} catch { /* missing or unreadable: not trusted */ }
}
return false;
}
/** Claude Code's project directory name for a cwd (every non-alphanumeric becomes '-'). */
export const claudeProjectSlug = (cwd) => cwd.replace(/[^A-Za-z0-9]/g, '-');
+48 -6
View File
@@ -6,9 +6,10 @@
// catalog. That decides where a terminal starts. It is not a sandbox: a shell can go anywhere the
// user can.
import { randomUUID } from 'node:crypto';
import { stat } from 'node:fs/promises';
import { AGENT_TITLES, agentCommand, detectAgents, shellQuote } from './agents.mjs';
import { createChatMethods } from './chat-methods.mjs';
import { createChatSessions } from './chat-sessions.mjs';
import { claudeFolderTrusted, createChatSessions } from './chat-sessions.mjs';
import { initialTabStatus, nextTabStatus, statusFields, watchChatStatus } from './chat-status.mjs';
import { createFilesMethods } from './files-methods.mjs';
import { createQuickCommands } from './quick-commands.mjs';
@@ -25,6 +26,8 @@ export function submitDelayMs(text, platform = process.platform) {
const MUTATION_MEMORY = 256;
const MAX_TITLE = 200;
const FOREGROUND_CHECK_MS = 2000;
/** How long a Claude tab in an untrusted folder is watched for trust before the phone is left on the terminal. */
const TRUST_WATCH_MS = 30 * 60_000;
// A quick command's starting prompt for Claude or Codex, one argument after the fixed command
// (Orca's 'argv' prompt injection, src/shared/tui-agent-startup.ts). The prompt is never typed: it
// rides in the terminal's environment and the typed line ends in "$RUFLO_PHONE_AGENT_PROMPT", so the
@@ -52,7 +55,8 @@ export const CLOSE_REVOKED = Symbol('closeRevoked');
* chatSessions: where Claude/Codex transcripts are looked for (tests pass their own roots).
* stateDir: where quick commands are saved; without one they live in memory.
*/
export function createFullMethods({ terminals, projects, log = () => {}, detect = detectAgents, chatSessions = createChatSessions(), chatPollMs, stateDir = null }) {
export function createFullMethods({ terminals, projects, log = () => {}, detect = detectAgents, chatSessions = createChatSessions(), chatPollMs, stateDir = null,
claudeTrust = (cwd) => claudeFolderTrusted(cwd), trustPollMs = 1500 }) {
const publicationEpoch = `ruflo-phone:${randomUUID()}`;
let snapshotVersion = 0;
/** worktreeId -> { tabs: Tab[], activeTabId: string|null } (tab = { tabId, leafId, handle, title, launchAgent }) */
@@ -80,7 +84,8 @@ export function createFullMethods({ terminals, projects, log = () => {}, detect
return {
...statusFields(t.chat.status),
agentType: t.chat.agent, paneKey: `${t.tabId}:${t.leafId}`, terminalHandle: t.handle, tabId: t.tabId, worktreeId,
...(t.chat.sessionId ? { providerSession: { key: 'session_id', id: t.chat.sessionId, transcriptPath: t.chat.transcriptPath } } : {}),
// Held back until the agent is past its first-run prompt (see revealWhenTrusted).
...(t.chat.sessionId && t.chat.shown !== false ? { providerSession: { key: 'session_id', id: t.chat.sessionId, transcriptPath: t.chat.transcriptPath } } : {}),
};
}
@@ -158,6 +163,32 @@ export function createFullMethods({ terminals, projects, log = () => {}, detect
});
}
/**
* The phone opens an agent tab in its chat view once the tab reports a session, and Claude is
* given its session id at launch. In a folder Claude does not trust yet, its first-run trust
* prompt is in the terminal, and the chat view would hide it. So the session is reported only
* once Claude trusts the folder, or has written its transcript (it is past the prompt then).
*/
function revealWhenTrusted(tab, row, t) {
const started = Date.now();
let timer = null;
const check = async () => {
timer = null;
if (terminals.get(t.handle) !== t || tab.chat.shown !== false) return;
let ready = await claudeTrust(row.path);
// The path the host chose at launch, not one from the phone.
if (!ready) ready = await stat(tab.chat.transcriptPath).then((s) => s.isFile(), () => false);
if (ready) {
tab.chat.shown = true;
if (sessionOf(row.worktreeId).tabs.includes(tab)) publish(row.worktreeId);
} else if (Date.now() - started < TRUST_WATCH_MS) {
timer = setTimeout(check, trustPollMs);
timer.unref?.();
}
};
void check();
}
// A turn the transcript left open (the agent crashed or was quit mid-turn) must not keep Stop up.
const foregroundTimer = setInterval(() => {
for (const [worktreeId, s] of sessions) for (const tab of s.tabs) if (tab.chat?.status.state === 'working') applyStatus(tab, worktreeId);
@@ -193,8 +224,9 @@ export function createFullMethods({ terminals, projects, log = () => {}, detect
};
const launchedAt = Date.now();
if (claude) {
tab.chat = { agent: 'claude', sessionId: claude.sessionId, transcriptPath: claude.transcriptPath, status: initialTabStatus(launchedAt) };
tab.chat = { agent: 'claude', sessionId: claude.sessionId, transcriptPath: claude.transcriptPath, status: initialTabStatus(launchedAt), shown: false };
followStatus(tab, row.worktreeId, claude);
revealWhenTrusted(tab, row, t);
}
if (agent === 'codex') {
// Codex names its own session when it writes the first prompt; the tab gains it then.
@@ -344,8 +376,18 @@ export function createFullMethods({ terminals, projects, log = () => {}, detect
'terminal.unsubscribe': (p, conn) => {
const streams = streamsOf(conn);
const keys = [p?.requestId, p?.subscriptionId, p?.client?.id ? `${p?.subscriptionId}:${p.client.id}` : null].filter((k) => typeof k === 'string');
for (const k of keys) { const stop = streams.get(k); if (stop) { stop(); streams.delete(k); } }
// With a requestId, end only that request's stream: a cancel for an older stream that lands
// after the phone re-subscribed must not stop the new one, which the slot key (terminal:client)
// now names. Without a requestId, use the slot, as Orca's hosts that predate it do.
const keys = typeof p?.requestId === 'string'
? [p.requestId]
: [p?.subscriptionId, p?.client?.id ? `${p?.subscriptionId}:${p.client.id}` : null].filter((k) => typeof k === 'string');
for (const k of keys) {
const stop = streams.get(k);
if (!stop) continue;
stop();
for (const [key, value] of streams) if (value === stop) streams.delete(key);
}
return { unsubscribed: true };
},
+3
View File
@@ -2,6 +2,7 @@
// launches, no git writes (projects.mjs only reads `git worktree list`). Anything not listed here answers `method_not_found`.
import { hostname } from 'node:os';
import { BUNDLE_CAPABILITY, BundleError } from './bundle.mjs';
import { createTeamSnapshotRead } from './team-snapshot.mjs';
import { createWorkspaceReads } from './workspace-reads.mjs';
/** Orca runtime protocol this host speaks (src/shared/protocol-version.ts). */
@@ -49,6 +50,8 @@ export function createDispatcher({ runtimeId, bundle, projects = null, machineNa
'worktree.ps': (p) => (projects ? projects.worktreePs(p) : { worktrees: [], totalCount: 0, truncated: false }),
'repo.list': () => (projects ? projects.repoList() : { repos: [] }),
...(projects ? createWorkspaceReads({ projects }) : {}),
// Teams & swarm: read-only, so a monitor phone gets it too, as on the RuPro desktop.
...(projects ? createTeamSnapshotRead({ projects }) : {}),
};
if (bundle) {
methods['mobileWeb.bundle.manifest'] = () => bundle.manifestReply();
+205
View File
@@ -0,0 +1,205 @@
// `ruflo.teamSnapshot.read`, the phone's Teams & swarm screen. The reader below is the RuPro
// desktop's (cognitum-one/ruflo-ui overlays/ruflo/runtime/ruflo-team-snapshot-reader.mjs at
// 8bbe93d73), unchanged, so both hosts send the phone the same shape.
//
// Read-only snapshot of who is working in a workspace: Claude Code agent teams
// (~/.claude/teams, ~/.claude/tasks) and ruflo swarm / hive-mind / tasks / claims
// (<worktree>/.claude-flow). Every value is copied field by field from an
// allowlist, never spread, so tokens (hive-mind `hiveToken`), member prompts and
// claim context never leave the host. Files are size-capped, symlinks refused.
import {createHash} from 'node:crypto';
import {closeSync,fstatSync,lstatSync,openSync,readSync,readdirSync} from 'node:fs';
import {homedir} from 'node:os';
import {basename,join} from 'node:path';
import {RpcError} from './rpc.mjs';
export const LIMITS=Object.freeze({teams:6,members:24,messages:40,inboxes:64,teamTasks:60,swarms:5,agents:30,tasks:30,claims:30,file:512*1024,text:280});
const NAME=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
const DONE_SWARM=new Set(['terminated','stopped','completed','failed','shutdown']);
const OPEN_TASK=new Set(['pending','in_progress','in-progress','running','assigned','blocked','queued']);
const OPEN_CLAIM=new Set(['active','paused','blocked','review','handoff-pending']);
const DAY=86_400_000,FORTNIGHT=14*DAY;
function clip(value,max=LIMITS.text){
if(typeof value!=='string')return null;
const text=value.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g,'').replace(/\s+/g,' ').trim();
return text?(text.length>max?text.slice(0,max-1)+'…':text):null;
}
function id(value){return typeof value==='string'&&value.length<=200?clip(value,200):null}
function num(value){return typeof value==='number'&&Number.isFinite(value)?value:null}
function time(value){
if(typeof value==='number'&&Number.isFinite(value))return value;
if(typeof value==='string'){const t=Date.parse(value);return Number.isFinite(t)?t:null}
return null;
}
/** Regular file, not a symlink, under the size cap; otherwise null. */
function readJson(path){
try{
const stat=lstatSync(path);
if(!stat.isFile()||stat.size>LIMITS.file)return null;
const fd=openSync(path,'r');
try{
const size=fstatSync(fd).size;if(size>LIMITS.file)return null;
const buffer=Buffer.alloc(size);let read=0;
while(read<size){const n=readSync(fd,buffer,read,size-read,read);if(n<=0)break;read+=n}
return {value:JSON.parse(buffer.subarray(0,read).toString('utf8')),mtime:stat.mtimeMs};
}finally{closeSync(fd)}
}catch{return null}
}
function listDir(path,limit){
try{
const stat=lstatSync(path);if(!stat.isDirectory())return [];
return readdirSync(path,{withFileTypes:true}).filter(e=>!e.isSymbolicLink()).slice(0,limit*4);
}catch{return []}
}
function inside(path,root){return path===root||path.startsWith(root.endsWith('/')?root:root+'/')}
/** Message text is often JSON inside JSON ({type:'idle_notification',summary,...}). */
function message(raw,inbox){
if(!raw||typeof raw!=='object')return null;
let kind='message',summary=null;
if(typeof raw.text==='string'){
const text=raw.text.trim();
if(text.startsWith('{')){
try{const inner=JSON.parse(text);if(inner&&typeof inner==='object'){kind=id(inner.type)??'message';summary=clip(inner.summary)??clip(inner.result)??clip(inner.content)??clip(inner.reason)}}catch{summary=clip(text)}
}else summary=clip(text);
}
if(kind==='message'&&typeof raw.type==='string')kind=id(raw.type)??kind;
return {from:id(raw.from)??'unknown',to:inbox,at:time(raw.timestamp),kind,summary,read:raw.read===true};
}
function memberStatus(name,lead,messages){
if(name===lead)return 'lead';
const last=messages.filter(m=>m.from===name).sort((a,b)=>(b.at??0)-(a.at??0))[0];
if(!last)return 'unknown';
if(/shutdown|terminated|stopped/.test(last.kind))return 'stopped';
if(last.kind==='idle_notification')return 'idle';
return 'working';
}
function readTeam(home,name,config,mtime){
const members=Array.isArray(config.members)?config.members.slice(0,LIMITS.members):[];
const lead=id(members.find(m=>m?.agentId===config.leadAgentId)?.name)??'team-lead';
const messages=[];
for(const entry of listDir(join(home,'.claude','teams',name,'inboxes'),LIMITS.inboxes).slice(0,LIMITS.inboxes)){
if(!entry.isFile()||!entry.name.endsWith('.json'))continue;
const inbox=entry.name.slice(0,-5);if(!NAME.test(inbox))continue;
const file=readJson(join(home,'.claude','teams',name,'inboxes',entry.name));
if(!Array.isArray(file?.value))continue;
for(const raw of file.value.slice(-LIMITS.messages)){const m=message(raw,inbox);if(m)messages.push(m)}
}
messages.sort((a,b)=>(b.at??0)-(a.at??0));
const tasks=[];
for(const entry of listDir(join(home,'.claude','tasks',name),LIMITS.teamTasks)){
if(tasks.length>=LIMITS.teamTasks)break;
if(!entry.isFile()||!entry.name.endsWith('.json'))continue;
const task=readJson(join(home,'.claude','tasks',name,entry.name))?.value;
if(!task||typeof task!=='object')continue;
tasks.push({id:id(task.id)??entry.name.slice(0,-5),subject:clip(task.subject)??clip(task.description)??'Untitled task',status:id(task.status)??'unknown',owner:id(task.owner),blocked:Array.isArray(task.blockedBy)&&task.blockedBy.length>0});
}
return {
source:'claude-team',name,createdAt:time(config.createdAt),updatedAt:Math.max(mtime,messages[0]?.at??0)||null,
lead,leadCwd:typeof members[0]?.cwd==='string'?members[0].cwd:null,
members:members.filter(m=>m&&typeof m==='object').map(m=>{
const memberName=id(m.name)??'member';
const recent=messages.find(x=>x.from===memberName);
return {name:memberName,agentType:id(m.agentType),model:id(m.model),color:id(m.color),
backend:memberName===lead?'lead':m.backendType==='tmux'||(typeof m.tmuxPaneId==='string'&&/^%\d+$/.test(m.tmuxPaneId))?'pane':'in-process',
joinedAt:time(m.joinedAt),status:memberStatus(memberName,lead,messages),lastSummary:recent?.summary??null,lastActivityAt:recent?.at??null};
}),
messages:messages.slice(0,LIMITS.messages),tasks,
memberCount:Array.isArray(config.members)?config.members.length:0,
};
}
/** Claude Code agent teams whose lead works in one of `roots` (newest first). */
export function readClaudeTeams(home,roots){
const base=join(home,'.claude','teams'),found=[];
for(const entry of listDir(base,256)){
if(!entry.isDirectory()||!NAME.test(entry.name))continue;
const file=readJson(join(base,entry.name,'config.json'));
const config=file?.value;if(!config||typeof config!=='object'||!Array.isArray(config.members))continue;
const cwd=config.members.find(m=>m?.agentId===config.leadAgentId)?.cwd??config.members[0]?.cwd;
if(typeof cwd!=='string')continue;
const root=[...roots].sort((x,y)=>y.length-x.length).find(r=>inside(cwd,r));if(!root)continue;
found.push({name:entry.name,config,mtime:file.mtime,root});
}
found.sort((a,b)=>b.mtime-a.mtime);
return found.slice(0,LIMITS.teams).map(t=>({...readTeam(home,t.name,t.config,t.mtime),root:t.root}));
}
/** Live ruflo coordination state for one workspace; stale or finished entries are dropped. */
export function readRufloState(worktreePath,now=Date.now()){
const dir=join(worktreePath,'.claude-flow');
const swarmFile=readJson(join(dir,'swarm','swarm-state.json'))?.value;
const swarms=[];
if(swarmFile&&typeof swarmFile.swarms==='object'&&swarmFile.swarms)
for(const s of Object.values(swarmFile.swarms)){
if(!s||typeof s!=='object'||DONE_SWARM.has(s.status))continue;
const updatedAt=time(s.updatedAt);
swarms.push({source:'ruflo-swarm',id:id(s.swarmId)??'swarm',topology:id(s.topology),strategy:id(s.config?.strategy),status:id(s.status)??'unknown',
maxAgents:num(s.maxAgents),agentCount:Array.isArray(s.agents)?s.agents.length:0,taskCount:Array.isArray(s.tasks)?s.tasks.length:0,
consensus:id(s.config?.consensusMechanism),updatedAt,stale:updatedAt!==null&&now-updatedAt>DAY});
}
swarms.sort((a,b)=>(b.updatedAt??0)-(a.updatedAt??0));
const h=readJson(join(dir,'hive-mind','state.json'))?.value;
let hive=null;
if(h&&typeof h==='object'&&h.initialized===true){
const updatedAt=time(h.updatedAt);
hive={source:'ruflo-hive',topology:id(h.topology),consensus:id(h.consensusStrategy),
queen:h.queen&&typeof h.queen==='object'?{agentId:id(h.queen.agentId),term:num(h.queen.term)}:null,
workerCount:Array.isArray(h.workers)?h.workers.length:0,pendingVotes:Array.isArray(h.consensus?.pending)?h.consensus.pending.length:0,
decidedVotes:Array.isArray(h.consensus?.history)?h.consensus.history.length:0,updatedAt,stale:updatedAt!==null&&now-updatedAt>DAY};
}
const a=readJson(join(dir,'agents.json'))?.value;
const agents=a&&typeof a.agents==='object'&&a.agents?Object.values(a.agents).filter(x=>x&&typeof x==='object'&&!DONE_SWARM.has(x.status)).slice(0,LIMITS.agents).map(x=>({
id:id(x.agentId)??'agent',type:id(x.agentType),status:id(x.status)??'unknown',role:id(x.config?.hiveRole)??id(x.config?.role),domain:id(x.domain),health:num(x.health),taskCount:num(x.taskCount)})):[];
const t=readJson(join(dir,'tasks','store.json'))?.value;
const tasks=t&&typeof t.tasks==='object'&&t.tasks?Object.values(t.tasks).filter(x=>x&&typeof x==='object'&&OPEN_TASK.has(x.status)&&now-(time(x.startedAt)??time(x.createdAt)??0)<FORTNIGHT).sort((x,y)=>(time(y.createdAt)??0)-(time(x.createdAt)??0)).slice(0,LIMITS.tasks).map(x=>({
source:'ruflo-task',id:id(x.taskId)??'task',type:id(x.type),status:id(x.status),priority:id(x.priority),description:clip(x.description,200),assignees:Array.isArray(x.assignedTo)?x.assignedTo.length:0,progress:num(x.progress)})):[];
const c=readJson(join(dir,'claims','claims.json'))?.value;
const claims=c&&typeof c.claims==='object'&&c.claims?Object.values(c.claims).filter(x=>x&&typeof x==='object'&&OPEN_CLAIM.has(x.status)&&now-(time(x.statusChangedAt)??time(x.claimedAt)??0)<FORTNIGHT).slice(0,LIMITS.claims).map(x=>({
source:'ruflo-claim',issueId:id(x.issueId)??'claim',claimant:id(x.claimant?.agentId)??id(x.claimant?.userId)??'unknown',claimantType:id(x.claimant?.agentType)??id(x.claimant?.type),
status:id(x.status),progress:num(x.progress),claimedAt:time(x.claimedAt)})):[];
return {swarms:swarms.slice(0,LIMITS.swarms),hive,agents,tasks,claims};
}
function hasRuflo(state){return state.swarms.length>0||state.hive!==null||state.agents.length>0||state.tasks.length>0||state.claims.length>0}
/** One normalized model for the phone: per workspace, its Claude teams and ruflo state. */
export function readTeamSnapshot({home,worktrees,now=Date.now()}){
const roots=worktrees.map(w=>w.path);
const teams=readClaudeTeams(home,roots);
const workspaces=[];
for(const w of worktrees){
const ruflo=readRufloState(w.path,now);
const own=teams.filter(t=>t.root===w.path).map(({root,leadCwd,...team})=>team);
if(!own.length&&!hasRuflo(ruflo))continue;
workspaces.push({id:w.id,name:w.name,claudeTeams:own,ruflo});
}
workspaces.sort((x,y)=>Math.max(0,...y.claudeTeams.map(t=>t.updatedAt??0))-Math.max(0,...x.claudeTeams.map(t=>t.updatedAt??0)));
return {generatedAt:now,workspaces:workspaces.slice(0,8)};
}
/**
* The method, over the workspaces this host shares and nothing else: the phone sends no path,
* and a team shows only when its lead works inside one of them. Worktree ids embed the absolute
* path, so the phone gets a hash of it as the key, as the desktop does.
* @param {{ projects: { worktreePs: Function }, home?: string }} deps
*/
export function createTeamSnapshotRead({ projects, home = homedir() }) {
return {
'ruflo.teamSnapshot.read': async () => {
try {
const rows = (await projects.worktreePs({})).worktrees;
const worktrees = rows.filter((r) => typeof r.path === 'string' && r.path.startsWith('/')).map((r) => ({
id: createHash('sha256').update(String(r.worktreeId)).digest('hex').slice(0, 16),
name: basename(r.path) || 'Workspace',
path: r.path,
}));
return readTeamSnapshot({ home, worktrees });
} catch {
throw new RpcError('invalid_argument', 'ruflo_team_snapshot_unavailable');
}
},
};
}
+36 -7
View File
@@ -3,12 +3,12 @@
// are fake agents on PATH that write fixture transcripts where the real ones would.
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { chmodSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
import { chmodSync, mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { after, before, describe, it } from 'node:test';
import { fileURLToPath } from 'node:url';
import { createChatSessions } from '../src/chat-sessions.mjs';
import { claudeFolderTrusted, createChatSessions } from '../src/chat-sessions.mjs';
import { createFullMethods } from '../src/full-methods.mjs';
import { decodePairingOffer } from '../src/offer.mjs';
import { mintPairing } from '../src/pairing.mjs';
@@ -26,6 +26,7 @@ const FAKE_CLAUDE = `#!/usr/bin/env node
const fs = require('fs'); const path = require('path');
const id = process.argv[process.argv.indexOf('--session-id') + 1];
const dir = path.join(process.env.FAKE_CLAUDE_ROOT, process.cwd().replace(/[^A-Za-z0-9]/g, '-'));
if (process.env.FAKE_CLAUDE_QUIET) { console.log('FAKE-CLAUDE waiting at its trust prompt'); setTimeout(() => {}, 60000); return; }
fs.mkdirSync(dir, { recursive: true });
const file = path.join(dir, id + '.jsonl');
const lines = fs.readFileSync(path.join(process.env.FAKE_FIXTURES, 'claude-transcript.jsonl'), 'utf8').replaceAll('SESSION', id).split('\\n');
@@ -52,7 +53,7 @@ setTimeout(() => {}, 60000);
`;
describe('chat view over the phone connection', () => {
let store; let host; let terminals; let worktreeId; let phone; let readOnly; let claudeRoot; let codexRoot; let tabs;
let store; let host; let terminals; let worktreeId; let repoDir; let phone; let readOnly; let claudeRoot; let codexRoot; let tabs;
const saved = { PATH: process.env.PATH, SHELL: process.env.SHELL, HOME: process.env.HOME };
const wt = () => ({ worktree: `id:${worktreeId}` });
@@ -65,7 +66,7 @@ describe('chat view over the phone connection', () => {
// `claude` ahead of the fake one on PATH.
Object.assign(process.env, { PATH: `${bin}:${saved.PATH}`, SHELL: '/bin/sh', HOME: tmp(), FAKE_CLAUDE_ROOT: claudeRoot, FAKE_CODEX_ROOT: codexRoot, FAKE_FIXTURES: fixtureDir });
const repoDir = tmp();
repoDir = tmp();
const g = (...a) => execFileSync('git', ['-C', repoDir, ...a], { stdio: 'pipe' });
g('init', '-q', '-b', 'main'); g('-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-q', '--allow-empty', '-m', 'init');
const projects = createProjectCatalog(await resolveProjects({ projects: [repoDir] }));
@@ -74,7 +75,7 @@ describe('chat view over the phone connection', () => {
store = openStore({ dir: tmp() });
terminals = createTerminalManager({ pty: await loadPty() });
const chatSessions = createChatSessions({ roots: { claude: [claudeRoot], codex: [codexRoot] }, pollMs: 100, maxPollMs: 200 });
const fullMethods = createFullMethods({ terminals, projects, chatSessions, chatPollMs: 100 });
const fullMethods = createFullMethods({ terminals, projects, chatSessions, chatPollMs: 100, trustPollMs: 100 });
host = await startPhoneHost({ store, bind: '127.0.0.1', port: 0, projects, fullMethods });
phone = await connectPhone(decodePairingOffer(mintPairing({ store, endpoint: host.endpoint, name: 'Full', access: 'full' }).url));
readOnly = await connectPhone(decodePairingOffer(mintPairing({ store, endpoint: host.endpoint, name: 'RO' }).url));
@@ -91,9 +92,10 @@ describe('chat view over the phone connection', () => {
const tabRow = async (id, pred) => (await tabs.until((f) => f.result?.type === 'updated'
&& f.result.tabs.some((t) => t.id === id && pred(t)), 15000)).result.tabs.find((t) => t.id === id);
it('a Claude tab carries its session from the start, and its transcript streams to the chat view', async () => {
it('a Claude tab reports its session once Claude is past its trust prompt, and its transcript streams to the chat view', async () => {
const created = await phone.call('session.tabs.createTerminal', { ...wt(), agent: 'claude' });
const row = await tabRow(created.result.tab.id, (t) => t.agentStatus);
// This folder is not trusted (a fresh HOME), so the session shows once Claude writes its transcript.
const row = await tabRow(created.result.tab.id, (t) => t.agentStatus?.providerSession);
const { agentStatus } = row;
assert.equal(row.launchAgent, 'claude');
assert.equal(agentStatus.agentType, 'claude');
@@ -130,6 +132,33 @@ describe('chat view over the phone connection', () => {
assert.equal(end.streaming, undefined);
});
it('holds a Claude tab\'s session back while Claude waits at its trust prompt, and shows it once the folder is trusted', async () => {
process.env.FAKE_CLAUDE_QUIET = '1';
let created;
try { created = await phone.call('session.tabs.createTerminal', { ...wt(), agent: 'claude' }); } finally { delete process.env.FAKE_CLAUDE_QUIET; }
const id = created.result.tab.id;
const waiting = await tabRow(id, (t) => t.agentStatus);
await new Promise((r) => setTimeout(r, 2000));
const still = (await phone.call('session.tabs.list', wt())).result?.tabs?.find((t) => t.id === id) ?? waiting;
assert.equal(still.agentStatus.agentType, 'claude');
assert.equal(still.agentStatus.providerSession, undefined, 'no session while the trust prompt is up');
writeFileSync(join(process.env.HOME, '.claude.json'), JSON.stringify({ projects: { [repoDir]: { hasTrustDialogAccepted: true } } }));
const shown = await tabRow(id, (t) => t.agentStatus?.providerSession);
assert.match(shown.agentStatus.providerSession.id, /^[0-9a-f-]{36}$/);
await phone.call('session.tabs.close', { ...wt(), tabId: id, reason: 'user' });
});
it('counts only a trust Claude recorded for that exact folder', async () => {
const home = tmp(); const env = { CLAUDE_CONFIG_DIR: home };
const parent = tmp(); const child = join(parent, 'child'); mkdirSync(child);
assert.equal(await claudeFolderTrusted(child, env), false, 'no file');
writeFileSync(join(home, '.claude.json'), '{not json');
assert.equal(await claudeFolderTrusted(child, env), false, 'unreadable');
writeFileSync(join(home, '.claude.json'), JSON.stringify({ projects: { [parent]: { hasTrustDialogAccepted: true }, [child]: { hasTrustDialogAccepted: false } } }));
assert.equal(await claudeFolderTrusted(child, env), false, 'a parent folder does not count');
assert.equal(await claudeFolderTrusted(parent, env), true);
});
it('a Codex tab gains its session once Codex writes its rollout, and the chat view reads it', async () => {
const created = await phone.call('session.tabs.createTerminal', { ...wt(), agent: 'codex' });
const id = created.result.tab.id;
+13
View File
@@ -101,6 +101,19 @@ describe('full access: tabs, terminals and agents', () => {
await phone.call('terminal.send', { terminal, text: 'stty size', enter: true });
await term.until(() => text(term).includes('20 60'));
// A late cancel of an older stream must not stop the newer one on the same terminal and client.
const client = { id: 'phone-1', type: 'mobile' };
const fresh = phone.stream('terminal.subscribe', { terminal, client, viewport: { cols: 60, rows: 20 } });
await fresh.until((f) => f.result?.type === 'subscribed');
await phone.call('terminal.unsubscribe', { subscriptionId: terminal, client: { id: 'phone-1' }, requestId: term.id });
await phone.call('terminal.send', { terminal, text: 'echo still-$((6*7))', enter: true });
await fresh.until(() => text(fresh).includes('still-42'));
// Without a requestId the slot is used, so this one ends the live stream.
await phone.call('terminal.unsubscribe', { subscriptionId: terminal, client: { id: 'phone-1' } });
await phone.call('terminal.send', { terminal, text: 'echo gone-$((6*8))', enter: true });
await new Promise((r) => setTimeout(r, 400));
assert.ok(!text(fresh).includes('gone-48'), 'the slot cancel ended the stream');
const list = await phone.call('terminal.list', { worktree: `id:${worktreeId}` });
assert.ok(list.result.terminals.some((t) => t.handle === terminal));
+44
View File
@@ -266,6 +266,50 @@ describe('access levels', () => {
});
});
describe('teams and swarms', () => {
it('shows a read-only phone the swarms, claims and Claude teams in shared workspaces only, without secrets', async () => {
const { execFileSync } = await import('node:child_process');
const { realpathSync } = await import('node:fs');
const { resolveProjects, createProjectCatalog } = await import('../src/projects.mjs');
const repoDir = realpathSync(tmp()); const elsewhere = realpathSync(tmp()); const home = realpathSync(tmp());
execFileSync('git', ['-C', repoDir, 'init', '-q', '-b', 'main']);
const write = (path, value) => { mkdirSync(join(path, '..'), { recursive: true }); writeFileSync(path, JSON.stringify(value)); };
const now = Date.now(); const iso = new Date(now).toISOString();
write(join(repoDir, '.claude-flow', 'swarm', 'swarm-state.json'), { swarms: {
s1: { swarmId: 'swarm-1', topology: 'hierarchical', status: 'running', maxAgents: 8, agents: [{}, {}], tasks: [{}], updatedAt: iso, config: { strategy: 'specialized' } },
s2: { swarmId: 'swarm-old', status: 'terminated' } } });
write(join(repoDir, '.claude-flow', 'hive-mind', 'state.json'), { initialized: true, topology: 'mesh', hiveToken: 'SECRET-HIVE-TOKEN', workers: [{}], updatedAt: iso });
write(join(repoDir, '.claude-flow', 'claims', 'claims.json'), { claims: { c1: { issueId: 'pr-7', status: 'active', claimant: { agentId: 'coder-1' }, claimedAt: now, context: 'SECRET-CONTEXT' } } });
const team = (name, cwd) => write(join(home, '.claude', 'teams', name, 'config.json'),
{ leadAgentId: 'lead', createdAt: now, members: [{ agentId: 'lead', name: 'team-lead', cwd, prompt: 'SECRET-PROMPT' }, { agentId: 'w', name: 'worker', cwd }] });
team('shared-team', join(repoDir, 'src')); team('private-team', elsewhere);
write(join(home, '.claude', 'teams', 'shared-team', 'inboxes', 'team-lead.json'),
[{ from: 'worker', timestamp: iso, text: JSON.stringify({ type: 'idle_notification', summary: 'done with tests' }) }]);
const { repos } = await resolveProjects([repoDir]);
const savedHome = process.env.HOME; process.env.HOME = home;
const s = openStore({ dir: tmp() });
let h;
try { h = await startPhoneHost({ store: s, bind: BIND, port: 0, projects: createProjectCatalog({ repos }) }); } finally { process.env.HOME = savedHome; }
try {
const phone = await connectPhone(decodePairingOffer(mintPairing({ store: s, endpoint: h.endpoint, name: 'Monitor' }).url));
const r = await phone.call('ruflo.teamSnapshot.read', {});
assert.equal(r.ok, true, JSON.stringify(r.error));
assert.equal(r.result.workspaces.length, 1);
const [ws] = r.result.workspaces;
assert.match(ws.id, /^[0-9a-f]{16}$/, 'the key is a hash, not the path');
assert.deepEqual(ws.claudeTeams.map((t) => t.name), ['shared-team']);
assert.equal(ws.claudeTeams[0].members.find((m) => m.name === 'worker').status, 'idle');
assert.deepEqual(ws.ruflo.swarms.map((x) => [x.id, x.agentCount, x.strategy]), [['swarm-1', 2, 'specialized']]);
assert.equal(ws.ruflo.hive.workerCount, 1);
assert.deepEqual(ws.ruflo.claims.map((c) => [c.issueId, c.claimant]), [['pr-7', 'coder-1']]);
const sent = JSON.stringify(r.result);
for (const secret of ['SECRET-HIVE-TOKEN', 'SECRET-CONTEXT', 'SECRET-PROMPT', elsewhere, home]) assert.ok(!sent.includes(secret), secret);
await phone.close();
} finally { await h.close(); }
});
});
describe('default listen address', () => {
const lan = (address, name = 'en0') => ({ name, address, kind: 'lan' });
it('prefers a tailnet address', () => {