draken 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/MEMORY.md +64 -13
  3. package/README.md +25 -19
  4. package/SETUP.md +26 -3
  5. package/TRAY.md +3 -3
  6. package/VOICE.md +8 -6
  7. package/dist/db/schema.d.ts.map +1 -1
  8. package/dist/db/schema.js +65 -0
  9. package/dist/db/schema.js.map +1 -1
  10. package/dist/memory/readiness.d.ts +4 -3
  11. package/dist/memory/readiness.d.ts.map +1 -1
  12. package/dist/memory/readiness.js +128 -35
  13. package/dist/memory/readiness.js.map +1 -1
  14. package/dist/memory/storage.d.ts.map +1 -1
  15. package/dist/memory/storage.js +1 -0
  16. package/dist/memory/storage.js.map +1 -1
  17. package/dist/routes/sync.d.ts.map +1 -1
  18. package/dist/routes/sync.js +9 -0
  19. package/dist/routes/sync.js.map +1 -1
  20. package/dist/sync/activity.d.ts +11 -1
  21. package/dist/sync/activity.d.ts.map +1 -1
  22. package/dist/sync/activity.js +18 -3
  23. package/dist/sync/activity.js.map +1 -1
  24. package/dist/sync/background.d.ts +7 -2
  25. package/dist/sync/background.d.ts.map +1 -1
  26. package/dist/sync/background.js +66 -19
  27. package/dist/sync/background.js.map +1 -1
  28. package/dist/sync/conversation.d.ts +20 -0
  29. package/dist/sync/conversation.d.ts.map +1 -0
  30. package/dist/sync/conversation.js +127 -0
  31. package/dist/sync/conversation.js.map +1 -0
  32. package/dist/sync/manager.d.ts.map +1 -1
  33. package/dist/sync/manager.js +56 -16
  34. package/dist/sync/manager.js.map +1 -1
  35. package/dist/sync/preparation.d.ts +1 -1
  36. package/dist/sync/preparation.d.ts.map +1 -1
  37. package/dist/sync/preparation.js +23 -5
  38. package/dist/sync/preparation.js.map +1 -1
  39. package/dist/sync/store.d.ts +4 -1
  40. package/dist/sync/store.d.ts.map +1 -1
  41. package/dist/sync/store.js +24 -7
  42. package/dist/sync/store.js.map +1 -1
  43. package/dist/sync/summary-preparation.d.ts +14 -0
  44. package/dist/sync/summary-preparation.d.ts.map +1 -0
  45. package/dist/sync/summary-preparation.js +205 -0
  46. package/dist/sync/summary-preparation.js.map +1 -0
  47. package/dist/sync/tree.d.ts +17 -1
  48. package/dist/sync/tree.d.ts.map +1 -1
  49. package/dist/sync/tree.js +94 -29
  50. package/dist/sync/tree.js.map +1 -1
  51. package/dist/sync/update-status.d.ts +9 -0
  52. package/dist/sync/update-status.d.ts.map +1 -0
  53. package/dist/sync/update-status.js +21 -0
  54. package/dist/sync/update-status.js.map +1 -0
  55. package/dist/sync/usage.d.ts +3 -1
  56. package/dist/sync/usage.d.ts.map +1 -1
  57. package/dist/sync/usage.js +24 -6
  58. package/dist/sync/usage.js.map +1 -1
  59. package/dist/types.d.ts +21 -1
  60. package/dist/types.d.ts.map +1 -1
  61. package/dist/voice/live-context.d.ts +1 -1
  62. package/dist/voice/live-context.d.ts.map +1 -1
  63. package/dist/voice/live-context.js +1 -1
  64. package/dist/voice/live.d.ts.map +1 -1
  65. package/dist/voice/live.js +265 -32
  66. package/dist/voice/live.js.map +1 -1
  67. package/package.json +1 -1
  68. package/public/assets/index-sHcfjDUD.js +131 -0
  69. package/public/index.html +1 -1
  70. package/public/assets/index-DXPfCm7z.js +0 -131
@@ -0,0 +1,131 @@
1
+ var qs=Object.defineProperty;var ls=s=>{throw TypeError(s)};var Ds=(s,t,n)=>t in s?qs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n;var I=(s,t,n)=>Ds(s,typeof t!="symbol"?t+"":t,n),ds=(s,t,n)=>t.has(s)||ls("Cannot "+n);var y=(s,t,n)=>(ds(s,t,"read from private field"),n?n.call(s):t.get(s)),L=(s,t,n)=>t.has(s)?ls("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,n),D=(s,t,n,a)=>(ds(s,t,"write to private field"),a?a.call(s,n):t.set(s,n),n);import{r as d,j as e,P as Rs,R as Ls,a as Os}from"./index-B13h0MjX.js";/**
2
+ * @license lucide-react v0.468.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const $s=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),js=(...s)=>s.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim();/**
7
+ * @license lucide-react v0.468.0 - ISC
8
+ *
9
+ * This source code is licensed under the ISC license.
10
+ * See the LICENSE file in the root directory of this source tree.
11
+ */var Us={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
12
+ * @license lucide-react v0.468.0 - ISC
13
+ *
14
+ * This source code is licensed under the ISC license.
15
+ * See the LICENSE file in the root directory of this source tree.
16
+ */const Fs=d.forwardRef(({color:s="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:i="",children:c,iconNode:g,...p},m)=>d.createElement("svg",{ref:m,...Us,width:t,height:t,stroke:s,strokeWidth:a?Number(n)*24/Number(t):n,className:js("lucide",i),...p},[...g.map(([w,o])=>d.createElement(w,o)),...Array.isArray(c)?c:[c]]));/**
17
+ * @license lucide-react v0.468.0 - ISC
18
+ *
19
+ * This source code is licensed under the ISC license.
20
+ * See the LICENSE file in the root directory of this source tree.
21
+ */const M=(s,t)=>{const n=d.forwardRef(({className:a,...i},c)=>d.createElement(Fs,{ref:c,iconNode:t,className:js(`lucide-${$s(s)}`,a),...i}));return n.displayName=`${s}`,n};/**
22
+ * @license lucide-react v0.468.0 - ISC
23
+ *
24
+ * This source code is licensed under the ISC license.
25
+ * See the LICENSE file in the root directory of this source tree.
26
+ */const zs=M("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/**
27
+ * @license lucide-react v0.468.0 - ISC
28
+ *
29
+ * This source code is licensed under the ISC license.
30
+ * See the LICENSE file in the root directory of this source tree.
31
+ */const hs=M("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/**
32
+ * @license lucide-react v0.468.0 - ISC
33
+ *
34
+ * This source code is licensed under the ISC license.
35
+ * See the LICENSE file in the root directory of this source tree.
36
+ */const bs=M("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/**
37
+ * @license lucide-react v0.468.0 - ISC
38
+ *
39
+ * This source code is licensed under the ISC license.
40
+ * See the LICENSE file in the root directory of this source tree.
41
+ */const Hs=M("AudioLines",[["path",{d:"M2 10v3",key:"1fnikh"}],["path",{d:"M6 6v11",key:"11sgs0"}],["path",{d:"M10 3v18",key:"yhl04a"}],["path",{d:"M14 8v7",key:"3a1oy3"}],["path",{d:"M18 5v13",key:"123xd1"}],["path",{d:"M22 10v3",key:"154ddg"}]]);/**
42
+ * @license lucide-react v0.468.0 - ISC
43
+ *
44
+ * This source code is licensed under the ISC license.
45
+ * See the LICENSE file in the root directory of this source tree.
46
+ */const Bs=M("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/**
47
+ * @license lucide-react v0.468.0 - ISC
48
+ *
49
+ * This source code is licensed under the ISC license.
50
+ * See the LICENSE file in the root directory of this source tree.
51
+ */const Vs=M("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/**
52
+ * @license lucide-react v0.468.0 - ISC
53
+ *
54
+ * This source code is licensed under the ISC license.
55
+ * See the LICENSE file in the root directory of this source tree.
56
+ */const Ys=M("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/**
57
+ * @license lucide-react v0.468.0 - ISC
58
+ *
59
+ * This source code is licensed under the ISC license.
60
+ * See the LICENSE file in the root directory of this source tree.
61
+ */const Gs=M("Headphones",[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3",key:"1xhozi"}]]);/**
62
+ * @license lucide-react v0.468.0 - ISC
63
+ *
64
+ * This source code is licensed under the ISC license.
65
+ * See the LICENSE file in the root directory of this source tree.
66
+ */const Ks=M("Keyboard",[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]]);/**
67
+ * @license lucide-react v0.468.0 - ISC
68
+ *
69
+ * This source code is licensed under the ISC license.
70
+ * See the LICENSE file in the root directory of this source tree.
71
+ */const Ws=M("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/**
72
+ * @license lucide-react v0.468.0 - ISC
73
+ *
74
+ * This source code is licensed under the ISC license.
75
+ * See the LICENSE file in the root directory of this source tree.
76
+ */const Qs=M("LogIn",[["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}],["polyline",{points:"10 17 15 12 10 7",key:"1ail0h"}],["line",{x1:"15",x2:"3",y1:"12",y2:"12",key:"v6grx8"}]]);/**
77
+ * @license lucide-react v0.468.0 - ISC
78
+ *
79
+ * This source code is licensed under the ISC license.
80
+ * See the LICENSE file in the root directory of this source tree.
81
+ */const Js=M("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/**
82
+ * @license lucide-react v0.468.0 - ISC
83
+ *
84
+ * This source code is licensed under the ISC license.
85
+ * See the LICENSE file in the root directory of this source tree.
86
+ */const ws=M("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/**
87
+ * @license lucide-react v0.468.0 - ISC
88
+ *
89
+ * This source code is licensed under the ISC license.
90
+ * See the LICENSE file in the root directory of this source tree.
91
+ */const Zs=M("MicOff",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M18.89 13.23A7.12 7.12 0 0 0 19 12v-2",key:"80xlxr"}],["path",{d:"M5 10v2a7 7 0 0 0 12 5",key:"p2k8kg"}],["path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33",key:"1gzdoj"}],["path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12",key:"r2i35w"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
92
+ * @license lucide-react v0.468.0 - ISC
93
+ *
94
+ * This source code is licensed under the ISC license.
95
+ * See the LICENSE file in the root directory of this source tree.
96
+ */const Xs=M("Mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
97
+ * @license lucide-react v0.468.0 - ISC
98
+ *
99
+ * This source code is licensed under the ISC license.
100
+ * See the LICENSE file in the root directory of this source tree.
101
+ */const et=M("PhoneOff",[["path",{d:"M10.68 13.31a16 16 0 0 0 3.41 2.6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7 2 2 0 0 1 1.72 2v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.42 19.42 0 0 1-3.33-2.67m-2.67-3.34a19.79 19.79 0 0 1-3.07-8.63A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91",key:"z86iuo"}],["line",{x1:"22",x2:"2",y1:"2",y2:"22",key:"11kh81"}]]);/**
102
+ * @license lucide-react v0.468.0 - ISC
103
+ *
104
+ * This source code is licensed under the ISC license.
105
+ * See the LICENSE file in the root directory of this source tree.
106
+ */const Xe=M("Phone",[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/**
107
+ * @license lucide-react v0.468.0 - ISC
108
+ *
109
+ * This source code is licensed under the ISC license.
110
+ * See the LICENSE file in the root directory of this source tree.
111
+ */const st=M("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/**
112
+ * @license lucide-react v0.468.0 - ISC
113
+ *
114
+ * This source code is licensed under the ISC license.
115
+ * See the LICENSE file in the root directory of this source tree.
116
+ */const tt=M("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/**
117
+ * @license lucide-react v0.468.0 - ISC
118
+ *
119
+ * This source code is licensed under the ISC license.
120
+ * See the LICENSE file in the root directory of this source tree.
121
+ */const ks=M("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
122
+ * @license lucide-react v0.468.0 - ISC
123
+ *
124
+ * This source code is licensed under the ISC license.
125
+ * See the LICENSE file in the root directory of this source tree.
126
+ */const at=M("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/**
127
+ * @license lucide-react v0.468.0 - ISC
128
+ *
129
+ * This source code is licensed under the ISC license.
130
+ * See the LICENSE file in the root directory of this source tree.
131
+ */const es=M("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),is="draken_token",os="draken_username";function Ns(){return{token:localStorage.getItem(is),username:localStorage.getItem(os)}}function nt(s,t){localStorage.setItem(is,s),localStorage.setItem(os,t)}function ss(){localStorage.removeItem(is),localStorage.removeItem(os)}function cs(){const{token:s}=Ns();return s?{Authorization:`Bearer ${s}`}:{}}const Ss=d.createContext(null),Me={isAuthenticated:!1,isLoading:!1,authEnabled:!0,username:null};function rt({children:s}){const[t,n]=d.useState({...Me,isLoading:!0});d.useEffect(()=>{let c=!0;const g=m=>{c&&n(m)};return(async()=>{try{if(!(await(await fetch("/api/auth/status")).json()).enabled){g({isAuthenticated:!0,isLoading:!1,authEnabled:!1,username:null});return}const{token:o,username:r}=Ns();if(!o){g(Me);return}(await fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${o}`}})).ok?g({isAuthenticated:!0,isLoading:!1,authEnabled:!0,username:r}):(c&&ss(),g(Me))}catch(m){console.error("Auth check failed:",m),g(Me)}})(),()=>{c=!1}},[]);const a=async(c,g)=>{const p=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:c,password:g})}),m=await p.json();if(!p.ok)throw new Error(m.error||"Login failed");nt(m.token,m.username),n({isAuthenticated:!0,isLoading:!1,authEnabled:!0,username:m.username})},i=()=>{ss(),n(Me)};return e.jsx(Ss.Provider,{value:{...t,login:a,logout:i},children:s})}function Cs(){const s=d.useContext(Ss);if(!s)throw new Error("useAuth must be used within an AuthProvider");return s}function it(){const{login:s}=Cs(),[t,n]=d.useState(""),[a,i]=d.useState(""),[c,g]=d.useState(null),[p,m]=d.useState(!1),w=async o=>{o.preventDefault(),g(null),m(!0);try{await s(t,a)}catch(r){g(r instanceof Error?r.message:"Login failed")}finally{m(!1)}};return e.jsx("div",{className:"login-page",children:e.jsxs("div",{className:"login-card",children:[e.jsxs("div",{className:"login-header",children:[e.jsx("img",{src:"/favicon.png",alt:"Draken",className:"login-logo"}),e.jsx("h1",{children:"Draken"}),e.jsx("p",{className:"login-subtitle",children:"Your engineering sync across pi sessions"})]}),e.jsxs("form",{onSubmit:w,className:"login-form",children:[c&&e.jsxs("div",{className:"login-error",role:"alert",children:[e.jsx(Vs,{size:16}),c]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"username",children:"Username"}),e.jsxs("div",{className:"input-with-icon",children:[e.jsx(at,{size:18,className:"input-icon"}),e.jsx("input",{id:"username",type:"text",className:"input",placeholder:"Enter username",value:t,onChange:o=>n(o.target.value),autoComplete:"username",autoFocus:!0})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"input-with-icon",children:[e.jsx(Ws,{size:18,className:"input-icon"}),e.jsx("input",{id:"password",type:"password",className:"input",placeholder:"Enter password",value:a,onChange:o=>i(o.target.value),autoComplete:"current-password"})]})]}),e.jsx("button",{type:"submit",className:"btn btn-primary btn-lg login-btn",disabled:p||!t||!a,children:p?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"spinner spinner-sm"})," Signing in..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Qs,{size:18})," Sign In"]})})]})]})})}async function T(s,t="GET",n,a){const i=await fetch(`/api${s}`,{method:t,signal:a,headers:{"Content-Type":"application/json",...cs()},body:n===void 0?void 0:JSON.stringify(n)});if(i.status===401)throw ss(),window.location.reload(),new Error("Authentication required");if(i.status===204)return;const c=await i.json();if(!i.ok)throw new Error(c.error||`Request failed (${i.status})`);return c}const ot=(s=!1)=>T(`/setup${s?"?refresh=1":""}`),ct=(s,t,n)=>T(`/settings/preparation-usage?range=${s}&bucket=${t}`,"GET",void 0,n),Es=()=>T("/settings/auto-index"),us=s=>T("/settings/auto-index","PATCH",{enabled:s}),lt=()=>T("/settings/auto-summary"),dt=s=>T("/settings/auto-summary","PATCH",{enabled:s}),ts=s=>T(`/home${s?`?before=${s}`:""}`),ht=s=>T("/syncs/start-call","POST",{request_id:s}),ut=s=>T("/syncs/start-chat","POST",{request_id:s}),pt=(s,t,n)=>T(`/syncs/${s}/chat/messages`,"POST",{message:t,request_id:n}),ps=s=>T(`/syncs/${s}/recap`,"POST"),ms=()=>T("/overview"),mt=()=>T("/scan","POST"),gt=(s,t)=>T(`/agents/${encodeURIComponent(s)}`,"PATCH",{enabled:t}),ft=(s,t)=>T(`/sessions/${encodeURIComponent(s)}`,"PATCH",{included:t}),Qe=s=>T(`/syncs/${s}`),xt=(s,t)=>T(`/syncs/${s}/conversation`,"GET",void 0,t),yt=s=>T(`/syncs/${s}/progress`),gs=(s,t)=>T(`/syncs/${s}/call-readiness`,"GET",void 0,t),vt=(s,t)=>T(`/syncs/${s}/chat-readiness`,"GET",void 0,t),jt=s=>T(`/syncs/${s}/prepare-call`,"POST"),bt=(s,t)=>T(`/syncs/${s}/tree/${t}`),wt=s=>T(`/syncs/${s}/expand`,"POST"),kt=s=>T(`/syncs/${s}/cancel`,"POST"),Nt=s=>T(`/syncs/${s}/briefing`,"POST"),St=(s,t)=>T(`/syncs/${s}/messages`,"POST",{message:t}),Ct=s=>T("/memory/progress","GET",void 0,s),Et=(s,t)=>T("/memory/search","POST",s,t),At=(s,t=0,n)=>T(`/memory/records/${encodeURIComponent(s)}?offset=${t}`,"GET",void 0,n),qe=(s,t,n)=>T(`/syncs/${s}/notes`,"PATCH",{decisions:t,carry_forward:n}),_t=(s,t,n)=>T(`/syncs/${s}/complete`,"POST",{decisions:t,carry_forward:n,reviewed:!0}),Pt=s=>T(`/syncs/${s}/discard`,"POST"),De=25;function fs({items:s,title:t}){const[n,a]=d.useState(0),[i,c]=d.useState(""),[g,p]=d.useState("");if(d.useEffect(()=>{const u=k=>{const v=k.detail,f=s.findIndex(E=>E.ref===v);f<0||(c(""),a(Math.floor(f/De)),p(v))};return window.addEventListener("draken:evidence",u),()=>window.removeEventListener("draken:evidence",u)},[s]),d.useEffect(()=>{if(!g)return;const u=document.getElementById(`evidence-${g}`);u&&(u.open=!0,u.scrollIntoView({behavior:"smooth",block:"center"}),p(""))},[g,n,i]),!s.length)return null;const m=i.toLocaleLowerCase(),w=m?s.filter(u=>`${u.ref} ${u.session_name} ${u.cwd} ${u.text}`.toLocaleLowerCase().includes(m)):s,o=Math.max(1,Math.ceil(w.length/De)),r=Math.min(n,o-1);return e.jsxs("section",{className:"evidence-section",children:[e.jsxs("h3",{children:[t," ",e.jsx("span",{className:"count",children:s.length})]}),s.length>De&&e.jsxs("div",{className:"evidence-controls",children:[e.jsx("input",{className:"input","aria-label":`Search ${t}`,placeholder:"Find a topic, workspace, or evidence ID…",value:i,onChange:u=>{c(u.target.value),a(0)}}),e.jsxs("div",{className:"pagination",children:[e.jsx("button",{className:"btn btn-secondary",disabled:r===0,onClick:()=>a(r-1),children:"Previous"}),e.jsxs("span",{children:[r+1," / ",o," · ",w.length," entries"]}),e.jsx("button",{className:"btn btn-secondary",disabled:r>=o-1,onClick:()=>a(r+1),children:"Next"})]})]}),e.jsx("div",{className:"evidence-list",children:w.slice(r*De,(r+1)*De).map(u=>e.jsxs("details",{className:"evidence",id:`evidence-${u.ref}`,children:[e.jsxs("summary",{children:[e.jsx("span",{className:"reference",children:u.ref}),e.jsxs("span",{className:"evidence-title",children:[e.jsxs("strong",{children:[u.agent&&u.agent!=="pi"&&`${u.agent} · `,u.session_name||u.cwd.split("/").filter(Boolean).pop()||u.cwd]}),e.jsx("span",{children:u.unavailable?"Original session source unavailable":u.text.slice(0,130)})]}),e.jsx("span",{className:"role-label",children:u.role})]}),e.jsxs("div",{className:"evidence-body",children:[e.jsxs("dl",{children:[e.jsx("dt",{children:"Workspace"}),e.jsx("dd",{children:u.cwd}),e.jsx("dt",{children:"Session"}),e.jsx("dd",{children:u.session_id}),e.jsx("dt",{children:"Source"}),e.jsx("dd",{children:u.source_path}),e.jsx("dt",{children:"Entry"}),e.jsxs("dd",{children:[u.entry_id," · ",u.timestamp]})]}),u.unavailable?e.jsx("p",{className:"alert warning",role:"status",children:u.unavailable}):e.jsx("pre",{children:u.text})]})]},u.ref))})]})}function Le({text:s,evidence:t}){const n=new Set(t.map(a=>a.ref));return e.jsx("div",{className:"prose",children:s.split(/(\[(?:[EC]\d+|H[a-f0-9]{24})\])/g).map((a,i)=>{const c=a.slice(1,-1);return/^H[a-f0-9]{24}$/.test(c)?e.jsxs("a",{className:"citation",href:`/history/${c}`,target:"_blank",rel:"noopener noreferrer","aria-label":`Inspect historical source ${c}`,children:["[history ",c.slice(-6),"]"]},i):!/^\[(E|C)\d+\]$/.test(a)||!n.has(c)?e.jsx("span",{children:a},i):e.jsx("button",{className:"citation",onClick:()=>window.dispatchEvent(new CustomEvent("draken:evidence",{detail:c})),"aria-label":`Inspect evidence ${c}`,children:a},i)})})}function Tt({syncId:s,progress:t,evidence:n,onCancel:a,onResume:i,resumeEnabled:c}){var b;const[g,p]=d.useState(new Set),[m,w]=d.useState(null),[o,r]=d.useState(""),[u,k]=d.useState(!1),v=t.run;if(d.useEffect(()=>{w(null),p(new Set)},[v==null?void 0:v.id]),!v)return null;const f=!t.busy&&["failed","cancelled","interrupted"].includes(v.status),E=new Map(t.nodes.map(x=>[x.key,x])),j=new Set(t.nodes.flatMap(x=>x.children)),_=t.nodes.filter(x=>!j.has(x.key)),h=async x=>{k(!0),r("");try{w(await bt(s,x.key))}catch(C){r(C instanceof Error?C.message:"Could not load summary")}finally{k(!1)}},N=(x,C=new Set)=>{if(C.has(x.key))return null;const O=new Set([...C,x.key]),z=g.has(x.key);return e.jsxs("li",{children:[e.jsxs("div",{className:"tree-node",children:[e.jsx("button",{className:"tree-toggle","aria-label":`Expand ${x.label}`,disabled:!x.children.length,onClick:()=>p(P=>{const R=new Set(P);return R.has(x.key)?R.delete(x.key):R.add(x.key),R}),children:x.children.length?z?"▾":"▸":"·"}),e.jsxs("button",{className:"tree-label",disabled:!["done","cached"].includes(x.status)||u,onClick:()=>void h(x),title:x.error||x.label,children:[e.jsx("span",{className:"role-label",children:x.kind})," ",x.label]}),e.jsx("span",{className:`status ${x.status}`,children:x.status})]}),z&&e.jsx("ul",{children:x.children.map(P=>E.has(P)?N(E.get(P),O):null)})]},x.key)};return e.jsxs("section",{className:"card tree-card",children:[e.jsxs("div",{className:"section-heading",children:[e.jsx("h2",{children:"Summary tree"}),e.jsx("span",{className:`status ${v.status}`,children:v.status})]}),e.jsx("p",{className:"small muted",children:"Complete source batches → compact reconciliation → final verdict"}),e.jsx("progress",{max:Math.max(1,v.total_entries),value:v.processed_entries,"aria-label":"Evidence compression progress"}),e.jsxs("div",{className:"tree-stats",children:[e.jsxs("span",{children:[v.processed_entries," / ",v.total_entries," entries processed"]}),e.jsxs("span",{children:[v.invocations," / ",v.max_invocations," pi invocations"]}),e.jsxs("span",{children:[v.cache_hits," cached nodes reused"]})]}),!!((b=v.metrics)!=null&&b.length)&&e.jsxs("details",{className:"small",children:[e.jsx("summary",{children:"Model request timing"}),e.jsxs("p",{children:[(v.metrics.reduce((x,C)=>x+C.elapsed_ms,0)/1e3).toFixed(1)," seconds across ",v.metrics.length," requests · ",v.metrics.reduce((x,C)=>x+C.input_tokens_estimate,0).toLocaleString()," estimated input tokens."]}),e.jsx("p",{className:"muted",children:"Includes pi startup and provider waiting/generation, not separately measured. Token counts are local planning estimates with input headroom, not billed usage. A completed request can still fail summary validation."}),e.jsx("ul",{children:v.metrics.map((x,C)=>e.jsxs("li",{children:[x.stage||x.task,x.repair?" (repair)":""," · ",(x.elapsed_ms/1e3).toFixed(1)," s · ",x.status]},C))})]}),e.jsxs("p",{className:"small",children:[f?"Stopped at: ":"",v.stage]}),v.question&&e.jsxs("p",{className:"small muted",children:["Question: ",v.question]}),v.error&&e.jsxs("div",{className:"alert error",role:"alert",children:[e.jsx("strong",{children:"Last run’s error:"})," ",v.error]}),f&&e.jsxs("div",{className:"alert warning",children:[e.jsx("strong",{children:"Generation stopped. No model calls are running."}),e.jsxs("p",{className:"small",children:[v.processed_entries<v.total_entries?`${v.total_entries-v.processed_entries} entries still need compression.`:"Raw chunks were processed, but reconciliation or the final reply did not finish."," Successful chunks are cached; nothing was marked reviewed."]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"small",children:"Resume to continue from cached chunks instead of generating them again."}),e.jsx("button",{className:"btn btn-primary",disabled:!c,onClick:i,children:"Resume generation"})]})]}),t.busy&&e.jsx("button",{className:"btn btn-secondary",onClick:a,children:"Cancel generation"}),e.jsxs("details",{className:"tree-browser",children:[e.jsxs("summary",{children:["Inspect ",t.nodes.length," summary nodes"]}),e.jsx("ul",{children:_.map(x=>N(x))})]}),o&&e.jsx("p",{role:"alert",className:"error",children:o}),m&&e.jsxs("div",{className:"node-inspector",children:[e.jsxs("div",{className:"section-heading",children:[e.jsx("h3",{children:m.label}),e.jsx("button",{className:"btn btn-ghost",onClick:()=>w(null),children:"Close"})]}),"observations"in m.output?e.jsxs(e.Fragment,{children:[m.output.observations.map((x,C)=>e.jsxs("div",{className:"node-observation",children:[e.jsx("strong",{children:x.topic})," ",e.jsx("span",{className:"status",children:x.state}),e.jsx(Le,{text:`${x.summary} ${x.evidence.map(O=>m.refs[O]?`[${m.refs[O]}]`:"[source unavailable]").join(" ")}`,evidence:n})]},C)),m.output.limitations.map((x,C)=>e.jsx("p",{className:"muted small",children:x},C))]}):m.output.groups.map((x,C)=>e.jsxs("p",{className:"small",children:[x.topic," · ",x.members.length," related observations"]},C))]})]})}function as({state:s,unavailable:t=!1}){if(!s&&!t)return null;const n=s!=null&&s.ended_at?"Session ended":t?"Update status unavailable":s?{up_to_date:"Up to date",preparing:"Preparing new info…",new_info:"New info ready",paused:"Live updates paused",error:"Updates unavailable"}[s.update_state]:"Update status unavailable",a=s!=null&&s.ended_at?"This session has ended. Its transcript is retained and nothing was marked reviewed automatically.":(s==null?void 0:s.error)||"Keep chatting with the last prepared context. Newly prepared information is adopted between turns; previous messages and the initial briefing stay unchanged.";return e.jsxs("span",{className:"small muted conversation-info",role:"status","aria-label":"Conversation updates",title:a,children:[e.jsx("span",{"aria-hidden":"true",children:(s==null?void 0:s.update_state)==="preparing"?"◌":"●"})," ",n]})}const Re=4e3,It=s=>s?new Date(s).toLocaleString():"Edit date not retained";function ns({record:s}){return e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"small muted",children:[It(s.at)," · ",s.role," · ",s.kind,s.sync_id?` · Sync #${s.sync_id}`:""]}),e.jsx("p",{className:"small muted",children:s.qualification})]})}function As({reference:s}){return e.jsx(Mt,{reference:s},s)}function Mt({reference:s}){const[t,n]=d.useState(null),[a,i]=d.useState(0),[c,g]=d.useState("");return d.useEffect(()=>{const p=new AbortController;return g(""),n(null),At(s,a,p.signal).then(m=>{p.signal.aborted||n(m)}).catch(m=>{p.signal.aborted||g(m.message)}),()=>p.abort()},[s,a]),e.jsxs("section",{className:"history-source","aria-label":"Historical source",children:[c&&e.jsx("p",{role:"alert",children:c}),!t&&!c&&e.jsx("p",{role:"status",children:"Reading historical source…"}),t&&e.jsxs(e.Fragment,{children:[e.jsx("h2",{children:t.record.title}),e.jsx(ns,{record:t.record}),t.record.workspace&&e.jsx("p",{className:"source-path",children:t.record.workspace}),e.jsx("pre",{className:"history-excerpt",children:t.record.text}),e.jsxs("p",{className:"small muted",children:["Characters ",Math.min(a+1,t.total),"–",Math.min(a+Re,t.total)," of ",t.total," in the retained record. Source logs may contain more."]}),t.total>Re&&e.jsxs("div",{className:"pagination",children:[e.jsx("button",{className:"btn btn-secondary",disabled:!a,onClick:()=>i(Math.max(0,a-Re)),children:"Earlier text"}),e.jsx("button",{className:"btn btn-secondary",disabled:a+Re>=t.total,onClick:()=>i(a+Re),children:"Later text"})]}),t.record.sync_id&&e.jsxs("p",{children:[e.jsxs("a",{href:`/syncs/${t.record.sync_id}`,target:"_blank",rel:"noopener noreferrer",children:["Open original sync #",t.record.sync_id]}),t.record.origin_ref&&` · original reference ${t.record.origin_ref}`]}),t.neighbors.length>0&&e.jsxs("details",{children:[e.jsx("summary",{children:"Surrounding retained records"}),e.jsx("p",{className:"small muted",children:"Nearby records in this session or discussion—not necessarily the full conversation."}),t.neighbors.map(p=>e.jsxs("article",{children:[e.jsx("h3",{children:e.jsx("a",{href:`/history/${p.ref}`,target:"_blank",rel:"noopener noreferrer",children:p.title})}),e.jsx(ns,{record:p}),e.jsx("pre",{className:"history-excerpt",children:p.text})]},p.ref))]})]})]})}const qt={scanning:"Checking history for changes…",downloading:"Downloading the local search model…",loading:"Preparing the local search model…",indexing:"Indexing new and changed history…",searching:"Finding matching history…",reading:"Reading a historical source…"},Je=s=>s<60?`${Math.ceil(s)} sec`:`${Math.ceil(s/60)} min`,Ge=s=>s.toLocaleString();function We({enabled:s,waiting:t=!1,backgroundOnly:n=!1,onLookupChange:a}){const[i,c]=d.useState(null),[g,p]=d.useState(!1);if(d.useEffect(()=>{if(a==null||a(!1),!s)return;c(null),p(!1);const f=new AbortController;let E;const j=async()=>{try{const _=await Ct(f.signal);f.signal.aborted||(c(_),p(!1),a==null||a(!!(_.active&&!_.background&&_.work&&["scanning","searching","reading"].includes(_.work.stage)&&_.updated_at&&Math.abs(Date.now()-_.updated_at)<5e3)))}catch{f.signal.aborted||(p(!0),a==null||a(!1))}f.signal.aborted||(E=setTimeout(()=>void j(),1e3))};return j(),()=>{f.abort(),clearTimeout(E),a==null||a(!1)}},[s,a]),!s)return null;if(!(i!=null&&i.active)||!i.work||n&&!i.background)return t?e.jsx("p",{className:"small muted",role:"status",children:g?"Progress is unavailable; your search is still pending.":"Waiting for local history work…"}):null;const m=i.work,w=m.stage==="indexing",o=m.stage==="downloading",r=o?m.downloaded_bytes:m.completed,u=o?m.download_total_bytes:m.total,k=u?Math.floor(r/u*100):0,v=i.updated_at?Math.floor((Date.now()-i.updated_at)/1e3):0;return e.jsxs("section",{className:"history-progress","aria-label":"Local history progress",children:[e.jsx("p",{role:"status",children:e.jsx("strong",{children:w&&!u?"History is up to date.":qt[m.stage]})}),(w&&u>0||o)&&e.jsxs(e.Fragment,{children:[e.jsx("progress",{"aria-label":o?"Model download":"History indexing",max:u||1,value:u?r:void 0}),e.jsxs("p",{children:[o?`${(r/1e6).toFixed(1)} / ${(u/1e6).toFixed(1)} MB`:`${Ge(r)} / ${Ge(u)} new or changed passages ready`," · ",k,"%"]})]}),e.jsxs("p",{className:"small muted",children:[w&&`${Ge(m.reused)} unchanged passages reused (not part of this progress). `,"Elapsed ",Je(i.elapsed_ms/1e3),".",w&&m.remaining_seconds!==null&&m.remaining_seconds>0&&` About ${Je(m.remaining_seconds)} remaining (estimate).`,w&&u>0&&m.parallelism&&` Up to ${m.parallelism.workers} embedding worker${m.parallelism.workers===1?"":"s"}, ${m.parallelism.threads} CPU threads total.`,i.queued>0&&` ${Ge(i.queued)} other history request${i.queued===1?"":"s"} waiting.`]}),(g||v>=15)&&e.jsxs("p",{className:"small muted",children:[g?"Progress updates are temporarily unavailable.":`No new progress for ${Je(v)}.`," Cancelling keeps completed embeddings for the next request."]})]})}const xs=["[Thinking...]","[Hmmm...]","[Hmmmmmm...]"],ys=["[Checking...]","[Looking that up...]"];function Ze(s){const t=Array.from(s.trim().replace(/\s+/g," "));if(t.length<=140)return t.join("");const n=t.slice(-140).join(""),a=n.indexOf(" ");return"…"+(a>=0&&a<25?n.slice(a+1):n)}function Dt({call:s,historyLookup:t}){const[n,a]=d.useState(0),i=!!s.replyPendingSince&&!["connecting","hearing","speaking","paused","ended"].includes(s.phase)&&!s.error;d.useEffect(()=>{if(a(0),!i)return;const p=setInterval(()=>a(m=>(m+1)%6),5e3);return()=>clearInterval(p)},[i,s.replyPendingSince,t]);let c,g="";return s.phase==="ended"?c="[Call ended]":s.error?c="[Reply unavailable]":s.phase==="paused"?c="[Sound paused]":s.phase==="connecting"?c=s.notice.includes("microphone permission")?"[Waiting for microphone...]":"[Connecting...]":s.phase==="hearing"?(c=s.question?Ze(s.question):"[Listening...]",g=s.question?"You":""):i?c=t?ys[n%ys.length]:xs[n%xs.length]:s.notice.startsWith("Reply muted locally;")?c="[Reply stopped]":s.answer?(c=Ze(s.answer),g="Draken"):s.question?(c=Ze(s.question),g="You"):c=s.phase==="speaking"?"[Speaking...]":s.muted?"[Microphone off]":"[Listening...]",e.jsxs("div",{className:"voice-captions",role:"region","aria-label":"Live captions","aria-live":"off","data-kind":g?"transcript":"status",children:[g&&e.jsx("span",{className:"voice-caption-speaker",children:g}),e.jsx("div",{className:"voice-caption-window",children:e.jsx("p",{children:c})})]})}var Y,U,te,pe,ye,Ee,oe,ce,ae,me,Oe,F,$e,Ue,ve,Ae,Fe,ze;class Rt{constructor({onClose:t=()=>{},onEvent:n=()=>{}}={}){L(this,Y);L(this,U);L(this,te);L(this,pe);L(this,ye,new Set);L(this,Ee,[]);L(this,oe);L(this,ce);L(this,ae);L(this,me,new Float32Array(1024));L(this,Oe,new AbortController);L(this,F,!1);L(this,$e,!1);L(this,Ue,!1);L(this,ve);L(this,Ae);L(this,Fe);L(this,ze);D(this,Fe,t),D(this,ze,n)}get closed(){return y(this,F)}get clock(){var t;return!y(this,F)&&((t=y(this,U))==null?void 0:t.state)==="running"?y(this,U).currentTime:NaN}get audioState(){var t;return((t=y(this,U))==null?void 0:t.state)||"closed"}async resume(){var t,n;y(this,F)||(await((t=y(this,U))==null?void 0:t.resume()),await((n=y(this,ae))==null?void 0:n.play()))}gateInput(t){var n;(n=y(this,te))==null||n.getAudioTracks().forEach(a=>{a.enabled=!!t})}get inputActive(){var t;return!!((t=y(this,te))!=null&&t.getAudioTracks().some(n=>n.readyState==="live"))}get level(){var n;if(y(this,F)||y(this,Ue)||((n=y(this,U))==null?void 0:n.state)!=="running"||!y(this,oe))return 0;y(this,oe).getFloatTimeDomainData(y(this,me));const t=Math.sqrt(y(this,me).reduce((a,i)=>a+i*i,0)/y(this,me).length);return Number.isFinite(t)?Math.min(1,t*12):0}async open(t,n){if(y(this,$e)||y(this,F))throw t.getTracks().forEach(a=>a.stop()),new Error("A voice peer can open only once.");D(this,$e,!0),D(this,te,t);try{if(t.getAudioTracks().length!==1||t.getVideoTracks().length)throw new Error("Exactly one audio track is required.");if(D(this,Y,new RTCPeerConnection),D(this,U,new AudioContext),D(this,oe,y(this,U).createAnalyser()),y(this,oe).fftSize=y(this,me).length,D(this,ce,y(this,U).createGain()),y(this,oe).connect(y(this,ce)),y(this,ce).connect(y(this,U).destination),D(this,Ae,setTimeout(()=>this.close("Voice connection timed out."),6e4)),await y(this,U).resume(),y(this,F)||y(this,U).state!=="running")throw new Error("Voice playback could not start.");D(this,pe,y(this,Y).addTrack(t.getAudioTracks()[0],t));const a=y(this,Y).createDataChannel("oai-events"),i=new Promise((g,p)=>{D(this,ve,p);const m=()=>{y(this,Y).connectionState==="connected"&&a.readyState==="open"?(D(this,ve,void 0),clearTimeout(y(this,Ae)),g()):["failed","disconnected","closed"].includes(y(this,Y).connectionState)&&this.close("Voice connection lost. Start a new call explicitly.")};y(this,Y).onconnectionstatechange=m,a.onopen=m,a.onclose=()=>this.close("Voice event connection closed."),a.onerror=()=>this.close("Voice event connection failed.")});if(i.catch(()=>{}),a.onmessage=g=>{if(!y(this,F)){if(typeof g.data!="string"||g.data.length>2e5){this.close("Voice event exceeds its limit.");return}try{y(this,ze).call(this,JSON.parse(g.data))}catch{this.close("Invalid voice event.")}}},y(this,Y).ontrack=g=>{if(y(this,F)){g.track.stop();return}if(g.track.kind!=="audio"||y(this,ye).size){this.close("Unexpected remote media track.");return}y(this,ye).add(g.track);const p=new MediaStream([g.track]);D(this,ae,new Audio),y(this,ae).muted=!0,y(this,ae).srcObject=p,y(this,ae).play().catch(()=>this.close("Voice playback could not start."));const m=y(this,U).createMediaStreamSource(p);y(this,Ee).push(m),m.connect(y(this,oe)),g.track.onended=()=>this.close("Voice output ended.")},await y(this,Y).setLocalDescription(await y(this,Y).createOffer()),y(this,F))throw new Error("Voice connection cancelled.");const c=await n(y(this,Y).localDescription.sdp,y(this,Oe).signal);if(y(this,F))throw new Error("Voice connection cancelled.");if(typeof c!="string"||c.length>64e3||!c.startsWith("v=0"))throw new Error("Invalid voice answer.");await y(this,Y).setRemoteDescription({type:"answer",sdp:c}),await i}catch(a){throw this.close("Voice connection failed or cancelled."),a}}muteOutput(t){D(this,Ue,!!t),y(this,ce)&&(y(this,ce).gain.value=t?0:1)}stopInput(){var t;(t=y(this,te))==null||t.getTracks().forEach(n=>n.stop()),D(this,te,void 0),y(this,pe)&&!y(this,F)&&y(this,pe).replaceTrack(null).catch(()=>this.close("Cannot mute voice input."))}async replaceInput(t){if(y(this,F)||!y(this,pe)||t.getAudioTracks().length!==1||t.getVideoTracks().length)throw t.getTracks().forEach(a=>a.stop()),new Error("Cannot attach voice input.");const n=y(this,te);D(this,te,t),n==null||n.getTracks().forEach(a=>a.stop());try{await y(this,pe).replaceTrack(t.getAudioTracks()[0])}catch(a){throw t.getTracks().forEach(i=>i.stop()),this.close("Cannot attach voice input."),a}if(y(this,F)||y(this,te)!==t)throw t.getTracks().forEach(a=>a.stop()),new Error("Voice input was superseded.")}close(t="Call ended."){var n,a,i,c,g;if(!y(this,F)){D(this,F,!0),clearTimeout(y(this,Ae)),y(this,Oe).abort(),(n=y(this,ve))==null||n.call(this,new Error(t)),D(this,ve,void 0),(a=y(this,Y))==null||a.close(),(i=y(this,te))==null||i.getTracks().forEach(p=>p.stop()),y(this,ye).forEach(p=>p.stop()),y(this,ye).clear(),y(this,Ee).forEach(p=>p.disconnect()),D(this,Ee,[]),(c=y(this,oe))==null||c.disconnect(),(g=y(this,ce))==null||g.disconnect(),y(this,me).fill(0),y(this,ae)&&(y(this,ae).pause(),y(this,ae).srcObject=null,D(this,ae,void 0)),y(this,U)&&y(this,U).state!=="closed"&&y(this,U).close().catch(()=>{});try{y(this,Fe).call(this,t)}catch{}}}}Y=new WeakMap,U=new WeakMap,te=new WeakMap,pe=new WeakMap,ye=new WeakMap,Ee=new WeakMap,oe=new WeakMap,ce=new WeakMap,ae=new WeakMap,me=new WeakMap,Oe=new WeakMap,F=new WeakMap,$e=new WeakMap,Ue=new WeakMap,ve=new WeakMap,Ae=new WeakMap,Fe=new WeakMap,ze=new WeakMap;const rs={phase:"connecting",muted:!1,microphone:!1,voiceInterruption:!1,question:"",answer:"",evidence:[],error:"",notice:"",startedAt:0,turnId:0,replyPendingSince:0,historyReady:!1};async function ne(s,t={}){const n=await fetch(`/api/voice${s}`,{...t,headers:{"Content-Type":"application/json",...cs()}});if(!n.ok){const a=await n.json().catch(()=>({}));throw new Error(a.error||(n.status===401?"Sign in again to use the call.":"The live connection failed."))}return n.status===204?void 0:n.json()}class Lt{constructor(t){I(this,"state",{...rs,phase:"connecting"});I(this,"alive",!0);I(this,"id","");I(this,"pageExit",()=>{this.end()});I(this,"peer");I(this,"life",new AbortController);I(this,"inputContext",new AudioContext);I(this,"inputMeter",this.inputContext.createAnalyser());I(this,"inputSource");I(this,"input");I(this,"changing",!1);I(this,"cursor",0);I(this,"timer",0);I(this,"speechAt",0);I(this,"providerDone",!0);I(this,"stopped",!1);I(this,"newQuestion",!1);I(this,"pendingAnswer",!1);I(this,"answerSettled",!1);I(this,"awaitingUser",!1);I(this,"userId",0);I(this,"inputEpoch",0);I(this,"pendingNotice","Preparing the answer. I’ll continue automatically.");I(this,"assistantId",null);I(this,"observed",0);I(this,"reportedAt",0);I(this,"micBuffer",new Float32Array(1024));this.options=t,window.addEventListener("pagehide",this.pageExit),this.inputMeter.fftSize=1024,this.inputContext.resume().catch(()=>{}),this.peer=new Rt({onEvent:n=>this.providerEvent(n),onClose:n=>{this.alive&&(this.set({error:n}),this.end())}}),this.set({})}set(t){this.state={...this.state,...t},this.options.onState(this.state)}async request(t,n){return ne(`/live/calls/${this.id}${t}`,{method:n?"POST":"GET",...n?{body:JSON.stringify(n)}:{},signal:this.life.signal})}async microphone(){var n;const t=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1});if(!this.alive)throw t.getTracks().forEach(a=>a.stop()),new Error("Call ended");(n=this.inputSource)==null||n.disconnect(),this.inputSource=this.inputContext.createMediaStreamSource(t),this.inputSource.connect(this.inputMeter),this.input=t,this.set({microphone:!0});for(const a of t.getAudioTracks())a.addEventListener("ended",()=>{this.alive&&!this.state.muted&&this.input===t&&(this.set({muted:!0,microphone:!1,notice:"Microphone disconnected. Type, or turn the microphone on again."}),this.peer.stopInput())});return t}silentInput(){const t=this.inputContext.createMediaStreamDestination(),n=this.inputContext.createConstantSource();return n.offset.value=0,n.connect(t),n.start(),t.stream}async start(t){var n,a;try{if(!this.alive)return;this.set({notice:"Connecting your call. Your microphone is still off."}),this.id=crypto.randomUUID();const i=await ne("/live/calls",{method:"POST",body:JSON.stringify({syncId:t,requestId:this.id}),signal:this.life.signal});if(i.id!==this.id)throw new Error("The call reservation identity did not match.");if(!this.alive){ne(`/live/calls/${this.id}/end`,{method:"POST",keepalive:!0}).catch(()=>{});return}if(document.visibilityState!=="visible")throw new Error("History is ready. Return to this page and start the call again to enable the microphone.");this.set({historyReady:!0,startedAt:i.startedAt,notice:"History is ready. Waiting for microphone permission…"}),this.poll();let c;try{c=await this.microphone(),this.set({notice:""})}catch{if(!this.alive)return;c=this.silentInput(),this.set({muted:!0,notice:"Microphone unavailable. You can type instead."})}if(this.input=c,await this.peer.open(c,async(g,p)=>(await ne(`/live/calls/${i.id}/connect`,{method:"POST",body:JSON.stringify({sdp:g}),signal:p})).sdp),!this.alive)return;try{(a=(n=this.options).onPlayback)==null||a.call(n,{text:"",samples:new Float32Array(0),sampleRate:0,duration:1/0,startedAt:0,now:()=>this.peer.clock,level:()=>this.peer.level})}catch{}this.set({phase:this.state.replyPendingSince?"thinking":"listening"}),this.timer=window.setInterval(()=>this.meter(),80)}catch(i){this.alive&&(this.set({error:i instanceof Error?i.message:"Live voice could not start"}),await this.end())}}providerEvent(t){var n,a;this.alive&&(t.type==="input_transcript.added"&&this.stopped&&this.newQuestion&&(this.stopped=!1,this.peer.muteOutput(!1),this.set({notice:""})),t.type==="turn.created"&&((n=t.turn)==null?void 0:n.role)==="assistant"&&(this.stopped&&this.newQuestion&&(this.stopped=!1,this.newQuestion=!1,this.peer.muteOutput(!1)),this.providerDone=!1),t.type==="output_transcript.added"&&!this.stopped&&(this.providerDone=!1,this.state.voiceInterruption||this.peer.gateInput(!1)),t.type==="turn.done"&&((a=t.turn)==null?void 0:a.role)==="assistant"&&(this.providerDone=!0))}meter(){if(!this.alive)return;const t=performance.now(),n=this.peer.level;let a=0;this.state.muted||(this.inputMeter.getFloatTimeDomainData(this.micBuffer),a=Math.sqrt(this.micBuffer.reduce((i,c)=>i+c*c,0)/this.micBuffer.length)*10),this.stopped&&a>.08&&(this.newQuestion=!0),n>.02?(this.speechAt=t,this.observed+=80,this.state.phase!=="speaking"&&this.set({phase:"speaking"}),this.state.voiceInterruption||this.peer.gateInput(!1),this.assistantId&&t-this.reportedAt>1e3&&(this.reportedAt=t,this.request("/observed",{messageId:this.assistantId,milliseconds:this.observed}).catch(()=>{}))):(this.providerDone||this.pendingAnswer||this.answerSettled)&&t-this.speechAt>400&&this.state.phase==="speaking"&&(this.set({phase:this.state.replyPendingSince?"thinking":"listening"}),this.peer.gateInput(!this.state.muted)),this.peer.audioState==="suspended"&&this.state.phase!=="paused"&&this.set({phase:"paused"})}async poll(){var t,n;try{for(;this.alive;){const a=await this.request(`/events?after=${this.cursor}`);if(!this.alive)return;for(const i of a.events){if(this.cursor=i.sequence,i.type==="sources"&&this.set({evidence:i.evidence}),i.type==="message"){if(i.role==="user"){if(i.id<this.userId)continue;i.id>this.userId&&(this.awaitingUser||this.inputEpoch++,this.pendingAnswer=!1,this.answerSettled=!1,this.set({answer:"",error:"",replyPendingSince:this.awaitingUser?this.state.replyPendingSince:0,...!this.awaitingUser&&!this.stopped?{phase:"hearing"}:{},...this.state.notice===this.pendingNotice?{notice:""}:{}}),this.awaitingUser=!1),this.userId=i.id,this.set({question:i.text}),i.final&&!this.answerSettled&&(!this.stopped||this.newQuestion)&&(this.pendingAnswer=!0,this.set({replyPendingSince:this.state.replyPendingSince||Date.now(),...["speaking","paused"].includes(this.state.phase)?{}:{phase:"thinking"}}))}else this.assistantId!==i.id&&(this.assistantId=i.id,this.observed=0),this.set({turnId:i.id,answer:i.text,evidence:i.evidence});(n=(t=this.options).onTurn)==null||n.call(t,i.role==="user"?i.text:"",i.role==="assistant"?i.text:"",i.evidence,i.id)}i.type==="answer_pending"&&i.id===this.userId&&!this.awaitingUser&&(!this.stopped||this.newQuestion)&&(this.pendingAnswer=i.pending===!0,this.answerSettled=!this.pendingAnswer,this.set({replyPendingSince:this.pendingAnswer?this.state.replyPendingSince||Date.now():0,...["thinking","listening","hearing"].includes(this.state.phase)?{phase:this.pendingAnswer?"thinking":"listening"}:{},...!this.state.notice||this.state.notice===this.pendingNotice?{notice:this.pendingAnswer?this.pendingNotice:""}:{},...i.error?{error:i.error}:{}})),i.type==="error"&&this.set({error:i.error})}if(!a.active){await this.end();return}await new Promise(i=>setTimeout(i,250))}}catch(a){this.alive&&(this.set({error:a instanceof Error?a.message:"Live connection lost"}),await this.end())}}async sendText(t){if(!this.alive||!this.id||!t.trim()||t.length>2e3)return;const n=++this.inputEpoch;this.newQuestion=!0,this.awaitingUser=!0,this.answerSettled=!1,this.pendingAnswer=!1,this.set({phase:"thinking",error:"",question:t,answer:"",replyPendingSince:Date.now()});try{await this.request("/text",{question:t,requestId:crypto.randomUUID()}),this.alive&&n===this.inputEpoch&&this.stopped&&(this.stopped=!1,this.peer.muteOutput(!1),this.set({notice:""}))}catch(a){this.alive&&n===this.inputEpoch&&(this.awaitingUser=!1,this.pendingAnswer=!1,this.answerSettled=!0,this.set({phase:"listening",replyPendingSince:0,error:a instanceof Error?a.message:"Question could not be sent"}))}}async toggleMute(){var t;if(!(!this.alive||this.changing)){this.changing=!0;try{if(!this.state.muted)this.set({muted:!0}),this.peer.stopInput(),(t=this.inputSource)==null||t.disconnect();else{const n=await this.microphone();await this.peer.replaceInput(n),this.alive&&(this.set({muted:!1,notice:""}),this.peer.gateInput(this.state.voiceInterruption||this.state.phase!=="speaking"))}}catch{this.alive&&this.set({muted:!0,notice:"Microphone unavailable. You can type instead."})}finally{this.changing=!1}}}setVoiceInterruption(t){this.set({voiceInterruption:t}),this.peer.gateInput(!this.state.muted&&(t||this.state.phase!=="speaking"))}async interrupt(){if(this.alive){this.inputEpoch++,this.pendingAnswer=!1,this.awaitingUser=!1,this.answerSettled=!0,this.stopped=!0,this.newQuestion=!1,this.peer.muteOutput(!0),this.peer.gateInput(!this.state.muted),this.set({phase:"listening",replyPendingSince:0,notice:"Reply muted locally; a stop request was sent. Ask another question to continue."});try{await this.request("/interrupt",{})}catch{this.alive&&(this.set({error:"The remote stop could not be confirmed. The call was ended."}),await this.end())}}}async resumeSound(){await this.peer.resume(),this.alive&&this.set({phase:this.state.replyPendingSince?"thinking":"listening"})}async end(){var t,n,a,i;if(this.alive){this.alive=!1,window.removeEventListener("pagehide",this.pageExit),clearInterval(this.timer),this.life.abort(),(t=this.input)==null||t.getTracks().forEach(c=>c.stop()),(n=this.inputSource)==null||n.disconnect(),this.peer.close(),this.inputContext.close().catch(()=>{});try{(i=(a=this.options).onPlayback)==null||i.call(a,null)}catch{}if(this.pendingAnswer=!1,this.awaitingUser=!1,this.set({phase:"ended",muted:!0,notice:"",replyPendingSince:0}),this.id){const c=new AbortController,g=setTimeout(()=>c.abort(),4e3);try{await ne(`/live/calls/${this.id}/end`,{method:"POST",keepalive:!0,signal:c.signal})}catch{}finally{clearTimeout(g)}}}}}const Ot={connecting:"Getting ready",listening:"Your turn",hearing:"Listening to you",thinking:"Preparing your answer",speaking:"Draken is speaking",paused:"Sound paused",ended:"Call ended"},$t=s=>`${Math.floor(s/60)}:${String(s%60).padStart(2,"0")}`;function Ut({sync:s,readiness:t,onPrepareHistory:n,disabled:a,beforeStart:i,onActiveChange:c,onClosed:g,onChat:p,autoStart:m=!1,onAutoStartHandled:w,updatesUnavailable:o=!1}){var Ie;const[r,u]=d.useState(null),[k,v]=d.useState(""),[f,E]=d.useState(!1),[j,_]=d.useState(rs),[h,N]=d.useState(0),[b,x]=d.useState(!1),[C,O]=d.useState(""),[z,P]=d.useState([]),[R,_e]=d.useState(null),[J,re]=d.useState(""),[B,G]=d.useState(!1),[K,je]=d.useState(!1),X=d.useRef(null),H=d.useRef(null),W=d.useRef(null),be=d.useRef(null),q=d.useRef(null),V=d.useRef(!0),Z=d.useRef(!1),we=d.useRef(!1),[ke,He]=d.useState(!1),Pe=[...s.items,...s.context],le=Pe.find(l=>l.ref===J),fe=!!((Ie=s.conversation)!=null&&Ie.ended_at),ee=(t==null?void 0:t.ready)===!0&&!fe,xe=window.isSecureContext,Ne=new URL(window.location.href);Ne.protocol="https:",Ne.port=String((r==null?void 0:r.httpsPort)||443),d.useEffect(()=>{J&&H.current&&W.current&&(H.current.scrollTop+=W.current.getBoundingClientRect().top-H.current.getBoundingClientRect().top)},[J]);const de=async()=>{try{const l=await ne("/status");V.current&&(u(l),v(""))}catch(l){V.current&&v(l instanceof Error?l.message:"Could not check ChatGPT voice")}};d.useEffect(()=>{V.current=!0,de();const l=setInterval(()=>{q.current||de()},15e3);return()=>{var S;clearInterval(l),V.current=!1,(S=q.current)==null||S.end()}},[]),d.useEffect(()=>{var l,S,A;f&&!((l=X.current)!=null&&l.open)?(S=X.current)==null||S.showModal():f||(A=X.current)==null||A.close()},[f]),d.useEffect(()=>{if(!f||!j.startedAt||j.phase==="ended")return;const l=()=>N(Math.max(0,Math.floor((Date.now()-j.startedAt)/1e3)));l();const S=setInterval(l,1e3);return()=>clearInterval(S)},[f,j.startedAt,j.phase==="ended"]);const Te=async()=>{var l;if(!(q.current||Z.current||we.current||!ee)){we.current=!0,He(!0),v("");try{if(await i(),!V.current||document.visibilityState!=="visible")return;_({...rs}),N(0),P([]),O(""),re(""),x(!1),G(!1),je(!1),E(!0),c(!0);const S=new Lt({onState:A=>{V.current&&(_(A),!A.microphone&&A.muted&&x(!0))},onPlayback:A=>{be.current=A},onTurn:(A,$,Q,Ce)=>{V.current&&P(ie=>ie.some(he=>he.id===Ce)?ie.map(he=>he.id===Ce?{id:Ce,question:A,answer:$,refs:Q}:he):[...ie,{id:Ce,question:A,answer:$,refs:Q}])}});q.current=S,q.current===S&&await S.start(s.id)}catch(S){if(await((l=q.current)==null?void 0:l.end()),V.current){const A=S instanceof Error?S.message:"The call could not start";v(A),q.current&&_($=>({...$,phase:"ended",error:A}))}}finally{we.current=!1,V.current&&He(!1)}}};d.useEffect(()=>{!m||a||!ee||!r||(w==null||w(),r.installed&&!r.activeCall&&xe&&document.visibilityState==="visible"?Te():v("Your snapshot is ready. Start the call explicitly when audio is available and this page is visible."))},[m,a,ee,r]);const Se=async()=>{var l;if(!Z.current){Z.current=!0,re(""),await((l=q.current)==null?void 0:l.end()),q.current=null,V.current&&(E(!1),_e(null),c(!1));try{await g(),await de()}finally{Z.current=!1}}},Be=async()=>{try{_e(await ne(`/syncs/${s.id}/history`))}catch(l){v(l instanceof Error?l.message:"Could not load call history")}},Ve=async()=>{try{const l=await fetch("/api/voice/certificate",{headers:cs()});if(!l.ok)throw new Error("Could not download the local certificate. Check your dashboard login.");const S=URL.createObjectURL(await l.blob()),A=document.createElement("a");A.href=S,A.download="draken-local-root.crt",A.click(),setTimeout(()=>URL.revokeObjectURL(S),1e3)}catch(l){v(l instanceof Error?l.message:"Certificate download failed")}},Ye=()=>{var S;if(!C.trim())return;const l=C.trim();O(""),(S=q.current)==null||S.sendText(l)};return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"card voice-entry","aria-label":"Voice calls",children:[e.jsxs("div",{className:"voice-entry-main",children:[e.jsx("div",{className:"voice-entry-icon","aria-hidden":"true",children:e.jsx(Xe,{size:22})}),e.jsxs("div",{children:[e.jsx("h2",{children:"Talk it through. Out loud."}),e.jsx("p",{className:"muted small",children:"Live voice through ChatGPT. Audio goes to OpenAI; replies may paraphrase."}),e.jsx(as,{state:s.conversation,unavailable:o})]}),e.jsxs("div",{className:"conversation-actions",children:[e.jsxs("button",{className:"btn btn-secondary",disabled:f||ke,onClick:p,children:[e.jsx(ws,{size:16}),"Chat instead"]}),!xe&&(r!=null&&r.httpsPort)?e.jsxs("a",{className:"btn btn-primary",href:Ne.href,children:["Open secure call page ",e.jsx(Ys,{size:15})]}):e.jsxs("button",{className:"btn btn-primary",disabled:a||ke||!ee||!(r!=null&&r.installed)||!!(r!=null&&r.activeCall)||!xe,onClick:()=>void Te(),children:[e.jsx(Xe,{size:16}),"Call Draken"]})]})]}),e.jsx("p",{className:"small muted",children:"Relevant earlier history is found automatically. Retrieved excerpts go to ChatGPT, separately from this frozen snapshot; no review or saved decisions change."}),!xe&&e.jsxs("p",{className:"small muted",children:["The microphone needs trusted HTTPS. ",r!=null&&r.httpsPort?"The secure page uses your existing dashboard login. Install the local certificate once on this device before opening it.":"Use localhost, or enable HTTPS on the server."]}),(r==null?void 0:r.certificateAvailable)&&e.jsxs("details",{className:"voice-history",children:[e.jsx("summary",{children:"First-time browser setup"}),e.jsx("p",{className:"small",children:"Trust only your own Draken server’s certificate. This is a one-time device setup, not another account or voice subscription."}),e.jsx("button",{className:"btn btn-secondary",onClick:()=>void Ve(),children:"Download local certificate"}),e.jsxs("ul",{className:"small",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Windows:"})," open the downloaded certificate → Install Certificate → Current User → place in Trusted Root Certification Authorities."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"macOS:"})," import into Keychain Access → login keychain. Open its Trust section and choose Always Trust."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Firefox/Linux:"})," Settings → Privacy & Security → Certificates → View Certificates → Authorities → Import. Trust it to identify websites."]})]}),e.jsxs("p",{className:"small muted",children:["Restart the browser if needed, open the secure page, sign in, and allow the microphone when you start a call. Keep the server’s private keys private. See ",e.jsx("code",{children:"VOICE.md"})," for an SSH-tunnel alternative."]})]}),s.status==="open"&&!fe&&e.jsx("p",{className:"small muted",role:"status",children:ee?`Ready to call. History cutoff: ${t!=null&&t.before?new Date(t.before).toLocaleString():"prepared snapshot"}. Prepared updates become available between turns.`:t?t.preparing?"Preparing history before calling. Your microphone is off.":t.briefingReady?"History needs preparation before you can call.":"Prepare the briefing first.":"Checking call readiness…"}),s.status==="open"&&!fe&&(t==null?void 0:t.briefingReady)&&!t.preparing&&e.jsx("button",{className:"btn btn-secondary",disabled:a||ke,onClick:n,children:ee?"Refresh history":"Prepare history"}),(t==null?void 0:t.error)&&e.jsx("p",{className:"small",role:"alert",children:t.error}),s.status!=="open"&&e.jsx("p",{className:"small muted",children:"This sync is closed. Start a new sync for another call."}),r&&!r.installed&&e.jsxs("p",{className:"small muted",children:["ChatGPT voice needs server setup and sign-in: ",e.jsx("code",{children:"npm run voice:realtime:setup"}),", then ",e.jsx("code",{children:"npm run voice:realtime:login"}),"."]}),k&&e.jsxs("p",{className:"small",role:"alert",children:[k," ",e.jsx("button",{className:"btn btn-secondary",onClick:()=>void de(),children:"Retry"})]}),(r==null?void 0:r.activeCall)&&!f&&e.jsxs("div",{className:"small voice-reconnect",children:["A call is still open in another tab or device.",e.jsx("button",{className:"btn btn-secondary",disabled:a,onClick:()=>{window.confirm("End the existing voice call? Its completed transcript is kept.")&&ne(`/live/calls/${r.activeCall.id}/end`,{method:"POST",body:"{}"}).then(de).catch(l=>v(l.message))},children:"End previous call"})]}),e.jsxs("details",{className:"voice-history",onToggle:l=>{l.currentTarget.open&&Be()},children:[e.jsx("summary",{children:"Call history"}),(R==null?void 0:R.length)===0&&e.jsx("p",{className:"muted small",children:"No calls yet. Transcripts are saved here; raw audio is not recorded."}),R==null?void 0:R.map(l=>e.jsxs("details",{className:"voice-history-call",children:[e.jsxs("summary",{children:[new Date(l.started_at).toLocaleString()," · ",l.turns.length," ",l.mode==="native"?"messages":"turns"," · ",l.status]}),e.jsx("p",{className:"small muted",children:l.end_reason||"Call in progress"}),l.mode==="native"?e.jsx("p",{className:"small muted",children:"Ordered live transcripts, not verified question–answer pairs. Sources are supplied context, not verified citations. Exact playback is not confirmed."}):e.jsx("p",{className:"small muted",children:"Historical call from the retired local speech engine. These records are preserved; this engine cannot start new calls."}),l.turns.map(S=>e.jsxs("div",{className:"voice-history-turn",children:[S.question&&e.jsxs(e.Fragment,{children:[e.jsx("strong",{className:"message-author",children:"You"}),e.jsx("p",{className:"prose",children:S.question})]}),(S.answer||!S.question||l.mode!=="native")&&e.jsxs(e.Fragment,{children:[e.jsxs("strong",{className:"message-author",children:["Draken · ",S.status]}),e.jsx(Le,{text:`${S.answer||S.error||"No reply generated."} ${JSON.parse(S.evidence_json).map(A=>`[${A}]`).join(" ")}`,evidence:Pe}),S.status!=="completed"&&e.jsxs("p",{className:"small muted",children:["Generated text is shown above. ",S.heard_text?`Confirmed played: ${S.heard_text}`:"Playback was not confirmed."]})]})]},S.id))]},l.id))]})]}),e.jsxs("dialog",{ref:X,className:"voice-dialog","aria-labelledby":"voice-title",onCancel:l=>{l.preventDefault(),Se()},children:[e.jsxs("div",{className:"voice-dialog-header",children:[e.jsxs("div",{children:[e.jsx("span",{className:"eyebrow",children:"DRAKEN / VOICE SYNC"}),e.jsxs("h2",{id:"voice-title",children:["Sync #",s.id]}),e.jsx(as,{state:s.conversation,unavailable:o})]}),e.jsx("span",{className:"voice-clock","aria-label":"Call duration",children:$t(h)}),e.jsx("button",{className:"icon-button","aria-label":"Close call",onClick:()=>void Se(),children:e.jsx(es,{size:18})})]}),e.jsxs("div",{className:"voice-call-body",children:[j.historyReady?e.jsxs("div",{className:"voice-scene",children:[f&&j.phase!=="ended"?e.jsx(Rs,{playback:be,mode:j.phase==="speaking"?"speaking":j.phase==="hearing"?"listening":j.replyPendingSince&&!j.error?"thinking":"idle"}):e.jsx("img",{loading:"lazy",className:"voice-scene-poster",src:"/persona/call-poster.webp",alt:"Draken’s workshop"}),e.jsx(Dt,{call:j,historyLookup:K})]}):e.jsxs("section",{className:"voice-preparation","aria-label":"Call preparation",children:[e.jsx("h3",{children:j.phase==="ended"?"Call could not start":"Connecting your call"}),e.jsx("p",{className:"small muted",children:"Your microphone is off until the call is ready."})]}),e.jsx("p",{className:"sr-only",role:"status","aria-label":"Call state","aria-live":"polite",children:j.muted&&j.phase==="listening"?"Microphone muted":Ot[j.phase]})]}),j.error&&e.jsx("div",{className:"alert error",role:"alert",children:j.error}),j.error&&j.question&&j.phase==="listening"&&e.jsx("button",{className:"btn btn-primary",onClick:()=>{var l;return void((l=q.current)==null?void 0:l.sendText(j.question))},children:"Retry question"}),j.phase==="paused"&&e.jsx("button",{className:"btn btn-primary",onClick:()=>{var l;return void((l=q.current)==null?void 0:l.resumeSound())},children:"Resume sound"}),e.jsxs("div",{className:"voice-controls",children:[e.jsxs("button",{className:`btn btn-secondary ${j.muted?"is-muted":""}`,disabled:j.phase==="connecting"||j.phase==="ended",onClick:()=>{var l;return void((l=q.current)==null?void 0:l.toggleMute())},children:[j.muted?e.jsx(Zs,{size:18}):e.jsx(Xs,{size:18}),j.muted?j.microphone?"Unmute":"Enable mic":"Mute"]}),e.jsxs("button",{className:"btn btn-secondary",disabled:!["thinking","speaking","paused"].includes(j.phase),onClick:()=>{var l;return void((l=q.current)==null?void 0:l.interrupt().catch(()=>{}))},children:[e.jsx(ks,{size:15}),"Stop reply"]}),e.jsxs("button",{className:"btn btn-danger",onClick:()=>void Se(),children:[e.jsx(et,{size:18}),j.phase==="ended"?"Close":"End call"]})]}),e.jsxs("div",{className:"voice-options",children:[e.jsxs("button",{className:"voice-keyboard-toggle","aria-pressed":j.voiceInterruption,disabled:j.phase==="connecting"||j.phase==="ended",onClick:()=>{var l;return(l=q.current)==null?void 0:l.setVoiceInterruption(!j.voiceInterruption)},children:[e.jsx(Gs,{size:16}),"Headphone mode"]}),e.jsxs("button",{className:"voice-keyboard-toggle",onClick:()=>x(l=>!l),"aria-expanded":b,children:[e.jsx(Ks,{size:16}),b?"Hide keyboard":"Type a question"]})]}),b&&e.jsxs("form",{className:"voice-compose",onSubmit:l=>{l.preventDefault(),Ye()},children:[e.jsx("input",{className:"input","aria-label":"Type a question for this call",placeholder:"Or ask here…",maxLength:2e3,disabled:j.phase==="connecting"||j.phase==="ended",value:C,onChange:l=>O(l.target.value)}),e.jsx("button",{className:"btn btn-primary","aria-label":"Send voice-call question",disabled:!C.trim()||j.phase==="connecting"||j.phase==="ended",children:e.jsx(bs,{size:18})})]}),e.jsxs("details",{className:"voice-conversation",open:B,onToggle:l=>G(l.currentTarget.open),children:[e.jsx("summary",{children:"Conversation & details"}),e.jsxs("div",{className:"voice-call-details",ref:H,children:[j.notice&&e.jsx("p",{className:"small muted voice-notice",children:j.notice}),e.jsx(We,{enabled:f&&j.historyReady&&(!!j.replyPendingSince||["connecting","thinking"].includes(j.phase)),onLookupChange:je}),e.jsx("p",{className:"small muted",children:j.phase==="speaking"?j.voiceInterruption?"Speak to interrupt. Use headphones to avoid speaker feedback.":"Listening pauses during replies to prevent echo. Tap Stop reply to speak.":"Speak naturally. A short pause sends your question."}),e.jsx("div",{className:"voice-transcript",children:z.map(l=>e.jsxs("div",{children:[l.question&&e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"You"}),e.jsx("p",{children:l.question})]}),l.answer&&e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Draken · generated reply"}),e.jsx("p",{className:l.id===j.turnId?"voice-answer":void 0,children:l.answer})]})]},l.id))}),!z.length&&e.jsx("p",{className:"small muted",children:"No transcript yet."}),e.jsx("p",{className:"small muted",children:"Live generated transcripts, not word-timed subtitles. Exact playback and agreement are not confirmed. Full text is retained here even when the scene shows only its latest lines."}),j.evidence.length>0&&e.jsxs("details",{className:"voice-history",children:[e.jsxs("summary",{children:["Sources supplied (",j.evidence.length,")"]}),e.jsx("p",{className:"small muted",children:"Context available to the voice model, not verified citations for every spoken claim."}),e.jsx("div",{className:"voice-sources",children:j.evidence.map(l=>e.jsx("button",{className:"citation",onClick:S=>{const A=S.currentTarget.closest("details");A&&(A.open=!1),re(J===l?"":l)},children:l.startsWith("H")?`History ${l.slice(-6)}`:`Source ${l}`},l))})]}),f&&/^H[a-f0-9]{24}$/.test(J)&&e.jsxs("section",{className:"voice-source",ref:W,children:[e.jsx("button",{className:"btn btn-secondary",onClick:()=>re(""),children:"Close historical source"}),e.jsx(As,{reference:J})]}),f&&le&&e.jsxs("section",{className:"voice-source",ref:W,children:[e.jsxs("div",{className:"section-heading",children:[e.jsxs("strong",{children:[le.ref," · ",le.session_name||le.cwd]}),e.jsx("button",{className:"icon-button","aria-label":"Close source",onClick:()=>re(""),children:e.jsx(es,{size:16})})]}),e.jsx("pre",{children:le.text})]})]})]}),e.jsxs("div",{className:"voice-footer",children:[e.jsx(Hs,{size:14}),e.jsx("span",{children:"Experimental live audio to OpenAI · Generated, not verified · 30-minute limit"})]})]})]})}function Ft({sync:s,readiness:t,draft:n,setDraft:a,disabled:i,sending:c,onSend:g,onCancel:p,onPrepareHistory:m,onVoice:w,updatesUnavailable:o=!1}){var O,z;const r=s.tree.run,u=!!((O=s.conversation)!=null&&O.ended_at),k=s.status==="open"&&!u,v=s.busy&&(r==null?void 0:r.status)==="running"&&!!r.question,f=!s.busy&&!!(r!=null&&r.question)&&["failed","cancelled","interrupted"].includes((r==null?void 0:r.status)||""),E=c?n:v||f?r==null?void 0:r.question:null,j=v||c,_=c?"Sending your message…":r!=null&&r.stage.includes("Searching")?"Searching your prepared history…":r!=null&&r.stage.includes("Reconciling")?"Checking later updates…":r!=null&&r.stage.includes("Checking evidence")?"Checking source references…":r!=null&&r.stage.includes("Thinking")?"Draken is thinking…":"Reading the snapshot context…",h=d.useRef(null),N=d.useRef(!0);d.useEffect(()=>{N.current&&h.current&&(h.current.scrollTop=h.current.scrollHeight)},[s.messages.length,E,j,_]);const b=[...s.items,...s.context],x=!!(s.briefing&&s.tree.complete&&((z=s.conversation)!=null&&z.history_before||t!=null&&t.ready)),C=i||!k||!x;return e.jsxs("section",{className:"card text-chat","aria-label":"Chat with Draken",children:[e.jsxs("header",{className:"chat-heading",children:[e.jsx("img",{className:"chat-avatar",src:"/persona/chat-avatar.webp",alt:"Draken",width:"52",height:"52"}),e.jsxs("div",{children:[e.jsx("h2",{children:"Chat with Draken"}),e.jsx("p",{className:"small muted",children:"Same conversation. No microphone or audio."}),e.jsx(as,{state:s.conversation,unavailable:o})]}),e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:w,children:"Voice & call history"})]}),e.jsxs("div",{className:"chat-thread",ref:h,onScroll:()=>{const P=h.current;P&&(N.current=P.scrollHeight-P.scrollTop-P.clientHeight<80)},children:[!s.messages.length&&!E&&e.jsxs("div",{className:"chat-welcome",children:[e.jsx("h3",{children:"What would you like to pick up?"}),e.jsx("p",{children:"Ask about a project, a decision, or what still needs your attention. Draken will use the snapshot and prepared original history."})]}),s.messages.map(P=>e.jsxs("article",{className:`chat-message ${P.role}`,children:[P.role==="assistant"&&e.jsx("img",{className:"chat-avatar",src:"/persona/chat-avatar.webp",alt:"",width:"36",height:"36"}),e.jsxs("div",{className:"chat-bubble",children:[e.jsxs("div",{className:"chat-author",children:[e.jsx("strong",{children:P.role==="user"?"You":"Draken"}),e.jsx("time",{dateTime:P.created_at,children:new Date(P.created_at).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})})]}),e.jsx(Le,{text:P.content,evidence:b})]})]},P.id)),E&&!(r!=null&&r.request_id&&(v||f&&!c))&&e.jsx("article",{className:"chat-message user",children:e.jsxs("div",{className:"chat-bubble",children:[e.jsx("strong",{children:"You"}),e.jsx("p",{className:"prose",children:E})]})}),j&&e.jsxs("div",{className:"chat-message assistant",children:[e.jsx("img",{className:"chat-avatar",src:"/persona/chat-avatar.webp",alt:"",width:"36",height:"36"}),e.jsxs("div",{className:"chat-bubble chat-thinking",role:"status","aria-label":"Chat status","aria-live":"polite",children:[e.jsx("span",{className:"spinner","aria-hidden":"true"}),_,e.jsx("span",{className:"small muted",children:"Your answer will appear here when it’s ready."})]})]}),f&&e.jsxs("div",{className:"alert warning",role:"alert",children:[e.jsx("strong",{children:(r==null?void 0:r.status)==="failed"?"Reply failed.":"Reply stopped."}),e.jsx("p",{children:(r==null?void 0:r.error)||"The question is retained. Nothing was marked reviewed."}),e.jsx("button",{className:"btn btn-secondary",disabled:C,onClick:()=>g((r==null?void 0:r.question)||""),children:"Retry chat reply"})]})]}),k&&e.jsxs(e.Fragment,{children:[!j&&e.jsx("p",{className:"small muted",role:"status",children:x?"Newly prepared information is used on your next turn. You can keep chatting while updates are prepared.":s.busy?"Preparing the briefing and history for chat…":t!=null&&t.briefingReady?"Prepare history before sending a message.":"Prepare the briefing and history first."}),(t==null?void 0:t.error)&&e.jsx("p",{role:"alert",className:"small",children:t.error}),e.jsxs("form",{className:"chat-compose",onSubmit:P=>{P.preventDefault(),!C&&n.trim()&&(N.current=!0,g())},children:[e.jsx("label",{htmlFor:"chat-question",className:"sr-only",children:"Message Draken"}),e.jsx("textarea",{id:"chat-question",rows:3,maxLength:4e3,value:n,disabled:C,onChange:P=>a(P.target.value),placeholder:"Ask Draken…",onKeyDown:P=>{var R;P.key==="Enter"&&!P.shiftKey&&!P.nativeEvent.isComposing&&(P.preventDefault(),n.trim()&&!C&&((R=P.currentTarget.form)==null||R.requestSubmit()))}}),e.jsxs("div",{className:"chat-compose-footer",children:[e.jsx("span",{className:"small muted",children:"Enter to send · Shift+Enter for a new line"}),v?e.jsxs("button",{type:"button",className:"btn btn-secondary",onClick:p,children:[e.jsx(ks,{size:14}),"Stop reply"]}):e.jsxs("button",{className:"btn btn-primary",disabled:C||!n.trim(),children:[e.jsx(bs,{size:16}),"Send message"]})]})]}),(t==null?void 0:t.briefingReady)&&!t.preparing&&!j&&e.jsx("button",{className:"btn btn-secondary chat-refresh",disabled:i,onClick:m,children:x?"Refresh history":"Prepare history"})]}),!k&&e.jsx("p",{className:"small muted",children:u&&s.status==="open"?"Session ended after 30 minutes without a user message. Your chat is preserved; start a new sync to continue. Nothing was marked reviewed.":"This sync is closed. Its chat is preserved; start a new sync to continue."}),!k&&n.trim()&&e.jsxs("div",{className:"chat-compose",children:[e.jsx("label",{htmlFor:"ended-chat-draft",children:"Unsent message — copy it into a new sync"}),e.jsx("textarea",{id:"ended-chat-draft",rows:3,readOnly:!0,value:n})]}),e.jsx("p",{className:"small muted chat-boundary",children:"Messages stay with this sync. Calls remain in call history. Chatting never marks anything reviewed or saves decisions for you."})]})}function _s(){const s=crypto.getRandomValues(new Uint8Array(16));s[6]=s[6]&15|64,s[8]=s[8]&63|128;const t=[...s].map(n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Ps({cost:s}){if(!s)return null;const t=s.usd===null?"unavailable":s.usd>0&&s.usd<1e-6?"<$0.000001":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:s.usd<.01?6:2}).format(s.usd),n="Sync preparation only: summaries, consolidation, preparation recaps and final briefing, including retries. Excludes later questions, calls and conversation recaps. API-equivalent estimate from pi usage and catalog prices, not a subscription charge or invoice.",a=s.usd===null?" Usage/pricing was not captured or is unavailable for this preparation.":s.complete?"":" Partial total: some preparation usage/pricing is missing or work is still running.";return e.jsxs("span",{className:"sync-cost small muted",title:n+a,children:["Est. cost: ",t,s.usd!==null&&!s.complete?" (partial)":""]})}function ge(s,t,n){s.button||s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),t(n))}function zt({id:s,chat:t=!1,callIntent:n,consumeIntent:a,navigate:i,setGuard:c}){var xe,Ne,de,Te,Se,Be,Ve,Ye,Ie;const[g,p]=d.useState(null),[m,w]=d.useState(null),o=g&&(m==null?void 0:m.id)===s&&!((xe=g.conversation)!=null&&xe.ended_at)?{...g,conversation:m.state}:g,[r,u]=d.useState(null),[k,v]=d.useState(!1),[f,E]=d.useState(""),[j,_]=d.useState(""),[h,N]=d.useState(!1),[b,x]=d.useState(!1),[C,O]=d.useState(""),[z,P]=d.useState(""),[R,_e]=d.useState(""),J=d.useRef(!0),re=d.useRef(null),B=l=>{J.current&&(p(l),O(l.decisions),P(l.carry_forward))},G=async(l,S)=>{E(l),_("");try{await S()}catch(A){J.current&&_(A instanceof Error?A.message:"Something went wrong")}finally{J.current&&E("")}};d.useEffect(()=>(J.current=!0,Qe(s).then(B).catch(l=>{J.current&&_(l.message)}),()=>{J.current=!1}),[s]),d.useEffect(()=>{if(!(o!=null&&o.busy))return;let l=!1,S;const A=async()=>{try{const $=await yt(s);if(l)return;if($.busy)p(Q=>Q&&{...Q,tree:$});else{const Q=await Qe(s);l||B(Q);return}}catch($){l||_($ instanceof Error?$.message:"Could not refresh progress")}l||(S=setTimeout(()=>void A(),1e3))};return A(),()=>{l=!0,clearTimeout(S)}},[s,o==null?void 0:o.busy]),d.useEffect(()=>{u(null);const l=new AbortController;let S;const A=async()=>{try{const $=await(t?vt:gs)(s,l.signal);l.signal.aborted||u($)}catch{l.signal.aborted||u(null)}l.signal.aborted||(S=setTimeout(()=>void A(),o!=null&&o.busy?1e3:3e3))};return A(),()=>{l.abort(),clearTimeout(S)}},[s,o==null?void 0:o.busy,o==null?void 0:o.briefing,o==null?void 0:o.status,h,t]),d.useEffect(()=>{const l=new AbortController;let S;const A=async()=>{let $=!1;try{const Q=await xt(s,l.signal);l.signal.aborted||(w({id:s,state:Q}),v(!1),$=!!Q.ended_at)}catch{l.signal.aborted||v(!0)}!l.signal.aborted&&!$&&(S=setTimeout(()=>void A(),3e3))};return A(),()=>{l.abort(),clearTimeout(S)}},[s]);const K=!!(o&&(C!==o.decisions||z!==o.carry_forward)),je=!!R.trim();d.useEffect(()=>{c(()=>!(K||je||h)||window.confirm(h?"Leave this page and end the call?":"Leave with unsaved notes or an unsent message?"));const S=A=>{(K||je||h)&&(A.preventDefault(),A.returnValue="")};return window.addEventListener("beforeunload",S),()=>{c(null),window.removeEventListener("beforeunload",S)}},[K,je,h,c]);const X=()=>{a(),x(!1)},H=!!(f||o!=null&&o.busy||h),W=(o==null?void 0:o.status)==="open",be=!!((Ne=o==null?void 0:o.conversation)!=null&&Ne.ended_at),q=W&&!be,V=o?[...o.items,...o.context]:[],Z=V.some(l=>l.unavailable),we=()=>void G("Preparing your conversation…",async()=>{if(o){if(t&&K)throw new Error("Save or undo your note edits before preparing chat.");x(!t),K&&await qe(s,C,z),B(await Nt(s))}}),ke=()=>void G("Preparing history for your conversation…",async()=>{if(t&&K)throw new Error("Save or undo your note edits before refreshing history.");X(),u(null),K&&await qe(s,C,z),B(await jt(s))}),He=(l=R)=>void G("Starting discussion…",async()=>{K&&await qe(s,C,z),B(await St(s,l))}),Pe=(l=R)=>void G("Sending message…",async()=>{var $,Q;if(X(),K)throw new Error("Save your note edits, or undo them, before sending a message. Chat does not save decisions for you.");const S=(($=re.current)==null?void 0:$.text)===l?re.current:{text:l,id:_s()};re.current=S;let A;try{A=await pt(s,l,S.id)}catch(Ce){const ie=await Qe(s).catch(()=>null);if(((Q=ie==null?void 0:ie.tree.run)==null?void 0:Q.request_id)!==S.id)throw ie&&p(he=>he&&{...he,conversation:ie.conversation}),Ce;A=ie}B(A),_e(""),re.current=null}),le=()=>{var l;return(l=o==null?void 0:o.tree.run)!=null&&l.question?t||o.tree.run.request_id?Pe(o.tree.run.question):He(o.tree.run.question):we()},fe=()=>{X(),G("Stopping preparation…",async()=>{await kt(s)})},ee=!(o!=null&&o.busy)&&(o==null?void 0:o.tree.run)&&["failed","cancelled","interrupted"].includes(o.tree.run.status);return d.useEffect(()=>{(ee||r!=null&&r.error)&&X()},[ee,r==null?void 0:r.error]),e.jsxs("main",{className:"sync-detail",children:[e.jsxs("a",{className:"back-link",href:"/",onClick:l=>ge(l,i,"/"),children:[e.jsx(zs,{size:16}),"All syncs"]}),j&&e.jsx("div",{className:"alert error",role:"alert",children:j}),!o&&!j&&e.jsx("p",{role:"status",children:"Opening sync…"}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"page-heading",children:[e.jsxs("div",{children:[e.jsx("span",{className:"eyebrow",children:q?"LIVE CONVERSATION":"SAVED CONVERSATION"}),e.jsxs("h1",{children:["Sync #",s]}),e.jsxs("p",{className:"muted",children:["Initial snapshot created ",new Date(o.snapshot_at).toLocaleString()," · ",o.item_count," entries · ",e.jsx("span",{className:`status ${o.status}`,children:o.status==="completed"?"reviewed":be&&W?"session ended":o.status})]}),e.jsx(Ps,{cost:o.aggregation_cost})]}),W&&e.jsxs("button",{className:"btn btn-secondary",disabled:H||Z||!!(o.tree.run&&!o.tree.complete),onClick:()=>{window.confirm(`Mark these ${o.item_count} snapshot entries reviewed? Later activity is not affected. This does not mean every spoken suggestion was agreed.`)&&G("Marking snapshot reviewed…",async()=>{B(await _t(s,C,z))})},children:[e.jsx(Bs,{size:16}),"Mark reviewed"]})]}),be&&W&&e.jsxs("div",{className:"alert warning",role:"status",children:[e.jsx("strong",{children:"Session ended"}),e.jsx("p",{children:"There have been no user messages for 30 minutes. The transcript and notes are retained; nothing was marked reviewed automatically."}),e.jsx("button",{className:"btn btn-secondary",onClick:()=>i("/"),children:"Start a new sync"})]}),Z&&e.jsxs("div",{className:"alert warning",role:"alert",children:[e.jsx("strong",{children:"Original session evidence unavailable."}),e.jsx("p",{children:"Restore the original session files to inspect the missing excerpts, prepare replies, call or mark this snapshot reviewed. Your conversation and saved notes are still available; Draken keeps pointers, not copies of original session text."})]}),(f||o.busy)&&!(t&&(f==="Sending message…"||(de=o.tree.run)!=null&&de.question&&o.tree.run.status==="running"))&&e.jsxs("div",{className:"working",role:"status",children:[e.jsx("span",{className:"spinner"}),f||(o.recap_state==="running"?"Making a short conversation recap…":r!=null&&r.preparing?"Preparing searchable history…":((Te=o.tree.run)==null?void 0:Te.stage)||"Preparing your conversation…"),o.busy&&e.jsx("button",{className:"btn btn-secondary",onClick:fe,children:"Cancel preparation"})]}),e.jsx(We,{enabled:o.busy}),o.busy&&!((Se=o.tree.run)!=null&&Se.question)&&o.recap_state!=="running"&&e.jsx("p",{className:"small muted",children:"The complete new snapshot is being reconciled. Large histories can take a while. Leaving or reloading will not start your microphone."}),ee&&q&&!(t&&((Be=o.tree.run)!=null&&Be.question))&&e.jsxs("div",{className:"alert warning",role:"alert",children:[e.jsx("strong",{children:(Ve=o.tree.run)!=null&&Ve.question?"Reply stopped.":"Preparation stopped."}),e.jsx("p",{children:((Ye=o.tree.run)==null?void 0:Ye.error)||"Your snapshot is retained. Nothing was marked reviewed."}),e.jsx("button",{className:"btn btn-primary",disabled:H||Z,onClick:le,children:(Ie=o.tree.run)!=null&&Ie.question?"Retry reply":t?"Retry preparation":"Retry preparation & call"})]}),q&&!o.briefing&&!o.busy&&!ee&&o.snapshot_version===2&&e.jsx("button",{className:"btn btn-primary",disabled:H||Z,onClick:we,children:t?"Prepare for chat":"Prepare & call"}),t?e.jsx(Ft,{sync:o,updatesUnavailable:k,readiness:r,draft:R,setDraft:_e,disabled:H||Z,sending:f==="Sending message…",onSend:Pe,onCancel:fe,onPrepareHistory:ke,onVoice:()=>i(`/syncs/${s}`)}):e.jsx(Ut,{sync:o,updatesUnavailable:k,readiness:r,onPrepareHistory:ke,disabled:H||Z,onActiveChange:N,onChat:()=>{X(),i(`/syncs/${s}/chat`)},autoStart:(n||b)&&q&&!ee&&!Z,onAutoStartHandled:X,beforeStart:async()=>{K&&B(await qe(s,C,z));const l=await gs(s);if(u(l),!l.ready)throw new Error("History needs preparation before calling. Use Prepare history first.")},onClosed:async()=>{await G("Saving a short recap…",async()=>{B(await ps(s))})}},s),e.jsxs("section",{className:"card recap-card",children:[e.jsxs("div",{className:"section-heading",children:[e.jsx("h2",{children:"At a glance"}),e.jsx("button",{className:"btn btn-secondary",disabled:H,onClick:()=>void G("Summarizing the conversation…",async()=>B(await ps(s))),children:o.recap?"Refresh recap":"Make recap"})]}),e.jsx("p",{className:"prose",children:o.recap||"Use Make recap to condense this conversation. Ending a call also requests a recap. The full briefing and original history remain below."}),e.jsx("p",{className:"small muted",children:"Automatic summary, not saved decisions or proof of agreement."}),o.recap_error&&e.jsx("p",{role:"alert",className:"small",children:o.recap_error})]}),o.memory.length>0&&e.jsxs("details",{className:"detail-section",children:[e.jsx("summary",{children:"Previous sync recaps"}),o.memory.map(l=>e.jsxs("article",{className:"memory-recap",children:[e.jsxs("a",{href:`/syncs/${l.sync_id}`,onClick:S=>ge(S,i,`/syncs/${l.sync_id}`),children:["Sync #",l.sync_id]})," ",e.jsx("span",{className:"small muted",children:l.status==="open"?"not marked reviewed":l.status||"historical"}),e.jsx("p",{className:"prose",children:l.recap||"No automatic recap in this older snapshot."}),l.decisions&&e.jsxs("p",{className:"small prose",children:["Saved decisions: ",l.decisions]}),l.carry_forward&&e.jsxs("p",{className:"small prose",children:["Carried forward: ",l.carry_forward]})]},l.sync_id))]}),e.jsxs("details",{className:"detail-section",open:!o.messages.length&&!!o.briefing,children:[e.jsx("summary",{children:"Full briefing"}),e.jsxs("section",{className:"briefing-card",children:[e.jsx("p",{className:"small muted",children:"This snapshot contains the entries captured during preparation, not a live view. Check the original source dates in the evidence."}),(r==null?void 0:r.before)&&e.jsxs("p",{className:"small muted",children:["Latest ready history cutoff: ",new Date(r.before).toLocaleString(),". Active conversations adopt prepared updates between turns; this initial briefing stays unchanged."]}),o.briefing?e.jsx(Le,{text:o.briefing,evidence:V}):e.jsx("p",{children:"No briefing yet."}),o.snapshot_version<2&&e.jsxs("div",{className:"alert warning",children:["This is a historical capped snapshot. Notes and discussion are preserved.",W&&e.jsx("button",{className:"btn btn-secondary",disabled:H,onClick:()=>{window.confirm("Expand this legacy snapshot to currently eligible history? Existing notes and citations are retained.")&&G("Expanding snapshot…",async()=>B((await wt(s)).sync))},children:"Expand to full history"})]})]})]}),!t&&e.jsxs("details",{className:"detail-section",children:[e.jsxs("summary",{children:["Saved text conversation (",o.messages.length,")"]}),e.jsxs("section",{className:"discussion",children:[o.messages.map(l=>e.jsxs("div",{className:`message ${l.role}`,children:[e.jsx("span",{className:"message-author",children:l.role==="user"?"You":"Draken"}),e.jsx(Le,{text:l.content,evidence:V})]},l.id)),e.jsx("button",{className:"btn btn-secondary",disabled:h,onClick:()=>{X(),i(`/syncs/${s}/chat`)},children:"Open chat"})]})]}),e.jsxs("details",{className:"detail-section",children:[e.jsxs("summary",{children:["Decisions & carry-forward",K?" · unsaved":""]}),e.jsxs("section",{className:"notes-card",children:[e.jsxs("div",{className:"notes-grid",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"decisions",children:"Decisions"}),e.jsx("textarea",{id:"decisions",rows:4,maxLength:4e3,disabled:!W||H,value:C,onChange:l=>O(l.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"carry-forward",children:"Carry into the next sync"}),e.jsx("textarea",{id:"carry-forward",rows:4,maxLength:4e3,disabled:!W||H,value:z,onChange:l=>P(l.target.value)})]})]}),e.jsx("p",{className:"small muted",children:"Only these explicitly saved notes are decisions. A call or its automatic recap does not mark anything agreed or reviewed."}),W&&e.jsx("button",{className:"btn btn-secondary",disabled:H||!K,onClick:()=>void G("Saving notes…",async()=>B(await qe(s,C,z))),children:"Save notes"})]})]}),e.jsxs("details",{className:"detail-section",children:[e.jsx("summary",{children:"Evidence & preparation details"}),e.jsx(Tt,{syncId:s,progress:o.tree,evidence:V,onResume:q?le:void 0,resumeEnabled:!H&&!Z,onCancel:fe}),e.jsx(fs,{items:o.items,title:"New evidence in this snapshot"}),e.jsx(fs,{items:o.context,title:"Earlier context — not new progress"})]}),W&&e.jsxs("div",{className:"detail-footer",children:[e.jsx("p",{className:"small muted",children:"Included does not mean reviewed. You can return to this sync at this URL, or start a separate one for new activity."}),e.jsx("button",{className:"btn btn-ghost",disabled:H,onClick:()=>{window.confirm("Discard this sync and release its unreviewed entries? Its history is retained.")&&G("Discarding sync…",async()=>B(await Pt(s)))},children:"Discard sync"})]})]})]})}function Ts({active:s=!0,firstRun:t=!1,always:n=!1,onReady:a,onTextReady:i}){const[c,g]=d.useState(null),[p,m]=d.useState(null),[w,o]=d.useState(""),[r,u]=d.useState(!1),[k,v]=d.useState(0);if(d.useEffect(()=>{if(!s)return;let E=!0;const j=async(h=!1)=>{u(!0);try{const[N,b]=await Promise.all([ot(h),ne("/status").catch(()=>null)]);if(!E)return;g(N),m(b),o(b?"":"Voice status is unavailable. Configured text chat can still be used."),a==null||a(N.pi.state==="configured"&&!!(b!=null&&b.installed)),i==null||i(N.pi.state==="configured")}catch{E&&(o("Could not check setup or reach Draken. The last displayed state may be stale. Check the server terminal, then retry."),a==null||a(!1),i==null||i(!1))}finally{E&&u(!1)}};j(k>0);const _=setInterval(()=>void j(),6e4);return()=>{E=!1,clearInterval(_)}},[s,k,a,i]),!s||!n&&!t&&!w&&(c==null?void 0:c.pi.state)==="configured"&&(p!=null&&p.installed))return null;const f=c==null?void 0:c.pi;return e.jsxs("section",{className:"setup-panel","aria-label":"Draken setup",children:[e.jsx("h2",{children:t?"First-time setup":"Runtime & sign-in"}),e.jsx("p",{className:"small muted",children:"Draken reads agent histories, but pi runs summaries and text chat. Voice uses a separate ChatGPT sign-in. Setup and login are explicit terminal commands—not browser downloads or credential forms."}),e.jsxs("p",{className:"small muted",children:["New installations enable automatic local indexing while the server runs. It accumulates searchable history without creating syncs, summaries or briefings, and makes no provider model calls. Local embeddings use CPU, memory and disk; first use may download about 136 MB of search model files. Change this in ",e.jsx("strong",{children:"Settings → Automatically index history"}),". Existing installations keep their saved indexing choice. Only your Sync with Draken or Chat instead action starts a new snapshot and briefing using configured models and their quota or API billing."]}),!c&&!w&&e.jsx("p",{className:"small",role:"status",children:"Checking setup…"}),f&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{children:[e.jsxs("strong",{children:["Summarization: ",f.state==="configured"?"credentials configured":f.state==="missing"?"pi not found":f.state==="needs_login"?"sign-in needed":"needs attention"]}),e.jsxs("span",{className:"small muted",children:[" · ",f.source==="managed"?"Draken-private pi":"Existing / external pi",f.version&&` ${f.version}`]})]}),e.jsx("p",{className:"small",children:f.message}),f.state!=="configured"&&e.jsxs("div",{className:"setup-commands",children:[["missing","incompatible"].includes(f.state)&&e.jsxs("p",{children:[e.jsx("code",{children:"draken setup"})," — install a pinned, private pi after confirmation. An explicit ",e.jsx("code",{children:"DRAKEN_PI_BIN"})," must be fixed or unset first."]}),e.jsxs("p",{children:[e.jsx("code",{children:"draken login"})," — open pi; type ",e.jsx("code",{children:"/login"}),", follow its prompts, then ",e.jsx("code",{children:"/quit"}),"."]}),e.jsxs("p",{children:[e.jsx("code",{children:"draken doctor"})," — inspect configuration without a generation request."]})]}),e.jsx("ul",{className:"small muted",children:f.models.map(E=>e.jsxs("li",{children:[E.model," · ",E.state.replace(/_/g," ")]},E.model))}),e.jsxs("p",{className:"small muted source-path",children:["Pi credential directory: ",f.agent_dir]})]}),p&&e.jsx("p",{children:e.jsxs("strong",{children:["ChatGPT voice: ",p.installed?"helper and sign-in configured":"setup needed"]})}),p&&!p.installed&&e.jsxs("div",{className:"setup-commands",children:[e.jsxs("p",{children:[e.jsx("code",{children:"draken voice setup"})," — install the native helper."]}),e.jsxs("p",{children:[e.jsx("code",{children:"draken voice login"})," — use its separate official ChatGPT sign-in. No pi tokens are copied."]})]}),(n||t||(f==null?void 0:f.state)!=="configured"||!(p!=null&&p.installed))&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"small muted",children:["Run commands on the server as its user, with the same environment. After login, click Check setup again. Keep the server terminal open; Ctrl+C stops it. ",e.jsx("code",{children:"draken status"})," checks connectivity."]}),c&&e.jsxs("p",{className:"small muted source-path",children:["Draken data: ",c.data_dir]}),e.jsxs("p",{className:"small muted",children:["Choose sources in ",e.jsx("strong",{children:"Settings → Agents & sessions"}),", then ",e.jsx("strong",{children:"Sync with Draken"}),". Source scanning works before sign-in. Credential presence does not verify model access, billing or voice playback."]})]}),w&&e.jsx("p",{className:"small",role:"alert",children:w}),e.jsx("button",{type:"button",className:"btn btn-secondary",disabled:r,onClick:()=>v(E=>E+1),children:r?"Checking…":"Check setup again"})]})}function Is({active:s,indexing:t,controls:n=!1,disabled:a=!1,onBusyChange:i}){const[c,g]=d.useState(null),[p,m]=d.useState(!1),[w,o]=d.useState(""),[r,u]=d.useState("");d.useEffect(()=>{if(!s||p)return;let f=!0;const E=async()=>{try{const _=await lt();f&&(g(_),u(""))}catch(_){f&&u(_ instanceof Error?_.message:"Could not read summary preparation status")}};E();const j=setInterval(()=>void E(),4e3);return()=>{f=!1,clearInterval(j)}},[s,p]);const k=async f=>{m(!0),i==null||i(!0),o("");try{g(await dt(f))}catch(E){o(E instanceof Error?E.message:"Could not save summary preparation settings")}finally{m(!1),i==null||i(!1)}},v=c&&{off:"Background summary preparation is off.",waiting:"Waiting for the next summary preparation batch.",running:"Preparing reusable summaries ahead of your next sync…",paused:"Summary preparation is paused.",error:"Summary preparation needs an explicit retry."}[c.status];return e.jsxs("section",{"aria-label":"Background summary preparation",children:[n&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"index-toggle",children:[e.jsx("input",{type:"checkbox",role:"switch",checked:(c==null?void 0:c.enabled)||!1,disabled:!c||p||a||!t&&!c.enabled,onChange:f=>void k(f.target.checked)}),e.jsxs("span",{children:[e.jsx("strong",{children:"Prepare summaries ahead"}),e.jsx("span",{className:"small muted",children:"Use the configured summary provider and its quota or API billing to cache reusable summaries. Never create a sync or briefing automatically."})]})]}),e.jsx("p",{className:"small muted",children:"Off until you enable it, including after an upgrade. Requires automatic indexing. After 64 new or changed eligible entries, prepare summary chunks and compaction in the background. Starting a chat or sync reuses completed work; changed tails, reconciliation and the opening briefing may still need preparation."}),e.jsx("p",{className:"small muted",children:"Foreground work takes priority. Disabling either option stops background preparation and keeps valid cache entries. Provider failures pause paid retries until you explicitly retry. Preparation usage includes these requests; cached entries are not reviewed work or completed syncs."})]}),c&&(n||c.enabled)&&e.jsxs(e.Fragment,{children:[e.jsx("p",{role:"status",className:"small muted",children:!t&&c.enabled?"Summary preparation is paused while automatic indexing is off.":v}),c.last_completed_at&&e.jsxs("p",{className:"small muted",children:["Last successful background pass: ",c.prepared_entries.toLocaleString()," entries, ",new Date(c.last_completed_at).toLocaleString(),". Later changes may still need preparation."]}),c.error&&e.jsx("p",{role:"alert",children:c.error}),n&&c.enabled&&c.status==="error"&&e.jsx("button",{type:"button",className:"btn btn-secondary",disabled:p||a||!t,onClick:()=>void k(!0),children:"Retry summary preparation"})]}),p&&e.jsx("p",{role:"status",children:"Saving summary preparation…"}),(w||r)&&e.jsx("p",{role:"alert",className:"small",children:w||r})]})}function Ms({settings:s}){const t={off:"Automatic indexing is off.",waiting:"Waiting for the next indexing batch.",scanning:"Checking history for changes…",indexing:"Indexing searchable history…",summarizing:"Preparing reusable summary cache…",paused:"Paused for your conversation or foreground work.",stopping:"Stopping automatic indexing…",error:"Automatic indexing needs attention."}[s.phase];return e.jsxs("section",{className:"history-progress","aria-label":"Automatic indexing",children:[e.jsx("p",{role:"status",children:e.jsx("strong",{children:t})}),s.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"small muted",children:[s.pending_records.toLocaleString()," source changes waiting for local indexing. ",s.last_completed_at&&`Last completed indexing batch: ${new Date(s.last_completed_at).toLocaleString()}.`]}),e.jsxs("p",{className:"small muted",children:[s.pending_entries.toLocaleString()," entries available for your next sync. History accumulates without creating snapshots or briefings."]})]}),s.error&&e.jsx("p",{role:"alert",children:s.error}),e.jsx(We,{enabled:s.enabled&&s.phase==="indexing",backgroundOnly:!0})]})}function Ht(){const[s,t]=d.useState(null),[n,a]=d.useState(!1);return d.useEffect(()=>{let i=!0;const c=async()=>{try{const p=await Es();i&&(t(p),a(!1))}catch{i&&a(!0)}};c();const g=setInterval(()=>void c(),4e3);return()=>{i=!1,clearInterval(g)}},[]),n?e.jsx("p",{role:"status",className:"small muted",children:"Automatic indexing status is temporarily unavailable."}):s!=null&&s.enabled?e.jsxs(e.Fragment,{children:[e.jsx(Ms,{settings:s}),s.summary_enabled&&e.jsx(Is,{active:!0,indexing:s.enabled})]}):null}const Bt=s=>new Date(s).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"});function Vt({navigate:s}){const[t,n]=d.useState(null),[a,i]=d.useState(""),[c,g]=d.useState(""),[p,m]=d.useState(""),[w,o]=d.useState(!1),[r,u]=d.useState(!1),k=d.useRef(!0),v=d.useRef(!1),f=d.useRef(),E=async()=>{const h=await ts();k.current&&n(N=>N&&N.syncs.length>20?{...h,syncs:[...h.syncs,...N.syncs.filter(b=>{var x;return b.id<((x=h.syncs[h.syncs.length-1])==null?void 0:x.id)})],next_cursor:N.next_cursor}:h)};d.useEffect(()=>{k.current=!0,E().catch(N=>g(N.message)),window.isSecureContext||ne("/status").then(N=>{if(k.current&&N.httpsPort){const b=new URL("/",location.href);b.protocol="https:",b.port=String(N.httpsPort),m(b.href)}}).catch(()=>{});const h=setInterval(()=>{v.current||E().catch(()=>{})},4e3);return()=>{k.current=!1,clearInterval(h)}},[]);const j=async(h="call")=>{if(!v.current){v.current=!0,i("Collecting new activity…"),g(""),f.current||(f.current=_s());try{if(h==="call"){const b=await ne("/status");if(!b.installed)throw new Error("Voice is not ready on this server. Complete voice setup before starting a sync call.");if(b.activeCall)throw new Error("End the existing call before starting another sync.")}const N=await(h==="chat"?ut:ht)(f.current);k.current&&s(`/syncs/${N.sync.id}${h==="chat"?"/chat":""}`,h==="call")}catch(N){k.current&&g(N instanceof Error?N.message:"Could not start the sync")}finally{v.current=!1,k.current&&i("")}}},_=!!(!w||a||t!=null&&t.busy||t!=null&&t.active_call);return e.jsxs("main",{className:"sync-home",children:[e.jsxs("div",{className:"page-heading",children:[e.jsxs("div",{children:[e.jsx("h1",{children:"Pick up where you left off."}),e.jsx("p",{className:"muted",children:"New activity. A little memory. One conversation."})]}),e.jsxs("div",{className:"conversation-actions",children:[e.jsxs("button",{className:"btn btn-secondary",disabled:!t||!r||!!(a||t!=null&&t.busy||t!=null&&t.active_call),onClick:()=>void j("chat"),children:[e.jsx(ws,{size:17}),"Chat instead"]}),p?e.jsxs("a",{className:"btn btn-primary",href:p,children:["Open secure Draken",e.jsx(hs,{size:17})]}):e.jsxs("button",{className:"btn btn-primary",disabled:!t||_||!window.isSecureContext,onClick:()=>void j(),children:[e.jsx(Xe,{size:17}),"Sync with Draken"]})]})]}),!window.isSecureContext&&e.jsx("p",{className:"small muted",children:"Use trusted HTTPS or localhost for the combined sync and call."}),e.jsx("p",{className:"home-hint muted small",children:"Automatic indexing accumulates searchable history locally. Enable Prepare summaries ahead in Settings to cache summary work before your next chat. Click Sync with Draken or Chat instead to create the snapshot and opening briefing. Active conversations receive prepared updates between turns and end after 30 minutes without a user message. Nothing is marked reviewed until you confirm it."}),e.jsxs("div",{className:"home-counts","aria-label":"Sync tracking",children:[e.jsxs("span",{children:[e.jsx("strong",{children:(t==null?void 0:t.available)??"—"})," available for a new sync"]}),e.jsxs("span",{children:[e.jsx("strong",{children:(t==null?void 0:t.included_unreviewed)??"—"})," reserved, not reviewed"]}),e.jsxs("span",{children:[e.jsx("strong",{children:(t==null?void 0:t.covered)??"—"})," reviewed"]})]}),e.jsx(Ht,{}),e.jsxs("details",{className:"home-preparation-info",children:[e.jsx("summary",{children:"Automatic indexing and cost tracking"}),e.jsxs("p",{children:[e.jsx("strong",{children:"Automatic local indexing:"})," new installations automatically accumulate searchable history while the server runs, checking once a minute and indexing batches at 64 source changes. While a conversation is active, even small changes are prepared on the next idle check and used between turns. Without an active conversation, smaller tails wait for explicit preparation or a full batch. Turn it off in ",e.jsx("strong",{children:"Settings → Automatically index history"}),". Existing installations keep their previous choice, including off. Local embeddings use CPU, memory and disk; first use may download about 136 MB of search model files."]}),e.jsxs("p",{children:["Automatic indexing makes no provider model calls and creates no syncs, summaries or briefings. Only your Sync with Draken or Chat instead action creates a snapshot and starts its briefing, using configured models and their quota or API billing. The separate ",e.jsx("strong",{children:"Settings → Prepare summaries ahead"})," option uses your summary provider to cache chunk summaries and compaction before you click. It starts off, including after upgrades. A new sync reuses matching cached work; changed tails, reconciliation and the final briefing may still take time. No background option creates a sync. Indexing does not edit or delete original agent logs, existing snapshots or notes. It never starts a call, saves decisions or marks work reviewed automatically."]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Preparation spending estimates:"})," open ",e.jsx("strong",{children:"Settings → Preparation usage"})," for estimated USD cost, completed batches and model requests over time. Preparation history, including past automatic work, retries and failed work, is retained; missing prices remain unavailable or partial."]}),e.jsx("p",{className:"small muted",children:"Not total spending, a provider invoice or account quota. Chat, voice, standalone post-conversation recaps and local machine/network costs are excluded. Opening this explanation or the usage dashboard does not start preparation."})]}),a&&e.jsxs("p",{role:"status",className:"working",children:[e.jsx("span",{className:"spinner"}),a]}),(t==null?void 0:t.busy)&&!a&&e.jsx("p",{className:"small muted",role:"status",children:"Draken is updating a sync. Open its card to follow progress."}),(t==null?void 0:t.active_call)&&e.jsx("p",{className:"small muted",children:"A call is active. End it before starting another sync."}),c&&e.jsx("div",{className:"alert error",role:"alert",children:c}),e.jsx(Ts,{firstRun:!!(t&&!t.syncs.length),onReady:o,onTextReady:u}),e.jsxs("section",{className:"sync-feed","aria-label":"Sync history",children:[t==null?void 0:t.syncs.map(h=>{var N,b;return e.jsxs("a",{className:"card sync-tile",href:`/syncs/${h.id}`,onClick:x=>ge(x,s,`/syncs/${h.id}`),children:[e.jsxs("div",{className:"sync-tile-heading",children:[e.jsxs("strong",{children:["Sync #",h.id]}),e.jsx("span",{className:`status ${h.status}`,children:h.busy?"working":h.active_call?"in call":h.needs_retry?"needs retry":h.status==="completed"?"reviewed":h.status==="open"?(N=h.conversation)!=null&&N.ended_at?"session ended":"open":"discarded"}),e.jsx(hs,{size:17,"aria-hidden":"true"})]}),e.jsxs("div",{className:"small muted",children:[Bt(h.created_at)," · ",h.item_count," ",h.item_count===1?"entry":"entries"," · ",h.calls," ",h.calls===1?"call":"calls",h.aggregation_cost&&e.jsxs(e.Fragment,{children:[" · ",e.jsx(Ps,{cost:h.aggregation_cost})]})]}),e.jsx("p",{className:"sync-tile-preview",children:h.preview||(h.needs_retry?"Preparation stopped. Open this sync to retry; its entries and cached work are retained.":h.busy?"Bringing the new activity together. Open this sync to follow preparation.":(b=h.conversation)!=null&&b.ended_at?"Session ended. Its transcript is retained; start a new sync to continue.":"No recap yet. Open this sync to continue the conversation.")}),e.jsx("span",{className:"sync-tile-kind small muted",children:h.preview_kind==="recap"?"Conversation recap · not saved decisions":h.preview_kind==="previous_recap"?"Earlier recap · conversation changed":h.preview_kind==="briefing"?"Briefing preview":"Frozen snapshot"})]},h.id)}),t&&!t.syncs.length&&e.jsxs("div",{className:"card welcome",children:[e.jsx("h2",{children:"Your next conversation starts here."}),e.jsx("p",{children:"Draken keeps track of the work you’ve already brought into a sync. Start above; the details can wait until you need them."})]})]}),(t==null?void 0:t.next_cursor)&&e.jsx("button",{className:"btn btn-secondary",onClick:async()=>{try{const h=await ts(t.next_cursor);n(N=>N?{...N,syncs:[...N.syncs,...h.syncs.filter(b=>!N.syncs.some(x=>x.id===b.id))],next_cursor:h.next_cursor}:h)}catch(h){g(h instanceof Error?h.message:"Could not load history")}},children:"Older syncs"})]})}function Yt({navigate:s,reference:t}){const[n,a]=d.useState(null),[i,c]=d.useState(""),[g,p]=d.useState(""),[m,w]=d.useState(!1),o=d.useRef();return d.useEffect(()=>()=>{var r;return(r=o.current)==null?void 0:r.abort()},[]),e.jsxs("main",{className:"sync-home history-page",children:[e.jsx("a",{className:"back-link",href:"/",onClick:r=>ge(r,s,"/"),children:"All syncs"}),e.jsx("h1",{children:t?"Historical source":"Find earlier work."}),e.jsx("p",{className:"muted",children:"Search retained sessions, sync discussions and explicitly saved notes. Results are historical evidence—not new progress, agreement or proof of execution."}),t?e.jsxs(e.Fragment,{children:[e.jsx(As,{reference:t},t),e.jsx("p",{children:e.jsx("a",{href:"/history",onClick:r=>ge(r,s,"/history"),children:"Search history"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"small muted",children:"Draken combines meaning and keyword matches automatically. First use prepares a local model (about 136 MB); later searches reuse it and update changed records. Search text stays on this server. Your source exclusions and history baseline still apply."}),e.jsxs("form",{className:"history-search",onSubmit:async r=>{r.preventDefault(),w(!0),p(""),a(null);const u=new AbortController;o.current=u;try{const k=await Et({question:i},u.signal);u.signal.aborted||a(k)}catch(k){u.signal.aborted||p(k instanceof Error?k.message:"Search failed")}finally{w(!1)}},children:[e.jsx("label",{htmlFor:"history-question",children:"What do you want to find?"}),e.jsx("textarea",{id:"history-question",rows:3,maxLength:2e3,value:i,onChange:r=>c(r.target.value),placeholder:"Why did we change that approach?"}),e.jsxs("div",{className:"history-actions",children:[e.jsx("button",{className:"btn btn-primary",disabled:m||!i.trim(),children:m?"Searching…":"Search history"}),m&&e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>{var r;return(r=o.current)==null?void 0:r.abort()},children:"Cancel search"})]}),e.jsx(We,{enabled:m,waiting:!0})]}),g&&e.jsx("p",{className:"alert error",role:"alert",children:g}),n&&e.jsxs("section",{"aria-label":"History search results",children:[e.jsx("p",{className:"small muted",children:"Meaning + keyword matches"}),!n.results.length&&e.jsx("p",{children:"No matches in this search. That does not prove the event never happened; try different wording or a wider scope."}),n.results.map(r=>e.jsxs("article",{className:"card history-result",children:[e.jsx("h2",{children:e.jsx("a",{href:`/history/${r.ref}`,target:"_blank",rel:"noopener noreferrer",children:r.title})}),e.jsx(ns,{record:r}),e.jsx("pre",{className:"history-excerpt",children:r.text}),e.jsx("a",{href:`/history/${r.ref}`,target:"_blank",rel:"noopener noreferrer",children:"Read source and surrounding context"})]},r.ref)),e.jsx("p",{className:"small muted",children:n.limitations})]})]})]})}const vs=s=>new Date(s).toLocaleString(),Gt={pi:"pi v3 JSONL",codex:"Rollout JSONL",claude:"Transcript JSONL"};function Kt({open:s}){const[t,n]=d.useState(!1),[a,i]=d.useState(null),[c,g]=d.useState(!0),[p,m]=d.useState(!1),[w,o]=d.useState(""),[r,u]=d.useState(""),[k,v]=d.useState(null),f=d.useRef(!0),E=d.useRef(!1);d.useEffect(()=>(f.current=!0,()=>{f.current=!1}),[]),d.useEffect(()=>{if(!s||!t||p)return;let h=!0;const N=async()=>{try{const[x,C]=await Promise.all([ms(),ts()]);h&&!E.current&&(i(x),g(C.busy||C.active_call),u(""))}catch(x){h&&!E.current&&u(x instanceof Error?x.message:"Could not read session sources")}};N();const b=setInterval(()=>void N(),4e3);return()=>{h=!1,clearInterval(b)}},[s,t,p]);const j=async(h,N)=>{if(!a||c||r||E.current)return;const b=a;E.current=!0,m(!0),o(""),N&&i(N);try{const x=await h();f.current&&i(x)}catch(x){f.current&&(N&&i(b),o(x instanceof Error?x.message:"Could not update session sources"))}finally{E.current=!1,f.current&&m(!1)}},_=!a||c||p||!!r;return e.jsxs("details",{className:"source-settings",onToggle:h=>n(h.currentTarget.open),children:[e.jsx("summary",{children:"Agents & sessions"}),e.jsx("p",{className:"small muted",children:"Directory presence is not an installation check. Opening this panel reads recorded metadata; it does not scan transcripts, index embeddings or call a model."}),e.jsx("p",{className:"small muted",children:"Enable each history source before importing it. Codex and Claude history start off; existing pi choices are preserved. Enabling a source allows its logs into the next scan, sync or enabled background batch. Automatic local indexing is on by default for new installations; turn it off separately if you prefer manual indexing. It does not create syncs or generate briefings. New sessions from enabled agents are selected by default. Summarization still runs through pi, regardless of which agent produced the history."}),!a&&e.jsx("p",{className:"small muted",role:"status",children:"Loading session inventory…"}),e.jsxs("button",{type:"button",className:"btn btn-secondary",disabled:_||!(a!=null&&a.agents.some(h=>h.enabled)),onClick:()=>void j(async()=>{const h=await mt();return f.current&&v(h),ms()}),children:[e.jsx(st,{size:15,"aria-hidden":"true"}),"Scan enabled agents"]}),c&&a&&e.jsx("p",{className:"small muted",children:"Source changes are paused while a call or sync preparation is active."}),p&&e.jsx("p",{className:"small muted",role:"status",children:"Updating session sources…"}),a==null?void 0:a.agents.map(h=>{const N=a.sessions.filter(b=>b.agent===h.id);return e.jsxs("section",{className:"agent-source","aria-labelledby":`${h.id}-source-title`,children:[e.jsxs("div",{className:"section-heading",children:[e.jsx("h3",{id:`${h.id}-source-title`,children:h.name}),e.jsx("span",{className:"status",children:Gt[h.id]})]}),e.jsxs("label",{className:"index-toggle",children:[e.jsx("input",{type:"checkbox",role:"switch","aria-label":`Enable ${h.name} history`,checked:h.enabled,disabled:_,onChange:b=>{const x=b.target.checked;j(()=>gt(h.id,x),{...a,agents:a.agents.map(C=>C.id===h.id?{...C,enabled:x}:C)})}}),e.jsxs("span",{children:[e.jsxs("strong",{children:["Include ",h.name," history"]}),e.jsx("span",{className:"small muted",children:h.enabled?"Enabled for scanning and future syncs":"Off — transcripts are not scanned or indexed"})]})]}),h.roots.map(b=>e.jsxs("div",{children:[e.jsx("p",{className:"small muted",children:b.status==="present"?"Directory found":b.status==="missing"?"Directory not found":"Directory unavailable"}),e.jsx("code",{className:"source-path",children:b.path})]},b.path)),e.jsxs("p",{className:"small muted",children:[N.length," recorded sessions · ",N.filter(b=>b.included).length," selected · ",N.filter(b=>b.missing).length," unavailable at last scan"]}),!N.length&&e.jsxs("p",{className:"small muted",children:["No ",h.name," sessions recorded yet.",h.enabled?" Scan enabled agents to discover them.":" Enable this source before scanning."]}),e.jsx("div",{className:"session-list","aria-label":`Discovered ${h.name} sessions`,children:N.map(b=>e.jsxs("label",{className:"session-source",children:[e.jsx("input",{type:"checkbox",checked:!!b.included,disabled:_||!h.enabled||!!b.missing,"aria-label":`Include ${b.name||"session"} (${b.id})`,onChange:x=>{const C=x.target.checked;j(()=>ft(b.id,C),{...a,sessions:a.sessions.map(O=>O.id===b.id?{...O,included:Number(C)}:O)})}}),e.jsxs("span",{children:[e.jsx("strong",{children:b.name||b.cwd.split(/[\\/]/).filter(Boolean).pop()||b.id}),e.jsx("span",{className:"source-cwd",title:b.cwd,children:b.cwd||"Workspace unavailable"}),e.jsxs("span",{className:"small",children:[b.included?"Selected":"Excluded"," · ",b.pending," unreviewed ",b.pending===1?"entry":"entries",b.missing?" · unavailable at last scan":""]}),e.jsxs("span",{className:"source-session-meta small muted",children:["Session ",b.external_id||b.id," · Last recorded change: ",vs(b.modified_at)]}),e.jsx("code",{className:"source-path",children:b.path})]})]},b.id))})]},h.id)}),a&&e.jsxs("p",{className:"small muted",children:[a.history_initialized&&a.history_since?`Existing history baseline: ${vs(a.history_since)}. It is preserved.`:"All indexed history is eligible; there is no rolling time window."," Source choices do not edit existing frozen syncs or mark evidence reviewed. Scanning does not generate summaries or start a call. Keep the original logs: evidence is verified from them, not copied into Draken."]}),k&&e.jsxs("p",{className:"small muted",role:"status",children:["Last requested scan: ",k.files," candidate log files checked · ",k.added," new records recorded."]}),k&&k.warnings.length>0&&e.jsx("ul",{className:"source-warnings small","aria-label":"Scan warnings",children:k.warnings.map((h,N)=>e.jsx("li",{children:h},N))}),(w||r)&&e.jsx("p",{className:"small",role:"alert",children:w||r})]})}const Ke=s=>s===null?"Unavailable":s>0&&s<1e-6?"<$0.000001":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:s<.01?6:2}).format(s),ue=s=>s.slice(0,16).replace("T"," "),se=s=>s.toLocaleString();function Wt(s,t){const n=(s||1)/4,a=10**Math.floor(Math.log10(n)),i=Math.max(t?1:Number.MIN_VALUE,[1,2,5,10].find(w=>w*a>=n)*a),c=Math.max(1,Math.ceil((s||1)/i)),g=c*i,p=Math.max(2,-Math.floor(Math.log10(i))),m=w=>t?se(w):w===0?"$0":i<1e-6||g>=1e9?`$${Number(w.toPrecision(3)).toExponential()}`:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:Math.min(6,p)}).format(w);return{maximum:g,ticks:Array.from({length:c+1},(w,o)=>({fraction:o/c,label:m(o*i)}))}}function Qt({active:s}){const[t,n]=d.useState("7d"),[a,i]=d.useState("1h"),[c,g]=d.useState("cost"),[p,m]=d.useState(null),[w,o]=d.useState("");if(d.useEffect(()=>{if(!s)return;const h=new AbortController;let N=!1;m(null),o("");const b=async()=>{if(!N){N=!0;try{const C=await ct(t,a,h.signal);h.signal.aborted||(m(C),o(""))}catch(C){h.signal.aborted||(m(null),o(C instanceof Error?C.message:"Could not load preparation usage"))}finally{N=!1}}};b();const x=setInterval(()=>void b(),15e3);return()=>{h.abort(),clearInterval(x)}},[s,t,a]),!s)return null;const r=(p==null?void 0:p.range)===t&&p.bucket===a?p:null,u=r==null?void 0:r.totals,k=(r==null?void 0:r.buckets.map(h=>c==="cost"?h.cost.usd||0:h.completed_batches))||[],v=Math.max(0,...k),f=Wt(v,c==="batches"),E=c==="cost"&&(u==null?void 0:u.cost.usd)===null,j=E?[]:f.ticks,_=c==="cost"?"USD":"Batches";return e.jsxs("section",{className:"preparation-usage","aria-labelledby":"preparation-usage-title",children:[e.jsx("h3",{id:"preparation-usage-title",children:"Preparation usage"}),e.jsx("p",{className:"small muted",children:"Preparation history, including past automatic work, background summary cache requests, retries and discarded batches. Local indexing makes no provider model calls. Estimates use recorded model usage and prices—not your bill, subscription charge or remaining quota."}),e.jsxs("div",{className:"usage-controls",children:[e.jsxs("label",{children:["Look back",e.jsxs("select",{value:t,onChange:h=>n(h.target.value),children:[e.jsx("option",{value:"6h",children:"6 hours"}),e.jsx("option",{value:"1d",children:"1 day"}),e.jsx("option",{value:"7d",children:"7 days"}),e.jsx("option",{value:"14d",children:"14 days"})]})]}),e.jsxs("label",{children:["Bucket size",e.jsxs("select",{value:a,onChange:h=>i(h.target.value),children:[e.jsx("option",{value:"1h",children:"1 hour"}),e.jsx("option",{value:"6h",children:"6 hours"}),e.jsx("option",{value:"24h",children:"24 hours"})]})]}),e.jsxs("label",{children:["Chart",e.jsxs("select",{value:c,onChange:h=>g(h.target.value),children:[e.jsx("option",{value:"cost",children:"Estimated cost"}),e.jsx("option",{value:"batches",children:"Completed batches"})]})]})]}),w?e.jsxs("p",{role:"alert",children:["Usage unavailable: ",w]}):r?u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"usage-totals",children:[e.jsxs("div",{children:[e.jsx("span",{className:"small",children:u.incomplete_pricing?"Known cost subtotal":"Est. preparation cost"}),e.jsx("strong",{children:Ke(u.cost.usd)}),e.jsx("span",{className:"small muted",children:u.incomplete_pricing?`${se(u.incomplete_pricing)} ${u.incomplete_pricing===1?"request has":"requests have"} incomplete pricing`:"USD · recorded API-price estimate"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"small",children:"Completed batches"}),e.jsx("strong",{children:se(u.completed_batches)}),e.jsxs("span",{className:"small muted",children:[se(u.entries)," entries across these batches"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"small",children:"Model requests"}),e.jsx("strong",{children:se(u.requests)}),e.jsxs("span",{className:"small muted",children:[se(r.active_attempts)," preparation ",r.active_attempts===1?"attempt":"attempts"," active now"]})]})]}),e.jsxs("p",{className:"small muted",children:[ue(r.from)," – ",ue(r.to)," UTC. Refreshes every 15 seconds while Settings is open."]}),!u.requests&&!u.completed_batches&&!u.failed_attempts?e.jsx("p",{children:"No preparation recorded in this period."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"usage-chart-heading small",children:[e.jsxs("strong",{children:[c==="cost"?"Estimated cost":"Completed batches"," per ",a]}),e.jsx("span",{children:c==="cost"?`Peak known: ${Ke(u.cost.usd===null?null:v)}`:`Peak: ${se(v)}`})]}),e.jsxs("div",{className:"usage-chart-frame",children:[e.jsx("span",{className:"usage-axis-unit small muted","aria-hidden":"true",children:_}),e.jsx("div",{className:"usage-y-axis small muted","aria-hidden":"true",style:{width:`${Math.max(7,...j.map(h=>h.label.length))}ch`},children:j.map(h=>e.jsx("span",{style:{top:`${(119-h.fraction*112)/120*100}%`},children:h.label},h.fraction))}),e.jsxs("svg",{className:"usage-chart",viewBox:"0 0 720 120",preserveAspectRatio:"none",role:"img","aria-label":`${c==="cost"?"Estimated preparation cost":"Completed batches"} by ${a} bucket. Y-axis: ${_}${E?", pricing unavailable":`, ${j[0].label} to ${j[j.length-1].label}`}. Exact values in bucket details below.`,children:[j.map(h=>e.jsx("line",{className:"usage-gridline",x1:"0",y1:119-h.fraction*112,x2:"720",y2:119-h.fraction*112},h.fraction)),r.buckets.map((h,N)=>{const b=c==="cost"&&!h.cost.complete,x=Math.max(k[N]>0?2:b?4:0,k[N]/f.maximum*112);return e.jsx("rect",{x:N/k.length*720,y:119-x,width:Math.max(.5,720/k.length-1),height:x,className:b?"usage-incomplete":void 0,children:e.jsxs("title",{children:[ue(h.from)," – ",ue(h.to)," UTC: ",c==="cost"?Ke(h.cost.usd)+(b?" (incomplete pricing)":""):`${h.completed_batches} batches`,"; ",h.requests," requests"]})},h.from)}),e.jsx("line",{x1:"0",y1:"7",x2:"0",y2:"119"}),e.jsx("line",{x1:"0",y1:"119",x2:"720",y2:"119"})]}),e.jsxs("div",{className:"usage-chart-axis small muted",children:[e.jsx("span",{children:ue(r.from).slice(5)}),e.jsx("span",{children:"UTC"}),e.jsx("span",{children:ue(r.to).slice(5)})]})]}),c==="cost"&&u.incomplete_pricing>0&&e.jsxs("p",{className:"small muted",children:[E?"No priced amounts are available. ":"","Gray bars have incomplete pricing. Their heights show only the known subtotal; short baseline markers indicate unpriced requests, not a measured cost. An unpriced request is not free."]}),e.jsxs("details",{className:"usage-details",children:[e.jsx("summary",{children:"Bucket details"}),e.jsx("div",{className:"usage-table-wrap",tabIndex:0,role:"region","aria-label":"Usage bucket details",children:e.jsxs("table",{children:[e.jsx("caption",{className:"sr-only",children:"Preparation usage by UTC time bucket, newest first"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"UTC interval"}),e.jsx("th",{scope:"col",children:"Batches"}),e.jsx("th",{scope:"col",children:"Requests"}),e.jsx("th",{scope:"col",children:"Est. cost"}),e.jsx("th",{scope:"col",children:"Incomplete pricing"})]})}),e.jsx("tbody",{children:[...r.buckets].reverse().map(h=>e.jsxs("tr",{children:[e.jsxs("th",{scope:"row",children:[ue(h.from),e.jsx("br",{}),"to ",ue(h.to)]}),e.jsx("td",{children:se(h.completed_batches)}),e.jsx("td",{children:se(h.requests)}),e.jsxs("td",{children:[Ke(h.cost.usd),!h.cost.complete&&" (partial)"]}),e.jsx("td",{children:se(h.incomplete_pricing)})]},h.from))})]})})]})]}),e.jsxs("p",{className:"small muted",children:[se(u.failed_attempts)," failed or stopped ",u.failed_attempts===1?"attempt":"attempts"," in this period. ",se(u.approximate_timing)," ",u.approximate_timing===1?"request uses":"requests use"," older, approximate timing (the preparation run’s start); newer requests use their recorded start time. Buckets align to UTC hours, with partial first and last buckets."]})]}):e.jsx("p",{role:"status",children:"Loading preparation usage…"}),e.jsx("p",{className:"small muted",children:"A completed batch is a snapshot’s first successful briefing preparation. Background summary caching, retries and rebuilds add costs, not extra batches. Batch counts use completion time; request costs use start time. Counts do not mean reviewed work or current call readiness. Chat, voice and post-conversation recaps are excluded. Local search indexing uses no model API; machine and network costs are not measured."})]})}function Jt(){const[s,t]=d.useState(!1),[n,a]=d.useState(null),[i,c]=d.useState(!1),[g,p]=d.useState(""),[m,w]=d.useState(""),o=d.useRef(null);return d.useEffect(()=>{var r,u,k;s&&!((r=o.current)!=null&&r.open)?(u=o.current)==null||u.showModal():s||(k=o.current)==null||k.close()},[s]),d.useEffect(()=>{if(!s||i)return;let r=!0;const u=async()=>{try{const v=await Es();r&&(a(v),w(""))}catch(v){r&&w(v instanceof Error?v.message:"Could not read settings")}};u();const k=setInterval(()=>void u(),4e3);return()=>{r=!1,clearInterval(k)}},[s,i]),e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:"btn btn-secondary header-settings","aria-haspopup":"dialog",onClick:()=>t(!0),children:[e.jsx(tt,{size:16,"aria-hidden":"true"}),"Settings"]}),e.jsxs("dialog",{ref:o,className:"settings-dialog","aria-labelledby":"settings-title",onCancel:r=>{r.preventDefault(),t(!1)},onClose:r=>{r.currentTarget.open||t(!1)},children:[e.jsxs("div",{className:"section-heading",children:[e.jsx("h2",{id:"settings-title",children:"Settings"}),e.jsx("button",{type:"button",className:"icon-button","aria-label":"Close settings",autoFocus:!0,onClick:()=>t(!1),children:e.jsx(es,{size:18,"aria-hidden":"true"})})]}),e.jsx(Qt,{active:s}),e.jsxs("label",{className:"index-toggle",children:[e.jsx("input",{type:"checkbox",role:"switch",checked:(n==null?void 0:n.enabled)||!1,disabled:!n||i,onChange:async r=>{const u=r.target.checked,k=n;c(!0),p(""),a(v=>v&&{...v,enabled:u});try{a(await us(u))}catch(v){a(k),p(v instanceof Error?v.message:"Could not save settings")}finally{c(!1)}}}),e.jsxs("span",{children:[e.jsx("strong",{children:"Automatically index history"}),e.jsx("span",{className:"small muted",children:"Accumulate searchable history locally. This option alone makes no provider requests."})]})]}),e.jsx("p",{className:"small muted",children:"On by default for new installations. Existing installations keep their saved indexing choice, including off. While the server runs, check once a minute and index batches at 64 source changes. Active conversations receive even small history updates on the next idle check, without waiting for 64 changes. Otherwise smaller tails wait for explicit preparation or a full batch. Only your Sync with Draken or Chat instead action creates a snapshot and starts its briefing. Replies, voice turns and foreground work take priority; updates can run between turns."}),e.jsx("p",{className:"small muted",children:"Indexing makes no provider model calls. Local embeddings use CPU, memory and disk; first use may download about 136 MB of pinned search model files. Disabling cancels automatic indexing and summary preparation, keeping completed embeddings and summaries. Local failures back off for at least five minutes; foreground preemption waits at least one minute. Existing conversations, notes and frozen snapshots are not rewritten. Nothing is marked reviewed and no microphone or call starts automatically. Agent and session exclusions remain respected."}),i&&e.jsx("p",{role:"status",children:"Saving…"}),(g||m)&&e.jsx("p",{className:"small",role:"alert",children:g||m}),s&&n&&e.jsx(Ms,{settings:n}),(n==null?void 0:n.enabled)&&n.phase==="error"&&e.jsx("button",{type:"button",className:"btn btn-secondary",disabled:i,onClick:async()=>{c(!0),p("");try{a(await us(!0))}catch(r){p(r instanceof Error?r.message:"Could not retry indexing")}finally{c(!1)}},children:"Retry automatic indexing"}),e.jsx(Is,{active:s,indexing:(n==null?void 0:n.enabled)||!1,controls:!0,disabled:i,onBusyChange:c}),e.jsx(Kt,{open:s}),e.jsx(Ts,{active:s,always:!0})]})]})}function Zt(){const{isAuthenticated:s,isLoading:t,authEnabled:n,username:a,logout:i}=Cs(),[c,g]=d.useState(window.location.pathname),[p,m]=d.useState(null),w=d.useRef(null),o=d.useRef(c),r=d.useCallback(f=>{w.current=f},[]),u=d.useCallback((f,E=!1)=>{w.current&&!w.current()||(window.history.pushState(null,"",f),o.current=f,g(f),m(E?Number(f.split("/").pop()):null),window.scrollTo(0,0))},[]);if(d.useEffect(()=>{const f=()=>{if(w.current&&!w.current()){window.history.pushState(null,"",o.current);return}o.current=window.location.pathname,g(o.current),m(null)};return window.addEventListener("popstate",f),()=>window.removeEventListener("popstate",f)},[]),t)return e.jsxs("div",{className:"app-loading",children:[e.jsx("span",{className:"spinner"}),"Opening Draken…"]});if(!s)return e.jsx(it,{});const k=/^\/syncs\/([1-9]\d*)(\/chat)?\/?$/.exec(c),v=k?Number(k[1]):null;return e.jsxs("div",{className:"app-container",children:[e.jsxs("header",{className:"header",children:[e.jsxs("a",{className:"brand",href:"/",onClick:f=>ge(f,u,"/"),"aria-label":"Draken sync history",children:[e.jsx("img",{src:"/favicon.png",alt:""}),e.jsxs("div",{children:[e.jsx("strong",{children:"Draken"}),e.jsx("span",{children:"Session sync"})]})]}),e.jsxs("div",{className:"header-right",children:[e.jsx("a",{href:"/history",onClick:f=>ge(f,u,"/history"),children:"Search history"}),e.jsx(Jt,{}),n&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"muted small",children:a}),e.jsx("button",{className:"icon-button",onClick:()=>{(!w.current||w.current())&&i()},"aria-label":"Sign out",children:e.jsx(Js,{size:18})})]})]})]}),v&&Number.isSafeInteger(v)?e.jsx(zt,{id:v,chat:!!(k!=null&&k[2]),callIntent:p===v,consumeIntent:()=>m(null),navigate:u,setGuard:r},v):/^\/history(?:\/H[a-f0-9]{24})?\/?$/.test(c)?e.jsx(Yt,{navigate:u,reference:c.split("/")[2]},c):c==="/"?e.jsx(Vt,{navigate:u}):e.jsxs("main",{className:"sync-home",children:[e.jsx("h1",{children:"Page not found"}),e.jsx("a",{href:"/",onClick:f=>ge(f,u,"/"),children:"All syncs"})]})]})}function Xt(){return e.jsx(rt,{children:e.jsx(Zt,{})})}Ls.createRoot(document.getElementById("root")).render(e.jsx(Os.StrictMode,{children:e.jsx(Xt,{})}));
package/public/index.html CHANGED
@@ -6,7 +6,7 @@
6
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
7
  <meta name="description" content="A local-first engineering sync across your pi sessions." />
8
8
  <title>Draken — Session Sync</title>
9
- <script type="module" crossorigin src="/assets/index-DXPfCm7z.js"></script>
9
+ <script type="module" crossorigin src="/assets/index-sHcfjDUD.js"></script>
10
10
  <link rel="modulepreload" crossorigin href="/assets/index-B13h0MjX.js">
11
11
  <link rel="stylesheet" crossorigin href="/assets/index-D79D-rxm.css">
12
12
  </head>