@adhdev/daemon-standalone 1.0.59-rc.16 → 1.0.59-rc.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -37477,10 +37477,10 @@ var require_dist3 = __commonJS({
37477
37477
  }
37478
37478
  function getDaemonBuildInfo() {
37479
37479
  if (cached2) return cached2;
37480
- const commit = readInjected(true ? "63de633575bcf32ebbfe01d663066ef4e99ef884" : void 0) ?? "unknown";
37481
- const commitShort = readInjected(true ? "63de6335" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
37482
- const version2 = readInjected(true ? "1.0.59-rc.16" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
37483
- const builtAt = readInjected(true ? "2026-09-12T13:51:33.368Z" : void 0);
37480
+ const commit = readInjected(true ? "397d4113c318c1e01345b5be762920bb1a5641af" : void 0) ?? "unknown";
37481
+ const commitShort = readInjected(true ? "397d4113" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
37482
+ const version2 = readInjected(true ? "1.0.59-rc.17" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
37483
+ const builtAt = readInjected(true ? "2026-09-12T15:16:54.103Z" : void 0);
37484
37484
  cached2 = builtAt ? { commit, commitShort, version: version2, builtAt } : { commit, commitShort, version: version2 };
37485
37485
  return cached2;
37486
37486
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adhdev/daemon-standalone",
3
- "version": "1.0.59-rc.16",
3
+ "version": "1.0.59-rc.17",
4
4
  "description": "ADHDev standalone daemon — embedded HTTP/WS server for local dashboard",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -37,7 +37,7 @@
37
37
  "license": "AGPL-3.0-or-later",
38
38
  "dependencies": {
39
39
  "@adhdev/ghostty-vt-node": "*",
40
- "@adhdev/session-host-core": "1.0.59-rc.16",
40
+ "@adhdev/session-host-core": "1.0.59-rc.17",
41
41
  "@xterm/addon-serialize": "^0.14.0",
42
42
  "@xterm/xterm": "^6.0.0",
43
43
  "chalk": "^5.3.0",
@@ -38,7 +38,7 @@ ${JSON.stringify(t.bundle,null,2)}
38
38
  \`\`\`json
39
39
  ${JSON.stringify(t,null,2)}
40
40
  \`\`\``}function Ki(e,t){return`${e}:${t}`}function rN(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function iN(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function ea(e,t){iN()&&console.debug(`[subscription-manager] ${e}`,t)}class lN{constructor(){st(this,"active",new Map);st(this,"retryTimers",new Map)}subscribe(t,n,a,o,r){var p,m;const i=Ki(a.topic,a.key),c=this.active.get(i);let d=!0;if(c)c.handlers.add(o),(!rN(c.request,a)||c.daemonId!==n)&&(c.daemonId=n,c.request=a,d=((p=t.sendData)==null?void 0:p.call(t,n,a))??!1,!d&&(r!=null&&r.retryIntervalMs)?this.scheduleRetry(i,t,r.retryIntervalMs):d&&this.clearRetry(i),ea("subscribe_update",{daemonId:n,topic:a.topic,key:a.key,accepted:d})),c.lastUpdate&&o(c.lastUpdate);else{const h={daemonId:n,request:a,handlers:new Set([o])};this.active.set(i,h),ea("subscribe",{daemonId:n,topic:a.topic,key:a.key}),d=((m=t.sendData)==null?void 0:m.call(t,n,a))??!1,!d&&(r!=null&&r.retryIntervalMs)&&this.scheduleRetry(i,t,r.retryIntervalMs)}const u=()=>{var b;this.clearRetry(i);const h=this.active.get(i);if(!h||(h.handlers.delete(o),h.handlers.size>0))return;this.active.delete(i);const g={type:"unsubscribe",topic:a.topic,key:a.key};ea("unsubscribe",{daemonId:n,topic:a.topic,key:a.key}),(b=t.sendData)==null||b.call(t,n,g)};return u.initialSendAccepted=d,u}publish(t){const n=Ki(t.topic,t.key),a=this.active.get(n);a&&(this.clearRetry(n),a.lastUpdate=t,On.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),a.handlers.forEach(o=>{o(t),On.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,n,a){const o=Ki(t,n),r=this.active.get(o);r&&(r.request={...r.request,params:{...r.request.params,...a}})}resubscribeAll(t){var n;ea("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(a=>({daemonId:a.daemonId,topic:a.request.topic,key:a.request.key}))});for(const a of this.active.values())(n=t.sendData)==null||n.call(t,a.daemonId,a.request)}resubscribeForDaemon(t,n){var o;const a=Array.from(this.active.values()).filter(r=>r.daemonId===t);ea("resubscribe_daemon",{daemonId:t,count:a.length,subscriptions:a.map(r=>({topic:r.request.topic,key:r.request.key}))});for(const r of a)(o=n.sendData)==null||o.call(n,r.daemonId,r.request)}scheduleRetry(t,n,a){if(this.retryTimers.has(t))return;const o=setTimeout(()=>{var c;this.retryTimers.delete(t);const r=this.active.get(t);if(!r)return;const i=((c=n.sendData)==null?void 0:c.call(n,r.daemonId,r.request))??!1;ea("subscribe_retry",{id:t,accepted:i,topic:r.request.topic,key:r.request.key}),i||this.scheduleRetry(t,n,a)},a);this.retryTimers.set(t,o)}clearRetry(t){const n=this.retryTimers.get(t);n!==void 0&&(clearTimeout(n),this.retryTimers.delete(t))}}const Ns=new lN;function cN(e,t){const n=new Map;for(const a of e||[])if((a.daemonId||a.id.includes(":")&&a.id.split(":")[0]||"")===t&&a.sessionId){n.set(a.sessionId,{parentSessionId:a.parentSessionId,providerSessionId:a.providerSessionId,workspace:a.workspace??null,sessionCapabilities:a.sessionCapabilities,cdpConnected:a.cdpConnected,activeChat:a.activeChat,controlValues:a.controlValues,providerControls:a.providerControls,summaryMetadata:a.summaryMetadata,runtimeWriteOwner:a.runtimeWriteOwner,runtimeAttachedClients:a.runtimeAttachedClients,cliName:a.cliName,type:a.type,mode:a.mode,status:a.status,lastMessagePreview:a.lastMessagePreview,lastMessageRole:a.lastMessageRole,lastMessageAt:a.lastMessageAt,lastMessageHash:a.lastMessageHash,completionMarker:a.completionMarker,seenCompletionMarker:a.seenCompletionMarker,settings:a.settings,activeInteractivePrompt:a.activeInteractivePrompt});for(const r of a.childSessions||[]){if(!(r!=null&&r.id))continue;const i=n.get(r.id)||{};n.set(r.id,{...i,...r})}}return n}function dN(e){const t=[],n=new Map;for(const a of e)if(a.parentId){const o=n.get(a.parentId)||[];o.push(a),n.set(a.parentId,o)}else t.push(a);return{topLevel:t,childrenByParent:n}}function Vi(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function uN(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function pN(e){uN()&&console.debug("[dashboard-conversations] statusPayloadToEntries",e.map(t=>({id:t.id,daemonId:t.daemonId,sessionId:t.sessionId,instanceId:t.instanceId,providerSessionId:t.providerSessionId,transport:t.transport,type:t.type})))}function Tr(e,t){const n=[],{daemonId:a,existingDaemon:o,existingEntries:r,timestamp:i}=t,c=i||e.timestamp||Date.now(),d=e.sessions||[],u=en(a,e.instanceId),{topLevel:p,childrenByParent:m}=dN(d),h=cN(r,a),g=e.machine?{...(o==null?void 0:o.machine)||{},...e.machine}:o==null?void 0:o.machine,b=p.filter(k=>k.kind==="workspace"&&k.transport==="cdp-page"),f=p.filter(k=>k.kind==="agent"&&k.transport==="pty"),x=p.filter(k=>k.kind==="agent"&&k.transport==="acp");n.push({...o||{},id:a,type:"adhdev-daemon",status:"online",timestamp:c,...e.version&&{version:e.version},...g&&{machine:g,platform:g.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},...e.beacon&&{beacon:u?e.beacon:void 0},...e.fleetStatusPeerView&&{fleetStatusPeerView:e.fleetStatusPeerView},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:b.some(k=>!!k.cdpConnected)});for(const k of b){const C=h.get(k.id),v=za(k,C),j=(m.get(k.id)||[]).map(y=>za(y,h.get(y.id)));n.push({id:`${a}:ide:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(C==null?void 0:C.providerSessionId),parentSessionId:v.parentId,sessionKind:v.kind,transport:v.transport,sessionCapabilities:v.capabilities,type:v.providerType,status:v.cdpConnected?"online":"detected",daemonId:a,instanceId:Vi(a,k.id),workspace:v.workspace,terminals:0,childSessions:j,agents:j.map(y=>({id:y.id,name:y.providerName||y.providerType,type:y.providerType,status:y.status})),activeChat:v.activeChat,...v.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:v.activeInteractivePrompt},chats:[],cdpConnected:v.cdpConnected,...v.lastMessagePreview!==void 0&&{lastMessagePreview:v.lastMessagePreview},...v.lastMessageRole!==void 0&&{lastMessageRole:v.lastMessageRole},...v.lastMessageAt!==void 0&&{lastMessageAt:v.lastMessageAt},...v.lastMessageHash!==void 0&&{lastMessageHash:v.lastMessageHash},lastUpdated:v.lastUpdated,unread:v.unread,lastSeenAt:v.lastSeenAt,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,seenCompletionMarker:v.seenCompletionMarker,surfaceHidden:v.surfaceHidden,muted:v.muted,...v.controlValues!==void 0&&{controlValues:v.controlValues},...v.providerControls!==void 0&&{providerControls:v.providerControls},...v.summaryMetadata!==void 0&&{summaryMetadata:v.summaryMetadata},...v.settings!==void 0&&{settings:v.settings},...v.messageInput!==void 0&&{messageInput:v.messageInput},timestamp:c})}for(const k of f){const C=h.get(k.id),v=za(k,C);n.push({id:`${a}:cli:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(C==null?void 0:C.providerSessionId),parentSessionId:v.parentId,sessionKind:v.kind,transport:v.transport,sessionCapabilities:v.capabilities,type:v.providerType,agentType:v.providerType,status:v.status||"running",daemonId:a,instanceId:Vi(a,k.id),cliName:v.providerName||v.providerType,mode:v.mode||(C==null?void 0:C.mode)||"terminal",workspace:v.workspace||"",...k.ownerDaemonId&&{ownerDaemonId:k.ownerDaemonId},...k.ownerMachineName&&{ownerMachineName:k.ownerMachineName},activeChat:v.activeChat,...v.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:v.activeInteractivePrompt},...v.resume!==void 0&&{resume:v.resume},...v.runtimeKey!==void 0&&{runtimeKey:v.runtimeKey},...v.runtimeDisplayName!==void 0&&{runtimeDisplayName:v.runtimeDisplayName},...v.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:v.runtimeWorkspaceLabel},...v.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:v.runtimeWriteOwner},...v.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:v.runtimeAttachedClients},...v.lastMessagePreview!==void 0&&{lastMessagePreview:v.lastMessagePreview},...v.lastMessageRole!==void 0&&{lastMessageRole:v.lastMessageRole},...v.lastMessageAt!==void 0&&{lastMessageAt:v.lastMessageAt},...v.lastMessageHash!==void 0&&{lastMessageHash:v.lastMessageHash},lastUpdated:v.lastUpdated,unread:v.unread,lastSeenAt:v.lastSeenAt,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,seenCompletionMarker:v.seenCompletionMarker,surfaceHidden:v.surfaceHidden,muted:v.muted,...v.controlValues!==void 0&&{controlValues:v.controlValues},...v.providerControls!==void 0&&{providerControls:v.providerControls},...v.summaryMetadata!==void 0&&{summaryMetadata:v.summaryMetadata},...v.settings!==void 0&&{settings:v.settings},...v.messageInput!==void 0&&{messageInput:v.messageInput},timestamp:c,_isCli:!0})}for(const k of x){const C=h.get(k.id),v=za(k,C);n.push({id:`${a}:acp:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(C==null?void 0:C.providerSessionId),parentSessionId:v.parentId,sessionKind:v.kind,transport:v.transport,sessionCapabilities:v.capabilities,type:v.providerType,agentType:v.providerType,status:v.status||"running",daemonId:a,instanceId:Vi(a,k.id),cliName:v.providerName||v.providerType,mode:"chat",workspace:v.workspace||"",...k.ownerDaemonId&&{ownerDaemonId:k.ownerDaemonId},...k.ownerMachineName&&{ownerMachineName:k.ownerMachineName},activeChat:v.activeChat,...v.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:v.activeInteractivePrompt},...v.runtimeKey!==void 0&&{runtimeKey:v.runtimeKey},...v.runtimeDisplayName!==void 0&&{runtimeDisplayName:v.runtimeDisplayName},...v.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:v.runtimeWorkspaceLabel},...v.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:v.runtimeWriteOwner},...v.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:v.runtimeAttachedClients},...v.lastMessagePreview!==void 0&&{lastMessagePreview:v.lastMessagePreview},...v.lastMessageRole!==void 0&&{lastMessageRole:v.lastMessageRole},...v.lastMessageAt!==void 0&&{lastMessageAt:v.lastMessageAt},...v.lastMessageHash!==void 0&&{lastMessageHash:v.lastMessageHash},lastUpdated:v.lastUpdated,unread:v.unread,lastSeenAt:v.lastSeenAt,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,seenCompletionMarker:v.seenCompletionMarker,surfaceHidden:v.surfaceHidden,muted:v.muted,...v.controlValues!==void 0&&{controlValues:v.controlValues},...v.providerControls!==void 0&&{providerControls:v.providerControls},...v.summaryMetadata!==void 0&&{summaryMetadata:v.summaryMetadata},...v.settings!==void 0&&{settings:v.settings},...v.messageInput!==void 0&&{messageInput:v.messageInput},timestamp:c,_isAcp:!0})}return pN(n),n}const mN=15e3,hN=15e3,fN=6e4,_u=12,gN=8e3,bN=4e3;function xN(e){const{force:t,hasSubscription:n,loadedAt:a,now:o,minFreshMs:r}=e;return t||a<=0?!0:n?!1:o-a>=r}const Yi=new Map,Qi=new Map,Uo=new Set;function vN(e){if(!e||typeof e!="object")return null;const t=e,n=t.status;if(n&&typeof n=="object")return n;const a=t.result;if(a&&typeof a=="object"&&"status"in a){const o=a.status;if(o&&typeof o=="object")return o}return t}function Na(){const{sendCommand:e,sendData:t}=kt(),{injectEntries:n,getIdes:a}=oo();return l.useCallback(async(o,r)=>{if(!o)return;const i=(r==null?void 0:r.minFreshMs)??fN;if(!xN({force:r==null?void 0:r.force,hasSubscription:Uo.has(o),loadedAt:Qi.get(o)||0,now:Date.now(),minFreshMs:i}))return;const c=Yi.get(o);if(c)return c;const d=(async()=>{t&&!Uo.has(o)&&(Ns.subscribe({sendData:t},o,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${o}`,params:{includeSessions:!0}},f=>{const x=a(),k=x.find(v=>v.id===o),C=Tr(f.status,{daemonId:o,existingDaemon:k,existingEntries:x,timestamp:f.timestamp});C.length>0&&n(C),Qi.set(o,Date.now())}).initialSendAccepted?Uo.add(o):Uo.delete(o));const u=await e(o,"get_status_metadata"),p=vN(u);if(!p)return;const m=a(),h=m.find(b=>b.id===o),g=Tr(p,{daemonId:o,existingDaemon:h,existingEntries:m,timestamp:p.timestamp||Date.now()});g.length>0&&n(g,{authoritativeDaemonIds:[o]}),Qi.set(o,Date.now())})().finally(()=>{Yi.delete(o)});return Yi.set(o,d),d},[a,n,e,t])}const yN=60,wN=50;function hf(e={}){return e.isCliLike?wN:yN}function kN(e={}){return hf(e)}const ff=new Map;function Eu(e,t){if(!e)return t;const n=ff.get(e);return typeof n=="number"&&n>t?n:t}function SN(e,t){e&&ff.set(e,t)}function CN(e){return{"data-transcript-read-source":e.transcriptReadSource,...e.transcriptFallbackReason?{"data-transcript-fallback-reason":e.transcriptFallbackReason}:{},...e.stale?{"data-transcript-stale":"true"}:{},...e.omittedBefore?{"data-transcript-omitted-before":"true"}:{},...e.transcriptReplicaDegraded?{"data-transcript-replica-degraded":"true"}:{}}}function jN(e){const t={role:e.role,kind:e.kind,content:e.content};return e.receivedAt!==null&&(t.receivedAt=e.receivedAt),e.timestamp!==null&&(t.timestamp=e.timestamp),e.bubbleState!==null&&(t.bubbleState=e.bubbleState),e.senderName!==null&&(t.senderName=e.senderName),e.turnKey!==null&&(t._turnKey=e.turnKey),typeof e.sequence=="number"&&(t.sequence=e.sequence),t}function NN(e){if(e.messageSource)return{selected:e.messageSource}}function AN(e){if(!e||typeof e!="object")return!1;const t=e;if(typeof t.sessionId!="string"||!t.sessionId||typeof t.status!="string"||!t.status||!Array.isArray(t.messages)||!t.provenance||typeof t.provenance!="object"||!("activeModal"in t))return!1;const n=t.activeModal;if(n!==null){if(!n||typeof n!="object")return!1;const a=n;if(typeof a.message!="string"||!Array.isArray(a.buttons))return!1}return!0}function TN(e,t){const n=NN(e.provenance);return{topic:"session.chat_tail",key:t.subscriptionKey,sessionId:e.sessionId,...e.historySessionId?{historySessionId:e.historySessionId}:{},seq:e.revision,timestamp:0,messages:e.messages.map(jN),status:e.status,...e.title?{title:e.title}:{},activeModal:e.activeModal?{message:e.activeModal.message,buttons:[...e.activeModal.buttons]}:null,activeInteractivePrompt:null,...n?{messageSource:n}:{},omittedBefore:t.omittedBefore,stale:t.stale,transcriptReadSource:"replica"}}const gf=new Set(["generating","waiting_approval","starting","streaming","working"]);function Ya(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="generating"||t==="no_progress"||t==="long_generating"||t==="streaming"||t==="working"||t==="starting"}const IN=new Set(["agent:generating_completed","agent:stopped","agent:waiting_approval","agent:waiting_choice"]);function PN(e){return typeof e=="string"&&IN.has(e)}function oc(e){const t=typeof e=="string"?e.trim().toLowerCase():"";return gf.has(t)}const jo=60;function DN(e,t=jo){return{tailLimit:t}}function Hu(e,t){const n=e[e.length-1];if(!n)return"empty:";let a="";try{a=JSON.stringify(n.content??"")}catch{a=String(n.content??"")}return["",e.length,String(n.id||""),String(n.index??""),String(n.receivedAt??n.timestamp??""),a].join("|")}function Ir(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(Ir).join(`
41
- `);if(typeof e=="object"){const t=e;return Ir(t.text??t.content??t.value??"")}return String(e)}function od(e){return Ir(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function LN(e){return e.length===0||e.every(od)}function Fu(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t],a=typeof(n==null?void 0:n.role)=="string"?n.role:"",o=typeof(n==null?void 0:n.kind)=="string"?n.kind:"";if(!(a==="system"||o==="system")&&!(o==="tool"||o==="thought"||o==="terminal"||o==="activity")&&!od(e[t]))return a}return""}function $u(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t],a=typeof(n==null?void 0:n.role)=="string"?n.role:"",o=typeof(n==null?void 0:n.kind)=="string"?n.kind:"";if(a==="system"||o==="system"||o==="tool"||o==="thought"||o==="terminal"||o==="activity"||od(e[t]))continue;if(a!=="assistant")return"";const r=e[t];return`${String(r.bubbleId??r.providerUnitKey??r.id??"")}#${Ir(r.content).length}`}return""}function bf(e,t){if(Fu(t)!=="assistant")return!1;const n=Array.isArray(e.liveMessages)?e.liveMessages:[];return Fu(n)!=="assistant"}function bi(e){return typeof e=="string"?{selected:e}:e}function MN(e){const t=bi(e);return!!t&&t.selected==="native-history"}function RN(e,t,n){return MN(n)?bf(e,t):!1}function xf(e,t){return Math.max(Math.max(0,t),Array.isArray(e.liveMessages)?e.liveMessages.length:0)}function _N(e,t,n,a,o,r,i){const c=oc(a)||Ya(a),d=r&&e.hasLiveSnapshot;if(!c&&!d)return!1;const u=c?xf(e,t):Array.isArray(e.liveMessages)?e.liveMessages.length:0;if(u<=0)return!1;if(LN(n))return!0;if(d&&!c&&bf(e,n))return!1;const p=bi(o);if(p){const m=p.selected,h=p.fallbackReason;if(m==="native-history"||typeof h=="string"&&h!==""&&!h.startsWith("native_history_"))return!1}return i==="replica"?!1:n.length<u}function EN(e,t,n,a){if(n.length!==0||xf(e,t)<=0||e.hasLiveSnapshot&&e.liveMessages.length===0)return!1;const r=bi(a);if(!r)return!1;const i=r.selected,c=r.fallbackReason,d=r.nativeSource;return i==="native-history"?c==="native_history_transient_gap_held":d==="native-unavailable"?!0:typeof c=="string"&&c.startsWith("native_history_")}function HN(e,t,n,a,o,r,i){return _N(e,t,n,a,o,r,i)?"defer-busy-shrink":EN(e,t,n,o)?"skip-transient-empty":"apply"}function FN(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}function Bu(e,t){const n=e[t];return typeof n=="string"?n:""}function Wu(e){return e.transcriptReadSource==="replica"?"replica":"legacy"}function Ou(e,t){return e[t]===!0}function Uu(e,t){const n=e[t];return typeof n=="string"&&n.length>0?n:void 0}function $N(e,t){const{sendData:n,sendCommand:a,isConnected:o}=kt(),r=(t==null?void 0:t.enabled)!==!1,i=(t==null?void 0:t.refreshEnabled)!==!1,c=Zn(e),d=e.sessionId||"",u=ui(e),p=`daemon:${c}:session:${d}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??jo),h=e.messages.length,g=l.useMemo(()=>!r||!c||!d?null:wf({daemonId:c,sessionId:d,historySessionId:u,subscriptionKey:p,sendData:n,tailLimit:m,fallbackRecentCount:h,includeActivity:En()}),[c,r,u,n,d,p,m]);l.useEffect(()=>{g==null||g.updateOptions({fallbackRecentCount:h})},[g,h]);const[b,f]=l.useState(()=>(g==null?void 0:g.getSnapshot())||Pr(m));l.useEffect(()=>{if(!g){f(Pr(m));return}g.retain(),f(g.getSnapshot());const v=g.subscribe(j=>{f(j)});return()=>{v(),g.release()}},[g,m]);const x=l.useCallback(async()=>{!g||!c||!d||await g.loadHistoryPage(async({offset:v,excludeRecentCount:j,excludeFromIdentity:y})=>{const S=e.agentType,w=await a(c,"chat_history",{agentType:S,offset:v,limit:30,targetSessionId:d,historySessionId:u,excludeRecentCount:j,...y?{excludeFromIdentity:y}:{},...En()?{includeActivity:!0}:{}}),N=w&&typeof w=="object"&&"result"in w?w.result||{}:w||{};return{messages:Array.isArray(N.messages)?N.messages:[],hasMore:N.hasMore===!0}})},[e.agentType,g,c,u,a,d]),k=l.useCallback((v=!1)=>!g||!c||!d?Promise.resolve():g.refreshAuthoritativeTail(async()=>{const j=await a(c,"read_chat",{agentType:e.agentType,targetSessionId:d,historySessionId:u,...m>0?{tailLimit:m}:{},...En()?{includeActivity:!0}:{}}),y=j&&typeof j=="object"&&"result"in j?j.result:j;if(!y||typeof y!="object"||y.success===!1)return null;const S=Array.isArray(y.messages)?y.messages:Array.isArray(y.messagesTail)?y.messagesTail:[];return{topic:"session.chat_tail",key:p,sessionId:d,historySessionId:u,seq:0,timestamp:0,messages:S,status:typeof y.status=="string"?y.status:"idle",...y.messageSource&&typeof y.messageSource=="object"?{messageSource:y.messageSource}:{}}},{force:v}),[e.agentType,g,c,u,a,d,p,m]);l.useEffect(()=>{if(g)return Kc(v=>{g.updateOptions({includeActivity:v}),v&&k(!0)})},[g,c,d,u]),l.useEffect(()=>{if(!g||!r||!i||!c||!d)return;k(!0);const v=()=>{typeof document<"u"&&document.visibilityState==="visible"&&k()};typeof document<"u"&&document.addEventListener("visibilitychange",v);let j=o?o(c):!0;const y=setInterval(()=>{if(!o)return;const S=o(c);S&&!j&&k(),j=S},2e3);return()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",v),clearInterval(y)}},[g,c,r,i,d,u]);const C=sA({hasController:!!g,enabled:r,daemonId:c,sessionId:d,refreshEnabled:i});return l.useEffect(()=>{if(!g||!C.armed)return;const v=setInterval(()=>{g.shouldRefreshForLiveness({visible:C.visible})&&k()},zN),j=()=>{typeof document>"u"||g.noteVisibilityChange(document.hidden)};return j(),typeof document<"u"&&document.addEventListener("visibilitychange",j),()=>{clearInterval(v),typeof document<"u"&&document.removeEventListener("visibilitychange",j)}},[g,C.armed,C.visible,d,u]),l.useMemo(()=>JN(b,x),[x,b])}function BN(e,t){const{sendData:n}=kt(),a=(t==null?void 0:t.enabled)!==!1,o=Math.max(0,(t==null?void 0:t.tailLimit)??jo),r=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??xi)),i=eA(r),[c,d]=l.useState(0);l.useEffect(()=>{if(!a||e.length===0)return;const p=setInterval(()=>{d(m=>m+1)},i);return()=>{clearInterval(p)}},[e.length,a,i]);const u=l.useMemo(()=>tA(e,{recentActivityMs:r}),[e,r,c]);l.useEffect(()=>{if(!a||!n||u.descriptors.length===0)return;const p=u.descriptors.map(m=>wf({...m,sendData:n,tailLimit:o}));return p.forEach(m=>{m.retain()}),()=>{p.forEach(m=>m.release())}},[u.signature,a,n,o])}function WN(e){const[t,n]=l.useState(0),a=l.useMemo(()=>{const i=[];for(const c of e){const d=Zn(c),u=c.sessionId||"";if(!d||!u)continue;const p=ui(c);i.push(No(d,u,p||u))}return i},[e]),o=a.join("|"),r=l.useSyncExternalStore(VN,zu,zu);return l.useEffect(()=>{if(a.length===0)return;const i=[];for(const c of a){const d=mo.get(c);if(!d)continue;let u=!1;i.push(d.subscribe(()=>{if(!u){u=!0;return}n(p=>p+1)}))}return()=>{for(const c of i)c()}},[o,r]),t}function ON(e){if(!e)return"";const t=e;return t.providerUnitKey?`unit:${t.providerUnitKey}`:t.bubbleId?`bubble:${t.bubbleId}`:typeof t.sequence=="number"&&Number.isFinite(t.sequence)?`seq:${t.sequence}`:""}const UN=1e3,qN=750,zN=5e3,vf=2e4,GN=12e4,KN=6e4,Ji=vf,qu=500,xi=12e4,mo=new Map;let yf=0;const rc=new Set;function ic(){yf+=1;for(const e of rc)e()}function VN(e){return rc.add(e),()=>{rc.delete(e)}}function zu(){return yf}function No(e,t,n){return`${e}::${t}::${n||t}`}function Pr(e=jo){return{liveMessages:[],hasLiveSnapshot:!1,cursor:DN([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null,transcriptReadSource:"legacy",omittedBefore:!1,stale:!1,transcriptReplicaDegraded:!1}}class YN{constructor(t){st(this,"manager");st(this,"sendData");st(this,"daemonId");st(this,"sessionId");st(this,"historySessionId");st(this,"subscriptionKey");st(this,"fallbackRecentCount");st(this,"includeActivity");st(this,"snapshot");st(this,"transportSubscription",null);st(this,"listeners",new Set);st(this,"retainCount",0);st(this,"loadHistoryPromise",null);st(this,"pendingDisconnectTimer",null);st(this,"authoritativeRefreshPromise",null);st(this,"lastAuthoritativeRefreshAt",0);st(this,"now");st(this,"lastActiveStatusAt",0);st(this,"lastAppliedAt",0);st(this,"lastInboundAt",0);st(this,"lastKnownStatus");st(this,"lastMappedRevisionSnapshot",null);st(this,"lastMappedOmittedBefore",!1);st(this,"lastMappedStale",!1);st(this,"terminalStatusRefreshPending",!1);st(this,"lastLivenessAttemptAt",0);st(this,"replicaHealthy",!1);st(this,"everHadHealthyReplica",!1);st(this,"lastReplicaAdvanceAt",0);st(this,"lastReplicaRevision",0);st(this,"lastReplicaBusyAt",0);st(this,"hiddenSinceAt",0);st(this,"hiddenElapsedMs",0);this.manager=t.manager||Ns,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount??0),this.includeActivity=t.includeActivity===!0,this.now=t.now??(()=>Date.now()),this.snapshot=Pr(Math.max(0,t.tailLimit??jo))}updateOptions(t){const n=this.sendData,a=this.daemonId,o=this.sessionId;if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.now&&(this.now=t.now),t.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount)),t.tailLimit!==void 0){const r=Math.max(0,t.tailLimit);r!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect()))}t.includeActivity!==void 0&&t.includeActivity!==this.includeActivity&&(this.includeActivity=t.includeActivity,this.transportSubscription&&(this.disconnect(),this.connect())),this.retainCount>0&&(n!==this.sendData||a!==this.daemonId||o!==this.sessionId)&&(this.disconnect(),this.connect())}getSnapshot(){return this.snapshot}clearLiveSnapshot(){this.snapshot={...Pr(this.snapshot.cursor.tailLimit),hasLiveSnapshot:!0},this.lastMappedRevisionSnapshot=null,this.emit()}reportTranscriptReplicaFallback(t){const n=this.replicaHealthy;this.replicaHealthy=!1,(n||!this.transportSubscription)&&this.syncLegacySubscription();const a=this.everHadHealthyReplica;this.snapshot.transcriptReadSource==="legacy"&&this.snapshot.transcriptFallbackReason===t&&this.snapshot.transcriptReplicaDegraded===a||(this.snapshot={...this.snapshot,transcriptReadSource:"legacy",transcriptFallbackReason:t,transcriptReplicaDegraded:a},this.emit())}applyTranscriptReplicaSnapshot(t,n){if(!AN(t)){this.reportTranscriptReplicaFallback("revision_invalid");return}const a=this.lastMappedRevisionSnapshot===t&&this.lastMappedOmittedBefore===n.omittedBefore&&this.lastMappedStale===(n.stale===!0);let o;if(a){const c=this.now();this.lastInboundAt=c,this.lastKnownStatus=t.status,(oc(t.status)||Ya(t.status))&&(this.lastActiveStatusAt=c),o="noop"}else o=this.handleUpdate(n.mapped??TN(t,{subscriptionKey:this.subscriptionKey,omittedBefore:n.omittedBefore,stale:n.stale===!0})),o==="noop"?(this.lastMappedRevisionSnapshot=t,this.lastMappedOmittedBefore=n.omittedBefore,this.lastMappedStale=n.stale===!0):this.lastMappedRevisionSnapshot=null;const r=typeof t.revision=="number"?t.revision:0;r>this.lastReplicaRevision&&(this.lastReplicaRevision=r,this.lastReplicaAdvanceAt=this.now(),this.hiddenElapsedMs=0),Ya(t.status)&&(this.lastReplicaBusyAt=this.now()),!this.replicaHealthy&&o==="applied"&&(this.replicaHealthy=!0,this.everHadHealthyReplica=!0,this.lastReplicaAdvanceAt===0&&(this.lastReplicaAdvanceAt=this.now()),this.syncLegacySubscription()),this.snapshot.transcriptReplicaDegraded&&(this.snapshot={...this.snapshot,transcriptReplicaDegraded:!1},this.emit())}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect(),this.retainCount===1&&ic()}isRetained(){return this.retainCount>0}getIdentity(){return{daemonId:this.daemonId,sessionId:this.sessionId}}release(){const t=this.retainCount>0;this.retainCount=Math.max(0,this.retainCount-1),t&&this.retainCount===0&&ic(),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const n=(async()=>{try{const a=this.snapshot.hasLiveSnapshot,o=a?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),r=await t({offset:this.snapshot.historyOffset,excludeRecentCount:o,excludeFromIdentity:ON(this.snapshot.liveMessages[0])}),i=Array.isArray(r.messages)?r.messages:[],c=!a&&i.length===0&&r.hasMore!==!0&&this.fallbackRecentCount>0,d=[...i,...this.snapshot.historyMessages],u=d.length>qu?d.slice(d.length-qu):d;this.snapshot={...this.snapshot,historyMessages:u,historyOffset:this.snapshot.historyOffset+i.length,hasMoreHistory:c?!0:r.hasMore===!0,historyError:null}}catch(a){this.snapshot={...this.snapshot,historyError:a instanceof Error?a.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=n,n}expireStaleReplicaLease(){if(!this.replicaHealthy||this.lastReplicaBusyAt===0)return;const t=this.now(),n=this.hiddenElapsedMs+(this.hiddenSinceAt>0?Math.max(0,t-this.hiddenSinceAt):0);if(t-this.lastReplicaBusyAt-n>Ji)return;const a=t-this.lastReplicaAdvanceAt-n>=Ji,o=this.lastAppliedAt>0&&t-this.lastAppliedAt-n>=Ji;!a&&!o||this.reportTranscriptReplicaFallback(a?"replica_lease_expired":"replica_screen_stalled")}noteTerminalStatusEvent(t){PN(t)&&(this.terminalStatusRefreshPending=!0)}noteVisibilityChange(t){const n=this.now();if(t){this.hiddenSinceAt===0&&(this.hiddenSinceAt=n);return}this.hiddenSinceAt!==0&&(this.hiddenElapsedMs+=Math.max(0,n-this.hiddenSinceAt),this.hiddenSinceAt=0)}shouldRefreshForLiveness(t={}){if(this.expireStaleReplicaLease(),this.lastInboundAt===0||this.authoritativeRefreshPromise)return!1;if(this.terminalStatusRefreshPending)return this.terminalStatusRefreshPending=!1,!0;if(this.replicaHealthy)return!1;const n=Math.max(this.lastAppliedAt,this.lastLivenessAttemptAt),a=this.now()-n,o=Ya(this.lastKnownStatus)?vf:GN,r=t.visible===!0?o:Math.max(o,KN);return a>=r}getLivenessStateForTest(){return{lastInboundAt:this.lastInboundAt,lastAppliedAt:this.lastAppliedAt,lastKnownStatus:this.lastKnownStatus}}refreshAuthoritativeTail(t,n={}){if(this.authoritativeRefreshPromise)return this.authoritativeRefreshPromise;const a=this.now();if(!n.force&&this.lastAuthoritativeRefreshAt>0&&a-this.lastAuthoritativeRefreshAt<qN)return Promise.resolve();this.lastAuthoritativeRefreshAt=a;const o=(async()=>{try{const r=await t();r&&this.handleUpdate(r),this.lastInboundAt=this.now(),this.lastLivenessAttemptAt=this.now()}catch{this.lastInboundAt=this.now(),this.lastLivenessAttemptAt=this.now()}})().finally(()=>{this.authoritativeRefreshPromise=null});return this.authoritativeRefreshPromise=o,o}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{},...this.includeActivity?{includeActivity:!0}:{}}}}shouldRunLegacySubscription(){return!this.replicaHealthy}syncLegacySubscription(){this.retainCount<=0||(this.shouldRunLegacySubscription()?this.connect():this.disconnect())}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||this.shouldRunLegacySubscription()&&(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),t=>{this.handleUpdate(t)},{retryIntervalMs:UN}))}disconnect(){var t;(t=this.transportSubscription)==null||t.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null,this.replicaHealthy=!1,this.everHadHealthyReplica=!1,this.lastReplicaAdvanceAt=0,this.lastReplicaRevision=0,this.lastReplicaBusyAt=0,this.hiddenSinceAt=0,this.hiddenElapsedMs=0,this.lastMappedRevisionSnapshot=null}emit(){this.listeners.forEach(t=>t(this.snapshot))}handleUpdate(t){if(t.error)return"rejected";const n=Bu(t,"sessionId");if(n&&n!==this.sessionId)return"rejected";const a=Bu(t,"historySessionId");if(a&&this.historySessionId&&a!==this.historySessionId)return"rejected";const o=FN(t),r=t.messageSource,i=this.now();this.lastInboundAt=i,this.lastKnownStatus=t.status;const c=this.lastActiveStatusAt>0&&i-this.lastActiveStatusAt<=xi;(oc(t.status)||Ya(t.status))&&(this.lastActiveStatusAt=i);const d=RN(this.snapshot,o,r);if(!d&&HN(this.snapshot,this.fallbackRecentCount,o,t.status,r,c,Wu(t))!=="apply")return"deferred";const u={tailLimit:this.snapshot.cursor.tailLimit};return!d&&Hu(this.snapshot.liveMessages)===Hu(o)&&$u(this.snapshot.liveMessages)===$u(o)&&this.snapshot.cursor.tailLimit===u.tailLimit?"noop":(this.lastAppliedAt=i,this.hiddenElapsedMs=0,this.snapshot={...this.snapshot,liveMessages:o,hasLiveSnapshot:!0,cursor:u,messageSource:bi(r),transcriptReadSource:Wu(t),omittedBefore:Ou(t,"omittedBefore"),stale:Ou(t,"stale"),...Uu(t,"transcriptFallbackReason")!==void 0?{transcriptFallbackReason:Uu(t,"transcriptFallbackReason")}:{}},this.emit(),"applied")}}function wf(e){const t=No(e.daemonId,e.sessionId,e.historySessionId),n=mo.get(t);if(n)return n.updateOptions(e),n;const a=new YN(e);return mo.set(t,a),ic(),a}function QN(e,t,n){if(!e||!t)return;const a=`${e}::${t}::`,o=No(e,t,n);for(const[r,i]of mo.entries())(r===o||r.startsWith(a))&&i.clearLiveSnapshot()}function kf(e){const t=Zn(e),n=e.sessionId||"";if(!t||!n)return;const a=ui(e),o=No(t,n,a||n),r=mo.get(o);if(!r)return;const i=r.getSnapshot();return i.hasLiveSnapshot?i:void 0}function JN(e,t){return{...e,loadHistoryPage:t}}function XN(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||(e.historySessionId||"").localeCompare(t.historySessionId||"")}function ZN(e,t={}){const n=String(e.status||"").trim().toLowerCase();if(gf.has(n)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const a=t.now??Date.now(),o=Math.max(0,Number(t.recentActivityMs??xi)),r=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return r>0?a-r<=o:Array.isArray(e.messages)&&e.messages.length>0}function eA(e=xi){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function tA(e,t={}){const n=new Set,a=[];for(const o of e){if(!ZN(o,t))continue;const r=Zn(o),i=o.sessionId||"";if(!r||!i)continue;const c=ui(o),d=No(r,i,c||i);n.has(d)||(n.add(d),a.push({daemonId:r,sessionId:i,historySessionId:c,subscriptionKey:`daemon:${r}:session:${i}`}))}return a.sort(XN),{descriptors:a,signature:a.map(o=>`${o.subscriptionKey}|${o.historySessionId}`).join("||")}}function sA(e){return{armed:!!(e.hasController&&e.enabled&&e.daemonId&&e.sessionId),visible:e.refreshEnabled}}function nA(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function aA(e){return nA(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const mr=new Map,lc=new Set;function Gu(e,t){!e||mr.get(e)===t||(t?mr.set(e,!0):mr.delete(e),lc.forEach(a=>a(e,t)))}function oA(e){return e?mr.get(e)===!0:!1}function rA(e){return lc.add(e),()=>{lc.delete(e)}}function iA(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function lA(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function cA(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Sf(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function Cf(e){const t=typeof e.completionMarker=="string"?e.completionMarker.trim():"";return t||(e.lastMessageHash?e.lastMessageHash:e.lastMessageAt?String(e.lastMessageAt):e.lastUpdated?String(e.lastUpdated):"")}function dA(e){return Sf(e)?!1:e.inboxBucket==="task_complete"&&Cf(e).length>0}function Ku(e){return e.branch||"detached HEAD"}function uA(e){if(e.error)return`${Ku(e)} · Git error: ${e.error}`;const t=[Ku(e)];return e.changedFiles>0?t.push(iA(e.changedFiles,"file")+" changed"):e.dirty||t.push("clean"),e.ahead>0&&t.push(`ahead ${e.ahead}`),e.behind>0&&t.push(`behind ${e.behind}`),e.hasConflicts&&t.push("conflicts"),t.join(" · ")}function pA(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${uA(t)}`}function mA(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function hA(e,t={}){if(t.enabled===!1)return[];if(!cA(e))return[];const n=Sf(e)?"working":dA(e)?"complete":null;if(!n)return[];const a=n==="complete"?Cf(e):"";return[{id:n==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${lA(a)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:pA(n,e.git),timestamp:mA(e,e.git),meta:{source:"git-system-bubble",phase:n,workspace:e.workspacePath,repoRoot:e.git.repoRoot,branch:e.git.branch,changedFiles:e.git.changedFiles,hasConflicts:e.git.hasConflicts}}]}const fA=60,gA=3e4;function bA(e){return{enabled:!!e.sessionId,refreshEnabled:e.isVisible,tailLimit:e.tailLimit}}function xA(e,t){return e.status==="no_progress"||e.status==="long_generating"?t("chatPane.busyNoProgress"):e.status==="generating"||e.status==="streaming"?t("chatPane.busyGenerating"):e.status==="waiting_approval"&&(!e.modalButtons||e.modalButtons.length===0)?t("chatPane.busyWaitingApproval"):null}function jf({activeConv:e,ideEntry:t,handleSendChat:n,handleSendNowQueued:a,handleCancelQueued:o,isSendingChat:r=!1,sendFeedbackMessage:i=null,pendingLocalMessage:c=null,pendingLocalMessages:d=null,retireEchoedPendingMessages:u,handleFocusAgent:p,isFocusingAgent:m,actionLogs:h,userName:g,scrollToBottomRequestNonce:b,isInputActive:f=!0,isVisible:x=!0}){var ee,q,ce,Q,oe,K,B,we;const{t:k}=je("common"),C=l.useRef(new Map),v=l.useRef(void 0),j=Na(),{sendCommand:y}=kt(),{isVisible:S}=Yc();Co("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:h.length,isSendingChat:r});const w=Pt.useMemo(()=>Xn(e),[e.status,e.connectionState]);Pt.useEffect(()=>{const fe=e.sessionId;if(fe)return Gu(fe,w.isGenerating),()=>{Gu(fe,!1)}},[e.sessionId,w.isGenerating]);const N=l.useMemo(()=>Kj(e,t),[e,t]),T=l.useMemo(()=>{var fe;return Zc((fe=N.targetEntry)==null?void 0:fe.providerControls,{hostIdeType:e.hostIdeType,providerType:N.providerType})},[e.hostIdeType,N.providerType,(ee=N.targetEntry)==null?void 0:ee.providerControls]),A=hf({isCliLike:N.isCli||N.isAcp}),M=kN({isCliLike:N.isCli||N.isAcp}),D=$N(e,bA({sessionId:e.sessionId,isVisible:x,tailLimit:M})),[P,I]=l.useState(()=>Eu(e.tabKey,A)),[_,L]=l.useState(()=>En()),R=e.tabKey,O=D.historyMessages,J=D.hasMoreHistory,G=D.historyError,W=Zh(e,D),E=Rj(W,d??(c?[c]:null),void 0,{excludeQueued:!0}),F=((d==null?void 0:d.length)??0)>0;l.useEffect(()=>{if(!u||(u(W),!F))return;const fe=setInterval(()=>u(W),gA);return()=>clearInterval(fe)},[u,W,F]);const H=l.useMemo(()=>Ev(E).length,[E]);l.useEffect(()=>{I(Eu(R,A))},[A,R]);const $=Math.max(0,E.length-P),X=sd(e),U=Zn(e),ge=aA(e),Ne=nd(e),Y=xA(e,k),ie=i||null,me=(Ne?lf:null)||i||Y,he=!!Ne,[re,pe]=l.useState(!1);l.useEffect(()=>{const fe=N.targetEntry;U&&(!fe||fe.providerControls===void 0||fe.controlValues===void 0)&&j(U,{minFreshMs:3e4}).catch(()=>{})},[U,N.isAcp,(q=N.targetEntry)==null?void 0:q.providerControls,(ce=N.targetEntry)==null?void 0:ce.controlValues,j]);const Z=l.useCallback(async()=>{if(!re){if(E.length>P){I(fe=>{const Pe=Math.min(E.length,fe+fA);return SN(R,Pe),Pe});return}pe(!0);try{await D.loadHistoryPage()}finally{pe(!1)}}},[D,re,E.length,R,P]),{allMessages:ue,receivedAtMap:se}=l.useMemo(()=>{const fe=$j({historyMessages:O,liveMessages:E,visibleLiveCount:P}),Pe=hA(e),Fe=Pe.length>0?[...fe,...Pe]:fe,He={};return Fe.forEach((We,be)=>{const Se=oi(We),Be=`${e.tabKey}:${Se}`;let Ze=pr(We)||C.current.get(Be)||0;Ze||(Ze=Date.now(),C.current.set(Be,Ze)),He[Se]=Ze}),{allMessages:Fe,receivedAtMap:He}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,$,O,E,P]),ne=l.useMemo(()=>h.filter(fe=>fe.routeId===e.tabKey).sort((fe,Pe)=>fe.timestamp-Pe.timestamp),[h,e.tabKey]),[le,ve]=l.useState({});l.useEffect(()=>{ve({})},[e.tabKey]);const ke=l.useCallback(async(fe,Pe)=>{if(U){ve(Fe=>({...Fe,[fe]:{status:"loading"}}));try{const Fe=await y(U,"expand_tool_block",{targetSessionId:e.sessionId,agentType:N.providerType||e.agentType,toolBlockRef:Pe}),He=Mn(Fe),We=He!=null&&He.success?He.callArgs!==void 0?`${He.toolName?`${He.toolName}: `:""}${He.callArgs}`:He.result:void 0;ve(be=>({...be,[fe]:We!==void 0?{status:"expanded",text:We}:{status:"error"}}))}catch{ve(Fe=>({...Fe,[fe]:{status:"error"}}))}}},[e.agentType,e.sessionId,N.providerType,U,y]),De=l.useCallback(fe=>{ve(Pe=>{if(!Pe[fe])return Pe;const Fe={...Pe};return delete Fe[fe],Fe})},[]),ye=l.useCallback(async()=>{var be,Se;if(!U)return;const fe=df({activeConv:e,visibleMessages:ue,actionLogs:h,controls:(be=N.targetEntry)==null?void 0:be.providerControls,controlValues:(Se=N.targetEntry)==null?void 0:Se.controlValues,visibleBarControlCount:T.length,chatTailState:{liveMessages:D.liveMessages,hasLiveSnapshot:D.hasLiveSnapshot,hasMoreHistory:J,historyError:G,historyMessages:O},ui:{controlsVisible:S,visibleLiveCount:P,activityVisible:_,activityCount:H,hiddenLiveCount:$,isInputActive:f,isVisible:x}}),Pe=await y(U,"get_chat_debug_bundle",{agentType:N.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:fe}),Fe=Mn(Pe),He=mf(Fe),We=await pf(He);We==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),ft.showToast(uf(Fe,{locatorCopyStatus:We}),We==="failed"?"warning":"success")},[e,h,H,ue,S,D.hasLiveSnapshot,D.liveMessages,N.providerType,(Q=N.targetEntry)==null?void 0:Q.controlValues,(oe=N.targetEntry)==null?void 0:oe.providerControls,U,J,$,O,f,x,G,y,_,T.length,P]);l.useEffect(()=>Kc(L),[]);const V=l.useCallback(()=>{L(fe=>{const Pe=!fe;return mh(Pe),Pe})},[]),te=l.useCallback(()=>{const fe=oN(v.current);v.current=fe.state,fe.shouldCollect&&ye().catch(Pe=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",Pe),ft.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[ye]),Ce=l.useMemo(()=>{if(E.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-xxs text-blue-400 font-medium",children:[k("chatPane.connectingToMachine"),s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-2xs opacity-35",children:k("chatPane.establishingP2P")})]})]});if((w.isGenerating||e.status==="streaming")&&pe(!1),e.status==="not_monitored"&&ge)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(ro,{size:28})}),s.jsx("div",{className:"text-xxs opacity-50",children:k("chatPane.agentNotMonitored")}),s.jsx("button",{onClick:p,disabled:m,className:"btn btn-primary",children:m?s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(an,{size:12}),k("chatPane.switchingPanel")]}):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Un,{size:14})," ",k("chatPane.openPanel",{label:X})]})}),s.jsx("div",{className:"text-2xs opacity-35 max-w-[280px]",children:k("chatPane.clickToSwitchMonitoring")})]});if(e.status==="panel_hidden"&&ge)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Uc,{size:28})}),s.jsx("div",{className:"text-xxs opacity-50",children:k("chatPane.agentPanelHidden")}),s.jsx("button",{onClick:p,disabled:m,className:"btn btn-primary",children:m?s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(an,{size:12}),k("chatPane.openingPanel")]}):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Un,{size:14})," ",k("chatPane.openPanel",{label:X})]})}),s.jsx("div",{className:"text-2xs opacity-35 max-w-[280px]",children:k("chatPane.openPanelHint")})]});if(e.status==="idle"&&!re)return!J&&O.length===0?s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"opacity-40",children:s.jsx(Gs,{size:26})}),s.jsx("div",{className:"text-xxs opacity-40",children:k("chatPane.noMessagesYet")})]}):s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"opacity-40 animate-pulse",children:s.jsx(Gs,{size:26})}),s.jsx("div",{className:"text-xxs opacity-40",children:k("chatPane.loadingChat")})]})}},[e.connectionState,e.status,ge,p,J,O.length,m,re,E.length,X,w.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col relative",...CN(D),children:[s.jsxs("div",{className:"chat-activity-toggle-bar",children:[s.jsxs("button",{type:"button",className:`chat-activity-toggle ${_?"chat-activity-toggle-active":""}`,onClick:V,"aria-pressed":_,title:k("chatPane.activityToggleTitle"),children:[s.jsx("span",{className:"chat-activity-toggle-dot"}),k("chatPane.activityToggleLabel"),H>0&&s.jsx("span",{className:"chat-activity-toggle-count",children:H})]}),s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx(Cj,{sessionId:e.sessionId,daemonId:e.daemonId,muted:!!((K=N.targetEntry)!=null&&K.muted),sendDaemonCommand:y}),s.jsx(kj,{sessionId:e.sessionId,daemonId:e.daemonId,conv:e})]})]}),D.transcriptReplicaDegraded&&s.jsx("div",{className:"px-3 py-1.5 text-2xs text-amber-400/90 bg-amber-500/10 border-b border-amber-500/20",role:"status","data-testid":"transcript-replica-degraded-notice",children:k("chatPane.replicaDegraded")}),s.jsx(Xv,{messages:ue,actionLogs:ne,agentName:wa(e)||X||"Agent",userName:g,isCliMode:N.isCli||N.isAcp,isWorking:w.isGenerating,contextKey:e.tabKey,receivedAtMap:se,lastMessageHash:e.lastMessageHash,showActivityMessages:_,onLoadMore:Z,isLoadingMore:re,hasMoreHistory:J,hiddenLiveCount:$,loadError:G??void 0,emptyState:Ce,scrollToBottomRequestNonce:b,isVisible:x,onSendNow:a,isSendingNow:r,onCancelQueued:o,toolExpansions:le,onExpandToolBlock:ke,onCollapseToolBlock:De}),s.jsx(BC,{entries:d??(c?[c]:[]),onSendNow:a,onCancelQueued:o,isSendingNow:r}),s.jsx(RC,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:N.providerType,displayLabel:N.displayLabel,controls:(B=N.targetEntry)==null?void 0:B.providerControls,controlValues:(we=N.targetEntry)==null?void 0:we.controlValues,currentStatus:e.status,coordinatorHint:fi(e),isActive:f,isCliTerminal:N.isCliTerminal}),!N.isCliTerminal&&s.jsx(Oh,{contextKey:e.tabKey,panelLabel:X,isSending:r,isBusy:he,statusMessage:me,inlineStatusMessage:ie,onSend:n,isActive:f,showControlsToggle:T.length>0,onControlsToggle:te,messageInput:e.messageInput})]})}let Nf=zs;function Af(){return Nf()}class vA{constructor(){st(this,"listeners",new Map)}send(t,n){return!1}isConnected(){return!1}on(t,n){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(n),()=>{var a;(a=this.listeners.get(t))==null||a.delete(n)}}emit(t,...n){var a;(a=this.listeners.get(t))==null||a.forEach(o=>o(...n))}}let Tf=new vA;class yA{sendPtyInput(t,n,a){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,n){return!1}get(t){}onScreenshot(t,n){return()=>{}}onRuntimeEvent(t,n,a){return()=>{}}requestRuntimeSnapshot(t,n,a){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let Et=new yA;function wA(e){e.dashboardWS&&(Tf=e.dashboardWS),e.connectionManager&&(Et=e.connectionManager),e.useDaemonsHook&&(Nf=e.useDaemonsHook)}const kA=.5,SA=1.25,Is="\x1B",Vu={ArrowUp:"A",ArrowDown:"B",ArrowLeft:"D",ArrowRight:"C"};function CA(e){return 1+(e.shift?1:0)+(e.alt?2:0)+(e.ctrl?4:0)}function Yu(e,t){let n=e;if(t.shift&&n.length===1&&(n=n.toUpperCase()),t.ctrl){const a=n.toUpperCase().charCodeAt(0);return String.fromCharCode(a&31)}return n}function jA(e,t){if(t in Vu){const a=Vu[t],o=CA(e);return o===1?`${Is}[${a}`:`${Is}[1;${o}${a}`}switch(t){case"Enter":return e.alt?`${Is}\r`:"\r";case"Escape":return e.alt?`${Is}${Is}`:Is;case"Backspace":{const a=e.ctrl?"\b":"";return e.alt?`${Is}${a}`:a}case"Tab":{const a=e.shift?`${Is}[Z`:" ";return e.alt&&!e.shift?`${Is} `:a}case"Space":{const a=Yu(" ",e);return e.alt?`${Is}${a}`:a}}const n=Yu(t,e);return e.alt?`${Is}${n}`:n}function At(e){return sd(e)}function ka(e){return of(e).join(" · ")}function If(e){var t,n;return!!e.daemonId&&!!((t=e.coordinator)!=null&&t.meshId||typeof((n=e.settings)==null?void 0:n.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0)}function NA(e){var o,r,i;const t=[],n=typeof((o=e.settings)==null?void 0:o.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0,a=!!((r=e.coordinator)!=null&&r.meshId)||typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0;return n&&t.push("Mesh node"),a&&t.push("Coordinator"),t}function AA(e){var i,c,d;const t=[],n=typeof((i=e.settings)==null?void 0:i.meshNodeFor)=="string"?e.settings.meshNodeFor.trim():"",a=typeof((c=e.coordinator)==null?void 0:c.meshId)=="string"?e.coordinator.meshId.trim():"",o=typeof((d=e.settings)==null?void 0:d.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor.trim():"",r=a||o;if(n&&t.push(`Mesh node: ${n}`),r&&t.push(`Coordinator: ${r}`),e.meshQueueStats){const{pending:u,assigned:p,completed:m,failed:h}=e.meshQueueStats;t.push(`Queue: ${u} pending, ${p} assigned, ${m} completed, ${h} failed`)}return t.join(" · ")}function Pf(e,t){const n=af(e,t);return n||(e.title?e.title:ka(e)||"No messages yet")}function Df(e,t){const{isReconnecting:n,isConnecting:a,isErrored:o}=Xn(e);return n?"Reconnecting…":a?"Connecting…":t!=null&&t.requiresAction?"Action needed":o?"Needs attention":null}function TA(e,t){const n=["Chat",...of(e)];return t!=null&&t.timestampLabel&&n.push(t.timestampLabel),n.filter(Boolean).join(" · ")}function Hn(e){return Df(e)||ka(e)}function IA(e,t){return`${At(e)} · ${Pf(e,t)}`}function PA(e){const t=Ar(e),n=t?ts(t):wa(e);return`${At(e)} — ${n||"Agent"}`}function DA(e){return wa(e)||"CLI"}function Lf(e){return nf(e)}function Mf(e){return e?`Remote · ${At(e)||e.workspaceName||"Session"}`:"Remote"}const Qu=[{kind:"regex",label:"section matches",hint:"regex against a screen section",make:e=>({section:e[0],matches:""})},{kind:"elapsed",label:"elapsed_ms",hint:"N ms since state entered",make:()=>({elapsed_ms:1e3})},{kind:"stable",label:"stable_ms",hint:"region unchanged for N ms",make:()=>({stable_ms:1e3,cursor_above:5})},{kind:"changed",label:"changed",hint:"region changed vs prev frame",make:()=>({cursor_above:3,changed:!0})},{kind:"all",label:"all (AND)",hint:"every child must match",make:()=>({all:[]})},{kind:"any",label:"any (OR)",hint:"some child must match",make:()=>({any:[]})},{kind:"not",label:"not",hint:"invert a condition",make:()=>({not:{matches:""}})}],LA=[{label:"active spinner (busy)",cond:{section:"body",matches:"(?:^|\\n)\\s*[·✢✳✶✽✷✸✹]\\s+\\w.*?(?:…|\\.\\.\\.)"}},{label:"completion marker (done)",cond:{section:"body",matches:"✻\\s+\\w+ed\\s+for\\s+(?:\\d+h\\s+)?(?:\\d+m\\s+)?\\d+s"}},{label:"approval prompt (❯ 1.)",cond:{section:"footer",matches:"(?:^|\\n)\\s*[❯›>]\\s*1\\.\\s*.+"}},{label:"picker (Select a …)",cond:{section:"modal",matches:"Select (?:a |an )?(?:model|mode|option)\\b"}},{label:"stable 1.2s (settled)",cond:{stable_ms:1200,cursor_above:5}}];function MA(e){return"all"in e?"all":"any"in e?"any":"not"in e?"not":"elapsed_ms"in e?"elapsed":"stable_ms"in e&&!("changed"in e)?"stable":"changed"in e?"changed":"regex"}function rd({cond:e,path:t,sections:n,onChange:a,onRemove:o,onPreview:r,preview:i}){const c=MA(e),d=i[t],u=p=>{const m=Qu.find(h=>h.kind===p);m&&a(m.make(n))};return s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-1.5 space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("select",{value:c,onChange:p=>u(p.target.value),className:"bg-bg-secondary text-text-primary text-3xs font-mono rounded border border-border-default px-1 py-0.5",children:Qu.map(p=>s.jsx("option",{value:p.kind,children:p.label},p.kind))}),(c==="regex"||c==="stable"||c==="changed"||c==="elapsed")&&s.jsx("button",{type:"button",className:"text-3xs text-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:()=>r(t,e),children:"test"}),d&&d!=="loading"&&s.jsx("span",{className:`text-3xs font-mono px-1.5 py-0.5 rounded ${d.result?"text-status-online bg-status-online/20":"text-text-secondary bg-bg-glass"}`,children:d.result?"match ✓":"no match"}),d==="loading"&&s.jsx("span",{className:"text-3xs text-text-muted",children:"testing…"}),o&&s.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-xs px-1",onClick:o,children:"×"})]}),c==="regex"&&s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs("select",{value:e.section??"",onChange:p=>a({...e,section:p.target.value||void 0}),className:"bg-bg-secondary text-accent-primary text-3xs font-mono rounded border border-border-default px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(whole screen)"}),n.map(p=>s.jsx("option",{value:p,children:p},p))]}),s.jsx("input",{value:e.matches??"",onChange:p=>a({...e,matches:p.target.value}),placeholder:"regex",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-primary text-3xs font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),c==="elapsed"&&s.jsx(hn,{label:"elapsed_ms",value:e.elapsed_ms,onChange:p=>a({elapsed_ms:p})}),c==="stable"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(hn,{label:"stable_ms",value:e.stable_ms,onChange:p=>a({...e,stable_ms:p})}),s.jsx(hn,{label:"cursor_above",value:e.cursor_above??0,onChange:p=>a({...e,cursor_above:p||void 0})})]}),c==="changed"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(hn,{label:"cursor_above",value:e.cursor_above,onChange:p=>a({...e,cursor_above:p})}),s.jsxs("label",{className:"flex items-center gap-1 text-3xs text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:!!e.changed,onChange:p=>a({...e,changed:p.target.checked}),className:"accent-[var(--accent-primary)]"}),"changed"]})]}),(c==="all"||c==="any")&&s.jsx(RA,{kind:c,cond:e,path:t,sections:n,onChange:a,onPreview:r,preview:i}),c==="not"&&s.jsx("div",{className:"pl-2 border-l border-border-default",children:s.jsx(rd,{cond:e.not,path:`${t}.not`,sections:n,onChange:p=>a({not:p}),onPreview:r,preview:i})})]})}function RA({kind:e,cond:t,path:n,sections:a,onChange:o,onPreview:r,preview:i}){const c=(e==="all"?t.all:t.any)??[],d=u=>o(e==="all"?{all:u}:{any:u});return s.jsxs("div",{className:"pl-2 border-l border-border-default space-y-1",children:[c.map((u,p)=>s.jsx(rd,{cond:u,path:`${n}.${e}[${p}]`,sections:a,onChange:m=>d(c.map((h,g)=>g===p?m:h)),onRemove:()=>d(c.filter((m,h)=>h!==p)),onPreview:r,preview:i},p)),s.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[s.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d([...c,{section:a[0],matches:""}]),children:"+ condition"}),LA.map(u=>s.jsxs("button",{type:"button",className:"text-3xs text-accent-primary/80 hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:()=>d([...c,JSON.parse(JSON.stringify(u.cond))]),title:"insert verified pattern",children:["+ ",u.label]},u.label))]})]})}function hn({label:e,value:t,onChange:n}){return s.jsxs("label",{className:"flex items-center gap-1 text-3xs text-text-secondary font-mono",children:[e,s.jsx("input",{type:"number",value:Number.isFinite(t)?t:0,onChange:a=>n(Number(a.target.value)),className:"w-20 bg-bg-secondary text-text-primary rounded border border-border-default px-1 py-0.5 outline-none focus:border-accent"})]})}function _A({sections:e,otherSectionIds:t,onChange:n,onTest:a,testResult:o}){const r=Object.keys(e),i=o&&o!=="loading"&&!("error"in o)?Object.fromEntries(o.sections.map(m=>[m.id,m])):{},c=(m,h)=>{if(!h||h===m||e[h])return;const g={};for(const[b,f]of Object.entries(e))g[b===m?h:b]=f;n(g)},d=(m,h)=>n({...e,[m]:h}),u=m=>{const h={...e};delete h[m],n(h)},p=()=>{let m="section",h=1;for(;e[m];)m=`section${h++}`;n({...e,[m]:{from_top:0}})};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold",children:"Sections"}),s.jsx("span",{className:"text-text-muted text-3xs",children:"— how the screen is split; conditions match against these"}),s.jsx("button",{type:"button",className:"ml-auto text-3xs text-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:a,title:"Resolve all sections against the live session screen",children:o==="loading"?"testing…":"test on live screen"}),s.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:p,children:"+ section"})]}),o&&o!=="loading"&&"error"in o&&s.jsx("div",{className:"text-status-error bg-status-error/15 border border-status-error/40 rounded p-1.5 text-3xs mb-1",children:o.error}),s.jsx("div",{className:"space-y-1.5",children:r.map(m=>{var f;const h=e[m],g=h.anchor!=null?"anchor":"positional",b=x=>{x==="anchor"?d(m,{anchor:h.anchor??"^",anchor_last:h.anchor_last,until:h.until}):d(m,{from_top:h.from_top??0,until:h.until})};return s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{value:m,onChange:x=>c(m,x.target.value.trim()),className:"w-28 bg-bg-secondary text-accent-primary font-mono text-2xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsxs("div",{className:"inline-flex rounded border border-border-default overflow-hidden text-3xs",children:[s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${g==="positional"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>b("positional"),children:"positional"}),s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${g==="anchor"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>b("anchor"),children:"anchor"})]}),s.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-sm px-1",onClick:()=>u(m),children:"×"})]}),g==="positional"?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx(hn,{label:"from_top",value:typeof h.from_top=="number"?h.from_top:0,onChange:x=>d(m,{...h,from_top:x,from_bottom:void 0})}),s.jsx(hn,{label:"from_bottom",value:typeof h.from_bottom=="number"?h.from_bottom:0,onChange:x=>d(m,{...h,from_bottom:x||void 0})}),s.jsx(Ju,{def:h,otherIds:t(m),onChange:x=>d(m,x)})]}):s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-3xs text-text-muted w-16",children:"anchor"}),s.jsx("input",{value:h.anchor??"",onChange:x=>d(m,{...h,anchor:x.target.value}),placeholder:"^regex locating section start",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-primary text-3xs font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsxs("label",{className:"flex items-center gap-1 text-3xs text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:!!h.anchor_last,onChange:x=>d(m,{...h,anchor_last:x.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"last"]})]}),s.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s.jsx(Ju,{def:h,otherIds:t(m),onChange:x=>d(m,x)})}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-3xs text-text-muted w-16",children:"ctx next"}),s.jsx("input",{value:((f=h.anchor_context)==null?void 0:f.next)??"",onChange:x=>d(m,{...h,anchor_context:{...h.anchor_context,next:x.target.value||void 0}}),placeholder:"optional: line after anchor must match",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-secondary text-3xs font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]})]}),i[m]&&s.jsxs("div",{className:"border-t border-border-subtle pt-1",children:[s.jsxs("div",{className:"text-4xs text-text-muted mb-0.5",children:["captured lines ",i[m].fromLine,"–",i[m].toLine,i[m].text.trim()===""&&s.jsx("span",{className:"text-amber-400 ml-1",children:"(empty — check bounds)"})]}),s.jsx("pre",{className:"font-mono text-3xs text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary rounded border border-border-subtle px-2 py-1 max-h-28 overflow-y-auto",children:i[m].text||"(empty)"})]})]},m)})})]})}function Ju({def:e,otherIds:t,onChange:n}){const a=e.until??"",o=a.startsWith("^");return s.jsxs("label",{className:"flex items-center gap-1 text-3xs text-text-secondary",children:["until",s.jsxs("select",{value:o?"__regex__":a,onChange:r=>{const i=r.target.value;n(i===""?{...e,until:void 0}:i==="__regex__"?{...e,until:a.startsWith("^")?a:"^"}:{...e,until:i})},className:"bg-bg-secondary text-accent-primary rounded border border-border-default px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(none)"}),t.map(r=>s.jsx("option",{value:r,children:r},r)),s.jsx("option",{value:"__regex__",children:"regex…"})]}),o&&s.jsx("input",{value:a,onChange:r=>n({...e,until:r.target.value}),spellCheck:!1,className:"w-40 bg-bg-secondary text-text-primary font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]})}function EA({model:e,onChange:t,onPreview:n,preview:a,onTestSections:o,sectionPreview:r}){const i=e.states.map(m=>m.id),c=Object.keys(e.sections??{}),d=l.useCallback(m=>t({...e,...m}),[e,t]),u=(m,h)=>d({states:e.states.map((g,b)=>b===m?{...g,...h}:g)}),p=(m,h)=>d({transitions:e.transitions.map((g,b)=>b===m?{...g,...h}:g)});return s.jsxs("div",{className:"space-y-3",children:[s.jsx(_A,{sections:e.sections??{},otherSectionIds:m=>c.filter(h=>h!==m),onChange:m=>d({sections:m}),onTest:()=>o(e.sections??{}),testResult:r}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold",children:"States"}),s.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d({states:[...e.states,{id:`state${e.states.length}`,label:"New"}]}),children:"+ state"})]}),s.jsx("div",{className:"space-y-1.5",children:e.states.map((m,h)=>s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1",children:[s.jsxs("div",{className:"flex items-end gap-2 flex-wrap",children:[s.jsxs("label",{className:"flex flex-col gap-0.5",children:[s.jsx("span",{className:"text-4xs text-text-muted uppercase tracking-wide",children:"id (used by transitions)"}),s.jsx("input",{value:m.id,onChange:g=>u(h,{id:g.target.value}),placeholder:"idle",className:"w-32 bg-bg-secondary text-accent-primary font-mono text-2xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),s.jsxs("label",{className:"flex flex-col gap-0.5 flex-1",children:[s.jsx("span",{className:"text-4xs text-text-muted uppercase tracking-wide",children:"label (shown in dashboard)"}),s.jsx("input",{value:m.label,onChange:g=>u(h,{label:g.target.value}),placeholder:"Ready",className:"w-full bg-bg-secondary text-text-primary text-2xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),s.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1 pb-0.5",onClick:()=>d({states:e.states.filter((g,b)=>b!==h)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-3xs text-text-secondary flex-wrap",children:[s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"radio",name:"initial",checked:!!m.initial,onChange:()=>d({states:e.states.map((g,b)=>({...g,initial:b===h}))}),className:"accent-[var(--accent-primary)]"}),"initial"]}),s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"checkbox",checked:!!m.modal,onChange:g=>u(h,{modal:g.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"modal"]}),s.jsxs("label",{className:"flex items-center gap-1",children:["status",s.jsxs("select",{value:m.status??"",onChange:g=>u(h,{status:g.target.value||void 0}),className:"bg-bg-secondary text-text-primary rounded border border-border-default px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(auto)"}),s.jsx("option",{value:"idle",children:"idle"}),s.jsx("option",{value:"generating",children:"generating"}),s.jsx("option",{value:"approval",children:"approval"})]})]})]})]},h))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold",children:"Transitions"}),s.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d({transitions:[...e.transitions,{from:i[0]??"",to:i[0]??""}]}),children:"+ transition"})]}),s.jsx("div",{className:"space-y-1.5",children:e.transitions.map((m,h)=>s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"text-3xs text-text-muted",children:"from"}),s.jsx(HA,{value:m.from,states:i,onChange:g=>p(h,{from:g})}),s.jsx("span",{className:"text-3xs text-text-muted",children:"→"}),s.jsx("select",{value:m.to,onChange:g=>p(h,{to:g.target.value}),className:"bg-bg-secondary text-status-online font-mono text-3xs rounded border border-border-default px-1 py-0.5",children:i.map(g=>s.jsx("option",{value:g,children:g},g))}),s.jsx("span",{className:"text-3xs text-text-muted ml-1",children:"label"}),s.jsx("input",{value:m.label??"",onChange:g=>p(h,{label:g.target.value||void 0}),placeholder:"debug name only (optional)",title:"Display name shown in the debug history/transition table. Does not affect behaviour.",className:"flex-1 min-w-[120px] bg-bg-secondary text-text-secondary text-3xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1",onClick:()=>d({transitions:e.transitions.filter((g,b)=>b!==h)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(hn,{label:"min_hold_ms",value:m.min_hold_ms??0,onChange:g=>p(h,{min_hold_ms:g||void 0})}),s.jsx(hn,{label:"priority",value:m.priority??0,onChange:g=>p(h,{priority:g||void 0})})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-3xs text-text-muted",children:"when"}),!m.when&&s.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>p(h,{when:{section:c[0],matches:""}}),children:"+ guard condition"}),m.when&&s.jsx("button",{type:"button",className:"text-3xs text-text-muted hover:text-status-error",onClick:()=>p(h,{when:void 0}),children:"remove guard"})]}),m.when&&s.jsx(rd,{cond:m.when,path:`t${h}`,sections:c,onChange:g=>p(h,{when:g}),onPreview:n,preview:a})]})]},h))})]})]})}function HA({value:e,states:t,onChange:n}){const a=new Set(Array.isArray(e)?e:e==="*"?t:[e]),o=e==="*",r=i=>{const c=new Set(a);c.has(i)?c.delete(i):c.add(i);const d=t.filter(u=>c.has(u));n(d.length===1?d[0]:d)};return s.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.map(i=>s.jsx("button",{type:"button",onClick:()=>r(i),className:`font-mono text-3xs px-1 py-0.5 rounded border ${o||a.has(i)?"text-accent-primary bg-accent-primary/20 border-accent":"text-text-muted border-border-default hover:border-border-default"}`,children:i},i))})}function Ss(e){return e&&typeof e=="object"?e:{}}function St(e){return typeof e=="string"?e:""}function FA(e){const t=Ss(e);return!!(typeof t.spec_id=="string"&&t.spec_id.length>0||"current_state"in t||Array.isArray(t.stateHistory))}function $A(e){const t=Ss(e.parser),n=Ss(t.parsedStatusCache),a=Ss(e.activeModal).buttons!=null?Ss(e.activeModal):Ss(n.activeModal),o=Array.isArray(a.buttons)?a.buttons:null;if(!o||o.length===0){const r=St(a.message)||St(a.title);return r?{title:r,buttons:[]}:null}return{title:St(a.message)||St(a.title)||null,buttons:o.map((r,i)=>({index:i,label:typeof r=="string"?r:String(r)}))}}function BA(e){const t=Array.isArray(e.messages)?e.messages:null;return t?t.map(n=>Ss(n)).filter(n=>typeof n.role=="string").map(n=>({role:St(n.role),content:St(n.content),receivedAt:typeof n.receivedAt=="number"?n.receivedAt:void 0})):[]}function Xu(e){if(e==null||typeof e!="object")return null;const t=e;if(FA(e))return{cliType:St(t.cliType),spec_id:St(t.spec_id),specPath:typeof t.specPath=="string"?t.specPath:void 0,current_state:t.current_state??null,current_modal:t.current_modal??null,activeInteractivePrompt:t.activeInteractivePrompt,exited:t.exited===!0,screen:St(t.screen),sections:t.sections??void 0,stateHistory:Array.isArray(t.stateHistory)?t.stateHistory:[],statusHistory:[],idleHoldPending:t.idleHoldPending===!0,lastBusyAt:typeof t.lastBusyAt=="number"?t.lastBusyAt:0,cursorPosition:t.cursorPosition??null,completionIdleDebounce:t.completionIdleDebounce??null,fsm:t.fsm??null,name:typeof t.name=="string"?t.name:void 0,status:typeof t.status=="string"?t.status:void 0,workingDir:typeof t.workingDir=="string"?t.workingDir:void 0,spawnedAtMs:typeof t.spawnedAtMs=="number"?t.spawnedAtMs:void 0,providerSessionId:t.providerSessionId??null,messages:t.messages??void 0,committedMessages:t.committedMessages??void 0,nativeSource:!1,transcriptAuthority:void 0};const n=Ss(t.terminal),a=Ss(t.parser),o=Ss(a.parsedStatusCache),r=Ss(t.runtimeMetadata),i=St(n.screenText)||St(n.lastScreenText)||St(t.screenText),c=St(o.status)||St(t.currentStatus)||St(t.status),d=St(o.providerSessionId)||St(r.providerSessionId)||null,u=St(o.transcriptAuthority)||St(t.transcriptAuthority)||void 0,p=(Array.isArray(t.statusHistory)?t.statusHistory:[]).map(m=>Ss(m)).filter(m=>typeof m.status=="string"&&typeof m.at=="number").map(m=>({status:m.status,at:m.at,trigger:typeof m.trigger=="string"?m.trigger:null}));return{cliType:St(t.cliType)||St(t.type),spec_id:St(t.cliType)||St(t.type)||"native-source",specPath:typeof t.specPath=="string"?t.specPath:void 0,current_state:c?{id:c,label:c,title:null}:null,current_modal:$A(t),activeInteractivePrompt:t.activeInteractivePrompt??null,exited:t.exited===!0,screen:i,sections:void 0,stateHistory:[],statusHistory:p,idleHoldPending:!1,lastBusyAt:typeof t.lastBusyAt=="number"?t.lastBusyAt:0,cursorPosition:null,completionIdleDebounce:null,fsm:null,name:St(t.cliName)||St(t.name)||void 0,status:c||void 0,workingDir:typeof t.workingDir=="string"?t.workingDir:void 0,spawnedAtMs:typeof r.spawnedAtMs=="number"?r.spawnedAtMs:typeof t.spawnAt=="number"?t.spawnAt:void 0,providerSessionId:d,messages:BA(t),committedMessages:void 0,nativeSource:!0,transcriptAuthority:u}}function ta(e){const t=Date.now()-e;if(t<0)return"just now";if(t<2e3)return`${t}ms ago`;if(t<6e4)return`${(t/1e3).toFixed(1)}s ago`;const n=Math.floor(t/6e4);return n<60?`${n}m ago`:`${Math.floor(n/60)}h ago`}function Zu(e){return e<=0?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}const WA={busy_hold_expired:"text-status-warning bg-status-warning/20 border border-status-warning/40",idle_hold_committed:"text-status-online bg-status-online/20 border border-status-online/40",completion_idle_after:"text-accent-primary bg-accent-primary/20 border border-accent",forced_completion:"text-orange-200 bg-orange-500/20 border border-orange-500/30",forceEmit:"text-purple-200 bg-purple-500/20 border border-purple-500/30",spec_reload:"text-purple-200 bg-purple-500/20 border border-purple-500/30",eval_match:"text-text-secondary bg-bg-glass border border-border-default"},OA={idle:"text-status-online bg-status-online/20 border border-status-online/40",busy:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",generating:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",waiting_approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",picker:"text-accent-primary bg-accent-primary/20 border border-accent",signing_in:"text-accent-primary bg-accent-primary/20 border border-accent"};function qo(e){return OA[e]??"text-text-primary bg-bg-glass border border-border-default"}function sa({children:e}){return s.jsx("div",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold mb-1.5 mt-0.5",children:e})}function zo(){return s.jsx("div",{className:"border-t border-white/8 my-2"})}function Rf({node:e,depth:t=0}){var o;const n=e.result?"text-status-online":"text-text-muted",a=e.result?"●":"○";return s.jsxs("div",{style:{marginLeft:t*10},className:"font-mono text-3xs leading-relaxed",children:[s.jsxs("span",{className:n,children:[a," "]}),s.jsx("span",{className:"text-text-secondary",children:e.kind}),s.jsxs("span",{className:"text-text-muted",children:[" ",e.detail]}),e.remainingMs!=null&&e.remainingMs>0&&s.jsxs("span",{className:"text-status-warning",children:[" (",e.remainingMs,"ms left)"]}),(o=e.children)==null?void 0:o.map((r,i)=>s.jsx(Rf,{node:r,depth:t+1},i))]})}function UA({t:e}){const[t,n]=l.useState(!1),a=e.fires?"text-status-online bg-status-online/20 border-status-online/40":e.holdSatisfied?"text-text-secondary bg-bg-glass border-border-default":"text-status-warning bg-status-warning/20 border-status-warning/40";return s.jsxs("div",{className:"border border-border-default rounded bg-surface-secondary overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-1 hover:bg-bg-glass-hover text-left",onClick:()=>n(o=>!o),children:[s.jsx("span",{className:"text-3xs text-text-muted w-3",children:e.cond?t?"▾":"▸":" "}),s.jsxs("span",{className:`font-mono text-2xs px-1.5 py-0.5 rounded border ${a}`,children:["→ ",e.to]}),s.jsx("span",{className:"text-text-secondary font-mono text-3xs truncate",children:e.label}),s.jsxs("span",{className:"ml-auto flex items-center gap-1.5 shrink-0",children:[e.fires&&s.jsx("span",{className:"text-status-online text-3xs font-mono",children:"FIRES"}),!e.holdSatisfied&&s.jsxs("span",{className:"text-status-warning text-3xs font-mono",children:["hold ",e.holdRemainingMs,"ms"]}),s.jsx("span",{className:`text-3xs font-mono ${e.condResult?"text-status-online":"text-text-muted"}`,children:e.condResult?"cond✓":"cond✗"})]})]}),t&&e.cond&&s.jsx("div",{className:"px-3 pb-1.5 pt-0.5 bg-bg-secondary border-t border-border-default",children:s.jsx(Rf,{node:e.cond})})]})}function qA({activeConv:e,onClose:t}){var he,re,pe,Z,ue;const{sendCommand:n}=kt(),[a,o]=l.useState(!0),[r,i]=l.useState(null),[c,d]=l.useState(null),[u,p]=l.useState(!1),[m,h]=l.useState(new Set(["footer"])),[g,b]=l.useState("Snapshot"),[f,x]=l.useState(!1),[k,C]=l.useState(null),[v,j]=l.useState(!1),[y,S]=l.useState(""),[w,N]=l.useState(!1),[T,A]=l.useState("idle"),[M,D]=l.useState(null),[P,I]=l.useState([]),[_,L]=l.useState({}),[R,O]=l.useState(null),[J,G]=l.useState(!1),W=e.daemonId||((he=e.routeId)==null?void 0:he.split(":")[0])||e.routeId||"",E=e.sessionId||"",F=l.useCallback(async()=>{o(!0),d(null);try{const se=await n(W,"get_spec_debug",{targetSessionId:E}),ne=se&&typeof se=="object"?se:{},le=ne.result&&typeof ne.result=="object"?ne.result:ne;le!=null&&le.success?i(le):(d((le==null?void 0:le.error)||"Failed to load spec debug"),i(null))}catch(se){d((se==null?void 0:se.message)||String(se)),i(null)}finally{o(!1)}},[n,W,E]);l.useEffect(()=>{F()},[F]),l.useEffect(()=>{if(!J)return;const se=setInterval(()=>{F()},1e3);return()=>clearInterval(se)},[J,F]),l.useEffect(()=>{const se=ne=>{ne.key==="Escape"&&!f&&t()};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[t,f]);const H=l.useCallback(async se=>{try{const ne=await n(W,"validate_spec",{content:JSON.stringify(se)}),le=ne&&typeof ne=="object"?ne:{},ve=le.result&&typeof le.result=="object"?le.result:le;I(ve!=null&&ve.valid?[]:(ve==null?void 0:ve.errors)??["validation failed"])}catch(ne){I([(ne==null?void 0:ne.message)||String(ne)])}},[n,W]),$=l.useCallback(async()=>{D(null),A("idle"),L({});try{const se=await n(W,"get_spec_source",{targetSessionId:E}),ne=se&&typeof se=="object"?se:{},le=ne.result&&typeof ne.result=="object"?ne.result:ne;if(!(le!=null&&le.success)||typeof le.content!="string"){D((le==null?void 0:le.error)||"Failed to load spec source");return}S(le.content);let ve=null;try{ve=JSON.parse(le.content)}catch{}ve&&ve.$schema==="adhdev:cli/spec@4"?(C(ve),j(!1),H(ve)):(C(null),j(!0)),N(!1),x(!0)}catch(se){D((se==null?void 0:se.message)||String(se))}},[n,W,E,H]),X=l.useCallback(se=>{C(se),S(JSON.stringify(se,null,2)),N(!0),A("idle"),H(se)},[H]),U=l.useCallback(async(se,ne)=>{L(le=>({...le,[se]:"loading"}));try{const le=await n(W,"eval_condition_preview",{targetSessionId:E,condition:ne}),ve=le&&typeof le=="object"?le:{},ke=ve.result&&typeof ve.result=="object"?ve.result:ve;!(ke!=null&&ke.success)||!ke.result?L(De=>({...De,[se]:{result:!1,detail:ke==null?void 0:ke.error}})):L(De=>({...De,[se]:{result:ke.result.result,detail:ke.result.detail}}))}catch(le){L(ve=>({...ve,[se]:{result:!1,detail:le==null?void 0:le.message}}))}},[n,W,E]),ge=l.useCallback(async se=>{O("loading");try{const ne=await n(W,"resolve_section_preview",{targetSessionId:E,sections:se}),le=ne&&typeof ne=="object"?ne:{},ve=le.result&&typeof le.result=="object"?le.result:le;!(ve!=null&&ve.success)||!Array.isArray(ve.sections)?O({error:(ve==null?void 0:ve.error)||"resolve failed"}):O({sections:ve.sections,screenLineCount:ve.screenLineCount??0})}catch(ne){O({error:(ne==null?void 0:ne.message)||String(ne)})}},[n,W,E]),Ne=l.useCallback(async()=>{var le,ve;const se=(le=r==null?void 0:r.snapshot)==null?void 0:le.specPath;if(!se){D("No spec path on this session");return}if(!v&&P.length>0){D("Fix validation errors before saving");return}const ne=!v&&k?JSON.stringify(k,null,2):y;A("saving"),D(null);try{const ke=await n(W,"write_spec_source",{specPath:se,content:ne}),De=ke&&typeof ke=="object"?ke:{},ye=De.result&&typeof De.result=="object"?De.result:De;if(!(ye!=null&&ye.success)){A("error"),D(((ve=ye==null?void 0:ye.validationErrors)==null?void 0:ve.join(`
41
+ `);if(typeof e=="object"){const t=e;return Ir(t.text??t.content??t.value??"")}return String(e)}function od(e){return Ir(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function LN(e){return e.length===0||e.every(od)}function Fu(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t],a=typeof(n==null?void 0:n.role)=="string"?n.role:"",o=typeof(n==null?void 0:n.kind)=="string"?n.kind:"";if(!(a==="system"||o==="system")&&!(o==="tool"||o==="thought"||o==="terminal"||o==="activity")&&!od(e[t]))return a}return""}function $u(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t],a=typeof(n==null?void 0:n.role)=="string"?n.role:"",o=typeof(n==null?void 0:n.kind)=="string"?n.kind:"";if(a==="system"||o==="system"||o==="tool"||o==="thought"||o==="terminal"||o==="activity"||od(e[t]))continue;if(a!=="assistant")return"";const r=e[t];return`${String(r.bubbleId??r.providerUnitKey??r.id??"")}#${Ir(r.content).length}`}return""}function bf(e,t){if(Fu(t)!=="assistant")return!1;const n=Array.isArray(e.liveMessages)?e.liveMessages:[];return Fu(n)!=="assistant"}function bi(e){return typeof e=="string"?{selected:e}:e}function MN(e){const t=bi(e);return!!t&&t.selected==="native-history"}function RN(e,t,n){return MN(n)?bf(e,t):!1}function xf(e,t){return Math.max(Math.max(0,t),Array.isArray(e.liveMessages)?e.liveMessages.length:0)}function _N(e,t,n,a,o,r,i){const c=oc(a)||Ya(a),d=r&&e.hasLiveSnapshot;if(!c&&!d)return!1;const u=c?xf(e,t):Array.isArray(e.liveMessages)?e.liveMessages.length:0;if(u<=0)return!1;if(LN(n))return!0;if(d&&!c&&bf(e,n))return!1;const p=bi(o);if(p){const m=p.selected,h=p.fallbackReason;if(m==="native-history"||typeof h=="string"&&h!==""&&!h.startsWith("native_history_"))return!1}return i==="replica"?!1:n.length<u}function EN(e,t,n,a){if(n.length!==0||xf(e,t)<=0||e.hasLiveSnapshot&&e.liveMessages.length===0)return!1;const r=bi(a);if(!r)return!1;const i=r.selected,c=r.fallbackReason,d=r.nativeSource;return i==="native-history"?c==="native_history_transient_gap_held":d==="native-unavailable"?!0:typeof c=="string"&&c.startsWith("native_history_")}function HN(e,t,n,a,o,r,i){return _N(e,t,n,a,o,r,i)?"defer-busy-shrink":EN(e,t,n,o)?"skip-transient-empty":"apply"}function FN(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}function Bu(e,t){const n=e[t];return typeof n=="string"?n:""}function Wu(e){return e.transcriptReadSource==="replica"?"replica":"legacy"}function Ou(e,t){return e[t]===!0}function Uu(e,t){const n=e[t];return typeof n=="string"&&n.length>0?n:void 0}function $N(e,t){const{sendData:n,sendCommand:a,isConnected:o}=kt(),r=(t==null?void 0:t.enabled)!==!1,i=(t==null?void 0:t.refreshEnabled)!==!1,c=Zn(e),d=e.sessionId||"",u=ui(e),p=`daemon:${c}:session:${d}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??jo),h=e.messages.length,g=l.useMemo(()=>!r||!c||!d?null:wf({daemonId:c,sessionId:d,historySessionId:u,subscriptionKey:p,sendData:n,tailLimit:m,fallbackRecentCount:h,includeActivity:En()}),[c,r,u,n,d,p,m]);l.useEffect(()=>{g==null||g.updateOptions({fallbackRecentCount:h})},[g,h]);const[b,f]=l.useState(()=>(g==null?void 0:g.getSnapshot())||Pr(m));l.useEffect(()=>{if(!g){f(Pr(m));return}g.retain(),f(g.getSnapshot());const v=g.subscribe(j=>{f(j)});return()=>{v(),g.release()}},[g,m]);const x=l.useCallback(async()=>{!g||!c||!d||await g.loadHistoryPage(async({offset:v,excludeRecentCount:j,excludeFromIdentity:y})=>{const S=e.agentType,w=await a(c,"chat_history",{agentType:S,offset:v,limit:30,targetSessionId:d,historySessionId:u,excludeRecentCount:j,...y?{excludeFromIdentity:y}:{},...En()?{includeActivity:!0}:{}}),N=w&&typeof w=="object"&&"result"in w?w.result||{}:w||{};return{messages:Array.isArray(N.messages)?N.messages:[],hasMore:N.hasMore===!0}})},[e.agentType,g,c,u,a,d]),k=l.useCallback((v=!1)=>!g||!c||!d?Promise.resolve():g.refreshAuthoritativeTail(async()=>{const j=await a(c,"read_chat",{agentType:e.agentType,targetSessionId:d,historySessionId:u,...m>0?{tailLimit:m}:{},...En()?{includeActivity:!0}:{}}),y=j&&typeof j=="object"&&"result"in j?j.result:j;if(!y||typeof y!="object"||y.success===!1)return null;const S=Array.isArray(y.messages)?y.messages:Array.isArray(y.messagesTail)?y.messagesTail:[];return{topic:"session.chat_tail",key:p,sessionId:d,historySessionId:u,seq:0,timestamp:0,messages:S,status:typeof y.status=="string"?y.status:"idle",...y.messageSource&&typeof y.messageSource=="object"?{messageSource:y.messageSource}:{}}},{force:v}),[e.agentType,g,c,u,a,d,p,m]);l.useEffect(()=>{if(g)return Kc(v=>{g.updateOptions({includeActivity:v}),v&&k(!0)})},[g,c,d,u]),l.useEffect(()=>{if(!g||!r||!i||!c||!d)return;k(!0);const v=()=>{typeof document<"u"&&document.visibilityState==="visible"&&k()},j=w=>{w.persisted&&k()};typeof document<"u"&&document.addEventListener("visibilitychange",v),typeof window<"u"&&window.addEventListener("pageshow",j);let y=o?o(c):!0;const S=setInterval(()=>{if(!o)return;const w=o(c);w&&!y&&k(),y=w},2e3);return()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",v),typeof window<"u"&&window.removeEventListener("pageshow",j),clearInterval(S)}},[g,c,r,i,d,u]);const C=sA({hasController:!!g,enabled:r,daemonId:c,sessionId:d,refreshEnabled:i});return l.useEffect(()=>{if(!g||!C.armed)return;const v=setInterval(()=>{g.shouldRefreshForLiveness({visible:C.visible})&&k()},zN),j=()=>{typeof document>"u"||g.noteVisibilityChange(document.hidden)},y=()=>{g.noteVisibilityChange(!0)},S=()=>{g.noteVisibilityChange(!1)};return j(),typeof document<"u"&&document.addEventListener("visibilitychange",j),typeof window<"u"&&(window.addEventListener("pagehide",y),window.addEventListener("pageshow",S)),()=>{clearInterval(v),typeof document<"u"&&document.removeEventListener("visibilitychange",j),typeof window<"u"&&(window.removeEventListener("pagehide",y),window.removeEventListener("pageshow",S))}},[g,C.armed,C.visible,d,u]),l.useMemo(()=>JN(b,x),[x,b])}function BN(e,t){const{sendData:n}=kt(),a=(t==null?void 0:t.enabled)!==!1,o=Math.max(0,(t==null?void 0:t.tailLimit)??jo),r=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??xi)),i=eA(r),[c,d]=l.useState(0);l.useEffect(()=>{if(!a||e.length===0)return;const p=setInterval(()=>{d(m=>m+1)},i);return()=>{clearInterval(p)}},[e.length,a,i]);const u=l.useMemo(()=>tA(e,{recentActivityMs:r}),[e,r,c]);l.useEffect(()=>{if(!a||!n||u.descriptors.length===0)return;const p=u.descriptors.map(m=>wf({...m,sendData:n,tailLimit:o}));return p.forEach(m=>{m.retain()}),()=>{p.forEach(m=>m.release())}},[u.signature,a,n,o])}function WN(e){const[t,n]=l.useState(0),a=l.useMemo(()=>{const i=[];for(const c of e){const d=Zn(c),u=c.sessionId||"";if(!d||!u)continue;const p=ui(c);i.push(No(d,u,p||u))}return i},[e]),o=a.join("|"),r=l.useSyncExternalStore(VN,zu,zu);return l.useEffect(()=>{if(a.length===0)return;const i=[];for(const c of a){const d=mo.get(c);if(!d)continue;let u=!1;i.push(d.subscribe(()=>{if(!u){u=!0;return}n(p=>p+1)}))}return()=>{for(const c of i)c()}},[o,r]),t}function ON(e){if(!e)return"";const t=e;return t.providerUnitKey?`unit:${t.providerUnitKey}`:t.bubbleId?`bubble:${t.bubbleId}`:typeof t.sequence=="number"&&Number.isFinite(t.sequence)?`seq:${t.sequence}`:""}const UN=1e3,qN=750,zN=5e3,vf=2e4,GN=12e4,KN=6e4,Ji=vf,qu=500,xi=12e4,mo=new Map;let yf=0;const rc=new Set;function ic(){yf+=1;for(const e of rc)e()}function VN(e){return rc.add(e),()=>{rc.delete(e)}}function zu(){return yf}function No(e,t,n){return`${e}::${t}::${n||t}`}function Pr(e=jo){return{liveMessages:[],hasLiveSnapshot:!1,cursor:DN([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null,transcriptReadSource:"legacy",omittedBefore:!1,stale:!1,transcriptReplicaDegraded:!1}}class YN{constructor(t){st(this,"manager");st(this,"sendData");st(this,"daemonId");st(this,"sessionId");st(this,"historySessionId");st(this,"subscriptionKey");st(this,"fallbackRecentCount");st(this,"includeActivity");st(this,"snapshot");st(this,"transportSubscription",null);st(this,"listeners",new Set);st(this,"retainCount",0);st(this,"loadHistoryPromise",null);st(this,"pendingDisconnectTimer",null);st(this,"authoritativeRefreshPromise",null);st(this,"lastAuthoritativeRefreshAt",0);st(this,"now");st(this,"lastActiveStatusAt",0);st(this,"lastAppliedAt",0);st(this,"lastInboundAt",0);st(this,"lastKnownStatus");st(this,"lastMappedRevisionSnapshot",null);st(this,"lastMappedOmittedBefore",!1);st(this,"lastMappedStale",!1);st(this,"terminalStatusRefreshPending",!1);st(this,"lastLivenessAttemptAt",0);st(this,"replicaHealthy",!1);st(this,"everHadHealthyReplica",!1);st(this,"lastReplicaAdvanceAt",0);st(this,"lastReplicaRevision",0);st(this,"lastReplicaBusyAt",0);st(this,"hiddenSinceAt",0);st(this,"hiddenElapsedMs",0);this.manager=t.manager||Ns,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount??0),this.includeActivity=t.includeActivity===!0,this.now=t.now??(()=>Date.now()),this.snapshot=Pr(Math.max(0,t.tailLimit??jo))}updateOptions(t){const n=this.sendData,a=this.daemonId,o=this.sessionId;if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.now&&(this.now=t.now),t.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount)),t.tailLimit!==void 0){const r=Math.max(0,t.tailLimit);r!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect()))}t.includeActivity!==void 0&&t.includeActivity!==this.includeActivity&&(this.includeActivity=t.includeActivity,this.transportSubscription&&(this.disconnect(),this.connect())),this.retainCount>0&&(n!==this.sendData||a!==this.daemonId||o!==this.sessionId)&&(this.disconnect(),this.connect())}getSnapshot(){return this.snapshot}clearLiveSnapshot(){this.snapshot={...Pr(this.snapshot.cursor.tailLimit),hasLiveSnapshot:!0},this.lastMappedRevisionSnapshot=null,this.emit()}reportTranscriptReplicaFallback(t){const n=this.replicaHealthy;this.replicaHealthy=!1,(n||!this.transportSubscription)&&this.syncLegacySubscription();const a=this.everHadHealthyReplica;this.snapshot.transcriptReadSource==="legacy"&&this.snapshot.transcriptFallbackReason===t&&this.snapshot.transcriptReplicaDegraded===a||(this.snapshot={...this.snapshot,transcriptReadSource:"legacy",transcriptFallbackReason:t,transcriptReplicaDegraded:a},this.emit())}applyTranscriptReplicaSnapshot(t,n){if(!AN(t)){this.reportTranscriptReplicaFallback("revision_invalid");return}const a=this.lastMappedRevisionSnapshot===t&&this.lastMappedOmittedBefore===n.omittedBefore&&this.lastMappedStale===(n.stale===!0);let o;if(a){const c=this.now();this.lastInboundAt=c,this.lastKnownStatus=t.status,(oc(t.status)||Ya(t.status))&&(this.lastActiveStatusAt=c),o="noop"}else o=this.handleUpdate(n.mapped??TN(t,{subscriptionKey:this.subscriptionKey,omittedBefore:n.omittedBefore,stale:n.stale===!0})),o==="noop"?(this.lastMappedRevisionSnapshot=t,this.lastMappedOmittedBefore=n.omittedBefore,this.lastMappedStale=n.stale===!0):this.lastMappedRevisionSnapshot=null;const r=typeof t.revision=="number"?t.revision:0;r>this.lastReplicaRevision&&(this.lastReplicaRevision=r,this.lastReplicaAdvanceAt=this.now(),this.hiddenElapsedMs=0),Ya(t.status)&&(this.lastReplicaBusyAt=this.now()),!this.replicaHealthy&&o==="applied"&&(this.replicaHealthy=!0,this.everHadHealthyReplica=!0,this.lastReplicaAdvanceAt===0&&(this.lastReplicaAdvanceAt=this.now()),this.syncLegacySubscription()),this.snapshot.transcriptReplicaDegraded&&(this.snapshot={...this.snapshot,transcriptReplicaDegraded:!1},this.emit())}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect(),this.retainCount===1&&ic()}isRetained(){return this.retainCount>0}getIdentity(){return{daemonId:this.daemonId,sessionId:this.sessionId}}release(){const t=this.retainCount>0;this.retainCount=Math.max(0,this.retainCount-1),t&&this.retainCount===0&&ic(),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const n=(async()=>{try{const a=this.snapshot.hasLiveSnapshot,o=a?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),r=await t({offset:this.snapshot.historyOffset,excludeRecentCount:o,excludeFromIdentity:ON(this.snapshot.liveMessages[0])}),i=Array.isArray(r.messages)?r.messages:[],c=!a&&i.length===0&&r.hasMore!==!0&&this.fallbackRecentCount>0,d=[...i,...this.snapshot.historyMessages],u=d.length>qu?d.slice(d.length-qu):d;this.snapshot={...this.snapshot,historyMessages:u,historyOffset:this.snapshot.historyOffset+i.length,hasMoreHistory:c?!0:r.hasMore===!0,historyError:null}}catch(a){this.snapshot={...this.snapshot,historyError:a instanceof Error?a.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=n,n}expireStaleReplicaLease(){if(!this.replicaHealthy||this.lastReplicaBusyAt===0)return;const t=this.now(),n=this.hiddenElapsedMs+(this.hiddenSinceAt>0?Math.max(0,t-this.hiddenSinceAt):0);if(t-this.lastReplicaBusyAt-n>Ji)return;const a=t-this.lastReplicaAdvanceAt-n>=Ji,o=this.lastAppliedAt>0&&t-this.lastAppliedAt-n>=Ji;!a&&!o||this.reportTranscriptReplicaFallback(a?"replica_lease_expired":"replica_screen_stalled")}noteTerminalStatusEvent(t){PN(t)&&(this.terminalStatusRefreshPending=!0)}noteVisibilityChange(t){const n=this.now();if(t){this.hiddenSinceAt===0&&(this.hiddenSinceAt=n);return}this.hiddenSinceAt!==0&&(this.hiddenElapsedMs+=Math.max(0,n-this.hiddenSinceAt),this.hiddenSinceAt=0)}shouldRefreshForLiveness(t={}){if(this.expireStaleReplicaLease(),this.lastInboundAt===0||this.authoritativeRefreshPromise)return!1;if(this.terminalStatusRefreshPending)return this.terminalStatusRefreshPending=!1,!0;if(this.replicaHealthy)return!1;const n=Math.max(this.lastAppliedAt,this.lastLivenessAttemptAt),a=this.now()-n,o=Ya(this.lastKnownStatus)?vf:GN,r=t.visible===!0?o:Math.max(o,KN);return a>=r}getLivenessStateForTest(){return{lastInboundAt:this.lastInboundAt,lastAppliedAt:this.lastAppliedAt,lastKnownStatus:this.lastKnownStatus}}refreshAuthoritativeTail(t,n={}){if(this.authoritativeRefreshPromise)return this.authoritativeRefreshPromise;const a=this.now();if(!n.force&&this.lastAuthoritativeRefreshAt>0&&a-this.lastAuthoritativeRefreshAt<qN)return Promise.resolve();this.lastAuthoritativeRefreshAt=a;const o=(async()=>{try{const r=await t();r&&this.handleUpdate(r),this.lastInboundAt=this.now(),this.lastLivenessAttemptAt=this.now()}catch{this.lastInboundAt=this.now(),this.lastLivenessAttemptAt=this.now()}})().finally(()=>{this.authoritativeRefreshPromise=null});return this.authoritativeRefreshPromise=o,o}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{},...this.includeActivity?{includeActivity:!0}:{}}}}shouldRunLegacySubscription(){return!this.replicaHealthy}syncLegacySubscription(){this.retainCount<=0||(this.shouldRunLegacySubscription()?this.connect():this.disconnect())}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||this.shouldRunLegacySubscription()&&(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),t=>{this.handleUpdate(t)},{retryIntervalMs:UN}))}disconnect(){var t;(t=this.transportSubscription)==null||t.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null,this.replicaHealthy=!1,this.everHadHealthyReplica=!1,this.lastReplicaAdvanceAt=0,this.lastReplicaRevision=0,this.lastReplicaBusyAt=0,this.hiddenSinceAt=0,this.hiddenElapsedMs=0,this.lastMappedRevisionSnapshot=null}emit(){this.listeners.forEach(t=>t(this.snapshot))}handleUpdate(t){if(t.error)return"rejected";const n=Bu(t,"sessionId");if(n&&n!==this.sessionId)return"rejected";const a=Bu(t,"historySessionId");if(a&&this.historySessionId&&a!==this.historySessionId)return"rejected";const o=FN(t),r=t.messageSource,i=this.now();this.lastInboundAt=i,this.lastKnownStatus=t.status;const c=this.lastActiveStatusAt>0&&i-this.lastActiveStatusAt<=xi;(oc(t.status)||Ya(t.status))&&(this.lastActiveStatusAt=i);const d=RN(this.snapshot,o,r);if(!d&&HN(this.snapshot,this.fallbackRecentCount,o,t.status,r,c,Wu(t))!=="apply")return"deferred";const u={tailLimit:this.snapshot.cursor.tailLimit};return!d&&Hu(this.snapshot.liveMessages)===Hu(o)&&$u(this.snapshot.liveMessages)===$u(o)&&this.snapshot.cursor.tailLimit===u.tailLimit?"noop":(this.lastAppliedAt=i,this.hiddenElapsedMs=0,this.snapshot={...this.snapshot,liveMessages:o,hasLiveSnapshot:!0,cursor:u,messageSource:bi(r),transcriptReadSource:Wu(t),omittedBefore:Ou(t,"omittedBefore"),stale:Ou(t,"stale"),...Uu(t,"transcriptFallbackReason")!==void 0?{transcriptFallbackReason:Uu(t,"transcriptFallbackReason")}:{}},this.emit(),"applied")}}function wf(e){const t=No(e.daemonId,e.sessionId,e.historySessionId),n=mo.get(t);if(n)return n.updateOptions(e),n;const a=new YN(e);return mo.set(t,a),ic(),a}function QN(e,t,n){if(!e||!t)return;const a=`${e}::${t}::`,o=No(e,t,n);for(const[r,i]of mo.entries())(r===o||r.startsWith(a))&&i.clearLiveSnapshot()}function kf(e){const t=Zn(e),n=e.sessionId||"";if(!t||!n)return;const a=ui(e),o=No(t,n,a||n),r=mo.get(o);if(!r)return;const i=r.getSnapshot();return i.hasLiveSnapshot?i:void 0}function JN(e,t){return{...e,loadHistoryPage:t}}function XN(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||(e.historySessionId||"").localeCompare(t.historySessionId||"")}function ZN(e,t={}){const n=String(e.status||"").trim().toLowerCase();if(gf.has(n)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const a=t.now??Date.now(),o=Math.max(0,Number(t.recentActivityMs??xi)),r=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return r>0?a-r<=o:Array.isArray(e.messages)&&e.messages.length>0}function eA(e=xi){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function tA(e,t={}){const n=new Set,a=[];for(const o of e){if(!ZN(o,t))continue;const r=Zn(o),i=o.sessionId||"";if(!r||!i)continue;const c=ui(o),d=No(r,i,c||i);n.has(d)||(n.add(d),a.push({daemonId:r,sessionId:i,historySessionId:c,subscriptionKey:`daemon:${r}:session:${i}`}))}return a.sort(XN),{descriptors:a,signature:a.map(o=>`${o.subscriptionKey}|${o.historySessionId}`).join("||")}}function sA(e){return{armed:!!(e.hasController&&e.enabled&&e.daemonId&&e.sessionId),visible:e.refreshEnabled}}function nA(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function aA(e){return nA(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const mr=new Map,lc=new Set;function Gu(e,t){!e||mr.get(e)===t||(t?mr.set(e,!0):mr.delete(e),lc.forEach(a=>a(e,t)))}function oA(e){return e?mr.get(e)===!0:!1}function rA(e){return lc.add(e),()=>{lc.delete(e)}}function iA(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function lA(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function cA(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Sf(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function Cf(e){const t=typeof e.completionMarker=="string"?e.completionMarker.trim():"";return t||(e.lastMessageHash?e.lastMessageHash:e.lastMessageAt?String(e.lastMessageAt):e.lastUpdated?String(e.lastUpdated):"")}function dA(e){return Sf(e)?!1:e.inboxBucket==="task_complete"&&Cf(e).length>0}function Ku(e){return e.branch||"detached HEAD"}function uA(e){if(e.error)return`${Ku(e)} · Git error: ${e.error}`;const t=[Ku(e)];return e.changedFiles>0?t.push(iA(e.changedFiles,"file")+" changed"):e.dirty||t.push("clean"),e.ahead>0&&t.push(`ahead ${e.ahead}`),e.behind>0&&t.push(`behind ${e.behind}`),e.hasConflicts&&t.push("conflicts"),t.join(" · ")}function pA(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${uA(t)}`}function mA(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function hA(e,t={}){if(t.enabled===!1)return[];if(!cA(e))return[];const n=Sf(e)?"working":dA(e)?"complete":null;if(!n)return[];const a=n==="complete"?Cf(e):"";return[{id:n==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${lA(a)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:pA(n,e.git),timestamp:mA(e,e.git),meta:{source:"git-system-bubble",phase:n,workspace:e.workspacePath,repoRoot:e.git.repoRoot,branch:e.git.branch,changedFiles:e.git.changedFiles,hasConflicts:e.git.hasConflicts}}]}const fA=60,gA=3e4;function bA(e){return{enabled:!!e.sessionId,refreshEnabled:e.isVisible,tailLimit:e.tailLimit}}function xA(e,t){return e.status==="no_progress"||e.status==="long_generating"?t("chatPane.busyNoProgress"):e.status==="generating"||e.status==="streaming"?t("chatPane.busyGenerating"):e.status==="waiting_approval"&&(!e.modalButtons||e.modalButtons.length===0)?t("chatPane.busyWaitingApproval"):null}function jf({activeConv:e,ideEntry:t,handleSendChat:n,handleSendNowQueued:a,handleCancelQueued:o,isSendingChat:r=!1,sendFeedbackMessage:i=null,pendingLocalMessage:c=null,pendingLocalMessages:d=null,retireEchoedPendingMessages:u,handleFocusAgent:p,isFocusingAgent:m,actionLogs:h,userName:g,scrollToBottomRequestNonce:b,isInputActive:f=!0,isVisible:x=!0}){var ee,q,ce,Q,oe,K,B,we;const{t:k}=je("common"),C=l.useRef(new Map),v=l.useRef(void 0),j=Na(),{sendCommand:y}=kt(),{isVisible:S}=Yc();Co("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:h.length,isSendingChat:r});const w=Pt.useMemo(()=>Xn(e),[e.status,e.connectionState]);Pt.useEffect(()=>{const fe=e.sessionId;if(fe)return Gu(fe,w.isGenerating),()=>{Gu(fe,!1)}},[e.sessionId,w.isGenerating]);const N=l.useMemo(()=>Kj(e,t),[e,t]),T=l.useMemo(()=>{var fe;return Zc((fe=N.targetEntry)==null?void 0:fe.providerControls,{hostIdeType:e.hostIdeType,providerType:N.providerType})},[e.hostIdeType,N.providerType,(ee=N.targetEntry)==null?void 0:ee.providerControls]),A=hf({isCliLike:N.isCli||N.isAcp}),M=kN({isCliLike:N.isCli||N.isAcp}),D=$N(e,bA({sessionId:e.sessionId,isVisible:x,tailLimit:M})),[P,I]=l.useState(()=>Eu(e.tabKey,A)),[_,L]=l.useState(()=>En()),R=e.tabKey,O=D.historyMessages,J=D.hasMoreHistory,G=D.historyError,W=Zh(e,D),E=Rj(W,d??(c?[c]:null),void 0,{excludeQueued:!0}),F=((d==null?void 0:d.length)??0)>0;l.useEffect(()=>{if(!u||(u(W),!F))return;const fe=setInterval(()=>u(W),gA);return()=>clearInterval(fe)},[u,W,F]);const H=l.useMemo(()=>Ev(E).length,[E]);l.useEffect(()=>{I(Eu(R,A))},[A,R]);const $=Math.max(0,E.length-P),X=sd(e),U=Zn(e),ge=aA(e),Ne=nd(e),Y=xA(e,k),ie=i||null,me=(Ne?lf:null)||i||Y,he=!!Ne,[re,pe]=l.useState(!1);l.useEffect(()=>{const fe=N.targetEntry;U&&(!fe||fe.providerControls===void 0||fe.controlValues===void 0)&&j(U,{minFreshMs:3e4}).catch(()=>{})},[U,N.isAcp,(q=N.targetEntry)==null?void 0:q.providerControls,(ce=N.targetEntry)==null?void 0:ce.controlValues,j]);const Z=l.useCallback(async()=>{if(!re){if(E.length>P){I(fe=>{const Pe=Math.min(E.length,fe+fA);return SN(R,Pe),Pe});return}pe(!0);try{await D.loadHistoryPage()}finally{pe(!1)}}},[D,re,E.length,R,P]),{allMessages:ue,receivedAtMap:se}=l.useMemo(()=>{const fe=$j({historyMessages:O,liveMessages:E,visibleLiveCount:P}),Pe=hA(e),Fe=Pe.length>0?[...fe,...Pe]:fe,He={};return Fe.forEach((We,be)=>{const Se=oi(We),Be=`${e.tabKey}:${Se}`;let Ze=pr(We)||C.current.get(Be)||0;Ze||(Ze=Date.now(),C.current.set(Be,Ze)),He[Se]=Ze}),{allMessages:Fe,receivedAtMap:He}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,$,O,E,P]),ne=l.useMemo(()=>h.filter(fe=>fe.routeId===e.tabKey).sort((fe,Pe)=>fe.timestamp-Pe.timestamp),[h,e.tabKey]),[le,ve]=l.useState({});l.useEffect(()=>{ve({})},[e.tabKey]);const ke=l.useCallback(async(fe,Pe)=>{if(U){ve(Fe=>({...Fe,[fe]:{status:"loading"}}));try{const Fe=await y(U,"expand_tool_block",{targetSessionId:e.sessionId,agentType:N.providerType||e.agentType,toolBlockRef:Pe}),He=Mn(Fe),We=He!=null&&He.success?He.callArgs!==void 0?`${He.toolName?`${He.toolName}: `:""}${He.callArgs}`:He.result:void 0;ve(be=>({...be,[fe]:We!==void 0?{status:"expanded",text:We}:{status:"error"}}))}catch{ve(Fe=>({...Fe,[fe]:{status:"error"}}))}}},[e.agentType,e.sessionId,N.providerType,U,y]),De=l.useCallback(fe=>{ve(Pe=>{if(!Pe[fe])return Pe;const Fe={...Pe};return delete Fe[fe],Fe})},[]),ye=l.useCallback(async()=>{var be,Se;if(!U)return;const fe=df({activeConv:e,visibleMessages:ue,actionLogs:h,controls:(be=N.targetEntry)==null?void 0:be.providerControls,controlValues:(Se=N.targetEntry)==null?void 0:Se.controlValues,visibleBarControlCount:T.length,chatTailState:{liveMessages:D.liveMessages,hasLiveSnapshot:D.hasLiveSnapshot,hasMoreHistory:J,historyError:G,historyMessages:O},ui:{controlsVisible:S,visibleLiveCount:P,activityVisible:_,activityCount:H,hiddenLiveCount:$,isInputActive:f,isVisible:x}}),Pe=await y(U,"get_chat_debug_bundle",{agentType:N.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:fe}),Fe=Mn(Pe),He=mf(Fe),We=await pf(He);We==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),ft.showToast(uf(Fe,{locatorCopyStatus:We}),We==="failed"?"warning":"success")},[e,h,H,ue,S,D.hasLiveSnapshot,D.liveMessages,N.providerType,(Q=N.targetEntry)==null?void 0:Q.controlValues,(oe=N.targetEntry)==null?void 0:oe.providerControls,U,J,$,O,f,x,G,y,_,T.length,P]);l.useEffect(()=>Kc(L),[]);const V=l.useCallback(()=>{L(fe=>{const Pe=!fe;return mh(Pe),Pe})},[]),te=l.useCallback(()=>{const fe=oN(v.current);v.current=fe.state,fe.shouldCollect&&ye().catch(Pe=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",Pe),ft.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[ye]),Ce=l.useMemo(()=>{if(E.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-xxs text-blue-400 font-medium",children:[k("chatPane.connectingToMachine"),s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-2xs opacity-35",children:k("chatPane.establishingP2P")})]})]});if((w.isGenerating||e.status==="streaming")&&pe(!1),e.status==="not_monitored"&&ge)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(ro,{size:28})}),s.jsx("div",{className:"text-xxs opacity-50",children:k("chatPane.agentNotMonitored")}),s.jsx("button",{onClick:p,disabled:m,className:"btn btn-primary",children:m?s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(an,{size:12}),k("chatPane.switchingPanel")]}):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Un,{size:14})," ",k("chatPane.openPanel",{label:X})]})}),s.jsx("div",{className:"text-2xs opacity-35 max-w-[280px]",children:k("chatPane.clickToSwitchMonitoring")})]});if(e.status==="panel_hidden"&&ge)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Uc,{size:28})}),s.jsx("div",{className:"text-xxs opacity-50",children:k("chatPane.agentPanelHidden")}),s.jsx("button",{onClick:p,disabled:m,className:"btn btn-primary",children:m?s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(an,{size:12}),k("chatPane.openingPanel")]}):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Un,{size:14})," ",k("chatPane.openPanel",{label:X})]})}),s.jsx("div",{className:"text-2xs opacity-35 max-w-[280px]",children:k("chatPane.openPanelHint")})]});if(e.status==="idle"&&!re)return!J&&O.length===0?s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"opacity-40",children:s.jsx(Gs,{size:26})}),s.jsx("div",{className:"text-xxs opacity-40",children:k("chatPane.noMessagesYet")})]}):s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"opacity-40 animate-pulse",children:s.jsx(Gs,{size:26})}),s.jsx("div",{className:"text-xxs opacity-40",children:k("chatPane.loadingChat")})]})}},[e.connectionState,e.status,ge,p,J,O.length,m,re,E.length,X,w.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col relative",...CN(D),children:[s.jsxs("div",{className:"chat-activity-toggle-bar",children:[s.jsxs("button",{type:"button",className:`chat-activity-toggle ${_?"chat-activity-toggle-active":""}`,onClick:V,"aria-pressed":_,title:k("chatPane.activityToggleTitle"),children:[s.jsx("span",{className:"chat-activity-toggle-dot"}),k("chatPane.activityToggleLabel"),H>0&&s.jsx("span",{className:"chat-activity-toggle-count",children:H})]}),s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx(Cj,{sessionId:e.sessionId,daemonId:e.daemonId,muted:!!((K=N.targetEntry)!=null&&K.muted),sendDaemonCommand:y}),s.jsx(kj,{sessionId:e.sessionId,daemonId:e.daemonId,conv:e})]})]}),D.transcriptReplicaDegraded&&s.jsx("div",{className:"px-3 py-1.5 text-2xs text-amber-400/90 bg-amber-500/10 border-b border-amber-500/20",role:"status","data-testid":"transcript-replica-degraded-notice",children:k("chatPane.replicaDegraded")}),s.jsx(Xv,{messages:ue,actionLogs:ne,agentName:wa(e)||X||"Agent",userName:g,isCliMode:N.isCli||N.isAcp,isWorking:w.isGenerating,contextKey:e.tabKey,receivedAtMap:se,lastMessageHash:e.lastMessageHash,showActivityMessages:_,onLoadMore:Z,isLoadingMore:re,hasMoreHistory:J,hiddenLiveCount:$,loadError:G??void 0,emptyState:Ce,scrollToBottomRequestNonce:b,isVisible:x,onSendNow:a,isSendingNow:r,onCancelQueued:o,toolExpansions:le,onExpandToolBlock:ke,onCollapseToolBlock:De}),s.jsx(BC,{entries:d??(c?[c]:[]),onSendNow:a,onCancelQueued:o,isSendingNow:r}),s.jsx(RC,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:N.providerType,displayLabel:N.displayLabel,controls:(B=N.targetEntry)==null?void 0:B.providerControls,controlValues:(we=N.targetEntry)==null?void 0:we.controlValues,currentStatus:e.status,coordinatorHint:fi(e),isActive:f,isCliTerminal:N.isCliTerminal}),!N.isCliTerminal&&s.jsx(Oh,{contextKey:e.tabKey,panelLabel:X,isSending:r,isBusy:he,statusMessage:me,inlineStatusMessage:ie,onSend:n,isActive:f,showControlsToggle:T.length>0,onControlsToggle:te,messageInput:e.messageInput})]})}let Nf=zs;function Af(){return Nf()}class vA{constructor(){st(this,"listeners",new Map)}send(t,n){return!1}isConnected(){return!1}on(t,n){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(n),()=>{var a;(a=this.listeners.get(t))==null||a.delete(n)}}emit(t,...n){var a;(a=this.listeners.get(t))==null||a.forEach(o=>o(...n))}}let Tf=new vA;class yA{sendPtyInput(t,n,a){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,n){return!1}get(t){}onScreenshot(t,n){return()=>{}}onRuntimeEvent(t,n,a){return()=>{}}requestRuntimeSnapshot(t,n,a){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let Et=new yA;function wA(e){e.dashboardWS&&(Tf=e.dashboardWS),e.connectionManager&&(Et=e.connectionManager),e.useDaemonsHook&&(Nf=e.useDaemonsHook)}const kA=.5,SA=1.25,Is="\x1B",Vu={ArrowUp:"A",ArrowDown:"B",ArrowLeft:"D",ArrowRight:"C"};function CA(e){return 1+(e.shift?1:0)+(e.alt?2:0)+(e.ctrl?4:0)}function Yu(e,t){let n=e;if(t.shift&&n.length===1&&(n=n.toUpperCase()),t.ctrl){const a=n.toUpperCase().charCodeAt(0);return String.fromCharCode(a&31)}return n}function jA(e,t){if(t in Vu){const a=Vu[t],o=CA(e);return o===1?`${Is}[${a}`:`${Is}[1;${o}${a}`}switch(t){case"Enter":return e.alt?`${Is}\r`:"\r";case"Escape":return e.alt?`${Is}${Is}`:Is;case"Backspace":{const a=e.ctrl?"\b":"";return e.alt?`${Is}${a}`:a}case"Tab":{const a=e.shift?`${Is}[Z`:" ";return e.alt&&!e.shift?`${Is} `:a}case"Space":{const a=Yu(" ",e);return e.alt?`${Is}${a}`:a}}const n=Yu(t,e);return e.alt?`${Is}${n}`:n}function At(e){return sd(e)}function ka(e){return of(e).join(" · ")}function If(e){var t,n;return!!e.daemonId&&!!((t=e.coordinator)!=null&&t.meshId||typeof((n=e.settings)==null?void 0:n.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0)}function NA(e){var o,r,i;const t=[],n=typeof((o=e.settings)==null?void 0:o.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0,a=!!((r=e.coordinator)!=null&&r.meshId)||typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0;return n&&t.push("Mesh node"),a&&t.push("Coordinator"),t}function AA(e){var i,c,d;const t=[],n=typeof((i=e.settings)==null?void 0:i.meshNodeFor)=="string"?e.settings.meshNodeFor.trim():"",a=typeof((c=e.coordinator)==null?void 0:c.meshId)=="string"?e.coordinator.meshId.trim():"",o=typeof((d=e.settings)==null?void 0:d.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor.trim():"",r=a||o;if(n&&t.push(`Mesh node: ${n}`),r&&t.push(`Coordinator: ${r}`),e.meshQueueStats){const{pending:u,assigned:p,completed:m,failed:h}=e.meshQueueStats;t.push(`Queue: ${u} pending, ${p} assigned, ${m} completed, ${h} failed`)}return t.join(" · ")}function Pf(e,t){const n=af(e,t);return n||(e.title?e.title:ka(e)||"No messages yet")}function Df(e,t){const{isReconnecting:n,isConnecting:a,isErrored:o}=Xn(e);return n?"Reconnecting…":a?"Connecting…":t!=null&&t.requiresAction?"Action needed":o?"Needs attention":null}function TA(e,t){const n=["Chat",...of(e)];return t!=null&&t.timestampLabel&&n.push(t.timestampLabel),n.filter(Boolean).join(" · ")}function Hn(e){return Df(e)||ka(e)}function IA(e,t){return`${At(e)} · ${Pf(e,t)}`}function PA(e){const t=Ar(e),n=t?ts(t):wa(e);return`${At(e)} — ${n||"Agent"}`}function DA(e){return wa(e)||"CLI"}function Lf(e){return nf(e)}function Mf(e){return e?`Remote · ${At(e)||e.workspaceName||"Session"}`:"Remote"}const Qu=[{kind:"regex",label:"section matches",hint:"regex against a screen section",make:e=>({section:e[0],matches:""})},{kind:"elapsed",label:"elapsed_ms",hint:"N ms since state entered",make:()=>({elapsed_ms:1e3})},{kind:"stable",label:"stable_ms",hint:"region unchanged for N ms",make:()=>({stable_ms:1e3,cursor_above:5})},{kind:"changed",label:"changed",hint:"region changed vs prev frame",make:()=>({cursor_above:3,changed:!0})},{kind:"all",label:"all (AND)",hint:"every child must match",make:()=>({all:[]})},{kind:"any",label:"any (OR)",hint:"some child must match",make:()=>({any:[]})},{kind:"not",label:"not",hint:"invert a condition",make:()=>({not:{matches:""}})}],LA=[{label:"active spinner (busy)",cond:{section:"body",matches:"(?:^|\\n)\\s*[·✢✳✶✽✷✸✹]\\s+\\w.*?(?:…|\\.\\.\\.)"}},{label:"completion marker (done)",cond:{section:"body",matches:"✻\\s+\\w+ed\\s+for\\s+(?:\\d+h\\s+)?(?:\\d+m\\s+)?\\d+s"}},{label:"approval prompt (❯ 1.)",cond:{section:"footer",matches:"(?:^|\\n)\\s*[❯›>]\\s*1\\.\\s*.+"}},{label:"picker (Select a …)",cond:{section:"modal",matches:"Select (?:a |an )?(?:model|mode|option)\\b"}},{label:"stable 1.2s (settled)",cond:{stable_ms:1200,cursor_above:5}}];function MA(e){return"all"in e?"all":"any"in e?"any":"not"in e?"not":"elapsed_ms"in e?"elapsed":"stable_ms"in e&&!("changed"in e)?"stable":"changed"in e?"changed":"regex"}function rd({cond:e,path:t,sections:n,onChange:a,onRemove:o,onPreview:r,preview:i}){const c=MA(e),d=i[t],u=p=>{const m=Qu.find(h=>h.kind===p);m&&a(m.make(n))};return s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-1.5 space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("select",{value:c,onChange:p=>u(p.target.value),className:"bg-bg-secondary text-text-primary text-3xs font-mono rounded border border-border-default px-1 py-0.5",children:Qu.map(p=>s.jsx("option",{value:p.kind,children:p.label},p.kind))}),(c==="regex"||c==="stable"||c==="changed"||c==="elapsed")&&s.jsx("button",{type:"button",className:"text-3xs text-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:()=>r(t,e),children:"test"}),d&&d!=="loading"&&s.jsx("span",{className:`text-3xs font-mono px-1.5 py-0.5 rounded ${d.result?"text-status-online bg-status-online/20":"text-text-secondary bg-bg-glass"}`,children:d.result?"match ✓":"no match"}),d==="loading"&&s.jsx("span",{className:"text-3xs text-text-muted",children:"testing…"}),o&&s.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-xs px-1",onClick:o,children:"×"})]}),c==="regex"&&s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs("select",{value:e.section??"",onChange:p=>a({...e,section:p.target.value||void 0}),className:"bg-bg-secondary text-accent-primary text-3xs font-mono rounded border border-border-default px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(whole screen)"}),n.map(p=>s.jsx("option",{value:p,children:p},p))]}),s.jsx("input",{value:e.matches??"",onChange:p=>a({...e,matches:p.target.value}),placeholder:"regex",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-primary text-3xs font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),c==="elapsed"&&s.jsx(hn,{label:"elapsed_ms",value:e.elapsed_ms,onChange:p=>a({elapsed_ms:p})}),c==="stable"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(hn,{label:"stable_ms",value:e.stable_ms,onChange:p=>a({...e,stable_ms:p})}),s.jsx(hn,{label:"cursor_above",value:e.cursor_above??0,onChange:p=>a({...e,cursor_above:p||void 0})})]}),c==="changed"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(hn,{label:"cursor_above",value:e.cursor_above,onChange:p=>a({...e,cursor_above:p})}),s.jsxs("label",{className:"flex items-center gap-1 text-3xs text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:!!e.changed,onChange:p=>a({...e,changed:p.target.checked}),className:"accent-[var(--accent-primary)]"}),"changed"]})]}),(c==="all"||c==="any")&&s.jsx(RA,{kind:c,cond:e,path:t,sections:n,onChange:a,onPreview:r,preview:i}),c==="not"&&s.jsx("div",{className:"pl-2 border-l border-border-default",children:s.jsx(rd,{cond:e.not,path:`${t}.not`,sections:n,onChange:p=>a({not:p}),onPreview:r,preview:i})})]})}function RA({kind:e,cond:t,path:n,sections:a,onChange:o,onPreview:r,preview:i}){const c=(e==="all"?t.all:t.any)??[],d=u=>o(e==="all"?{all:u}:{any:u});return s.jsxs("div",{className:"pl-2 border-l border-border-default space-y-1",children:[c.map((u,p)=>s.jsx(rd,{cond:u,path:`${n}.${e}[${p}]`,sections:a,onChange:m=>d(c.map((h,g)=>g===p?m:h)),onRemove:()=>d(c.filter((m,h)=>h!==p)),onPreview:r,preview:i},p)),s.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[s.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d([...c,{section:a[0],matches:""}]),children:"+ condition"}),LA.map(u=>s.jsxs("button",{type:"button",className:"text-3xs text-accent-primary/80 hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:()=>d([...c,JSON.parse(JSON.stringify(u.cond))]),title:"insert verified pattern",children:["+ ",u.label]},u.label))]})]})}function hn({label:e,value:t,onChange:n}){return s.jsxs("label",{className:"flex items-center gap-1 text-3xs text-text-secondary font-mono",children:[e,s.jsx("input",{type:"number",value:Number.isFinite(t)?t:0,onChange:a=>n(Number(a.target.value)),className:"w-20 bg-bg-secondary text-text-primary rounded border border-border-default px-1 py-0.5 outline-none focus:border-accent"})]})}function _A({sections:e,otherSectionIds:t,onChange:n,onTest:a,testResult:o}){const r=Object.keys(e),i=o&&o!=="loading"&&!("error"in o)?Object.fromEntries(o.sections.map(m=>[m.id,m])):{},c=(m,h)=>{if(!h||h===m||e[h])return;const g={};for(const[b,f]of Object.entries(e))g[b===m?h:b]=f;n(g)},d=(m,h)=>n({...e,[m]:h}),u=m=>{const h={...e};delete h[m],n(h)},p=()=>{let m="section",h=1;for(;e[m];)m=`section${h++}`;n({...e,[m]:{from_top:0}})};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold",children:"Sections"}),s.jsx("span",{className:"text-text-muted text-3xs",children:"— how the screen is split; conditions match against these"}),s.jsx("button",{type:"button",className:"ml-auto text-3xs text-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:a,title:"Resolve all sections against the live session screen",children:o==="loading"?"testing…":"test on live screen"}),s.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:p,children:"+ section"})]}),o&&o!=="loading"&&"error"in o&&s.jsx("div",{className:"text-status-error bg-status-error/15 border border-status-error/40 rounded p-1.5 text-3xs mb-1",children:o.error}),s.jsx("div",{className:"space-y-1.5",children:r.map(m=>{var f;const h=e[m],g=h.anchor!=null?"anchor":"positional",b=x=>{x==="anchor"?d(m,{anchor:h.anchor??"^",anchor_last:h.anchor_last,until:h.until}):d(m,{from_top:h.from_top??0,until:h.until})};return s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{value:m,onChange:x=>c(m,x.target.value.trim()),className:"w-28 bg-bg-secondary text-accent-primary font-mono text-2xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsxs("div",{className:"inline-flex rounded border border-border-default overflow-hidden text-3xs",children:[s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${g==="positional"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>b("positional"),children:"positional"}),s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${g==="anchor"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>b("anchor"),children:"anchor"})]}),s.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-sm px-1",onClick:()=>u(m),children:"×"})]}),g==="positional"?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx(hn,{label:"from_top",value:typeof h.from_top=="number"?h.from_top:0,onChange:x=>d(m,{...h,from_top:x,from_bottom:void 0})}),s.jsx(hn,{label:"from_bottom",value:typeof h.from_bottom=="number"?h.from_bottom:0,onChange:x=>d(m,{...h,from_bottom:x||void 0})}),s.jsx(Ju,{def:h,otherIds:t(m),onChange:x=>d(m,x)})]}):s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-3xs text-text-muted w-16",children:"anchor"}),s.jsx("input",{value:h.anchor??"",onChange:x=>d(m,{...h,anchor:x.target.value}),placeholder:"^regex locating section start",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-primary text-3xs font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsxs("label",{className:"flex items-center gap-1 text-3xs text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:!!h.anchor_last,onChange:x=>d(m,{...h,anchor_last:x.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"last"]})]}),s.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s.jsx(Ju,{def:h,otherIds:t(m),onChange:x=>d(m,x)})}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-3xs text-text-muted w-16",children:"ctx next"}),s.jsx("input",{value:((f=h.anchor_context)==null?void 0:f.next)??"",onChange:x=>d(m,{...h,anchor_context:{...h.anchor_context,next:x.target.value||void 0}}),placeholder:"optional: line after anchor must match",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-secondary text-3xs font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]})]}),i[m]&&s.jsxs("div",{className:"border-t border-border-subtle pt-1",children:[s.jsxs("div",{className:"text-4xs text-text-muted mb-0.5",children:["captured lines ",i[m].fromLine,"–",i[m].toLine,i[m].text.trim()===""&&s.jsx("span",{className:"text-amber-400 ml-1",children:"(empty — check bounds)"})]}),s.jsx("pre",{className:"font-mono text-3xs text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary rounded border border-border-subtle px-2 py-1 max-h-28 overflow-y-auto",children:i[m].text||"(empty)"})]})]},m)})})]})}function Ju({def:e,otherIds:t,onChange:n}){const a=e.until??"",o=a.startsWith("^");return s.jsxs("label",{className:"flex items-center gap-1 text-3xs text-text-secondary",children:["until",s.jsxs("select",{value:o?"__regex__":a,onChange:r=>{const i=r.target.value;n(i===""?{...e,until:void 0}:i==="__regex__"?{...e,until:a.startsWith("^")?a:"^"}:{...e,until:i})},className:"bg-bg-secondary text-accent-primary rounded border border-border-default px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(none)"}),t.map(r=>s.jsx("option",{value:r,children:r},r)),s.jsx("option",{value:"__regex__",children:"regex…"})]}),o&&s.jsx("input",{value:a,onChange:r=>n({...e,until:r.target.value}),spellCheck:!1,className:"w-40 bg-bg-secondary text-text-primary font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]})}function EA({model:e,onChange:t,onPreview:n,preview:a,onTestSections:o,sectionPreview:r}){const i=e.states.map(m=>m.id),c=Object.keys(e.sections??{}),d=l.useCallback(m=>t({...e,...m}),[e,t]),u=(m,h)=>d({states:e.states.map((g,b)=>b===m?{...g,...h}:g)}),p=(m,h)=>d({transitions:e.transitions.map((g,b)=>b===m?{...g,...h}:g)});return s.jsxs("div",{className:"space-y-3",children:[s.jsx(_A,{sections:e.sections??{},otherSectionIds:m=>c.filter(h=>h!==m),onChange:m=>d({sections:m}),onTest:()=>o(e.sections??{}),testResult:r}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold",children:"States"}),s.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d({states:[...e.states,{id:`state${e.states.length}`,label:"New"}]}),children:"+ state"})]}),s.jsx("div",{className:"space-y-1.5",children:e.states.map((m,h)=>s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1",children:[s.jsxs("div",{className:"flex items-end gap-2 flex-wrap",children:[s.jsxs("label",{className:"flex flex-col gap-0.5",children:[s.jsx("span",{className:"text-4xs text-text-muted uppercase tracking-wide",children:"id (used by transitions)"}),s.jsx("input",{value:m.id,onChange:g=>u(h,{id:g.target.value}),placeholder:"idle",className:"w-32 bg-bg-secondary text-accent-primary font-mono text-2xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),s.jsxs("label",{className:"flex flex-col gap-0.5 flex-1",children:[s.jsx("span",{className:"text-4xs text-text-muted uppercase tracking-wide",children:"label (shown in dashboard)"}),s.jsx("input",{value:m.label,onChange:g=>u(h,{label:g.target.value}),placeholder:"Ready",className:"w-full bg-bg-secondary text-text-primary text-2xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),s.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1 pb-0.5",onClick:()=>d({states:e.states.filter((g,b)=>b!==h)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-3xs text-text-secondary flex-wrap",children:[s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"radio",name:"initial",checked:!!m.initial,onChange:()=>d({states:e.states.map((g,b)=>({...g,initial:b===h}))}),className:"accent-[var(--accent-primary)]"}),"initial"]}),s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"checkbox",checked:!!m.modal,onChange:g=>u(h,{modal:g.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"modal"]}),s.jsxs("label",{className:"flex items-center gap-1",children:["status",s.jsxs("select",{value:m.status??"",onChange:g=>u(h,{status:g.target.value||void 0}),className:"bg-bg-secondary text-text-primary rounded border border-border-default px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(auto)"}),s.jsx("option",{value:"idle",children:"idle"}),s.jsx("option",{value:"generating",children:"generating"}),s.jsx("option",{value:"approval",children:"approval"})]})]})]})]},h))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold",children:"Transitions"}),s.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d({transitions:[...e.transitions,{from:i[0]??"",to:i[0]??""}]}),children:"+ transition"})]}),s.jsx("div",{className:"space-y-1.5",children:e.transitions.map((m,h)=>s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"text-3xs text-text-muted",children:"from"}),s.jsx(HA,{value:m.from,states:i,onChange:g=>p(h,{from:g})}),s.jsx("span",{className:"text-3xs text-text-muted",children:"→"}),s.jsx("select",{value:m.to,onChange:g=>p(h,{to:g.target.value}),className:"bg-bg-secondary text-status-online font-mono text-3xs rounded border border-border-default px-1 py-0.5",children:i.map(g=>s.jsx("option",{value:g,children:g},g))}),s.jsx("span",{className:"text-3xs text-text-muted ml-1",children:"label"}),s.jsx("input",{value:m.label??"",onChange:g=>p(h,{label:g.target.value||void 0}),placeholder:"debug name only (optional)",title:"Display name shown in the debug history/transition table. Does not affect behaviour.",className:"flex-1 min-w-[120px] bg-bg-secondary text-text-secondary text-3xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1",onClick:()=>d({transitions:e.transitions.filter((g,b)=>b!==h)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(hn,{label:"min_hold_ms",value:m.min_hold_ms??0,onChange:g=>p(h,{min_hold_ms:g||void 0})}),s.jsx(hn,{label:"priority",value:m.priority??0,onChange:g=>p(h,{priority:g||void 0})})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-3xs text-text-muted",children:"when"}),!m.when&&s.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>p(h,{when:{section:c[0],matches:""}}),children:"+ guard condition"}),m.when&&s.jsx("button",{type:"button",className:"text-3xs text-text-muted hover:text-status-error",onClick:()=>p(h,{when:void 0}),children:"remove guard"})]}),m.when&&s.jsx(rd,{cond:m.when,path:`t${h}`,sections:c,onChange:g=>p(h,{when:g}),onPreview:n,preview:a})]})]},h))})]})]})}function HA({value:e,states:t,onChange:n}){const a=new Set(Array.isArray(e)?e:e==="*"?t:[e]),o=e==="*",r=i=>{const c=new Set(a);c.has(i)?c.delete(i):c.add(i);const d=t.filter(u=>c.has(u));n(d.length===1?d[0]:d)};return s.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.map(i=>s.jsx("button",{type:"button",onClick:()=>r(i),className:`font-mono text-3xs px-1 py-0.5 rounded border ${o||a.has(i)?"text-accent-primary bg-accent-primary/20 border-accent":"text-text-muted border-border-default hover:border-border-default"}`,children:i},i))})}function Ss(e){return e&&typeof e=="object"?e:{}}function St(e){return typeof e=="string"?e:""}function FA(e){const t=Ss(e);return!!(typeof t.spec_id=="string"&&t.spec_id.length>0||"current_state"in t||Array.isArray(t.stateHistory))}function $A(e){const t=Ss(e.parser),n=Ss(t.parsedStatusCache),a=Ss(e.activeModal).buttons!=null?Ss(e.activeModal):Ss(n.activeModal),o=Array.isArray(a.buttons)?a.buttons:null;if(!o||o.length===0){const r=St(a.message)||St(a.title);return r?{title:r,buttons:[]}:null}return{title:St(a.message)||St(a.title)||null,buttons:o.map((r,i)=>({index:i,label:typeof r=="string"?r:String(r)}))}}function BA(e){const t=Array.isArray(e.messages)?e.messages:null;return t?t.map(n=>Ss(n)).filter(n=>typeof n.role=="string").map(n=>({role:St(n.role),content:St(n.content),receivedAt:typeof n.receivedAt=="number"?n.receivedAt:void 0})):[]}function Xu(e){if(e==null||typeof e!="object")return null;const t=e;if(FA(e))return{cliType:St(t.cliType),spec_id:St(t.spec_id),specPath:typeof t.specPath=="string"?t.specPath:void 0,current_state:t.current_state??null,current_modal:t.current_modal??null,activeInteractivePrompt:t.activeInteractivePrompt,exited:t.exited===!0,screen:St(t.screen),sections:t.sections??void 0,stateHistory:Array.isArray(t.stateHistory)?t.stateHistory:[],statusHistory:[],idleHoldPending:t.idleHoldPending===!0,lastBusyAt:typeof t.lastBusyAt=="number"?t.lastBusyAt:0,cursorPosition:t.cursorPosition??null,completionIdleDebounce:t.completionIdleDebounce??null,fsm:t.fsm??null,name:typeof t.name=="string"?t.name:void 0,status:typeof t.status=="string"?t.status:void 0,workingDir:typeof t.workingDir=="string"?t.workingDir:void 0,spawnedAtMs:typeof t.spawnedAtMs=="number"?t.spawnedAtMs:void 0,providerSessionId:t.providerSessionId??null,messages:t.messages??void 0,committedMessages:t.committedMessages??void 0,nativeSource:!1,transcriptAuthority:void 0};const n=Ss(t.terminal),a=Ss(t.parser),o=Ss(a.parsedStatusCache),r=Ss(t.runtimeMetadata),i=St(n.screenText)||St(n.lastScreenText)||St(t.screenText),c=St(o.status)||St(t.currentStatus)||St(t.status),d=St(o.providerSessionId)||St(r.providerSessionId)||null,u=St(o.transcriptAuthority)||St(t.transcriptAuthority)||void 0,p=(Array.isArray(t.statusHistory)?t.statusHistory:[]).map(m=>Ss(m)).filter(m=>typeof m.status=="string"&&typeof m.at=="number").map(m=>({status:m.status,at:m.at,trigger:typeof m.trigger=="string"?m.trigger:null}));return{cliType:St(t.cliType)||St(t.type),spec_id:St(t.cliType)||St(t.type)||"native-source",specPath:typeof t.specPath=="string"?t.specPath:void 0,current_state:c?{id:c,label:c,title:null}:null,current_modal:$A(t),activeInteractivePrompt:t.activeInteractivePrompt??null,exited:t.exited===!0,screen:i,sections:void 0,stateHistory:[],statusHistory:p,idleHoldPending:!1,lastBusyAt:typeof t.lastBusyAt=="number"?t.lastBusyAt:0,cursorPosition:null,completionIdleDebounce:null,fsm:null,name:St(t.cliName)||St(t.name)||void 0,status:c||void 0,workingDir:typeof t.workingDir=="string"?t.workingDir:void 0,spawnedAtMs:typeof r.spawnedAtMs=="number"?r.spawnedAtMs:typeof t.spawnAt=="number"?t.spawnAt:void 0,providerSessionId:d,messages:BA(t),committedMessages:void 0,nativeSource:!0,transcriptAuthority:u}}function ta(e){const t=Date.now()-e;if(t<0)return"just now";if(t<2e3)return`${t}ms ago`;if(t<6e4)return`${(t/1e3).toFixed(1)}s ago`;const n=Math.floor(t/6e4);return n<60?`${n}m ago`:`${Math.floor(n/60)}h ago`}function Zu(e){return e<=0?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}const WA={busy_hold_expired:"text-status-warning bg-status-warning/20 border border-status-warning/40",idle_hold_committed:"text-status-online bg-status-online/20 border border-status-online/40",completion_idle_after:"text-accent-primary bg-accent-primary/20 border border-accent",forced_completion:"text-orange-200 bg-orange-500/20 border border-orange-500/30",forceEmit:"text-purple-200 bg-purple-500/20 border border-purple-500/30",spec_reload:"text-purple-200 bg-purple-500/20 border border-purple-500/30",eval_match:"text-text-secondary bg-bg-glass border border-border-default"},OA={idle:"text-status-online bg-status-online/20 border border-status-online/40",busy:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",generating:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",waiting_approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",picker:"text-accent-primary bg-accent-primary/20 border border-accent",signing_in:"text-accent-primary bg-accent-primary/20 border border-accent"};function qo(e){return OA[e]??"text-text-primary bg-bg-glass border border-border-default"}function sa({children:e}){return s.jsx("div",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold mb-1.5 mt-0.5",children:e})}function zo(){return s.jsx("div",{className:"border-t border-white/8 my-2"})}function Rf({node:e,depth:t=0}){var o;const n=e.result?"text-status-online":"text-text-muted",a=e.result?"●":"○";return s.jsxs("div",{style:{marginLeft:t*10},className:"font-mono text-3xs leading-relaxed",children:[s.jsxs("span",{className:n,children:[a," "]}),s.jsx("span",{className:"text-text-secondary",children:e.kind}),s.jsxs("span",{className:"text-text-muted",children:[" ",e.detail]}),e.remainingMs!=null&&e.remainingMs>0&&s.jsxs("span",{className:"text-status-warning",children:[" (",e.remainingMs,"ms left)"]}),(o=e.children)==null?void 0:o.map((r,i)=>s.jsx(Rf,{node:r,depth:t+1},i))]})}function UA({t:e}){const[t,n]=l.useState(!1),a=e.fires?"text-status-online bg-status-online/20 border-status-online/40":e.holdSatisfied?"text-text-secondary bg-bg-glass border-border-default":"text-status-warning bg-status-warning/20 border-status-warning/40";return s.jsxs("div",{className:"border border-border-default rounded bg-surface-secondary overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-1 hover:bg-bg-glass-hover text-left",onClick:()=>n(o=>!o),children:[s.jsx("span",{className:"text-3xs text-text-muted w-3",children:e.cond?t?"▾":"▸":" "}),s.jsxs("span",{className:`font-mono text-2xs px-1.5 py-0.5 rounded border ${a}`,children:["→ ",e.to]}),s.jsx("span",{className:"text-text-secondary font-mono text-3xs truncate",children:e.label}),s.jsxs("span",{className:"ml-auto flex items-center gap-1.5 shrink-0",children:[e.fires&&s.jsx("span",{className:"text-status-online text-3xs font-mono",children:"FIRES"}),!e.holdSatisfied&&s.jsxs("span",{className:"text-status-warning text-3xs font-mono",children:["hold ",e.holdRemainingMs,"ms"]}),s.jsx("span",{className:`text-3xs font-mono ${e.condResult?"text-status-online":"text-text-muted"}`,children:e.condResult?"cond✓":"cond✗"})]})]}),t&&e.cond&&s.jsx("div",{className:"px-3 pb-1.5 pt-0.5 bg-bg-secondary border-t border-border-default",children:s.jsx(Rf,{node:e.cond})})]})}function qA({activeConv:e,onClose:t}){var he,re,pe,Z,ue;const{sendCommand:n}=kt(),[a,o]=l.useState(!0),[r,i]=l.useState(null),[c,d]=l.useState(null),[u,p]=l.useState(!1),[m,h]=l.useState(new Set(["footer"])),[g,b]=l.useState("Snapshot"),[f,x]=l.useState(!1),[k,C]=l.useState(null),[v,j]=l.useState(!1),[y,S]=l.useState(""),[w,N]=l.useState(!1),[T,A]=l.useState("idle"),[M,D]=l.useState(null),[P,I]=l.useState([]),[_,L]=l.useState({}),[R,O]=l.useState(null),[J,G]=l.useState(!1),W=e.daemonId||((he=e.routeId)==null?void 0:he.split(":")[0])||e.routeId||"",E=e.sessionId||"",F=l.useCallback(async()=>{o(!0),d(null);try{const se=await n(W,"get_spec_debug",{targetSessionId:E}),ne=se&&typeof se=="object"?se:{},le=ne.result&&typeof ne.result=="object"?ne.result:ne;le!=null&&le.success?i(le):(d((le==null?void 0:le.error)||"Failed to load spec debug"),i(null))}catch(se){d((se==null?void 0:se.message)||String(se)),i(null)}finally{o(!1)}},[n,W,E]);l.useEffect(()=>{F()},[F]),l.useEffect(()=>{if(!J)return;const se=setInterval(()=>{F()},1e3);return()=>clearInterval(se)},[J,F]),l.useEffect(()=>{const se=ne=>{ne.key==="Escape"&&!f&&t()};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[t,f]);const H=l.useCallback(async se=>{try{const ne=await n(W,"validate_spec",{content:JSON.stringify(se)}),le=ne&&typeof ne=="object"?ne:{},ve=le.result&&typeof le.result=="object"?le.result:le;I(ve!=null&&ve.valid?[]:(ve==null?void 0:ve.errors)??["validation failed"])}catch(ne){I([(ne==null?void 0:ne.message)||String(ne)])}},[n,W]),$=l.useCallback(async()=>{D(null),A("idle"),L({});try{const se=await n(W,"get_spec_source",{targetSessionId:E}),ne=se&&typeof se=="object"?se:{},le=ne.result&&typeof ne.result=="object"?ne.result:ne;if(!(le!=null&&le.success)||typeof le.content!="string"){D((le==null?void 0:le.error)||"Failed to load spec source");return}S(le.content);let ve=null;try{ve=JSON.parse(le.content)}catch{}ve&&ve.$schema==="adhdev:cli/spec@4"?(C(ve),j(!1),H(ve)):(C(null),j(!0)),N(!1),x(!0)}catch(se){D((se==null?void 0:se.message)||String(se))}},[n,W,E,H]),X=l.useCallback(se=>{C(se),S(JSON.stringify(se,null,2)),N(!0),A("idle"),H(se)},[H]),U=l.useCallback(async(se,ne)=>{L(le=>({...le,[se]:"loading"}));try{const le=await n(W,"eval_condition_preview",{targetSessionId:E,condition:ne}),ve=le&&typeof le=="object"?le:{},ke=ve.result&&typeof ve.result=="object"?ve.result:ve;!(ke!=null&&ke.success)||!ke.result?L(De=>({...De,[se]:{result:!1,detail:ke==null?void 0:ke.error}})):L(De=>({...De,[se]:{result:ke.result.result,detail:ke.result.detail}}))}catch(le){L(ve=>({...ve,[se]:{result:!1,detail:le==null?void 0:le.message}}))}},[n,W,E]),ge=l.useCallback(async se=>{O("loading");try{const ne=await n(W,"resolve_section_preview",{targetSessionId:E,sections:se}),le=ne&&typeof ne=="object"?ne:{},ve=le.result&&typeof le.result=="object"?le.result:le;!(ve!=null&&ve.success)||!Array.isArray(ve.sections)?O({error:(ve==null?void 0:ve.error)||"resolve failed"}):O({sections:ve.sections,screenLineCount:ve.screenLineCount??0})}catch(ne){O({error:(ne==null?void 0:ne.message)||String(ne)})}},[n,W,E]),Ne=l.useCallback(async()=>{var le,ve;const se=(le=r==null?void 0:r.snapshot)==null?void 0:le.specPath;if(!se){D("No spec path on this session");return}if(!v&&P.length>0){D("Fix validation errors before saving");return}const ne=!v&&k?JSON.stringify(k,null,2):y;A("saving"),D(null);try{const ke=await n(W,"write_spec_source",{specPath:se,content:ne}),De=ke&&typeof ke=="object"?ke:{},ye=De.result&&typeof De.result=="object"?De.result:De;if(!(ye!=null&&ye.success)){A("error"),D(((ve=ye==null?void 0:ye.validationErrors)==null?void 0:ve.join(`
42
42
  `))||(ye==null?void 0:ye.error)||"Save failed");return}A("saved"),N(!1),setTimeout(()=>{F()},400),setTimeout(()=>A("idle"),1500)}catch(ke){A("error"),D((ke==null?void 0:ke.message)||String(ke))}},[n,W,(re=r==null?void 0:r.snapshot)==null?void 0:re.specPath,y,k,v,P,F]),Y=Xu(r==null?void 0:r.snapshot),ie=async()=>{var V,te,Ce;let se=r;se||(await F(),se=r);const ne=Xu(se==null?void 0:se.snapshot),le=[],ve=(ne==null?void 0:ne.nativeSource)===!0;if(le.push("# Spec Debug Snapshot"),le.push(`Generated: ${new Date().toISOString()}`),le.push(`Session: ${(se==null?void 0:se.sessionId)??""} (${(se==null?void 0:se.providerType)??""})`),ve&&(le.push("Provider kind: native-source (no state-machine spec — State History / FSM / Sections are N/A)"),ne!=null&&ne.transcriptAuthority&&le.push(`transcriptAuthority: ${ne.transcriptAuthority}`)),le.push(`Spec: ${(ne==null?void 0:ne.spec_id)??""} (${(ne==null?void 0:ne.specPath)??""})`),le.push(`Provider: ${(ne==null?void 0:ne.name)??""} (${(ne==null?void 0:ne.cliType)??""})`),le.push(`Working dir: ${(ne==null?void 0:ne.workingDir)??""}`),le.push(`Spawned: ${ne!=null&&ne.spawnedAtMs?new Date(ne.spawnedAtMs).toISOString():""}`),le.push(""),le.push("## Current State"),le.push(`State: ${((V=ne==null?void 0:ne.current_state)==null?void 0:V.id)??"none"} (${((te=ne==null?void 0:ne.current_state)==null?void 0:te.label)??""})`),le.push(`Status: ${(ne==null?void 0:ne.status)??""}`),le.push(`Idle hold pending: ${(ne==null?void 0:ne.idleHoldPending)??!1}`),le.push(`Exited: ${(ne==null?void 0:ne.exited)??!1}`),le.push(`Last busy: ${ne!=null&&ne.lastBusyAt?ta(ne.lastBusyAt):""}`),le.push(`Cursor: ${(ne==null?void 0:ne.cursorPosition)!=null?`(${ne.cursorPosition.row},${ne.cursorPosition.col})`:"n/a"}`),(Ce=ne==null?void 0:ne.completionIdleDebounce)!=null&&Ce.active){const ee=ne.completionIdleDebounce;le.push(`completion_idle_after: age=${ee.ageMs}ms hold=${ee.holdMs}ms force=${ee.forceAfterMs}ms remaining=${Math.max(0,ee.holdMs-ee.ageMs)}ms`)}if(le.push(""),le.push("## Modal"),ne!=null&&ne.current_modal){const ee=ne.current_modal.buttons.map(q=>q.label).join(" / ");le.push(`${ne.current_modal.title??""} [${ee}]`)}else le.push("none");if(le.push(""),le.push("## State History (last 20)"),ve&&!(ne!=null&&ne.statusHistory&&ne.statusHistory.length>0)&&le.push("N/A (native-source provider — no state-machine rules)"),ve&&(ne!=null&&ne.statusHistory)&&ne.statusHistory.length>0){le.push("(legacy engine status transitions — native-source provider has no state-machine rules)");for(const ee of[...ne.statusHistory].reverse().slice(0,20))le.push(`- ${ee.status} @ ${new Date(ee.at).toISOString()}${ee.trigger?` | trigger: ${ee.trigger}`:""}`)}const ke=ne!=null&&ne.stateHistory?[...ne.stateHistory].reverse().slice(0,20):[];for(const ee of ke){const q=ee.reason!=null?typeof ee.reason=="string"?ee.reason:JSON.stringify(ee.reason):"",ce=ee.debounceKind!=null?typeof ee.debounceKind=="string"?ee.debounceKind:JSON.stringify(ee.debounceKind):"",Q=ee.matchedStateId!=null?String(ee.matchedStateId):"",oe=(ee.matchedRules??[]).map(K=>typeof K=="string"?K:JSON.stringify(K)).join(", ");le.push(`- ${ee.stateId} @ ${new Date(ee.at).toISOString()} held ${ee.durationMs}ms | reason: ${q} | debounce: ${ce} | eval→${Q} | rules: ${oe}`)}if(le.push(""),le.push("## Sections"),ve)le.push("N/A (native-source provider — no state-machine sections)");else if(ne!=null&&ne.sections)for(const[ee,q]of Object.entries(ne.sections)){const ce=q.split(`
43
43
  `).slice(0,3).join(`
44
44
  `);le.push(`${ee}: ${ce}`)}le.push(""),le.push("## Last Assistant Message");const ye=[...(ne==null?void 0:ne.messages)??(ne==null?void 0:ne.committedMessages)??[]].reverse().find(ee=>ee.role==="assistant");le.push(ye?ye.content.slice(0,400):""),le.push(""),le.push("## Screen (first 50 lines)"),le.push(ne!=null&&ne.screen?ne.screen.split(`
package/public/index.html CHANGED
@@ -7,7 +7,7 @@
7
7
  <meta name="description" content="ADHDev self-hosted dashboard for controlling AI agents" />
8
8
  <link rel="icon" href="/otter-logo.png" />
9
9
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet" />
10
- <script type="module" crossorigin src="/assets/index-D-xVE1_m.js"></script>
10
+ <script type="module" crossorigin src="/assets/index-vwspJ7fS.js"></script>
11
11
  <link rel="modulepreload" crossorigin href="/assets/vendor-DgFmqOGd.js">
12
12
  <link rel="stylesheet" crossorigin href="/assets/index-C0v4C-oL.css">
13
13
  </head>
@@ -40988,7 +40988,7 @@ var require_dist3 = __commonJS({
40988
40988
  if (cached2) return cached2;
40989
40989
  const commit = readInjected(true ? "unknown" : void 0) ?? "unknown";
40990
40990
  const commitShort = readInjected(true ? "unknown" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
40991
- const version2 = readInjected(true ? "1.0.59-rc.16" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
40991
+ const version2 = readInjected(true ? "1.0.59-rc.17" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
40992
40992
  const builtAt = readInjected(true ? "unknown" : void 0);
40993
40993
  cached2 = builtAt ? { commit, commitShort, version: version2, builtAt } : { commit, commitShort, version: version2 };
40994
40994
  return cached2;