draken 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/MEMORY.md +36 -5
- package/README.md +14 -12
- package/SETUP.md +23 -3
- package/TRAY.md +2 -2
- package/VOICE.md +1 -1
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +24 -0
- package/dist/db/schema.js.map +1 -1
- package/dist/routes/sync.d.ts.map +1 -1
- package/dist/routes/sync.js +7 -0
- package/dist/routes/sync.js.map +1 -1
- package/dist/sync/background.d.ts +4 -2
- package/dist/sync/background.d.ts.map +1 -1
- package/dist/sync/background.js +46 -17
- package/dist/sync/background.js.map +1 -1
- package/dist/sync/store.d.ts +4 -1
- package/dist/sync/store.d.ts.map +1 -1
- package/dist/sync/store.js +9 -0
- package/dist/sync/store.js.map +1 -1
- package/dist/sync/summary-preparation.d.ts +14 -0
- package/dist/sync/summary-preparation.d.ts.map +1 -0
- package/dist/sync/summary-preparation.js +205 -0
- package/dist/sync/summary-preparation.js.map +1 -0
- package/dist/sync/tree.d.ts +17 -1
- package/dist/sync/tree.d.ts.map +1 -1
- package/dist/sync/tree.js +94 -29
- package/dist/sync/tree.js.map +1 -1
- package/dist/sync/usage.d.ts +3 -1
- package/dist/sync/usage.d.ts.map +1 -1
- package/dist/sync/usage.js +24 -6
- package/dist/sync/usage.js.map +1 -1
- package/dist/types.d.ts +9 -1
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/public/assets/index-5bTQNQYG.js +131 -0
- package/public/index.html +1 -1
- package/public/assets/index-DXPfCm7z.js +0 -131
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
var Ts=Object.defineProperty;var rs=t=>{throw TypeError(t)};var _s=(t,s,n)=>s in t?Ts(t,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[s]=n;var _=(t,s,n)=>_s(t,typeof s!="symbol"?s+"":s,n),is=(t,s,n)=>s.has(t)||rs("Cannot "+n);var j=(t,s,n)=>(is(t,s,"read from private field"),n?n.call(t):s.get(t)),U=(t,s,n)=>s.has(t)?rs("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(t):s.set(t,n),D=(t,s,n,a)=>(is(t,s,"write to private field"),a?a.call(t,n):s.set(t,n),n);import{r as c,j as e,P as Is,R as Ms,a as qs}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 Ds=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),fs=(...t)=>t.filter((s,n,a)=>!!s&&s.trim()!==""&&a.indexOf(s)===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 Rs={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 Ls=c.forwardRef(({color:t="currentColor",size:s=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:i="",children:o,iconNode:r,...m},u)=>c.createElement("svg",{ref:u,...Rs,width:s,height:s,stroke:t,strokeWidth:a?Number(n)*24/Number(s):n,className:fs("lucide",i),...m},[...r.map(([N,l])=>c.createElement(N,l)),...Array.isArray(o)?o:[o]]));/**
|
|
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 q=(t,s)=>{const n=c.forwardRef(({className:a,...i},o)=>c.createElement(Ls,{ref:o,iconNode:s,className:fs(`lucide-${Ds(t)}`,a),...i}));return n.displayName=`${t}`,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 $s=q("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 os=q("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 xs=q("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 Os=q("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 Us=q("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 Fs=q("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 zs=q("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 Hs=q("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 Vs=q("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 Bs=q("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 Ys=q("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 Gs=q("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 ys=q("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 Ks=q("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 Ws=q("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 Qs=q("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 We=q("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 Js=q("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 Zs=q("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 vs=q("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 Xs=q("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 Qe=q("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),ss="draken_token",ts="draken_username";function js(){return{token:localStorage.getItem(ss),username:localStorage.getItem(ts)}}function et(t,s){localStorage.setItem(ss,t),localStorage.setItem(ts,s)}function Je(){localStorage.removeItem(ss),localStorage.removeItem(ts)}function as(){const{token:t}=js();return t?{Authorization:`Bearer ${t}`}:{}}const bs=c.createContext(null),Ee={isAuthenticated:!1,isLoading:!1,authEnabled:!0,username:null};function st({children:t}){const[s,n]=c.useState({...Ee,isLoading:!0});c.useEffect(()=>{let o=!0;const r=u=>{o&&n(u)};return(async()=>{try{if(!(await(await fetch("/api/auth/status")).json()).enabled){r({isAuthenticated:!0,isLoading:!1,authEnabled:!1,username:null});return}const{token:l,username:p}=js();if(!l){r(Ee);return}(await fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${l}`}})).ok?r({isAuthenticated:!0,isLoading:!1,authEnabled:!0,username:p}):(o&&Je(),r(Ee))}catch(u){console.error("Auth check failed:",u),r(Ee)}})(),()=>{o=!1}},[]);const a=async(o,r)=>{const m=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:o,password:r})}),u=await m.json();if(!m.ok)throw new Error(u.error||"Login failed");et(u.token,u.username),n({isAuthenticated:!0,isLoading:!1,authEnabled:!0,username:u.username})},i=()=>{Je(),n(Ee)};return e.jsx(bs.Provider,{value:{...s,login:a,logout:i},children:t})}function ws(){const t=c.useContext(bs);if(!t)throw new Error("useAuth must be used within an AuthProvider");return t}function tt(){const{login:t}=ws(),[s,n]=c.useState(""),[a,i]=c.useState(""),[o,r]=c.useState(null),[m,u]=c.useState(!1),N=async l=>{l.preventDefault(),r(null),u(!0);try{await t(s,a)}catch(p){r(p instanceof Error?p.message:"Login failed")}finally{u(!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:N,className:"login-form",children:[o&&e.jsxs("div",{className:"login-error",role:"alert",children:[e.jsx(Fs,{size:16}),o]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"username",children:"Username"}),e.jsxs("div",{className:"input-with-icon",children:[e.jsx(Xs,{size:18,className:"input-icon"}),e.jsx("input",{id:"username",type:"text",className:"input",placeholder:"Enter username",value:s,onChange:l=>n(l.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(Bs,{size:18,className:"input-icon"}),e.jsx("input",{id:"password",type:"password",className:"input",placeholder:"Enter password",value:a,onChange:l=>i(l.target.value),autoComplete:"current-password"})]})]}),e.jsx("button",{type:"submit",className:"btn btn-primary btn-lg login-btn",disabled:m||!s||!a,children:m?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"spinner spinner-sm"})," Signing in..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ys,{size:18})," Sign In"]})})]})]})})}async function T(t,s="GET",n,a){const i=await fetch(`/api${t}`,{method:s,signal:a,headers:{"Content-Type":"application/json",...as()},body:n===void 0?void 0:JSON.stringify(n)});if(i.status===401)throw Je(),window.location.reload(),new Error("Authentication required");if(i.status===204)return;const o=await i.json();if(!i.ok)throw new Error(o.error||`Request failed (${i.status})`);return o}const at=(t=!1)=>T(`/setup${t?"?refresh=1":""}`),nt=(t,s,n)=>T(`/settings/preparation-usage?range=${t}&bucket=${s}`,"GET",void 0,n),ks=()=>T("/settings/auto-index"),cs=t=>T("/settings/auto-index","PATCH",{enabled:t}),rt=()=>T("/settings/auto-summary"),it=t=>T("/settings/auto-summary","PATCH",{enabled:t}),Ze=t=>T(`/home${t?`?before=${t}`:""}`),ot=t=>T("/syncs/start-call","POST",{request_id:t}),ct=t=>T("/syncs/start-chat","POST",{request_id:t}),lt=(t,s,n)=>T(`/syncs/${t}/chat/messages`,"POST",{message:s,request_id:n}),ls=t=>T(`/syncs/${t}/recap`,"POST"),ds=()=>T("/overview"),dt=()=>T("/scan","POST"),ht=(t,s)=>T(`/agents/${encodeURIComponent(t)}`,"PATCH",{enabled:s}),ut=(t,s)=>T(`/sessions/${encodeURIComponent(t)}`,"PATCH",{included:s}),Ye=t=>T(`/syncs/${t}`),pt=t=>T(`/syncs/${t}/progress`),hs=(t,s)=>T(`/syncs/${t}/call-readiness`,"GET",void 0,s),mt=(t,s)=>T(`/syncs/${t}/chat-readiness`,"GET",void 0,s),gt=t=>T(`/syncs/${t}/prepare-call`,"POST"),ft=(t,s)=>T(`/syncs/${t}/tree/${s}`),xt=t=>T(`/syncs/${t}/expand`,"POST"),yt=t=>T(`/syncs/${t}/cancel`,"POST"),vt=t=>T(`/syncs/${t}/briefing`,"POST"),jt=(t,s)=>T(`/syncs/${t}/messages`,"POST",{message:s}),bt=t=>T("/memory/progress","GET",void 0,t),wt=(t,s)=>T("/memory/search","POST",t,s),kt=(t,s=0,n)=>T(`/memory/records/${encodeURIComponent(t)}?offset=${s}`,"GET",void 0,n),Ae=(t,s,n)=>T(`/syncs/${t}/notes`,"PATCH",{decisions:s,carry_forward:n}),Nt=(t,s,n)=>T(`/syncs/${t}/complete`,"POST",{decisions:s,carry_forward:n,reviewed:!0}),St=t=>T(`/syncs/${t}/discard`,"POST"),Pe=25;function us({items:t,title:s}){const[n,a]=c.useState(0),[i,o]=c.useState(""),[r,m]=c.useState("");if(c.useEffect(()=>{const h=k=>{const x=k.detail,b=t.findIndex(g=>g.ref===x);b<0||(o(""),a(Math.floor(b/Pe)),m(x))};return window.addEventListener("draken:evidence",h),()=>window.removeEventListener("draken:evidence",h)},[t]),c.useEffect(()=>{if(!r)return;const h=document.getElementById(`evidence-${r}`);h&&(h.open=!0,h.scrollIntoView({behavior:"smooth",block:"center"}),m(""))},[r,n,i]),!t.length)return null;const u=i.toLocaleLowerCase(),N=u?t.filter(h=>`${h.ref} ${h.session_name} ${h.cwd} ${h.text}`.toLocaleLowerCase().includes(u)):t,l=Math.max(1,Math.ceil(N.length/Pe)),p=Math.min(n,l-1);return e.jsxs("section",{className:"evidence-section",children:[e.jsxs("h3",{children:[s," ",e.jsx("span",{className:"count",children:t.length})]}),t.length>Pe&&e.jsxs("div",{className:"evidence-controls",children:[e.jsx("input",{className:"input","aria-label":`Search ${s}`,placeholder:"Find a topic, workspace, or evidence ID…",value:i,onChange:h=>{o(h.target.value),a(0)}}),e.jsxs("div",{className:"pagination",children:[e.jsx("button",{className:"btn btn-secondary",disabled:p===0,onClick:()=>a(p-1),children:"Previous"}),e.jsxs("span",{children:[p+1," / ",l," · ",N.length," entries"]}),e.jsx("button",{className:"btn btn-secondary",disabled:p>=l-1,onClick:()=>a(p+1),children:"Next"})]})]}),e.jsx("div",{className:"evidence-list",children:N.slice(p*Pe,(p+1)*Pe).map(h=>e.jsxs("details",{className:"evidence",id:`evidence-${h.ref}`,children:[e.jsxs("summary",{children:[e.jsx("span",{className:"reference",children:h.ref}),e.jsxs("span",{className:"evidence-title",children:[e.jsxs("strong",{children:[h.agent&&h.agent!=="pi"&&`${h.agent} · `,h.session_name||h.cwd.split("/").filter(Boolean).pop()||h.cwd]}),e.jsx("span",{children:h.unavailable?"Original session source unavailable":h.text.slice(0,130)})]}),e.jsx("span",{className:"role-label",children:h.role})]}),e.jsxs("div",{className:"evidence-body",children:[e.jsxs("dl",{children:[e.jsx("dt",{children:"Workspace"}),e.jsx("dd",{children:h.cwd}),e.jsx("dt",{children:"Session"}),e.jsx("dd",{children:h.session_id}),e.jsx("dt",{children:"Source"}),e.jsx("dd",{children:h.source_path}),e.jsx("dt",{children:"Entry"}),e.jsxs("dd",{children:[h.entry_id," · ",h.timestamp]})]}),h.unavailable?e.jsx("p",{className:"alert warning",role:"status",children:h.unavailable}):e.jsx("pre",{children:h.text})]})]},h.ref))})]})}function _e({text:t,evidence:s}){const n=new Set(s.map(a=>a.ref));return e.jsx("div",{className:"prose",children:t.split(/(\[(?:[EC]\d+|H[a-f0-9]{24})\])/g).map((a,i)=>{const o=a.slice(1,-1);return/^H[a-f0-9]{24}$/.test(o)?e.jsxs("a",{className:"citation",href:`/history/${o}`,target:"_blank",rel:"noopener noreferrer","aria-label":`Inspect historical source ${o}`,children:["[history ",o.slice(-6),"]"]},i):!/^\[(E|C)\d+\]$/.test(a)||!n.has(o)?e.jsx("span",{children:a},i):e.jsx("button",{className:"citation",onClick:()=>window.dispatchEvent(new CustomEvent("draken:evidence",{detail:o})),"aria-label":`Inspect evidence ${o}`,children:a},i)})})}function Ct({syncId:t,progress:s,evidence:n,onCancel:a,onResume:i,resumeEnabled:o}){var f;const[r,m]=c.useState(new Set),[u,N]=c.useState(null),[l,p]=c.useState(""),[h,k]=c.useState(!1),x=s.run;if(c.useEffect(()=>{N(null),m(new Set)},[x==null?void 0:x.id]),!x)return null;const b=!s.busy&&["failed","cancelled","interrupted"].includes(x.status),g=new Map(s.nodes.map(v=>[v.key,v])),A=new Set(s.nodes.flatMap(v=>v.children)),C=s.nodes.filter(v=>!A.has(v.key)),d=async v=>{k(!0),p("");try{N(await ft(t,v.key))}catch(E){p(E instanceof Error?E.message:"Could not load summary")}finally{k(!1)}},w=(v,E=new Set)=>{if(E.has(v.key))return null;const F=new Set([...E,v.key]),ee=r.has(v.key);return e.jsxs("li",{children:[e.jsxs("div",{className:"tree-node",children:[e.jsx("button",{className:"tree-toggle","aria-label":`Expand ${v.label}`,disabled:!v.children.length,onClick:()=>m(I=>{const R=new Set(I);return R.has(v.key)?R.delete(v.key):R.add(v.key),R}),children:v.children.length?ee?"▾":"▸":"·"}),e.jsxs("button",{className:"tree-label",disabled:!["done","cached"].includes(v.status)||h,onClick:()=>void d(v),title:v.error||v.label,children:[e.jsx("span",{className:"role-label",children:v.kind})," ",v.label]}),e.jsx("span",{className:`status ${v.status}`,children:v.status})]}),ee&&e.jsx("ul",{children:v.children.map(I=>g.has(I)?w(g.get(I),F):null)})]},v.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 ${x.status}`,children:x.status})]}),e.jsx("p",{className:"small muted",children:"Complete source batches → compact reconciliation → final verdict"}),e.jsx("progress",{max:Math.max(1,x.total_entries),value:x.processed_entries,"aria-label":"Evidence compression progress"}),e.jsxs("div",{className:"tree-stats",children:[e.jsxs("span",{children:[x.processed_entries," / ",x.total_entries," entries processed"]}),e.jsxs("span",{children:[x.invocations," / ",x.max_invocations," pi invocations"]}),e.jsxs("span",{children:[x.cache_hits," cached nodes reused"]})]}),!!((f=x.metrics)!=null&&f.length)&&e.jsxs("details",{className:"small",children:[e.jsx("summary",{children:"Model request timing"}),e.jsxs("p",{children:[(x.metrics.reduce((v,E)=>v+E.elapsed_ms,0)/1e3).toFixed(1)," seconds across ",x.metrics.length," requests · ",x.metrics.reduce((v,E)=>v+E.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:x.metrics.map((v,E)=>e.jsxs("li",{children:[v.stage||v.task,v.repair?" (repair)":""," · ",(v.elapsed_ms/1e3).toFixed(1)," s · ",v.status]},E))})]}),e.jsxs("p",{className:"small",children:[b?"Stopped at: ":"",x.stage]}),x.question&&e.jsxs("p",{className:"small muted",children:["Question: ",x.question]}),x.error&&e.jsxs("div",{className:"alert error",role:"alert",children:[e.jsx("strong",{children:"Last run’s error:"})," ",x.error]}),b&&e.jsxs("div",{className:"alert warning",children:[e.jsx("strong",{children:"Generation stopped. No model calls are running."}),e.jsxs("p",{className:"small",children:[x.processed_entries<x.total_entries?`${x.total_entries-x.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:!o,onClick:i,children:"Resume generation"})]})]}),s.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 ",s.nodes.length," summary nodes"]}),e.jsx("ul",{children:C.map(v=>w(v))})]}),l&&e.jsx("p",{role:"alert",className:"error",children:l}),u&&e.jsxs("div",{className:"node-inspector",children:[e.jsxs("div",{className:"section-heading",children:[e.jsx("h3",{children:u.label}),e.jsx("button",{className:"btn btn-ghost",onClick:()=>N(null),children:"Close"})]}),"observations"in u.output?e.jsxs(e.Fragment,{children:[u.output.observations.map((v,E)=>e.jsxs("div",{className:"node-observation",children:[e.jsx("strong",{children:v.topic})," ",e.jsx("span",{className:"status",children:v.state}),e.jsx(_e,{text:`${v.summary} ${v.evidence.map(F=>u.refs[F]?`[${u.refs[F]}]`:"[source unavailable]").join(" ")}`,evidence:n})]},E)),u.output.limitations.map((v,E)=>e.jsx("p",{className:"muted small",children:v},E))]}):u.output.groups.map((v,E)=>e.jsxs("p",{className:"small",children:[v.topic," · ",v.members.length," related observations"]},E))]})]})}const Te=4e3,Et=t=>t?new Date(t).toLocaleString():"Edit date not retained";function Xe({record:t}){return e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"small muted",children:[Et(t.at)," · ",t.role," · ",t.kind,t.sync_id?` · Sync #${t.sync_id}`:""]}),e.jsx("p",{className:"small muted",children:t.qualification})]})}function Ns({reference:t}){return e.jsx(At,{reference:t},t)}function At({reference:t}){const[s,n]=c.useState(null),[a,i]=c.useState(0),[o,r]=c.useState("");return c.useEffect(()=>{const m=new AbortController;return r(""),n(null),kt(t,a,m.signal).then(u=>{m.signal.aborted||n(u)}).catch(u=>{m.signal.aborted||r(u.message)}),()=>m.abort()},[t,a]),e.jsxs("section",{className:"history-source","aria-label":"Historical source",children:[o&&e.jsx("p",{role:"alert",children:o}),!s&&!o&&e.jsx("p",{role:"status",children:"Reading historical source…"}),s&&e.jsxs(e.Fragment,{children:[e.jsx("h2",{children:s.record.title}),e.jsx(Xe,{record:s.record}),s.record.workspace&&e.jsx("p",{className:"source-path",children:s.record.workspace}),e.jsx("pre",{className:"history-excerpt",children:s.record.text}),e.jsxs("p",{className:"small muted",children:["Characters ",Math.min(a+1,s.total),"–",Math.min(a+Te,s.total)," of ",s.total," in the retained record. Source logs may contain more."]}),s.total>Te&&e.jsxs("div",{className:"pagination",children:[e.jsx("button",{className:"btn btn-secondary",disabled:!a,onClick:()=>i(Math.max(0,a-Te)),children:"Earlier text"}),e.jsx("button",{className:"btn btn-secondary",disabled:a+Te>=s.total,onClick:()=>i(a+Te),children:"Later text"})]}),s.record.sync_id&&e.jsxs("p",{children:[e.jsxs("a",{href:`/syncs/${s.record.sync_id}`,target:"_blank",rel:"noopener noreferrer",children:["Open original sync #",s.record.sync_id]}),s.record.origin_ref&&` · original reference ${s.record.origin_ref}`]}),s.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."}),s.neighbors.map(m=>e.jsxs("article",{children:[e.jsx("h3",{children:e.jsx("a",{href:`/history/${m.ref}`,target:"_blank",rel:"noopener noreferrer",children:m.title})}),e.jsx(Xe,{record:m}),e.jsx("pre",{className:"history-excerpt",children:m.text})]},m.ref))]})]})]})}const Pt={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…"},Ge=t=>t<60?`${Math.ceil(t)} sec`:`${Math.ceil(t/60)} min`,Fe=t=>t.toLocaleString();function He({enabled:t,waiting:s=!1,backgroundOnly:n=!1,onLookupChange:a}){const[i,o]=c.useState(null),[r,m]=c.useState(!1);if(c.useEffect(()=>{if(a==null||a(!1),!t)return;o(null),m(!1);const b=new AbortController;let g;const A=async()=>{try{const C=await bt(b.signal);b.signal.aborted||(o(C),m(!1),a==null||a(!!(C.active&&!C.background&&C.work&&["scanning","searching","reading"].includes(C.work.stage)&&C.updated_at&&Math.abs(Date.now()-C.updated_at)<5e3)))}catch{b.signal.aborted||(m(!0),a==null||a(!1))}b.signal.aborted||(g=setTimeout(()=>void A(),1e3))};return A(),()=>{b.abort(),clearTimeout(g),a==null||a(!1)}},[t,a]),!t)return null;if(!(i!=null&&i.active)||!i.work||n&&!i.background)return s?e.jsx("p",{className:"small muted",role:"status",children:r?"Progress is unavailable; your search is still pending.":"Waiting for local history work…"}):null;const u=i.work,N=u.stage==="indexing",l=u.stage==="downloading",p=l?u.downloaded_bytes:u.completed,h=l?u.download_total_bytes:u.total,k=h?Math.floor(p/h*100):0,x=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:N&&!h?"History is up to date.":Pt[u.stage]})}),(N&&h>0||l)&&e.jsxs(e.Fragment,{children:[e.jsx("progress",{"aria-label":l?"Model download":"History indexing",max:h||1,value:h?p:void 0}),e.jsxs("p",{children:[l?`${(p/1e6).toFixed(1)} / ${(h/1e6).toFixed(1)} MB`:`${Fe(p)} / ${Fe(h)} new or changed passages ready`," · ",k,"%"]})]}),e.jsxs("p",{className:"small muted",children:[N&&`${Fe(u.reused)} unchanged passages reused (not part of this progress). `,"Elapsed ",Ge(i.elapsed_ms/1e3),".",N&&u.remaining_seconds!==null&&u.remaining_seconds>0&&` About ${Ge(u.remaining_seconds)} remaining (estimate).`,N&&h>0&&u.parallelism&&` Up to ${u.parallelism.workers} embedding worker${u.parallelism.workers===1?"":"s"}, ${u.parallelism.threads} CPU threads total.`,i.queued>0&&` ${Fe(i.queued)} other history request${i.queued===1?"":"s"} waiting.`]}),(r||x>=15)&&e.jsxs("p",{className:"small muted",children:[r?"Progress updates are temporarily unavailable.":`No new progress for ${Ge(x)}.`," Cancelling keeps completed embeddings for the next request."]})]})}const ps=["[Thinking...]","[Hmmm...]","[Hmmmmmm...]"],ms=["[Checking...]","[Looking that up...]"];function Ke(t){const s=Array.from(t.trim().replace(/\s+/g," "));if(s.length<=140)return s.join("");const n=s.slice(-140).join(""),a=n.indexOf(" ");return"…"+(a>=0&&a<25?n.slice(a+1):n)}function Tt({call:t,historyLookup:s}){const[n,a]=c.useState(0),i=!!t.replyPendingSince&&!["connecting","hearing","speaking","paused","ended"].includes(t.phase)&&!t.error;c.useEffect(()=>{if(a(0),!i)return;const m=setInterval(()=>a(u=>(u+1)%6),5e3);return()=>clearInterval(m)},[i,t.replyPendingSince,s]);let o,r="";return t.phase==="ended"?o="[Call ended]":t.error?o="[Reply unavailable]":t.phase==="paused"?o="[Sound paused]":t.phase==="connecting"?o=t.notice.includes("microphone permission")?"[Waiting for microphone...]":"[Connecting...]":t.phase==="hearing"?(o=t.question?Ke(t.question):"[Listening...]",r=t.question?"You":""):i?o=s?ms[n%ms.length]:ps[n%ps.length]:t.notice.startsWith("Reply muted locally;")?o="[Reply stopped]":t.answer?(o=Ke(t.answer),r="Draken"):t.question?(o=Ke(t.question),r="You"):o=t.phase==="speaking"?"[Speaking...]":t.muted?"[Microphone off]":"[Listening...]",e.jsxs("div",{className:"voice-captions",role:"region","aria-label":"Live captions","aria-live":"off","data-kind":r?"transcript":"status",children:[r&&e.jsx("span",{className:"voice-caption-speaker",children:r}),e.jsx("div",{className:"voice-caption-window",children:e.jsx("p",{children:o})})]})}var Y,H,J,ue,ve,ke,ne,ce,Z,pe,Ie,V,Me,qe,je,Ne,De,Re;class _t{constructor({onClose:s=()=>{},onEvent:n=()=>{}}={}){U(this,Y);U(this,H);U(this,J);U(this,ue);U(this,ve,new Set);U(this,ke,[]);U(this,ne);U(this,ce);U(this,Z);U(this,pe,new Float32Array(1024));U(this,Ie,new AbortController);U(this,V,!1);U(this,Me,!1);U(this,qe,!1);U(this,je);U(this,Ne);U(this,De);U(this,Re);D(this,De,s),D(this,Re,n)}get closed(){return j(this,V)}get clock(){var s;return!j(this,V)&&((s=j(this,H))==null?void 0:s.state)==="running"?j(this,H).currentTime:NaN}get audioState(){var s;return((s=j(this,H))==null?void 0:s.state)||"closed"}async resume(){var s,n;j(this,V)||(await((s=j(this,H))==null?void 0:s.resume()),await((n=j(this,Z))==null?void 0:n.play()))}gateInput(s){var n;(n=j(this,J))==null||n.getAudioTracks().forEach(a=>{a.enabled=!!s})}get inputActive(){var s;return!!((s=j(this,J))!=null&&s.getAudioTracks().some(n=>n.readyState==="live"))}get level(){var n;if(j(this,V)||j(this,qe)||((n=j(this,H))==null?void 0:n.state)!=="running"||!j(this,ne))return 0;j(this,ne).getFloatTimeDomainData(j(this,pe));const s=Math.sqrt(j(this,pe).reduce((a,i)=>a+i*i,0)/j(this,pe).length);return Number.isFinite(s)?Math.min(1,s*12):0}async open(s,n){if(j(this,Me)||j(this,V))throw s.getTracks().forEach(a=>a.stop()),new Error("A voice peer can open only once.");D(this,Me,!0),D(this,J,s);try{if(s.getAudioTracks().length!==1||s.getVideoTracks().length)throw new Error("Exactly one audio track is required.");if(D(this,Y,new RTCPeerConnection),D(this,H,new AudioContext),D(this,ne,j(this,H).createAnalyser()),j(this,ne).fftSize=j(this,pe).length,D(this,ce,j(this,H).createGain()),j(this,ne).connect(j(this,ce)),j(this,ce).connect(j(this,H).destination),D(this,Ne,setTimeout(()=>this.close("Voice connection timed out."),6e4)),await j(this,H).resume(),j(this,V)||j(this,H).state!=="running")throw new Error("Voice playback could not start.");D(this,ue,j(this,Y).addTrack(s.getAudioTracks()[0],s));const a=j(this,Y).createDataChannel("oai-events"),i=new Promise((r,m)=>{D(this,je,m);const u=()=>{j(this,Y).connectionState==="connected"&&a.readyState==="open"?(D(this,je,void 0),clearTimeout(j(this,Ne)),r()):["failed","disconnected","closed"].includes(j(this,Y).connectionState)&&this.close("Voice connection lost. Start a new call explicitly.")};j(this,Y).onconnectionstatechange=u,a.onopen=u,a.onclose=()=>this.close("Voice event connection closed."),a.onerror=()=>this.close("Voice event connection failed.")});if(i.catch(()=>{}),a.onmessage=r=>{if(!j(this,V)){if(typeof r.data!="string"||r.data.length>2e5){this.close("Voice event exceeds its limit.");return}try{j(this,Re).call(this,JSON.parse(r.data))}catch{this.close("Invalid voice event.")}}},j(this,Y).ontrack=r=>{if(j(this,V)){r.track.stop();return}if(r.track.kind!=="audio"||j(this,ve).size){this.close("Unexpected remote media track.");return}j(this,ve).add(r.track);const m=new MediaStream([r.track]);D(this,Z,new Audio),j(this,Z).muted=!0,j(this,Z).srcObject=m,j(this,Z).play().catch(()=>this.close("Voice playback could not start."));const u=j(this,H).createMediaStreamSource(m);j(this,ke).push(u),u.connect(j(this,ne)),r.track.onended=()=>this.close("Voice output ended.")},await j(this,Y).setLocalDescription(await j(this,Y).createOffer()),j(this,V))throw new Error("Voice connection cancelled.");const o=await n(j(this,Y).localDescription.sdp,j(this,Ie).signal);if(j(this,V))throw new Error("Voice connection cancelled.");if(typeof o!="string"||o.length>64e3||!o.startsWith("v=0"))throw new Error("Invalid voice answer.");await j(this,Y).setRemoteDescription({type:"answer",sdp:o}),await i}catch(a){throw this.close("Voice connection failed or cancelled."),a}}muteOutput(s){D(this,qe,!!s),j(this,ce)&&(j(this,ce).gain.value=s?0:1)}stopInput(){var s;(s=j(this,J))==null||s.getTracks().forEach(n=>n.stop()),D(this,J,void 0),j(this,ue)&&!j(this,V)&&j(this,ue).replaceTrack(null).catch(()=>this.close("Cannot mute voice input."))}async replaceInput(s){if(j(this,V)||!j(this,ue)||s.getAudioTracks().length!==1||s.getVideoTracks().length)throw s.getTracks().forEach(a=>a.stop()),new Error("Cannot attach voice input.");const n=j(this,J);D(this,J,s),n==null||n.getTracks().forEach(a=>a.stop());try{await j(this,ue).replaceTrack(s.getAudioTracks()[0])}catch(a){throw s.getTracks().forEach(i=>i.stop()),this.close("Cannot attach voice input."),a}if(j(this,V)||j(this,J)!==s)throw s.getTracks().forEach(a=>a.stop()),new Error("Voice input was superseded.")}close(s="Call ended."){var n,a,i,o,r;if(!j(this,V)){D(this,V,!0),clearTimeout(j(this,Ne)),j(this,Ie).abort(),(n=j(this,je))==null||n.call(this,new Error(s)),D(this,je,void 0),(a=j(this,Y))==null||a.close(),(i=j(this,J))==null||i.getTracks().forEach(m=>m.stop()),j(this,ve).forEach(m=>m.stop()),j(this,ve).clear(),j(this,ke).forEach(m=>m.disconnect()),D(this,ke,[]),(o=j(this,ne))==null||o.disconnect(),(r=j(this,ce))==null||r.disconnect(),j(this,pe).fill(0),j(this,Z)&&(j(this,Z).pause(),j(this,Z).srcObject=null,D(this,Z,void 0)),j(this,H)&&j(this,H).state!=="closed"&&j(this,H).close().catch(()=>{});try{j(this,De).call(this,s)}catch{}}}}Y=new WeakMap,H=new WeakMap,J=new WeakMap,ue=new WeakMap,ve=new WeakMap,ke=new WeakMap,ne=new WeakMap,ce=new WeakMap,Z=new WeakMap,pe=new WeakMap,Ie=new WeakMap,V=new WeakMap,Me=new WeakMap,qe=new WeakMap,je=new WeakMap,Ne=new WeakMap,De=new WeakMap,Re=new WeakMap;const es={phase:"connecting",muted:!1,microphone:!1,voiceInterruption:!1,question:"",answer:"",evidence:[],error:"",notice:"",startedAt:0,turnId:0,replyPendingSince:0,historyReady:!1};async function X(t,s={}){const n=await fetch(`/api/voice${t}`,{...s,headers:{"Content-Type":"application/json",...as()}});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 It{constructor(s){_(this,"state",{...es,phase:"connecting"});_(this,"alive",!0);_(this,"id","");_(this,"pageExit",()=>{this.end()});_(this,"peer");_(this,"life",new AbortController);_(this,"inputContext",new AudioContext);_(this,"inputMeter",this.inputContext.createAnalyser());_(this,"inputSource");_(this,"input");_(this,"changing",!1);_(this,"cursor",0);_(this,"timer",0);_(this,"speechAt",0);_(this,"providerDone",!0);_(this,"stopped",!1);_(this,"newQuestion",!1);_(this,"pendingAnswer",!1);_(this,"answerSettled",!1);_(this,"awaitingUser",!1);_(this,"userId",0);_(this,"inputEpoch",0);_(this,"pendingNotice","Preparing the answer. I’ll continue automatically.");_(this,"assistantId",null);_(this,"observed",0);_(this,"reportedAt",0);_(this,"micBuffer",new Float32Array(1024));this.options=s,window.addEventListener("pagehide",this.pageExit),this.inputMeter.fftSize=1024,this.inputContext.resume().catch(()=>{}),this.peer=new _t({onEvent:n=>this.providerEvent(n),onClose:n=>{this.alive&&(this.set({error:n}),this.end())}}),this.set({})}set(s){this.state={...this.state,...s},this.options.onState(this.state)}async request(s,n){return X(`/live/calls/${this.id}${s}`,{method:n?"POST":"GET",...n?{body:JSON.stringify(n)}:{},signal:this.life.signal})}async microphone(){var n;const s=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1});if(!this.alive)throw s.getTracks().forEach(a=>a.stop()),new Error("Call ended");(n=this.inputSource)==null||n.disconnect(),this.inputSource=this.inputContext.createMediaStreamSource(s),this.inputSource.connect(this.inputMeter),this.input=s,this.set({microphone:!0});for(const a of s.getAudioTracks())a.addEventListener("ended",()=>{this.alive&&!this.state.muted&&this.input===s&&(this.set({muted:!0,microphone:!1,notice:"Microphone disconnected. Type, or turn the microphone on again."}),this.peer.stopInput())});return s}silentInput(){const s=this.inputContext.createMediaStreamDestination(),n=this.inputContext.createConstantSource();return n.offset.value=0,n.connect(s),n.start(),s.stream}async start(s){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 X("/live/calls",{method:"POST",body:JSON.stringify({syncId:s,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){X(`/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 o;try{o=await this.microphone(),this.set({notice:""})}catch{if(!this.alive)return;o=this.silentInput(),this.set({muted:!0,notice:"Microphone unavailable. You can type instead."})}if(this.input=o,await this.peer.open(o,async(r,m)=>(await X(`/live/calls/${i.id}/connect`,{method:"POST",body:JSON.stringify({sdp:r}),signal:m})).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(s){var n,a;this.alive&&(s.type==="input_transcript.added"&&this.stopped&&this.newQuestion&&(this.stopped=!1,this.peer.muteOutput(!1),this.set({notice:""})),s.type==="turn.created"&&((n=s.turn)==null?void 0:n.role)==="assistant"&&(this.stopped&&this.newQuestion&&(this.stopped=!1,this.newQuestion=!1,this.peer.muteOutput(!1)),this.providerDone=!1),s.type==="output_transcript.added"&&!this.stopped&&(this.providerDone=!1,this.state.voiceInterruption||this.peer.gateInput(!1)),s.type==="turn.done"&&((a=s.turn)==null?void 0:a.role)==="assistant"&&(this.providerDone=!0))}meter(){if(!this.alive)return;const s=performance.now(),n=this.peer.level;let a=0;this.state.muted||(this.inputMeter.getFloatTimeDomainData(this.micBuffer),a=Math.sqrt(this.micBuffer.reduce((i,o)=>i+o*o,0)/this.micBuffer.length)*10),this.stopped&&a>.08&&(this.newQuestion=!0),n>.02?(this.speechAt=s,this.observed+=80,this.state.phase!=="speaking"&&this.set({phase:"speaking"}),this.state.voiceInterruption||this.peer.gateInput(!1),this.assistantId&&s-this.reportedAt>1e3&&(this.reportedAt=s,this.request("/observed",{messageId:this.assistantId,milliseconds:this.observed}).catch(()=>{}))):(this.providerDone||this.pendingAnswer||this.answerSettled)&&s-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 s,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=(s=this.options).onTurn)==null||n.call(s,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(s){if(!this.alive||!this.id||!s.trim()||s.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:s,answer:"",replyPendingSince:Date.now()});try{await this.request("/text",{question:s,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 s;if(!(!this.alive||this.changing)){this.changing=!0;try{if(!this.state.muted)this.set({muted:!0}),this.peer.stopInput(),(s=this.inputSource)==null||s.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(s){this.set({voiceInterruption:s}),this.peer.gateInput(!this.state.muted&&(s||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 s,n,a,i;if(this.alive){this.alive=!1,window.removeEventListener("pagehide",this.pageExit),clearInterval(this.timer),this.life.abort(),(s=this.input)==null||s.getTracks().forEach(o=>o.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 o=new AbortController,r=setTimeout(()=>o.abort(),4e3);try{await X(`/live/calls/${this.id}/end`,{method:"POST",keepalive:!0,signal:o.signal})}catch{}finally{clearTimeout(r)}}}}}const Mt={connecting:"Getting ready",listening:"Your turn",hearing:"Listening to you",thinking:"Preparing your answer",speaking:"Draken is speaking",paused:"Sound paused",ended:"Call ended"},qt=t=>`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`;function Dt({sync:t,readiness:s,onPrepareHistory:n,disabled:a,beforeStart:i,onActiveChange:o,onClosed:r,onChat:m,autoStart:u=!1,onAutoStartHandled:N}){const[l,p]=c.useState(null),[h,k]=c.useState(""),[x,b]=c.useState(!1),[g,A]=c.useState(es),[C,d]=c.useState(0),[w,f]=c.useState(!1),[v,E]=c.useState(""),[F,ee]=c.useState([]),[I,R]=c.useState(null),[L,re]=c.useState(""),[ie,B]=c.useState(!1),[se,ge]=c.useState(!1),G=c.useRef(null),fe=c.useRef(null),xe=c.useRef(null),Le=c.useRef(null),z=c.useRef(null),K=c.useRef(!0),le=c.useRef(!1),oe=c.useRef(!1),[be,Se]=c.useState(!1),Ce=[...t.items,...t.context],de=Ce.find(y=>y.ref===L),te=(s==null?void 0:s.ready)===!0,ye=window.isSecureContext,we=new URL(window.location.href);we.protocol="https:",we.port=String((l==null?void 0:l.httpsPort)||443),c.useEffect(()=>{L&&fe.current&&xe.current&&(fe.current.scrollTop+=xe.current.getBoundingClientRect().top-fe.current.getBoundingClientRect().top)},[L]);const S=async()=>{try{const y=await X("/status");K.current&&(p(y),k(""))}catch(y){K.current&&k(y instanceof Error?y.message:"Could not check ChatGPT voice")}};c.useEffect(()=>{K.current=!0,S();const y=setInterval(()=>{z.current||S()},15e3);return()=>{var P;clearInterval(y),K.current=!1,(P=z.current)==null||P.end()}},[]),c.useEffect(()=>{var y,P,M;x&&!((y=G.current)!=null&&y.open)?(P=G.current)==null||P.showModal():x||(M=G.current)==null||M.close()},[x]),c.useEffect(()=>{if(!x||!g.startedAt||g.phase==="ended")return;const y=()=>d(Math.max(0,Math.floor((Date.now()-g.startedAt)/1e3)));y();const P=setInterval(y,1e3);return()=>clearInterval(P)},[x,g.startedAt,g.phase==="ended"]);const $=async()=>{var y;if(!(z.current||le.current||oe.current||!te)){oe.current=!0,Se(!0),k("");try{if(await i(),!K.current||document.visibilityState!=="visible")return;A({...es}),d(0),ee([]),E(""),re(""),f(!1),B(!1),ge(!1),b(!0),o(!0);const P=new It({onState:M=>{K.current&&(A(M),!M.microphone&&M.muted&&f(!0))},onPlayback:M=>{Le.current=M},onTurn:(M,$e,ns,Oe)=>{K.current&&ee(Be=>Be.some(Ue=>Ue.id===Oe)?Be.map(Ue=>Ue.id===Oe?{id:Oe,question:M,answer:$e,refs:ns}:Ue):[...Be,{id:Oe,question:M,answer:$e,refs:ns}])}});z.current=P,z.current===P&&await P.start(t.id)}catch(P){if(await((y=z.current)==null?void 0:y.end()),K.current){const M=P instanceof Error?P.message:"The call could not start";k(M),z.current&&A($e=>({...$e,phase:"ended",error:M}))}}finally{oe.current=!1,K.current&&Se(!1)}}};c.useEffect(()=>{!u||a||!te||!l||(N==null||N(),l.installed&&!l.activeCall&&ye&&document.visibilityState==="visible"?$():k("Your snapshot is ready. Start the call explicitly when audio is available and this page is visible."))},[u,a,te,l]);const O=async()=>{var y;if(!le.current){le.current=!0,re(""),await((y=z.current)==null?void 0:y.end()),z.current=null,K.current&&(b(!1),R(null),o(!1));try{await r(),await S()}finally{le.current=!1}}},W=async()=>{try{R(await X(`/syncs/${t.id}/history`))}catch(y){k(y instanceof Error?y.message:"Could not load call history")}},ae=async()=>{try{const y=await fetch("/api/voice/certificate",{headers:as()});if(!y.ok)throw new Error("Could not download the local certificate. Check your dashboard login.");const P=URL.createObjectURL(await y.blob()),M=document.createElement("a");M.href=P,M.download="draken-local-root.crt",M.click(),setTimeout(()=>URL.revokeObjectURL(P),1e3)}catch(y){k(y instanceof Error?y.message:"Certificate download failed")}},Ve=()=>{var P;if(!v.trim())return;const y=v.trim();E(""),(P=z.current)==null||P.sendText(y)};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(We,{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.jsxs("div",{className:"conversation-actions",children:[e.jsxs("button",{className:"btn btn-secondary",disabled:x||be,onClick:m,children:[e.jsx(ys,{size:16}),"Chat instead"]}),!ye&&(l!=null&&l.httpsPort)?e.jsxs("a",{className:"btn btn-primary",href:we.href,children:["Open secure call page ",e.jsx(zs,{size:15})]}):e.jsxs("button",{className:"btn btn-primary",disabled:a||be||!te||!(l!=null&&l.installed)||!!(l!=null&&l.activeCall)||!ye,onClick:()=>void $(),children:[e.jsx(We,{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."}),!ye&&e.jsxs("p",{className:"small muted",children:["The microphone needs trusted HTTPS. ",l!=null&&l.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."]}),(l==null?void 0:l.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 ae(),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."]})]}),t.status==="open"&&e.jsx("p",{className:"small muted",role:"status",children:te?`Ready to call. History cutoff: ${s!=null&&s.before?new Date(s.before).toLocaleString():"prepared snapshot"}. Refresh history for later work.`:s?s.preparing?"Preparing history before calling. Your microphone is off.":s.briefingReady?"History needs preparation before you can call.":"Prepare the briefing first.":"Checking call readiness…"}),t.status==="open"&&(s==null?void 0:s.briefingReady)&&!s.preparing&&e.jsx("button",{className:"btn btn-secondary",disabled:a||be,onClick:n,children:te?"Refresh history":"Prepare history"}),(s==null?void 0:s.error)&&!te&&e.jsx("p",{className:"small",role:"alert",children:s.error}),t.status!=="open"&&e.jsx("p",{className:"small muted",children:"This sync is closed. Start a new sync for another call."}),l&&!l.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"}),"."]}),h&&e.jsxs("p",{className:"small",role:"alert",children:[h," ",e.jsx("button",{className:"btn btn-secondary",onClick:()=>void S(),children:"Retry"})]}),(l==null?void 0:l.activeCall)&&!x&&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.")&&X(`/live/calls/${l.activeCall.id}/end`,{method:"POST",body:"{}"}).then(S).catch(y=>k(y.message))},children:"End previous call"})]}),e.jsxs("details",{className:"voice-history",onToggle:y=>{y.currentTarget.open&&W()},children:[e.jsx("summary",{children:"Call history"}),(I==null?void 0:I.length)===0&&e.jsx("p",{className:"muted small",children:"No calls yet. Transcripts are saved here; raw audio is not recorded."}),I==null?void 0:I.map(y=>e.jsxs("details",{className:"voice-history-call",children:[e.jsxs("summary",{children:[new Date(y.started_at).toLocaleString()," · ",y.turns.length," ",y.mode==="native"?"messages":"turns"," · ",y.status]}),e.jsx("p",{className:"small muted",children:y.end_reason||"Call in progress"}),y.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."}),y.turns.map(P=>e.jsxs("div",{className:"voice-history-turn",children:[P.question&&e.jsxs(e.Fragment,{children:[e.jsx("strong",{className:"message-author",children:"You"}),e.jsx("p",{className:"prose",children:P.question})]}),(P.answer||!P.question||y.mode!=="native")&&e.jsxs(e.Fragment,{children:[e.jsxs("strong",{className:"message-author",children:["Draken · ",P.status]}),e.jsx(_e,{text:`${P.answer||P.error||"No reply generated."} ${JSON.parse(P.evidence_json).map(M=>`[${M}]`).join(" ")}`,evidence:Ce}),P.status!=="completed"&&e.jsxs("p",{className:"small muted",children:["Generated text is shown above. ",P.heard_text?`Confirmed played: ${P.heard_text}`:"Playback was not confirmed."]})]})]},P.id))]},y.id))]})]}),e.jsxs("dialog",{ref:G,className:"voice-dialog","aria-labelledby":"voice-title",onCancel:y=>{y.preventDefault(),O()},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 #",t.id]})]}),e.jsx("span",{className:"voice-clock","aria-label":"Call duration",children:qt(C)}),e.jsx("button",{className:"icon-button","aria-label":"Close call",onClick:()=>void O(),children:e.jsx(Qe,{size:18})})]}),e.jsxs("div",{className:"voice-call-body",children:[g.historyReady?e.jsxs("div",{className:"voice-scene",children:[x&&g.phase!=="ended"?e.jsx(Is,{playback:Le,mode:g.phase==="speaking"?"speaking":g.phase==="hearing"?"listening":g.replyPendingSince&&!g.error?"thinking":"idle"}):e.jsx("img",{loading:"lazy",className:"voice-scene-poster",src:"/persona/call-poster.webp",alt:"Draken’s workshop"}),e.jsx(Tt,{call:g,historyLookup:se})]}):e.jsxs("section",{className:"voice-preparation","aria-label":"Call preparation",children:[e.jsx("h3",{children:g.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:g.muted&&g.phase==="listening"?"Microphone muted":Mt[g.phase]})]}),g.error&&e.jsx("div",{className:"alert error",role:"alert",children:g.error}),g.error&&g.question&&g.phase==="listening"&&e.jsx("button",{className:"btn btn-primary",onClick:()=>{var y;return void((y=z.current)==null?void 0:y.sendText(g.question))},children:"Retry question"}),g.phase==="paused"&&e.jsx("button",{className:"btn btn-primary",onClick:()=>{var y;return void((y=z.current)==null?void 0:y.resumeSound())},children:"Resume sound"}),e.jsxs("div",{className:"voice-controls",children:[e.jsxs("button",{className:`btn btn-secondary ${g.muted?"is-muted":""}`,disabled:g.phase==="connecting"||g.phase==="ended",onClick:()=>{var y;return void((y=z.current)==null?void 0:y.toggleMute())},children:[g.muted?e.jsx(Ks,{size:18}):e.jsx(Ws,{size:18}),g.muted?g.microphone?"Unmute":"Enable mic":"Mute"]}),e.jsxs("button",{className:"btn btn-secondary",disabled:!["thinking","speaking","paused"].includes(g.phase),onClick:()=>{var y;return void((y=z.current)==null?void 0:y.interrupt().catch(()=>{}))},children:[e.jsx(vs,{size:15}),"Stop reply"]}),e.jsxs("button",{className:"btn btn-danger",onClick:()=>void O(),children:[e.jsx(Qs,{size:18}),g.phase==="ended"?"Close":"End call"]})]}),e.jsxs("div",{className:"voice-options",children:[e.jsxs("button",{className:"voice-keyboard-toggle","aria-pressed":g.voiceInterruption,disabled:g.phase==="connecting"||g.phase==="ended",onClick:()=>{var y;return(y=z.current)==null?void 0:y.setVoiceInterruption(!g.voiceInterruption)},children:[e.jsx(Hs,{size:16}),"Headphone mode"]}),e.jsxs("button",{className:"voice-keyboard-toggle",onClick:()=>f(y=>!y),"aria-expanded":w,children:[e.jsx(Vs,{size:16}),w?"Hide keyboard":"Type a question"]})]}),w&&e.jsxs("form",{className:"voice-compose",onSubmit:y=>{y.preventDefault(),Ve()},children:[e.jsx("input",{className:"input","aria-label":"Type a question for this call",placeholder:"Or ask here…",maxLength:2e3,disabled:g.phase==="connecting"||g.phase==="ended",value:v,onChange:y=>E(y.target.value)}),e.jsx("button",{className:"btn btn-primary","aria-label":"Send voice-call question",disabled:!v.trim()||g.phase==="connecting"||g.phase==="ended",children:e.jsx(xs,{size:18})})]}),e.jsxs("details",{className:"voice-conversation",open:ie,onToggle:y=>B(y.currentTarget.open),children:[e.jsx("summary",{children:"Conversation & details"}),e.jsxs("div",{className:"voice-call-details",ref:fe,children:[g.notice&&e.jsx("p",{className:"small muted voice-notice",children:g.notice}),e.jsx(He,{enabled:x&&g.historyReady&&(!!g.replyPendingSince||["connecting","thinking"].includes(g.phase)),onLookupChange:ge}),e.jsx("p",{className:"small muted",children:g.phase==="speaking"?g.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:F.map(y=>e.jsxs("div",{children:[y.question&&e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"You"}),e.jsx("p",{children:y.question})]}),y.answer&&e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Draken · generated reply"}),e.jsx("p",{className:y.id===g.turnId?"voice-answer":void 0,children:y.answer})]})]},y.id))}),!F.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."}),g.evidence.length>0&&e.jsxs("details",{className:"voice-history",children:[e.jsxs("summary",{children:["Sources supplied (",g.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:g.evidence.map(y=>e.jsx("button",{className:"citation",onClick:P=>{const M=P.currentTarget.closest("details");M&&(M.open=!1),re(L===y?"":y)},children:y.startsWith("H")?`History ${y.slice(-6)}`:`Source ${y}`},y))})]}),x&&/^H[a-f0-9]{24}$/.test(L)&&e.jsxs("section",{className:"voice-source",ref:xe,children:[e.jsx("button",{className:"btn btn-secondary",onClick:()=>re(""),children:"Close historical source"}),e.jsx(Ns,{reference:L})]}),x&&de&&e.jsxs("section",{className:"voice-source",ref:xe,children:[e.jsxs("div",{className:"section-heading",children:[e.jsxs("strong",{children:[de.ref," · ",de.session_name||de.cwd]}),e.jsx("button",{className:"icon-button","aria-label":"Close source",onClick:()=>re(""),children:e.jsx(Qe,{size:16})})]}),e.jsx("pre",{children:de.text})]})]})]}),e.jsxs("div",{className:"voice-footer",children:[e.jsx(Os,{size:14}),e.jsx("span",{children:"Experimental live audio to OpenAI · Generated, not verified · 30-minute limit"})]})]})]})}function Rt({sync:t,readiness:s,draft:n,setDraft:a,disabled:i,sending:o,onSend:r,onCancel:m,onPrepareHistory:u,onVoice:N}){const l=t.tree.run,p=t.status==="open",h=t.busy&&(l==null?void 0:l.status)==="running"&&!!l.question,k=!t.busy&&!!(l!=null&&l.question)&&["failed","cancelled","interrupted"].includes((l==null?void 0:l.status)||""),x=o?n:h||k?l==null?void 0:l.question:null,b=h||o,g=o?"Sending your message…":l!=null&&l.stage.includes("Searching")?"Searching your prepared history…":l!=null&&l.stage.includes("Reconciling")?"Checking later updates…":l!=null&&l.stage.includes("Checking evidence")?"Checking source references…":l!=null&&l.stage.includes("Thinking")?"Draken is thinking…":"Reading the snapshot context…",A=c.useRef(null),C=c.useRef(!0);c.useEffect(()=>{C.current&&A.current&&(A.current.scrollTop=A.current.scrollHeight)},[t.messages.length,x,b,g]);const d=[...t.items,...t.context],w=i||!p||!(s!=null&&s.ready);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 history. No microphone or audio."})]}),e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:N,children:"Voice & call history"})]}),e.jsxs("div",{className:"chat-thread",ref:A,onScroll:()=>{const f=A.current;f&&(C.current=f.scrollHeight-f.scrollTop-f.clientHeight<80)},children:[!t.messages.length&&!x&&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."})]}),t.messages.map(f=>e.jsxs("article",{className:`chat-message ${f.role}`,children:[f.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:f.role==="user"?"You":"Draken"}),e.jsx("time",{dateTime:f.created_at,children:new Date(f.created_at).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})})]}),e.jsx(_e,{text:f.content,evidence:d})]})]},f.id)),x&&!(l!=null&&l.request_id&&(h||k&&!o))&&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:x})]})}),b&&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"}),g,e.jsx("span",{className:"small muted",children:"Your answer will appear here when it’s ready."})]})]}),k&&e.jsxs("div",{className:"alert warning",role:"alert",children:[e.jsx("strong",{children:(l==null?void 0:l.status)==="failed"?"Reply failed.":"Reply stopped."}),e.jsx("p",{children:(l==null?void 0:l.error)||"The question is retained. Nothing was marked reviewed."}),e.jsx("button",{className:"btn btn-secondary",disabled:w,onClick:()=>r((l==null?void 0:l.question)||""),children:"Retry chat reply"})]})]}),p&&e.jsxs(e.Fragment,{children:[!b&&e.jsx("p",{className:"small muted",role:"status",children:s!=null&&s.ready?`History cutoff: ${s.before?new Date(s.before).toLocaleString():"prepared snapshot"}. Refresh for later work.`:t.busy?"Preparing the briefing and history for chat…":s!=null&&s.briefingReady?"Prepare history before sending a message.":"Prepare the briefing and history first."}),(s==null?void 0:s.error)&&e.jsx("p",{role:"alert",className:"small",children:s.error}),e.jsxs("form",{className:"chat-compose",onSubmit:f=>{f.preventDefault(),!w&&n.trim()&&(C.current=!0,r())},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:w,onChange:f=>a(f.target.value),placeholder:"Ask Draken…",onKeyDown:f=>{var v;f.key==="Enter"&&!f.shiftKey&&!f.nativeEvent.isComposing&&(f.preventDefault(),n.trim()&&!w&&((v=f.currentTarget.form)==null||v.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"}),h?e.jsxs("button",{type:"button",className:"btn btn-secondary",onClick:m,children:[e.jsx(vs,{size:14}),"Stop reply"]}):e.jsxs("button",{className:"btn btn-primary",disabled:w||!n.trim(),children:[e.jsx(xs,{size:16}),"Send message"]})]})]}),(s==null?void 0:s.briefingReady)&&!s.preparing&&!b&&e.jsx("button",{className:"btn btn-secondary chat-refresh",disabled:i,onClick:u,children:s.ready?"Refresh history":"Prepare history"})]}),!p&&e.jsx("p",{className:"small muted",children:"This sync is closed. Its chat is preserved; start a new sync to continue."}),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 Ss(){const t=crypto.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const s=[...t].map(n=>n.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function Cs({cost:t}){if(!t)return null;const s=t.usd===null?"unavailable":t.usd>0&&t.usd<1e-6?"<$0.000001":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:t.usd<.01?6:2}).format(t.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=t.usd===null?" Usage/pricing was not captured or is unavailable for this preparation.":t.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: ",s,t.usd!==null&&!t.complete?" (partial)":""]})}function me(t,s,n){t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||(t.preventDefault(),s(n))}function Lt({id:t,chat:s=!1,callIntent:n,consumeIntent:a,navigate:i,setGuard:o}){var be,Se,Ce,de,te,ye,we;const[r,m]=c.useState(null),[u,N]=c.useState(null),[l,p]=c.useState(""),[h,k]=c.useState(""),[x,b]=c.useState(!1),[g,A]=c.useState(!1),[C,d]=c.useState(""),[w,f]=c.useState(""),[v,E]=c.useState(""),F=c.useRef(!0),ee=c.useRef(null),I=S=>{F.current&&(m(S),d(S.decisions),f(S.carry_forward))},R=async(S,$)=>{p(S),k("");try{await $()}catch(O){F.current&&k(O instanceof Error?O.message:"Something went wrong")}finally{F.current&&p("")}};c.useEffect(()=>(F.current=!0,Ye(t).then(I).catch(S=>{F.current&&k(S.message)}),()=>{F.current=!1}),[t]),c.useEffect(()=>{if(!(r!=null&&r.busy))return;let S=!1,$;const O=async()=>{try{const W=await pt(t);if(S)return;if(W.busy)m(ae=>ae&&{...ae,tree:W});else{const ae=await Ye(t);S||I(ae);return}}catch(W){S||k(W instanceof Error?W.message:"Could not refresh progress")}S||($=setTimeout(()=>void O(),1e3))};return O(),()=>{S=!0,clearTimeout($)}},[t,r==null?void 0:r.busy]),c.useEffect(()=>{N(null);const S=new AbortController;let $;const O=async()=>{try{const W=await(s?mt:hs)(t,S.signal);S.signal.aborted||N(W)}catch{S.signal.aborted||N(null)}S.signal.aborted||($=setTimeout(()=>void O(),r!=null&&r.busy?1e3:3e3))};return O(),()=>{S.abort(),clearTimeout($)}},[t,r==null?void 0:r.busy,r==null?void 0:r.briefing,r==null?void 0:r.status,x,s]);const L=!!(r&&(C!==r.decisions||w!==r.carry_forward)),re=!!v.trim();c.useEffect(()=>{o(()=>!(L||re||x)||window.confirm(x?"Leave this page and end the call?":"Leave with unsaved notes or an unsent message?"));const $=O=>{(L||re||x)&&(O.preventDefault(),O.returnValue="")};return window.addEventListener("beforeunload",$),()=>{o(null),window.removeEventListener("beforeunload",$)}},[L,re,x,o]);const ie=()=>{a(),A(!1)},B=!!(l||r!=null&&r.busy||x),se=(r==null?void 0:r.status)==="open",ge=r?[...r.items,...r.context]:[],G=ge.some(S=>S.unavailable),fe=()=>void R("Preparing your conversation…",async()=>{if(r){if(s&&L)throw new Error("Save or undo your note edits before preparing chat.");A(!s),L&&await Ae(t,C,w),I(await vt(t))}}),xe=()=>void R("Preparing history for your conversation…",async()=>{if(s&&L)throw new Error("Save or undo your note edits before refreshing history.");ie(),N(null),L&&await Ae(t,C,w),I(await gt(t))}),Le=(S=v)=>void R("Starting discussion…",async()=>{L&&await Ae(t,C,w),I(await jt(t,S))}),z=(S=v)=>void R("Sending message…",async()=>{var W,ae;if(ie(),L)throw new Error("Save your note edits, or undo them, before sending a message. Chat does not save decisions for you.");const $=((W=ee.current)==null?void 0:W.text)===S?ee.current:{text:S,id:Ss()};ee.current=$;let O;try{O=await lt(t,S,$.id)}catch(Ve){const y=await Ye(t).catch(()=>null);if(((ae=y==null?void 0:y.tree.run)==null?void 0:ae.request_id)!==$.id)throw Ve;O=y}I(O),E(""),ee.current=null}),K=()=>{var S;return(S=r==null?void 0:r.tree.run)!=null&&S.question?s||r.tree.run.request_id?z(r.tree.run.question):Le(r.tree.run.question):fe()},le=()=>{ie(),R("Stopping preparation…",async()=>{await yt(t)})},oe=!(r!=null&&r.busy)&&(r==null?void 0:r.tree.run)&&["failed","cancelled","interrupted"].includes(r.tree.run.status);return c.useEffect(()=>{(oe||u!=null&&u.error)&&ie()},[oe,u==null?void 0:u.error]),e.jsxs("main",{className:"sync-detail",children:[e.jsxs("a",{className:"back-link",href:"/",onClick:S=>me(S,i,"/"),children:[e.jsx($s,{size:16}),"All syncs"]}),h&&e.jsx("div",{className:"alert error",role:"alert",children:h}),!r&&!h&&e.jsx("p",{role:"status",children:"Opening sync…"}),r&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"page-heading",children:[e.jsxs("div",{children:[e.jsx("span",{className:"eyebrow",children:"FROZEN CONVERSATION"}),e.jsxs("h1",{children:["Sync #",t]}),e.jsxs("p",{className:"muted",children:["Snapshot created ",new Date(r.snapshot_at).toLocaleString()," · ",r.item_count," entries · ",e.jsx("span",{className:`status ${r.status}`,children:r.status==="completed"?"reviewed":r.status})]}),e.jsx(Cs,{cost:r.aggregation_cost})]}),se&&e.jsxs("button",{className:"btn btn-secondary",disabled:B||G||!!(r.tree.run&&!r.tree.complete),onClick:()=>{window.confirm(`Mark these ${r.item_count} snapshot entries reviewed? Later activity is not affected. This does not mean every spoken suggestion was agreed.`)&&R("Marking snapshot reviewed…",async()=>{I(await Nt(t,C,w))})},children:[e.jsx(Us,{size:16}),"Mark reviewed"]})]}),G&&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."})]}),(l||r.busy)&&!(s&&(l==="Sending message…"||(be=r.tree.run)!=null&&be.question&&r.tree.run.status==="running"))&&e.jsxs("div",{className:"working",role:"status",children:[e.jsx("span",{className:"spinner"}),l||(r.recap_state==="running"?"Making a short conversation recap…":u!=null&&u.preparing?"Preparing searchable history…":((Se=r.tree.run)==null?void 0:Se.stage)||"Preparing your conversation…"),r.busy&&e.jsx("button",{className:"btn btn-secondary",onClick:le,children:"Cancel preparation"})]}),e.jsx(He,{enabled:r.busy}),r.busy&&!((Ce=r.tree.run)!=null&&Ce.question)&&r.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."}),oe&&!(s&&((de=r.tree.run)!=null&&de.question))&&e.jsxs("div",{className:"alert warning",role:"alert",children:[e.jsx("strong",{children:(te=r.tree.run)!=null&&te.question?"Reply stopped.":"Preparation stopped."}),e.jsx("p",{children:((ye=r.tree.run)==null?void 0:ye.error)||"Your snapshot is retained. Nothing was marked reviewed."}),e.jsx("button",{className:"btn btn-primary",disabled:B||G,onClick:K,children:(we=r.tree.run)!=null&&we.question?"Retry reply":s?"Retry preparation":"Retry preparation & call"})]}),se&&!r.briefing&&!r.busy&&!oe&&r.snapshot_version===2&&e.jsx("button",{className:"btn btn-primary",disabled:B||G,onClick:fe,children:s?"Prepare for chat":"Prepare & call"}),s?e.jsx(Rt,{sync:r,readiness:u,draft:v,setDraft:E,disabled:B||G,sending:l==="Sending message…",onSend:z,onCancel:le,onPrepareHistory:xe,onVoice:()=>i(`/syncs/${t}`)}):e.jsx(Dt,{sync:r,readiness:u,onPrepareHistory:xe,disabled:B||G,onActiveChange:b,onChat:()=>{ie(),i(`/syncs/${t}/chat`)},autoStart:(n||g)&&!oe&&!G,onAutoStartHandled:ie,beforeStart:async()=>{L&&I(await Ae(t,C,w));const S=await hs(t);if(N(S),!S.ready)throw new Error("History needs preparation before calling. Use Prepare history first.")},onClosed:async()=>{await R("Saving a short recap…",async()=>{I(await ls(t))})}},t),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:B,onClick:()=>void R("Summarizing the conversation…",async()=>I(await ls(t))),children:r.recap?"Refresh recap":"Make recap"})]}),e.jsx("p",{className:"prose",children:r.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."}),r.recap_error&&e.jsx("p",{role:"alert",className:"small",children:r.recap_error})]}),r.memory.length>0&&e.jsxs("details",{className:"detail-section",children:[e.jsx("summary",{children:"Previous sync recaps"}),r.memory.map(S=>e.jsxs("article",{className:"memory-recap",children:[e.jsxs("a",{href:`/syncs/${S.sync_id}`,onClick:$=>me($,i,`/syncs/${S.sync_id}`),children:["Sync #",S.sync_id]})," ",e.jsx("span",{className:"small muted",children:S.status==="open"?"not marked reviewed":S.status||"historical"}),e.jsx("p",{className:"prose",children:S.recap||"No automatic recap in this older snapshot."}),S.decisions&&e.jsxs("p",{className:"small prose",children:["Saved decisions: ",S.decisions]}),S.carry_forward&&e.jsxs("p",{className:"small prose",children:["Carried forward: ",S.carry_forward]})]},S.sync_id))]}),e.jsxs("details",{className:"detail-section",open:!r.messages.length&&!!r.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."}),(u==null?void 0:u.before)&&e.jsxs("p",{className:"small muted",children:["Conversation history cutoff: ",new Date(u.before).toLocaleString(),". Later activity waits for another preparation."]}),r.briefing?e.jsx(_e,{text:r.briefing,evidence:ge}):e.jsx("p",{children:"No briefing yet."}),r.snapshot_version<2&&e.jsxs("div",{className:"alert warning",children:["This is a historical capped snapshot. Notes and discussion are preserved.",se&&e.jsx("button",{className:"btn btn-secondary",disabled:B,onClick:()=>{window.confirm("Expand this legacy snapshot to currently eligible history? Existing notes and citations are retained.")&&R("Expanding snapshot…",async()=>I((await xt(t)).sync))},children:"Expand to full history"})]})]})]}),!s&&e.jsxs("details",{className:"detail-section",children:[e.jsxs("summary",{children:["Saved text conversation (",r.messages.length,")"]}),e.jsxs("section",{className:"discussion",children:[r.messages.map(S=>e.jsxs("div",{className:`message ${S.role}`,children:[e.jsx("span",{className:"message-author",children:S.role==="user"?"You":"Draken"}),e.jsx(_e,{text:S.content,evidence:ge})]},S.id)),e.jsx("button",{className:"btn btn-secondary",disabled:x,onClick:()=>{ie(),i(`/syncs/${t}/chat`)},children:"Open chat"})]})]}),e.jsxs("details",{className:"detail-section",children:[e.jsxs("summary",{children:["Decisions & carry-forward",L?" · 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:!se||B,value:C,onChange:S=>d(S.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:!se||B,value:w,onChange:S=>f(S.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."}),se&&e.jsx("button",{className:"btn btn-secondary",disabled:B||!L,onClick:()=>void R("Saving notes…",async()=>I(await Ae(t,C,w))),children:"Save notes"})]})]}),e.jsxs("details",{className:"detail-section",children:[e.jsx("summary",{children:"Evidence & preparation details"}),e.jsx(Ct,{syncId:t,progress:r.tree,evidence:ge,onResume:se?K:void 0,resumeEnabled:!B&&!G,onCancel:le}),e.jsx(us,{items:r.items,title:"New evidence in this snapshot"}),e.jsx(us,{items:r.context,title:"Earlier context — not new progress"})]}),se&&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:B,onClick:()=>{window.confirm("Discard this sync and release its unreviewed entries? Its history is retained.")&&R("Discarding sync…",async()=>I(await St(t)))},children:"Discard sync"})]})]})]})}function Es({active:t=!0,firstRun:s=!1,always:n=!1,onReady:a,onTextReady:i}){const[o,r]=c.useState(null),[m,u]=c.useState(null),[N,l]=c.useState(""),[p,h]=c.useState(!1),[k,x]=c.useState(0);if(c.useEffect(()=>{if(!t)return;let g=!0;const A=async(d=!1)=>{h(!0);try{const[w,f]=await Promise.all([at(d),X("/status").catch(()=>null)]);if(!g)return;r(w),u(f),l(f?"":"Voice status is unavailable. Configured text chat can still be used."),a==null||a(w.pi.state==="configured"&&!!(f!=null&&f.installed)),i==null||i(w.pi.state==="configured")}catch{g&&(l("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{g&&h(!1)}};A(k>0);const C=setInterval(()=>void A(),6e4);return()=>{g=!1,clearInterval(C)}},[t,k,a,i]),!t||!n&&!s&&!N&&(o==null?void 0:o.pi.state)==="configured"&&(m!=null&&m.installed))return null;const b=o==null?void 0:o.pi;return e.jsxs("section",{className:"setup-panel","aria-label":"Draken setup",children:[e.jsx("h2",{children:s?"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."]}),!o&&!N&&e.jsx("p",{className:"small",role:"status",children:"Checking setup…"}),b&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{children:[e.jsxs("strong",{children:["Summarization: ",b.state==="configured"?"credentials configured":b.state==="missing"?"pi not found":b.state==="needs_login"?"sign-in needed":"needs attention"]}),e.jsxs("span",{className:"small muted",children:[" · ",b.source==="managed"?"Draken-private pi":"Existing / external pi",b.version&&` ${b.version}`]})]}),e.jsx("p",{className:"small",children:b.message}),b.state!=="configured"&&e.jsxs("div",{className:"setup-commands",children:[["missing","incompatible"].includes(b.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:b.models.map(g=>e.jsxs("li",{children:[g.model," · ",g.state.replace(/_/g," ")]},g.model))}),e.jsxs("p",{className:"small muted source-path",children:["Pi credential directory: ",b.agent_dir]})]}),m&&e.jsx("p",{children:e.jsxs("strong",{children:["ChatGPT voice: ",m.installed?"helper and sign-in configured":"setup needed"]})}),m&&!m.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||s||(b==null?void 0:b.state)!=="configured"||!(m!=null&&m.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."]}),o&&e.jsxs("p",{className:"small muted source-path",children:["Draken data: ",o.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."]})]}),N&&e.jsx("p",{className:"small",role:"alert",children:N}),e.jsx("button",{type:"button",className:"btn btn-secondary",disabled:p,onClick:()=>x(g=>g+1),children:p?"Checking…":"Check setup again"})]})}function As({active:t,indexing:s,controls:n=!1,disabled:a=!1,onBusyChange:i}){const[o,r]=c.useState(null),[m,u]=c.useState(!1),[N,l]=c.useState(""),[p,h]=c.useState("");c.useEffect(()=>{if(!t||m)return;let b=!0;const g=async()=>{try{const C=await rt();b&&(r(C),h(""))}catch(C){b&&h(C instanceof Error?C.message:"Could not read summary preparation status")}};g();const A=setInterval(()=>void g(),4e3);return()=>{b=!1,clearInterval(A)}},[t,m]);const k=async b=>{u(!0),i==null||i(!0),l("");try{r(await it(b))}catch(g){l(g instanceof Error?g.message:"Could not save summary preparation settings")}finally{u(!1),i==null||i(!1)}},x=o&&{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."}[o.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:(o==null?void 0:o.enabled)||!1,disabled:!o||m||a||!s&&!o.enabled,onChange:b=>void k(b.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."})]}),o&&(n||o.enabled)&&e.jsxs(e.Fragment,{children:[e.jsx("p",{role:"status",className:"small muted",children:!s&&o.enabled?"Summary preparation is paused while automatic indexing is off.":x}),o.last_completed_at&&e.jsxs("p",{className:"small muted",children:["Last successful background pass: ",o.prepared_entries.toLocaleString()," entries, ",new Date(o.last_completed_at).toLocaleString(),". Later changes may still need preparation."]}),o.error&&e.jsx("p",{role:"alert",children:o.error}),n&&o.enabled&&o.status==="error"&&e.jsx("button",{type:"button",className:"btn btn-secondary",disabled:m||a||!s,onClick:()=>void k(!0),children:"Retry summary preparation"})]}),m&&e.jsx("p",{role:"status",children:"Saving summary preparation…"}),(N||p)&&e.jsx("p",{role:"alert",className:"small",children:N||p})]})}function Ps({settings:t}){const s={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."}[t.phase];return e.jsxs("section",{className:"history-progress","aria-label":"Automatic indexing",children:[e.jsx("p",{role:"status",children:e.jsx("strong",{children:s})}),t.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"small muted",children:[t.pending_records.toLocaleString()," source changes waiting for local indexing. ",t.last_completed_at&&`Last completed indexing batch: ${new Date(t.last_completed_at).toLocaleString()}.`]}),e.jsxs("p",{className:"small muted",children:[t.pending_entries.toLocaleString()," entries available for your next sync. History accumulates without creating snapshots or briefings."]})]}),t.error&&e.jsx("p",{role:"alert",children:t.error}),e.jsx(He,{enabled:t.enabled&&t.phase==="indexing",backgroundOnly:!0})]})}function $t(){const[t,s]=c.useState(null),[n,a]=c.useState(!1);return c.useEffect(()=>{let i=!0;const o=async()=>{try{const m=await ks();i&&(s(m),a(!1))}catch{i&&a(!0)}};o();const r=setInterval(()=>void o(),4e3);return()=>{i=!1,clearInterval(r)}},[]),n?e.jsx("p",{role:"status",className:"small muted",children:"Automatic indexing status is temporarily unavailable."}):t!=null&&t.enabled?e.jsxs(e.Fragment,{children:[e.jsx(Ps,{settings:t}),t.summary_enabled&&e.jsx(As,{active:!0,indexing:t.enabled})]}):null}const Ot=t=>new Date(t).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"});function Ut({navigate:t}){const[s,n]=c.useState(null),[a,i]=c.useState(""),[o,r]=c.useState(""),[m,u]=c.useState(""),[N,l]=c.useState(!1),[p,h]=c.useState(!1),k=c.useRef(!0),x=c.useRef(!1),b=c.useRef(),g=async()=>{const d=await Ze();k.current&&n(w=>w&&w.syncs.length>20?{...d,syncs:[...d.syncs,...w.syncs.filter(f=>{var v;return f.id<((v=d.syncs[d.syncs.length-1])==null?void 0:v.id)})],next_cursor:w.next_cursor}:d)};c.useEffect(()=>{k.current=!0,g().catch(w=>r(w.message)),window.isSecureContext||X("/status").then(w=>{if(k.current&&w.httpsPort){const f=new URL("/",location.href);f.protocol="https:",f.port=String(w.httpsPort),u(f.href)}}).catch(()=>{});const d=setInterval(()=>{x.current||g().catch(()=>{})},4e3);return()=>{k.current=!1,clearInterval(d)}},[]);const A=async(d="call")=>{if(!x.current){x.current=!0,i("Collecting new activity…"),r(""),b.current||(b.current=Ss());try{if(d==="call"){const f=await X("/status");if(!f.installed)throw new Error("Voice is not ready on this server. Complete voice setup before starting a sync call.");if(f.activeCall)throw new Error("End the existing call before starting another sync.")}const w=await(d==="chat"?ct:ot)(b.current);k.current&&t(`/syncs/${w.sync.id}${d==="chat"?"/chat":""}`,d==="call")}catch(w){k.current&&r(w instanceof Error?w.message:"Could not start the sync")}finally{x.current=!1,k.current&&i("")}}},C=!!(!N||a||s!=null&&s.busy||s!=null&&s.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:!s||!p||!!(a||s!=null&&s.busy||s!=null&&s.active_call),onClick:()=>void A("chat"),children:[e.jsx(ys,{size:17}),"Chat instead"]}),m?e.jsxs("a",{className:"btn btn-primary",href:m,children:["Open secure Draken",e.jsx(os,{size:17})]}):e.jsxs("button",{className:"btn btn-primary",disabled:!s||C||!window.isSecureContext,onClick:()=>void A(),children:[e.jsx(We,{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. 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:(s==null?void 0:s.available)??"—"})," not yet in a sync"]}),e.jsxs("span",{children:[e.jsx("strong",{children:(s==null?void 0:s.included_unreviewed)??"—"})," included, not reviewed"]}),e.jsxs("span",{children:[e.jsx("strong",{children:(s==null?void 0:s.covered)??"—"})," reviewed"]})]}),e.jsx($t,{}),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. Smaller tails wait for explicit foreground preparation; there is no timed flush. 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]}),(s==null?void 0:s.busy)&&!a&&e.jsx("p",{className:"small muted",role:"status",children:"Draken is updating a sync. Open its card to follow progress."}),(s==null?void 0:s.active_call)&&e.jsx("p",{className:"small muted",children:"A call is active. End it before starting another sync."}),o&&e.jsx("div",{className:"alert error",role:"alert",children:o}),e.jsx(Es,{firstRun:!!(s&&!s.syncs.length),onReady:l,onTextReady:h}),e.jsxs("section",{className:"sync-feed","aria-label":"Sync history",children:[s==null?void 0:s.syncs.map(d=>e.jsxs("a",{className:"card sync-tile",href:`/syncs/${d.id}`,onClick:w=>me(w,t,`/syncs/${d.id}`),children:[e.jsxs("div",{className:"sync-tile-heading",children:[e.jsxs("strong",{children:["Sync #",d.id]}),e.jsx("span",{className:`status ${d.status}`,children:d.busy?"working":d.active_call?"in call":d.needs_retry?"needs retry":d.status==="completed"?"reviewed":d.status==="open"?"open":"discarded"}),e.jsx(os,{size:17,"aria-hidden":"true"})]}),e.jsxs("div",{className:"small muted",children:[Ot(d.created_at)," · ",d.item_count," ",d.item_count===1?"entry":"entries"," · ",d.calls," ",d.calls===1?"call":"calls",d.aggregation_cost&&e.jsxs(e.Fragment,{children:[" · ",e.jsx(Cs,{cost:d.aggregation_cost})]})]}),e.jsx("p",{className:"sync-tile-preview",children:d.preview||(d.needs_retry?"Preparation stopped. Open this sync to retry; its entries and cached work are retained.":d.busy?"Bringing the new activity together. Open this sync to follow preparation.":"No recap yet. Open this sync to continue the conversation.")}),e.jsx("span",{className:"sync-tile-kind small muted",children:d.preview_kind==="recap"?"Conversation recap · not saved decisions":d.preview_kind==="previous_recap"?"Earlier recap · conversation changed":d.preview_kind==="briefing"?"Briefing preview":"Frozen snapshot"})]},d.id)),s&&!s.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."})]})]}),(s==null?void 0:s.next_cursor)&&e.jsx("button",{className:"btn btn-secondary",onClick:async()=>{try{const d=await Ze(s.next_cursor);n(w=>w?{...w,syncs:[...w.syncs,...d.syncs.filter(f=>!w.syncs.some(v=>v.id===f.id))],next_cursor:d.next_cursor}:d)}catch(d){r(d instanceof Error?d.message:"Could not load history")}},children:"Older syncs"})]})}function Ft({navigate:t,reference:s}){const[n,a]=c.useState(null),[i,o]=c.useState(""),[r,m]=c.useState(""),[u,N]=c.useState(!1),l=c.useRef();return c.useEffect(()=>()=>{var p;return(p=l.current)==null?void 0:p.abort()},[]),e.jsxs("main",{className:"sync-home history-page",children:[e.jsx("a",{className:"back-link",href:"/",onClick:p=>me(p,t,"/"),children:"All syncs"}),e.jsx("h1",{children:s?"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."}),s?e.jsxs(e.Fragment,{children:[e.jsx(Ns,{reference:s},s),e.jsx("p",{children:e.jsx("a",{href:"/history",onClick:p=>me(p,t,"/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 p=>{p.preventDefault(),N(!0),m(""),a(null);const h=new AbortController;l.current=h;try{const k=await wt({question:i},h.signal);h.signal.aborted||a(k)}catch(k){h.signal.aborted||m(k instanceof Error?k.message:"Search failed")}finally{N(!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:p=>o(p.target.value),placeholder:"Why did we change that approach?"}),e.jsxs("div",{className:"history-actions",children:[e.jsx("button",{className:"btn btn-primary",disabled:u||!i.trim(),children:u?"Searching…":"Search history"}),u&&e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>{var p;return(p=l.current)==null?void 0:p.abort()},children:"Cancel search"})]}),e.jsx(He,{enabled:u,waiting:!0})]}),r&&e.jsx("p",{className:"alert error",role:"alert",children:r}),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(p=>e.jsxs("article",{className:"card history-result",children:[e.jsx("h2",{children:e.jsx("a",{href:`/history/${p.ref}`,target:"_blank",rel:"noopener noreferrer",children:p.title})}),e.jsx(Xe,{record:p}),e.jsx("pre",{className:"history-excerpt",children:p.text}),e.jsx("a",{href:`/history/${p.ref}`,target:"_blank",rel:"noopener noreferrer",children:"Read source and surrounding context"})]},p.ref)),e.jsx("p",{className:"small muted",children:n.limitations})]})]})]})}const gs=t=>new Date(t).toLocaleString(),zt={pi:"pi v3 JSONL",codex:"Rollout JSONL",claude:"Transcript JSONL"};function Ht({open:t}){const[s,n]=c.useState(!1),[a,i]=c.useState(null),[o,r]=c.useState(!0),[m,u]=c.useState(!1),[N,l]=c.useState(""),[p,h]=c.useState(""),[k,x]=c.useState(null),b=c.useRef(!0),g=c.useRef(!1);c.useEffect(()=>(b.current=!0,()=>{b.current=!1}),[]),c.useEffect(()=>{if(!t||!s||m)return;let d=!0;const w=async()=>{try{const[v,E]=await Promise.all([ds(),Ze()]);d&&!g.current&&(i(v),r(E.busy||E.active_call),h(""))}catch(v){d&&!g.current&&h(v instanceof Error?v.message:"Could not read session sources")}};w();const f=setInterval(()=>void w(),4e3);return()=>{d=!1,clearInterval(f)}},[t,s,m]);const A=async(d,w)=>{if(!a||o||p||g.current)return;const f=a;g.current=!0,u(!0),l(""),w&&i(w);try{const v=await d();b.current&&i(v)}catch(v){b.current&&(w&&i(f),l(v instanceof Error?v.message:"Could not update session sources"))}finally{g.current=!1,b.current&&u(!1)}},C=!a||o||m||!!p;return e.jsxs("details",{className:"source-settings",onToggle:d=>n(d.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:C||!(a!=null&&a.agents.some(d=>d.enabled)),onClick:()=>void A(async()=>{const d=await dt();return b.current&&x(d),ds()}),children:[e.jsx(Js,{size:15,"aria-hidden":"true"}),"Scan enabled agents"]}),o&&a&&e.jsx("p",{className:"small muted",children:"Source changes are paused while a call or sync preparation is active."}),m&&e.jsx("p",{className:"small muted",role:"status",children:"Updating session sources…"}),a==null?void 0:a.agents.map(d=>{const w=a.sessions.filter(f=>f.agent===d.id);return e.jsxs("section",{className:"agent-source","aria-labelledby":`${d.id}-source-title`,children:[e.jsxs("div",{className:"section-heading",children:[e.jsx("h3",{id:`${d.id}-source-title`,children:d.name}),e.jsx("span",{className:"status",children:zt[d.id]})]}),e.jsxs("label",{className:"index-toggle",children:[e.jsx("input",{type:"checkbox",role:"switch","aria-label":`Enable ${d.name} history`,checked:d.enabled,disabled:C,onChange:f=>{const v=f.target.checked;A(()=>ht(d.id,v),{...a,agents:a.agents.map(E=>E.id===d.id?{...E,enabled:v}:E)})}}),e.jsxs("span",{children:[e.jsxs("strong",{children:["Include ",d.name," history"]}),e.jsx("span",{className:"small muted",children:d.enabled?"Enabled for scanning and future syncs":"Off — transcripts are not scanned or indexed"})]})]}),d.roots.map(f=>e.jsxs("div",{children:[e.jsx("p",{className:"small muted",children:f.status==="present"?"Directory found":f.status==="missing"?"Directory not found":"Directory unavailable"}),e.jsx("code",{className:"source-path",children:f.path})]},f.path)),e.jsxs("p",{className:"small muted",children:[w.length," recorded sessions · ",w.filter(f=>f.included).length," selected · ",w.filter(f=>f.missing).length," unavailable at last scan"]}),!w.length&&e.jsxs("p",{className:"small muted",children:["No ",d.name," sessions recorded yet.",d.enabled?" Scan enabled agents to discover them.":" Enable this source before scanning."]}),e.jsx("div",{className:"session-list","aria-label":`Discovered ${d.name} sessions`,children:w.map(f=>e.jsxs("label",{className:"session-source",children:[e.jsx("input",{type:"checkbox",checked:!!f.included,disabled:C||!d.enabled||!!f.missing,"aria-label":`Include ${f.name||"session"} (${f.id})`,onChange:v=>{const E=v.target.checked;A(()=>ut(f.id,E),{...a,sessions:a.sessions.map(F=>F.id===f.id?{...F,included:Number(E)}:F)})}}),e.jsxs("span",{children:[e.jsx("strong",{children:f.name||f.cwd.split(/[\\/]/).filter(Boolean).pop()||f.id}),e.jsx("span",{className:"source-cwd",title:f.cwd,children:f.cwd||"Workspace unavailable"}),e.jsxs("span",{className:"small",children:[f.included?"Selected":"Excluded"," · ",f.pending," unreviewed ",f.pending===1?"entry":"entries",f.missing?" · unavailable at last scan":""]}),e.jsxs("span",{className:"source-session-meta small muted",children:["Session ",f.external_id||f.id," · Last recorded change: ",gs(f.modified_at)]}),e.jsx("code",{className:"source-path",children:f.path})]})]},f.id))})]},d.id)}),a&&e.jsxs("p",{className:"small muted",children:[a.history_initialized&&a.history_since?`Existing history baseline: ${gs(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((d,w)=>e.jsx("li",{children:d},w))}),(N||p)&&e.jsx("p",{className:"small",role:"alert",children:N||p})]})}const ze=t=>t===null?"Unavailable":t>0&&t<1e-6?"<$0.000001":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:t<.01?6:2}).format(t),he=t=>t.slice(0,16).replace("T"," "),Q=t=>t.toLocaleString();function Vt(t,s){const n=(t||1)/4,a=10**Math.floor(Math.log10(n)),i=Math.max(s?1:Number.MIN_VALUE,[1,2,5,10].find(N=>N*a>=n)*a),o=Math.max(1,Math.ceil((t||1)/i)),r=o*i,m=Math.max(2,-Math.floor(Math.log10(i))),u=N=>s?Q(N):N===0?"$0":i<1e-6||r>=1e9?`$${Number(N.toPrecision(3)).toExponential()}`:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:Math.min(6,m)}).format(N);return{maximum:r,ticks:Array.from({length:o+1},(N,l)=>({fraction:l/o,label:u(l*i)}))}}function Bt({active:t}){const[s,n]=c.useState("7d"),[a,i]=c.useState("1h"),[o,r]=c.useState("cost"),[m,u]=c.useState(null),[N,l]=c.useState("");if(c.useEffect(()=>{if(!t)return;const d=new AbortController;let w=!1;u(null),l("");const f=async()=>{if(!w){w=!0;try{const E=await nt(s,a,d.signal);d.signal.aborted||(u(E),l(""))}catch(E){d.signal.aborted||(u(null),l(E instanceof Error?E.message:"Could not load preparation usage"))}finally{w=!1}}};f();const v=setInterval(()=>void f(),15e3);return()=>{d.abort(),clearInterval(v)}},[t,s,a]),!t)return null;const p=(m==null?void 0:m.range)===s&&m.bucket===a?m:null,h=p==null?void 0:p.totals,k=(p==null?void 0:p.buckets.map(d=>o==="cost"?d.cost.usd||0:d.completed_batches))||[],x=Math.max(0,...k),b=Vt(x,o==="batches"),g=o==="cost"&&(h==null?void 0:h.cost.usd)===null,A=g?[]:b.ticks,C=o==="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:s,onChange:d=>n(d.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:d=>i(d.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:o,onChange:d=>r(d.target.value),children:[e.jsx("option",{value:"cost",children:"Estimated cost"}),e.jsx("option",{value:"batches",children:"Completed batches"})]})]})]}),N?e.jsxs("p",{role:"alert",children:["Usage unavailable: ",N]}):p?h&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"usage-totals",children:[e.jsxs("div",{children:[e.jsx("span",{className:"small",children:h.incomplete_pricing?"Known cost subtotal":"Est. preparation cost"}),e.jsx("strong",{children:ze(h.cost.usd)}),e.jsx("span",{className:"small muted",children:h.incomplete_pricing?`${Q(h.incomplete_pricing)} ${h.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:Q(h.completed_batches)}),e.jsxs("span",{className:"small muted",children:[Q(h.entries)," entries across these batches"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"small",children:"Model requests"}),e.jsx("strong",{children:Q(h.requests)}),e.jsxs("span",{className:"small muted",children:[Q(p.active_attempts)," preparation ",p.active_attempts===1?"attempt":"attempts"," active now"]})]})]}),e.jsxs("p",{className:"small muted",children:[he(p.from)," – ",he(p.to)," UTC. Refreshes every 15 seconds while Settings is open."]}),!h.requests&&!h.completed_batches&&!h.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:[o==="cost"?"Estimated cost":"Completed batches"," per ",a]}),e.jsx("span",{children:o==="cost"?`Peak known: ${ze(h.cost.usd===null?null:x)}`:`Peak: ${Q(x)}`})]}),e.jsxs("div",{className:"usage-chart-frame",children:[e.jsx("span",{className:"usage-axis-unit small muted","aria-hidden":"true",children:C}),e.jsx("div",{className:"usage-y-axis small muted","aria-hidden":"true",style:{width:`${Math.max(7,...A.map(d=>d.label.length))}ch`},children:A.map(d=>e.jsx("span",{style:{top:`${(119-d.fraction*112)/120*100}%`},children:d.label},d.fraction))}),e.jsxs("svg",{className:"usage-chart",viewBox:"0 0 720 120",preserveAspectRatio:"none",role:"img","aria-label":`${o==="cost"?"Estimated preparation cost":"Completed batches"} by ${a} bucket. Y-axis: ${C}${g?", pricing unavailable":`, ${A[0].label} to ${A[A.length-1].label}`}. Exact values in bucket details below.`,children:[A.map(d=>e.jsx("line",{className:"usage-gridline",x1:"0",y1:119-d.fraction*112,x2:"720",y2:119-d.fraction*112},d.fraction)),p.buckets.map((d,w)=>{const f=o==="cost"&&!d.cost.complete,v=Math.max(k[w]>0?2:f?4:0,k[w]/b.maximum*112);return e.jsx("rect",{x:w/k.length*720,y:119-v,width:Math.max(.5,720/k.length-1),height:v,className:f?"usage-incomplete":void 0,children:e.jsxs("title",{children:[he(d.from)," – ",he(d.to)," UTC: ",o==="cost"?ze(d.cost.usd)+(f?" (incomplete pricing)":""):`${d.completed_batches} batches`,"; ",d.requests," requests"]})},d.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:he(p.from).slice(5)}),e.jsx("span",{children:"UTC"}),e.jsx("span",{children:he(p.to).slice(5)})]})]}),o==="cost"&&h.incomplete_pricing>0&&e.jsxs("p",{className:"small muted",children:[g?"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:[...p.buckets].reverse().map(d=>e.jsxs("tr",{children:[e.jsxs("th",{scope:"row",children:[he(d.from),e.jsx("br",{}),"to ",he(d.to)]}),e.jsx("td",{children:Q(d.completed_batches)}),e.jsx("td",{children:Q(d.requests)}),e.jsxs("td",{children:[ze(d.cost.usd),!d.cost.complete&&" (partial)"]}),e.jsx("td",{children:Q(d.incomplete_pricing)})]},d.from))})]})})]})]}),e.jsxs("p",{className:"small muted",children:[Q(h.failed_attempts)," failed or stopped ",h.failed_attempts===1?"attempt":"attempts"," in this period. ",Q(h.approximate_timing)," ",h.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 Yt(){const[t,s]=c.useState(!1),[n,a]=c.useState(null),[i,o]=c.useState(!1),[r,m]=c.useState(""),[u,N]=c.useState(""),l=c.useRef(null);return c.useEffect(()=>{var p,h,k;t&&!((p=l.current)!=null&&p.open)?(h=l.current)==null||h.showModal():t||(k=l.current)==null||k.close()},[t]),c.useEffect(()=>{if(!t||i)return;let p=!0;const h=async()=>{try{const x=await ks();p&&(a(x),N(""))}catch(x){p&&N(x instanceof Error?x.message:"Could not read settings")}};h();const k=setInterval(()=>void h(),4e3);return()=>{p=!1,clearInterval(k)}},[t,i]),e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:"btn btn-secondary header-settings","aria-haspopup":"dialog",onClick:()=>s(!0),children:[e.jsx(Zs,{size:16,"aria-hidden":"true"}),"Settings"]}),e.jsxs("dialog",{ref:l,className:"settings-dialog","aria-labelledby":"settings-title",onCancel:p=>{p.preventDefault(),s(!1)},onClose:p=>{p.currentTarget.open||s(!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:()=>s(!1),children:e.jsx(Qe,{size:18,"aria-hidden":"true"})})]}),e.jsx(Bt,{active:t}),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 p=>{const h=p.target.checked,k=n;o(!0),m(""),a(x=>x&&{...x,enabled:h});try{a(await cs(h))}catch(x){a(k),m(x instanceof Error?x.message:"Could not save settings")}finally{o(!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. Smaller tails wait for explicit foreground preparation, such as a sync, Prepare history or search; there is no timed flush. Only your Sync with Draken or Chat instead action creates a snapshot and starts its briefing. Calls and foreground work take priority."}),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…"}),(r||u)&&e.jsx("p",{className:"small",role:"alert",children:r||u}),t&&n&&e.jsx(Ps,{settings:n}),(n==null?void 0:n.enabled)&&n.phase==="error"&&e.jsx("button",{type:"button",className:"btn btn-secondary",disabled:i,onClick:async()=>{o(!0),m("");try{a(await cs(!0))}catch(p){m(p instanceof Error?p.message:"Could not retry indexing")}finally{o(!1)}},children:"Retry automatic indexing"}),e.jsx(As,{active:t,indexing:(n==null?void 0:n.enabled)||!1,controls:!0,disabled:i,onBusyChange:o}),e.jsx(Ht,{open:t}),e.jsx(Es,{active:t,always:!0})]})]})}function Gt(){const{isAuthenticated:t,isLoading:s,authEnabled:n,username:a,logout:i}=ws(),[o,r]=c.useState(window.location.pathname),[m,u]=c.useState(null),N=c.useRef(null),l=c.useRef(o),p=c.useCallback(b=>{N.current=b},[]),h=c.useCallback((b,g=!1)=>{N.current&&!N.current()||(window.history.pushState(null,"",b),l.current=b,r(b),u(g?Number(b.split("/").pop()):null),window.scrollTo(0,0))},[]);if(c.useEffect(()=>{const b=()=>{if(N.current&&!N.current()){window.history.pushState(null,"",l.current);return}l.current=window.location.pathname,r(l.current),u(null)};return window.addEventListener("popstate",b),()=>window.removeEventListener("popstate",b)},[]),s)return e.jsxs("div",{className:"app-loading",children:[e.jsx("span",{className:"spinner"}),"Opening Draken…"]});if(!t)return e.jsx(tt,{});const k=/^\/syncs\/([1-9]\d*)(\/chat)?\/?$/.exec(o),x=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:b=>me(b,h,"/"),"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:b=>me(b,h,"/history"),children:"Search history"}),e.jsx(Yt,{}),n&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"muted small",children:a}),e.jsx("button",{className:"icon-button",onClick:()=>{(!N.current||N.current())&&i()},"aria-label":"Sign out",children:e.jsx(Gs,{size:18})})]})]})]}),x&&Number.isSafeInteger(x)?e.jsx(Lt,{id:x,chat:!!(k!=null&&k[2]),callIntent:m===x,consumeIntent:()=>u(null),navigate:h,setGuard:p},x):/^\/history(?:\/H[a-f0-9]{24})?\/?$/.test(o)?e.jsx(Ft,{navigate:h,reference:o.split("/")[2]},o):o==="/"?e.jsx(Ut,{navigate:h}):e.jsxs("main",{className:"sync-home",children:[e.jsx("h1",{children:"Page not found"}),e.jsx("a",{href:"/",onClick:b=>me(b,h,"/"),children:"All syncs"})]})]})}function Kt(){return e.jsx(st,{children:e.jsx(Gt,{})})}Ms.createRoot(document.getElementById("root")).render(e.jsx(qs.StrictMode,{children:e.jsx(Kt,{})}));
|
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-
|
|
9
|
+
<script type="module" crossorigin src="/assets/index-5bTQNQYG.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>
|