agent-relay-server 0.57.0 → 0.57.1

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.
Files changed (69) hide show
  1. package/docs/openapi.json +1 -1
  2. package/package.json +1 -1
  3. package/public/assets/{MessageBubble-DmZIqnga.js → MessageBubble-BqFAi9gS.js} +2 -2
  4. package/public/assets/{MessageBubble-DmZIqnga.js.map → MessageBubble-BqFAi9gS.js.map} +1 -1
  5. package/public/assets/{PlanGraphPanel-DpTMkCBs.js → PlanGraphPanel-CJROpj66.js} +2 -2
  6. package/public/assets/{PlanGraphPanel-DpTMkCBs.js.map → PlanGraphPanel-CJROpj66.js.map} +1 -1
  7. package/public/assets/{activity-D_3n1maA.js → activity-D2m3VCXV.js} +2 -2
  8. package/public/assets/{activity-D_3n1maA.js.map → activity-D2m3VCXV.js.map} +1 -1
  9. package/public/assets/{agent-profiles-Bp-KhfLJ.js → agent-profiles-CIf4b1V7.js} +2 -2
  10. package/public/assets/{agent-profiles-Bp-KhfLJ.js.map → agent-profiles-CIf4b1V7.js.map} +1 -1
  11. package/public/assets/{agents-CHG09FED.js → agents-lDwoWazM.js} +2 -2
  12. package/public/assets/{agents-CHG09FED.js.map → agents-lDwoWazM.js.map} +1 -1
  13. package/public/assets/{analytics-DadE7J8c.js → analytics-OsZ2HJxy.js} +2 -2
  14. package/public/assets/{analytics-DadE7J8c.js.map → analytics-OsZ2HJxy.js.map} +1 -1
  15. package/public/assets/{automation-Da7hPlwY.js → automation-4eeiOl19.js} +2 -2
  16. package/public/assets/{automation-Da7hPlwY.js.map → automation-4eeiOl19.js.map} +1 -1
  17. package/public/assets/{branch-state-badge-BIFdTVFP.js → branch-state-badge-B9WqTxZJ.js} +2 -2
  18. package/public/assets/{branch-state-badge-BIFdTVFP.js.map → branch-state-badge-B9WqTxZJ.js.map} +1 -1
  19. package/public/assets/{channels-CTkaNTj3.js → channels-HK6sLYpZ.js} +2 -2
  20. package/public/assets/{channels-CTkaNTj3.js.map → channels-HK6sLYpZ.js.map} +1 -1
  21. package/public/assets/{chat-EaifCGGe.js → chat-B9FJi94P.js} +2 -2
  22. package/public/assets/{chat-EaifCGGe.js.map → chat-B9FJi94P.js.map} +1 -1
  23. package/public/assets/{connectors-CIMZt48i.js → connectors-3mMNW4Qk.js} +2 -2
  24. package/public/assets/{connectors-CIMZt48i.js.map → connectors-3mMNW4Qk.js.map} +1 -1
  25. package/public/assets/{display-D6H3VZ53.js → display-CketawEF.js} +2 -2
  26. package/public/assets/{display-D6H3VZ53.js.map → display-CketawEF.js.map} +1 -1
  27. package/public/assets/{formatted-body-impl-CDwuhxYD.js → formatted-body-impl-BOLz9dDs.js} +2 -2
  28. package/public/assets/{formatted-body-impl-CDwuhxYD.js.map → formatted-body-impl-BOLz9dDs.js.map} +1 -1
  29. package/public/assets/{index-DG_cFJIA.js → index-0rOVZ5nm.js} +6 -6
  30. package/public/assets/{index-DG_cFJIA.js.map → index-0rOVZ5nm.js.map} +1 -1
  31. package/public/assets/{insights-DqaWxMEv.js → insights-DwtSIqYc.js} +2 -2
  32. package/public/assets/{insights-DqaWxMEv.js.map → insights-DwtSIqYc.js.map} +1 -1
  33. package/public/assets/{integrations-g0NS0UqB.js → integrations-Dd6haLpy.js} +2 -2
  34. package/public/assets/{integrations-g0NS0UqB.js.map → integrations-Dd6haLpy.js.map} +1 -1
  35. package/public/assets/{maintenance-B1ipDm3t.js → maintenance-DVzbjn4x.js} +2 -2
  36. package/public/assets/{maintenance-B1ipDm3t.js.map → maintenance-DVzbjn4x.js.map} +1 -1
  37. package/public/assets/{managed-agents-DHft-J93.js → managed-agents-CJXaWFgZ.js} +2 -2
  38. package/public/assets/{managed-agents-DHft-J93.js.map → managed-agents-CJXaWFgZ.js.map} +1 -1
  39. package/public/assets/{markdown-preview-impl-Dk0jta-N.js → markdown-preview-impl-CCoHxXmF.js} +2 -2
  40. package/public/assets/{markdown-preview-impl-Dk0jta-N.js.map → markdown-preview-impl-CCoHxXmF.js.map} +1 -1
  41. package/public/assets/{memory-Cc_14vr4.js → memory-f9IAAOSG.js} +2 -2
  42. package/public/assets/{memory-Cc_14vr4.js.map → memory-f9IAAOSG.js.map} +1 -1
  43. package/public/assets/{messages-gSUwhZbt.js → messages-DuSBSnsM.js} +2 -2
  44. package/public/assets/{messages-gSUwhZbt.js.map → messages-DuSBSnsM.js.map} +1 -1
  45. package/public/assets/{orchestrators-D7RL2Vdm.js → orchestrators-BUCE7jk3.js} +2 -2
  46. package/public/assets/{orchestrators-D7RL2Vdm.js.map → orchestrators-BUCE7jk3.js.map} +1 -1
  47. package/public/assets/{overview-PP2eD4_Y.js → overview-B0_IOXOo.js} +2 -2
  48. package/public/assets/{overview-PP2eD4_Y.js.map → overview-B0_IOXOo.js.map} +1 -1
  49. package/public/assets/{pairs-DhF9MXdu.js → pairs-DdA8n3dX.js} +2 -2
  50. package/public/assets/{pairs-DhF9MXdu.js.map → pairs-DdA8n3dX.js.map} +1 -1
  51. package/public/assets/{security-CwMaW5CQ.js → security-07gu7r1C.js} +2 -2
  52. package/public/assets/{security-CwMaW5CQ.js.map → security-07gu7r1C.js.map} +1 -1
  53. package/public/assets/{select-CifGD5oc.js → select-CLQutzAh.js} +2 -2
  54. package/public/assets/{select-CifGD5oc.js.map → select-CLQutzAh.js.map} +1 -1
  55. package/public/assets/{settings-Cc8EgRR7.js → settings-E4QJiNjt.js} +2 -2
  56. package/public/assets/{settings-Cc8EgRR7.js.map → settings-E4QJiNjt.js.map} +1 -1
  57. package/public/assets/{store-DKtaJZyC.js → store-DmxnYVm1.js} +2 -2
  58. package/public/assets/{store-DKtaJZyC.js.map → store-DmxnYVm1.js.map} +1 -1
  59. package/public/assets/{tasks-Boji1e5w.js → tasks-BB1nTWjm.js} +2 -2
  60. package/public/assets/{tasks-Boji1e5w.js.map → tasks-BB1nTWjm.js.map} +1 -1
  61. package/public/assets/{teams-DJVSjs4x.js → teams-BtY2fi5X.js} +2 -2
  62. package/public/assets/{teams-DJVSjs4x.js.map → teams-BtY2fi5X.js.map} +1 -1
  63. package/public/assets/{terminal-viewer-impl-DdbGJg-X.js → terminal-viewer-impl-CHCUDXgj.js} +2 -2
  64. package/public/assets/{terminal-viewer-impl-DdbGJg-X.js.map → terminal-viewer-impl-CHCUDXgj.js.map} +1 -1
  65. package/public/assets/{work-queue-BKsEKdR7.js → work-queue-CPXo2IdX.js} +2 -2
  66. package/public/assets/{work-queue-BKsEKdR7.js.map → work-queue-CPXo2IdX.js.map} +1 -1
  67. package/public/assets/{workspaces-BTJ2O87P.js → workspaces-D_vNXWDf.js} +2 -2
  68. package/public/assets/{workspaces-BTJ2O87P.js.map → workspaces-D_vNXWDf.js.map} +1 -1
  69. package/public/index.html +3 -3
package/docs/openapi.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "openapi": "3.1.0",
3
3
  "info": {
4
4
  "title": "Agent Relay API",
5
- "version": "0.57.0",
5
+ "version": "0.57.1",
6
6
  "description": "Real-time message bus for inter-agent communication. Agent-first: this spec is designed for machine consumption — agents can self-discover the full API surface via GET /api/spec.",
7
7
  "license": {
8
8
  "name": "MIT",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-relay-server",
3
- "version": "0.57.0",
3
+ "version": "0.57.1",
4
4
  "description": "Lightweight HTTP message relay for inter-agent communication across machines",
5
5
  "module": "src/index.ts",
6
6
  "type": "module",
@@ -1,2 +1,2 @@
1
- import{r as e}from"./chunk-CilyBKbf.js";import{Fn as t,Gn as n,N as r,Nn as i,Xt as a,Zt as o,b as s,bt as c,c as l,cn as u,g as d,i as f,in as p,it as m,jn as h,jt as g,mn as _,nn as v,on as y,p as b,qt as x,r as S,rn as C,sn as w,yt as T,zt as E}from"./lucide-react-C3j5Huiw.js";import{n as D,p as O,t as k}from"./store-DKtaJZyC.js";import{D as A,I as j,M,W as N,it as P,j as F,w as I,z as L}from"./display-D6H3VZ53.js";import{a as R,i as z,o as ee,t as B}from"./index-DG_cFJIA.js";var V=e(n(),1),H={online:`came online`,offline:`went offline`,shutdown:`shut down`,restarted:`restarted`,"compaction-requested":`compaction requested`,compacting:`compaction started`,compacted:`context compacted`,"compaction-stalled":`compaction stalled — may need manual intervention`,"clear-requested":`clear requested`,"clearing-context":`clear started`,"context-cleared":`context cleared`,"clear-stalled":`context clear stalled — may need manual intervention`,"shutting-down":`shutting down`},te=new Set(Object.keys(H)),ne=3e3;function U(e){return new Date(e.occurredAt??e.createdAt).getTime()}function re(e){if(e.kind!==`session`)return null;let t=e.payload?.session;return!t||t.type!==`narration`&&t.type!==`reasoning`&&t.type!==`tool`?null:{id:e.id,kind:t.type,label:typeof t.label==`string`?t.label:void 0,text:e.body,ts:U(e),turnId:typeof t.turnId==`string`?t.turnId:void 0}}function ie(e){if(e.kind!==`session`)return null;let t=e.payload?.session;if(t?.type!==`notice`)return null;let n=typeof t.label==`string`&&t.label?t.label:`compacted`;return{id:`notice-${e.id}`,status:n,timestamp:U(e)}}function ae(e){return e.kind===`system`&&e.from===`system`}function W(e){let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`}function oe(e){let t=e.filter(e=>te.has(e.status)).slice().sort((e,t)=>e.timestamp-t.timestamp),n=[];for(let e of t)n.some(t=>t.id===e.id)||n.some(t=>t.status===e.status&&Math.abs(t.timestamp-e.timestamp)<=ne)||n.push(e);return n}function se(e,t,n,r=[]){let i=[];for(let e of r){let t=e.entries.reduce((e,t)=>Math.min(e,N(t.originalCreatedAt)),1/0),n=Number.isFinite(t)?t-1:e.importedAt;i.push({ts:n,entry:{type:`import-boundary`,history:e,timestamp:n}});for(let t of e.entries)i.push({ts:N(t.originalCreatedAt),entry:{type:`imported-message`,history:e,entry:t}})}if(n){let e=new Date(n).getTime();Number.isFinite(e)&&i.push({ts:e,entry:{type:`created`,timestamp:e}})}let a=new Map;for(let t of e){if(t.kind!==`session`)continue;let e=t.payload?.session;if(e?.type===`response`&&typeof e.turnId==`string`){let n=a.get(e.turnId)??[];n.push(t.body.trim()),a.set(e.turnId,n)}}let o=[];for(let t of e){if(ae(t)){i.push({ts:U(t),entry:{type:`notice`,msg:t}});continue}let e=ie(t);if(e){o.push(e);continue}let n=re(t);if(n){if(n.kind===`narration`&&n.turnId&&a.get(n.turnId)?.some(e=>L(e,n.text)))continue;i.push({ts:n.ts,entry:{type:`activity`,steps:[n],timestamp:n.ts}});continue}i.push({ts:U(t),entry:{type:`message`,msg:t}})}for(let e of oe([...t,...o]))i.push({ts:e.timestamp,entry:{type:`status`,event:e}});let s={created:0,date:1,"import-boundary":2,"imported-message":3,message:4,activity:4,notice:4,status:5};i.sort((e,t)=>{let n=e.ts-t.ts;return Math.abs(n)<3e3&&s[e.entry.type]-s[t.entry.type]||n});let c=[],l=``;for(let{ts:e,entry:t}of i){if(t.type===`created`){c.push(t);continue}let n=W(e);if(n!==l&&(c.push({type:`date`,date:n,timestamp:e}),l=n),t.type===`activity`){let e=c[c.length-1];if(e&&e.type===`activity`&&ce(e,t)){e.steps.push(...t.steps);continue}}c.push(t)}return c}function ce(e,t){let n=e.steps[e.steps.length-1]?.turnId,r=t.steps[0]?.turnId;return n&&r?n===r:!n&&!r}function G(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/1024/1024).toFixed(1)} MB`}function le(e,t){if(t.startsWith(`/`))return t;let n=`${e.replace(/\/+$/,``)}/${t}`.split(`/`),r=[];for(let e of n)!e||e===`.`||(e===`..`?r.pop():r.push(e));return`/`+r.join(`/`)}function ue(e){let t=e.replace(/\/+$/,``),n=t.lastIndexOf(`/`);return n>0?t.slice(0,n):`/`}function de(e,t){return e.filter(e=>e.status===`online`&&j(t,e.baseDir)).sort((e,t)=>F(t.baseDir).length-F(e.baseDir).length)[0]||e.find(e=>e.status===`online`)}function fe(){return typeof window<`u`&&window.matchMedia(`(min-width: 1280px)`).matches}function K(){return typeof window<`u`&&!!window.getSelection()?.toString()}function pe(e){let t=e.payload?.attachments;return Array.isArray(t)?t.filter(e=>!!(e&&typeof e==`object`&&typeof e.artifactId==`string`)):[]}var me=[`👍`,`❤️`,`✅`,`👀`];function he(e){let t=new Map;for(let n of e.reactions||[]){let e=M(n.emoji),r=t.get(e)??{emoji:e,count:0,mine:!1,actors:[]};r.count+=1,r.mine=r.mine||n.actorId===`user`,r.actors.push(n.actorId),t.set(e,r)}return[...t.values()].sort((e,t)=>t.count-e.count||e.emoji.localeCompare(t.emoji))}function q(e){return I(e)}function ge(e,t){let n=e.readBy||[],r=e.resolvedToAgent||t||e.to,i=r?n.includes(r):!1,a=n.some(e=>e!==P);if(i||a){let e=i?r:n.find(e=>e!==P);return{label:`read`,title:e?`Read by ${e}`:`Read by agent`,tone:`ok`,icon:u}}if(e.deliveryStatus===`delivered`)return{label:`delivered`,title:`Delivered to agent inbox`,tone:`ok`,icon:u};if(e.deliveryStatus===`queued`)return{label:`queued`,title:`Queued until the target agent is available`,tone:`warn`,icon:x};if(e.deliveryStatus===`failed`||e.deliveryStatus===`dead`){let t=e.deliveryPoisonReason||e.deliveryLastError||e.deliveryStatus;return{label:e.deliveryStatus,title:t,tone:`danger`,icon:v}}return{label:`sent`,title:`Accepted by Relay`,tone:`muted`,icon:w}}function _e(e){let t=N(e.createdAt);return(e.reactions||[]).reduce((e,t)=>Math.max(e,N(t.updatedAt||t.createdAt)),t)}function ve(e){return e?e.messages.reduce((e,t)=>Math.max(e,_e(t)),0):0}function J(e){return new Date(e).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})}function ye(e){for(let t of e)t.previewUrl&&URL.revokeObjectURL(t.previewUrl)}function be(e,t,n,r){if(e?.teamId)return{teamId:e.teamId};let i=[...t];n&&!i.some(e=>e.id===n.id)&&i.push(n);let a=i.filter(e=>e.threadId).reverse(),o=a.find(e=>!!r[D(e.threadId,e.channel)])??a[0];return o?.threadId?{threadId:o.threadId,...o.channel?{channel:o.channel}:{}}:null}var Y=i(),xe={online:`text-emerald-400`,offline:`text-zinc-400`,shutdown:`text-zinc-400`,restarted:`text-blue-400`,"compaction-requested":`text-zinc-400`,compacting:`text-amber-400`,compacted:`text-amber-400`,"compaction-stalled":`text-red-400`,"clear-requested":`text-zinc-400`,"clearing-context":`text-amber-400`,"context-cleared":`text-amber-400`,"clear-stalled":`text-red-400`,"shutting-down":`text-zinc-400`};function Se(e){let t=new Date,[n,r,i]=e.split(`-`).map(Number),a=new Date(n,r-1,i);if(e===W(t.getTime()))return`Today`;let o=new Date(t);return o.setDate(o.getDate()-1),e===W(o.getTime())?`Yesterday`:a.toLocaleDateString(void 0,{weekday:`short`,month:`short`,day:`numeric`,year:a.getFullYear()===t.getFullYear()?void 0:`numeric`})}function Ce({event:e}){return(0,Y.jsxs)(`div`,{className:`flex items-center justify-center gap-2 py-2 my-1`,children:[(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`}),(0,Y.jsxs)(`div`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,Y.jsx)(a,{className:h(`w-2 h-2 fill-current`,xe[e.status]||`text-zinc-400`)}),(0,Y.jsx)(`span`,{children:H[e.status]||e.status}),(0,Y.jsx)(`span`,{className:`text-muted-foreground/60`,children:J(e.timestamp)})]}),(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}var we={"branch.landed":T,"context.warning":b},Te={"branch.landed":`branch landed`,"context.warning":`context warning`};function Ee({msg:e}){let t=typeof e.payload?.kind==`string`?e.payload.kind:``,n=we[t]??r,i=Te[t]??(t||`system signal`);return(0,Y.jsxs)(`div`,{className:`flex items-center justify-center gap-2 py-2 my-1`,children:[(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`}),(0,Y.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-full border border-border bg-muted/30 px-2.5 py-1 text-xs text-muted-foreground`,children:[(0,Y.jsx)(n,{className:`h-3 w-3`}),(0,Y.jsx)(`span`,{children:i}),(0,Y.jsx)(`span`,{className:`text-muted-foreground/60`,children:J(e.occurredAt??e.createdAt)})]}),(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function De({blockedLabel:e,onInterrupt:t}){return e?(0,Y.jsx)(`div`,{className:`flex justify-start mb-3`,children:(0,Y.jsxs)(`div`,{className:`flex items-center gap-2 rounded-2xl rounded-bl-sm bg-card ring-1 ring-red-500/30 px-4 py-2.5`,children:[(0,Y.jsx)(v,{className:`w-3.5 h-3.5 text-red-400`}),(0,Y.jsxs)(`span`,{className:`text-xs text-red-300`,children:[`blocked: `,e]})]})}):(0,Y.jsx)(`div`,{className:`flex justify-start mb-3`,children:(0,Y.jsxs)(`div`,{className:`flex items-center gap-2 rounded-2xl rounded-bl-sm bg-card ring-1 ring-foreground/10 px-4 py-2.5`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,Y.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-yellow-400 animate-[pulse_1.4s_ease-in-out_infinite]`}),(0,Y.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-yellow-400 animate-[pulse_1.4s_ease-in-out_0.2s_infinite]`}),(0,Y.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-yellow-400 animate-[pulse_1.4s_ease-in-out_0.4s_infinite]`})]}),(0,Y.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`working`}),t&&(0,Y.jsxs)(`button`,{onClick:t,title:`Interrupt`,className:`ml-1 flex items-center gap-1 rounded-full px-1.5 py-0.5 text-xs text-muted-foreground hover:text-red-300 hover:bg-red-500/10 transition-colors`,children:[(0,Y.jsx)(o,{className:`w-3.5 h-3.5`}),`Stop`]})]})})}var X=`agent-relay:chat-hide-tools`,Z=(()=>{let e=new Set,t=(()=>{try{return window.localStorage.getItem(X)===`on`}catch{return!1}})(),n=()=>e.forEach(e=>e());return typeof window<`u`&&window.addEventListener(`storage`,e=>{e.key===X&&(t=e.newValue===`on`,n())}),{subscribe(t){return e.add(t),()=>e.delete(t)},get:()=>t,toggle(){t=!t;try{window.localStorage.setItem(X,t?`on`:`off`)}catch{}n()}}})();function Oe(){return[(0,V.useSyncExternalStore)(Z.subscribe,Z.get,()=>!1),Z.toggle]}function Q({steps:e,showReasoning:t}){let[n,r]=Oe(),i=t?e:e.filter(e=>e.kind!==`reasoning`);if(!i.length)return null;let a=i.filter(e=>e.kind===`tool`).length;return(0,Y.jsx)(`div`,{className:`flex justify-start mb-2`,children:(0,Y.jsxs)(`div`,{className:`max-w-[85%] md:max-w-[75%] min-w-0 space-y-1.5`,children:[i.map(e=>e.kind===`narration`?(0,Y.jsx)(B,{text:e.text,className:`text-sm leading-relaxed break-words text-foreground/90 min-w-0`},e.id):e.kind===`reasoning`?(0,Y.jsxs)(`div`,{className:`flex items-start gap-1.5 text-xs leading-relaxed text-muted-foreground/80`,children:[(0,Y.jsx)(_,{className:`w-3.5 h-3.5 mt-0.5 shrink-0 opacity-70`}),(0,Y.jsx)(B,{text:e.text,className:`italic break-words min-w-0`})]},e.id):n?null:(0,Y.jsxs)(`div`,{className:`flex items-start gap-1.5 text-xs leading-relaxed text-muted-foreground`,children:[(0,Y.jsx)(d,{className:`w-3 h-3 mt-0.5 shrink-0 opacity-70`}),(0,Y.jsxs)(`span`,{className:`min-w-0 break-words`,children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:e.label||`tool`}),e.text?(0,Y.jsxs)(`span`,{className:`opacity-70`,children:[` — `,e.text]}):null]})]},e.id)),a>0&&(0,Y.jsxs)(`button`,{onClick:r,className:`flex items-center gap-1 text-[11px] text-muted-foreground/50 hover:text-muted-foreground transition-colors text-left`,children:[(0,Y.jsx)(p,{className:h(`w-3 h-3 shrink-0 transition-transform`,!n&&`rotate-90`)}),(0,Y.jsx)(`span`,{children:n?`show ${a} tool step${a===1?``:`s`}`:`hide tool steps`})]})]})})}function ke({date:e}){return(0,Y.jsxs)(`div`,{className:`flex items-center justify-center gap-3 py-3 my-1`,children:[(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`}),(0,Y.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:Se(e)}),(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function Ae({timestamp:e}){let t=new Date(e).toLocaleString(void 0,{month:`short`,day:`numeric`,year:`numeric`,hour:`2-digit`,minute:`2-digit`});return(0,Y.jsxs)(`div`,{className:`flex items-center justify-center gap-2 py-2 my-1`,children:[(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`}),(0,Y.jsxs)(`span`,{className:`text-xs text-muted-foreground/60`,children:[`created `,t]}),(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function je({history:e}){let t=e.sourceAgentLabel||e.sourcePeerId,n=e.entries.length;return(0,Y.jsxs)(`div`,{className:`flex items-center justify-center gap-2 py-2 my-1`,children:[(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`}),(0,Y.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-full border border-dashed border-border bg-muted/30 px-2 py-1 text-[11px] text-muted-foreground`,children:[(0,Y.jsx)(c,{className:`h-3 w-3`}),(0,Y.jsxs)(`span`,{children:[`forked history from `,t]}),(0,Y.jsxs)(`span`,{className:`text-muted-foreground/60`,children:[n,` `,n===1?`entry`:`entries`]})]}),(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function Me({entry:e,sourceLabel:t}){let n=e.message,r=A(n),i=e.originalFrom===P;return(0,Y.jsx)(`div`,{className:h(`flex mb-3 opacity-80`,i?`justify-end`:`justify-start`),children:(0,Y.jsx)(`div`,{className:`max-w-[85%] md:max-w-[75%]`,children:(0,Y.jsxs)(`div`,{className:h(`rounded-2xl border border-dashed px-3.5 py-2 text-sm select-text`,i?`border-primary/25 bg-primary/10 text-foreground rounded-br-sm`:`border-border bg-card/70 rounded-bl-sm`),children:[(0,Y.jsxs)(`div`,{className:h(`mb-1 text-[10px] uppercase tracking-normal`,i?`text-primary/70`:`text-muted-foreground`),children:[`forked history · `,i?`you`:t||e.originalFrom]}),(0,Y.jsx)(B,{text:r,rawBody:n.body,className:`leading-relaxed`}),(0,Y.jsxs)(`p`,{className:h(`mt-1 flex items-center justify-end gap-1.5 text-xs`,i?`text-primary/60`:`text-muted-foreground`),children:[(0,Y.jsxs)(`span`,{className:`opacity-40`,children:[`#`,e.originalMessageId]}),(0,Y.jsx)(`span`,{children:J(e.originalCreatedAt)})]})]})})})}function Ne({scrollRef:e,timeline:t}){let[n,r]=(0,V.useState)(!0),[i,a]=(0,V.useState)(null),[o,s]=(0,V.useState)(null),[c,l]=(0,V.useState)(!0),u=(0,V.useMemo)(()=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(!(!n||n.type!==`message`)&&n.msg.from===`user`)return{id:n.msg.id,body:A(n.msg)}}return null},[t]);if((0,V.useEffect)(()=>{let t=e.current;if(!u||!t){r(!0);return}let n=t.querySelector(`[data-msg-id="${u.id}"]`);if(!n){r(!0);return}let i=new IntersectionObserver(([e])=>{if(e&&(r(e.isIntersecting),!e.isIntersecting)){let n=e.rootBounds?.top??t.getBoundingClientRect().top;l(e.boundingClientRect.top<n)}},{root:t,threshold:0});i.observe(n);let a=()=>{let e=n.getBoundingClientRect(),r=t.getBoundingClientRect();l(e.top<r.top)};return t.addEventListener(`scroll`,a,{passive:!0}),()=>{i.disconnect(),t.removeEventListener(`scroll`,a)}},[u?.id,e]),n||!u||!u.body.trim())return null;let d=i?.id===u.id?i.value:!1,f=o?.id===u.id?o.value:!1;function p(){let t=e.current;!t||!u||t.querySelector(`[data-msg-id="${u.id}"]`)?.scrollIntoView({behavior:`smooth`,block:`center`})}let m=c?`↑`:`↓`;return f?(0,Y.jsx)(`div`,{className:`sticky top-0 z-10 -mx-3 md:-mx-4 -mt-3 md:-mt-4 bg-background`,children:(0,Y.jsxs)(`button`,{type:`button`,className:`w-full flex items-center justify-center gap-1.5 py-1 text-[11px] text-primary/60 hover:text-primary border-b border-primary/10 transition-colors`,onClick:()=>s({id:u.id,value:!1}),children:[(0,Y.jsx)(`span`,{children:`Your prompt`}),(0,Y.jsx)(y,{className:`w-3 h-3`})]})}):(0,Y.jsxs)(`div`,{className:`sticky top-0 z-10 -mx-3 md:-mx-4 -mt-3 md:-mt-4 px-2 md:px-3 pt-2 pb-1.5 bg-background border-b border-primary/10`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px] text-muted-foreground mb-0.5`,children:[(0,Y.jsx)(`span`,{className:`font-medium text-primary/70`,children:`Your prompt`}),(0,Y.jsxs)(`button`,{type:`button`,className:`ml-auto hover:text-foreground transition-colors`,onClick:p,children:[m,` scroll to original`]}),(0,Y.jsx)(`button`,{type:`button`,className:`hover:text-foreground transition-colors`,onClick:()=>s({id:u.id,value:!0}),title:`Minimize`,children:(0,Y.jsx)(C,{className:`w-3 h-3`})})]}),(0,Y.jsx)(`p`,{className:h(`text-sm text-foreground leading-snug cursor-pointer`,!d&&`line-clamp-2`),onClick:()=>a({id:u.id,value:!d}),children:u.body})]})}function Pe(){return(0,V.useSyncExternalStore)(e=>O.subscribe(e),()=>O.getPlayingKey(),()=>null)}function Fe({attachment:e,outbound:n}){let r=e.kind===`image`,i=e.title||e.artifactId,[a,o]=(0,V.useState)(null),[s,c]=(0,V.useState)(null),[l,u]=(0,V.useState)(!1),[d,p]=(0,V.useState)(!1);(0,V.useEffect)(()=>{let n=!1,r=null;async function i(){u(!0),c(null),o(null);try{let i=await t(`/artifacts/${encodeURIComponent(e.artifactId)}/content`);if(n)return;r=URL.createObjectURL(i),o(r)}catch(e){n||c(e.message)}finally{n||u(!1)}}return i(),()=>{n=!0,r&&URL.revokeObjectURL(r)}},[e.artifactId]);function _(){if(!a)return;let e=document.createElement(`a`);e.href=a,e.download=i,document.body.appendChild(e),e.click(),e.remove()}return r?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`button`,{type:`button`,onClick:()=>a&&p(!0),disabled:!a,className:`group/img mt-2 block overflow-hidden rounded-md border border-foreground/10 bg-black/10 text-left disabled:cursor-default relative`,children:a?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`img`,{src:a,alt:i,loading:`lazy`,className:`block max-h-72 max-w-full object-contain`}),(0,Y.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center bg-black/0 group-hover/img:bg-black/30 transition-colors`,children:(0,Y.jsx)(S,{className:`w-6 h-6 text-white opacity-0 group-hover/img:opacity-100 transition-opacity drop-shadow-md`})})]}):(0,Y.jsxs)(`span`,{className:h(`flex min-h-20 items-center gap-2 px-3 py-2 text-xs`,s?`text-red-400`:`text-muted-foreground`),children:[l?(0,Y.jsx)(m,{className:`h-4 w-4 animate-spin`}):(0,Y.jsx)(v,{className:`h-4 w-4`}),s||`Loading image`]})}),a&&(0,Y.jsx)(z,{open:d,onOpenChange:p,children:(0,Y.jsxs)(R,{className:`max-w-[95vw] max-h-[95vh] w-auto p-0 bg-black/95 border-zinc-800 gap-0 overflow-hidden`,showCloseButton:!1,children:[(0,Y.jsx)(ee,{className:`sr-only`,children:i}),(0,Y.jsxs)(`div`,{className:`relative flex items-center justify-center min-h-[200px]`,children:[(0,Y.jsx)(`img`,{src:a,alt:i,className:`max-w-[93vw] max-h-[90vh] object-contain`}),(0,Y.jsxs)(`div`,{className:`absolute top-2 right-2 flex gap-1`,children:[(0,Y.jsx)(`button`,{type:`button`,onClick:_,className:`rounded-md bg-black/60 hover:bg-black/80 p-2 text-white transition-colors`,title:`Download`,children:(0,Y.jsx)(E,{className:`w-4 h-4`})}),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>p(!1),className:`rounded-md bg-black/60 hover:bg-black/80 p-2 text-white transition-colors`,title:`Close`,children:(0,Y.jsx)(f,{className:`w-4 h-4`})})]})]})]})})]}):(0,Y.jsxs)(`button`,{type:`button`,onClick:_,disabled:!a,className:h(`mt-2 flex w-full items-center gap-2 rounded-md border px-2.5 py-2 text-left text-xs transition-colors disabled:cursor-default disabled:opacity-70`,n?`border-primary-foreground/20 bg-primary-foreground/10 hover:bg-primary-foreground/15`:`border-border bg-background hover:bg-muted`),children:[l?(0,Y.jsx)(m,{className:`h-4 w-4 shrink-0 animate-spin`}):s?(0,Y.jsx)(v,{className:`h-4 w-4 shrink-0 text-red-400`}):(0,Y.jsx)(g,{className:`h-4 w-4 shrink-0`}),(0,Y.jsx)(`span`,{className:h(`min-w-0 flex-1 truncate`,s&&`text-red-400`),children:s||i}),(0,Y.jsx)(E,{className:`h-3.5 w-3.5 shrink-0`})]})}function $({open:e,onToggle:t,onReact:n}){return(0,Y.jsxs)(`div`,{className:`relative shrink-0`,children:[(0,Y.jsx)(`button`,{type:`button`,title:`Add reaction`,onClick:t,className:h(`inline-flex h-5 w-6 items-center justify-center rounded-full border border-border bg-popover text-muted-foreground shadow-sm transition hover:bg-muted hover:text-foreground`,e?`opacity-100`:`opacity-0 pointer-events-none md:group-hover/msg:opacity-100 md:group-hover/msg:pointer-events-auto`),children:(0,Y.jsx)(s,{className:`h-3 w-3`})}),e&&(0,Y.jsx)(`div`,{className:`absolute bottom-full left-0 z-30 mb-1 flex gap-0.5 rounded-full border border-border bg-popover p-0.5 shadow-md`,children:me.map(e=>(0,Y.jsx)(`button`,{type:`button`,title:`React ${e}`,onClick:()=>n(e),className:`inline-flex h-6 w-7 items-center justify-center rounded-full text-xs transition-colors hover:bg-muted`,children:e},e))})]})}var Ie=(0,V.memo)(function({msg:e,peer:t,onOpenReferencedPath:n,onPreviewReferencedPath:r,onPreviewReferencedPathEnd:i}){let a=e.from!==`user`&&e.to!==`user`,s=a?e.from===t:e.from===P,c=a?s?`→ ${e.to}`:`from ${e.from}`:null,u=k(e=>e.reactToMessage),d=k(e=>e.voiceTtsEnabled),f=Pe(),p=k(e=>{let n=e.agentsById[t]?.meta?.cwd;return typeof n==`string`?n:``}),[m,g]=(0,V.useState)(!1),_=(0,V.useRef)(null),v=(0,V.useRef)(null),y=(0,V.useRef)(!1),b=A(e),x=J(e.occurredAt??e.createdAt),S=pe(e),C=he(e),w=s?ge(e,t):null,T=w?.icon,E=f===String(e.id),D=d&&!s&&!a&&!q(e)&&b.trim().length>0;function j(t){t.stopPropagation(),E?O.bargeIn():O.speak(e.body,String(e.id))}(0,V.useEffect)(()=>{if(!m)return;function e(e){K()||_.current&&!_.current.contains(e.target)&&g(!1)}return document.addEventListener(`mousedown`,e),document.addEventListener(`touchstart`,e),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`touchstart`,e)}},[m]);function M(e){return le(p||`/`,e)}function N(e,t){let r=M(e);n?.(r,t)}function F(e,t,n){let i=M(e);r?.(i,t,n)}function I(t){u(e,t),g(!1)}function L(e){e.button===0&&(v.current={x:e.clientX,y:e.clientY},y.current=!1)}function R(e){let t=v.current;t&&(Math.abs(e.clientX-t.x)>3||Math.abs(e.clientY-t.y)>3)&&(y.current=!0)}function z(t){if(!(q(e)||s||a)&&!t.target.closest(`a,button,input,textarea,select,[role="button"]`)){if(y.current||K()){y.current=!1;return}g(e=>!e)}}return(0,Y.jsx)(`div`,{"data-msg-id":e.id,className:h(`group/msg flex mb-3`,s?`justify-end`:`justify-start`),children:(0,Y.jsxs)(`div`,{ref:_,className:`relative max-w-[85%] md:max-w-[75%]`,children:[D&&(0,Y.jsx)(`button`,{type:`button`,title:E?`Stop playback`:`Play aloud`,onClick:j,className:h(`absolute -top-2 -right-2 z-20 inline-flex h-6 w-6 items-center justify-center rounded-full border bg-popover shadow-sm transition`,E?`border-primary/50 text-primary opacity-100`:`border-border text-muted-foreground opacity-70 hover:bg-muted hover:text-foreground hover:opacity-100 [@media(hover:hover)]:md:opacity-0 [@media(hover:hover)]:md:group-hover/msg:opacity-100`),children:E?(0,Y.jsx)(o,{className:`h-3.5 w-3.5 animate-pulse`}):(0,Y.jsx)(l,{className:`h-3.5 w-3.5`})}),(0,Y.jsxs)(`div`,{className:h(`rounded-2xl px-3.5 py-2 text-sm select-text`,!s&&!q(e)&&!a&&`cursor-pointer`,s?`bg-primary text-primary-foreground rounded-br-sm`:`bg-card ring-1 ring-foreground/10 rounded-bl-sm`),onPointerDown:L,onPointerMove:R,onClick:z,children:[c&&(0,Y.jsx)(`p`,{className:h(`text-xs font-medium mb-1 opacity-60`,s?`text-primary-foreground`:`text-muted-foreground`),children:c}),e.subject&&(0,Y.jsx)(`p`,{className:h(`text-xs font-semibold mb-1`,s?`text-primary-foreground/70`:`text-muted-foreground`),children:e.subject}),(0,Y.jsx)(B,{text:b,rawBody:e.body,className:`leading-relaxed`,onOpenPath:N,onPreviewPath:F,onPreviewPathEnd:i,resolvePathTitle:(e,t)=>`${M(e)}${t?`:${t}`:``}`}),S.map(t=>(0,Y.jsx)(Fe,{attachment:t,outbound:s},`${e.id}-${t.artifactId}-${t.role||``}`)),(0,Y.jsxs)(`p`,{className:h(`text-xs mt-1 flex items-center gap-1.5`,s?`justify-end text-primary-foreground/60`:`justify-end text-muted-foreground`),children:[(0,Y.jsxs)(`span`,{className:`opacity-40`,children:[`#`,e.id]}),(0,Y.jsx)(`span`,{children:x}),w&&T&&(0,Y.jsxs)(`span`,{className:h(`inline-flex items-center gap-1`,w.tone===`ok`&&`text-emerald-300`,w.tone===`warn`&&`text-amber-200`,w.tone===`danger`&&`text-red-200`),title:w.title,children:[(0,Y.jsx)(T,{className:`h-3 w-3`}),w.label]})]})]}),!q(e)&&C.length>0&&(0,Y.jsxs)(`div`,{className:h(`flex flex-wrap items-center gap-0.5 -mt-1 relative z-10`,s?`justify-end pr-2`:`justify-start pl-2`),children:[!s&&(0,Y.jsx)($,{open:m,onToggle:()=>g(e=>!e),onReact:I}),C.map(e=>(0,Y.jsxs)(`button`,{type:`button`,title:e.actors.join(`, `),onClick:()=>I(e.emoji),className:h(`inline-flex h-5 items-center gap-0.5 rounded-full border px-1.5 text-[11px] shadow-sm transition-colors`,e.mine?`border-primary/40 bg-primary/10 text-primary`:`border-border bg-background hover:bg-muted text-foreground`),children:[(0,Y.jsx)(`span`,{children:e.emoji}),e.count>1&&(0,Y.jsx)(`span`,{children:e.count})]},e.emoji))]}),!q(e)&&!s&&C.length===0&&(0,Y.jsx)(`div`,{className:`absolute -bottom-2.5 left-1 z-20`,children:(0,Y.jsx)($,{open:m,onToggle:()=>g(e=>!e),onReact:I})})]})})});export{ve as _,ke as a,Ee as c,G as d,de as f,fe as g,ye as h,Ae as i,Ce as l,be as m,Q as n,je as o,ue as p,De as r,Me as s,Ie as t,Ne as u,se as v};
2
- //# sourceMappingURL=MessageBubble-DmZIqnga.js.map
1
+ import{r as e}from"./chunk-CilyBKbf.js";import{Fn as t,Gn as n,N as r,Nn as i,Xt as a,Zt as o,b as s,bt as c,c as l,cn as u,g as d,i as f,in as p,it as m,jn as h,jt as g,mn as _,nn as v,on as y,p as b,qt as x,r as S,rn as C,sn as w,yt as T,zt as E}from"./lucide-react-C3j5Huiw.js";import{n as D,p as O,t as k}from"./store-DmxnYVm1.js";import{D as A,I as j,M,W as N,it as P,j as F,w as I,z as L}from"./display-CketawEF.js";import{a as R,i as z,o as ee,t as B}from"./index-0rOVZ5nm.js";var V=e(n(),1),H={online:`came online`,offline:`went offline`,shutdown:`shut down`,restarted:`restarted`,"compaction-requested":`compaction requested`,compacting:`compaction started`,compacted:`context compacted`,"compaction-stalled":`compaction stalled — may need manual intervention`,"clear-requested":`clear requested`,"clearing-context":`clear started`,"context-cleared":`context cleared`,"clear-stalled":`context clear stalled — may need manual intervention`,"shutting-down":`shutting down`},te=new Set(Object.keys(H)),ne=3e3;function U(e){return new Date(e.occurredAt??e.createdAt).getTime()}function re(e){if(e.kind!==`session`)return null;let t=e.payload?.session;return!t||t.type!==`narration`&&t.type!==`reasoning`&&t.type!==`tool`?null:{id:e.id,kind:t.type,label:typeof t.label==`string`?t.label:void 0,text:e.body,ts:U(e),turnId:typeof t.turnId==`string`?t.turnId:void 0}}function ie(e){if(e.kind!==`session`)return null;let t=e.payload?.session;if(t?.type!==`notice`)return null;let n=typeof t.label==`string`&&t.label?t.label:`compacted`;return{id:`notice-${e.id}`,status:n,timestamp:U(e)}}function ae(e){return e.kind===`system`&&e.from===`system`}function W(e){let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`}function oe(e){let t=e.filter(e=>te.has(e.status)).slice().sort((e,t)=>e.timestamp-t.timestamp),n=[];for(let e of t)n.some(t=>t.id===e.id)||n.some(t=>t.status===e.status&&Math.abs(t.timestamp-e.timestamp)<=ne)||n.push(e);return n}function se(e,t,n,r=[]){let i=[];for(let e of r){let t=e.entries.reduce((e,t)=>Math.min(e,N(t.originalCreatedAt)),1/0),n=Number.isFinite(t)?t-1:e.importedAt;i.push({ts:n,entry:{type:`import-boundary`,history:e,timestamp:n}});for(let t of e.entries)i.push({ts:N(t.originalCreatedAt),entry:{type:`imported-message`,history:e,entry:t}})}if(n){let e=new Date(n).getTime();Number.isFinite(e)&&i.push({ts:e,entry:{type:`created`,timestamp:e}})}let a=new Map;for(let t of e){if(t.kind!==`session`)continue;let e=t.payload?.session;if(e?.type===`response`&&typeof e.turnId==`string`){let n=a.get(e.turnId)??[];n.push(t.body.trim()),a.set(e.turnId,n)}}let o=[];for(let t of e){if(ae(t)){i.push({ts:U(t),entry:{type:`notice`,msg:t}});continue}let e=ie(t);if(e){o.push(e);continue}let n=re(t);if(n){if(n.kind===`narration`&&n.turnId&&a.get(n.turnId)?.some(e=>L(e,n.text)))continue;i.push({ts:n.ts,entry:{type:`activity`,steps:[n],timestamp:n.ts}});continue}i.push({ts:U(t),entry:{type:`message`,msg:t}})}for(let e of oe([...t,...o]))i.push({ts:e.timestamp,entry:{type:`status`,event:e}});let s={created:0,date:1,"import-boundary":2,"imported-message":3,message:4,activity:4,notice:4,status:5};i.sort((e,t)=>{let n=e.ts-t.ts;return Math.abs(n)<3e3&&s[e.entry.type]-s[t.entry.type]||n});let c=[],l=``;for(let{ts:e,entry:t}of i){if(t.type===`created`){c.push(t);continue}let n=W(e);if(n!==l&&(c.push({type:`date`,date:n,timestamp:e}),l=n),t.type===`activity`){let e=c[c.length-1];if(e&&e.type===`activity`&&ce(e,t)){e.steps.push(...t.steps);continue}}c.push(t)}return c}function ce(e,t){let n=e.steps[e.steps.length-1]?.turnId,r=t.steps[0]?.turnId;return n&&r?n===r:!n&&!r}function G(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/1024/1024).toFixed(1)} MB`}function le(e,t){if(t.startsWith(`/`))return t;let n=`${e.replace(/\/+$/,``)}/${t}`.split(`/`),r=[];for(let e of n)!e||e===`.`||(e===`..`?r.pop():r.push(e));return`/`+r.join(`/`)}function ue(e){let t=e.replace(/\/+$/,``),n=t.lastIndexOf(`/`);return n>0?t.slice(0,n):`/`}function de(e,t){return e.filter(e=>e.status===`online`&&j(t,e.baseDir)).sort((e,t)=>F(t.baseDir).length-F(e.baseDir).length)[0]||e.find(e=>e.status===`online`)}function fe(){return typeof window<`u`&&window.matchMedia(`(min-width: 1280px)`).matches}function K(){return typeof window<`u`&&!!window.getSelection()?.toString()}function pe(e){let t=e.payload?.attachments;return Array.isArray(t)?t.filter(e=>!!(e&&typeof e==`object`&&typeof e.artifactId==`string`)):[]}var me=[`👍`,`❤️`,`✅`,`👀`];function he(e){let t=new Map;for(let n of e.reactions||[]){let e=M(n.emoji),r=t.get(e)??{emoji:e,count:0,mine:!1,actors:[]};r.count+=1,r.mine=r.mine||n.actorId===`user`,r.actors.push(n.actorId),t.set(e,r)}return[...t.values()].sort((e,t)=>t.count-e.count||e.emoji.localeCompare(t.emoji))}function q(e){return I(e)}function ge(e,t){let n=e.readBy||[],r=e.resolvedToAgent||t||e.to,i=r?n.includes(r):!1,a=n.some(e=>e!==P);if(i||a){let e=i?r:n.find(e=>e!==P);return{label:`read`,title:e?`Read by ${e}`:`Read by agent`,tone:`ok`,icon:u}}if(e.deliveryStatus===`delivered`)return{label:`delivered`,title:`Delivered to agent inbox`,tone:`ok`,icon:u};if(e.deliveryStatus===`queued`)return{label:`queued`,title:`Queued until the target agent is available`,tone:`warn`,icon:x};if(e.deliveryStatus===`failed`||e.deliveryStatus===`dead`){let t=e.deliveryPoisonReason||e.deliveryLastError||e.deliveryStatus;return{label:e.deliveryStatus,title:t,tone:`danger`,icon:v}}return{label:`sent`,title:`Accepted by Relay`,tone:`muted`,icon:w}}function _e(e){let t=N(e.createdAt);return(e.reactions||[]).reduce((e,t)=>Math.max(e,N(t.updatedAt||t.createdAt)),t)}function ve(e){return e?e.messages.reduce((e,t)=>Math.max(e,_e(t)),0):0}function J(e){return new Date(e).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})}function ye(e){for(let t of e)t.previewUrl&&URL.revokeObjectURL(t.previewUrl)}function be(e,t,n,r){if(e?.teamId)return{teamId:e.teamId};let i=[...t];n&&!i.some(e=>e.id===n.id)&&i.push(n);let a=i.filter(e=>e.threadId).reverse(),o=a.find(e=>!!r[D(e.threadId,e.channel)])??a[0];return o?.threadId?{threadId:o.threadId,...o.channel?{channel:o.channel}:{}}:null}var Y=i(),xe={online:`text-emerald-400`,offline:`text-zinc-400`,shutdown:`text-zinc-400`,restarted:`text-blue-400`,"compaction-requested":`text-zinc-400`,compacting:`text-amber-400`,compacted:`text-amber-400`,"compaction-stalled":`text-red-400`,"clear-requested":`text-zinc-400`,"clearing-context":`text-amber-400`,"context-cleared":`text-amber-400`,"clear-stalled":`text-red-400`,"shutting-down":`text-zinc-400`};function Se(e){let t=new Date,[n,r,i]=e.split(`-`).map(Number),a=new Date(n,r-1,i);if(e===W(t.getTime()))return`Today`;let o=new Date(t);return o.setDate(o.getDate()-1),e===W(o.getTime())?`Yesterday`:a.toLocaleDateString(void 0,{weekday:`short`,month:`short`,day:`numeric`,year:a.getFullYear()===t.getFullYear()?void 0:`numeric`})}function Ce({event:e}){return(0,Y.jsxs)(`div`,{className:`flex items-center justify-center gap-2 py-2 my-1`,children:[(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`}),(0,Y.jsxs)(`div`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,Y.jsx)(a,{className:h(`w-2 h-2 fill-current`,xe[e.status]||`text-zinc-400`)}),(0,Y.jsx)(`span`,{children:H[e.status]||e.status}),(0,Y.jsx)(`span`,{className:`text-muted-foreground/60`,children:J(e.timestamp)})]}),(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}var we={"branch.landed":T,"context.warning":b},Te={"branch.landed":`branch landed`,"context.warning":`context warning`};function Ee({msg:e}){let t=typeof e.payload?.kind==`string`?e.payload.kind:``,n=we[t]??r,i=Te[t]??(t||`system signal`);return(0,Y.jsxs)(`div`,{className:`flex items-center justify-center gap-2 py-2 my-1`,children:[(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`}),(0,Y.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-full border border-border bg-muted/30 px-2.5 py-1 text-xs text-muted-foreground`,children:[(0,Y.jsx)(n,{className:`h-3 w-3`}),(0,Y.jsx)(`span`,{children:i}),(0,Y.jsx)(`span`,{className:`text-muted-foreground/60`,children:J(e.occurredAt??e.createdAt)})]}),(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function De({blockedLabel:e,onInterrupt:t}){return e?(0,Y.jsx)(`div`,{className:`flex justify-start mb-3`,children:(0,Y.jsxs)(`div`,{className:`flex items-center gap-2 rounded-2xl rounded-bl-sm bg-card ring-1 ring-red-500/30 px-4 py-2.5`,children:[(0,Y.jsx)(v,{className:`w-3.5 h-3.5 text-red-400`}),(0,Y.jsxs)(`span`,{className:`text-xs text-red-300`,children:[`blocked: `,e]})]})}):(0,Y.jsx)(`div`,{className:`flex justify-start mb-3`,children:(0,Y.jsxs)(`div`,{className:`flex items-center gap-2 rounded-2xl rounded-bl-sm bg-card ring-1 ring-foreground/10 px-4 py-2.5`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,Y.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-yellow-400 animate-[pulse_1.4s_ease-in-out_infinite]`}),(0,Y.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-yellow-400 animate-[pulse_1.4s_ease-in-out_0.2s_infinite]`}),(0,Y.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-yellow-400 animate-[pulse_1.4s_ease-in-out_0.4s_infinite]`})]}),(0,Y.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`working`}),t&&(0,Y.jsxs)(`button`,{onClick:t,title:`Interrupt`,className:`ml-1 flex items-center gap-1 rounded-full px-1.5 py-0.5 text-xs text-muted-foreground hover:text-red-300 hover:bg-red-500/10 transition-colors`,children:[(0,Y.jsx)(o,{className:`w-3.5 h-3.5`}),`Stop`]})]})})}var X=`agent-relay:chat-hide-tools`,Z=(()=>{let e=new Set,t=(()=>{try{return window.localStorage.getItem(X)===`on`}catch{return!1}})(),n=()=>e.forEach(e=>e());return typeof window<`u`&&window.addEventListener(`storage`,e=>{e.key===X&&(t=e.newValue===`on`,n())}),{subscribe(t){return e.add(t),()=>e.delete(t)},get:()=>t,toggle(){t=!t;try{window.localStorage.setItem(X,t?`on`:`off`)}catch{}n()}}})();function Oe(){return[(0,V.useSyncExternalStore)(Z.subscribe,Z.get,()=>!1),Z.toggle]}function Q({steps:e,showReasoning:t}){let[n,r]=Oe(),i=t?e:e.filter(e=>e.kind!==`reasoning`);if(!i.length)return null;let a=i.filter(e=>e.kind===`tool`).length;return(0,Y.jsx)(`div`,{className:`flex justify-start mb-2`,children:(0,Y.jsxs)(`div`,{className:`max-w-[85%] md:max-w-[75%] min-w-0 space-y-1.5`,children:[i.map(e=>e.kind===`narration`?(0,Y.jsx)(B,{text:e.text,className:`text-sm leading-relaxed break-words text-foreground/90 min-w-0`},e.id):e.kind===`reasoning`?(0,Y.jsxs)(`div`,{className:`flex items-start gap-1.5 text-xs leading-relaxed text-muted-foreground/80`,children:[(0,Y.jsx)(_,{className:`w-3.5 h-3.5 mt-0.5 shrink-0 opacity-70`}),(0,Y.jsx)(B,{text:e.text,className:`italic break-words min-w-0`})]},e.id):n?null:(0,Y.jsxs)(`div`,{className:`flex items-start gap-1.5 text-xs leading-relaxed text-muted-foreground`,children:[(0,Y.jsx)(d,{className:`w-3 h-3 mt-0.5 shrink-0 opacity-70`}),(0,Y.jsxs)(`span`,{className:`min-w-0 break-words`,children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:e.label||`tool`}),e.text?(0,Y.jsxs)(`span`,{className:`opacity-70`,children:[` — `,e.text]}):null]})]},e.id)),a>0&&(0,Y.jsxs)(`button`,{onClick:r,className:`flex items-center gap-1 text-[11px] text-muted-foreground/50 hover:text-muted-foreground transition-colors text-left`,children:[(0,Y.jsx)(p,{className:h(`w-3 h-3 shrink-0 transition-transform`,!n&&`rotate-90`)}),(0,Y.jsx)(`span`,{children:n?`show ${a} tool step${a===1?``:`s`}`:`hide tool steps`})]})]})})}function ke({date:e}){return(0,Y.jsxs)(`div`,{className:`flex items-center justify-center gap-3 py-3 my-1`,children:[(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`}),(0,Y.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:Se(e)}),(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function Ae({timestamp:e}){let t=new Date(e).toLocaleString(void 0,{month:`short`,day:`numeric`,year:`numeric`,hour:`2-digit`,minute:`2-digit`});return(0,Y.jsxs)(`div`,{className:`flex items-center justify-center gap-2 py-2 my-1`,children:[(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`}),(0,Y.jsxs)(`span`,{className:`text-xs text-muted-foreground/60`,children:[`created `,t]}),(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function je({history:e}){let t=e.sourceAgentLabel||e.sourcePeerId,n=e.entries.length;return(0,Y.jsxs)(`div`,{className:`flex items-center justify-center gap-2 py-2 my-1`,children:[(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`}),(0,Y.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-full border border-dashed border-border bg-muted/30 px-2 py-1 text-[11px] text-muted-foreground`,children:[(0,Y.jsx)(c,{className:`h-3 w-3`}),(0,Y.jsxs)(`span`,{children:[`forked history from `,t]}),(0,Y.jsxs)(`span`,{className:`text-muted-foreground/60`,children:[n,` `,n===1?`entry`:`entries`]})]}),(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function Me({entry:e,sourceLabel:t}){let n=e.message,r=A(n),i=e.originalFrom===P;return(0,Y.jsx)(`div`,{className:h(`flex mb-3 opacity-80`,i?`justify-end`:`justify-start`),children:(0,Y.jsx)(`div`,{className:`max-w-[85%] md:max-w-[75%]`,children:(0,Y.jsxs)(`div`,{className:h(`rounded-2xl border border-dashed px-3.5 py-2 text-sm select-text`,i?`border-primary/25 bg-primary/10 text-foreground rounded-br-sm`:`border-border bg-card/70 rounded-bl-sm`),children:[(0,Y.jsxs)(`div`,{className:h(`mb-1 text-[10px] uppercase tracking-normal`,i?`text-primary/70`:`text-muted-foreground`),children:[`forked history · `,i?`you`:t||e.originalFrom]}),(0,Y.jsx)(B,{text:r,rawBody:n.body,className:`leading-relaxed`}),(0,Y.jsxs)(`p`,{className:h(`mt-1 flex items-center justify-end gap-1.5 text-xs`,i?`text-primary/60`:`text-muted-foreground`),children:[(0,Y.jsxs)(`span`,{className:`opacity-40`,children:[`#`,e.originalMessageId]}),(0,Y.jsx)(`span`,{children:J(e.originalCreatedAt)})]})]})})})}function Ne({scrollRef:e,timeline:t}){let[n,r]=(0,V.useState)(!0),[i,a]=(0,V.useState)(null),[o,s]=(0,V.useState)(null),[c,l]=(0,V.useState)(!0),u=(0,V.useMemo)(()=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(!(!n||n.type!==`message`)&&n.msg.from===`user`)return{id:n.msg.id,body:A(n.msg)}}return null},[t]);if((0,V.useEffect)(()=>{let t=e.current;if(!u||!t){r(!0);return}let n=t.querySelector(`[data-msg-id="${u.id}"]`);if(!n){r(!0);return}let i=new IntersectionObserver(([e])=>{if(e&&(r(e.isIntersecting),!e.isIntersecting)){let n=e.rootBounds?.top??t.getBoundingClientRect().top;l(e.boundingClientRect.top<n)}},{root:t,threshold:0});i.observe(n);let a=()=>{let e=n.getBoundingClientRect(),r=t.getBoundingClientRect();l(e.top<r.top)};return t.addEventListener(`scroll`,a,{passive:!0}),()=>{i.disconnect(),t.removeEventListener(`scroll`,a)}},[u?.id,e]),n||!u||!u.body.trim())return null;let d=i?.id===u.id?i.value:!1,f=o?.id===u.id?o.value:!1;function p(){let t=e.current;!t||!u||t.querySelector(`[data-msg-id="${u.id}"]`)?.scrollIntoView({behavior:`smooth`,block:`center`})}let m=c?`↑`:`↓`;return f?(0,Y.jsx)(`div`,{className:`sticky top-0 z-10 -mx-3 md:-mx-4 -mt-3 md:-mt-4 bg-background`,children:(0,Y.jsxs)(`button`,{type:`button`,className:`w-full flex items-center justify-center gap-1.5 py-1 text-[11px] text-primary/60 hover:text-primary border-b border-primary/10 transition-colors`,onClick:()=>s({id:u.id,value:!1}),children:[(0,Y.jsx)(`span`,{children:`Your prompt`}),(0,Y.jsx)(y,{className:`w-3 h-3`})]})}):(0,Y.jsxs)(`div`,{className:`sticky top-0 z-10 -mx-3 md:-mx-4 -mt-3 md:-mt-4 px-2 md:px-3 pt-2 pb-1.5 bg-background border-b border-primary/10`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px] text-muted-foreground mb-0.5`,children:[(0,Y.jsx)(`span`,{className:`font-medium text-primary/70`,children:`Your prompt`}),(0,Y.jsxs)(`button`,{type:`button`,className:`ml-auto hover:text-foreground transition-colors`,onClick:p,children:[m,` scroll to original`]}),(0,Y.jsx)(`button`,{type:`button`,className:`hover:text-foreground transition-colors`,onClick:()=>s({id:u.id,value:!0}),title:`Minimize`,children:(0,Y.jsx)(C,{className:`w-3 h-3`})})]}),(0,Y.jsx)(`p`,{className:h(`text-sm text-foreground leading-snug cursor-pointer`,!d&&`line-clamp-2`),onClick:()=>a({id:u.id,value:!d}),children:u.body})]})}function Pe(){return(0,V.useSyncExternalStore)(e=>O.subscribe(e),()=>O.getPlayingKey(),()=>null)}function Fe({attachment:e,outbound:n}){let r=e.kind===`image`,i=e.title||e.artifactId,[a,o]=(0,V.useState)(null),[s,c]=(0,V.useState)(null),[l,u]=(0,V.useState)(!1),[d,p]=(0,V.useState)(!1);(0,V.useEffect)(()=>{let n=!1,r=null;async function i(){u(!0),c(null),o(null);try{let i=await t(`/artifacts/${encodeURIComponent(e.artifactId)}/content`);if(n)return;r=URL.createObjectURL(i),o(r)}catch(e){n||c(e.message)}finally{n||u(!1)}}return i(),()=>{n=!0,r&&URL.revokeObjectURL(r)}},[e.artifactId]);function _(){if(!a)return;let e=document.createElement(`a`);e.href=a,e.download=i,document.body.appendChild(e),e.click(),e.remove()}return r?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`button`,{type:`button`,onClick:()=>a&&p(!0),disabled:!a,className:`group/img mt-2 block overflow-hidden rounded-md border border-foreground/10 bg-black/10 text-left disabled:cursor-default relative`,children:a?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`img`,{src:a,alt:i,loading:`lazy`,className:`block max-h-72 max-w-full object-contain`}),(0,Y.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center bg-black/0 group-hover/img:bg-black/30 transition-colors`,children:(0,Y.jsx)(S,{className:`w-6 h-6 text-white opacity-0 group-hover/img:opacity-100 transition-opacity drop-shadow-md`})})]}):(0,Y.jsxs)(`span`,{className:h(`flex min-h-20 items-center gap-2 px-3 py-2 text-xs`,s?`text-red-400`:`text-muted-foreground`),children:[l?(0,Y.jsx)(m,{className:`h-4 w-4 animate-spin`}):(0,Y.jsx)(v,{className:`h-4 w-4`}),s||`Loading image`]})}),a&&(0,Y.jsx)(z,{open:d,onOpenChange:p,children:(0,Y.jsxs)(R,{className:`max-w-[95vw] max-h-[95vh] w-auto p-0 bg-black/95 border-zinc-800 gap-0 overflow-hidden`,showCloseButton:!1,children:[(0,Y.jsx)(ee,{className:`sr-only`,children:i}),(0,Y.jsxs)(`div`,{className:`relative flex items-center justify-center min-h-[200px]`,children:[(0,Y.jsx)(`img`,{src:a,alt:i,className:`max-w-[93vw] max-h-[90vh] object-contain`}),(0,Y.jsxs)(`div`,{className:`absolute top-2 right-2 flex gap-1`,children:[(0,Y.jsx)(`button`,{type:`button`,onClick:_,className:`rounded-md bg-black/60 hover:bg-black/80 p-2 text-white transition-colors`,title:`Download`,children:(0,Y.jsx)(E,{className:`w-4 h-4`})}),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>p(!1),className:`rounded-md bg-black/60 hover:bg-black/80 p-2 text-white transition-colors`,title:`Close`,children:(0,Y.jsx)(f,{className:`w-4 h-4`})})]})]})]})})]}):(0,Y.jsxs)(`button`,{type:`button`,onClick:_,disabled:!a,className:h(`mt-2 flex w-full items-center gap-2 rounded-md border px-2.5 py-2 text-left text-xs transition-colors disabled:cursor-default disabled:opacity-70`,n?`border-primary-foreground/20 bg-primary-foreground/10 hover:bg-primary-foreground/15`:`border-border bg-background hover:bg-muted`),children:[l?(0,Y.jsx)(m,{className:`h-4 w-4 shrink-0 animate-spin`}):s?(0,Y.jsx)(v,{className:`h-4 w-4 shrink-0 text-red-400`}):(0,Y.jsx)(g,{className:`h-4 w-4 shrink-0`}),(0,Y.jsx)(`span`,{className:h(`min-w-0 flex-1 truncate`,s&&`text-red-400`),children:s||i}),(0,Y.jsx)(E,{className:`h-3.5 w-3.5 shrink-0`})]})}function $({open:e,onToggle:t,onReact:n}){return(0,Y.jsxs)(`div`,{className:`relative shrink-0`,children:[(0,Y.jsx)(`button`,{type:`button`,title:`Add reaction`,onClick:t,className:h(`inline-flex h-5 w-6 items-center justify-center rounded-full border border-border bg-popover text-muted-foreground shadow-sm transition hover:bg-muted hover:text-foreground`,e?`opacity-100`:`opacity-0 pointer-events-none md:group-hover/msg:opacity-100 md:group-hover/msg:pointer-events-auto`),children:(0,Y.jsx)(s,{className:`h-3 w-3`})}),e&&(0,Y.jsx)(`div`,{className:`absolute bottom-full left-0 z-30 mb-1 flex gap-0.5 rounded-full border border-border bg-popover p-0.5 shadow-md`,children:me.map(e=>(0,Y.jsx)(`button`,{type:`button`,title:`React ${e}`,onClick:()=>n(e),className:`inline-flex h-6 w-7 items-center justify-center rounded-full text-xs transition-colors hover:bg-muted`,children:e},e))})]})}var Ie=(0,V.memo)(function({msg:e,peer:t,onOpenReferencedPath:n,onPreviewReferencedPath:r,onPreviewReferencedPathEnd:i}){let a=e.from!==`user`&&e.to!==`user`,s=a?e.from===t:e.from===P,c=a?s?`→ ${e.to}`:`from ${e.from}`:null,u=k(e=>e.reactToMessage),d=k(e=>e.voiceTtsEnabled),f=Pe(),p=k(e=>{let n=e.agentsById[t]?.meta?.cwd;return typeof n==`string`?n:``}),[m,g]=(0,V.useState)(!1),_=(0,V.useRef)(null),v=(0,V.useRef)(null),y=(0,V.useRef)(!1),b=A(e),x=J(e.occurredAt??e.createdAt),S=pe(e),C=he(e),w=s?ge(e,t):null,T=w?.icon,E=f===String(e.id),D=d&&!s&&!a&&!q(e)&&b.trim().length>0;function j(t){t.stopPropagation(),E?O.bargeIn():O.speak(e.body,String(e.id))}(0,V.useEffect)(()=>{if(!m)return;function e(e){K()||_.current&&!_.current.contains(e.target)&&g(!1)}return document.addEventListener(`mousedown`,e),document.addEventListener(`touchstart`,e),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`touchstart`,e)}},[m]);function M(e){return le(p||`/`,e)}function N(e,t){let r=M(e);n?.(r,t)}function F(e,t,n){let i=M(e);r?.(i,t,n)}function I(t){u(e,t),g(!1)}function L(e){e.button===0&&(v.current={x:e.clientX,y:e.clientY},y.current=!1)}function R(e){let t=v.current;t&&(Math.abs(e.clientX-t.x)>3||Math.abs(e.clientY-t.y)>3)&&(y.current=!0)}function z(t){if(!(q(e)||s||a)&&!t.target.closest(`a,button,input,textarea,select,[role="button"]`)){if(y.current||K()){y.current=!1;return}g(e=>!e)}}return(0,Y.jsx)(`div`,{"data-msg-id":e.id,className:h(`group/msg flex mb-3`,s?`justify-end`:`justify-start`),children:(0,Y.jsxs)(`div`,{ref:_,className:`relative max-w-[85%] md:max-w-[75%]`,children:[D&&(0,Y.jsx)(`button`,{type:`button`,title:E?`Stop playback`:`Play aloud`,onClick:j,className:h(`absolute -top-2 -right-2 z-20 inline-flex h-6 w-6 items-center justify-center rounded-full border bg-popover shadow-sm transition`,E?`border-primary/50 text-primary opacity-100`:`border-border text-muted-foreground opacity-70 hover:bg-muted hover:text-foreground hover:opacity-100 [@media(hover:hover)]:md:opacity-0 [@media(hover:hover)]:md:group-hover/msg:opacity-100`),children:E?(0,Y.jsx)(o,{className:`h-3.5 w-3.5 animate-pulse`}):(0,Y.jsx)(l,{className:`h-3.5 w-3.5`})}),(0,Y.jsxs)(`div`,{className:h(`rounded-2xl px-3.5 py-2 text-sm select-text`,!s&&!q(e)&&!a&&`cursor-pointer`,s?`bg-primary text-primary-foreground rounded-br-sm`:`bg-card ring-1 ring-foreground/10 rounded-bl-sm`),onPointerDown:L,onPointerMove:R,onClick:z,children:[c&&(0,Y.jsx)(`p`,{className:h(`text-xs font-medium mb-1 opacity-60`,s?`text-primary-foreground`:`text-muted-foreground`),children:c}),e.subject&&(0,Y.jsx)(`p`,{className:h(`text-xs font-semibold mb-1`,s?`text-primary-foreground/70`:`text-muted-foreground`),children:e.subject}),(0,Y.jsx)(B,{text:b,rawBody:e.body,className:`leading-relaxed`,onOpenPath:N,onPreviewPath:F,onPreviewPathEnd:i,resolvePathTitle:(e,t)=>`${M(e)}${t?`:${t}`:``}`}),S.map(t=>(0,Y.jsx)(Fe,{attachment:t,outbound:s},`${e.id}-${t.artifactId}-${t.role||``}`)),(0,Y.jsxs)(`p`,{className:h(`text-xs mt-1 flex items-center gap-1.5`,s?`justify-end text-primary-foreground/60`:`justify-end text-muted-foreground`),children:[(0,Y.jsxs)(`span`,{className:`opacity-40`,children:[`#`,e.id]}),(0,Y.jsx)(`span`,{children:x}),w&&T&&(0,Y.jsxs)(`span`,{className:h(`inline-flex items-center gap-1`,w.tone===`ok`&&`text-emerald-300`,w.tone===`warn`&&`text-amber-200`,w.tone===`danger`&&`text-red-200`),title:w.title,children:[(0,Y.jsx)(T,{className:`h-3 w-3`}),w.label]})]})]}),!q(e)&&C.length>0&&(0,Y.jsxs)(`div`,{className:h(`flex flex-wrap items-center gap-0.5 -mt-1 relative z-10`,s?`justify-end pr-2`:`justify-start pl-2`),children:[!s&&(0,Y.jsx)($,{open:m,onToggle:()=>g(e=>!e),onReact:I}),C.map(e=>(0,Y.jsxs)(`button`,{type:`button`,title:e.actors.join(`, `),onClick:()=>I(e.emoji),className:h(`inline-flex h-5 items-center gap-0.5 rounded-full border px-1.5 text-[11px] shadow-sm transition-colors`,e.mine?`border-primary/40 bg-primary/10 text-primary`:`border-border bg-background hover:bg-muted text-foreground`),children:[(0,Y.jsx)(`span`,{children:e.emoji}),e.count>1&&(0,Y.jsx)(`span`,{children:e.count})]},e.emoji))]}),!q(e)&&!s&&C.length===0&&(0,Y.jsx)(`div`,{className:`absolute -bottom-2.5 left-1 z-20`,children:(0,Y.jsx)($,{open:m,onToggle:()=>g(e=>!e),onReact:I})})]})})});export{ve as _,ke as a,Ee as c,G as d,de as f,fe as g,ye as h,Ae as i,Ce as l,be as m,Q as n,je as o,ue as p,De as r,Me as s,Ie as t,Ne as u,se as v};
2
+ //# sourceMappingURL=MessageBubble-BqFAi9gS.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"MessageBubble-DmZIqnga.js","names":[],"sources":["../../dashboard/src/components/chat/sessionTrace.ts","../../dashboard/src/components/chat/helpers.ts","../../dashboard/src/components/chat/TraceView.tsx","../../dashboard/src/components/chat/hooks/useTtsPlayingKey.ts","../../dashboard/src/components/chat/MessageBubble.tsx"],"sourcesContent":["\nimport { toTimestamp, responseBodyContainsBlock } from '@/lib/display'\nimport type { ChatStatusEvent as StatusEvent } from '@/store'\nimport type { ChatHistoryImport, ChatHistoryImportEntry, Message } from '@/types'\n\nexport interface ActivityStep { id: number; kind: 'narration' | 'reasoning' | 'tool'; label?: string; text: string; ts: number; turnId?: string }\n\nexport type TimelineEntry =\n | { type: 'message'; msg: Message }\n | { type: 'notice'; msg: Message }\n | { type: 'activity'; steps: ActivityStep[]; timestamp: number }\n | { type: 'import-boundary'; history: ChatHistoryImport; timestamp: number }\n | { type: 'imported-message'; history: ChatHistoryImport; entry: ChatHistoryImportEntry }\n | { type: 'status'; event: StatusEvent }\n | { type: 'date'; date: string; timestamp: number }\n | { type: 'created'; timestamp: number }\n\nexport const TIMELINE_STATUS_LABELS: Record<string, string> = {\n online: 'came online',\n offline: 'went offline',\n shutdown: 'shut down',\n restarted: 'restarted',\n 'compaction-requested': 'compaction requested',\n compacting: 'compaction started',\n compacted: 'context compacted',\n 'compaction-stalled': 'compaction stalled — may need manual intervention',\n 'clear-requested': 'clear requested',\n 'clearing-context': 'clear started',\n 'context-cleared': 'context cleared',\n 'clear-stalled': 'context clear stalled — may need manual intervention',\n 'shutting-down': 'shutting down',\n}\n\nconst TIMELINE_STATUSES = new Set(Object.keys(TIMELINE_STATUS_LABELS))\nconst STATUS_DEDUPE_WINDOW_MS = 3000\n\n// True event time of a message: occurredAt (set when a Runner backfilled a message it had\n// queued during an outage, #196) falling back to the server receive time. Used for chat\n// timeline ordering + display so a backfilled turn lands where it actually happened in the\n// conversation, not at the bottom. Display-only — DB poll cursors still use created_at.\nexport function messageEventTime(msg: Message): number {\n return new Date(msg.occurredAt ?? msg.createdAt).getTime()\n}\n\n// Narration/reasoning/tool session events are mirrored as `kind:\"session\"` messages\n// but must not become chat bubbles — they render inline in the turn's activity trace.\n// (`narration` = the agent's intermediate spoken text; `reasoning` = its thinking.)\nexport function sessionActivityStep(msg: Message): ActivityStep | null {\n if (msg.kind !== 'session') return null\n const s = msg.payload?.session as { type?: string; label?: string; turnId?: string } | undefined\n if (!s || (s.type !== 'narration' && s.type !== 'reasoning' && s.type !== 'tool')) return null\n return {\n id: msg.id,\n kind: s.type,\n label: typeof s.label === 'string' ? s.label : undefined,\n text: msg.body,\n ts: messageEventTime(msg),\n turnId: typeof s.turnId === 'string' ? s.turnId : undefined,\n }\n}\n\n// A `notice` session event (e.g. the runner's durable \"context compacted\" marker) renders\n// as a discreet timeline marker, reusing the StatusMarker path. Its `label` carries a\n// timeline-status key (e.g. \"compacted\"); we surface it as a StatusEvent so it dedupes with\n// the ephemeral live timeline-status decoration and survives a reload (the ephemeral one does\n// not). Returns null for non-notice messages or labels we don't render.\nexport function sessionNoticeStatusEvent(msg: Message): StatusEvent | null {\n if (msg.kind !== 'session') return null\n const s = msg.payload?.session as { type?: string; label?: string } | undefined\n if (s?.type !== 'notice') return null\n const status = typeof s.label === 'string' && s.label ? s.label : 'compacted'\n return { id: `notice-${msg.id}`, status, timestamp: messageEventTime(msg) }\n}\n\n// Bus-level system signals (kind:\"system\", from:\"system\") — e.g. branch.landed,\n// context.warning. Rendered as notice pills, NOT chat bubbles or session status markers.\nexport function isBusSignalMessage(msg: Message): boolean {\n return msg.kind === 'system' && msg.from === 'system'\n}\n\nexport function dateKey(ts: number): string {\n const d = new Date(ts)\n return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`\n}\n\nexport function dedupeStatusEvents(statusEvents: StatusEvent[]): StatusEvent[] {\n const events = statusEvents\n .filter((event) => TIMELINE_STATUSES.has(event.status))\n .slice()\n .sort((a, b) => a.timestamp - b.timestamp)\n const result: StatusEvent[] = []\n for (const event of events) {\n if (result.some((existing) => existing.id === event.id)) continue\n if (result.some((existing) => existing.status === event.status && Math.abs(existing.timestamp - event.timestamp) <= STATUS_DEDUPE_WINDOW_MS)) continue\n result.push(event)\n }\n return result\n}\n\nexport function buildTimeline(messages: Message[], statusEvents: StatusEvent[], createdAt?: string | number | null, importedHistory: ChatHistoryImport[] = []): TimelineEntry[] {\n const raw: Array<{ ts: number; entry: TimelineEntry }> = []\n\n for (const history of importedHistory) {\n const firstImportedAt = history.entries.reduce((min, entry) => Math.min(min, toTimestamp(entry.originalCreatedAt)), Number.POSITIVE_INFINITY)\n const boundaryAt = Number.isFinite(firstImportedAt) ? firstImportedAt - 1 : history.importedAt\n raw.push({ ts: boundaryAt, entry: { type: 'import-boundary', history, timestamp: boundaryAt } })\n for (const entry of history.entries) {\n raw.push({ ts: toTimestamp(entry.originalCreatedAt), entry: { type: 'imported-message', history, entry } })\n }\n }\n\n if (createdAt) {\n const ts = new Date(createdAt as string).getTime()\n if (Number.isFinite(ts)) raw.push({ ts, entry: { type: 'created', timestamp: ts } })\n }\n\n // The closing response bubble (session type \"response\") repeats the turn's\n // narration. In `final` capture mode the body is just the final line; in `full`\n // mode it is every narration block joined with blank-line separators\n // (matching extractLastAssistantTurn).\n // Collect the response bodies per turn so a narration step is suppressed from the\n // trace whenever it appears as a blank-line-delimited block of the body — so no line\n // shows twice in either mode (final: only the matching final line; full: all of them).\n const responseBodiesByTurn = new Map<string, string[]>()\n for (const msg of messages) {\n if (msg.kind !== 'session') continue\n const s = msg.payload?.session as { type?: string; turnId?: string } | undefined\n if (s?.type === 'response' && typeof s.turnId === 'string') {\n const list = responseBodiesByTurn.get(s.turnId) ?? []\n list.push(msg.body.trim())\n responseBodiesByTurn.set(s.turnId, list)\n }\n }\n\n const noticeStatusEvents: StatusEvent[] = []\n for (const msg of messages) {\n if (isBusSignalMessage(msg)) {\n raw.push({ ts: messageEventTime(msg), entry: { type: 'notice', msg } })\n continue\n }\n const notice = sessionNoticeStatusEvent(msg)\n if (notice) {\n noticeStatusEvents.push(notice)\n continue\n }\n const step = sessionActivityStep(msg)\n if (step) {\n if (step.kind === 'narration' && step.turnId) {\n const bodies = responseBodiesByTurn.get(step.turnId)\n if (bodies?.some((body) => responseBodyContainsBlock(body, step.text))) continue\n }\n raw.push({ ts: step.ts, entry: { type: 'activity', steps: [step], timestamp: step.ts } })\n continue\n }\n raw.push({ ts: messageEventTime(msg), entry: { type: 'message', msg } })\n }\n for (const event of dedupeStatusEvents([...statusEvents, ...noticeStatusEvents])) {\n raw.push({ ts: event.timestamp, entry: { type: 'status', event } })\n }\n\n const typeOrder = { created: 0, date: 1, 'import-boundary': 2, 'imported-message': 3, message: 4, activity: 4, notice: 4, status: 5 } as const\n raw.sort((a, b) => {\n const dt = a.ts - b.ts\n if (Math.abs(dt) < 3000) return typeOrder[a.entry.type] - typeOrder[b.entry.type] || dt\n return dt\n })\n\n const entries: TimelineEntry[] = []\n let lastDate = ''\n for (const { ts, entry } of raw) {\n if (entry.type === 'created') {\n entries.push(entry)\n continue\n }\n const dk = dateKey(ts)\n if (dk !== lastDate) {\n entries.push({ type: 'date', date: dk, timestamp: ts })\n lastDate = dk\n }\n // Coalesce consecutive activity steps from the same turn into one trace.\n if (entry.type === 'activity') {\n const prev = entries[entries.length - 1]\n if (prev && prev.type === 'activity' && sameActivityTurn(prev, entry)) {\n prev.steps.push(...entry.steps)\n continue\n }\n }\n entries.push(entry)\n }\n\n return entries\n}\n\nexport function sameActivityTurn(a: Extract<TimelineEntry, { type: 'activity' }>, b: Extract<TimelineEntry, { type: 'activity' }>): boolean {\n const at = a.steps[a.steps.length - 1]?.turnId\n const bt = b.steps[0]?.turnId\n if (at && bt) return at === bt\n // No turn id on either side: group adjacent steps regardless.\n return !at && !bt\n}\n","\nimport { AlertCircle, Check, CheckCheck, Clock } from 'lucide-react'\nimport { HUMAN_AGENT_ID } from '@/lib/constants'\nimport {\n isReactionEventMessage,\n normalizePathForCompare,\n normalizeReactionEmoji,\n pathWithinBase,\n toTimestamp,\n} from '@/lib/display'\nimport { planLookupKey } from '@/store/slices/plans'\nimport type { Agent, AttachmentRef, InboxThread, Message, Orchestrator, Plan } from '@/types'\nimport type { PendingAttachment } from './types'\n\nexport function formatBytes(size: number): string {\n if (size < 1024) return `${size} B`\n if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`\n return `${(size / 1024 / 1024).toFixed(1)} MB`\n}\n\nexport function resolveRelativePath(cwd: string, path: string): string {\n if (path.startsWith('/')) return path\n const parts = `${cwd.replace(/\\/+$/, '')}/${path}`.split('/')\n const stack: string[] = []\n for (const part of parts) {\n if (!part || part === '.') continue\n if (part === '..') stack.pop()\n else stack.push(part)\n }\n return '/' + stack.join('/')\n}\n\nexport function parentPath(path: string): string {\n const trimmed = path.replace(/\\/+$/, '')\n const index = trimmed.lastIndexOf('/')\n return index > 0 ? trimmed.slice(0, index) : '/'\n}\n\nexport function orchestratorForFilePreview(orchestrators: Orchestrator[], path: string): Orchestrator | undefined {\n return orchestrators\n .filter((orch) => orch.status === 'online' && pathWithinBase(path, orch.baseDir))\n .sort((a, b) => normalizePathForCompare(b.baseDir).length - normalizePathForCompare(a.baseDir).length)[0] ||\n orchestrators.find((orch) => orch.status === 'online')\n}\n\nexport function supportsSideFilePreview(): boolean {\n return typeof window !== 'undefined' && window.matchMedia('(min-width: 1280px)').matches\n}\n\nexport function hasActiveTextSelection(): boolean {\n return typeof window !== 'undefined' && Boolean(window.getSelection()?.toString())\n}\n\nexport function messageAttachments(msg: Message): AttachmentRef[] {\n const attachments = msg.payload?.attachments\n if (!Array.isArray(attachments)) return []\n return attachments.filter((item): item is AttachmentRef => Boolean(item && typeof item === 'object' && typeof (item as AttachmentRef).artifactId === 'string'))\n}\n\nexport const QUICK_REACTIONS = ['👍', '❤️', '✅', '👀'] as const\n\nexport function groupedReactions(msg: Message): Array<{ emoji: string; count: number; mine: boolean; actors: string[] }> {\n const groups = new Map<string, { emoji: string; count: number; mine: boolean; actors: string[] }>()\n for (const reaction of msg.reactions || []) {\n const emoji = normalizeReactionEmoji(reaction.emoji)\n const current = groups.get(emoji) ?? { emoji, count: 0, mine: false, actors: [] }\n current.count += 1\n current.mine = current.mine || reaction.actorId === HUMAN_AGENT_ID\n current.actors.push(reaction.actorId)\n groups.set(emoji, current)\n }\n return [...groups.values()].sort((a, b) => b.count - a.count || a.emoji.localeCompare(b.emoji))\n}\n\nexport function isReactionEvent(msg: Message): boolean {\n return isReactionEventMessage(msg)\n}\n\nexport function outboundReceipt(msg: Message, peer: string): { label: string; title: string; tone: 'muted' | 'ok' | 'warn' | 'danger'; icon: typeof Check } {\n const readBy = msg.readBy || []\n const expectedReader = msg.resolvedToAgent || peer || msg.to\n const readByExpected = expectedReader ? readBy.includes(expectedReader) : false\n const readBySomeone = readBy.some((id) => id !== HUMAN_AGENT_ID)\n if (readByExpected || readBySomeone) {\n const reader = readByExpected ? expectedReader : readBy.find((id) => id !== HUMAN_AGENT_ID)\n return { label: 'read', title: reader ? `Read by ${reader}` : 'Read by agent', tone: 'ok', icon: CheckCheck }\n }\n if (msg.deliveryStatus === 'delivered') {\n return { label: 'delivered', title: 'Delivered to agent inbox', tone: 'ok', icon: CheckCheck }\n }\n if (msg.deliveryStatus === 'queued') {\n return { label: 'queued', title: 'Queued until the target agent is available', tone: 'warn', icon: Clock }\n }\n if (msg.deliveryStatus === 'failed' || msg.deliveryStatus === 'dead') {\n const detail = msg.deliveryPoisonReason || msg.deliveryLastError || msg.deliveryStatus\n return { label: msg.deliveryStatus, title: detail, tone: 'danger', icon: AlertCircle }\n }\n return { label: 'sent', title: 'Accepted by Relay', tone: 'muted', icon: Check }\n}\n\nexport function messageActivityTimestamp(msg: Message): number {\n const messageAt = toTimestamp(msg.createdAt)\n return (msg.reactions || []).reduce((latest, reaction) => {\n return Math.max(latest, toTimestamp(reaction.updatedAt || reaction.createdAt))\n }, messageAt)\n}\n\nexport function threadActivityTimestamp(thread: InboxThread | undefined): number {\n if (!thread) return 0\n return thread.messages.reduce((latest, msg) => Math.max(latest, messageActivityTimestamp(msg)), 0)\n}\n\nexport function chatTimestamp(iso: string | number): string {\n const d = new Date(iso as string)\n return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })\n}\n\nexport function revokePendingAttachmentUrls(items: PendingAttachment[]): void {\n for (const item of items) if (item.previewUrl) URL.revokeObjectURL(item.previewUrl)\n}\n\ntype ChatPlanContext = { threadId: string | number; channel?: string } | { teamId: string; channel?: string }\n\nexport function resolveChatPlanContext(\n agent: Agent | null,\n messages: Message[],\n lastMessage: Message | null | undefined,\n plansByThread: Record<string, Plan | null>,\n): ChatPlanContext | null {\n if (agent?.teamId) return { teamId: agent.teamId }\n const ordered = [...messages]\n if (lastMessage && !ordered.some((message) => message.id === lastMessage.id)) ordered.push(lastMessage)\n const threaded = ordered.filter((message) => message.threadId).reverse()\n const knownPlanMessage = threaded.find((message) => Boolean(plansByThread[planLookupKey(message.threadId!, message.channel)]))\n const selected = knownPlanMessage ?? threaded[0]\n if (!selected?.threadId) return null\n return {\n threadId: selected.threadId,\n ...(selected.channel ? { channel: selected.channel } : {}),\n }\n}\n","\nimport { useEffect, useMemo, useState, useSyncExternalStore } from 'react'\nimport type React from 'react'\nimport { AlertCircle, AlertTriangle, Brain, ChevronDown, ChevronRight, ChevronUp, Circle, CircleStop, GitFork, GitMerge, Radio, Terminal } from 'lucide-react'\nimport type { LucideIcon } from 'lucide-react'\nimport { FormattedBody } from '@/components/shared/formatted-body'\nimport { HUMAN_AGENT_ID } from '@/lib/constants'\nimport { messageBody } from '@/lib/display'\nimport type { ChatHistoryImport, ChatHistoryImportEntry } from '@/types'\nimport { cn } from '@/lib/utils'\nimport { chatTimestamp } from './helpers'\nimport { dateKey, TIMELINE_STATUS_LABELS, type ActivityStep, type TimelineEntry } from './sessionTrace'\nimport type { Message } from '@/types'\nimport type { ChatStatusEvent as StatusEvent } from '@/store'\n\nconst TIMELINE_STATUS_COLORS: Record<string, string> = {\n online: 'text-emerald-400',\n offline: 'text-zinc-400',\n shutdown: 'text-zinc-400',\n restarted: 'text-blue-400',\n 'compaction-requested': 'text-zinc-400',\n compacting: 'text-amber-400',\n compacted: 'text-amber-400',\n 'compaction-stalled': 'text-red-400',\n 'clear-requested': 'text-zinc-400',\n 'clearing-context': 'text-amber-400',\n 'context-cleared': 'text-amber-400',\n 'clear-stalled': 'text-red-400',\n 'shutting-down': 'text-zinc-400',\n}\n\nfunction dateSeparatorLabel(dateStr: string): string {\n const today = new Date()\n const [y, m, d] = dateStr.split('-').map(Number)\n const target = new Date(y!, m! - 1, d)\n const todayKey = dateKey(today.getTime())\n if (dateStr === todayKey) return 'Today'\n const yesterday = new Date(today)\n yesterday.setDate(yesterday.getDate() - 1)\n if (dateStr === dateKey(yesterday.getTime())) return 'Yesterday'\n return target.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric', year: target.getFullYear() !== today.getFullYear() ? 'numeric' : undefined })\n}\n\nexport function StatusMarker({ event }: { event: StatusEvent }) {\n return (\n <div className=\"flex items-center justify-center gap-2 py-2 my-1\">\n <div className=\"h-px flex-1 bg-border\" />\n <div className=\"flex items-center gap-1.5 text-xs text-muted-foreground\">\n <Circle className={cn('w-2 h-2 fill-current', TIMELINE_STATUS_COLORS[event.status] || 'text-zinc-400')} />\n <span>{TIMELINE_STATUS_LABELS[event.status] || event.status}</span>\n <span className=\"text-muted-foreground/60\">{chatTimestamp(event.timestamp)}</span>\n </div>\n <div className=\"h-px flex-1 bg-border\" />\n </div>\n )\n}\n\nconst BUS_SIGNAL_ICON: Record<string, LucideIcon> = {\n 'branch.landed': GitMerge,\n 'context.warning': AlertTriangle,\n}\n\nconst BUS_SIGNAL_LABEL: Record<string, string> = {\n 'branch.landed': 'branch landed',\n 'context.warning': 'context warning',\n}\n\nexport function NoticePill({ msg }: { msg: Message }) {\n const signalKind = typeof msg.payload?.kind === 'string' ? msg.payload.kind : ''\n const Icon: LucideIcon = BUS_SIGNAL_ICON[signalKind] ?? Radio\n const label = BUS_SIGNAL_LABEL[signalKind] ?? (signalKind || 'system signal')\n return (\n <div className=\"flex items-center justify-center gap-2 py-2 my-1\">\n <div className=\"h-px flex-1 bg-border\" />\n <div className=\"flex items-center gap-1.5 rounded-full border border-border bg-muted/30 px-2.5 py-1 text-xs text-muted-foreground\">\n <Icon className=\"h-3 w-3\" />\n <span>{label}</span>\n <span className=\"text-muted-foreground/60\">{chatTimestamp(msg.occurredAt ?? (msg.createdAt as string))}</span>\n </div>\n <div className=\"h-px flex-1 bg-border\" />\n </div>\n )\n}\n\nexport function BusyIndicator({ blockedLabel, onInterrupt }: { blockedLabel?: string; onInterrupt?: () => void }) {\n if (blockedLabel) {\n return (\n <div className=\"flex justify-start mb-3\">\n <div className=\"flex items-center gap-2 rounded-2xl rounded-bl-sm bg-card ring-1 ring-red-500/30 px-4 py-2.5\">\n <AlertCircle className=\"w-3.5 h-3.5 text-red-400\" />\n <span className=\"text-xs text-red-300\">blocked: {blockedLabel}</span>\n </div>\n </div>\n )\n }\n\n return (\n <div className=\"flex justify-start mb-3\">\n <div className=\"flex items-center gap-2 rounded-2xl rounded-bl-sm bg-card ring-1 ring-foreground/10 px-4 py-2.5\">\n <div className=\"flex items-center gap-1\">\n <span className=\"w-1.5 h-1.5 rounded-full bg-yellow-400 animate-[pulse_1.4s_ease-in-out_infinite]\" />\n <span className=\"w-1.5 h-1.5 rounded-full bg-yellow-400 animate-[pulse_1.4s_ease-in-out_0.2s_infinite]\" />\n <span className=\"w-1.5 h-1.5 rounded-full bg-yellow-400 animate-[pulse_1.4s_ease-in-out_0.4s_infinite]\" />\n </div>\n <span className=\"text-xs text-muted-foreground\">working</span>\n {onInterrupt && (\n <button\n onClick={onInterrupt}\n title=\"Interrupt\"\n className=\"ml-1 flex items-center gap-1 rounded-full px-1.5 py-0.5 text-xs text-muted-foreground hover:text-red-300 hover:bg-red-500/10 transition-colors\"\n >\n <CircleStop className=\"w-3.5 h-3.5\" />\n Stop\n </button>\n )}\n </div>\n </div>\n )\n}\n\nconst HIDE_TOOLS_KEY = 'agent-relay:chat-hide-tools'\nconst hideToolsStore = (() => {\n const listeners = new Set<() => void>()\n let value = (() => {\n try {\n return window.localStorage.getItem(HIDE_TOOLS_KEY) === 'on'\n } catch {\n return false\n }\n })()\n const emit = () => listeners.forEach((l) => l())\n if (typeof window !== 'undefined') {\n window.addEventListener('storage', (e) => {\n if (e.key !== HIDE_TOOLS_KEY) return\n value = e.newValue === 'on'\n emit()\n })\n }\n return {\n subscribe(cb: () => void) {\n listeners.add(cb)\n return () => listeners.delete(cb)\n },\n get: () => value,\n toggle() {\n value = !value\n try {\n window.localStorage.setItem(HIDE_TOOLS_KEY, value ? 'on' : 'off')\n } catch {}\n emit()\n },\n }\n})()\n\nfunction useHideTools(): [boolean, () => void] {\n const hideTools = useSyncExternalStore(hideToolsStore.subscribe, hideToolsStore.get, () => false)\n return [hideTools, hideToolsStore.toggle]\n}\n\nexport function ActivityTrace({ steps, showReasoning }: { steps: ActivityStep[]; showReasoning: boolean }) {\n const [hideTools, toggleHideTools] = useHideTools()\n const visible = showReasoning ? steps : steps.filter((s) => s.kind !== 'reasoning')\n if (!visible.length) return null\n const toolCount = visible.filter((s) => s.kind === 'tool').length\n return (\n <div className=\"flex justify-start mb-2\">\n <div className=\"max-w-[85%] md:max-w-[75%] min-w-0 space-y-1.5\">\n {visible.map((step) => {\n if (step.kind === 'narration') {\n return (\n <FormattedBody\n key={step.id}\n text={step.text}\n className=\"text-sm leading-relaxed break-words text-foreground/90 min-w-0\"\n />\n )\n }\n if (step.kind === 'reasoning') {\n return (\n <div key={step.id} className=\"flex items-start gap-1.5 text-xs leading-relaxed text-muted-foreground/80\">\n <Brain className=\"w-3.5 h-3.5 mt-0.5 shrink-0 opacity-70\" />\n <FormattedBody text={step.text} className=\"italic break-words min-w-0\" />\n </div>\n )\n }\n if (hideTools) return null\n return (\n <div key={step.id} className=\"flex items-start gap-1.5 text-xs leading-relaxed text-muted-foreground\">\n <Terminal className=\"w-3 h-3 mt-0.5 shrink-0 opacity-70\" />\n <span className=\"min-w-0 break-words\">\n <span className=\"font-medium\">{step.label || 'tool'}</span>\n {step.text ? <span className=\"opacity-70\"> — {step.text}</span> : null}\n </span>\n </div>\n )\n })}\n {toolCount > 0 && (\n <button\n onClick={toggleHideTools}\n className=\"flex items-center gap-1 text-[11px] text-muted-foreground/50 hover:text-muted-foreground transition-colors text-left\"\n >\n <ChevronRight className={cn('w-3 h-3 shrink-0 transition-transform', !hideTools && 'rotate-90')} />\n <span>{hideTools ? `show ${toolCount} tool step${toolCount === 1 ? '' : 's'}` : 'hide tool steps'}</span>\n </button>\n )}\n </div>\n </div>\n )\n}\n\nexport function DateSeparator({ date }: { date: string }) {\n return (\n <div className=\"flex items-center justify-center gap-3 py-3 my-1\">\n <div className=\"h-px flex-1 bg-border\" />\n <span className=\"text-xs font-medium text-muted-foreground\">{dateSeparatorLabel(date)}</span>\n <div className=\"h-px flex-1 bg-border\" />\n </div>\n )\n}\n\nexport function CreatedMarker({ timestamp }: { timestamp: number }) {\n const d = new Date(timestamp)\n const label = d.toLocaleString(undefined, { month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit' })\n return (\n <div className=\"flex items-center justify-center gap-2 py-2 my-1\">\n <div className=\"h-px flex-1 bg-border\" />\n <span className=\"text-xs text-muted-foreground/60\">created {label}</span>\n <div className=\"h-px flex-1 bg-border\" />\n </div>\n )\n}\n\nexport function ImportedHistoryMarker({ history }: { history: ChatHistoryImport }) {\n const source = history.sourceAgentLabel || history.sourcePeerId\n const count = history.entries.length\n return (\n <div className=\"flex items-center justify-center gap-2 py-2 my-1\">\n <div className=\"h-px flex-1 bg-border\" />\n <div className=\"flex items-center gap-1.5 rounded-full border border-dashed border-border bg-muted/30 px-2 py-1 text-[11px] text-muted-foreground\">\n <GitFork className=\"h-3 w-3\" />\n <span>forked history from {source}</span>\n <span className=\"text-muted-foreground/60\">{count} {count === 1 ? 'entry' : 'entries'}</span>\n </div>\n <div className=\"h-px flex-1 bg-border\" />\n </div>\n )\n}\n\nexport function ImportedMessageBubble({ entry, sourceLabel }: { entry: ChatHistoryImportEntry; sourceLabel?: string }) {\n const msg = entry.message\n const body = messageBody(msg)\n const isOriginalHuman = entry.originalFrom === HUMAN_AGENT_ID\n return (\n <div className={cn('flex mb-3 opacity-80', isOriginalHuman ? 'justify-end' : 'justify-start')}>\n <div className=\"max-w-[85%] md:max-w-[75%]\">\n <div\n className={cn(\n 'rounded-2xl border border-dashed px-3.5 py-2 text-sm select-text',\n isOriginalHuman\n ? 'border-primary/25 bg-primary/10 text-foreground rounded-br-sm'\n : 'border-border bg-card/70 rounded-bl-sm'\n )}\n >\n <div className={cn('mb-1 text-[10px] uppercase tracking-normal', isOriginalHuman ? 'text-primary/70' : 'text-muted-foreground')}>\n forked history · {isOriginalHuman ? 'you' : (sourceLabel || entry.originalFrom)}\n </div>\n <FormattedBody text={body} rawBody={msg.body} className=\"leading-relaxed\" />\n <p className={cn('mt-1 flex items-center justify-end gap-1.5 text-xs', isOriginalHuman ? 'text-primary/60' : 'text-muted-foreground')}>\n <span className=\"opacity-40\">#{entry.originalMessageId}</span>\n <span>{chatTimestamp(entry.originalCreatedAt)}</span>\n </p>\n </div>\n </div>\n </div>\n )\n}\n\nexport function StickyPromptBanner({ scrollRef, timeline }: { scrollRef: React.RefObject<HTMLElement | null>; timeline: TimelineEntry[] }) {\n const [hidden, setHidden] = useState(true)\n const [expandedByPrompt, setExpandedByPrompt] = useState<{ id: number; value: boolean } | null>(null)\n const [collapsedByPrompt, setCollapsedByPrompt] = useState<{ id: number; value: boolean } | null>(null)\n const [promptAbove, setPromptAbove] = useState(true)\n\n const lastOutbound = useMemo(() => {\n for (let i = timeline.length - 1; i >= 0; i--) {\n const entry = timeline[i]\n if (!entry || entry.type !== 'message') continue\n if (entry.msg.from === HUMAN_AGENT_ID) {\n return { id: entry.msg.id, body: messageBody(entry.msg) }\n }\n }\n return null\n }, [timeline])\n\n useEffect(() => {\n const scrollEl = scrollRef.current\n if (!lastOutbound || !scrollEl) { setHidden(true); return }\n const target = scrollEl.querySelector(`[data-msg-id=\"${lastOutbound.id}\"]`)\n if (!target) { setHidden(true); return }\n const observer = new IntersectionObserver(\n ([e]) => {\n if (!e) return\n setHidden(e.isIntersecting)\n if (!e.isIntersecting) {\n const rootTop = e.rootBounds?.top ?? scrollEl.getBoundingClientRect().top\n setPromptAbove(e.boundingClientRect.top < rootTop)\n }\n },\n { root: scrollEl, threshold: 0 }\n )\n observer.observe(target)\n const onScroll = () => {\n const r = target.getBoundingClientRect()\n const sr = scrollEl.getBoundingClientRect()\n setPromptAbove(r.top < sr.top)\n }\n scrollEl.addEventListener('scroll', onScroll, { passive: true })\n return () => { observer.disconnect(); scrollEl.removeEventListener('scroll', onScroll) }\n }, [lastOutbound?.id, scrollRef])\n\n if (hidden || !lastOutbound || !lastOutbound.body.trim()) return null\n\n const expanded = expandedByPrompt?.id === lastOutbound.id ? expandedByPrompt.value : false\n const collapsed = collapsedByPrompt?.id === lastOutbound.id ? collapsedByPrompt.value : false\n\n function scrollToPrompt() {\n const scrollEl = scrollRef.current\n if (!scrollEl || !lastOutbound) return\n const target = scrollEl.querySelector(`[data-msg-id=\"${lastOutbound.id}\"]`)\n target?.scrollIntoView({ behavior: 'smooth', block: 'center' })\n }\n\n const arrow = promptAbove ? '↑' : '↓'\n\n if (collapsed) {\n return (\n <div className=\"sticky top-0 z-10 -mx-3 md:-mx-4 -mt-3 md:-mt-4 bg-background\">\n <button\n type=\"button\"\n className=\"w-full flex items-center justify-center gap-1.5 py-1 text-[11px] text-primary/60 hover:text-primary border-b border-primary/10 transition-colors\"\n onClick={() => setCollapsedByPrompt({ id: lastOutbound.id, value: false })}\n >\n <span>Your prompt</span>\n <ChevronDown className=\"w-3 h-3\" />\n </button>\n </div>\n )\n }\n\n return (\n <div className=\"sticky top-0 z-10 -mx-3 md:-mx-4 -mt-3 md:-mt-4 px-2 md:px-3 pt-2 pb-1.5 bg-background border-b border-primary/10\">\n <div className=\"flex items-center gap-2 text-[11px] text-muted-foreground mb-0.5\">\n <span className=\"font-medium text-primary/70\">Your prompt</span>\n <button\n type=\"button\"\n className=\"ml-auto hover:text-foreground transition-colors\"\n onClick={scrollToPrompt}\n >\n {arrow} scroll to original\n </button>\n <button\n type=\"button\"\n className=\"hover:text-foreground transition-colors\"\n onClick={() => setCollapsedByPrompt({ id: lastOutbound.id, value: true })}\n title=\"Minimize\"\n >\n <ChevronUp className=\"w-3 h-3\" />\n </button>\n </div>\n <p\n className={cn('text-sm text-foreground leading-snug cursor-pointer', !expanded && 'line-clamp-2')}\n onClick={() => setExpandedByPrompt({ id: lastOutbound.id, value: !expanded })}\n >\n {lastOutbound.body}\n </p>\n </div>\n )\n}\n","\nimport { useSyncExternalStore } from 'react'\nimport { voiceTts } from '@/lib/voice'\n\nexport function useTtsPlayingKey(): string | null {\n return useSyncExternalStore(\n (cb) => voiceTts.subscribe(cb),\n () => voiceTts.getPlayingKey(),\n () => null,\n )\n}\n","\nimport { memo, useEffect, useRef, useState } from 'react'\nimport { AlertCircle, CircleStop, Download, FileText, Loader2, SmilePlus, Volume2, X, ZoomIn } from 'lucide-react'\nimport { voiceTts } from '@/lib/voice'\nimport { useRelayStore } from '@/store'\nimport { FormattedBody } from '@/components/shared/formatted-body'\nimport { Button } from '@/components/ui/button'\nimport { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'\nimport { apiBlob } from '@/lib/api'\nimport { HUMAN_AGENT_ID } from '@/lib/constants'\nimport { messageBody } from '@/lib/display'\nimport type { AttachmentRef, Message } from '@/types'\nimport { cn } from '@/lib/utils'\nimport type { ReferencedPathInfo } from './types'\nimport {\n chatTimestamp,\n groupedReactions,\n hasActiveTextSelection,\n isReactionEvent,\n messageAttachments,\n outboundReceipt,\n QUICK_REACTIONS,\n resolveRelativePath,\n} from './helpers'\nimport { useTtsPlayingKey } from './hooks/useTtsPlayingKey'\n\nfunction AttachmentPreview({ attachment, outbound }: { attachment: AttachmentRef; outbound: boolean }) {\n const isImage = attachment.kind === 'image'\n const title = attachment.title || attachment.artifactId\n const [objectUrl, setObjectUrl] = useState<string | null>(null)\n const [error, setError] = useState<string | null>(null)\n const [loading, setLoading] = useState(false)\n const [lightboxOpen, setLightboxOpen] = useState(false)\n\n useEffect(() => {\n let cancelled = false\n let url: string | null = null\n\n async function load() {\n setLoading(true)\n setError(null)\n setObjectUrl(null)\n try {\n const blob = await apiBlob(`/artifacts/${encodeURIComponent(attachment.artifactId)}/content`)\n if (cancelled) return\n url = URL.createObjectURL(blob)\n setObjectUrl(url)\n } catch (e) {\n if (!cancelled) setError((e as Error).message)\n } finally {\n if (!cancelled) setLoading(false)\n }\n }\n\n void load()\n return () => {\n cancelled = true\n if (url) URL.revokeObjectURL(url)\n }\n }, [attachment.artifactId])\n\n function download() {\n if (!objectUrl) return\n const a = document.createElement('a')\n a.href = objectUrl\n a.download = title\n document.body.appendChild(a)\n a.click()\n a.remove()\n }\n\n if (isImage) {\n return (\n <>\n <button\n type=\"button\"\n onClick={() => objectUrl && setLightboxOpen(true)}\n disabled={!objectUrl}\n className=\"group/img mt-2 block overflow-hidden rounded-md border border-foreground/10 bg-black/10 text-left disabled:cursor-default relative\"\n >\n {objectUrl ? (\n <>\n <img src={objectUrl} alt={title} loading=\"lazy\" className=\"block max-h-72 max-w-full object-contain\" />\n <span className=\"absolute inset-0 flex items-center justify-center bg-black/0 group-hover/img:bg-black/30 transition-colors\">\n <ZoomIn className=\"w-6 h-6 text-white opacity-0 group-hover/img:opacity-100 transition-opacity drop-shadow-md\" />\n </span>\n </>\n ) : (\n <span className={cn('flex min-h-20 items-center gap-2 px-3 py-2 text-xs', error ? 'text-red-400' : 'text-muted-foreground')}>\n {loading ? <Loader2 className=\"h-4 w-4 animate-spin\" /> : <AlertCircle className=\"h-4 w-4\" />}\n {error || 'Loading image'}\n </span>\n )}\n </button>\n {objectUrl && (\n <Dialog open={lightboxOpen} onOpenChange={setLightboxOpen}>\n <DialogContent className=\"max-w-[95vw] max-h-[95vh] w-auto p-0 bg-black/95 border-zinc-800 gap-0 overflow-hidden\" showCloseButton={false}>\n <DialogTitle className=\"sr-only\">{title}</DialogTitle>\n <div className=\"relative flex items-center justify-center min-h-[200px]\">\n <img src={objectUrl} alt={title} className=\"max-w-[93vw] max-h-[90vh] object-contain\" />\n <div className=\"absolute top-2 right-2 flex gap-1\">\n <button type=\"button\" onClick={download} className=\"rounded-md bg-black/60 hover:bg-black/80 p-2 text-white transition-colors\" title=\"Download\">\n <Download className=\"w-4 h-4\" />\n </button>\n <button type=\"button\" onClick={() => setLightboxOpen(false)} className=\"rounded-md bg-black/60 hover:bg-black/80 p-2 text-white transition-colors\" title=\"Close\">\n <X className=\"w-4 h-4\" />\n </button>\n </div>\n </div>\n </DialogContent>\n </Dialog>\n )}\n </>\n )\n }\n\n return (\n <button\n type=\"button\"\n onClick={download}\n disabled={!objectUrl}\n className={cn(\n 'mt-2 flex w-full items-center gap-2 rounded-md border px-2.5 py-2 text-left text-xs transition-colors disabled:cursor-default disabled:opacity-70',\n outbound ? 'border-primary-foreground/20 bg-primary-foreground/10 hover:bg-primary-foreground/15' : 'border-border bg-background hover:bg-muted'\n )}\n >\n {loading ? <Loader2 className=\"h-4 w-4 shrink-0 animate-spin\" /> : error ? <AlertCircle className=\"h-4 w-4 shrink-0 text-red-400\" /> : <FileText className=\"h-4 w-4 shrink-0\" />}\n <span className={cn('min-w-0 flex-1 truncate', error && 'text-red-400')}>{error || title}</span>\n <Download className=\"h-3.5 w-3.5 shrink-0\" />\n </button>\n )\n}\n\nfunction AddReaction({ open, onToggle, onReact }: { open: boolean; onToggle: () => void; onReact: (emoji: string) => void }) {\n return (\n <div className=\"relative shrink-0\">\n <button\n type=\"button\"\n title=\"Add reaction\"\n onClick={onToggle}\n className={cn(\n 'inline-flex h-5 w-6 items-center justify-center rounded-full border border-border bg-popover text-muted-foreground shadow-sm transition hover:bg-muted hover:text-foreground',\n open ? 'opacity-100' : 'opacity-0 pointer-events-none md:group-hover/msg:opacity-100 md:group-hover/msg:pointer-events-auto'\n )}\n >\n <SmilePlus className=\"h-3 w-3\" />\n </button>\n {open && (\n <div className=\"absolute bottom-full left-0 z-30 mb-1 flex gap-0.5 rounded-full border border-border bg-popover p-0.5 shadow-md\">\n {QUICK_REACTIONS.map((emoji) => (\n <button\n key={emoji}\n type=\"button\"\n title={`React ${emoji}`}\n onClick={() => onReact(emoji)}\n className=\"inline-flex h-6 w-7 items-center justify-center rounded-full text-xs transition-colors hover:bg-muted\"\n >\n {emoji}\n </button>\n ))}\n </div>\n )}\n </div>\n )\n}\n\nexport const MessageBubble = memo(function MessageBubble({\n msg,\n peer,\n onOpenReferencedPath,\n onPreviewReferencedPath,\n onPreviewReferencedPathEnd,\n}: {\n msg: Message\n peer: string\n onOpenReferencedPath?: (path: string, line?: number, type?: ReferencedPathInfo['type']) => void\n onPreviewReferencedPath?: (path: string, line?: number, anchor?: DOMRect) => void\n onPreviewReferencedPathEnd?: () => void\n}) {\n const isPeerMessage = msg.from !== HUMAN_AGENT_ID && msg.to !== HUMAN_AGENT_ID\n // For agent↔agent messages, treat the selected agent (peer) as the local side:\n // messages it sent are outbound (right), messages it received are inbound (left).\n const isOutbound = isPeerMessage ? msg.from === peer : msg.from === HUMAN_AGENT_ID\n const peerLabel = isPeerMessage\n ? (isOutbound ? `→ ${msg.to}` : `from ${msg.from}`)\n : null\n const reactToMessage = useRelayStore((s) => s.reactToMessage)\n const voiceTtsEnabled = useRelayStore((s) => s.voiceTtsEnabled)\n const ttsPlayingKey = useTtsPlayingKey()\n const peerCwd = useRelayStore((s) => {\n const cwd = s.agentsById[peer]?.meta?.cwd\n return typeof cwd === 'string' ? cwd : ''\n })\n const [showQuickReact, setShowQuickReact] = useState(false)\n const bubbleRef = useRef<HTMLDivElement>(null)\n const pointerStartRef = useRef<{ x: number; y: number } | null>(null)\n const suppressBubbleClickRef = useRef(false)\n const body = messageBody(msg)\n const time = chatTimestamp(msg.occurredAt ?? (msg.createdAt as string))\n const attachments = messageAttachments(msg)\n const reactions = groupedReactions(msg)\n const receipt = isOutbound ? outboundReceipt(msg, peer) : null\n const ReceiptIcon = receipt?.icon\n // On-demand TTS: replay any agent response through the same Kokoro/browser\n // pipeline. Only when the speaker is on, and only for inbound non-reaction text.\n const isTtsPlaying = ttsPlayingKey === String(msg.id)\n const showPlayButton = voiceTtsEnabled && !isOutbound && !isPeerMessage && !isReactionEvent(msg) && body.trim().length > 0\n function togglePlay(e: React.MouseEvent) {\n e.stopPropagation()\n if (isTtsPlaying) voiceTts.bargeIn()\n else voiceTts.speak(msg.body, String(msg.id))\n }\n useEffect(() => {\n if (!showQuickReact) return\n function dismiss(e: MouseEvent | TouchEvent) {\n if (hasActiveTextSelection()) return\n if (bubbleRef.current && !bubbleRef.current.contains(e.target as Node)) setShowQuickReact(false)\n }\n document.addEventListener('mousedown', dismiss)\n document.addEventListener('touchstart', dismiss)\n return () => { document.removeEventListener('mousedown', dismiss); document.removeEventListener('touchstart', dismiss) }\n }, [showQuickReact])\n\n function resolvedReferencedPath(path: string): string {\n return resolveRelativePath(peerCwd || '/', path)\n }\n\n function openReferencedPath(path: string, line?: number) {\n const absolute = resolvedReferencedPath(path)\n onOpenReferencedPath?.(absolute, line)\n }\n\n function previewReferencedPath(path: string, line?: number, anchor?: DOMRect) {\n const absolute = resolvedReferencedPath(path)\n onPreviewReferencedPath?.(absolute, line, anchor)\n }\n\n function handleReact(emoji: string) {\n reactToMessage(msg, emoji)\n setShowQuickReact(false)\n }\n\n function handleBubblePointerDown(e: React.PointerEvent<HTMLDivElement>) {\n if (e.button !== 0) return\n pointerStartRef.current = { x: e.clientX, y: e.clientY }\n suppressBubbleClickRef.current = false\n }\n\n function handleBubblePointerMove(e: React.PointerEvent<HTMLDivElement>) {\n const start = pointerStartRef.current\n if (!start) return\n if (Math.abs(e.clientX - start.x) > 3 || Math.abs(e.clientY - start.y) > 3) {\n suppressBubbleClickRef.current = true\n }\n }\n\n function handleBubbleClick(e: React.MouseEvent<HTMLDivElement>) {\n if (isReactionEvent(msg) || isOutbound || isPeerMessage) return\n const target = e.target as HTMLElement\n if (target.closest('a,button,input,textarea,select,[role=\"button\"]')) return\n if (suppressBubbleClickRef.current || hasActiveTextSelection()) {\n suppressBubbleClickRef.current = false\n return\n }\n setShowQuickReact((v) => !v)\n }\n\n return (\n <div data-msg-id={msg.id} className={cn('group/msg flex mb-3', isOutbound ? 'justify-end' : 'justify-start')}>\n <div ref={bubbleRef} className=\"relative max-w-[85%] md:max-w-[75%]\">\n {showPlayButton && (\n <button\n type=\"button\"\n title={isTtsPlaying ? 'Stop playback' : 'Play aloud'}\n onClick={togglePlay}\n className={cn(\n 'absolute -top-2 -right-2 z-20 inline-flex h-6 w-6 items-center justify-center rounded-full border bg-popover shadow-sm transition',\n isTtsPlaying\n ? 'border-primary/50 text-primary opacity-100'\n // Hide-until-hover only on hover-capable devices; touch screens (iPad)\n // have no hover, so keep the button visible there instead of opacity-0.\n : 'border-border text-muted-foreground opacity-70 hover:bg-muted hover:text-foreground hover:opacity-100 [@media(hover:hover)]:md:opacity-0 [@media(hover:hover)]:md:group-hover/msg:opacity-100'\n )}\n >\n {isTtsPlaying ? <CircleStop className=\"h-3.5 w-3.5 animate-pulse\" /> : <Volume2 className=\"h-3.5 w-3.5\" />}\n </button>\n )}\n <div\n className={cn(\n 'rounded-2xl px-3.5 py-2 text-sm select-text',\n !isOutbound && !isReactionEvent(msg) && !isPeerMessage && 'cursor-pointer',\n isOutbound\n ? 'bg-primary text-primary-foreground rounded-br-sm'\n : 'bg-card ring-1 ring-foreground/10 rounded-bl-sm'\n )}\n onPointerDown={handleBubblePointerDown}\n onPointerMove={handleBubblePointerMove}\n onClick={handleBubbleClick}\n >\n {peerLabel && (\n <p className={cn('text-xs font-medium mb-1 opacity-60', isOutbound ? 'text-primary-foreground' : 'text-muted-foreground')}>\n {peerLabel}\n </p>\n )}\n {msg.subject && (\n <p className={cn('text-xs font-semibold mb-1', isOutbound ? 'text-primary-foreground/70' : 'text-muted-foreground')}>\n {msg.subject}\n </p>\n )}\n <FormattedBody\n text={body}\n rawBody={msg.body}\n className=\"leading-relaxed\"\n onOpenPath={openReferencedPath}\n onPreviewPath={previewReferencedPath}\n onPreviewPathEnd={onPreviewReferencedPathEnd}\n resolvePathTitle={(path, line) => `${resolvedReferencedPath(path)}${line ? `:${line}` : ''}`}\n />\n {attachments.map((attachment) => (\n <AttachmentPreview key={`${msg.id}-${attachment.artifactId}-${attachment.role || ''}`} attachment={attachment} outbound={isOutbound} />\n ))}\n <p className={cn('text-xs mt-1 flex items-center gap-1.5', isOutbound ? 'justify-end text-primary-foreground/60' : 'justify-end text-muted-foreground')}>\n <span className=\"opacity-40\">#{msg.id}</span>\n <span>{time}</span>\n {receipt && ReceiptIcon && (\n <span\n className={cn(\n 'inline-flex items-center gap-1',\n receipt.tone === 'ok' && 'text-emerald-300',\n receipt.tone === 'warn' && 'text-amber-200',\n receipt.tone === 'danger' && 'text-red-200'\n )}\n title={receipt.title}\n >\n <ReceiptIcon className=\"h-3 w-3\" />\n {receipt.label}\n </span>\n )}\n </p>\n </div>\n {!isReactionEvent(msg) && reactions.length > 0 && (\n <div className={cn('flex flex-wrap items-center gap-0.5 -mt-1 relative z-10', isOutbound ? 'justify-end pr-2' : 'justify-start pl-2')}>\n {!isOutbound && <AddReaction open={showQuickReact} onToggle={() => setShowQuickReact((v) => !v)} onReact={handleReact} />}\n {reactions.map((reaction) => (\n <button\n key={reaction.emoji}\n type=\"button\"\n title={reaction.actors.join(', ')}\n onClick={() => handleReact(reaction.emoji)}\n className={cn(\n 'inline-flex h-5 items-center gap-0.5 rounded-full border px-1.5 text-[11px] shadow-sm transition-colors',\n reaction.mine\n ? 'border-primary/40 bg-primary/10 text-primary'\n : 'border-border bg-background hover:bg-muted text-foreground'\n )}\n >\n <span>{reaction.emoji}</span>\n {reaction.count > 1 && <span>{reaction.count}</span>}\n </button>\n ))}\n </div>\n )}\n {!isReactionEvent(msg) && !isOutbound && reactions.length === 0 && (\n <div className=\"absolute -bottom-2.5 left-1 z-20\">\n <AddReaction open={showQuickReact} onToggle={() => setShowQuickReact((v) => !v)} onReact={handleReact} />\n </div>\n )}\n </div>\n </div>\n )\n})\n"],"mappings":"mfAiBA,EAAA,geAgBA,GAAA,IAAA,IAAA,OAAA,KAAA,EAAA,CAAA,CACA,GAAA,IAMA,SAAA,EAAA,EAAA,sDAOA,SAAA,GAAA,EAAA,gRAmBA,SAAA,GAAA,EAAA,8MAUA,SAAA,GAAA,EAAA,6CAIA,SAAA,EAAA,EAAA,+HAKA,SAAA,G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EP,CAAC,EAAgB,EAAI,EAAI,CAAC,GAAc,EAAU,SAAW,IAC5D,EAAA,EAAA,KAAC,MAAD,CAAK,UAAU,6CACb,EAAA,EAAA,KAAC,EAAD,CAAa,KAAM,EAAgB,aAAgB,EAAmB,GAAM,CAAC,EAAE,CAAE,QAAS,EAAe,CAAA,CACrG,CAAA,CAEJ,GACF,CAAA,EAER"}
1
+ {"version":3,"file":"MessageBubble-BqFAi9gS.js","names":[],"sources":["../../dashboard/src/components/chat/sessionTrace.ts","../../dashboard/src/components/chat/helpers.ts","../../dashboard/src/components/chat/TraceView.tsx","../../dashboard/src/components/chat/hooks/useTtsPlayingKey.ts","../../dashboard/src/components/chat/MessageBubble.tsx"],"sourcesContent":["\nimport { toTimestamp, responseBodyContainsBlock } from '@/lib/display'\nimport type { ChatStatusEvent as StatusEvent } from '@/store'\nimport type { ChatHistoryImport, ChatHistoryImportEntry, Message } from '@/types'\n\nexport interface ActivityStep { id: number; kind: 'narration' | 'reasoning' | 'tool'; label?: string; text: string; ts: number; turnId?: string }\n\nexport type TimelineEntry =\n | { type: 'message'; msg: Message }\n | { type: 'notice'; msg: Message }\n | { type: 'activity'; steps: ActivityStep[]; timestamp: number }\n | { type: 'import-boundary'; history: ChatHistoryImport; timestamp: number }\n | { type: 'imported-message'; history: ChatHistoryImport; entry: ChatHistoryImportEntry }\n | { type: 'status'; event: StatusEvent }\n | { type: 'date'; date: string; timestamp: number }\n | { type: 'created'; timestamp: number }\n\nexport const TIMELINE_STATUS_LABELS: Record<string, string> = {\n online: 'came online',\n offline: 'went offline',\n shutdown: 'shut down',\n restarted: 'restarted',\n 'compaction-requested': 'compaction requested',\n compacting: 'compaction started',\n compacted: 'context compacted',\n 'compaction-stalled': 'compaction stalled — may need manual intervention',\n 'clear-requested': 'clear requested',\n 'clearing-context': 'clear started',\n 'context-cleared': 'context cleared',\n 'clear-stalled': 'context clear stalled — may need manual intervention',\n 'shutting-down': 'shutting down',\n}\n\nconst TIMELINE_STATUSES = new Set(Object.keys(TIMELINE_STATUS_LABELS))\nconst STATUS_DEDUPE_WINDOW_MS = 3000\n\n// True event time of a message: occurredAt (set when a Runner backfilled a message it had\n// queued during an outage, #196) falling back to the server receive time. Used for chat\n// timeline ordering + display so a backfilled turn lands where it actually happened in the\n// conversation, not at the bottom. Display-only — DB poll cursors still use created_at.\nexport function messageEventTime(msg: Message): number {\n return new Date(msg.occurredAt ?? msg.createdAt).getTime()\n}\n\n// Narration/reasoning/tool session events are mirrored as `kind:\"session\"` messages\n// but must not become chat bubbles — they render inline in the turn's activity trace.\n// (`narration` = the agent's intermediate spoken text; `reasoning` = its thinking.)\nexport function sessionActivityStep(msg: Message): ActivityStep | null {\n if (msg.kind !== 'session') return null\n const s = msg.payload?.session as { type?: string; label?: string; turnId?: string } | undefined\n if (!s || (s.type !== 'narration' && s.type !== 'reasoning' && s.type !== 'tool')) return null\n return {\n id: msg.id,\n kind: s.type,\n label: typeof s.label === 'string' ? s.label : undefined,\n text: msg.body,\n ts: messageEventTime(msg),\n turnId: typeof s.turnId === 'string' ? s.turnId : undefined,\n }\n}\n\n// A `notice` session event (e.g. the runner's durable \"context compacted\" marker) renders\n// as a discreet timeline marker, reusing the StatusMarker path. Its `label` carries a\n// timeline-status key (e.g. \"compacted\"); we surface it as a StatusEvent so it dedupes with\n// the ephemeral live timeline-status decoration and survives a reload (the ephemeral one does\n// not). Returns null for non-notice messages or labels we don't render.\nexport function sessionNoticeStatusEvent(msg: Message): StatusEvent | null {\n if (msg.kind !== 'session') return null\n const s = msg.payload?.session as { type?: string; label?: string } | undefined\n if (s?.type !== 'notice') return null\n const status = typeof s.label === 'string' && s.label ? s.label : 'compacted'\n return { id: `notice-${msg.id}`, status, timestamp: messageEventTime(msg) }\n}\n\n// Bus-level system signals (kind:\"system\", from:\"system\") — e.g. branch.landed,\n// context.warning. Rendered as notice pills, NOT chat bubbles or session status markers.\nexport function isBusSignalMessage(msg: Message): boolean {\n return msg.kind === 'system' && msg.from === 'system'\n}\n\nexport function dateKey(ts: number): string {\n const d = new Date(ts)\n return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`\n}\n\nexport function dedupeStatusEvents(statusEvents: StatusEvent[]): StatusEvent[] {\n const events = statusEvents\n .filter((event) => TIMELINE_STATUSES.has(event.status))\n .slice()\n .sort((a, b) => a.timestamp - b.timestamp)\n const result: StatusEvent[] = []\n for (const event of events) {\n if (result.some((existing) => existing.id === event.id)) continue\n if (result.some((existing) => existing.status === event.status && Math.abs(existing.timestamp - event.timestamp) <= STATUS_DEDUPE_WINDOW_MS)) continue\n result.push(event)\n }\n return result\n}\n\nexport function buildTimeline(messages: Message[], statusEvents: StatusEvent[], createdAt?: string | number | null, importedHistory: ChatHistoryImport[] = []): TimelineEntry[] {\n const raw: Array<{ ts: number; entry: TimelineEntry }> = []\n\n for (const history of importedHistory) {\n const firstImportedAt = history.entries.reduce((min, entry) => Math.min(min, toTimestamp(entry.originalCreatedAt)), Number.POSITIVE_INFINITY)\n const boundaryAt = Number.isFinite(firstImportedAt) ? firstImportedAt - 1 : history.importedAt\n raw.push({ ts: boundaryAt, entry: { type: 'import-boundary', history, timestamp: boundaryAt } })\n for (const entry of history.entries) {\n raw.push({ ts: toTimestamp(entry.originalCreatedAt), entry: { type: 'imported-message', history, entry } })\n }\n }\n\n if (createdAt) {\n const ts = new Date(createdAt as string).getTime()\n if (Number.isFinite(ts)) raw.push({ ts, entry: { type: 'created', timestamp: ts } })\n }\n\n // The closing response bubble (session type \"response\") repeats the turn's\n // narration. In `final` capture mode the body is just the final line; in `full`\n // mode it is every narration block joined with blank-line separators\n // (matching extractLastAssistantTurn).\n // Collect the response bodies per turn so a narration step is suppressed from the\n // trace whenever it appears as a blank-line-delimited block of the body — so no line\n // shows twice in either mode (final: only the matching final line; full: all of them).\n const responseBodiesByTurn = new Map<string, string[]>()\n for (const msg of messages) {\n if (msg.kind !== 'session') continue\n const s = msg.payload?.session as { type?: string; turnId?: string } | undefined\n if (s?.type === 'response' && typeof s.turnId === 'string') {\n const list = responseBodiesByTurn.get(s.turnId) ?? []\n list.push(msg.body.trim())\n responseBodiesByTurn.set(s.turnId, list)\n }\n }\n\n const noticeStatusEvents: StatusEvent[] = []\n for (const msg of messages) {\n if (isBusSignalMessage(msg)) {\n raw.push({ ts: messageEventTime(msg), entry: { type: 'notice', msg } })\n continue\n }\n const notice = sessionNoticeStatusEvent(msg)\n if (notice) {\n noticeStatusEvents.push(notice)\n continue\n }\n const step = sessionActivityStep(msg)\n if (step) {\n if (step.kind === 'narration' && step.turnId) {\n const bodies = responseBodiesByTurn.get(step.turnId)\n if (bodies?.some((body) => responseBodyContainsBlock(body, step.text))) continue\n }\n raw.push({ ts: step.ts, entry: { type: 'activity', steps: [step], timestamp: step.ts } })\n continue\n }\n raw.push({ ts: messageEventTime(msg), entry: { type: 'message', msg } })\n }\n for (const event of dedupeStatusEvents([...statusEvents, ...noticeStatusEvents])) {\n raw.push({ ts: event.timestamp, entry: { type: 'status', event } })\n }\n\n const typeOrder = { created: 0, date: 1, 'import-boundary': 2, 'imported-message': 3, message: 4, activity: 4, notice: 4, status: 5 } as const\n raw.sort((a, b) => {\n const dt = a.ts - b.ts\n if (Math.abs(dt) < 3000) return typeOrder[a.entry.type] - typeOrder[b.entry.type] || dt\n return dt\n })\n\n const entries: TimelineEntry[] = []\n let lastDate = ''\n for (const { ts, entry } of raw) {\n if (entry.type === 'created') {\n entries.push(entry)\n continue\n }\n const dk = dateKey(ts)\n if (dk !== lastDate) {\n entries.push({ type: 'date', date: dk, timestamp: ts })\n lastDate = dk\n }\n // Coalesce consecutive activity steps from the same turn into one trace.\n if (entry.type === 'activity') {\n const prev = entries[entries.length - 1]\n if (prev && prev.type === 'activity' && sameActivityTurn(prev, entry)) {\n prev.steps.push(...entry.steps)\n continue\n }\n }\n entries.push(entry)\n }\n\n return entries\n}\n\nexport function sameActivityTurn(a: Extract<TimelineEntry, { type: 'activity' }>, b: Extract<TimelineEntry, { type: 'activity' }>): boolean {\n const at = a.steps[a.steps.length - 1]?.turnId\n const bt = b.steps[0]?.turnId\n if (at && bt) return at === bt\n // No turn id on either side: group adjacent steps regardless.\n return !at && !bt\n}\n","\nimport { AlertCircle, Check, CheckCheck, Clock } from 'lucide-react'\nimport { HUMAN_AGENT_ID } from '@/lib/constants'\nimport {\n isReactionEventMessage,\n normalizePathForCompare,\n normalizeReactionEmoji,\n pathWithinBase,\n toTimestamp,\n} from '@/lib/display'\nimport { planLookupKey } from '@/store/slices/plans'\nimport type { Agent, AttachmentRef, InboxThread, Message, Orchestrator, Plan } from '@/types'\nimport type { PendingAttachment } from './types'\n\nexport function formatBytes(size: number): string {\n if (size < 1024) return `${size} B`\n if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`\n return `${(size / 1024 / 1024).toFixed(1)} MB`\n}\n\nexport function resolveRelativePath(cwd: string, path: string): string {\n if (path.startsWith('/')) return path\n const parts = `${cwd.replace(/\\/+$/, '')}/${path}`.split('/')\n const stack: string[] = []\n for (const part of parts) {\n if (!part || part === '.') continue\n if (part === '..') stack.pop()\n else stack.push(part)\n }\n return '/' + stack.join('/')\n}\n\nexport function parentPath(path: string): string {\n const trimmed = path.replace(/\\/+$/, '')\n const index = trimmed.lastIndexOf('/')\n return index > 0 ? trimmed.slice(0, index) : '/'\n}\n\nexport function orchestratorForFilePreview(orchestrators: Orchestrator[], path: string): Orchestrator | undefined {\n return orchestrators\n .filter((orch) => orch.status === 'online' && pathWithinBase(path, orch.baseDir))\n .sort((a, b) => normalizePathForCompare(b.baseDir).length - normalizePathForCompare(a.baseDir).length)[0] ||\n orchestrators.find((orch) => orch.status === 'online')\n}\n\nexport function supportsSideFilePreview(): boolean {\n return typeof window !== 'undefined' && window.matchMedia('(min-width: 1280px)').matches\n}\n\nexport function hasActiveTextSelection(): boolean {\n return typeof window !== 'undefined' && Boolean(window.getSelection()?.toString())\n}\n\nexport function messageAttachments(msg: Message): AttachmentRef[] {\n const attachments = msg.payload?.attachments\n if (!Array.isArray(attachments)) return []\n return attachments.filter((item): item is AttachmentRef => Boolean(item && typeof item === 'object' && typeof (item as AttachmentRef).artifactId === 'string'))\n}\n\nexport const QUICK_REACTIONS = ['👍', '❤️', '✅', '👀'] as const\n\nexport function groupedReactions(msg: Message): Array<{ emoji: string; count: number; mine: boolean; actors: string[] }> {\n const groups = new Map<string, { emoji: string; count: number; mine: boolean; actors: string[] }>()\n for (const reaction of msg.reactions || []) {\n const emoji = normalizeReactionEmoji(reaction.emoji)\n const current = groups.get(emoji) ?? { emoji, count: 0, mine: false, actors: [] }\n current.count += 1\n current.mine = current.mine || reaction.actorId === HUMAN_AGENT_ID\n current.actors.push(reaction.actorId)\n groups.set(emoji, current)\n }\n return [...groups.values()].sort((a, b) => b.count - a.count || a.emoji.localeCompare(b.emoji))\n}\n\nexport function isReactionEvent(msg: Message): boolean {\n return isReactionEventMessage(msg)\n}\n\nexport function outboundReceipt(msg: Message, peer: string): { label: string; title: string; tone: 'muted' | 'ok' | 'warn' | 'danger'; icon: typeof Check } {\n const readBy = msg.readBy || []\n const expectedReader = msg.resolvedToAgent || peer || msg.to\n const readByExpected = expectedReader ? readBy.includes(expectedReader) : false\n const readBySomeone = readBy.some((id) => id !== HUMAN_AGENT_ID)\n if (readByExpected || readBySomeone) {\n const reader = readByExpected ? expectedReader : readBy.find((id) => id !== HUMAN_AGENT_ID)\n return { label: 'read', title: reader ? `Read by ${reader}` : 'Read by agent', tone: 'ok', icon: CheckCheck }\n }\n if (msg.deliveryStatus === 'delivered') {\n return { label: 'delivered', title: 'Delivered to agent inbox', tone: 'ok', icon: CheckCheck }\n }\n if (msg.deliveryStatus === 'queued') {\n return { label: 'queued', title: 'Queued until the target agent is available', tone: 'warn', icon: Clock }\n }\n if (msg.deliveryStatus === 'failed' || msg.deliveryStatus === 'dead') {\n const detail = msg.deliveryPoisonReason || msg.deliveryLastError || msg.deliveryStatus\n return { label: msg.deliveryStatus, title: detail, tone: 'danger', icon: AlertCircle }\n }\n return { label: 'sent', title: 'Accepted by Relay', tone: 'muted', icon: Check }\n}\n\nexport function messageActivityTimestamp(msg: Message): number {\n const messageAt = toTimestamp(msg.createdAt)\n return (msg.reactions || []).reduce((latest, reaction) => {\n return Math.max(latest, toTimestamp(reaction.updatedAt || reaction.createdAt))\n }, messageAt)\n}\n\nexport function threadActivityTimestamp(thread: InboxThread | undefined): number {\n if (!thread) return 0\n return thread.messages.reduce((latest, msg) => Math.max(latest, messageActivityTimestamp(msg)), 0)\n}\n\nexport function chatTimestamp(iso: string | number): string {\n const d = new Date(iso as string)\n return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })\n}\n\nexport function revokePendingAttachmentUrls(items: PendingAttachment[]): void {\n for (const item of items) if (item.previewUrl) URL.revokeObjectURL(item.previewUrl)\n}\n\ntype ChatPlanContext = { threadId: string | number; channel?: string } | { teamId: string; channel?: string }\n\nexport function resolveChatPlanContext(\n agent: Agent | null,\n messages: Message[],\n lastMessage: Message | null | undefined,\n plansByThread: Record<string, Plan | null>,\n): ChatPlanContext | null {\n if (agent?.teamId) return { teamId: agent.teamId }\n const ordered = [...messages]\n if (lastMessage && !ordered.some((message) => message.id === lastMessage.id)) ordered.push(lastMessage)\n const threaded = ordered.filter((message) => message.threadId).reverse()\n const knownPlanMessage = threaded.find((message) => Boolean(plansByThread[planLookupKey(message.threadId!, message.channel)]))\n const selected = knownPlanMessage ?? threaded[0]\n if (!selected?.threadId) return null\n return {\n threadId: selected.threadId,\n ...(selected.channel ? { channel: selected.channel } : {}),\n }\n}\n","\nimport { useEffect, useMemo, useState, useSyncExternalStore } from 'react'\nimport type React from 'react'\nimport { AlertCircle, AlertTriangle, Brain, ChevronDown, ChevronRight, ChevronUp, Circle, CircleStop, GitFork, GitMerge, Radio, Terminal } from 'lucide-react'\nimport type { LucideIcon } from 'lucide-react'\nimport { FormattedBody } from '@/components/shared/formatted-body'\nimport { HUMAN_AGENT_ID } from '@/lib/constants'\nimport { messageBody } from '@/lib/display'\nimport type { ChatHistoryImport, ChatHistoryImportEntry } from '@/types'\nimport { cn } from '@/lib/utils'\nimport { chatTimestamp } from './helpers'\nimport { dateKey, TIMELINE_STATUS_LABELS, type ActivityStep, type TimelineEntry } from './sessionTrace'\nimport type { Message } from '@/types'\nimport type { ChatStatusEvent as StatusEvent } from '@/store'\n\nconst TIMELINE_STATUS_COLORS: Record<string, string> = {\n online: 'text-emerald-400',\n offline: 'text-zinc-400',\n shutdown: 'text-zinc-400',\n restarted: 'text-blue-400',\n 'compaction-requested': 'text-zinc-400',\n compacting: 'text-amber-400',\n compacted: 'text-amber-400',\n 'compaction-stalled': 'text-red-400',\n 'clear-requested': 'text-zinc-400',\n 'clearing-context': 'text-amber-400',\n 'context-cleared': 'text-amber-400',\n 'clear-stalled': 'text-red-400',\n 'shutting-down': 'text-zinc-400',\n}\n\nfunction dateSeparatorLabel(dateStr: string): string {\n const today = new Date()\n const [y, m, d] = dateStr.split('-').map(Number)\n const target = new Date(y!, m! - 1, d)\n const todayKey = dateKey(today.getTime())\n if (dateStr === todayKey) return 'Today'\n const yesterday = new Date(today)\n yesterday.setDate(yesterday.getDate() - 1)\n if (dateStr === dateKey(yesterday.getTime())) return 'Yesterday'\n return target.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric', year: target.getFullYear() !== today.getFullYear() ? 'numeric' : undefined })\n}\n\nexport function StatusMarker({ event }: { event: StatusEvent }) {\n return (\n <div className=\"flex items-center justify-center gap-2 py-2 my-1\">\n <div className=\"h-px flex-1 bg-border\" />\n <div className=\"flex items-center gap-1.5 text-xs text-muted-foreground\">\n <Circle className={cn('w-2 h-2 fill-current', TIMELINE_STATUS_COLORS[event.status] || 'text-zinc-400')} />\n <span>{TIMELINE_STATUS_LABELS[event.status] || event.status}</span>\n <span className=\"text-muted-foreground/60\">{chatTimestamp(event.timestamp)}</span>\n </div>\n <div className=\"h-px flex-1 bg-border\" />\n </div>\n )\n}\n\nconst BUS_SIGNAL_ICON: Record<string, LucideIcon> = {\n 'branch.landed': GitMerge,\n 'context.warning': AlertTriangle,\n}\n\nconst BUS_SIGNAL_LABEL: Record<string, string> = {\n 'branch.landed': 'branch landed',\n 'context.warning': 'context warning',\n}\n\nexport function NoticePill({ msg }: { msg: Message }) {\n const signalKind = typeof msg.payload?.kind === 'string' ? msg.payload.kind : ''\n const Icon: LucideIcon = BUS_SIGNAL_ICON[signalKind] ?? Radio\n const label = BUS_SIGNAL_LABEL[signalKind] ?? (signalKind || 'system signal')\n return (\n <div className=\"flex items-center justify-center gap-2 py-2 my-1\">\n <div className=\"h-px flex-1 bg-border\" />\n <div className=\"flex items-center gap-1.5 rounded-full border border-border bg-muted/30 px-2.5 py-1 text-xs text-muted-foreground\">\n <Icon className=\"h-3 w-3\" />\n <span>{label}</span>\n <span className=\"text-muted-foreground/60\">{chatTimestamp(msg.occurredAt ?? (msg.createdAt as string))}</span>\n </div>\n <div className=\"h-px flex-1 bg-border\" />\n </div>\n )\n}\n\nexport function BusyIndicator({ blockedLabel, onInterrupt }: { blockedLabel?: string; onInterrupt?: () => void }) {\n if (blockedLabel) {\n return (\n <div className=\"flex justify-start mb-3\">\n <div className=\"flex items-center gap-2 rounded-2xl rounded-bl-sm bg-card ring-1 ring-red-500/30 px-4 py-2.5\">\n <AlertCircle className=\"w-3.5 h-3.5 text-red-400\" />\n <span className=\"text-xs text-red-300\">blocked: {blockedLabel}</span>\n </div>\n </div>\n )\n }\n\n return (\n <div className=\"flex justify-start mb-3\">\n <div className=\"flex items-center gap-2 rounded-2xl rounded-bl-sm bg-card ring-1 ring-foreground/10 px-4 py-2.5\">\n <div className=\"flex items-center gap-1\">\n <span className=\"w-1.5 h-1.5 rounded-full bg-yellow-400 animate-[pulse_1.4s_ease-in-out_infinite]\" />\n <span className=\"w-1.5 h-1.5 rounded-full bg-yellow-400 animate-[pulse_1.4s_ease-in-out_0.2s_infinite]\" />\n <span className=\"w-1.5 h-1.5 rounded-full bg-yellow-400 animate-[pulse_1.4s_ease-in-out_0.4s_infinite]\" />\n </div>\n <span className=\"text-xs text-muted-foreground\">working</span>\n {onInterrupt && (\n <button\n onClick={onInterrupt}\n title=\"Interrupt\"\n className=\"ml-1 flex items-center gap-1 rounded-full px-1.5 py-0.5 text-xs text-muted-foreground hover:text-red-300 hover:bg-red-500/10 transition-colors\"\n >\n <CircleStop className=\"w-3.5 h-3.5\" />\n Stop\n </button>\n )}\n </div>\n </div>\n )\n}\n\nconst HIDE_TOOLS_KEY = 'agent-relay:chat-hide-tools'\nconst hideToolsStore = (() => {\n const listeners = new Set<() => void>()\n let value = (() => {\n try {\n return window.localStorage.getItem(HIDE_TOOLS_KEY) === 'on'\n } catch {\n return false\n }\n })()\n const emit = () => listeners.forEach((l) => l())\n if (typeof window !== 'undefined') {\n window.addEventListener('storage', (e) => {\n if (e.key !== HIDE_TOOLS_KEY) return\n value = e.newValue === 'on'\n emit()\n })\n }\n return {\n subscribe(cb: () => void) {\n listeners.add(cb)\n return () => listeners.delete(cb)\n },\n get: () => value,\n toggle() {\n value = !value\n try {\n window.localStorage.setItem(HIDE_TOOLS_KEY, value ? 'on' : 'off')\n } catch {}\n emit()\n },\n }\n})()\n\nfunction useHideTools(): [boolean, () => void] {\n const hideTools = useSyncExternalStore(hideToolsStore.subscribe, hideToolsStore.get, () => false)\n return [hideTools, hideToolsStore.toggle]\n}\n\nexport function ActivityTrace({ steps, showReasoning }: { steps: ActivityStep[]; showReasoning: boolean }) {\n const [hideTools, toggleHideTools] = useHideTools()\n const visible = showReasoning ? steps : steps.filter((s) => s.kind !== 'reasoning')\n if (!visible.length) return null\n const toolCount = visible.filter((s) => s.kind === 'tool').length\n return (\n <div className=\"flex justify-start mb-2\">\n <div className=\"max-w-[85%] md:max-w-[75%] min-w-0 space-y-1.5\">\n {visible.map((step) => {\n if (step.kind === 'narration') {\n return (\n <FormattedBody\n key={step.id}\n text={step.text}\n className=\"text-sm leading-relaxed break-words text-foreground/90 min-w-0\"\n />\n )\n }\n if (step.kind === 'reasoning') {\n return (\n <div key={step.id} className=\"flex items-start gap-1.5 text-xs leading-relaxed text-muted-foreground/80\">\n <Brain className=\"w-3.5 h-3.5 mt-0.5 shrink-0 opacity-70\" />\n <FormattedBody text={step.text} className=\"italic break-words min-w-0\" />\n </div>\n )\n }\n if (hideTools) return null\n return (\n <div key={step.id} className=\"flex items-start gap-1.5 text-xs leading-relaxed text-muted-foreground\">\n <Terminal className=\"w-3 h-3 mt-0.5 shrink-0 opacity-70\" />\n <span className=\"min-w-0 break-words\">\n <span className=\"font-medium\">{step.label || 'tool'}</span>\n {step.text ? <span className=\"opacity-70\"> — {step.text}</span> : null}\n </span>\n </div>\n )\n })}\n {toolCount > 0 && (\n <button\n onClick={toggleHideTools}\n className=\"flex items-center gap-1 text-[11px] text-muted-foreground/50 hover:text-muted-foreground transition-colors text-left\"\n >\n <ChevronRight className={cn('w-3 h-3 shrink-0 transition-transform', !hideTools && 'rotate-90')} />\n <span>{hideTools ? `show ${toolCount} tool step${toolCount === 1 ? '' : 's'}` : 'hide tool steps'}</span>\n </button>\n )}\n </div>\n </div>\n )\n}\n\nexport function DateSeparator({ date }: { date: string }) {\n return (\n <div className=\"flex items-center justify-center gap-3 py-3 my-1\">\n <div className=\"h-px flex-1 bg-border\" />\n <span className=\"text-xs font-medium text-muted-foreground\">{dateSeparatorLabel(date)}</span>\n <div className=\"h-px flex-1 bg-border\" />\n </div>\n )\n}\n\nexport function CreatedMarker({ timestamp }: { timestamp: number }) {\n const d = new Date(timestamp)\n const label = d.toLocaleString(undefined, { month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit' })\n return (\n <div className=\"flex items-center justify-center gap-2 py-2 my-1\">\n <div className=\"h-px flex-1 bg-border\" />\n <span className=\"text-xs text-muted-foreground/60\">created {label}</span>\n <div className=\"h-px flex-1 bg-border\" />\n </div>\n )\n}\n\nexport function ImportedHistoryMarker({ history }: { history: ChatHistoryImport }) {\n const source = history.sourceAgentLabel || history.sourcePeerId\n const count = history.entries.length\n return (\n <div className=\"flex items-center justify-center gap-2 py-2 my-1\">\n <div className=\"h-px flex-1 bg-border\" />\n <div className=\"flex items-center gap-1.5 rounded-full border border-dashed border-border bg-muted/30 px-2 py-1 text-[11px] text-muted-foreground\">\n <GitFork className=\"h-3 w-3\" />\n <span>forked history from {source}</span>\n <span className=\"text-muted-foreground/60\">{count} {count === 1 ? 'entry' : 'entries'}</span>\n </div>\n <div className=\"h-px flex-1 bg-border\" />\n </div>\n )\n}\n\nexport function ImportedMessageBubble({ entry, sourceLabel }: { entry: ChatHistoryImportEntry; sourceLabel?: string }) {\n const msg = entry.message\n const body = messageBody(msg)\n const isOriginalHuman = entry.originalFrom === HUMAN_AGENT_ID\n return (\n <div className={cn('flex mb-3 opacity-80', isOriginalHuman ? 'justify-end' : 'justify-start')}>\n <div className=\"max-w-[85%] md:max-w-[75%]\">\n <div\n className={cn(\n 'rounded-2xl border border-dashed px-3.5 py-2 text-sm select-text',\n isOriginalHuman\n ? 'border-primary/25 bg-primary/10 text-foreground rounded-br-sm'\n : 'border-border bg-card/70 rounded-bl-sm'\n )}\n >\n <div className={cn('mb-1 text-[10px] uppercase tracking-normal', isOriginalHuman ? 'text-primary/70' : 'text-muted-foreground')}>\n forked history · {isOriginalHuman ? 'you' : (sourceLabel || entry.originalFrom)}\n </div>\n <FormattedBody text={body} rawBody={msg.body} className=\"leading-relaxed\" />\n <p className={cn('mt-1 flex items-center justify-end gap-1.5 text-xs', isOriginalHuman ? 'text-primary/60' : 'text-muted-foreground')}>\n <span className=\"opacity-40\">#{entry.originalMessageId}</span>\n <span>{chatTimestamp(entry.originalCreatedAt)}</span>\n </p>\n </div>\n </div>\n </div>\n )\n}\n\nexport function StickyPromptBanner({ scrollRef, timeline }: { scrollRef: React.RefObject<HTMLElement | null>; timeline: TimelineEntry[] }) {\n const [hidden, setHidden] = useState(true)\n const [expandedByPrompt, setExpandedByPrompt] = useState<{ id: number; value: boolean } | null>(null)\n const [collapsedByPrompt, setCollapsedByPrompt] = useState<{ id: number; value: boolean } | null>(null)\n const [promptAbove, setPromptAbove] = useState(true)\n\n const lastOutbound = useMemo(() => {\n for (let i = timeline.length - 1; i >= 0; i--) {\n const entry = timeline[i]\n if (!entry || entry.type !== 'message') continue\n if (entry.msg.from === HUMAN_AGENT_ID) {\n return { id: entry.msg.id, body: messageBody(entry.msg) }\n }\n }\n return null\n }, [timeline])\n\n useEffect(() => {\n const scrollEl = scrollRef.current\n if (!lastOutbound || !scrollEl) { setHidden(true); return }\n const target = scrollEl.querySelector(`[data-msg-id=\"${lastOutbound.id}\"]`)\n if (!target) { setHidden(true); return }\n const observer = new IntersectionObserver(\n ([e]) => {\n if (!e) return\n setHidden(e.isIntersecting)\n if (!e.isIntersecting) {\n const rootTop = e.rootBounds?.top ?? scrollEl.getBoundingClientRect().top\n setPromptAbove(e.boundingClientRect.top < rootTop)\n }\n },\n { root: scrollEl, threshold: 0 }\n )\n observer.observe(target)\n const onScroll = () => {\n const r = target.getBoundingClientRect()\n const sr = scrollEl.getBoundingClientRect()\n setPromptAbove(r.top < sr.top)\n }\n scrollEl.addEventListener('scroll', onScroll, { passive: true })\n return () => { observer.disconnect(); scrollEl.removeEventListener('scroll', onScroll) }\n }, [lastOutbound?.id, scrollRef])\n\n if (hidden || !lastOutbound || !lastOutbound.body.trim()) return null\n\n const expanded = expandedByPrompt?.id === lastOutbound.id ? expandedByPrompt.value : false\n const collapsed = collapsedByPrompt?.id === lastOutbound.id ? collapsedByPrompt.value : false\n\n function scrollToPrompt() {\n const scrollEl = scrollRef.current\n if (!scrollEl || !lastOutbound) return\n const target = scrollEl.querySelector(`[data-msg-id=\"${lastOutbound.id}\"]`)\n target?.scrollIntoView({ behavior: 'smooth', block: 'center' })\n }\n\n const arrow = promptAbove ? '↑' : '↓'\n\n if (collapsed) {\n return (\n <div className=\"sticky top-0 z-10 -mx-3 md:-mx-4 -mt-3 md:-mt-4 bg-background\">\n <button\n type=\"button\"\n className=\"w-full flex items-center justify-center gap-1.5 py-1 text-[11px] text-primary/60 hover:text-primary border-b border-primary/10 transition-colors\"\n onClick={() => setCollapsedByPrompt({ id: lastOutbound.id, value: false })}\n >\n <span>Your prompt</span>\n <ChevronDown className=\"w-3 h-3\" />\n </button>\n </div>\n )\n }\n\n return (\n <div className=\"sticky top-0 z-10 -mx-3 md:-mx-4 -mt-3 md:-mt-4 px-2 md:px-3 pt-2 pb-1.5 bg-background border-b border-primary/10\">\n <div className=\"flex items-center gap-2 text-[11px] text-muted-foreground mb-0.5\">\n <span className=\"font-medium text-primary/70\">Your prompt</span>\n <button\n type=\"button\"\n className=\"ml-auto hover:text-foreground transition-colors\"\n onClick={scrollToPrompt}\n >\n {arrow} scroll to original\n </button>\n <button\n type=\"button\"\n className=\"hover:text-foreground transition-colors\"\n onClick={() => setCollapsedByPrompt({ id: lastOutbound.id, value: true })}\n title=\"Minimize\"\n >\n <ChevronUp className=\"w-3 h-3\" />\n </button>\n </div>\n <p\n className={cn('text-sm text-foreground leading-snug cursor-pointer', !expanded && 'line-clamp-2')}\n onClick={() => setExpandedByPrompt({ id: lastOutbound.id, value: !expanded })}\n >\n {lastOutbound.body}\n </p>\n </div>\n )\n}\n","\nimport { useSyncExternalStore } from 'react'\nimport { voiceTts } from '@/lib/voice'\n\nexport function useTtsPlayingKey(): string | null {\n return useSyncExternalStore(\n (cb) => voiceTts.subscribe(cb),\n () => voiceTts.getPlayingKey(),\n () => null,\n )\n}\n","\nimport { memo, useEffect, useRef, useState } from 'react'\nimport { AlertCircle, CircleStop, Download, FileText, Loader2, SmilePlus, Volume2, X, ZoomIn } from 'lucide-react'\nimport { voiceTts } from '@/lib/voice'\nimport { useRelayStore } from '@/store'\nimport { FormattedBody } from '@/components/shared/formatted-body'\nimport { Button } from '@/components/ui/button'\nimport { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'\nimport { apiBlob } from '@/lib/api'\nimport { HUMAN_AGENT_ID } from '@/lib/constants'\nimport { messageBody } from '@/lib/display'\nimport type { AttachmentRef, Message } from '@/types'\nimport { cn } from '@/lib/utils'\nimport type { ReferencedPathInfo } from './types'\nimport {\n chatTimestamp,\n groupedReactions,\n hasActiveTextSelection,\n isReactionEvent,\n messageAttachments,\n outboundReceipt,\n QUICK_REACTIONS,\n resolveRelativePath,\n} from './helpers'\nimport { useTtsPlayingKey } from './hooks/useTtsPlayingKey'\n\nfunction AttachmentPreview({ attachment, outbound }: { attachment: AttachmentRef; outbound: boolean }) {\n const isImage = attachment.kind === 'image'\n const title = attachment.title || attachment.artifactId\n const [objectUrl, setObjectUrl] = useState<string | null>(null)\n const [error, setError] = useState<string | null>(null)\n const [loading, setLoading] = useState(false)\n const [lightboxOpen, setLightboxOpen] = useState(false)\n\n useEffect(() => {\n let cancelled = false\n let url: string | null = null\n\n async function load() {\n setLoading(true)\n setError(null)\n setObjectUrl(null)\n try {\n const blob = await apiBlob(`/artifacts/${encodeURIComponent(attachment.artifactId)}/content`)\n if (cancelled) return\n url = URL.createObjectURL(blob)\n setObjectUrl(url)\n } catch (e) {\n if (!cancelled) setError((e as Error).message)\n } finally {\n if (!cancelled) setLoading(false)\n }\n }\n\n void load()\n return () => {\n cancelled = true\n if (url) URL.revokeObjectURL(url)\n }\n }, [attachment.artifactId])\n\n function download() {\n if (!objectUrl) return\n const a = document.createElement('a')\n a.href = objectUrl\n a.download = title\n document.body.appendChild(a)\n a.click()\n a.remove()\n }\n\n if (isImage) {\n return (\n <>\n <button\n type=\"button\"\n onClick={() => objectUrl && setLightboxOpen(true)}\n disabled={!objectUrl}\n className=\"group/img mt-2 block overflow-hidden rounded-md border border-foreground/10 bg-black/10 text-left disabled:cursor-default relative\"\n >\n {objectUrl ? (\n <>\n <img src={objectUrl} alt={title} loading=\"lazy\" className=\"block max-h-72 max-w-full object-contain\" />\n <span className=\"absolute inset-0 flex items-center justify-center bg-black/0 group-hover/img:bg-black/30 transition-colors\">\n <ZoomIn className=\"w-6 h-6 text-white opacity-0 group-hover/img:opacity-100 transition-opacity drop-shadow-md\" />\n </span>\n </>\n ) : (\n <span className={cn('flex min-h-20 items-center gap-2 px-3 py-2 text-xs', error ? 'text-red-400' : 'text-muted-foreground')}>\n {loading ? <Loader2 className=\"h-4 w-4 animate-spin\" /> : <AlertCircle className=\"h-4 w-4\" />}\n {error || 'Loading image'}\n </span>\n )}\n </button>\n {objectUrl && (\n <Dialog open={lightboxOpen} onOpenChange={setLightboxOpen}>\n <DialogContent className=\"max-w-[95vw] max-h-[95vh] w-auto p-0 bg-black/95 border-zinc-800 gap-0 overflow-hidden\" showCloseButton={false}>\n <DialogTitle className=\"sr-only\">{title}</DialogTitle>\n <div className=\"relative flex items-center justify-center min-h-[200px]\">\n <img src={objectUrl} alt={title} className=\"max-w-[93vw] max-h-[90vh] object-contain\" />\n <div className=\"absolute top-2 right-2 flex gap-1\">\n <button type=\"button\" onClick={download} className=\"rounded-md bg-black/60 hover:bg-black/80 p-2 text-white transition-colors\" title=\"Download\">\n <Download className=\"w-4 h-4\" />\n </button>\n <button type=\"button\" onClick={() => setLightboxOpen(false)} className=\"rounded-md bg-black/60 hover:bg-black/80 p-2 text-white transition-colors\" title=\"Close\">\n <X className=\"w-4 h-4\" />\n </button>\n </div>\n </div>\n </DialogContent>\n </Dialog>\n )}\n </>\n )\n }\n\n return (\n <button\n type=\"button\"\n onClick={download}\n disabled={!objectUrl}\n className={cn(\n 'mt-2 flex w-full items-center gap-2 rounded-md border px-2.5 py-2 text-left text-xs transition-colors disabled:cursor-default disabled:opacity-70',\n outbound ? 'border-primary-foreground/20 bg-primary-foreground/10 hover:bg-primary-foreground/15' : 'border-border bg-background hover:bg-muted'\n )}\n >\n {loading ? <Loader2 className=\"h-4 w-4 shrink-0 animate-spin\" /> : error ? <AlertCircle className=\"h-4 w-4 shrink-0 text-red-400\" /> : <FileText className=\"h-4 w-4 shrink-0\" />}\n <span className={cn('min-w-0 flex-1 truncate', error && 'text-red-400')}>{error || title}</span>\n <Download className=\"h-3.5 w-3.5 shrink-0\" />\n </button>\n )\n}\n\nfunction AddReaction({ open, onToggle, onReact }: { open: boolean; onToggle: () => void; onReact: (emoji: string) => void }) {\n return (\n <div className=\"relative shrink-0\">\n <button\n type=\"button\"\n title=\"Add reaction\"\n onClick={onToggle}\n className={cn(\n 'inline-flex h-5 w-6 items-center justify-center rounded-full border border-border bg-popover text-muted-foreground shadow-sm transition hover:bg-muted hover:text-foreground',\n open ? 'opacity-100' : 'opacity-0 pointer-events-none md:group-hover/msg:opacity-100 md:group-hover/msg:pointer-events-auto'\n )}\n >\n <SmilePlus className=\"h-3 w-3\" />\n </button>\n {open && (\n <div className=\"absolute bottom-full left-0 z-30 mb-1 flex gap-0.5 rounded-full border border-border bg-popover p-0.5 shadow-md\">\n {QUICK_REACTIONS.map((emoji) => (\n <button\n key={emoji}\n type=\"button\"\n title={`React ${emoji}`}\n onClick={() => onReact(emoji)}\n className=\"inline-flex h-6 w-7 items-center justify-center rounded-full text-xs transition-colors hover:bg-muted\"\n >\n {emoji}\n </button>\n ))}\n </div>\n )}\n </div>\n )\n}\n\nexport const MessageBubble = memo(function MessageBubble({\n msg,\n peer,\n onOpenReferencedPath,\n onPreviewReferencedPath,\n onPreviewReferencedPathEnd,\n}: {\n msg: Message\n peer: string\n onOpenReferencedPath?: (path: string, line?: number, type?: ReferencedPathInfo['type']) => void\n onPreviewReferencedPath?: (path: string, line?: number, anchor?: DOMRect) => void\n onPreviewReferencedPathEnd?: () => void\n}) {\n const isPeerMessage = msg.from !== HUMAN_AGENT_ID && msg.to !== HUMAN_AGENT_ID\n // For agent↔agent messages, treat the selected agent (peer) as the local side:\n // messages it sent are outbound (right), messages it received are inbound (left).\n const isOutbound = isPeerMessage ? msg.from === peer : msg.from === HUMAN_AGENT_ID\n const peerLabel = isPeerMessage\n ? (isOutbound ? `→ ${msg.to}` : `from ${msg.from}`)\n : null\n const reactToMessage = useRelayStore((s) => s.reactToMessage)\n const voiceTtsEnabled = useRelayStore((s) => s.voiceTtsEnabled)\n const ttsPlayingKey = useTtsPlayingKey()\n const peerCwd = useRelayStore((s) => {\n const cwd = s.agentsById[peer]?.meta?.cwd\n return typeof cwd === 'string' ? cwd : ''\n })\n const [showQuickReact, setShowQuickReact] = useState(false)\n const bubbleRef = useRef<HTMLDivElement>(null)\n const pointerStartRef = useRef<{ x: number; y: number } | null>(null)\n const suppressBubbleClickRef = useRef(false)\n const body = messageBody(msg)\n const time = chatTimestamp(msg.occurredAt ?? (msg.createdAt as string))\n const attachments = messageAttachments(msg)\n const reactions = groupedReactions(msg)\n const receipt = isOutbound ? outboundReceipt(msg, peer) : null\n const ReceiptIcon = receipt?.icon\n // On-demand TTS: replay any agent response through the same Kokoro/browser\n // pipeline. Only when the speaker is on, and only for inbound non-reaction text.\n const isTtsPlaying = ttsPlayingKey === String(msg.id)\n const showPlayButton = voiceTtsEnabled && !isOutbound && !isPeerMessage && !isReactionEvent(msg) && body.trim().length > 0\n function togglePlay(e: React.MouseEvent) {\n e.stopPropagation()\n if (isTtsPlaying) voiceTts.bargeIn()\n else voiceTts.speak(msg.body, String(msg.id))\n }\n useEffect(() => {\n if (!showQuickReact) return\n function dismiss(e: MouseEvent | TouchEvent) {\n if (hasActiveTextSelection()) return\n if (bubbleRef.current && !bubbleRef.current.contains(e.target as Node)) setShowQuickReact(false)\n }\n document.addEventListener('mousedown', dismiss)\n document.addEventListener('touchstart', dismiss)\n return () => { document.removeEventListener('mousedown', dismiss); document.removeEventListener('touchstart', dismiss) }\n }, [showQuickReact])\n\n function resolvedReferencedPath(path: string): string {\n return resolveRelativePath(peerCwd || '/', path)\n }\n\n function openReferencedPath(path: string, line?: number) {\n const absolute = resolvedReferencedPath(path)\n onOpenReferencedPath?.(absolute, line)\n }\n\n function previewReferencedPath(path: string, line?: number, anchor?: DOMRect) {\n const absolute = resolvedReferencedPath(path)\n onPreviewReferencedPath?.(absolute, line, anchor)\n }\n\n function handleReact(emoji: string) {\n reactToMessage(msg, emoji)\n setShowQuickReact(false)\n }\n\n function handleBubblePointerDown(e: React.PointerEvent<HTMLDivElement>) {\n if (e.button !== 0) return\n pointerStartRef.current = { x: e.clientX, y: e.clientY }\n suppressBubbleClickRef.current = false\n }\n\n function handleBubblePointerMove(e: React.PointerEvent<HTMLDivElement>) {\n const start = pointerStartRef.current\n if (!start) return\n if (Math.abs(e.clientX - start.x) > 3 || Math.abs(e.clientY - start.y) > 3) {\n suppressBubbleClickRef.current = true\n }\n }\n\n function handleBubbleClick(e: React.MouseEvent<HTMLDivElement>) {\n if (isReactionEvent(msg) || isOutbound || isPeerMessage) return\n const target = e.target as HTMLElement\n if (target.closest('a,button,input,textarea,select,[role=\"button\"]')) return\n if (suppressBubbleClickRef.current || hasActiveTextSelection()) {\n suppressBubbleClickRef.current = false\n return\n }\n setShowQuickReact((v) => !v)\n }\n\n return (\n <div data-msg-id={msg.id} className={cn('group/msg flex mb-3', isOutbound ? 'justify-end' : 'justify-start')}>\n <div ref={bubbleRef} className=\"relative max-w-[85%] md:max-w-[75%]\">\n {showPlayButton && (\n <button\n type=\"button\"\n title={isTtsPlaying ? 'Stop playback' : 'Play aloud'}\n onClick={togglePlay}\n className={cn(\n 'absolute -top-2 -right-2 z-20 inline-flex h-6 w-6 items-center justify-center rounded-full border bg-popover shadow-sm transition',\n isTtsPlaying\n ? 'border-primary/50 text-primary opacity-100'\n // Hide-until-hover only on hover-capable devices; touch screens (iPad)\n // have no hover, so keep the button visible there instead of opacity-0.\n : 'border-border text-muted-foreground opacity-70 hover:bg-muted hover:text-foreground hover:opacity-100 [@media(hover:hover)]:md:opacity-0 [@media(hover:hover)]:md:group-hover/msg:opacity-100'\n )}\n >\n {isTtsPlaying ? <CircleStop className=\"h-3.5 w-3.5 animate-pulse\" /> : <Volume2 className=\"h-3.5 w-3.5\" />}\n </button>\n )}\n <div\n className={cn(\n 'rounded-2xl px-3.5 py-2 text-sm select-text',\n !isOutbound && !isReactionEvent(msg) && !isPeerMessage && 'cursor-pointer',\n isOutbound\n ? 'bg-primary text-primary-foreground rounded-br-sm'\n : 'bg-card ring-1 ring-foreground/10 rounded-bl-sm'\n )}\n onPointerDown={handleBubblePointerDown}\n onPointerMove={handleBubblePointerMove}\n onClick={handleBubbleClick}\n >\n {peerLabel && (\n <p className={cn('text-xs font-medium mb-1 opacity-60', isOutbound ? 'text-primary-foreground' : 'text-muted-foreground')}>\n {peerLabel}\n </p>\n )}\n {msg.subject && (\n <p className={cn('text-xs font-semibold mb-1', isOutbound ? 'text-primary-foreground/70' : 'text-muted-foreground')}>\n {msg.subject}\n </p>\n )}\n <FormattedBody\n text={body}\n rawBody={msg.body}\n className=\"leading-relaxed\"\n onOpenPath={openReferencedPath}\n onPreviewPath={previewReferencedPath}\n onPreviewPathEnd={onPreviewReferencedPathEnd}\n resolvePathTitle={(path, line) => `${resolvedReferencedPath(path)}${line ? `:${line}` : ''}`}\n />\n {attachments.map((attachment) => (\n <AttachmentPreview key={`${msg.id}-${attachment.artifactId}-${attachment.role || ''}`} attachment={attachment} outbound={isOutbound} />\n ))}\n <p className={cn('text-xs mt-1 flex items-center gap-1.5', isOutbound ? 'justify-end text-primary-foreground/60' : 'justify-end text-muted-foreground')}>\n <span className=\"opacity-40\">#{msg.id}</span>\n <span>{time}</span>\n {receipt && ReceiptIcon && (\n <span\n className={cn(\n 'inline-flex items-center gap-1',\n receipt.tone === 'ok' && 'text-emerald-300',\n receipt.tone === 'warn' && 'text-amber-200',\n receipt.tone === 'danger' && 'text-red-200'\n )}\n title={receipt.title}\n >\n <ReceiptIcon className=\"h-3 w-3\" />\n {receipt.label}\n </span>\n )}\n </p>\n </div>\n {!isReactionEvent(msg) && reactions.length > 0 && (\n <div className={cn('flex flex-wrap items-center gap-0.5 -mt-1 relative z-10', isOutbound ? 'justify-end pr-2' : 'justify-start pl-2')}>\n {!isOutbound && <AddReaction open={showQuickReact} onToggle={() => setShowQuickReact((v) => !v)} onReact={handleReact} />}\n {reactions.map((reaction) => (\n <button\n key={reaction.emoji}\n type=\"button\"\n title={reaction.actors.join(', ')}\n onClick={() => handleReact(reaction.emoji)}\n className={cn(\n 'inline-flex h-5 items-center gap-0.5 rounded-full border px-1.5 text-[11px] shadow-sm transition-colors',\n reaction.mine\n ? 'border-primary/40 bg-primary/10 text-primary'\n : 'border-border bg-background hover:bg-muted text-foreground'\n )}\n >\n <span>{reaction.emoji}</span>\n {reaction.count > 1 && <span>{reaction.count}</span>}\n </button>\n ))}\n </div>\n )}\n {!isReactionEvent(msg) && !isOutbound && reactions.length === 0 && (\n <div className=\"absolute -bottom-2.5 left-1 z-20\">\n <AddReaction open={showQuickReact} onToggle={() => setShowQuickReact((v) => !v)} onReact={handleReact} />\n </div>\n )}\n </div>\n </div>\n )\n})\n"],"mappings":"mfAiBA,EAAA,geAgBA,GAAA,IAAA,IAAA,OAAA,KAAA,EAAA,CAAA,CACA,GAAA,IAMA,SAAA,EAAA,EAAA,sDAOA,SAAA,GAAA,EAAA,gRAmBA,SAAA,GAAA,EAAA,8MAUA,SAAA,GAAA,EAAA,6CAIA,SAAA,EAAA,EAAA,+HAKA,SAAA,GAAA,EAAA,wNAcA,SAAA,GAAA,EAAA,EAAA,EAAA,EAAA,EAAA,CAAA,6/CA8FA,SAAA,GAAA,EAAA,EAAA,uFCnLA,SAAgB,EAAY,EAAsB,CAGhD,OAFI,EAAO,KAAa,GAAG,EAAK,IAC5B,EAAO,KAAO,KAAa,IAAI,EAAO,MAAM,QAAQ,EAAE,CAAC,KACpD,IAAI,EAAO,KAAO,MAAM,QAAQ,EAAE,CAAC,KAG5C,SAAgB,GAAoB,EAAa,EAAsB,CACrE,GAAI,EAAK,WAAW,IAAI,CAAE,OAAO,EACjC,IAAM,EAAQ,GAAG,EAAI,QAAQ,OAAQ,GAAG,CAAC,GAAG,IAAO,MAAM,IAAI,CACvD,EAAkB,EAAE,CAC1B,IAAK,IAAM,KAAQ,EACb,CAAC,GAAQ,IAAS,MAClB,IAAS,KAAM,EAAM,KAAK,CACzB,EAAM,KAAK,EAAK,EAEvB,MAAO,IAAM,EAAM,KAAK,I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Y,CAAA,CAClC,EAAQ,MACJ,GAEP,GACA,GACL,CAAC,EAAgB,EAAI,EAAI,EAAU,OAAS,IAC3C,EAAA,EAAA,MAAC,MAAD,CAAK,UAAW,EAAG,0DAA2D,EAAa,mBAAqB,qBAAqB,UAArI,CACG,CAAC,IAAc,EAAA,EAAA,KAAC,EAAD,CAAa,KAAM,EAAgB,aAAgB,EAAmB,GAAM,CAAC,EAAE,CAAE,QAAS,EAAe,CAAA,CACxH,EAAU,IAAK,IACd,EAAA,EAAA,MAAC,SAAD,CAEE,KAAK,SACL,MAAO,EAAS,OAAO,KAAK,KAAK,CACjC,YAAe,EAAY,EAAS,MAAM,CAC1C,UAAW,EACT,0GACA,EAAS,KACL,+CACA,6DACL,UAVH,EAYE,EAAA,EAAA,KAAC,OAAD,CAAA,SAAO,EAAS,MAAa,CAAA,CAC5B,EAAS,MAAQ,IAAK,EAAA,EAAA,KAAC,OAAD,CAAA,SAAO,EAAS,MAAa,CAAA,CAC7C,EAbF,EAAS,MAaP,CACT,CACE,GAEP,CAAC,EAAgB,EAAI,EAAI,CAAC,GAAc,EAAU,SAAW,IAC5D,EAAA,EAAA,KAAC,MAAD,CAAK,UAAU,6CACb,EAAA,EAAA,KAAC,EAAD,CAAa,KAAM,EAAgB,aAAgB,EAAmB,GAAM,CAAC,EAAE,CAAE,QAAS,EAAe,CAAA,CACrG,CAAA,CAEJ,GACF,CAAA,EAER"}
@@ -1,2 +1,2 @@
1
- import{r as e}from"./chunk-CilyBKbf.js";import{Gn as t,Nn as n,St as r,jn as i,on as a,rn as o}from"./lucide-react-C3j5Huiw.js";import{n as s,r as c,t as l}from"./store-DKtaJZyC.js";var u=e(t(),1),d=`(max-width: 767px)`;function f(e){if(typeof window>`u`)return()=>{};let t=window.matchMedia(d);return t.addEventListener(`change`,e),()=>t.removeEventListener(`change`,e)}function p(){return(0,u.useSyncExternalStore)(f,()=>typeof window<`u`?window.matchMedia(d).matches:!1,()=>!1)}var m=n(),h=196,g=68,_=52,v=16,y=14,b=[`landed`,`in-progress`,`pending`,`blocked`],x={landed:{label:`landed`,dot:`bg-emerald-400`,accent:`border-l-emerald-400`,text:`text-emerald-300`,wire:`#34d399`},"in-progress":{label:`in progress`,dot:`bg-sky-400`,accent:`border-l-sky-400`,text:`text-sky-300`,wire:`#38bdf8`},pending:{label:`pending`,dot:`bg-amber-400`,accent:`border-l-amber-400`,text:`text-amber-300`,wire:`#fbbf24`},blocked:{label:`blocked`,dot:`bg-red-400`,accent:`border-l-red-400`,text:`text-red-300`,wire:`#f87171`}};function S(e){return e?e.label||(e.policyName?`policy:${e.policyName}`:e.agentId||``):``}function C(e){let t=new Map(e.nodes.map(e=>[e.id,e])),n=new Map(e.nodes.map((e,t)=>[e.id,t])),r=new Map,i=new Map(e.nodes.map(e=>[e.id,0]));for(let n of e.edges)!t.has(n.from)||!t.has(n.to)||(r.set(n.from,[...r.get(n.from)??[],n.to]),i.set(n.to,(i.get(n.to)??0)+1));let a=new Map(e.nodes.map(e=>[e.id,0])),o=e.nodes.filter(e=>(i.get(e.id)??0)===0).map(e=>e.id),s=new Set;for(;o.length;){let e=o.shift();s.add(e);let t=a.get(e)??0;for(let n of r.get(e)??[])a.set(n,Math.max(a.get(n)??0,t+1)),i.set(n,(i.get(n)??0)-1),(i.get(n)??0)===0&&o.push(n)}let c=Math.max(0,...Array.from(a.values()))+1;for(let t of e.nodes)s.has(t.id)||a.set(t.id,c++);let l=new Map;for(let t of e.nodes){let e=a.get(t.id)??0;l.set(e,[...l.get(e)??[],t])}let u=[...l.entries()].sort(([e],[t])=>e-t),d=Math.max(1,...u.map(([,e])=>e.length)),f=g+v,p=[];u.forEach(([e,t],r)=>{let i=[...t].sort((e,t)=>(e.lane||``).localeCompare(t.lane||``)||(n.get(e.id)??0)-(n.get(t.id)??0)),a=(d-i.length)*f/2;i.forEach((t,n)=>{p.push({node:t,layer:e,x:y+r*(h+_),y:y+a+n*f})})});let m=u.length;return{nodes:p,width:Math.max(320,y*2+m*h+Math.max(0,m-1)*_),height:Math.max(g+y*2,y*2+d*g+Math.max(0,d-1)*v)}}function w(e,t){let n=e.x+h,r=e.y+g/2,i=t.x,a=t.y+g/2,o=n+Math.max(20,(i-n)/2);return`M ${n} ${r} C ${o} ${r}, ${o} ${a}, ${i} ${a}`}function T({threadId:e,teamId:t,channel:n}){let d=t?c(t,n):e?s(e,n):``,f=l(e=>t?e.plansByTeam[d]:d?e.plansByThread[d]:null),_=l(e=>e.fetchPlan),v=l(e=>e.planCollapsed),y=l(e=>e.setPlanCollapsed),T=p(),E=v??T;(0,u.useEffect)(()=>{if(t){_({teamId:t,channel:n});return}e&&_({threadId:e,channel:n})},[n,_,t,e]);let D=(0,u.useMemo)(()=>f?C(f):null,[f]),O=(0,u.useMemo)(()=>new Map(D?.nodes.map(e=>[e.node.id,e])??[]),[D]),k=(0,u.useMemo)(()=>{if(!f)return[];let e=new Map;for(let t of f.nodes)e.set(t.status,(e.get(t.status)??0)+1);return b.filter(t=>e.has(t)).map(t=>({status:t,count:e.get(t)??0}))},[f]);if(!f||!D)return null;let A=f.nodes.length,j=k.find(e=>e.status===`landed`)?.count??0,M=`${A} node${A===1?``:`s`}${j>0?` · ${j} landed`:``}`;return(0,m.jsxs)(`section`,{className:`shrink-0 border-b border-border bg-card/45 px-3 py-2`,children:[(0,m.jsxs)(`button`,{type:`button`,onClick:()=>y(!E),"aria-expanded":!E,"aria-label":E?`Expand plan graph`:`Collapse plan graph`,className:i(`flex w-full min-w-0 items-center gap-2 text-left`,!E&&`mb-2`),children:[(0,m.jsx)(`span`,{className:`flex h-5 w-5 shrink-0 items-center justify-center rounded bg-muted/60`,children:(0,m.jsx)(r,{className:`h-3 w-3 text-muted-foreground`})}),(0,m.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,m.jsx)(`div`,{className:`truncate text-[13px] font-semibold leading-tight text-foreground`,children:f.title||`Plan`}),(0,m.jsx)(`div`,{className:`truncate text-[11px] leading-tight text-muted-foreground`,children:E?M:f.objective||M})]}),k.length>0&&(0,m.jsx)(`div`,{className:`hidden shrink-0 items-center gap-2.5 sm:flex`,children:k.map(({status:e,count:t})=>(0,m.jsxs)(`span`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground`,children:[(0,m.jsx)(`span`,{className:i(`h-1.5 w-1.5 rounded-full`,x[e].dot)}),(0,m.jsx)(`span`,{className:i(`font-medium tabular-nums`,x[e].text),children:t}),(0,m.jsx)(`span`,{children:x[e].label})]},e))}),(0,m.jsxs)(`span`,{className:`shrink-0 rounded bg-muted/60 px-1.5 py-0.5 text-[10px] font-medium tabular-nums text-muted-foreground`,children:[`v`,f.version]}),(0,m.jsx)(`span`,{className:`flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted/60 hover:text-foreground`,children:E?(0,m.jsx)(a,{className:`h-3.5 w-3.5`}):(0,m.jsx)(o,{className:`h-3.5 w-3.5`})})]}),E?null:f.nodes.length===0?(0,m.jsx)(`div`,{className:`rounded-md border border-dashed border-border px-3 py-3 text-center text-xs text-muted-foreground`,children:`No nodes yet — the plan graph fills in as the team is composed.`}):(0,m.jsx)(`div`,{className:`max-h-[min(46vh,360px)] overflow-auto`,children:(0,m.jsxs)(`div`,{className:`relative`,style:{width:D.width,height:D.height},children:[(0,m.jsxs)(`svg`,{className:`pointer-events-none absolute inset-0`,width:D.width,height:D.height,"aria-hidden":`true`,children:[(0,m.jsx)(`defs`,{children:b.map(e=>(0,m.jsx)(`marker`,{id:`plan-arrow-${e}`,viewBox:`0 0 8 8`,refX:`6.5`,refY:`4`,markerWidth:`6`,markerHeight:`6`,orient:`auto-start-reverse`,children:(0,m.jsx)(`path`,{d:`M0 0 L8 4 L0 8 z`,fill:x[e].wire})},e))}),f.edges.map(e=>{let t=O.get(e.from),n=O.get(e.to);if(!t||!n)return null;let r=x[t.node.status];return(0,m.jsx)(`path`,{d:w(t,n),stroke:r.wire,strokeOpacity:.7,strokeWidth:2,fill:`none`,strokeLinecap:`round`,markerEnd:`url(#plan-arrow-${t.node.status})`},`${e.from}->${e.to}`)})]}),D.nodes.map(({node:e,x:t,y:n})=>{let r=x[e.status],a=S(e.ownerRef);return(0,m.jsxs)(`article`,{className:i(`group absolute flex flex-col justify-between rounded-md border border-l-[3px] bg-background/95 p-2`,`shadow-sm transition-all hover:-translate-y-px hover:border-border hover:shadow-md hover:bg-background`,r.accent),style:{left:t,top:n,width:h,height:g},title:e.scopeBlurb||e.label,children:[(0,m.jsx)(`div`,{className:`truncate text-xs font-semibold leading-tight text-foreground`,children:e.label}),(e.scopeBlurb||e.id)&&(0,m.jsx)(`div`,{className:`truncate text-[10px] leading-tight text-muted-foreground`,children:e.scopeBlurb||e.id}),(0,m.jsxs)(`div`,{className:`flex min-w-0 items-center justify-between gap-1.5`,children:[(0,m.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1.5`,children:[(0,m.jsx)(`span`,{className:i(`h-1.5 w-1.5 shrink-0 rounded-full`,r.dot)}),(0,m.jsx)(`span`,{className:i(`text-[10px] font-medium`,r.text),children:r.label})]}),(0,m.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5`,children:[a&&(0,m.jsx)(`span`,{className:`truncate text-[10px] text-muted-foreground`,children:a}),e.lane&&(0,m.jsx)(`span`,{className:`shrink-0 rounded-sm bg-muted/70 px-1 py-px text-[9px] font-medium uppercase tracking-wide text-muted-foreground`,children:e.lane})]})]})]},e.id)})]})})]})}export{T as t};
2
- //# sourceMappingURL=PlanGraphPanel-DpTMkCBs.js.map
1
+ import{r as e}from"./chunk-CilyBKbf.js";import{Gn as t,Nn as n,St as r,jn as i,on as a,rn as o}from"./lucide-react-C3j5Huiw.js";import{n as s,r as c,t as l}from"./store-DmxnYVm1.js";var u=e(t(),1),d=`(max-width: 767px)`;function f(e){if(typeof window>`u`)return()=>{};let t=window.matchMedia(d);return t.addEventListener(`change`,e),()=>t.removeEventListener(`change`,e)}function p(){return(0,u.useSyncExternalStore)(f,()=>typeof window<`u`?window.matchMedia(d).matches:!1,()=>!1)}var m=n(),h=196,g=68,_=52,v=16,y=14,b=[`landed`,`in-progress`,`pending`,`blocked`],x={landed:{label:`landed`,dot:`bg-emerald-400`,accent:`border-l-emerald-400`,text:`text-emerald-300`,wire:`#34d399`},"in-progress":{label:`in progress`,dot:`bg-sky-400`,accent:`border-l-sky-400`,text:`text-sky-300`,wire:`#38bdf8`},pending:{label:`pending`,dot:`bg-amber-400`,accent:`border-l-amber-400`,text:`text-amber-300`,wire:`#fbbf24`},blocked:{label:`blocked`,dot:`bg-red-400`,accent:`border-l-red-400`,text:`text-red-300`,wire:`#f87171`}};function S(e){return e?e.label||(e.policyName?`policy:${e.policyName}`:e.agentId||``):``}function C(e){let t=new Map(e.nodes.map(e=>[e.id,e])),n=new Map(e.nodes.map((e,t)=>[e.id,t])),r=new Map,i=new Map(e.nodes.map(e=>[e.id,0]));for(let n of e.edges)!t.has(n.from)||!t.has(n.to)||(r.set(n.from,[...r.get(n.from)??[],n.to]),i.set(n.to,(i.get(n.to)??0)+1));let a=new Map(e.nodes.map(e=>[e.id,0])),o=e.nodes.filter(e=>(i.get(e.id)??0)===0).map(e=>e.id),s=new Set;for(;o.length;){let e=o.shift();s.add(e);let t=a.get(e)??0;for(let n of r.get(e)??[])a.set(n,Math.max(a.get(n)??0,t+1)),i.set(n,(i.get(n)??0)-1),(i.get(n)??0)===0&&o.push(n)}let c=Math.max(0,...Array.from(a.values()))+1;for(let t of e.nodes)s.has(t.id)||a.set(t.id,c++);let l=new Map;for(let t of e.nodes){let e=a.get(t.id)??0;l.set(e,[...l.get(e)??[],t])}let u=[...l.entries()].sort(([e],[t])=>e-t),d=Math.max(1,...u.map(([,e])=>e.length)),f=g+v,p=[];u.forEach(([e,t],r)=>{let i=[...t].sort((e,t)=>(e.lane||``).localeCompare(t.lane||``)||(n.get(e.id)??0)-(n.get(t.id)??0)),a=(d-i.length)*f/2;i.forEach((t,n)=>{p.push({node:t,layer:e,x:y+r*(h+_),y:y+a+n*f})})});let m=u.length;return{nodes:p,width:Math.max(320,y*2+m*h+Math.max(0,m-1)*_),height:Math.max(g+y*2,y*2+d*g+Math.max(0,d-1)*v)}}function w(e,t){let n=e.x+h,r=e.y+g/2,i=t.x,a=t.y+g/2,o=n+Math.max(20,(i-n)/2);return`M ${n} ${r} C ${o} ${r}, ${o} ${a}, ${i} ${a}`}function T({threadId:e,teamId:t,channel:n}){let d=t?c(t,n):e?s(e,n):``,f=l(e=>t?e.plansByTeam[d]:d?e.plansByThread[d]:null),_=l(e=>e.fetchPlan),v=l(e=>e.planCollapsed),y=l(e=>e.setPlanCollapsed),T=p(),E=v??T;(0,u.useEffect)(()=>{if(t){_({teamId:t,channel:n});return}e&&_({threadId:e,channel:n})},[n,_,t,e]);let D=(0,u.useMemo)(()=>f?C(f):null,[f]),O=(0,u.useMemo)(()=>new Map(D?.nodes.map(e=>[e.node.id,e])??[]),[D]),k=(0,u.useMemo)(()=>{if(!f)return[];let e=new Map;for(let t of f.nodes)e.set(t.status,(e.get(t.status)??0)+1);return b.filter(t=>e.has(t)).map(t=>({status:t,count:e.get(t)??0}))},[f]);if(!f||!D)return null;let A=f.nodes.length,j=k.find(e=>e.status===`landed`)?.count??0,M=`${A} node${A===1?``:`s`}${j>0?` · ${j} landed`:``}`;return(0,m.jsxs)(`section`,{className:`shrink-0 border-b border-border bg-card/45 px-3 py-2`,children:[(0,m.jsxs)(`button`,{type:`button`,onClick:()=>y(!E),"aria-expanded":!E,"aria-label":E?`Expand plan graph`:`Collapse plan graph`,className:i(`flex w-full min-w-0 items-center gap-2 text-left`,!E&&`mb-2`),children:[(0,m.jsx)(`span`,{className:`flex h-5 w-5 shrink-0 items-center justify-center rounded bg-muted/60`,children:(0,m.jsx)(r,{className:`h-3 w-3 text-muted-foreground`})}),(0,m.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,m.jsx)(`div`,{className:`truncate text-[13px] font-semibold leading-tight text-foreground`,children:f.title||`Plan`}),(0,m.jsx)(`div`,{className:`truncate text-[11px] leading-tight text-muted-foreground`,children:E?M:f.objective||M})]}),k.length>0&&(0,m.jsx)(`div`,{className:`hidden shrink-0 items-center gap-2.5 sm:flex`,children:k.map(({status:e,count:t})=>(0,m.jsxs)(`span`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground`,children:[(0,m.jsx)(`span`,{className:i(`h-1.5 w-1.5 rounded-full`,x[e].dot)}),(0,m.jsx)(`span`,{className:i(`font-medium tabular-nums`,x[e].text),children:t}),(0,m.jsx)(`span`,{children:x[e].label})]},e))}),(0,m.jsxs)(`span`,{className:`shrink-0 rounded bg-muted/60 px-1.5 py-0.5 text-[10px] font-medium tabular-nums text-muted-foreground`,children:[`v`,f.version]}),(0,m.jsx)(`span`,{className:`flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted/60 hover:text-foreground`,children:E?(0,m.jsx)(a,{className:`h-3.5 w-3.5`}):(0,m.jsx)(o,{className:`h-3.5 w-3.5`})})]}),E?null:f.nodes.length===0?(0,m.jsx)(`div`,{className:`rounded-md border border-dashed border-border px-3 py-3 text-center text-xs text-muted-foreground`,children:`No nodes yet — the plan graph fills in as the team is composed.`}):(0,m.jsx)(`div`,{className:`max-h-[min(46vh,360px)] overflow-auto`,children:(0,m.jsxs)(`div`,{className:`relative`,style:{width:D.width,height:D.height},children:[(0,m.jsxs)(`svg`,{className:`pointer-events-none absolute inset-0`,width:D.width,height:D.height,"aria-hidden":`true`,children:[(0,m.jsx)(`defs`,{children:b.map(e=>(0,m.jsx)(`marker`,{id:`plan-arrow-${e}`,viewBox:`0 0 8 8`,refX:`6.5`,refY:`4`,markerWidth:`6`,markerHeight:`6`,orient:`auto-start-reverse`,children:(0,m.jsx)(`path`,{d:`M0 0 L8 4 L0 8 z`,fill:x[e].wire})},e))}),f.edges.map(e=>{let t=O.get(e.from),n=O.get(e.to);if(!t||!n)return null;let r=x[t.node.status];return(0,m.jsx)(`path`,{d:w(t,n),stroke:r.wire,strokeOpacity:.7,strokeWidth:2,fill:`none`,strokeLinecap:`round`,markerEnd:`url(#plan-arrow-${t.node.status})`},`${e.from}->${e.to}`)})]}),D.nodes.map(({node:e,x:t,y:n})=>{let r=x[e.status],a=S(e.ownerRef);return(0,m.jsxs)(`article`,{className:i(`group absolute flex flex-col justify-between rounded-md border border-l-[3px] bg-background/95 p-2`,`shadow-sm transition-all hover:-translate-y-px hover:border-border hover:shadow-md hover:bg-background`,r.accent),style:{left:t,top:n,width:h,height:g},title:e.scopeBlurb||e.label,children:[(0,m.jsx)(`div`,{className:`truncate text-xs font-semibold leading-tight text-foreground`,children:e.label}),(e.scopeBlurb||e.id)&&(0,m.jsx)(`div`,{className:`truncate text-[10px] leading-tight text-muted-foreground`,children:e.scopeBlurb||e.id}),(0,m.jsxs)(`div`,{className:`flex min-w-0 items-center justify-between gap-1.5`,children:[(0,m.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1.5`,children:[(0,m.jsx)(`span`,{className:i(`h-1.5 w-1.5 shrink-0 rounded-full`,r.dot)}),(0,m.jsx)(`span`,{className:i(`text-[10px] font-medium`,r.text),children:r.label})]}),(0,m.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5`,children:[a&&(0,m.jsx)(`span`,{className:`truncate text-[10px] text-muted-foreground`,children:a}),e.lane&&(0,m.jsx)(`span`,{className:`shrink-0 rounded-sm bg-muted/70 px-1 py-px text-[9px] font-medium uppercase tracking-wide text-muted-foreground`,children:e.lane})]})]})]},e.id)})]})})]})}export{T as t};
2
+ //# sourceMappingURL=PlanGraphPanel-CJROpj66.js.map