draken 0.5.1 → 0.6.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 +19 -0
- package/MEMORY.md +10 -4
- package/PERSONA.md +9 -2
- package/README.md +8 -10
- package/SETUP.md +3 -3
- package/TRAY.md +2 -2
- package/VOICE.md +1 -1
- package/dist/auth/middleware.d.ts.map +1 -1
- package/dist/auth/middleware.js +0 -13
- package/dist/auth/middleware.js.map +1 -1
- package/dist/cli.js +6 -2
- package/dist/cli.js.map +1 -1
- package/dist/data-dir.d.ts +2 -0
- package/dist/data-dir.d.ts.map +1 -0
- package/dist/data-dir.js +12 -0
- package/dist/data-dir.js.map +1 -0
- package/dist/db/evidence.d.ts +2 -1
- package/dist/db/evidence.d.ts.map +1 -1
- package/dist/db/evidence.js +6 -5
- package/dist/db/evidence.js.map +1 -1
- package/dist/db/pointer-migration.js +4 -4
- package/dist/db/pointer-migration.js.map +1 -1
- package/dist/db/schema.d.ts +0 -1
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +7 -7
- package/dist/db/schema.js.map +1 -1
- package/dist/errors.d.ts +5 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +12 -0
- package/dist/errors.js.map +1 -0
- package/dist/memory/context.d.ts +2 -9
- package/dist/memory/context.d.ts.map +1 -1
- package/dist/memory/context.js +7 -84
- package/dist/memory/context.js.map +1 -1
- package/dist/memory/embedding-contract.d.ts +5 -0
- package/dist/memory/embedding-contract.d.ts.map +1 -0
- package/dist/memory/embedding-contract.js +12 -0
- package/dist/memory/embedding-contract.js.map +1 -0
- package/dist/memory/embedding-pool.d.ts +1 -2
- package/dist/memory/embedding-pool.d.ts.map +1 -1
- package/dist/memory/embedding-pool.js +9 -9
- package/dist/memory/embedding-pool.js.map +1 -1
- package/dist/memory/embedding-worker.js +2 -1
- package/dist/memory/embedding-worker.js.map +1 -1
- package/dist/{voice/history-focus.d.ts → memory/focus.d.ts} +6 -6
- package/dist/memory/focus.d.ts.map +1 -0
- package/dist/{voice/history-focus.js → memory/focus.js} +6 -6
- package/dist/memory/focus.js.map +1 -0
- package/dist/memory/index.d.ts.map +1 -1
- package/dist/memory/index.js +12 -15
- package/dist/memory/index.js.map +1 -1
- package/dist/memory/model-assets.d.ts +5 -0
- package/dist/memory/model-assets.d.ts.map +1 -0
- package/dist/memory/model-assets.js +84 -0
- package/dist/memory/model-assets.js.map +1 -0
- package/dist/memory/model.d.ts +2 -7
- package/dist/memory/model.d.ts.map +1 -1
- package/dist/memory/model.js +13 -83
- package/dist/memory/model.js.map +1 -1
- package/dist/memory/packet.d.ts +9 -0
- package/dist/memory/packet.d.ts.map +1 -0
- package/dist/memory/packet.js +78 -0
- package/dist/memory/packet.js.map +1 -0
- package/dist/memory/passages.d.ts +15 -0
- package/dist/memory/passages.d.ts.map +1 -0
- package/dist/memory/passages.js +22 -0
- package/dist/memory/passages.js.map +1 -0
- package/dist/memory/readiness.d.ts.map +1 -1
- package/dist/memory/readiness.js +2 -6
- package/dist/memory/readiness.js.map +1 -1
- package/dist/memory/service.d.ts +2 -1
- package/dist/memory/service.d.ts.map +1 -1
- package/dist/memory/service.js +46 -22
- package/dist/memory/service.js.map +1 -1
- package/dist/memory/sources.d.ts +0 -1
- package/dist/memory/sources.d.ts.map +1 -1
- package/dist/memory/sources.js +3 -7
- package/dist/memory/sources.js.map +1 -1
- package/dist/memory/stamps.d.ts +3 -3
- package/dist/memory/stamps.d.ts.map +1 -1
- package/dist/memory/stamps.js +3 -3
- package/dist/memory/stamps.js.map +1 -1
- package/dist/memory/storage.d.ts.map +1 -1
- package/dist/memory/storage.js +3 -2
- package/dist/memory/storage.js.map +1 -1
- package/dist/memory/types.d.ts +2 -1
- package/dist/memory/types.d.ts.map +1 -1
- package/dist/memory/types.js +2 -1
- package/dist/memory/types.js.map +1 -1
- package/dist/pi/runtime.js +7 -7
- package/dist/pi/runtime.js.map +1 -1
- package/dist/pi/setup.d.ts +0 -1
- package/dist/pi/setup.d.ts.map +1 -1
- package/dist/pi/setup.js +2 -11
- package/dist/pi/setup.js.map +1 -1
- package/dist/routes/auth.d.ts.map +1 -1
- package/dist/routes/auth.js +0 -5
- package/dist/routes/auth.js.map +1 -1
- package/dist/routes/http.d.ts +6 -0
- package/dist/routes/http.d.ts.map +1 -0
- package/dist/routes/http.js +22 -0
- package/dist/routes/http.js.map +1 -0
- package/dist/routes/live-voice.d.ts.map +1 -1
- package/dist/routes/live-voice.js +18 -32
- package/dist/routes/live-voice.js.map +1 -1
- package/dist/routes/memory.d.ts.map +1 -1
- package/dist/routes/memory.js +8 -14
- package/dist/routes/memory.js.map +1 -1
- package/dist/routes/sync.d.ts.map +1 -1
- package/dist/routes/sync.js +57 -64
- package/dist/routes/sync.js.map +1 -1
- package/dist/routes/voice.d.ts.map +1 -1
- package/dist/routes/voice.js +7 -7
- package/dist/routes/voice.js.map +1 -1
- package/dist/server-ownership.d.ts +5 -0
- package/dist/server-ownership.d.ts.map +1 -0
- package/dist/server-ownership.js +34 -0
- package/dist/server-ownership.js.map +1 -0
- package/dist/server-state.js +3 -3
- package/dist/server-state.js.map +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +40 -10
- package/dist/server.js.map +1 -1
- package/dist/sync/activity.d.ts +26 -0
- package/dist/sync/activity.d.ts.map +1 -0
- package/dist/sync/activity.js +80 -0
- package/dist/sync/activity.js.map +1 -0
- package/dist/{memory/automatic.d.ts → sync/background.d.ts} +5 -12
- package/dist/sync/background.d.ts.map +1 -0
- package/dist/{memory/automatic.js → sync/background.js} +29 -74
- package/dist/sync/background.js.map +1 -0
- package/dist/sync/collector.d.ts.map +1 -1
- package/dist/sync/collector.js +7 -6
- package/dist/sync/collector.js.map +1 -1
- package/dist/sync/manager.d.ts +1 -4
- package/dist/sync/manager.d.ts.map +1 -1
- package/dist/sync/manager.js +29 -49
- package/dist/sync/manager.js.map +1 -1
- package/dist/sync/models.d.ts +3 -0
- package/dist/sync/models.d.ts.map +1 -0
- package/dist/sync/models.js +12 -0
- package/dist/sync/models.js.map +1 -0
- package/dist/sync/pi.d.ts +1 -1
- package/dist/sync/pi.d.ts.map +1 -1
- package/dist/sync/pi.js +32 -19
- package/dist/sync/pi.js.map +1 -1
- package/dist/{voice → sync}/preparation.d.ts +0 -1
- package/dist/sync/preparation.d.ts.map +1 -0
- package/dist/{voice → sync}/preparation.js +10 -18
- package/dist/sync/preparation.js.map +1 -0
- package/dist/sync/retrieval.d.ts +3 -0
- package/dist/sync/retrieval.d.ts.map +1 -0
- package/dist/sync/retrieval.js +12 -0
- package/dist/sync/retrieval.js.map +1 -0
- package/dist/sync/source-files.d.ts +2 -4
- package/dist/sync/source-files.d.ts.map +1 -1
- package/dist/sync/source-files.js +5 -20
- package/dist/sync/source-files.js.map +1 -1
- package/dist/sync/store.d.ts +1 -14
- package/dist/sync/store.d.ts.map +1 -1
- package/dist/sync/store.js +32 -90
- package/dist/sync/store.js.map +1 -1
- package/dist/sync/tree.d.ts.map +1 -1
- package/dist/sync/tree.js +17 -22
- package/dist/sync/tree.js.map +1 -1
- package/dist/sync/usage.js +3 -3
- package/dist/sync/usage.js.map +1 -1
- package/dist/tray/launcher.js +2 -2
- package/dist/tray/launcher.js.map +1 -1
- package/dist/tray/worker.js +4 -4
- package/dist/tray/worker.js.map +1 -1
- package/dist/types.d.ts +1 -10
- package/dist/types.d.ts.map +1 -1
- package/dist/voice/history-delivery.js +3 -3
- package/dist/voice/history-delivery.js.map +1 -1
- package/dist/voice/live-context.js +3 -3
- package/dist/voice/live-context.js.map +1 -1
- package/dist/voice/live.d.ts +1 -0
- package/dist/voice/live.d.ts.map +1 -1
- package/dist/voice/live.js +57 -34
- package/dist/voice/live.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/index-DXPfCm7z.js +131 -0
- package/public/index.html +1 -1
- package/voice/realtime/README.md +1 -1
- package/voice/realtime/helper-process.mjs +54 -0
- package/voice/realtime/native.mjs +55 -15
- package/voice/realtime/probe-server.mjs +24 -4
- package/voice/realtime/probe.mjs +49 -11
- package/voice/realtime/rpc.mjs +7 -32
- package/voice/realtime/setup.mjs +82 -19
- package/dist/memory/automatic.d.ts.map +0 -1
- package/dist/memory/automatic.js.map +0 -1
- package/dist/sync/automatic.d.ts +0 -7
- package/dist/sync/automatic.d.ts.map +0 -1
- package/dist/sync/automatic.js +0 -56
- package/dist/sync/automatic.js.map +0 -1
- package/dist/voice/history-focus.d.ts.map +0 -1
- package/dist/voice/history-focus.js.map +0 -1
- package/dist/voice/preparation.d.ts.map +0 -1
- package/dist/voice/preparation.js.map +0 -1
- package/public/assets/index-DrGvDGTG.js +0 -131
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
var Ts=Object.defineProperty;var rs=t=>{throw TypeError(t)};var Ps=(t,s,a)=>s in t?Ts(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var _=(t,s,a)=>Ps(t,typeof s!="symbol"?s+"":s,a),is=(t,s,a)=>s.has(t)||rs("Cannot "+a);var y=(t,s,a)=>(is(t,s,"read from private field"),a?a.call(t):s.get(t)),U=(t,s,a)=>s.has(t)?rs("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(t):s.set(t,a),q=(t,s,a,n)=>(is(t,s,"write to private field"),n?n.call(t,a):s.set(t,a),a);import{r as o,j as e,P as _s,R as Is,a as Ms}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,a,n)=>!!s&&s.trim()!==""&&n.indexOf(s)===a).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 qs={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 Rs=o.forwardRef(({color:t="currentColor",size:s=24,strokeWidth:a=2,absoluteStrokeWidth:n,className:i="",children:c,iconNode:r,...m},u)=>o.createElement("svg",{ref:u,...qs,width:s,height:s,stroke:t,strokeWidth:n?Number(a)*24/Number(s):a,className:fs("lucide",i),...m},[...r.map(([j,l])=>o.createElement(j,l)),...Array.isArray(c)?c:[c]]));/**
|
|
17
|
+
* @license lucide-react v0.468.0 - ISC
|
|
18
|
+
*
|
|
19
|
+
* This source code is licensed under the ISC license.
|
|
20
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
21
|
+
*/const D=(t,s)=>{const a=o.forwardRef(({className:n,...i},c)=>o.createElement(Rs,{ref:c,iconNode:s,className:fs(`lucide-${Ds(t)}`,n),...i}));return a.displayName=`${t}`,a};/**
|
|
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=D("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=D("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=D("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 Ls=D("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 Os=D("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 Us=D("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 Fs=D("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 zs=D("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 Hs=D("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=D("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 Vs=D("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 Ys=D("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=D("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 Gs=D("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 Ks=D("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 Ws=D("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=D("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 Qs=D("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 Js=D("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=D("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 Zs=D("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=D("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 Xs(t,s){localStorage.setItem(ss,t),localStorage.setItem(ts,s)}function Je(){localStorage.removeItem(ss),localStorage.removeItem(ts)}function ns(){const{token:t}=js();return t?{Authorization:`Bearer ${t}`}:{}}const bs=o.createContext(null),Ee={isAuthenticated:!1,isLoading:!1,authEnabled:!0,username:null};function et({children:t}){const[s,a]=o.useState({...Ee,isLoading:!0});o.useEffect(()=>{let c=!0;const r=u=>{c&&a(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:v}=js();if(!l){r(Ee);return}(await fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${l}`}})).ok?r({isAuthenticated:!0,isLoading:!1,authEnabled:!0,username:v}):(c&&Je(),r(Ee))}catch(u){console.error("Auth check failed:",u),r(Ee)}})(),()=>{c=!1}},[]);const n=async(c,r)=>{const m=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:c,password:r})}),u=await m.json();if(!m.ok)throw new Error(u.error||"Login failed");Xs(u.token,u.username),a({isAuthenticated:!0,isLoading:!1,authEnabled:!0,username:u.username})},i=()=>{Je(),a(Ee)};return e.jsx(bs.Provider,{value:{...s,login:n,logout:i},children:t})}function ws(){const t=o.useContext(bs);if(!t)throw new Error("useAuth must be used within an AuthProvider");return t}function st(){const{login:t}=ws(),[s,a]=o.useState(""),[n,i]=o.useState(""),[c,r]=o.useState(null),[m,u]=o.useState(!1),j=async l=>{l.preventDefault(),r(null),u(!0);try{await t(s,n)}catch(v){r(v instanceof Error?v.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:j,className:"login-form",children:[c&&e.jsxs("div",{className:"login-error",role:"alert",children:[e.jsx(Us,{size:16}),c]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"username",children:"Username"}),e.jsxs("div",{className:"input-with-icon",children:[e.jsx(Zs,{size:18,className:"input-icon"}),e.jsx("input",{id:"username",type:"text",className:"input",placeholder:"Enter username",value:s,onChange:l=>a(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:n,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||!n,children:m?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"spinner spinner-sm"})," Signing in..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Vs,{size:18})," Sign In"]})})]})]})})}async function P(t,s="GET",a,n){const i=await fetch(`/api${t}`,{method:s,signal:n,headers:{"Content-Type":"application/json",...ns()},body:a===void 0?void 0:JSON.stringify(a)});if(i.status===401)throw Je(),window.location.reload(),new Error("Authentication required");if(i.status===204)return;const c=await i.json();if(!i.ok)throw new Error(c.error||`Request failed (${i.status})`);return c}const tt=(t=!1)=>P(`/setup${t?"?refresh=1":""}`),nt=(t,s,a)=>P(`/settings/preparation-usage?range=${t}&bucket=${s}`,"GET",void 0,a),ks=()=>P("/settings/auto-index"),cs=t=>P("/settings/auto-index","PATCH",{enabled:t}),Ze=t=>P(`/home${t?`?before=${t}`:""}`),at=t=>P("/syncs/start-call","POST",{request_id:t}),rt=t=>P("/syncs/start-chat","POST",{request_id:t}),it=(t,s,a)=>P(`/syncs/${t}/chat/messages`,"POST",{message:s,request_id:a}),ls=t=>P(`/syncs/${t}/recap`,"POST"),ds=()=>P("/overview"),ot=()=>P("/scan","POST"),ct=(t,s)=>P(`/agents/${encodeURIComponent(t)}`,"PATCH",{enabled:s}),lt=(t,s)=>P(`/sessions/${encodeURIComponent(t)}`,"PATCH",{included:s}),Ye=t=>P(`/syncs/${t}`),dt=t=>P(`/syncs/${t}/progress`),hs=(t,s)=>P(`/syncs/${t}/call-readiness`,"GET",void 0,s),ht=(t,s)=>P(`/syncs/${t}/chat-readiness`,"GET",void 0,s),ut=t=>P(`/syncs/${t}/prepare-call`,"POST"),pt=(t,s)=>P(`/syncs/${t}/tree/${s}`),mt=t=>P(`/syncs/${t}/expand`,"POST"),gt=t=>P(`/syncs/${t}/cancel`,"POST"),ft=t=>P(`/syncs/${t}/briefing`,"POST"),xt=(t,s)=>P(`/syncs/${t}/messages`,"POST",{message:s}),yt=t=>P("/memory/progress","GET",void 0,t),vt=(t,s)=>P("/memory/search","POST",t,s),jt=(t,s=0,a)=>P(`/memory/records/${encodeURIComponent(t)}?offset=${s}`,"GET",void 0,a),Ae=(t,s,a)=>P(`/syncs/${t}/notes`,"PATCH",{decisions:s,carry_forward:a}),bt=(t,s,a)=>P(`/syncs/${t}/complete`,"POST",{decisions:s,carry_forward:a,reviewed:!0}),wt=t=>P(`/syncs/${t}/discard`,"POST"),Te=25;function us({items:t,title:s}){const[a,n]=o.useState(0),[i,c]=o.useState(""),[r,m]=o.useState("");if(o.useEffect(()=>{const h=S=>{const b=S.detail,k=t.findIndex(g=>g.ref===b);k<0||(c(""),n(Math.floor(k/Te)),m(b))};return window.addEventListener("draken:evidence",h),()=>window.removeEventListener("draken:evidence",h)},[t]),o.useEffect(()=>{if(!r)return;const h=document.getElementById(`evidence-${r}`);h&&(h.open=!0,h.scrollIntoView({behavior:"smooth",block:"center"}),m(""))},[r,a,i]),!t.length)return null;const u=i.toLocaleLowerCase(),j=u?t.filter(h=>`${h.ref} ${h.session_name} ${h.cwd} ${h.text}`.toLocaleLowerCase().includes(u)):t,l=Math.max(1,Math.ceil(j.length/Te)),v=Math.min(a,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>Te&&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=>{c(h.target.value),n(0)}}),e.jsxs("div",{className:"pagination",children:[e.jsx("button",{className:"btn btn-secondary",disabled:v===0,onClick:()=>n(v-1),children:"Previous"}),e.jsxs("span",{children:[v+1," / ",l," · ",j.length," entries"]}),e.jsx("button",{className:"btn btn-secondary",disabled:v>=l-1,onClick:()=>n(v+1),children:"Next"})]})]}),e.jsx("div",{className:"evidence-list",children:j.slice(v*Te,(v+1)*Te).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 a=new Set(s.map(n=>n.ref));return e.jsx("div",{className:"prose",children:t.split(/(\[(?:[EC]\d+|H[a-f0-9]{24})\])/g).map((n,i)=>{const c=n.slice(1,-1);return/^H[a-f0-9]{24}$/.test(c)?e.jsxs("a",{className:"citation",href:`/history/${c}`,target:"_blank",rel:"noopener noreferrer","aria-label":`Inspect historical source ${c}`,children:["[history ",c.slice(-6),"]"]},i):!/^\[(E|C)\d+\]$/.test(n)||!a.has(c)?e.jsx("span",{children:n},i):e.jsx("button",{className:"citation",onClick:()=>window.dispatchEvent(new CustomEvent("draken:evidence",{detail:c})),"aria-label":`Inspect evidence ${c}`,children:n},i)})})}function kt({syncId:t,progress:s,evidence:a,onCancel:n,onResume:i,resumeEnabled:c}){var p;const[r,m]=o.useState(new Set),[u,j]=o.useState(null),[l,v]=o.useState(""),[h,S]=o.useState(!1),b=s.run;if(o.useEffect(()=>{j(null),m(new Set)},[b==null?void 0:b.id]),!b)return null;const k=!s.busy&&["failed","cancelled","interrupted"].includes(b.status),g=new Map(s.nodes.map(x=>[x.key,x])),T=new Set(s.nodes.flatMap(x=>x.children)),E=s.nodes.filter(x=>!T.has(x.key)),d=async x=>{S(!0),v("");try{j(await pt(t,x.key))}catch(C){v(C instanceof Error?C.message:"Could not load summary")}finally{S(!1)}},w=(x,C=new Set)=>{if(C.has(x.key))return null;const F=new Set([...C,x.key]),ee=r.has(x.key);return e.jsxs("li",{children:[e.jsxs("div",{className:"tree-node",children:[e.jsx("button",{className:"tree-toggle","aria-label":`Expand ${x.label}`,disabled:!x.children.length,onClick:()=>m(I=>{const R=new Set(I);return R.has(x.key)?R.delete(x.key):R.add(x.key),R}),children:x.children.length?ee?"▾":"▸":"·"}),e.jsxs("button",{className:"tree-label",disabled:!["done","cached"].includes(x.status)||h,onClick:()=>void d(x),title:x.error||x.label,children:[e.jsx("span",{className:"role-label",children:x.kind})," ",x.label]}),e.jsx("span",{className:`status ${x.status}`,children:x.status})]}),ee&&e.jsx("ul",{children:x.children.map(I=>g.has(I)?w(g.get(I),F):null)})]},x.key)};return e.jsxs("section",{className:"card tree-card",children:[e.jsxs("div",{className:"section-heading",children:[e.jsx("h2",{children:"Summary tree"}),e.jsx("span",{className:`status ${b.status}`,children:b.status})]}),e.jsx("p",{className:"small muted",children:"Complete source batches → compact reconciliation → final verdict"}),e.jsx("progress",{max:Math.max(1,b.total_entries),value:b.processed_entries,"aria-label":"Evidence compression progress"}),e.jsxs("div",{className:"tree-stats",children:[e.jsxs("span",{children:[b.processed_entries," / ",b.total_entries," entries processed"]}),e.jsxs("span",{children:[b.invocations," / ",b.max_invocations," pi invocations"]}),e.jsxs("span",{children:[b.cache_hits," cached nodes reused"]})]}),!!((p=b.metrics)!=null&&p.length)&&e.jsxs("details",{className:"small",children:[e.jsx("summary",{children:"Model request timing"}),e.jsxs("p",{children:[(b.metrics.reduce((x,C)=>x+C.elapsed_ms,0)/1e3).toFixed(1)," seconds across ",b.metrics.length," requests · ",b.metrics.reduce((x,C)=>x+C.input_tokens_estimate,0).toLocaleString()," estimated input tokens."]}),e.jsx("p",{className:"muted",children:"Includes pi startup and provider waiting/generation, not separately measured. Token counts are local planning estimates with input headroom, not billed usage. A completed request can still fail summary validation."}),e.jsx("ul",{children:b.metrics.map((x,C)=>e.jsxs("li",{children:[x.stage||x.task,x.repair?" (repair)":""," · ",(x.elapsed_ms/1e3).toFixed(1)," s · ",x.status]},C))})]}),e.jsxs("p",{className:"small",children:[k?"Stopped at: ":"",b.stage]}),b.question&&e.jsxs("p",{className:"small muted",children:["Question: ",b.question]}),b.error&&e.jsxs("div",{className:"alert error",role:"alert",children:[e.jsx("strong",{children:"Last run’s error:"})," ",b.error]}),k&&e.jsxs("div",{className:"alert warning",children:[e.jsx("strong",{children:"Generation stopped. No model calls are running."}),e.jsxs("p",{className:"small",children:[b.processed_entries<b.total_entries?`${b.total_entries-b.processed_entries} entries still need compression.`:"Raw chunks were processed, but reconciliation or the final reply did not finish."," Successful chunks are cached; nothing was marked reviewed."]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"small",children:"Resume to continue from cached chunks instead of generating them again."}),e.jsx("button",{className:"btn btn-primary",disabled:!c,onClick:i,children:"Resume generation"})]})]}),s.busy&&e.jsx("button",{className:"btn btn-secondary",onClick:n,children:"Cancel generation"}),e.jsxs("details",{className:"tree-browser",children:[e.jsxs("summary",{children:["Inspect ",s.nodes.length," summary nodes"]}),e.jsx("ul",{children:E.map(x=>w(x))})]}),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:()=>j(null),children:"Close"})]}),"observations"in u.output?e.jsxs(e.Fragment,{children:[u.output.observations.map((x,C)=>e.jsxs("div",{className:"node-observation",children:[e.jsx("strong",{children:x.topic})," ",e.jsx("span",{className:"status",children:x.state}),e.jsx(_e,{text:`${x.summary} ${x.evidence.map(F=>u.refs[F]?`[${u.refs[F]}]`:"[source unavailable]").join(" ")}`,evidence:a})]},C)),u.output.limitations.map((x,C)=>e.jsx("p",{className:"muted small",children:x},C))]}):u.output.groups.map((x,C)=>e.jsxs("p",{className:"small",children:[x.topic," · ",x.members.length," related observations"]},C))]})]})}const Pe=4e3,Nt=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:[Nt(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(St,{reference:t},t)}function St({reference:t}){const[s,a]=o.useState(null),[n,i]=o.useState(0),[c,r]=o.useState("");return o.useEffect(()=>{const m=new AbortController;return r(""),a(null),jt(t,n,m.signal).then(u=>{m.signal.aborted||a(u)}).catch(u=>{m.signal.aborted||r(u.message)}),()=>m.abort()},[t,n]),e.jsxs("section",{className:"history-source","aria-label":"Historical source",children:[c&&e.jsx("p",{role:"alert",children:c}),!s&&!c&&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(n+1,s.total),"–",Math.min(n+Pe,s.total)," of ",s.total," in the retained record. Source logs may contain more."]}),s.total>Pe&&e.jsxs("div",{className:"pagination",children:[e.jsx("button",{className:"btn btn-secondary",disabled:!n,onClick:()=>i(Math.max(0,n-Pe)),children:"Earlier text"}),e.jsx("button",{className:"btn btn-secondary",disabled:n+Pe>=s.total,onClick:()=>i(n+Pe),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 Ct={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:a=!1,onLookupChange:n}){const[i,c]=o.useState(null),[r,m]=o.useState(!1);if(o.useEffect(()=>{if(n==null||n(!1),!t)return;c(null),m(!1);const k=new AbortController;let g;const T=async()=>{try{const E=await yt(k.signal);k.signal.aborted||(c(E),m(!1),n==null||n(!!(E.active&&!E.background&&E.work&&["scanning","searching","reading"].includes(E.work.stage)&&E.updated_at&&Math.abs(Date.now()-E.updated_at)<5e3)))}catch{k.signal.aborted||(m(!0),n==null||n(!1))}k.signal.aborted||(g=setTimeout(()=>void T(),1e3))};return T(),()=>{k.abort(),clearTimeout(g),n==null||n(!1)}},[t,n]),!t)return null;if(!(i!=null&&i.active)||!i.work||a&&!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,j=u.stage==="indexing",l=u.stage==="downloading",v=l?u.downloaded_bytes:u.completed,h=l?u.download_total_bytes:u.total,S=h?Math.floor(v/h*100):0,b=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:j&&!h?"History is up to date.":Ct[u.stage]})}),(j&&h>0||l)&&e.jsxs(e.Fragment,{children:[e.jsx("progress",{"aria-label":l?"Model download":"History indexing",max:h||1,value:h?v:void 0}),e.jsxs("p",{children:[l?`${(v/1e6).toFixed(1)} / ${(h/1e6).toFixed(1)} MB`:`${Fe(v)} / ${Fe(h)} new or changed passages ready`," · ",S,"%"]})]}),e.jsxs("p",{className:"small muted",children:[j&&`${Fe(u.reused)} unchanged passages reused (not part of this progress). `,"Elapsed ",Ge(i.elapsed_ms/1e3),".",j&&u.remaining_seconds!==null&&u.remaining_seconds>0&&` About ${Ge(u.remaining_seconds)} remaining (estimate).`,j&&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||b>=15)&&e.jsxs("p",{className:"small muted",children:[r?"Progress updates are temporarily unavailable.":`No new progress for ${Ge(b)}.`," 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 a=s.slice(-140).join(""),n=a.indexOf(" ");return"…"+(n>=0&&n<25?a.slice(n+1):a)}function Et({call:t,historyLookup:s}){const[a,n]=o.useState(0),i=!!t.replyPendingSince&&!["connecting","hearing","speaking","paused","ended"].includes(t.phase)&&!t.error;o.useEffect(()=>{if(n(0),!i)return;const m=setInterval(()=>n(u=>(u+1)%6),5e3);return()=>clearInterval(m)},[i,t.replyPendingSince,s]);let c,r="";return t.phase==="ended"?c="[Call ended]":t.error?c="[Reply unavailable]":t.phase==="paused"?c="[Sound paused]":t.phase==="connecting"?c=t.notice.includes("microphone permission")?"[Waiting for microphone...]":"[Connecting...]":t.phase==="hearing"?(c=t.question?Ke(t.question):"[Listening...]",r=t.question?"You":""):i?c=s?ms[a%ms.length]:ps[a%ps.length]:t.notice.startsWith("Reply muted locally;")?c="[Reply stopped]":t.answer?(c=Ke(t.answer),r="Draken"):t.question?(c=Ke(t.question),r="You"):c=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:c})})]})}var Y,H,J,ue,ve,ke,ae,ce,Z,pe,Ie,B,Me,De,je,Ne,qe,Re;class At{constructor({onClose:s=()=>{},onEvent:a=()=>{}}={}){U(this,Y);U(this,H);U(this,J);U(this,ue);U(this,ve,new Set);U(this,ke,[]);U(this,ae);U(this,ce);U(this,Z);U(this,pe,new Float32Array(1024));U(this,Ie,new AbortController);U(this,B,!1);U(this,Me,!1);U(this,De,!1);U(this,je);U(this,Ne);U(this,qe);U(this,Re);q(this,qe,s),q(this,Re,a)}get closed(){return y(this,B)}get clock(){var s;return!y(this,B)&&((s=y(this,H))==null?void 0:s.state)==="running"?y(this,H).currentTime:NaN}get audioState(){var s;return((s=y(this,H))==null?void 0:s.state)||"closed"}async resume(){var s,a;y(this,B)||(await((s=y(this,H))==null?void 0:s.resume()),await((a=y(this,Z))==null?void 0:a.play()))}gateInput(s){var a;(a=y(this,J))==null||a.getAudioTracks().forEach(n=>{n.enabled=!!s})}get inputActive(){var s;return!!((s=y(this,J))!=null&&s.getAudioTracks().some(a=>a.readyState==="live"))}get level(){var a;if(y(this,B)||y(this,De)||((a=y(this,H))==null?void 0:a.state)!=="running"||!y(this,ae))return 0;y(this,ae).getFloatTimeDomainData(y(this,pe));const s=Math.sqrt(y(this,pe).reduce((n,i)=>n+i*i,0)/y(this,pe).length);return Number.isFinite(s)?Math.min(1,s*12):0}async open(s,a){if(y(this,Me)||y(this,B))throw s.getTracks().forEach(n=>n.stop()),new Error("A voice peer can open only once.");q(this,Me,!0),q(this,J,s);try{if(s.getAudioTracks().length!==1||s.getVideoTracks().length)throw new Error("Exactly one audio track is required.");if(q(this,Y,new RTCPeerConnection),q(this,H,new AudioContext),q(this,ae,y(this,H).createAnalyser()),y(this,ae).fftSize=y(this,pe).length,q(this,ce,y(this,H).createGain()),y(this,ae).connect(y(this,ce)),y(this,ce).connect(y(this,H).destination),q(this,Ne,setTimeout(()=>this.close("Voice connection timed out."),6e4)),await y(this,H).resume(),y(this,B)||y(this,H).state!=="running")throw new Error("Voice playback could not start.");q(this,ue,y(this,Y).addTrack(s.getAudioTracks()[0],s));const n=y(this,Y).createDataChannel("oai-events"),i=new Promise((r,m)=>{q(this,je,m);const u=()=>{y(this,Y).connectionState==="connected"&&n.readyState==="open"?(q(this,je,void 0),clearTimeout(y(this,Ne)),r()):["failed","disconnected","closed"].includes(y(this,Y).connectionState)&&this.close("Voice connection lost. Start a new call explicitly.")};y(this,Y).onconnectionstatechange=u,n.onopen=u,n.onclose=()=>this.close("Voice event connection closed."),n.onerror=()=>this.close("Voice event connection failed.")});if(i.catch(()=>{}),n.onmessage=r=>{if(!y(this,B)){if(typeof r.data!="string"||r.data.length>2e5){this.close("Voice event exceeds its limit.");return}try{y(this,Re).call(this,JSON.parse(r.data))}catch{this.close("Invalid voice event.")}}},y(this,Y).ontrack=r=>{if(y(this,B)){r.track.stop();return}if(r.track.kind!=="audio"||y(this,ve).size){this.close("Unexpected remote media track.");return}y(this,ve).add(r.track);const m=new MediaStream([r.track]);q(this,Z,new Audio),y(this,Z).muted=!0,y(this,Z).srcObject=m,y(this,Z).play().catch(()=>this.close("Voice playback could not start."));const u=y(this,H).createMediaStreamSource(m);y(this,ke).push(u),u.connect(y(this,ae)),r.track.onended=()=>this.close("Voice output ended.")},await y(this,Y).setLocalDescription(await y(this,Y).createOffer()),y(this,B))throw new Error("Voice connection cancelled.");const c=await a(y(this,Y).localDescription.sdp,y(this,Ie).signal);if(y(this,B))throw new Error("Voice connection cancelled.");if(typeof c!="string"||c.length>64e3||!c.startsWith("v=0"))throw new Error("Invalid voice answer.");await y(this,Y).setRemoteDescription({type:"answer",sdp:c}),await i}catch(n){throw this.close("Voice connection failed or cancelled."),n}}muteOutput(s){q(this,De,!!s),y(this,ce)&&(y(this,ce).gain.value=s?0:1)}stopInput(){var s;(s=y(this,J))==null||s.getTracks().forEach(a=>a.stop()),q(this,J,void 0),y(this,ue)&&!y(this,B)&&y(this,ue).replaceTrack(null).catch(()=>this.close("Cannot mute voice input."))}async replaceInput(s){if(y(this,B)||!y(this,ue)||s.getAudioTracks().length!==1||s.getVideoTracks().length)throw s.getTracks().forEach(n=>n.stop()),new Error("Cannot attach voice input.");const a=y(this,J);q(this,J,s),a==null||a.getTracks().forEach(n=>n.stop());try{await y(this,ue).replaceTrack(s.getAudioTracks()[0])}catch(n){throw s.getTracks().forEach(i=>i.stop()),this.close("Cannot attach voice input."),n}if(y(this,B)||y(this,J)!==s)throw s.getTracks().forEach(n=>n.stop()),new Error("Voice input was superseded.")}close(s="Call ended."){var a,n,i,c,r;if(!y(this,B)){q(this,B,!0),clearTimeout(y(this,Ne)),y(this,Ie).abort(),(a=y(this,je))==null||a.call(this,new Error(s)),q(this,je,void 0),(n=y(this,Y))==null||n.close(),(i=y(this,J))==null||i.getTracks().forEach(m=>m.stop()),y(this,ve).forEach(m=>m.stop()),y(this,ve).clear(),y(this,ke).forEach(m=>m.disconnect()),q(this,ke,[]),(c=y(this,ae))==null||c.disconnect(),(r=y(this,ce))==null||r.disconnect(),y(this,pe).fill(0),y(this,Z)&&(y(this,Z).pause(),y(this,Z).srcObject=null,q(this,Z,void 0)),y(this,H)&&y(this,H).state!=="closed"&&y(this,H).close().catch(()=>{});try{y(this,qe).call(this,s)}catch{}}}}Y=new WeakMap,H=new WeakMap,J=new WeakMap,ue=new WeakMap,ve=new WeakMap,ke=new WeakMap,ae=new WeakMap,ce=new WeakMap,Z=new WeakMap,pe=new WeakMap,Ie=new WeakMap,B=new WeakMap,Me=new WeakMap,De=new WeakMap,je=new WeakMap,Ne=new WeakMap,qe=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 a=await fetch(`/api/voice${t}`,{...s,headers:{"Content-Type":"application/json",...ns()}});if(!a.ok){const n=await a.json().catch(()=>({}));throw new Error(n.error||(a.status===401?"Sign in again to use the call.":"The live connection failed."))}return a.status===204?void 0:a.json()}class Tt{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 At({onEvent:a=>this.providerEvent(a),onClose:a=>{this.alive&&(this.set({error:a}),this.end())}}),this.set({})}set(s){this.state={...this.state,...s},this.options.onState(this.state)}async request(s,a){return X(`/live/calls/${this.id}${s}`,{method:a?"POST":"GET",...a?{body:JSON.stringify(a)}:{},signal:this.life.signal})}async microphone(){var a;const s=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1});if(!this.alive)throw s.getTracks().forEach(n=>n.stop()),new Error("Call ended");(a=this.inputSource)==null||a.disconnect(),this.inputSource=this.inputContext.createMediaStreamSource(s),this.inputSource.connect(this.inputMeter),this.input=s,this.set({microphone:!0});for(const n of s.getAudioTracks())n.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(),a=this.inputContext.createConstantSource();return a.offset.value=0,a.connect(s),a.start(),s.stream}async start(s){var a,n;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 c;try{c=await this.microphone(),this.set({notice:""})}catch{if(!this.alive)return;c=this.silentInput(),this.set({muted:!0,notice:"Microphone unavailable. You can type instead."})}if(this.input=c,await this.peer.open(c,async(r,m)=>(await X(`/live/calls/${i.id}/connect`,{method:"POST",body:JSON.stringify({sdp:r}),signal:m})).sdp),!this.alive)return;try{(n=(a=this.options).onPlayback)==null||n.call(a,{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 a,n;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"&&((a=s.turn)==null?void 0:a.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"&&((n=s.turn)==null?void 0:n.role)==="assistant"&&(this.providerDone=!0))}meter(){if(!this.alive)return;const s=performance.now(),a=this.peer.level;let n=0;this.state.muted||(this.inputMeter.getFloatTimeDomainData(this.micBuffer),n=Math.sqrt(this.micBuffer.reduce((i,c)=>i+c*c,0)/this.micBuffer.length)*10),this.stopped&&n>.08&&(this.newQuestion=!0),a>.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,a;try{for(;this.alive;){const n=await this.request(`/events?after=${this.cursor}`);if(!this.alive)return;for(const i of n.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});(a=(s=this.options).onTurn)==null||a.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(!n.active){await this.end();return}await new Promise(i=>setTimeout(i,250))}}catch(n){this.alive&&(this.set({error:n instanceof Error?n.message:"Live connection lost"}),await this.end())}}async sendText(s){if(!this.alive||!this.id||!s.trim()||s.length>2e3)return;const a=++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&&a===this.inputEpoch&&this.stopped&&(this.stopped=!1,this.peer.muteOutput(!1),this.set({notice:""}))}catch(n){this.alive&&a===this.inputEpoch&&(this.awaitingUser=!1,this.pendingAnswer=!1,this.answerSettled=!0,this.set({phase:"listening",replyPendingSince:0,error:n instanceof Error?n.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 a=await this.microphone();await this.peer.replaceInput(a),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,a,n,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(c=>c.stop()),(a=this.inputSource)==null||a.disconnect(),this.peer.close(),this.inputContext.close().catch(()=>{});try{(i=(n=this.options).onPlayback)==null||i.call(n,null)}catch{}if(this.pendingAnswer=!1,this.awaitingUser=!1,this.set({phase:"ended",muted:!0,notice:"",replyPendingSince:0}),this.id){const c=new AbortController,r=setTimeout(()=>c.abort(),4e3);try{await X(`/live/calls/${this.id}/end`,{method:"POST",keepalive:!0,signal:c.signal})}catch{}finally{clearTimeout(r)}}}}}const Pt={connecting:"Getting ready",listening:"Your turn",hearing:"Listening to you",thinking:"Preparing your answer",speaking:"Draken is speaking",paused:"Sound paused",ended:"Call ended"},_t=t=>`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`;function It({sync:t,readiness:s,onPrepareHistory:a,disabled:n,beforeStart:i,onActiveChange:c,onClosed:r,onChat:m,autoStart:u=!1,onAutoStartHandled:j}){const[l,v]=o.useState(null),[h,S]=o.useState(""),[b,k]=o.useState(!1),[g,T]=o.useState(es),[E,d]=o.useState(0),[w,p]=o.useState(!1),[x,C]=o.useState(""),[F,ee]=o.useState([]),[I,R]=o.useState(null),[$,re]=o.useState(""),[ie,V]=o.useState(!1),[se,ge]=o.useState(!1),G=o.useRef(null),fe=o.useRef(null),xe=o.useRef(null),$e=o.useRef(null),z=o.useRef(null),K=o.useRef(!0),le=o.useRef(!1),oe=o.useRef(!1),[be,Se]=o.useState(!1),Ce=[...t.items,...t.context],de=Ce.find(f=>f.ref===$),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),o.useEffect(()=>{$&&fe.current&&xe.current&&(fe.current.scrollTop+=xe.current.getBoundingClientRect().top-fe.current.getBoundingClientRect().top)},[$]);const N=async()=>{try{const f=await X("/status");K.current&&(v(f),S(""))}catch(f){K.current&&S(f instanceof Error?f.message:"Could not check ChatGPT voice")}};o.useEffect(()=>{K.current=!0,N();const f=setInterval(()=>{z.current||N()},15e3);return()=>{var A;clearInterval(f),K.current=!1,(A=z.current)==null||A.end()}},[]),o.useEffect(()=>{var f,A,M;b&&!((f=G.current)!=null&&f.open)?(A=G.current)==null||A.showModal():b||(M=G.current)==null||M.close()},[b]),o.useEffect(()=>{if(!b||!g.startedAt||g.phase==="ended")return;const f=()=>d(Math.max(0,Math.floor((Date.now()-g.startedAt)/1e3)));f();const A=setInterval(f,1e3);return()=>clearInterval(A)},[b,g.startedAt,g.phase==="ended"]);const L=async()=>{var f;if(!(z.current||le.current||oe.current||!te)){oe.current=!0,Se(!0),S("");try{if(await i(),!K.current||document.visibilityState!=="visible")return;T({...es}),d(0),ee([]),C(""),re(""),p(!1),V(!1),ge(!1),k(!0),c(!0);const A=new Tt({onState:M=>{K.current&&(T(M),!M.microphone&&M.muted&&p(!0))},onPlayback:M=>{$e.current=M},onTurn:(M,Le,as,Oe)=>{K.current&&ee(Ve=>Ve.some(Ue=>Ue.id===Oe)?Ve.map(Ue=>Ue.id===Oe?{id:Oe,question:M,answer:Le,refs:as}:Ue):[...Ve,{id:Oe,question:M,answer:Le,refs:as}])}});z.current=A,z.current===A&&await A.start(t.id)}catch(A){if(await((f=z.current)==null?void 0:f.end()),K.current){const M=A instanceof Error?A.message:"The call could not start";S(M),z.current&&T(Le=>({...Le,phase:"ended",error:M}))}}finally{oe.current=!1,K.current&&Se(!1)}}};o.useEffect(()=>{!u||n||!te||!l||(j==null||j(),l.installed&&!l.activeCall&&ye&&document.visibilityState==="visible"?L():S("Your snapshot is ready. Start the call explicitly when audio is available and this page is visible."))},[u,n,te,l]);const O=async()=>{var f;if(!le.current){le.current=!0,re(""),await((f=z.current)==null?void 0:f.end()),z.current=null,K.current&&(k(!1),R(null),c(!1));try{await r(),await N()}finally{le.current=!1}}},W=async()=>{try{R(await X(`/syncs/${t.id}/history`))}catch(f){S(f instanceof Error?f.message:"Could not load call history")}},ne=async()=>{try{const f=await fetch("/api/voice/certificate",{headers:ns()});if(!f.ok)throw new Error("Could not download the local certificate. Check your dashboard login.");const A=URL.createObjectURL(await f.blob()),M=document.createElement("a");M.href=A,M.download="draken-local-root.crt",M.click(),setTimeout(()=>URL.revokeObjectURL(A),1e3)}catch(f){S(f instanceof Error?f.message:"Certificate download failed")}},Be=()=>{var A;if(!x.trim())return;const f=x.trim();C(""),(A=z.current)==null||A.sendText(f)};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:b||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(Fs,{size:15})]}):e.jsxs("button",{className:"btn btn-primary",disabled:n||be||!te||!(l!=null&&l.installed)||!!(l!=null&&l.activeCall)||!ye,onClick:()=>void L(),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 ne(),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:n||be,onClick:a,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 N(),children:"Retry"})]}),(l==null?void 0:l.activeCall)&&!b&&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:n,onClick:()=>{window.confirm("End the existing voice call? Its completed transcript is kept.")&&X(`/live/calls/${l.activeCall.id}/end`,{method:"POST",body:"{}"}).then(N).catch(f=>S(f.message))},children:"End previous call"})]}),e.jsxs("details",{className:"voice-history",onToggle:f=>{f.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(f=>e.jsxs("details",{className:"voice-history-call",children:[e.jsxs("summary",{children:[new Date(f.started_at).toLocaleString()," · ",f.turns.length," ",f.mode==="native"?"messages":"turns"," · ",f.status]}),e.jsx("p",{className:"small muted",children:f.end_reason||"Call in progress"}),f.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."}),f.turns.map(A=>e.jsxs("div",{className:"voice-history-turn",children:[A.question&&e.jsxs(e.Fragment,{children:[e.jsx("strong",{className:"message-author",children:"You"}),e.jsx("p",{className:"prose",children:A.question})]}),(A.answer||!A.question||f.mode!=="native")&&e.jsxs(e.Fragment,{children:[e.jsxs("strong",{className:"message-author",children:["Draken · ",A.status]}),e.jsx(_e,{text:`${A.answer||A.error||"No reply generated."} ${JSON.parse(A.evidence_json).map(M=>`[${M}]`).join(" ")}`,evidence:Ce}),A.status!=="completed"&&e.jsxs("p",{className:"small muted",children:["Generated text is shown above. ",A.heard_text?`Confirmed played: ${A.heard_text}`:"Playback was not confirmed."]})]})]},A.id))]},f.id))]})]}),e.jsxs("dialog",{ref:G,className:"voice-dialog","aria-labelledby":"voice-title",onCancel:f=>{f.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:_t(E)}),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:[b&&g.phase!=="ended"?e.jsx(_s,{playback:$e,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(Et,{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":Pt[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 f;return void((f=z.current)==null?void 0:f.sendText(g.question))},children:"Retry question"}),g.phase==="paused"&&e.jsx("button",{className:"btn btn-primary",onClick:()=>{var f;return void((f=z.current)==null?void 0:f.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 f;return void((f=z.current)==null?void 0:f.toggleMute())},children:[g.muted?e.jsx(Gs,{size:18}):e.jsx(Ks,{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 f;return void((f=z.current)==null?void 0:f.interrupt().catch(()=>{}))},children:[e.jsx(vs,{size:15}),"Stop reply"]}),e.jsxs("button",{className:"btn btn-danger",onClick:()=>void O(),children:[e.jsx(Ws,{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 f;return(f=z.current)==null?void 0:f.setVoiceInterruption(!g.voiceInterruption)},children:[e.jsx(zs,{size:16}),"Headphone mode"]}),e.jsxs("button",{className:"voice-keyboard-toggle",onClick:()=>p(f=>!f),"aria-expanded":w,children:[e.jsx(Hs,{size:16}),w?"Hide keyboard":"Type a question"]})]}),w&&e.jsxs("form",{className:"voice-compose",onSubmit:f=>{f.preventDefault(),Be()},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:x,onChange:f=>C(f.target.value)}),e.jsx("button",{className:"btn btn-primary","aria-label":"Send voice-call question",disabled:!x.trim()||g.phase==="connecting"||g.phase==="ended",children:e.jsx(xs,{size:18})})]}),e.jsxs("details",{className:"voice-conversation",open:ie,onToggle:f=>V(f.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:b&&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(f=>e.jsxs("div",{children:[f.question&&e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"You"}),e.jsx("p",{children:f.question})]}),f.answer&&e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Draken · generated reply"}),e.jsx("p",{className:f.id===g.turnId?"voice-answer":void 0,children:f.answer})]})]},f.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(f=>e.jsx("button",{className:"citation",onClick:A=>{const M=A.currentTarget.closest("details");M&&(M.open=!1),re($===f?"":f)},children:f.startsWith("H")?`History ${f.slice(-6)}`:`Source ${f}`},f))})]}),b&&/^H[a-f0-9]{24}$/.test($)&&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:$})]}),b&&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(Ls,{size:14}),e.jsx("span",{children:"Experimental live audio to OpenAI · Generated, not verified · 30-minute limit"})]})]})]})}function Mt({sync:t,readiness:s,draft:a,setDraft:n,disabled:i,sending:c,onSend:r,onCancel:m,onPrepareHistory:u,onVoice:j}){const l=t.tree.run,v=t.status==="open",h=t.busy&&(l==null?void 0:l.status)==="running"&&!!l.question,S=!t.busy&&!!(l!=null&&l.question)&&["failed","cancelled","interrupted"].includes((l==null?void 0:l.status)||""),b=c?a:h||S?l==null?void 0:l.question:null,k=h||c,g=c?"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…",T=o.useRef(null),E=o.useRef(!0);o.useEffect(()=>{E.current&&T.current&&(T.current.scrollTop=T.current.scrollHeight)},[t.messages.length,b,k,g]);const d=[...t.items,...t.context],w=i||!v||!(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:j,children:"Voice & call history"})]}),e.jsxs("div",{className:"chat-thread",ref:T,onScroll:()=>{const p=T.current;p&&(E.current=p.scrollHeight-p.scrollTop-p.clientHeight<80)},children:[!t.messages.length&&!b&&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(p=>e.jsxs("article",{className:`chat-message ${p.role}`,children:[p.role==="assistant"&&e.jsx("img",{className:"chat-avatar",src:"/persona/chat-avatar.webp",alt:"",width:"36",height:"36"}),e.jsxs("div",{className:"chat-bubble",children:[e.jsxs("div",{className:"chat-author",children:[e.jsx("strong",{children:p.role==="user"?"You":"Draken"}),e.jsx("time",{dateTime:p.created_at,children:new Date(p.created_at).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})})]}),e.jsx(_e,{text:p.content,evidence:d})]})]},p.id)),b&&!(l!=null&&l.request_id&&(h||S&&!c))&&e.jsx("article",{className:"chat-message user",children:e.jsxs("div",{className:"chat-bubble",children:[e.jsx("strong",{children:"You"}),e.jsx("p",{className:"prose",children:b})]})}),k&&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."})]})]}),S&&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"})]})]}),v&&e.jsxs(e.Fragment,{children:[!k&&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:p=>{p.preventDefault(),!w&&a.trim()&&(E.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:a,disabled:w,onChange:p=>n(p.target.value),placeholder:"Ask Draken…",onKeyDown:p=>{var x;p.key==="Enter"&&!p.shiftKey&&!p.nativeEvent.isComposing&&(p.preventDefault(),a.trim()&&!w&&((x=p.currentTarget.form)==null||x.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||!a.trim(),children:[e.jsx(xs,{size:16}),"Send message"]})]})]}),(s==null?void 0:s.briefingReady)&&!s.preparing&&!k&&e.jsx("button",{className:"btn btn-secondary chat-refresh",disabled:i,onClick:u,children:s.ready?"Refresh history":"Prepare history"})]}),!v&&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(a=>a.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),a="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.",n=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:a+n,children:["Est. cost: ",s,t.usd!==null&&!t.complete?" (partial)":""]})}function me(t,s,a){t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||(t.preventDefault(),s(a))}function Dt({id:t,chat:s=!1,callIntent:a,consumeIntent:n,navigate:i,setGuard:c}){var be,Se,Ce,de,te,ye,we;const[r,m]=o.useState(null),[u,j]=o.useState(null),[l,v]=o.useState(""),[h,S]=o.useState(""),[b,k]=o.useState(!1),[g,T]=o.useState(!1),[E,d]=o.useState(""),[w,p]=o.useState(""),[x,C]=o.useState(""),F=o.useRef(!0),ee=o.useRef(null),I=N=>{F.current&&(m(N),d(N.decisions),p(N.carry_forward))},R=async(N,L)=>{v(N),S("");try{await L()}catch(O){F.current&&S(O instanceof Error?O.message:"Something went wrong")}finally{F.current&&v("")}};o.useEffect(()=>(F.current=!0,Ye(t).then(I).catch(N=>{F.current&&S(N.message)}),()=>{F.current=!1}),[t]),o.useEffect(()=>{if(!(r!=null&&r.busy))return;let N=!1,L;const O=async()=>{try{const W=await dt(t);if(N)return;if(W.busy)m(ne=>ne&&{...ne,tree:W});else{const ne=await Ye(t);N||I(ne);return}}catch(W){N||S(W instanceof Error?W.message:"Could not refresh progress")}N||(L=setTimeout(()=>void O(),1e3))};return O(),()=>{N=!0,clearTimeout(L)}},[t,r==null?void 0:r.busy]),o.useEffect(()=>{j(null);const N=new AbortController;let L;const O=async()=>{try{const W=await(s?ht:hs)(t,N.signal);N.signal.aborted||j(W)}catch{N.signal.aborted||j(null)}N.signal.aborted||(L=setTimeout(()=>void O(),r!=null&&r.busy?1e3:3e3))};return O(),()=>{N.abort(),clearTimeout(L)}},[t,r==null?void 0:r.busy,r==null?void 0:r.briefing,r==null?void 0:r.status,b,s]);const $=!!(r&&(E!==r.decisions||w!==r.carry_forward)),re=!!x.trim();o.useEffect(()=>{c(()=>!($||re||b)||window.confirm(b?"Leave this page and end the call?":"Leave with unsaved notes or an unsent message?"));const L=O=>{($||re||b)&&(O.preventDefault(),O.returnValue="")};return window.addEventListener("beforeunload",L),()=>{c(null),window.removeEventListener("beforeunload",L)}},[$,re,b,c]);const ie=()=>{n(),T(!1)},V=!!(l||r!=null&&r.busy||b),se=(r==null?void 0:r.status)==="open",ge=r?[...r.items,...r.context]:[],G=ge.some(N=>N.unavailable),fe=()=>void R("Preparing your conversation…",async()=>{if(r){if(s&&$)throw new Error("Save or undo your note edits before preparing chat.");T(!s),$&&await Ae(t,E,w),I(await ft(t))}}),xe=()=>void R("Preparing history for your conversation…",async()=>{if(s&&$)throw new Error("Save or undo your note edits before refreshing history.");ie(),j(null),$&&await Ae(t,E,w),I(await ut(t))}),$e=(N=x)=>void R("Starting discussion…",async()=>{$&&await Ae(t,E,w),I(await xt(t,N))}),z=(N=x)=>void R("Sending message…",async()=>{var W,ne;if(ie(),$)throw new Error("Save your note edits, or undo them, before sending a message. Chat does not save decisions for you.");const L=((W=ee.current)==null?void 0:W.text)===N?ee.current:{text:N,id:Ss()};ee.current=L;let O;try{O=await it(t,N,L.id)}catch(Be){const f=await Ye(t).catch(()=>null);if(((ne=f==null?void 0:f.tree.run)==null?void 0:ne.request_id)!==L.id)throw Be;O=f}I(O),C(""),ee.current=null}),K=()=>{var N;return(N=r==null?void 0:r.tree.run)!=null&&N.question?s||r.tree.run.request_id?z(r.tree.run.question):$e(r.tree.run.question):fe()},le=()=>{ie(),R("Stopping preparation…",async()=>{await gt(t)})},oe=!(r!=null&&r.busy)&&(r==null?void 0:r.tree.run)&&["failed","cancelled","interrupted"].includes(r.tree.run.status);return o.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:N=>me(N,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:V||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 bt(t,E,w))})},children:[e.jsx(Os,{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:V||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:V||G,onClick:fe,children:s?"Prepare for chat":"Prepare & call"}),s?e.jsx(Mt,{sync:r,readiness:u,draft:x,setDraft:C,disabled:V||G,sending:l==="Sending message…",onSend:z,onCancel:le,onPrepareHistory:xe,onVoice:()=>i(`/syncs/${t}`)}):e.jsx(It,{sync:r,readiness:u,onPrepareHistory:xe,disabled:V||G,onActiveChange:k,onChat:()=>{ie(),i(`/syncs/${t}/chat`)},autoStart:(a||g)&&!oe&&!G,onAutoStartHandled:ie,beforeStart:async()=>{$&&I(await Ae(t,E,w));const N=await hs(t);if(j(N),!N.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:V,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(N=>e.jsxs("article",{className:"memory-recap",children:[e.jsxs("a",{href:`/syncs/${N.sync_id}`,onClick:L=>me(L,i,`/syncs/${N.sync_id}`),children:["Sync #",N.sync_id]})," ",e.jsx("span",{className:"small muted",children:N.status==="open"?"not marked reviewed":N.status||"historical"}),e.jsx("p",{className:"prose",children:N.recap||"No automatic recap in this older snapshot."}),N.decisions&&e.jsxs("p",{className:"small prose",children:["Saved decisions: ",N.decisions]}),N.carry_forward&&e.jsxs("p",{className:"small prose",children:["Carried forward: ",N.carry_forward]})]},N.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:V,onClick:()=>{window.confirm("Expand this legacy snapshot to currently eligible history? Existing notes and citations are retained.")&&R("Expanding snapshot…",async()=>I((await mt(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(N=>e.jsxs("div",{className:`message ${N.role}`,children:[e.jsx("span",{className:"message-author",children:N.role==="user"?"You":"Draken"}),e.jsx(_e,{text:N.content,evidence:ge})]},N.id)),e.jsx("button",{className:"btn btn-secondary",disabled:b,onClick:()=>{ie(),i(`/syncs/${t}/chat`)},children:"Open chat"})]})]}),e.jsxs("details",{className:"detail-section",children:[e.jsxs("summary",{children:["Decisions & carry-forward",$?" · 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||V,value:E,onChange:N=>d(N.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||V,value:w,onChange:N=>p(N.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:V||!$,onClick:()=>void R("Saving notes…",async()=>I(await Ae(t,E,w))),children:"Save notes"})]})]}),e.jsxs("details",{className:"detail-section",children:[e.jsx("summary",{children:"Evidence & preparation details"}),e.jsx(kt,{syncId:t,progress:r.tree,evidence:ge,onResume:se?K:void 0,resumeEnabled:!V&&!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:V,onClick:()=>{window.confirm("Discard this sync and release its unreviewed entries? Its history is retained.")&&R("Discarding sync…",async()=>I(await wt(t)))},children:"Discard sync"})]})]})]})}function Es({active:t=!0,firstRun:s=!1,always:a=!1,onReady:n,onTextReady:i}){const[c,r]=o.useState(null),[m,u]=o.useState(null),[j,l]=o.useState(""),[v,h]=o.useState(!1),[S,b]=o.useState(0);if(o.useEffect(()=>{if(!t)return;let g=!0;const T=async(d=!1)=>{h(!0);try{const[w,p]=await Promise.all([tt(d),X("/status").catch(()=>null)]);if(!g)return;r(w),u(p),l(p?"":"Voice status is unavailable. Configured text chat can still be used."),n==null||n(w.pi.state==="configured"&&!!(p!=null&&p.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."),n==null||n(!1),i==null||i(!1))}finally{g&&h(!1)}};T(S>0);const E=setInterval(()=>void T(),6e4);return()=>{g=!1,clearInterval(E)}},[t,S,n,i]),!t||!a&&!s&&!j&&(c==null?void 0:c.pi.state)==="configured"&&(m!=null&&m.installed))return null;const k=c==null?void 0:c.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."]}),!c&&!j&&e.jsx("p",{className:"small",role:"status",children:"Checking setup…"}),k&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{children:[e.jsxs("strong",{children:["Summarization: ",k.state==="configured"?"credentials configured":k.state==="missing"?"pi not found":k.state==="needs_login"?"sign-in needed":"needs attention"]}),e.jsxs("span",{className:"small muted",children:[" · ",k.source==="managed"?"Draken-private pi":"Existing / external pi",k.version&&` ${k.version}`]})]}),e.jsx("p",{className:"small",children:k.message}),k.state!=="configured"&&e.jsxs("div",{className:"setup-commands",children:[["missing","incompatible"].includes(k.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:k.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: ",k.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."]})]}),(a||s||(k==null?void 0:k.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."]}),c&&e.jsxs("p",{className:"small muted source-path",children:["Draken data: ",c.data_dir]}),e.jsxs("p",{className:"small muted",children:["Choose sources in ",e.jsx("strong",{children:"Settings → Agents & sessions"}),", then ",e.jsx("strong",{children:"Sync with Draken"}),". Source scanning works before sign-in. Credential presence does not verify model access, billing or voice playback."]})]}),j&&e.jsx("p",{className:"small",role:"alert",children:j}),e.jsx("button",{type:"button",className:"btn btn-secondary",disabled:v,onClick:()=>b(g=>g+1),children:v?"Checking…":"Check setup again"})]})}function As({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…",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 qt(){const[t,s]=o.useState(null),[a,n]=o.useState(!1);return o.useEffect(()=>{let i=!0;const c=async()=>{try{const m=await ks();i&&(s(m),n(!1))}catch{i&&n(!0)}};c();const r=setInterval(()=>void c(),4e3);return()=>{i=!1,clearInterval(r)}},[]),a?e.jsx("p",{role:"status",className:"small muted",children:"Automatic indexing status is temporarily unavailable."}):t!=null&&t.enabled?e.jsx(As,{settings:t}):null}const Rt=t=>new Date(t).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"});function $t({navigate:t}){const[s,a]=o.useState(null),[n,i]=o.useState(""),[c,r]=o.useState(""),[m,u]=o.useState(""),[j,l]=o.useState(!1),[v,h]=o.useState(!1),S=o.useRef(!0),b=o.useRef(!1),k=o.useRef(),g=async()=>{const d=await Ze();S.current&&a(w=>w&&w.syncs.length>20?{...d,syncs:[...d.syncs,...w.syncs.filter(p=>{var x;return p.id<((x=d.syncs[d.syncs.length-1])==null?void 0:x.id)})],next_cursor:w.next_cursor}:d)};o.useEffect(()=>{S.current=!0,g().catch(w=>r(w.message)),window.isSecureContext||X("/status").then(w=>{if(S.current&&w.httpsPort){const p=new URL("/",location.href);p.protocol="https:",p.port=String(w.httpsPort),u(p.href)}}).catch(()=>{});const d=setInterval(()=>{b.current||g().catch(()=>{})},4e3);return()=>{S.current=!1,clearInterval(d)}},[]);const T=async(d="call")=>{if(!b.current){b.current=!0,i("Collecting new activity…"),r(""),k.current||(k.current=Ss());try{if(d==="call"){const p=await X("/status");if(!p.installed)throw new Error("Voice is not ready on this server. Complete voice setup before starting a sync call.");if(p.activeCall)throw new Error("End the existing call before starting another sync.")}const w=await(d==="chat"?rt:at)(k.current);S.current&&t(`/syncs/${w.sync.id}${d==="chat"?"/chat":""}`,d==="call")}catch(w){S.current&&r(w instanceof Error?w.message:"Could not start the sync")}finally{b.current=!1,S.current&&i("")}}},E=!!(!j||n||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||!v||!!(n||s!=null&&s.busy||s!=null&&s.active_call),onClick:()=>void T("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||E||!window.isSecureContext,onClick:()=>void T(),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. Click Sync with Draken or Chat instead to collect available entries into a snapshot and prepare its 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(qt,{}),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.jsx("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. Matching cached summaries can be reused. 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."})]}),n&&e.jsxs("p",{role:"status",className:"working",children:[e.jsx("span",{className:"spinner"}),n]}),(s==null?void 0:s.busy)&&!n&&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."}),c&&e.jsx("div",{className:"alert error",role:"alert",children:c}),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:[Rt(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);a(w=>w?{...w,syncs:[...w.syncs,...d.syncs.filter(p=>!w.syncs.some(x=>x.id===p.id))],next_cursor:d.next_cursor}:d)}catch(d){r(d instanceof Error?d.message:"Could not load history")}},children:"Older syncs"})]})}function Lt({navigate:t,reference:s}){const[a,n]=o.useState(null),[i,c]=o.useState(""),[r,m]=o.useState(""),[u,j]=o.useState(!1),l=o.useRef();return o.useEffect(()=>()=>{var v;return(v=l.current)==null?void 0:v.abort()},[]),e.jsxs("main",{className:"sync-home history-page",children:[e.jsx("a",{className:"back-link",href:"/",onClick:v=>me(v,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:v=>me(v,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 v=>{v.preventDefault(),j(!0),m(""),n(null);const h=new AbortController;l.current=h;try{const S=await vt({question:i},h.signal);h.signal.aborted||n(S)}catch(S){h.signal.aborted||m(S instanceof Error?S.message:"Search failed")}finally{j(!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:v=>c(v.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 v;return(v=l.current)==null?void 0:v.abort()},children:"Cancel search"})]}),e.jsx(He,{enabled:u,waiting:!0})]}),r&&e.jsx("p",{className:"alert error",role:"alert",children:r}),a&&e.jsxs("section",{"aria-label":"History search results",children:[e.jsx("p",{className:"small muted",children:"Meaning + keyword matches"}),!a.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."}),a.results.map(v=>e.jsxs("article",{className:"card history-result",children:[e.jsx("h2",{children:e.jsx("a",{href:`/history/${v.ref}`,target:"_blank",rel:"noopener noreferrer",children:v.title})}),e.jsx(Xe,{record:v}),e.jsx("pre",{className:"history-excerpt",children:v.text}),e.jsx("a",{href:`/history/${v.ref}`,target:"_blank",rel:"noopener noreferrer",children:"Read source and surrounding context"})]},v.ref)),e.jsx("p",{className:"small muted",children:a.limitations})]})]})]})}const gs=t=>new Date(t).toLocaleString(),Ot={pi:"pi v3 JSONL",codex:"Rollout JSONL",claude:"Transcript JSONL"};function Ut({open:t}){const[s,a]=o.useState(!1),[n,i]=o.useState(null),[c,r]=o.useState(!0),[m,u]=o.useState(!1),[j,l]=o.useState(""),[v,h]=o.useState(""),[S,b]=o.useState(null),k=o.useRef(!0),g=o.useRef(!1);o.useEffect(()=>(k.current=!0,()=>{k.current=!1}),[]),o.useEffect(()=>{if(!t||!s||m)return;let d=!0;const w=async()=>{try{const[x,C]=await Promise.all([ds(),Ze()]);d&&!g.current&&(i(x),r(C.busy||C.active_call),h(""))}catch(x){d&&!g.current&&h(x instanceof Error?x.message:"Could not read session sources")}};w();const p=setInterval(()=>void w(),4e3);return()=>{d=!1,clearInterval(p)}},[t,s,m]);const T=async(d,w)=>{if(!n||c||v||g.current)return;const p=n;g.current=!0,u(!0),l(""),w&&i(w);try{const x=await d();k.current&&i(x)}catch(x){k.current&&(w&&i(p),l(x instanceof Error?x.message:"Could not update session sources"))}finally{g.current=!1,k.current&&u(!1)}},E=!n||c||m||!!v;return e.jsxs("details",{className:"source-settings",onToggle:d=>a(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."}),!n&&e.jsx("p",{className:"small muted",role:"status",children:"Loading session inventory…"}),e.jsxs("button",{type:"button",className:"btn btn-secondary",disabled:E||!(n!=null&&n.agents.some(d=>d.enabled)),onClick:()=>void T(async()=>{const d=await ot();return k.current&&b(d),ds()}),children:[e.jsx(Qs,{size:15,"aria-hidden":"true"}),"Scan enabled agents"]}),c&&n&&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…"}),n==null?void 0:n.agents.map(d=>{const w=n.sessions.filter(p=>p.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:Ot[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:E,onChange:p=>{const x=p.target.checked;T(()=>ct(d.id,x),{...n,agents:n.agents.map(C=>C.id===d.id?{...C,enabled:x}:C)})}}),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(p=>e.jsxs("div",{children:[e.jsx("p",{className:"small muted",children:p.status==="present"?"Directory found":p.status==="missing"?"Directory not found":"Directory unavailable"}),e.jsx("code",{className:"source-path",children:p.path})]},p.path)),e.jsxs("p",{className:"small muted",children:[w.length," recorded sessions · ",w.filter(p=>p.included).length," selected · ",w.filter(p=>p.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(p=>e.jsxs("label",{className:"session-source",children:[e.jsx("input",{type:"checkbox",checked:!!p.included,disabled:E||!d.enabled||!!p.missing,"aria-label":`Include ${p.name||"session"} (${p.id})`,onChange:x=>{const C=x.target.checked;T(()=>lt(p.id,C),{...n,sessions:n.sessions.map(F=>F.id===p.id?{...F,included:Number(C)}:F)})}}),e.jsxs("span",{children:[e.jsx("strong",{children:p.name||p.cwd.split(/[\\/]/).filter(Boolean).pop()||p.id}),e.jsx("span",{className:"source-cwd",title:p.cwd,children:p.cwd||"Workspace unavailable"}),e.jsxs("span",{className:"small",children:[p.included?"Selected":"Excluded"," · ",p.pending," unreviewed ",p.pending===1?"entry":"entries",p.missing?" · unavailable at last scan":""]}),e.jsxs("span",{className:"source-session-meta small muted",children:["Session ",p.external_id||p.id," · Last recorded change: ",gs(p.modified_at)]}),e.jsx("code",{className:"source-path",children:p.path})]})]},p.id))})]},d.id)}),n&&e.jsxs("p",{className:"small muted",children:[n.history_initialized&&n.history_since?`Existing history baseline: ${gs(n.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."]}),S&&e.jsxs("p",{className:"small muted",role:"status",children:["Last requested scan: ",S.files," candidate log files checked · ",S.added," new records recorded."]}),S&&S.warnings.length>0&&e.jsx("ul",{className:"source-warnings small","aria-label":"Scan warnings",children:S.warnings.map((d,w)=>e.jsx("li",{children:d},w))}),(j||v)&&e.jsx("p",{className:"small",role:"alert",children:j||v})]})}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 Ft(t,s){const a=(t||1)/4,n=10**Math.floor(Math.log10(a)),i=Math.max(s?1:Number.MIN_VALUE,[1,2,5,10].find(j=>j*n>=a)*n),c=Math.max(1,Math.ceil((t||1)/i)),r=c*i,m=Math.max(2,-Math.floor(Math.log10(i))),u=j=>s?Q(j):j===0?"$0":i<1e-6||r>=1e9?`$${Number(j.toPrecision(3)).toExponential()}`:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:Math.min(6,m)}).format(j);return{maximum:r,ticks:Array.from({length:c+1},(j,l)=>({fraction:l/c,label:u(l*i)}))}}function zt({active:t}){const[s,a]=o.useState("7d"),[n,i]=o.useState("1h"),[c,r]=o.useState("cost"),[m,u]=o.useState(null),[j,l]=o.useState("");if(o.useEffect(()=>{if(!t)return;const d=new AbortController;let w=!1;u(null),l("");const p=async()=>{if(!w){w=!0;try{const C=await nt(s,n,d.signal);d.signal.aborted||(u(C),l(""))}catch(C){d.signal.aborted||(u(null),l(C instanceof Error?C.message:"Could not load preparation usage"))}finally{w=!1}}};p();const x=setInterval(()=>void p(),15e3);return()=>{d.abort(),clearInterval(x)}},[t,s,n]),!t)return null;const v=(m==null?void 0:m.range)===s&&m.bucket===n?m:null,h=v==null?void 0:v.totals,S=(v==null?void 0:v.buckets.map(d=>c==="cost"?d.cost.usd||0:d.completed_batches))||[],b=Math.max(0,...S),k=Ft(b,c==="batches"),g=c==="cost"&&(h==null?void 0:h.cost.usd)===null,T=g?[]:k.ticks,E=c==="cost"?"USD":"Batches";return e.jsxs("section",{className:"preparation-usage","aria-labelledby":"preparation-usage-title",children:[e.jsx("h3",{id:"preparation-usage-title",children:"Preparation usage"}),e.jsx("p",{className:"small muted",children:"Preparation history, including past automatic work, retries and discarded batches. Automatic indexing now 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=>a(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:n,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:c,onChange:d=>r(d.target.value),children:[e.jsx("option",{value:"cost",children:"Estimated cost"}),e.jsx("option",{value:"batches",children:"Completed batches"})]})]})]}),j?e.jsxs("p",{role:"alert",children:["Usage unavailable: ",j]}):v?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(v.active_attempts)," preparation ",v.active_attempts===1?"attempt":"attempts"," active now"]})]})]}),e.jsxs("p",{className:"small muted",children:[he(v.from)," – ",he(v.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:[c==="cost"?"Estimated cost":"Completed batches"," per ",n]}),e.jsx("span",{children:c==="cost"?`Peak known: ${ze(h.cost.usd===null?null:b)}`:`Peak: ${Q(b)}`})]}),e.jsxs("div",{className:"usage-chart-frame",children:[e.jsx("span",{className:"usage-axis-unit small muted","aria-hidden":"true",children:E}),e.jsx("div",{className:"usage-y-axis small muted","aria-hidden":"true",style:{width:`${Math.max(7,...T.map(d=>d.label.length))}ch`},children:T.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":`${c==="cost"?"Estimated preparation cost":"Completed batches"} by ${n} bucket. Y-axis: ${E}${g?", pricing unavailable":`, ${T[0].label} to ${T[T.length-1].label}`}. Exact values in bucket details below.`,children:[T.map(d=>e.jsx("line",{className:"usage-gridline",x1:"0",y1:119-d.fraction*112,x2:"720",y2:119-d.fraction*112},d.fraction)),v.buckets.map((d,w)=>{const p=c==="cost"&&!d.cost.complete,x=Math.max(S[w]>0?2:p?4:0,S[w]/k.maximum*112);return e.jsx("rect",{x:w/S.length*720,y:119-x,width:Math.max(.5,720/S.length-1),height:x,className:p?"usage-incomplete":void 0,children:e.jsxs("title",{children:[he(d.from)," – ",he(d.to)," UTC: ",c==="cost"?ze(d.cost.usd)+(p?" (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(v.from).slice(5)}),e.jsx("span",{children:"UTC"}),e.jsx("span",{children:he(v.to).slice(5)})]})]}),c==="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:[...v.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. 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 Ht(){const[t,s]=o.useState(!1),[a,n]=o.useState(null),[i,c]=o.useState(!1),[r,m]=o.useState(""),u=o.useRef(null);return o.useEffect(()=>{var j,l,v;t&&!((j=u.current)!=null&&j.open)?(l=u.current)==null||l.showModal():t||(v=u.current)==null||v.close()},[t]),o.useEffect(()=>{if(!t||i)return;let j=!0;const l=async()=>{try{const h=await ks();j&&(n(h),m(""))}catch(h){j&&m(h instanceof Error?h.message:"Could not read settings")}};l();const v=setInterval(()=>void l(),4e3);return()=>{j=!1,clearInterval(v)}},[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(Js,{size:16,"aria-hidden":"true"}),"Settings"]}),e.jsxs("dialog",{ref:u,className:"settings-dialog","aria-labelledby":"settings-title",onCancel:j=>{j.preventDefault(),s(!1)},onClose:j=>{j.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(zt,{active:t}),e.jsxs("label",{className:"index-toggle",children:[e.jsx("input",{type:"checkbox",role:"switch",checked:(a==null?void 0:a.enabled)||!1,disabled:!a||i,onChange:async j=>{const l=j.target.checked,v=a;c(!0),m(""),n(h=>h&&{...h,enabled:l});try{n(await cs(l))}catch(h){n(v),m(h instanceof Error?h.message:"Could not save settings")}finally{c(!1)}}}),e.jsxs("span",{children:[e.jsx("strong",{children:"Automatically index history"}),e.jsx("span",{className:"small muted",children:"Accumulate searchable history locally, without creating syncs, summaries or briefings."})]})]}),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, keeping completed embeddings. 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&&e.jsx("p",{className:"small",role:"alert",children:r}),t&&a&&e.jsx(As,{settings:a}),(a==null?void 0:a.enabled)&&a.phase==="error"&&e.jsx("button",{type:"button",className:"btn btn-secondary",disabled:i,onClick:async()=>{c(!0),m("");try{n(await cs(!0))}catch(j){m(j instanceof Error?j.message:"Could not retry indexing")}finally{c(!1)}},children:"Retry automatic indexing"}),e.jsx(Ut,{open:t}),e.jsx(Es,{active:t,always:!0})]})]})}function Bt(){const{isAuthenticated:t,isLoading:s,authEnabled:a,username:n,logout:i}=ws(),[c,r]=o.useState(window.location.pathname),[m,u]=o.useState(null),j=o.useRef(null),l=o.useRef(c),v=o.useCallback(k=>{j.current=k},[]),h=o.useCallback((k,g=!1)=>{j.current&&!j.current()||(window.history.pushState(null,"",k),l.current=k,r(k),u(g?Number(k.split("/").pop()):null),window.scrollTo(0,0))},[]);if(o.useEffect(()=>{const k=()=>{if(j.current&&!j.current()){window.history.pushState(null,"",l.current);return}l.current=window.location.pathname,r(l.current),u(null)};return window.addEventListener("popstate",k),()=>window.removeEventListener("popstate",k)},[]),s)return e.jsxs("div",{className:"app-loading",children:[e.jsx("span",{className:"spinner"}),"Opening Draken…"]});if(!t)return e.jsx(st,{});const S=/^\/syncs\/([1-9]\d*)(\/chat)?\/?$/.exec(c),b=S?Number(S[1]):null;return e.jsxs("div",{className:"app-container",children:[e.jsxs("header",{className:"header",children:[e.jsxs("a",{className:"brand",href:"/",onClick:k=>me(k,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:k=>me(k,h,"/history"),children:"Search history"}),e.jsx(Ht,{}),a&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"muted small",children:n}),e.jsx("button",{className:"icon-button",onClick:()=>{(!j.current||j.current())&&i()},"aria-label":"Sign out",children:e.jsx(Ys,{size:18})})]})]})]}),b&&Number.isSafeInteger(b)?e.jsx(Dt,{id:b,chat:!!(S!=null&&S[2]),callIntent:m===b,consumeIntent:()=>u(null),navigate:h,setGuard:v},b):/^\/history(?:\/H[a-f0-9]{24})?\/?$/.test(c)?e.jsx(Lt,{navigate:h,reference:c.split("/")[2]},c):c==="/"?e.jsx($t,{navigate:h}):e.jsxs("main",{className:"sync-home",children:[e.jsx("h1",{children:"Page not found"}),e.jsx("a",{href:"/",onClick:k=>me(k,h,"/"),children:"All syncs"})]})]})}function Vt(){return e.jsx(et,{children:e.jsx(Bt,{})})}Is.createRoot(document.getElementById("root")).render(e.jsx(Ms.StrictMode,{children:e.jsx(Vt,{})}));
|
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-DXPfCm7z.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>
|
package/voice/realtime/README.md
CHANGED
|
@@ -48,7 +48,7 @@ Current questions proactively receive bounded context before typed input or when
|
|
|
48
48
|
|
|
49
49
|
Each turn has its own cancellation signal and identity, including repeated identical questions. Stop, first transcript of newer input, call end and helper failure cancel timers and old retrieval ownership. Results delivered after cancellation cannot send a completion cue; already-sent provider work cannot be recalled, so local Stop still mutes immediately. Acknowledgements (including delayed or duplicated events) never authorize another cue. A failed completion request or the fixed 45-second completion deadline produces a visible failure without further automatic attempts. Normal transcript/playback qualifications and explicit review boundaries remain unchanged.
|
|
50
50
|
|
|
51
|
-
If the voice model delegates a lookup, `src/voice/live.ts`
|
|
51
|
+
If the voice model delegates a lookup, `src/voice/live.ts` uses the same prepared historical archive and fixed cutoff as proactive retrieval. Explicit E/C requests instead select frozen snapshot evidence; status questions may also include later prepared archive reports. The delegation text is an untrusted query, not instructions. No shell, arbitrary file access, network searches or pi model calls are available. Selected evidence is transferred as acknowledged developer-context parts by `src/voice/history-delivery.ts`; the small handoff receipt confirms delivery rather than containing the evidence itself. Selection remains bounded, not comprehensive. See [VOICE.md](../../VOICE.md) for retrieval scope and transport limits.
|
|
52
52
|
|
|
53
53
|
**Native speech may paraphrase.** It does not validate a complete JSON answer before speech is played. The UI says **Sources supplied**, not “verified citations.” An assistant’s claim is not independent test evidence, truncated output cannot establish a final suite pass, and an unverified deployment is not proof of a failed or absent deployment. These remain model instructions and human-review obligations, not a proof of semantic correctness.
|
|
54
54
|
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
|
|
3
|
+
/** Own a native-workflow command directly (Windows) or its private launcher
|
|
4
|
+
* group (Unix). Launcher stdio closure cannot prove descendants have stopped. */
|
|
5
|
+
export class NativeHelperProcess {
|
|
6
|
+
#closing = false;
|
|
7
|
+
#launcherClosed = false;
|
|
8
|
+
#exited = false;
|
|
9
|
+
#killTimer;
|
|
10
|
+
constructor(binary, args, { cwd, env, spawnProcess = spawn, stdio = ['pipe', 'pipe', 'pipe'] } = {}) {
|
|
11
|
+
this.child = spawnProcess(binary, args, { cwd, env, shell: false, detached: process.platform !== 'win32', stdio });
|
|
12
|
+
// Piped diagnostics can contain credentials/transcripts; never log them.
|
|
13
|
+
// Explicit terminal setup/login commands instead inherit the operator's IO.
|
|
14
|
+
this.child.stderr?.resume();
|
|
15
|
+
this.child.on('error', () => this.close());
|
|
16
|
+
this.child.on('close', () => {
|
|
17
|
+
this.#launcherClosed = true;
|
|
18
|
+
if (!this.#confirmExit()) this.close();
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
#confirmExit() {
|
|
22
|
+
if (this.#exited) return true;
|
|
23
|
+
if (!this.#launcherClosed) return false;
|
|
24
|
+
if (process.platform !== 'win32' && Number.isInteger(this.child.pid) && this.child.pid > 1) {
|
|
25
|
+
try { process.kill(-this.child.pid, 0); return false; }
|
|
26
|
+
catch (error) { if (error.code !== 'ESRCH') return false; }
|
|
27
|
+
}
|
|
28
|
+
this.#exited = true; clearTimeout(this.#killTimer);
|
|
29
|
+
return true;
|
|
30
|
+
}
|
|
31
|
+
async waitForExit(timeoutMs = 2500) {
|
|
32
|
+
const deadline = Date.now() + timeoutMs;
|
|
33
|
+
while (!this.#confirmExit()) {
|
|
34
|
+
const remaining = deadline - Date.now();
|
|
35
|
+
if (remaining <= 0) return false;
|
|
36
|
+
await new Promise(resolve => setTimeout(resolve, Math.min(50, remaining)));
|
|
37
|
+
}
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
#terminate(signal) {
|
|
41
|
+
if (process.platform !== 'win32' && Number.isInteger(this.child.pid) && this.child.pid > 1) {
|
|
42
|
+
try { process.kill(-this.child.pid, signal); return; } catch { /* Confirmation remains separate. */ }
|
|
43
|
+
}
|
|
44
|
+
try { this.child.kill(signal); } catch { /* An unsuccessful signal is not proof of exit. */ }
|
|
45
|
+
}
|
|
46
|
+
close() {
|
|
47
|
+
if (this.#closing) return;
|
|
48
|
+
this.#closing = true; this.child.stdin?.destroy();
|
|
49
|
+
if (this.#confirmExit()) return;
|
|
50
|
+
this.#terminate('SIGTERM');
|
|
51
|
+
this.#killTimer = setTimeout(() => { if (!this.#confirmExit()) this.#terminate('SIGKILL'); }, 1500);
|
|
52
|
+
this.#killTimer.unref();
|
|
53
|
+
}
|
|
54
|
+
}
|