@realtimex/realtimex-alchemy 1.0.52 → 1.0.53
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/CHANGELOG.md +9 -0
- package/dist/api/config/embeddingModels.js +41 -0
- package/dist/api/services/ChatService.js +1 -1
- package/dist/api/services/DeduplicationService.js +1 -1
- package/dist/api/services/EmbeddingService.js +8 -1
- package/dist/assets/{index-Be9CS22o.js → index-D5nmpTYI.js} +2 -2
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/supabase/migrations/20260127000004_variable_vector_dimensions.sql +99 -0
package/dist/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,15 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [1.0.53] - 2026-01-27
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
- **Vector Database**: Upgraded schema to support variable embedding dimensions (384, 768, 1024, 1536, 3072+), removing the vendor lock-in to OpenAI's 1536 dimensions.
|
|
12
|
+
- **Performance**: Added optimized partial HNSW indexes for common model dimensions (all-minilm, nomic-embed, mxbai) to maintain sub-millisecond search speeds.
|
|
13
|
+
|
|
14
|
+
### Improved
|
|
15
|
+
- **Flexibility**: Updated `EmbeddingService` to dynamically detect vector dimensions at runtime, allowing seamless switching between OpenAI and local Ollama models without schema changes.
|
|
16
|
+
|
|
8
17
|
## [1.0.52] - 2026-01-27
|
|
9
18
|
|
|
10
19
|
### Changed
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Embedding Model Dimension Configuration (Reference)
|
|
3
|
+
*
|
|
4
|
+
* NOTE: Dimensions are derived from actual embedding vectors at runtime.
|
|
5
|
+
* This file serves as documentation and for optional pre-validation.
|
|
6
|
+
*
|
|
7
|
+
* pgvector HNSW index has 2000 dimension limit.
|
|
8
|
+
* Models with >2000 dimensions (e.g., text-embedding-3-large) use sequential scan.
|
|
9
|
+
*/
|
|
10
|
+
export const EMBEDDING_DIMENSIONS = {
|
|
11
|
+
// OpenAI models
|
|
12
|
+
'text-embedding-3-small': 1536,
|
|
13
|
+
'text-embedding-3-large': 3072,
|
|
14
|
+
'text-embedding-ada-002': 1536,
|
|
15
|
+
// Anthropic (if/when available)
|
|
16
|
+
// 'voyage-large-2': 1024,
|
|
17
|
+
// Ollama common models
|
|
18
|
+
'nomic-embed-text': 768,
|
|
19
|
+
'mxbai-embed-large': 1024,
|
|
20
|
+
'all-minilm': 384,
|
|
21
|
+
'bge-large': 1024,
|
|
22
|
+
// Add more models as needed
|
|
23
|
+
};
|
|
24
|
+
/** pgvector HNSW index dimension limit */
|
|
25
|
+
export const HNSW_MAX_DIMENSIONS = 2000;
|
|
26
|
+
/**
|
|
27
|
+
* Get the dimension count for a given embedding model
|
|
28
|
+
* @param model - Model name
|
|
29
|
+
* @returns Dimension count (defaults to 1536 for unknown models)
|
|
30
|
+
*/
|
|
31
|
+
export function getDimensions(model) {
|
|
32
|
+
return EMBEDDING_DIMENSIONS[model] ?? 1536;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Check if a model is supported (has known dimensions)
|
|
36
|
+
* @param model - Model name
|
|
37
|
+
* @returns True if model has known dimensions
|
|
38
|
+
*/
|
|
39
|
+
export function isKnownModel(model) {
|
|
40
|
+
return model in EMBEDDING_DIMENSIONS;
|
|
41
|
+
}
|
|
@@ -64,7 +64,7 @@ export class ChatService {
|
|
|
64
64
|
let sources = [];
|
|
65
65
|
// 3. Retrieve Context (if embedding checks out)
|
|
66
66
|
if (queryEmbedding) {
|
|
67
|
-
const similar = await embeddingService.findSimilarSignals(queryEmbedding, userId, supabase, 0.55, // Lowered threshold for better recall
|
|
67
|
+
const similar = await embeddingService.findSimilarSignals(queryEmbedding, userId, supabase, settings, 0.55, // Lowered threshold for better recall
|
|
68
68
|
10 // Increased Top K
|
|
69
69
|
);
|
|
70
70
|
console.log(`[ChatService] RAG Retrieval: Found ${similar.length} signals for query: "${content}"`);
|
|
@@ -18,7 +18,7 @@ export class DeduplicationService {
|
|
|
18
18
|
try {
|
|
19
19
|
// 1. Semantic Check (if embedding exists)
|
|
20
20
|
if (embedding && embedding.length > 0) {
|
|
21
|
-
const similar = await embeddingService.findSimilarSignals(embedding, userId, supabase, this.SIMILARITY_THRESHOLD, 5 // Check top 5 matches
|
|
21
|
+
const similar = await embeddingService.findSimilarSignals(embedding, userId, supabase, settings, this.SIMILARITY_THRESHOLD, 5 // Check top 5 matches
|
|
22
22
|
);
|
|
23
23
|
if (similar.length > 0) {
|
|
24
24
|
const bestMatch = similar[0];
|
|
@@ -106,16 +106,23 @@ export class EmbeddingService {
|
|
|
106
106
|
* @param queryEmbedding - Query embedding vector
|
|
107
107
|
* @param userId - User ID for filtering
|
|
108
108
|
* @param supabase - Supabase client
|
|
109
|
+
* @param settings - Alchemy settings with embedding model info
|
|
109
110
|
* @param threshold - Similarity threshold (0-1)
|
|
110
111
|
* @param limit - Max results
|
|
111
112
|
* @returns Array of similar signals
|
|
112
113
|
*/
|
|
113
|
-
async findSimilarSignals(queryEmbedding, userId, supabase, threshold = this.SIMILARITY_THRESHOLD, limit = 10) {
|
|
114
|
+
async findSimilarSignals(queryEmbedding, userId, supabase, settings, threshold = this.SIMILARITY_THRESHOLD, limit = 10) {
|
|
114
115
|
try {
|
|
116
|
+
// Resolve embedding model from settings
|
|
117
|
+
const { model } = await SDKService.resolveEmbedProvider(settings);
|
|
118
|
+
// Use actual embedding length - works with any model regardless of lookup table
|
|
119
|
+
const dimensions = queryEmbedding.length;
|
|
115
120
|
// Format embedding as pgvector string
|
|
116
121
|
const embeddingStr = `[${queryEmbedding.join(',')}]`;
|
|
117
122
|
const { data, error } = await supabase.rpc('match_vectors', {
|
|
118
123
|
query_embedding: embeddingStr,
|
|
124
|
+
target_model: model,
|
|
125
|
+
target_dimensions: dimensions,
|
|
119
126
|
match_threshold: threshold,
|
|
120
127
|
match_count: limit,
|
|
121
128
|
target_user_id: userId
|
|
@@ -75,7 +75,7 @@ localhost:
|
|
|
75
75
|
facebook.com
|
|
76
76
|
twitter.com
|
|
77
77
|
instagram.com
|
|
78
|
-
linkedin.com/feed`,className:"w-full h-40 px-4 py-3 rounded-xl border border-border bg-surface text-fg text-sm placeholder:text-fg/40 focus:outline-none focus:border-[var(--border-hover)] transition-all resize-none"}),u.jsx("p",{className:"text-xs text-fg/50 ml-1",children:"Examples: google.com/search, localhost:, facebook.com, twitter.com"})]}),u.jsx("div",{className:"flex justify-end pt-2",children:u.jsxs("button",{onClick:T,disabled:N,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[N?u.jsx(Nt,{size:18,className:"animate-spin"}):u.jsx(fr,{size:18}),"Save Blacklist"]})})]})]})})]}),u.jsx("section",{className:"space-y-6 mt-8",children:u.jsxs("div",{className:"space-y-4",children:[u.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[u.jsx(qh,{size:14})," Blocked Tags"]}),u.jsxs("div",{className:"glass p-8 space-y-6",children:[u.jsx("div",{className:"space-y-2",children:u.jsx("p",{className:"text-sm text-fg/60",children:"Signals with these tags will be excluded from dynamic category generation and newsletters. Enter one tag per line."})}),u.jsxs("div",{className:"space-y-2",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Tags (separated by semicolon)"}),u.jsx("textarea",{value:w.join("; "),onChange:Y=>b(Y.target.value.split(";").map(Ie=>Ie.trim())),placeholder:"login; signup; footer; navigation",className:"w-full h-40 px-4 py-3 rounded-xl border border-border bg-surface text-fg text-sm placeholder:text-fg/40 focus:outline-none focus:border-[var(--border-hover)] transition-all resize-none"}),u.jsx("p",{className:"text-xs text-fg/50 ml-1",children:"You have full control. These tags will completely replace the system defaults."})]}),u.jsx("div",{className:"flex justify-end pt-2",children:u.jsxs("button",{onClick:ue,disabled:M,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[M?u.jsx(Nt,{size:18,className:"animate-spin"}):u.jsx(fr,{size:18}),"Save Blocked Tags"]})})]})]})})]})})]})}const mb=A.createContext(null);function OP({children:e}){const[t,n]=A.useState(!1),r=()=>n(!0),o=()=>n(!1);return u.jsx(mb.Provider,{value:{isExpanded:t,setIsExpanded:n,openTerminal:r,closeTerminal:o},children:e})}function IP(){const e=A.useContext(mb);if(!e)throw new Error("useTerminal must be used within a TerminalProvider");return e}function DP({isExpanded:e,onToggle:t,onNavigate:n,liftUp:r}={}){const[o,a]=A.useState([]),{isExpanded:l,setIsExpanded:d}=IP(),[h,p]=A.useState({}),m=e!==void 0?e:l,y=t||(()=>d(!l)),x=r?"bottom-32":"bottom-6";A.useEffect(()=>{w();const k=se.channel("processing_events_feed").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events"},_=>{const E=_.new;E.event_type==="error"&&p(N=>({...N,[E.id]:!0})),a(N=>{const R=[E,...N];return R.length>50?R.slice(0,50):R})}).subscribe();return()=>{se.removeChannel(k)}},[]);const w=async()=>{const{data:k}=await se.from("processing_events").select("*").order("created_at",{ascending:!1}).limit(30);k&&a(k)},b=k=>{p(_=>({..._,[k]:!_[k]}))},S=(k,_,E,N)=>{if(_==="debug")return u.jsx(dS,{size:14,className:"text-fg/40"});if(E?.is_completion||N?.is_completion)return u.jsx(vs,{size:14,className:"text-success"});switch(k){case"analysis":return u.jsx(Vx,{size:14,className:"text-primary"});case"action":return u.jsx(Xt,{size:14,className:"text-accent"});case"error":return u.jsx(Kg,{size:14,className:"text-error"});case"system":return u.jsx(ec,{size:14,className:"text-success"});default:return u.jsx(Kx,{size:14,className:"text-fg/40"})}};return m?u.jsxs(ze.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},className:"fixed bottom-6 right-6 z-50 w-[450px] max-h-[600px] glass shadow-2xl flex flex-col overflow-hidden border-primary/10",children:[u.jsxs("div",{className:"p-4 border-b border-border/10 flex items-center justify-between bg-surface/50",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(zl,{size:18,className:"text-primary"}),u.jsx("span",{className:"text-xs font-bold uppercase tracking-widest",children:"Alchemist Engine"}),u.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold bg-success/10 text-success px-2 py-0.5 rounded-full border border-success/10 animate-pulse ml-2",children:[u.jsx(oS,{size:10})," LIVE"]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{onClick:()=>a([]),className:"text-[10px] uppercase font-bold text-fg/40 hover:text-fg px-2 py-1 transition-colors",children:"Clear"}),u.jsx("button",{onClick:y,className:"text-fg/40 hover:text-fg p-1 transition-colors",children:u.jsx(TS,{size:18})})]})]}),u.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 custom-scrollbar bg-black/20",children:[o.length===0&&u.jsx("div",{className:"text-center py-12 text-fg/20 italic text-xs",children:"Idle. Awaiting signal mining events..."}),o.map(k=>u.jsxs("div",{className:"relative flex items-start gap-3 group",children:[u.jsx("div",{className:`mt-1 flex-shrink-0 w-6 h-6 rounded-full bg-surface border flex items-center justify-center ${k.metadata?.is_completion||k.details?.is_completion?"border-success/50 bg-success/5":"border-white/5"}`,children:S(k.event_type,k.level,k.metadata,k.details)}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[u.jsx("span",{className:"text-xs font-mono text-fg/60 shrink-0",children:new Date(k.created_at||Date.now()).toLocaleTimeString()}),u.jsx("span",{className:`text-xs font-bold uppercase tracking-wider ${k.level==="error"?"text-error":k.level==="warn"?"text-orange-400":k.event_type==="analysis"?"text-primary":"text-fg/90"}`,children:k.agent_state}),k.metadata?.actionable&&n&&u.jsxs("button",{onClick:()=>n("logs",k.metadata?.actionable),className:"ml-auto flex items-center gap-1 bg-primary/10 text-primary border border-primary/20 px-1.5 py-0.5 rounded text-[10px] uppercase font-bold tracking-wider hover:bg-primary/20 transition-all font-mono",children:[k.metadata.actionable.label,u.jsx(xi,{size:10,className:"-rotate-90"})]}),k.duration_ms&&!k.metadata?.actionable&&u.jsxs("span",{className:"ml-auto text-[10px] font-mono bg-bg/50 px-1.5 py-0.5 rounded flex items-center gap-1 text-fg/40",children:[u.jsx(vi,{size:10}),k.duration_ms,"ms"]})]}),k.metadata?.is_completion||k.details?.is_completion?u.jsxs("div",{className:"bg-success/5 border border-success/20 rounded-lg p-3 space-y-2 mt-2",children:[u.jsxs("div",{className:"flex items-center gap-2 text-success font-bold uppercase text-[9px] tracking-[0.2em]",children:[u.jsx(vs,{className:"w-3.5 h-3.5"}),"Mining Run Completed"]}),u.jsxs("div",{className:"grid grid-cols-3 gap-4 pt-1",children:[u.jsxs("div",{className:"space-y-0.5",children:[u.jsx("p",{className:"text-[10px] text-fg/40 uppercase",children:"Signals"}),u.jsx("p",{className:"text-sm font-bold text-primary",children:k.metadata?.signals_found||k.details?.signals_found||0})]}),u.jsxs("div",{className:"space-y-0.5",children:[u.jsx("p",{className:"text-[10px] text-fg/40 uppercase",children:"URLs"}),u.jsx("p",{className:"text-sm font-bold",children:k.metadata?.total_urls||k.details?.total_urls||0})]}),u.jsxs("div",{className:"space-y-0.5",children:[u.jsx("p",{className:"text-[10px] text-fg/40 uppercase",children:"Skipped"}),u.jsx("p",{className:"text-sm font-bold text-fg/60",children:k.metadata?.skipped||k.details?.skipped||0})]})]}),(k.metadata?.errors||k.details?.errors)>0&&u.jsxs("div",{className:"pt-1 border-t border-success/10 flex items-center justify-between mt-1",children:[u.jsxs("p",{className:"text-[10px] text-error font-bold flex items-center gap-1.5",children:[u.jsx(Kg,{size:12}),k.metadata?.errors||k.details?.errors," URLs failed to process"]}),n&&u.jsxs("button",{onClick:()=>n("logs",{filter:"errors"}),className:"flex items-center gap-1 text-[9px] uppercase font-bold text-error bg-error/10 border border-error/20 px-2 py-1 rounded hover:bg-error/20 transition-all group/btn",children:["View Logs",u.jsx(Cl,{size:10,className:"group-hover/btn:translate-x-0.5 transition-transform"})]})]})]}):u.jsx("p",{className:`text-sm break-words leading-relaxed ${k.level==="debug"?"text-fg/50 font-mono text-xs":""}`,children:k.message}),(k.details||k.metadata)&&u.jsxs("div",{className:"mt-2 text-xs",children:[u.jsxs("button",{onClick:()=>b(k.id),className:"flex items-center gap-1 text-fg/40 hover:text-primary transition-colors",children:[h[k.id]?u.jsx(qx,{size:12}):u.jsx(xi,{size:12}),h[k.id]?"Hide Details":"View Details"]}),u.jsx(Rt,{children:h[k.id]&&u.jsx(ze.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},className:"overflow-hidden",children:u.jsx("pre",{className:"mt-2 p-3 bg-bg/50 rounded border border-white/5 font-mono text-[10px] overflow-x-auto text-fg/70",children:JSON.stringify({...k.details,...k.metadata},null,2)})})})]})]})]},k.id))]})]}):u.jsxs("button",{onClick:y,className:`fixed ${x} right-6 z-50 glass p-4 flex items-center gap-3 hover:bg-surface transition-all shadow-xl group border-primary/10`,children:[u.jsxs("div",{className:"relative",children:[u.jsx(zl,{size:20,className:"text-primary"}),o.length>0&&u.jsxs("span",{className:"absolute -top-1 -right-1 flex h-2 w-2",children:[u.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-primary opacity-75"}),u.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-primary"})]})]}),u.jsx("span",{className:"text-xs font-bold uppercase tracking-widest hidden group-hover:block animate-in fade-in slide-in-from-right-2",children:"Live Engine Log"})]})}const gb="1.0.0",LP="20260127000003";async function MP(e){try{const{data:t,error:n}=await e.rpc("get_latest_migration_timestamp");return n?n.code==="42883"?{version:null,latestMigrationTimestamp:"0"}:{version:null,latestMigrationTimestamp:null}:{version:gb,latestMigrationTimestamp:t||null}}catch{return{version:null,latestMigrationTimestamp:null}}}async function zP(e){const t=gb,n=LP,r=await MP(e);if(r.latestMigrationTimestamp&&r.latestMigrationTimestamp.trim()!==""){const o=n,a=r.latestMigrationTimestamp;return o>a?{needsMigration:!0,appVersion:t,dbVersion:r.version,latestMigrationTimestamp:a,message:`New migrations available. Database is at ${a}, app has ${o}.`}:{needsMigration:!1,appVersion:t,dbVersion:r.version,latestMigrationTimestamp:a,message:"Database schema is up-to-date."}}return{needsMigration:!0,appVersion:t,dbVersion:null,latestMigrationTimestamp:null,message:"Database schema unknown. Migration required."}}function UP(){const[e,t]=A.useState("profile"),[n,r]=A.useState(!1);return u.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[u.jsxs("header",{className:"px-8 py-6 border-b border-border",children:[u.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Account Configuration"}),u.jsx("p",{className:"text-sm text-fg/50 font-medium",children:"Manage your Alchemist profile and essence links."})]}),u.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[u.jsxs("aside",{className:"w-64 border-r border-border p-4 space-y-1",children:[u.jsx(Md,{active:e==="profile",onClick:()=>t("profile"),icon:u.jsx(tc,{size:18}),label:"Profile"}),u.jsx(Md,{active:e==="security",onClick:()=>t("security"),icon:u.jsx(Gx,{size:18}),label:"Security"}),u.jsx(Md,{active:e==="supabase",onClick:()=>t("supabase"),icon:u.jsx(zo,{size:18}),label:"Supabase"})]}),u.jsxs("main",{className:"flex-1 overflow-y-auto custom-scrollbar p-8",children:[e==="profile"&&u.jsx(FP,{}),e==="security"&&u.jsx(BP,{}),e==="supabase"&&u.jsx($P,{})]})]})]})}function FP(){const[e,t]=A.useState(""),[n,r]=A.useState(""),[o,a]=A.useState(""),[l,d]=A.useState(!1),[h,p]=A.useState(!1),[m,y]=A.useState(null),[x,w]=A.useState(!0);A.useEffect(()=>{b()},[]);const b=async()=>{const{data:{user:_}}=await se.auth.getUser();if(!_)return;a(_.email||"");const{data:E}=await se.from("profiles").select("*").eq("id",_.id).maybeSingle();E&&(t(E.first_name||""),r(E.last_name||""),y(E.avatar_url));const{data:N}=await se.from("alchemy_settings").select("sound_enabled").eq("user_id",_.id).maybeSingle();N&&w(N.sound_enabled??!0)},S=async()=>{d(!0);const{data:{user:_}}=await se.auth.getUser();_&&(await se.from("profiles").upsert({id:_.id,first_name:e,last_name:n,full_name:e&&n?`${e} ${n}`:e||n||null}),await se.from("alchemy_settings").update({sound_enabled:x}).eq("user_id",_.id),d(!1))},k=async _=>{const E=_.target.files?.[0];if(E){p(!0);try{const{data:{user:N}}=await se.auth.getUser();if(!N)return;const R=E.name.split(".").pop(),M=`${N.id}/avatar-${Date.now()}.${R}`,{error:O}=await se.storage.from("avatars").upload(M,E,{upsert:!0});if(O)throw O;const{data:{publicUrl:V}}=se.storage.from("avatars").getPublicUrl(M);await se.from("profiles").update({avatar_url:V}).eq("id",N.id),y(V)}catch(N){console.error("Avatar upload failed:",N)}finally{p(!1)}}};return u.jsxs("div",{className:"max-w-2xl space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500",children:[u.jsxs("section",{className:"flex items-start gap-8",children:[u.jsxs("div",{className:"relative group",children:[u.jsx("div",{className:"w-32 h-32 rounded-3xl bg-surface border border-border flex items-center justify-center overflow-hidden shadow-xl",children:m?u.jsx("img",{src:m,alt:"Avatar",className:"w-full h-full object-cover"}):u.jsx(tc,{size:48,className:"text-fg/20"})}),u.jsxs("label",{className:"absolute inset-0 flex items-center justify-center bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer rounded-3xl",children:[u.jsx(fS,{size:24,className:"text-white"}),u.jsx("input",{type:"file",className:"hidden",accept:"image/*",onChange:k,disabled:h})]}),h&&u.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40 rounded-3xl",children:u.jsx(Nt,{size:24,className:"text-primary animate-spin"})})]}),u.jsxs("div",{className:"flex-1 space-y-4",children:[u.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[u.jsx(Yl,{label:"First Name",value:e,onChange:t,placeholder:"Zosimos"}),u.jsx(Yl,{label:"Last Name",value:n,onChange:r,placeholder:"of Panopolis"})]}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Email Address (Locked)"}),u.jsx("input",{type:"email",value:o,readOnly:!0,className:"w-full bg-black/5 border border-border rounded-xl py-3 px-4 text-sm text-fg/40 cursor-not-allowed"})]})]})]}),u.jsxs("section",{className:"glass p-6 space-y-4",children:[u.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[x?u.jsx(Zg,{size:20,className:"text-primary"}):u.jsx(ey,{size:20,className:"text-fg/40"}),"Sound Effects"]}),u.jsx("p",{className:"text-xs text-fg/40",children:"Enable audio feedback for sync events and signal discoveries."}),u.jsx("button",{onClick:()=>w(!x),className:`w-full p-4 rounded-xl border-2 transition-all ${x?"bg-primary/10 border-primary/30 text-primary":"bg-surface border-border text-fg/40"}`,children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("span",{className:"font-semibold text-sm",children:x?"Enabled":"Disabled"}),x?u.jsx(Zg,{size:18}):u.jsx(ey,{size:18})]})})]}),u.jsxs("section",{className:"glass p-6 space-y-4",children:[u.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[u.jsx(Yg,{size:20,className:"text-error"}),"Sign Out"]}),u.jsx("p",{className:"text-xs text-fg/40",children:"End your current session and return to the login screen."}),u.jsx("button",{onClick:()=>se.auth.signOut(),className:"w-full p-4 rounded-xl border-2 bg-error/10 border-error/30 text-error hover:bg-error hover:text-white transition-all",children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("span",{className:"font-semibold text-sm",children:"Logout"}),u.jsx(Yg,{size:18})]})})]}),u.jsx("div",{className:"flex justify-end pt-4 border-t border-border",children:u.jsxs("button",{onClick:S,disabled:l,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[l?u.jsx(Nt,{size:18,className:"animate-spin"}):u.jsx(fr,{size:18}),"Preserve Profile"]})})]})}function BP(){const[e,t]=A.useState(""),[n,r]=A.useState(""),[o,a]=A.useState(!1),[l,d]=A.useState(null),[h,p]=A.useState(!1),m=async()=>{if(!e||e!==n){d("Complexity keys do not match.");return}if(e.length<8){d("Entropy too low. Minimum 8 characters.");return}a(!0),d(null),p(!1);const{error:y}=await se.auth.updateUser({password:e});y?d(y.message):(p(!0),t(""),r("")),a(!1)};return u.jsx("div",{className:"max-w-2xl space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500",children:u.jsxs("div",{className:"glass p-6 space-y-6",children:[u.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[u.jsx(SS,{size:20,className:"text-error"})," Update Entropy Key"]}),u.jsxs("div",{className:"space-y-4",children:[u.jsx(Yl,{label:"New Password",type:"password",value:e,onChange:t,placeholder:"••••••••"}),u.jsx(Yl,{label:"Confirm Password",type:"password",value:n,onChange:r,placeholder:"••••••••"})]}),l&&u.jsx("p",{className:"text-xs text-error font-mono bg-error/5 p-3 rounded-lg border border-error/10",children:l}),h&&u.jsx("p",{className:"text-xs text-success font-mono bg-success/5 p-3 rounded-lg border border-success/10",children:"Key rotation successful."}),u.jsx("div",{className:"flex justify-end pt-2",children:u.jsxs("button",{onClick:m,disabled:o,className:"px-6 py-3 bg-error/10 text-error hover:bg-error hover:text-white font-bold rounded-xl border border-error/20 transition-all flex items-center gap-2",children:[o?u.jsx(Nt,{size:18,className:"animate-spin"}):u.jsx(Gx,{size:18}),"Rotate Key"]})})]})})}function $P(){const[e,t]=A.useState(!1),[n,r]=A.useState(null),o=ks(),a=bP();A.useEffect(()=>{o&&zP(se).then(r)},[]);const l=()=>{confirm("Sever connection to this essence? This will reset local resonance.")&&(vP(),window.location.reload())};return u.jsxs("div",{className:"max-w-2xl space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500",children:[u.jsxs("section",{className:"space-y-6",children:[u.jsx("div",{className:"flex items-center justify-between",children:u.jsxs("div",{children:[u.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[u.jsx(zo,{size:20,className:"text-primary"})," Essence Resonance"]}),u.jsx("p",{className:"text-xs text-fg/40 font-medium",children:"Bring Your Own Keys (BYOK) for intelligence persistence."})]})}),u.jsx("div",{className:"glass p-8 space-y-8",children:o?u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"flex items-start gap-4 p-4 glass bg-emerald-500/5 border border-emerald-500/20 rounded-2xl",children:[u.jsx(vs,{className:"w-6 h-6 text-emerald-500 mt-1"}),u.jsxs("div",{className:"flex-1 space-y-1",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("p",{className:"font-bold text-fg italic uppercase tracking-tighter",children:"Established Link"}),n?.latestMigrationTimestamp&&u.jsxs("span",{className:"text-[10px] font-mono bg-emerald-500/10 text-emerald-500 px-2 py-0.5 rounded-full border border-emerald-500/20",children:["v",n.latestMigrationTimestamp]})]}),u.jsx("p",{className:"text-xs font-mono text-fg/40 break-all",children:o.url})]})]}),a==="env"&&u.jsxs("div",{className:"flex items-center gap-3 p-3 bg-amber-500/5 border border-amber-500/10 rounded-xl",children:[u.jsx(pr,{size:16,className:"text-amber-500"}),u.jsx("p",{className:"text-[10px] text-amber-500 font-bold uppercase tracking-widest leading-none",children:"Active from environment variables. UI override enabled."})]}),u.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[u.jsxs("button",{onClick:()=>t(!0),className:"px-4 py-3 glass hover:bg-surface text-xs font-bold uppercase tracking-widest transition-all flex items-center justify-center gap-2",children:[u.jsx(ec,{size:14})," Realign Link"]}),a==="ui"&&u.jsxs("button",{onClick:l,className:"px-4 py-3 glass border-error/10 hover:bg-error/10 text-error/60 hover:text-error text-xs font-bold uppercase tracking-widest transition-all flex items-center justify-center gap-2",children:[u.jsx(Wh,{size:14})," Sever Link"]})]}),u.jsxs("div",{className:"space-y-1 pt-4 border-t border-border/10",children:[u.jsx("label",{className:"text-[9px] font-bold uppercase tracking-widest text-fg/20 ml-1",children:"Anon Secret Fragment"}),u.jsxs("div",{className:"p-3 bg-surface/50 rounded-xl font-mono text-[11px] text-fg/30 break-all border border-border",children:[o.anonKey.substring(0,32),"..."]})]})]}):u.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-6",children:[u.jsx(zo,{size:48,className:"text-fg/10"}),u.jsxs("div",{className:"space-y-2",children:[u.jsx("p",{className:"font-bold italic uppercase tracking-tighter",children:"No Essence Resonance"}),u.jsx("p",{className:"text-xs text-fg/40 max-w-[240px]",children:"The Alchemist requires a cloud core to store intelligence fragments."})]}),u.jsx("button",{onClick:()=>t(!0),className:"px-8 py-3 bg-primary text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] transition-all uppercase tracking-widest text-xs",children:"Initiate Link"})]})})]}),u.jsx(hb,{open:e,onComplete:()=>t(!1),canClose:!0})]})}function Md({active:e,icon:t,label:n,onClick:r}){return u.jsxs("button",{onClick:r,className:`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all ${e?"glass bg-primary/10 text-primary border-primary/20 shadow-sm":"text-fg/40 hover:bg-surface hover:text-fg"}`,children:[e?Mo.cloneElement(t,{className:"text-primary"}):t,u.jsx("span",{className:"font-semibold text-sm",children:n})]})}function Yl({label:e,value:t,onChange:n,placeholder:r,type:o="text"}){return u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:e}),u.jsx("input",{type:o,value:t,onChange:a=>n(a.target.value),className:"w-full bg-surface border border-border rounded-xl py-3 px-4 text-sm text-fg placeholder:text-fg/40 focus:border-[var(--border-hover)] outline-none transition-all",placeholder:r})]})}function VP({signal:e,onClose:t}){const[n,r]=Mo.useState(!1);if(!e)return null;const o=()=>{const d=`# ${e.title}
|
|
78
|
+
linkedin.com/feed`,className:"w-full h-40 px-4 py-3 rounded-xl border border-border bg-surface text-fg text-sm placeholder:text-fg/40 focus:outline-none focus:border-[var(--border-hover)] transition-all resize-none"}),u.jsx("p",{className:"text-xs text-fg/50 ml-1",children:"Examples: google.com/search, localhost:, facebook.com, twitter.com"})]}),u.jsx("div",{className:"flex justify-end pt-2",children:u.jsxs("button",{onClick:T,disabled:N,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[N?u.jsx(Nt,{size:18,className:"animate-spin"}):u.jsx(fr,{size:18}),"Save Blacklist"]})})]})]})})]}),u.jsx("section",{className:"space-y-6 mt-8",children:u.jsxs("div",{className:"space-y-4",children:[u.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[u.jsx(qh,{size:14})," Blocked Tags"]}),u.jsxs("div",{className:"glass p-8 space-y-6",children:[u.jsx("div",{className:"space-y-2",children:u.jsx("p",{className:"text-sm text-fg/60",children:"Signals with these tags will be excluded from dynamic category generation and newsletters. Enter one tag per line."})}),u.jsxs("div",{className:"space-y-2",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Tags (separated by semicolon)"}),u.jsx("textarea",{value:w.join("; "),onChange:Y=>b(Y.target.value.split(";").map(Ie=>Ie.trim())),placeholder:"login; signup; footer; navigation",className:"w-full h-40 px-4 py-3 rounded-xl border border-border bg-surface text-fg text-sm placeholder:text-fg/40 focus:outline-none focus:border-[var(--border-hover)] transition-all resize-none"}),u.jsx("p",{className:"text-xs text-fg/50 ml-1",children:"You have full control. These tags will completely replace the system defaults."})]}),u.jsx("div",{className:"flex justify-end pt-2",children:u.jsxs("button",{onClick:ue,disabled:M,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[M?u.jsx(Nt,{size:18,className:"animate-spin"}):u.jsx(fr,{size:18}),"Save Blocked Tags"]})})]})]})})]})})]})}const mb=A.createContext(null);function OP({children:e}){const[t,n]=A.useState(!1),r=()=>n(!0),o=()=>n(!1);return u.jsx(mb.Provider,{value:{isExpanded:t,setIsExpanded:n,openTerminal:r,closeTerminal:o},children:e})}function IP(){const e=A.useContext(mb);if(!e)throw new Error("useTerminal must be used within a TerminalProvider");return e}function DP({isExpanded:e,onToggle:t,onNavigate:n,liftUp:r}={}){const[o,a]=A.useState([]),{isExpanded:l,setIsExpanded:d}=IP(),[h,p]=A.useState({}),m=e!==void 0?e:l,y=t||(()=>d(!l)),x=r?"bottom-32":"bottom-6";A.useEffect(()=>{w();const k=se.channel("processing_events_feed").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events"},_=>{const E=_.new;E.event_type==="error"&&p(N=>({...N,[E.id]:!0})),a(N=>{const R=[E,...N];return R.length>50?R.slice(0,50):R})}).subscribe();return()=>{se.removeChannel(k)}},[]);const w=async()=>{const{data:k}=await se.from("processing_events").select("*").order("created_at",{ascending:!1}).limit(30);k&&a(k)},b=k=>{p(_=>({..._,[k]:!_[k]}))},S=(k,_,E,N)=>{if(_==="debug")return u.jsx(dS,{size:14,className:"text-fg/40"});if(E?.is_completion||N?.is_completion)return u.jsx(vs,{size:14,className:"text-success"});switch(k){case"analysis":return u.jsx(Vx,{size:14,className:"text-primary"});case"action":return u.jsx(Xt,{size:14,className:"text-accent"});case"error":return u.jsx(Kg,{size:14,className:"text-error"});case"system":return u.jsx(ec,{size:14,className:"text-success"});default:return u.jsx(Kx,{size:14,className:"text-fg/40"})}};return m?u.jsxs(ze.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},className:"fixed bottom-6 right-6 z-50 w-[450px] max-h-[600px] glass shadow-2xl flex flex-col overflow-hidden border-primary/10",children:[u.jsxs("div",{className:"p-4 border-b border-border/10 flex items-center justify-between bg-surface/50",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(zl,{size:18,className:"text-primary"}),u.jsx("span",{className:"text-xs font-bold uppercase tracking-widest",children:"Alchemist Engine"}),u.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold bg-success/10 text-success px-2 py-0.5 rounded-full border border-success/10 animate-pulse ml-2",children:[u.jsx(oS,{size:10})," LIVE"]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{onClick:()=>a([]),className:"text-[10px] uppercase font-bold text-fg/40 hover:text-fg px-2 py-1 transition-colors",children:"Clear"}),u.jsx("button",{onClick:y,className:"text-fg/40 hover:text-fg p-1 transition-colors",children:u.jsx(TS,{size:18})})]})]}),u.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 custom-scrollbar bg-black/20",children:[o.length===0&&u.jsx("div",{className:"text-center py-12 text-fg/20 italic text-xs",children:"Idle. Awaiting signal mining events..."}),o.map(k=>u.jsxs("div",{className:"relative flex items-start gap-3 group",children:[u.jsx("div",{className:`mt-1 flex-shrink-0 w-6 h-6 rounded-full bg-surface border flex items-center justify-center ${k.metadata?.is_completion||k.details?.is_completion?"border-success/50 bg-success/5":"border-white/5"}`,children:S(k.event_type,k.level,k.metadata,k.details)}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[u.jsx("span",{className:"text-xs font-mono text-fg/60 shrink-0",children:new Date(k.created_at||Date.now()).toLocaleTimeString()}),u.jsx("span",{className:`text-xs font-bold uppercase tracking-wider ${k.level==="error"?"text-error":k.level==="warn"?"text-orange-400":k.event_type==="analysis"?"text-primary":"text-fg/90"}`,children:k.agent_state}),k.metadata?.actionable&&n&&u.jsxs("button",{onClick:()=>n("logs",k.metadata?.actionable),className:"ml-auto flex items-center gap-1 bg-primary/10 text-primary border border-primary/20 px-1.5 py-0.5 rounded text-[10px] uppercase font-bold tracking-wider hover:bg-primary/20 transition-all font-mono",children:[k.metadata.actionable.label,u.jsx(xi,{size:10,className:"-rotate-90"})]}),k.duration_ms&&!k.metadata?.actionable&&u.jsxs("span",{className:"ml-auto text-[10px] font-mono bg-bg/50 px-1.5 py-0.5 rounded flex items-center gap-1 text-fg/40",children:[u.jsx(vi,{size:10}),k.duration_ms,"ms"]})]}),k.metadata?.is_completion||k.details?.is_completion?u.jsxs("div",{className:"bg-success/5 border border-success/20 rounded-lg p-3 space-y-2 mt-2",children:[u.jsxs("div",{className:"flex items-center gap-2 text-success font-bold uppercase text-[9px] tracking-[0.2em]",children:[u.jsx(vs,{className:"w-3.5 h-3.5"}),"Mining Run Completed"]}),u.jsxs("div",{className:"grid grid-cols-3 gap-4 pt-1",children:[u.jsxs("div",{className:"space-y-0.5",children:[u.jsx("p",{className:"text-[10px] text-fg/40 uppercase",children:"Signals"}),u.jsx("p",{className:"text-sm font-bold text-primary",children:k.metadata?.signals_found||k.details?.signals_found||0})]}),u.jsxs("div",{className:"space-y-0.5",children:[u.jsx("p",{className:"text-[10px] text-fg/40 uppercase",children:"URLs"}),u.jsx("p",{className:"text-sm font-bold",children:k.metadata?.total_urls||k.details?.total_urls||0})]}),u.jsxs("div",{className:"space-y-0.5",children:[u.jsx("p",{className:"text-[10px] text-fg/40 uppercase",children:"Skipped"}),u.jsx("p",{className:"text-sm font-bold text-fg/60",children:k.metadata?.skipped||k.details?.skipped||0})]})]}),(k.metadata?.errors||k.details?.errors)>0&&u.jsxs("div",{className:"pt-1 border-t border-success/10 flex items-center justify-between mt-1",children:[u.jsxs("p",{className:"text-[10px] text-error font-bold flex items-center gap-1.5",children:[u.jsx(Kg,{size:12}),k.metadata?.errors||k.details?.errors," URLs failed to process"]}),n&&u.jsxs("button",{onClick:()=>n("logs",{filter:"errors"}),className:"flex items-center gap-1 text-[9px] uppercase font-bold text-error bg-error/10 border border-error/20 px-2 py-1 rounded hover:bg-error/20 transition-all group/btn",children:["View Logs",u.jsx(Cl,{size:10,className:"group-hover/btn:translate-x-0.5 transition-transform"})]})]})]}):u.jsx("p",{className:`text-sm break-words leading-relaxed ${k.level==="debug"?"text-fg/50 font-mono text-xs":""}`,children:k.message}),(k.details||k.metadata)&&u.jsxs("div",{className:"mt-2 text-xs",children:[u.jsxs("button",{onClick:()=>b(k.id),className:"flex items-center gap-1 text-fg/40 hover:text-primary transition-colors",children:[h[k.id]?u.jsx(qx,{size:12}):u.jsx(xi,{size:12}),h[k.id]?"Hide Details":"View Details"]}),u.jsx(Rt,{children:h[k.id]&&u.jsx(ze.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},className:"overflow-hidden",children:u.jsx("pre",{className:"mt-2 p-3 bg-bg/50 rounded border border-white/5 font-mono text-[10px] overflow-x-auto text-fg/70",children:JSON.stringify({...k.details,...k.metadata},null,2)})})})]})]})]},k.id))]})]}):u.jsxs("button",{onClick:y,className:`fixed ${x} right-6 z-50 glass p-4 flex items-center gap-3 hover:bg-surface transition-all shadow-xl group border-primary/10`,children:[u.jsxs("div",{className:"relative",children:[u.jsx(zl,{size:20,className:"text-primary"}),o.length>0&&u.jsxs("span",{className:"absolute -top-1 -right-1 flex h-2 w-2",children:[u.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-primary opacity-75"}),u.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-primary"})]})]}),u.jsx("span",{className:"text-xs font-bold uppercase tracking-widest hidden group-hover:block animate-in fade-in slide-in-from-right-2",children:"Live Engine Log"})]})}const gb="1.0.0",LP="20260127000004";async function MP(e){try{const{data:t,error:n}=await e.rpc("get_latest_migration_timestamp");return n?n.code==="42883"?{version:null,latestMigrationTimestamp:"0"}:{version:null,latestMigrationTimestamp:null}:{version:gb,latestMigrationTimestamp:t||null}}catch{return{version:null,latestMigrationTimestamp:null}}}async function zP(e){const t=gb,n=LP,r=await MP(e);if(r.latestMigrationTimestamp&&r.latestMigrationTimestamp.trim()!==""){const o=n,a=r.latestMigrationTimestamp;return o>a?{needsMigration:!0,appVersion:t,dbVersion:r.version,latestMigrationTimestamp:a,message:`New migrations available. Database is at ${a}, app has ${o}.`}:{needsMigration:!1,appVersion:t,dbVersion:r.version,latestMigrationTimestamp:a,message:"Database schema is up-to-date."}}return{needsMigration:!0,appVersion:t,dbVersion:null,latestMigrationTimestamp:null,message:"Database schema unknown. Migration required."}}function UP(){const[e,t]=A.useState("profile"),[n,r]=A.useState(!1);return u.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[u.jsxs("header",{className:"px-8 py-6 border-b border-border",children:[u.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Account Configuration"}),u.jsx("p",{className:"text-sm text-fg/50 font-medium",children:"Manage your Alchemist profile and essence links."})]}),u.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[u.jsxs("aside",{className:"w-64 border-r border-border p-4 space-y-1",children:[u.jsx(Md,{active:e==="profile",onClick:()=>t("profile"),icon:u.jsx(tc,{size:18}),label:"Profile"}),u.jsx(Md,{active:e==="security",onClick:()=>t("security"),icon:u.jsx(Gx,{size:18}),label:"Security"}),u.jsx(Md,{active:e==="supabase",onClick:()=>t("supabase"),icon:u.jsx(zo,{size:18}),label:"Supabase"})]}),u.jsxs("main",{className:"flex-1 overflow-y-auto custom-scrollbar p-8",children:[e==="profile"&&u.jsx(FP,{}),e==="security"&&u.jsx(BP,{}),e==="supabase"&&u.jsx($P,{})]})]})]})}function FP(){const[e,t]=A.useState(""),[n,r]=A.useState(""),[o,a]=A.useState(""),[l,d]=A.useState(!1),[h,p]=A.useState(!1),[m,y]=A.useState(null),[x,w]=A.useState(!0);A.useEffect(()=>{b()},[]);const b=async()=>{const{data:{user:_}}=await se.auth.getUser();if(!_)return;a(_.email||"");const{data:E}=await se.from("profiles").select("*").eq("id",_.id).maybeSingle();E&&(t(E.first_name||""),r(E.last_name||""),y(E.avatar_url));const{data:N}=await se.from("alchemy_settings").select("sound_enabled").eq("user_id",_.id).maybeSingle();N&&w(N.sound_enabled??!0)},S=async()=>{d(!0);const{data:{user:_}}=await se.auth.getUser();_&&(await se.from("profiles").upsert({id:_.id,first_name:e,last_name:n,full_name:e&&n?`${e} ${n}`:e||n||null}),await se.from("alchemy_settings").update({sound_enabled:x}).eq("user_id",_.id),d(!1))},k=async _=>{const E=_.target.files?.[0];if(E){p(!0);try{const{data:{user:N}}=await se.auth.getUser();if(!N)return;const R=E.name.split(".").pop(),M=`${N.id}/avatar-${Date.now()}.${R}`,{error:O}=await se.storage.from("avatars").upload(M,E,{upsert:!0});if(O)throw O;const{data:{publicUrl:V}}=se.storage.from("avatars").getPublicUrl(M);await se.from("profiles").update({avatar_url:V}).eq("id",N.id),y(V)}catch(N){console.error("Avatar upload failed:",N)}finally{p(!1)}}};return u.jsxs("div",{className:"max-w-2xl space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500",children:[u.jsxs("section",{className:"flex items-start gap-8",children:[u.jsxs("div",{className:"relative group",children:[u.jsx("div",{className:"w-32 h-32 rounded-3xl bg-surface border border-border flex items-center justify-center overflow-hidden shadow-xl",children:m?u.jsx("img",{src:m,alt:"Avatar",className:"w-full h-full object-cover"}):u.jsx(tc,{size:48,className:"text-fg/20"})}),u.jsxs("label",{className:"absolute inset-0 flex items-center justify-center bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer rounded-3xl",children:[u.jsx(fS,{size:24,className:"text-white"}),u.jsx("input",{type:"file",className:"hidden",accept:"image/*",onChange:k,disabled:h})]}),h&&u.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40 rounded-3xl",children:u.jsx(Nt,{size:24,className:"text-primary animate-spin"})})]}),u.jsxs("div",{className:"flex-1 space-y-4",children:[u.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[u.jsx(Yl,{label:"First Name",value:e,onChange:t,placeholder:"Zosimos"}),u.jsx(Yl,{label:"Last Name",value:n,onChange:r,placeholder:"of Panopolis"})]}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Email Address (Locked)"}),u.jsx("input",{type:"email",value:o,readOnly:!0,className:"w-full bg-black/5 border border-border rounded-xl py-3 px-4 text-sm text-fg/40 cursor-not-allowed"})]})]})]}),u.jsxs("section",{className:"glass p-6 space-y-4",children:[u.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[x?u.jsx(Zg,{size:20,className:"text-primary"}):u.jsx(ey,{size:20,className:"text-fg/40"}),"Sound Effects"]}),u.jsx("p",{className:"text-xs text-fg/40",children:"Enable audio feedback for sync events and signal discoveries."}),u.jsx("button",{onClick:()=>w(!x),className:`w-full p-4 rounded-xl border-2 transition-all ${x?"bg-primary/10 border-primary/30 text-primary":"bg-surface border-border text-fg/40"}`,children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("span",{className:"font-semibold text-sm",children:x?"Enabled":"Disabled"}),x?u.jsx(Zg,{size:18}):u.jsx(ey,{size:18})]})})]}),u.jsxs("section",{className:"glass p-6 space-y-4",children:[u.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[u.jsx(Yg,{size:20,className:"text-error"}),"Sign Out"]}),u.jsx("p",{className:"text-xs text-fg/40",children:"End your current session and return to the login screen."}),u.jsx("button",{onClick:()=>se.auth.signOut(),className:"w-full p-4 rounded-xl border-2 bg-error/10 border-error/30 text-error hover:bg-error hover:text-white transition-all",children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("span",{className:"font-semibold text-sm",children:"Logout"}),u.jsx(Yg,{size:18})]})})]}),u.jsx("div",{className:"flex justify-end pt-4 border-t border-border",children:u.jsxs("button",{onClick:S,disabled:l,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[l?u.jsx(Nt,{size:18,className:"animate-spin"}):u.jsx(fr,{size:18}),"Preserve Profile"]})})]})}function BP(){const[e,t]=A.useState(""),[n,r]=A.useState(""),[o,a]=A.useState(!1),[l,d]=A.useState(null),[h,p]=A.useState(!1),m=async()=>{if(!e||e!==n){d("Complexity keys do not match.");return}if(e.length<8){d("Entropy too low. Minimum 8 characters.");return}a(!0),d(null),p(!1);const{error:y}=await se.auth.updateUser({password:e});y?d(y.message):(p(!0),t(""),r("")),a(!1)};return u.jsx("div",{className:"max-w-2xl space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500",children:u.jsxs("div",{className:"glass p-6 space-y-6",children:[u.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[u.jsx(SS,{size:20,className:"text-error"})," Update Entropy Key"]}),u.jsxs("div",{className:"space-y-4",children:[u.jsx(Yl,{label:"New Password",type:"password",value:e,onChange:t,placeholder:"••••••••"}),u.jsx(Yl,{label:"Confirm Password",type:"password",value:n,onChange:r,placeholder:"••••••••"})]}),l&&u.jsx("p",{className:"text-xs text-error font-mono bg-error/5 p-3 rounded-lg border border-error/10",children:l}),h&&u.jsx("p",{className:"text-xs text-success font-mono bg-success/5 p-3 rounded-lg border border-success/10",children:"Key rotation successful."}),u.jsx("div",{className:"flex justify-end pt-2",children:u.jsxs("button",{onClick:m,disabled:o,className:"px-6 py-3 bg-error/10 text-error hover:bg-error hover:text-white font-bold rounded-xl border border-error/20 transition-all flex items-center gap-2",children:[o?u.jsx(Nt,{size:18,className:"animate-spin"}):u.jsx(Gx,{size:18}),"Rotate Key"]})})]})})}function $P(){const[e,t]=A.useState(!1),[n,r]=A.useState(null),o=ks(),a=bP();A.useEffect(()=>{o&&zP(se).then(r)},[]);const l=()=>{confirm("Sever connection to this essence? This will reset local resonance.")&&(vP(),window.location.reload())};return u.jsxs("div",{className:"max-w-2xl space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500",children:[u.jsxs("section",{className:"space-y-6",children:[u.jsx("div",{className:"flex items-center justify-between",children:u.jsxs("div",{children:[u.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[u.jsx(zo,{size:20,className:"text-primary"})," Essence Resonance"]}),u.jsx("p",{className:"text-xs text-fg/40 font-medium",children:"Bring Your Own Keys (BYOK) for intelligence persistence."})]})}),u.jsx("div",{className:"glass p-8 space-y-8",children:o?u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"flex items-start gap-4 p-4 glass bg-emerald-500/5 border border-emerald-500/20 rounded-2xl",children:[u.jsx(vs,{className:"w-6 h-6 text-emerald-500 mt-1"}),u.jsxs("div",{className:"flex-1 space-y-1",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("p",{className:"font-bold text-fg italic uppercase tracking-tighter",children:"Established Link"}),n?.latestMigrationTimestamp&&u.jsxs("span",{className:"text-[10px] font-mono bg-emerald-500/10 text-emerald-500 px-2 py-0.5 rounded-full border border-emerald-500/20",children:["v",n.latestMigrationTimestamp]})]}),u.jsx("p",{className:"text-xs font-mono text-fg/40 break-all",children:o.url})]})]}),a==="env"&&u.jsxs("div",{className:"flex items-center gap-3 p-3 bg-amber-500/5 border border-amber-500/10 rounded-xl",children:[u.jsx(pr,{size:16,className:"text-amber-500"}),u.jsx("p",{className:"text-[10px] text-amber-500 font-bold uppercase tracking-widest leading-none",children:"Active from environment variables. UI override enabled."})]}),u.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[u.jsxs("button",{onClick:()=>t(!0),className:"px-4 py-3 glass hover:bg-surface text-xs font-bold uppercase tracking-widest transition-all flex items-center justify-center gap-2",children:[u.jsx(ec,{size:14})," Realign Link"]}),a==="ui"&&u.jsxs("button",{onClick:l,className:"px-4 py-3 glass border-error/10 hover:bg-error/10 text-error/60 hover:text-error text-xs font-bold uppercase tracking-widest transition-all flex items-center justify-center gap-2",children:[u.jsx(Wh,{size:14})," Sever Link"]})]}),u.jsxs("div",{className:"space-y-1 pt-4 border-t border-border/10",children:[u.jsx("label",{className:"text-[9px] font-bold uppercase tracking-widest text-fg/20 ml-1",children:"Anon Secret Fragment"}),u.jsxs("div",{className:"p-3 bg-surface/50 rounded-xl font-mono text-[11px] text-fg/30 break-all border border-border",children:[o.anonKey.substring(0,32),"..."]})]})]}):u.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-6",children:[u.jsx(zo,{size:48,className:"text-fg/10"}),u.jsxs("div",{className:"space-y-2",children:[u.jsx("p",{className:"font-bold italic uppercase tracking-tighter",children:"No Essence Resonance"}),u.jsx("p",{className:"text-xs text-fg/40 max-w-[240px]",children:"The Alchemist requires a cloud core to store intelligence fragments."})]}),u.jsx("button",{onClick:()=>t(!0),className:"px-8 py-3 bg-primary text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] transition-all uppercase tracking-widest text-xs",children:"Initiate Link"})]})})]}),u.jsx(hb,{open:e,onComplete:()=>t(!1),canClose:!0})]})}function Md({active:e,icon:t,label:n,onClick:r}){return u.jsxs("button",{onClick:r,className:`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all ${e?"glass bg-primary/10 text-primary border-primary/20 shadow-sm":"text-fg/40 hover:bg-surface hover:text-fg"}`,children:[e?Mo.cloneElement(t,{className:"text-primary"}):t,u.jsx("span",{className:"font-semibold text-sm",children:n})]})}function Yl({label:e,value:t,onChange:n,placeholder:r,type:o="text"}){return u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:e}),u.jsx("input",{type:o,value:t,onChange:a=>n(a.target.value),className:"w-full bg-surface border border-border rounded-xl py-3 px-4 text-sm text-fg placeholder:text-fg/40 focus:border-[var(--border-hover)] outline-none transition-all",placeholder:r})]})}function VP({signal:e,onClose:t}){const[n,r]=Mo.useState(!1);if(!e)return null;const o=()=>{const d=`# ${e.title}
|
|
79
79
|
|
|
80
80
|
**Category**: ${e.category||"Research"}
|
|
81
81
|
**Intelligence Score**: ${e.score}/100
|
|
@@ -122,4 +122,4 @@ ${e.content}`:""}`,h=new Blob([d],{type:"text/markdown"}),p=URL.createObjectURL(
|
|
|
122
122
|
`}),n}function Px(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function Rx(e,t){const n=qI(e,t),r=n.one(e,void 0),o=OI(n),a=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return o&&a.children.push({type:"text",value:`
|
|
123
123
|
`},o),a}function JI(e,t){return e&&"run"in e?async function(n,r){const o=Rx(n,{file:r,...t});await e.run(o,r)}:function(n,r){return Rx(n,{file:r,...e||t})}}function Ox(e){if(e)throw e}var Vd,Ix;function YI(){if(Ix)return Vd;Ix=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,o=function(p){return typeof Array.isArray=="function"?Array.isArray(p):t.call(p)==="[object Array]"},a=function(p){if(!p||t.call(p)!=="[object Object]")return!1;var m=e.call(p,"constructor"),y=p.constructor&&p.constructor.prototype&&e.call(p.constructor.prototype,"isPrototypeOf");if(p.constructor&&!m&&!y)return!1;var x;for(x in p);return typeof x>"u"||e.call(p,x)},l=function(p,m){n&&m.name==="__proto__"?n(p,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):p[m.name]=m.newValue},d=function(p,m){if(m==="__proto__")if(e.call(p,m)){if(r)return r(p,m).value}else return;return p[m]};return Vd=function h(){var p,m,y,x,w,b,S=arguments[0],k=1,_=arguments.length,E=!1;for(typeof S=="boolean"&&(E=S,S=arguments[1]||{},k=2),(S==null||typeof S!="object"&&typeof S!="function")&&(S={});k<_;++k)if(p=arguments[k],p!=null)for(m in p)y=d(S,m),x=d(p,m),S!==x&&(E&&x&&(a(x)||(w=o(x)))?(w?(w=!1,b=y&&o(y)?y:[]):b=y&&a(y)?y:{},l(S,{name:m,newValue:h(E,b,x)})):typeof x<"u"&&l(S,{name:m,newValue:x}));return S},Vd}var XI=YI();const qd=Zl(XI);function Fh(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function QI(){const e=[],t={run:n,use:r};return t;function n(...o){let a=-1;const l=o.pop();if(typeof l!="function")throw new TypeError("Expected function as last argument, not "+l);d(null,...o);function d(h,...p){const m=e[++a];let y=-1;if(h){l(h);return}for(;++y<o.length;)(p[y]===null||p[y]===void 0)&&(p[y]=o[y]);o=p,m?ZI(m,d)(...p):l(null,...p)}}function r(o){if(typeof o!="function")throw new TypeError("Expected `middelware` to be a function, not "+o);return e.push(o),t}}function ZI(e,t){let n;return r;function r(...l){const d=e.length>l.length;let h;d&&l.push(o);try{h=e.apply(this,l)}catch(p){const m=p;if(d&&n)throw m;return o(m)}d||(h&&h.then&&typeof h.then=="function"?h.then(a,o):h instanceof Error?o(h):a(h))}function o(l,...d){n||(n=!0,t(l,...d))}function a(l){o(null,l)}}const Zn={basename:e5,dirname:t5,extname:n5,join:r5,sep:"/"};function e5(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');aa(e);let n=0,r=-1,o=e.length,a;if(t===void 0||t.length===0||t.length>e.length){for(;o--;)if(e.codePointAt(o)===47){if(a){n=o+1;break}}else r<0&&(a=!0,r=o+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let l=-1,d=t.length-1;for(;o--;)if(e.codePointAt(o)===47){if(a){n=o+1;break}}else l<0&&(a=!0,l=o+1),d>-1&&(e.codePointAt(o)===t.codePointAt(d--)?d<0&&(r=o):(d=-1,r=l));return n===r?r=l:r<0&&(r=e.length),e.slice(n,r)}function t5(e){if(aa(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function n5(e){aa(e);let t=e.length,n=-1,r=0,o=-1,a=0,l;for(;t--;){const d=e.codePointAt(t);if(d===47){if(l){r=t+1;break}continue}n<0&&(l=!0,n=t+1),d===46?o<0?o=t:a!==1&&(a=1):o>-1&&(a=-1)}return o<0||n<0||a===0||a===1&&o===n-1&&o===r+1?"":e.slice(o,n)}function r5(...e){let t=-1,n;for(;++t<e.length;)aa(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":s5(n)}function s5(e){aa(e);const t=e.codePointAt(0)===47;let n=i5(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function i5(e,t){let n="",r=0,o=-1,a=0,l=-1,d,h;for(;++l<=e.length;){if(l<e.length)d=e.codePointAt(l);else{if(d===47)break;d=47}if(d===47){if(!(o===l-1||a===1))if(o!==l-1&&a===2){if(n.length<2||r!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(h=n.lastIndexOf("/"),h!==n.length-1){h<0?(n="",r=0):(n=n.slice(0,h),r=n.length-1-n.lastIndexOf("/")),o=l,a=0;continue}}else if(n.length>0){n="",r=0,o=l,a=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(o+1,l):n=e.slice(o+1,l),r=l-o-1;o=l,a=0}else d===46&&a>-1?a++:a=-1}return n}function aa(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const o5={cwd:a5};function a5(){return"/"}function Bh(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function l5(e){if(typeof e=="string")e=new URL(e);else if(!Bh(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return c5(e)}function c5(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){const r=t.codePointAt(n+2);if(r===70||r===102){const o=new TypeError("File URL path must not include encoded / characters");throw o.code="ERR_INVALID_FILE_URL_PATH",o}}return decodeURIComponent(t)}const Hd=["history","path","basename","stem","extname","dirname"];class Zb{constructor(t){let n;t?Bh(t)?n={path:t}:typeof t=="string"||u5(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":o5.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<Hd.length;){const a=Hd[r];a in n&&n[a]!==void 0&&n[a]!==null&&(this[a]=a==="history"?[...n[a]]:n[a])}let o;for(o in n)Hd.includes(o)||(this[o]=n[o])}get basename(){return typeof this.path=="string"?Zn.basename(this.path):void 0}set basename(t){Kd(t,"basename"),Wd(t,"basename"),this.path=Zn.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?Zn.dirname(this.path):void 0}set dirname(t){Dx(this.basename,"dirname"),this.path=Zn.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?Zn.extname(this.path):void 0}set extname(t){if(Wd(t,"extname"),Dx(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=Zn.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Bh(t)&&(t=l5(t)),Kd(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?Zn.basename(this.path,this.extname):void 0}set stem(t){Kd(t,"stem"),Wd(t,"stem"),this.path=Zn.join(this.dirname||"",t+(this.extname||""))}fail(t,n,r){const o=this.message(t,n,r);throw o.fatal=!0,o}info(t,n,r){const o=this.message(t,n,r);return o.fatal=void 0,o}message(t,n,r){const o=new Kt(t,n,r);return this.path&&(o.name=this.path+":"+o.name,o.file=this.path),o.fatal=!1,this.messages.push(o),o}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function Wd(e,t){if(e&&e.includes(Zn.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+Zn.sep+"`")}function Kd(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function Dx(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function u5(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const d5=(function(e){const r=this.constructor.prototype,o=r[e],a=function(){return o.apply(a,arguments)};return Object.setPrototypeOf(a,r),a}),h5={}.hasOwnProperty;class Zf extends d5{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=QI()}copy(){const t=new Zf;let n=-1;for(;++n<this.attachers.length;){const r=this.attachers[n];t.use(...r)}return t.data(qd(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(Yd("data",this.frozen),this.namespace[t]=n,this):h5.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Yd("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[n,...r]=this.attachers[this.freezeIndex];if(r[0]===!1)continue;r[0]===!0&&(r[0]=void 0);const o=n.call(t,...r);typeof o=="function"&&this.transformers.use(o)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const n=Nl(t),r=this.parser||this.Parser;return Gd("parse",r),r(String(n),n)}process(t,n){const r=this;return this.freeze(),Gd("process",this.parser||this.Parser),Jd("process",this.compiler||this.Compiler),n?o(void 0,n):new Promise(o);function o(a,l){const d=Nl(t),h=r.parse(d);r.run(h,d,function(m,y,x){if(m||!y||!x)return p(m);const w=y,b=r.stringify(w,x);m5(b)?x.value=b:x.result=b,p(m,x)});function p(m,y){m||!y?l(m):a?a(y):n(void 0,y)}}}processSync(t){let n=!1,r;return this.freeze(),Gd("processSync",this.parser||this.Parser),Jd("processSync",this.compiler||this.Compiler),this.process(t,o),Mx("processSync","process",n),r;function o(a,l){n=!0,Ox(a),r=l}}run(t,n,r){Lx(t),this.freeze();const o=this.transformers;return!r&&typeof n=="function"&&(r=n,n=void 0),r?a(void 0,r):new Promise(a);function a(l,d){const h=Nl(n);o.run(t,h,p);function p(m,y,x){const w=y||t;m?d(m):l?l(w):r(void 0,w,x)}}}runSync(t,n){let r=!1,o;return this.run(t,n,a),Mx("runSync","run",r),o;function a(l,d){Ox(l),o=d,r=!0}}stringify(t,n){this.freeze();const r=Nl(n),o=this.compiler||this.Compiler;return Jd("stringify",o),Lx(t),o(t,r)}use(t,...n){const r=this.attachers,o=this.namespace;if(Yd("use",this.frozen),t!=null)if(typeof t=="function")h(t,n);else if(typeof t=="object")Array.isArray(t)?d(t):l(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function a(p){if(typeof p=="function")h(p,[]);else if(typeof p=="object")if(Array.isArray(p)){const[m,...y]=p;h(m,y)}else l(p);else throw new TypeError("Expected usable value, not `"+p+"`")}function l(p){if(!("plugins"in p)&&!("settings"in p))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");d(p.plugins),p.settings&&(o.settings=qd(!0,o.settings,p.settings))}function d(p){let m=-1;if(p!=null)if(Array.isArray(p))for(;++m<p.length;){const y=p[m];a(y)}else throw new TypeError("Expected a list of plugins, not `"+p+"`")}function h(p,m){let y=-1,x=-1;for(;++y<r.length;)if(r[y][0]===p){x=y;break}if(x===-1)r.push([p,...m]);else if(m.length>0){let[w,...b]=m;const S=r[x][1];Fh(S)&&Fh(w)&&(w=qd(!0,S,w)),r[x]=[p,w,...b]}}}}const f5=new Zf().freeze();function Gd(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Jd(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Yd(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Lx(e){if(!Fh(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Mx(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function Nl(e){return p5(e)?e:new Zb(e)}function p5(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function m5(e){return typeof e=="string"||g5(e)}function g5(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const y5="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",zx=[],Ux={allowDangerousHtml:!0},x5=/^(https?|ircs?|mailto|xmpp)$/i,v5=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function ep(e){const t=w5(e),n=b5(e);return k5(t.runSync(t.parse(n),n),e)}function w5(e){const t=e.rehypePlugins||zx,n=e.remarkPlugins||zx,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Ux}:Ux;return f5().use(eI).use(n).use(JI,r).use(t)}function b5(e){const t=e.children||"",n=new Zb;return typeof t=="string"&&(n.value=t),n}function k5(e,t){const n=t.allowedElements,r=t.allowElement,o=t.components,a=t.disallowedElements,l=t.skipHtml,d=t.unwrapDisallowed,h=t.urlTransform||S5;for(const m of v5)Object.hasOwn(t,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+y5+m.id,void 0);return Qb(e,p),OR(e,{Fragment:u.Fragment,components:o,ignoreInvalidStyle:!0,jsx:u.jsx,jsxs:u.jsxs,passKeys:!0,passNode:!0});function p(m,y,x){if(m.type==="raw"&&x&&typeof y=="number")return l?x.children.splice(y,1):x.children[y]={type:"text",value:m.value},y;if(m.type==="element"){let w;for(w in Fd)if(Object.hasOwn(Fd,w)&&Object.hasOwn(m.properties,w)){const b=m.properties[w],S=Fd[w];(S===null||S.includes(m.tagName))&&(m.properties[w]=h(String(b||""),w,m))}}if(m.type==="element"){let w=n?!n.includes(m.tagName):a?a.includes(m.tagName):!1;if(!w&&r&&typeof y=="number"&&(w=!r(m,y,x)),w&&x&&typeof y=="number")return d&&m.children?x.children.splice(y,1,...m.children):x.children.splice(y,1),y}}}function S5(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),o=e.indexOf("/");return t===-1||o!==-1&&t>o||n!==-1&&t>n||r!==-1&&t>r||x5.test(e.slice(0,t))?e:""}function _5({message:e}){const t=e.role==="user";return u.jsx("div",{className:`flex w-full ${t?"justify-end":"justify-start"}`,children:u.jsxs("div",{className:`flex gap-3 max-w-[85%] ${t?"flex-row-reverse":"flex-row"}`,children:[u.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${t?"bg-primary text-white":"bg-gradient-to-br from-indigo-500 to-purple-600 text-white shadow-lg glow-primary"}`,children:t?u.jsx(tc,{size:16}):u.jsx(cS,{size:16})}),u.jsxs("div",{className:`flex flex-col ${t?"items-end":"items-start"}`,children:[u.jsx("div",{className:`px-5 py-3.5 rounded-2xl text-sm leading-relaxed shadow-sm ${t?"bg-primary/10 text-fg border border-primary/20 rounded-tr-none":"bg-surface/80 backdrop-blur-md text-fg border border-border/40 rounded-tl-none"}`,children:t?u.jsx("p",{className:"whitespace-pre-wrap",children:e.content}):u.jsx("div",{className:"markdown-body",children:u.jsx(ep,{components:{p:({node:n,...r})=>u.jsx("p",{className:"mb-2 last:mb-0",...r}),a:({node:n,...r})=>u.jsx("a",{className:"text-primary hover:underline",...r}),ul:({node:n,...r})=>u.jsx("ul",{className:"list-disc ml-4 mb-2",...r}),ol:({node:n,...r})=>u.jsx("ol",{className:"list-decimal ml-4 mb-2",...r}),code:({node:n,...r})=>u.jsx("code",{className:"bg-black/20 rounded px-1 py-0.5 font-mono text-xs",...r})},children:e.content})})}),u.jsx("span",{className:"text-[10px] text-fg/30 mt-1 px-1",children:new Date(e.created_at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]})]})})}function j5({sessionId:e,onContextUpdate:t,onNewSession:n,onSessionCreated:r}){const[o,a]=A.useState([]),[l,d]=A.useState(""),[h,p]=A.useState(!1),[m,y]=A.useState(!1),x=A.useRef(null),w=A.useRef(null);A.useEffect(()=>{e?b(e):(a([]),t([]))},[e,t]),A.useEffect(()=>{x.current&&x.current.scrollIntoView({behavior:"smooth"})},[o,m]);const b=async _=>{try{const{data:{session:E}}=await se.auth.getSession();if(!E)return;const N=await Je.get(`/api/chat/sessions/${_}/messages`,{headers:{"x-user-id":E.user.id}});if(N.data.success){a(N.data.messages);const R=N.data.messages[N.data.messages.length-1];R&&R.role==="assistant"&&R.context_sources&&t(R.context_sources)}}catch(E){console.error("Failed to fetch messages",E)}},S=async _=>{if(_?.preventDefault(),!l.trim()||h)return;const E=l.trim();d(""),w.current&&(w.current.style.height="auto");const{data:{session:N}}=await se.auth.getSession();if(!N)return;const R=N.user.id;p(!0),y(!0);try{let M=e;if(!M){const $=await Je.post("/api/chat/sessions",{},{headers:{"x-user-id":R}});if($.data.success)M=$.data.session.id,r(M);else throw new Error("Failed to create session")}const O={id:"temp-"+Date.now(),role:"user",content:E,created_at:new Date().toISOString()};a($=>[...$,O]);const V=await Je.post("/api/chat/message",{sessionId:M,content:E},{headers:{"x-user-id":R}});if(V.data.success){const $=V.data.message;a(W=>[...W,$]),$.context_sources&&t($.context_sources)}}catch(M){console.error("Message failed",M),a(O=>[...O,{id:"err-"+Date.now(),role:"assistant",content:"Sorry, I encountered an error processing your request.",created_at:new Date().toISOString()}])}finally{p(!1),y(!1)}},k=_=>{_.key==="Enter"&&!_.shiftKey&&(_.preventDefault(),S())};return u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-6",children:[o.length===0?u.jsxs("div",{className:"h-full flex flex-col items-center justify-center p-8 text-center opacity-60",children:[u.jsx("div",{className:"w-16 h-16 bg-primary/10 rounded-2xl flex items-center justify-center mb-4 text-primary animate-pulse",children:u.jsx(LS,{size:32})}),u.jsx("h3",{className:"text-xl font-bold mb-2",children:"Ask Alchemist"}),u.jsx("p",{className:"text-sm max-w-md mx-auto mb-8",children:"I can help you recall information, summarize topics, and find insights from your browsing history."}),u.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 max-w-lg w-full",children:["What have I read about React recently?","Summarize the latest AI news I visited.","Do I have any notes on Finance?","Find articles about 'Performance'"].map((_,E)=>u.jsx("button",{onClick:()=>d(_),className:"text-left p-3 text-xs bg-surface/50 hover:bg-surface border border-border/30 rounded-xl transition-all hover:scale-[1.02]",children:_},E))})]}):u.jsxs(u.Fragment,{children:[o.map((_,E)=>u.jsx(_5,{message:_},_.id||E)),m&&u.jsx(ze.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"flex justify-start w-full",children:u.jsxs("div",{className:"bg-surface/50 border border-border/30 rounded-2xl px-4 py-3 flex items-center gap-3",children:[u.jsxs("div",{className:"flex gap-1",children:[u.jsx("span",{className:"w-1.5 h-1.5 bg-primary/60 rounded-full animate-bounce",style:{animationDelay:"0s"}}),u.jsx("span",{className:"w-1.5 h-1.5 bg-primary/60 rounded-full animate-bounce",style:{animationDelay:"0.1s"}}),u.jsx("span",{className:"w-1.5 h-1.5 bg-primary/60 rounded-full animate-bounce",style:{animationDelay:"0.2s"}})]}),u.jsx("span",{className:"text-xs text-fg/50 font-mono",children:"Exploring memory..."})]})})]}),u.jsx("div",{ref:x})]}),u.jsx("div",{className:"p-4 bg-surface/30 border-t border-border/10 backdrop-blur-md",children:u.jsx("form",{onSubmit:S,className:"relative max-w-4xl mx-auto",children:u.jsxs("div",{className:"relative flex items-end gap-2 bg-surface/80 border border-border/40 rounded-2xl px-2 py-2 shadow-sm focus-within:ring-2 focus-within:ring-primary/50 focus-within:border-primary/50 transition-all",children:[u.jsx("textarea",{ref:w,value:l,onChange:_=>{d(_.target.value),_.target.style.height="auto",_.target.style.height=_.target.scrollHeight+"px"},onKeyDown:k,placeholder:"Ask about your history...",rows:1,className:"w-full bg-transparent border-none focus:ring-0 focus:outline-none py-2 pl-2 text-fg resize-none min-h-[24px] max-h-[200px] placeholder:text-fg/40",disabled:h}),u.jsx("button",{type:"submit",disabled:!l.trim()||h,className:"p-2 mb-0.5 bg-primary text-white rounded-xl shadow-lg hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-all shrink-0",children:h?u.jsx(ec,{size:18,className:"animate-spin"}):u.jsx(IS,{size:18})})]})})})]})}function E5({sources:e,onClose:t}){return!e||e.length===0?null:u.jsxs(ze.div,{initial:{opacity:0,x:20,width:0},animate:{opacity:1,x:0,width:300},exit:{opacity:0,x:20,width:0},className:"glass rounded-2xl border border-border/40 overflow-hidden flex flex-col",children:[u.jsxs("div",{className:"p-4 border-b border-border/10 flex items-center justify-between bg-surface/30",children:[u.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-fg/80",children:[u.jsx($x,{size:16,className:"text-secondary"}),u.jsx("span",{children:"Relevant Context"})]}),u.jsx("button",{onClick:t,className:"p-1 hover:bg-surface rounded-md text-fg/40 hover:text-fg transition-colors",children:u.jsx(bn,{size:14})})]}),u.jsx("div",{className:"flex-1 overflow-y-auto p-3 space-y-3",children:e.map((n,r)=>u.jsxs("div",{className:"p-3 bg-surface/40 hover:bg-surface/60 border border-border/20 rounded-xl transition-all group",children:[u.jsxs("div",{className:"flex justify-between items-start mb-2",children:[u.jsxs("div",{className:"flex items-center gap-1.5",children:[u.jsx("span",{className:"flex items-center justify-center w-4 h-4 bg-primary/10 text-primary text-[10px] font-bold rounded",children:r+1}),u.jsxs("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded border ${n.score>=80?"bg-yellow-500/10 text-yellow-500 border-yellow-500/20":"bg-blue-500/10 text-blue-400 border-blue-500/20"}`,children:[n.score,"% Match"]})]}),u.jsx("a",{href:n.url,target:"_blank",rel:"noopener noreferrer",className:"opacity-0 group-hover:opacity-100 text-fg/40 hover:text-primary transition-opacity",children:u.jsx(Ei,{size:12})})]}),u.jsx("a",{href:n.url,target:"_blank",rel:"noopener noreferrer",className:"text-xs font-bold text-fg/90 block mb-1 hover:text-primary transition-colors line-clamp-2",children:n.title}),u.jsx("p",{className:"text-[10px] text-fg/50 line-clamp-3 leading-relaxed",children:n.summary})]},r))}),u.jsxs("div",{className:"p-3 border-t border-border/10 bg-surface/30 text-[10px] text-center text-fg/30",children:["Alchemist used these ",e.length," signals to answer"]})]})}function N5(){const[e,t]=A.useState(null),[n,r]=A.useState([]),[o,a]=A.useState(!0);return u.jsxs("div",{className:"flex h-full gap-4 overflow-hidden",children:[u.jsx(sR,{activeSessionId:e,onSelectSession:t}),u.jsx("div",{className:"flex-1 flex flex-col min-w-0 glass rounded-2xl overflow-hidden border border-border/40 relative",children:u.jsx(j5,{sessionId:e,onContextUpdate:l=>{r(l),l.length>0&&a(!0)},onNewSession:()=>t(null),onSessionCreated:l=>t(l)})}),o&&u.jsx(E5,{sources:n,onClose:()=>a(!1)})]})}function C5({isOpen:e,onClose:t}){const[n,r]=A.useState(""),[o,a]=A.useState(!0);A.useEffect(()=>{e&&l()},[e]);const l=async()=>{a(!0);try{const h=await(await fetch("/CHANGELOG.md")).text();r(h)}catch(d){console.error("Failed to load changelog:",d),r(`# Error
|
|
124
124
|
|
|
125
|
-
Failed to load changelog.`)}finally{a(!1)}};return u.jsx(Rt,{children:e&&u.jsxs(u.Fragment,{children:[u.jsx(ze.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:t,className:"fixed inset-0 bg-black/60 backdrop-blur-sm z-50"}),u.jsx(ze.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:20},transition:{type:"spring",damping:25,stiffness:300},className:"fixed inset-0 z-50 flex items-center justify-center p-4 pointer-events-none",children:u.jsxs("div",{className:"glass w-full max-w-3xl max-h-[80vh] overflow-hidden pointer-events-auto shadow-2xl",children:[u.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx($x,{size:24,className:"text-primary"}),u.jsx("h2",{className:"text-xl font-bold",children:"Release Notes"})]}),u.jsx("button",{onClick:t,className:"p-2 hover:bg-surface rounded-lg transition-colors",children:u.jsx(bn,{size:20,className:"text-fg/60"})})]}),u.jsx("div",{className:"p-6 overflow-y-auto custom-scrollbar max-h-[calc(80vh-88px)]",children:o?u.jsx("div",{className:"flex items-center justify-center py-12",children:u.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-primary border-t-transparent"})}):u.jsx(ep,{components:{h1:({children:d})=>u.jsx("h1",{className:"text-2xl font-bold text-fg mb-6 mt-0",children:d}),h2:({children:d})=>u.jsx("h2",{className:"text-xl font-bold text-fg mt-8 mb-3 pb-2 border-b border-border first:mt-0",children:d}),h3:({children:d})=>u.jsx("h3",{className:"text-lg font-bold text-primary mt-6 mb-2",children:d}),p:({children:d})=>u.jsx("p",{className:"text-sm text-fg/70 mb-3 leading-relaxed",children:d}),ul:({children:d})=>u.jsx("ul",{className:"list-none space-y-1 mb-4 ml-0",children:d}),li:({children:d})=>u.jsx("li",{className:"text-sm text-fg/80 ml-4 mb-1 before:content-['•'] before:mr-2 before:text-primary",children:d}),a:({href:d,children:h})=>u.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:text-primary/80 underline transition-colors",children:h}),code:({children:d})=>u.jsx("code",{className:"bg-surface/50 text-accent px-1.5 py-0.5 rounded text-xs font-mono border border-border",children:d}),strong:({children:d})=>u.jsx("strong",{className:"font-bold text-fg",children:d})},children:n})})]})})]})})}function T5({asset:e,onClose:t}){const n=()=>{e.content&&navigator.clipboard.writeText(e.content)},r=()=>{if(!e.content)return;const o=new Blob([e.content],{type:"text/markdown"}),a=URL.createObjectURL(o),l=document.createElement("a");l.href=a,l.download=`${e.title.replace(/[^a-z0-9]/gi,"_").toLowerCase()}.md`,document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(a)};return u.jsx(Rt,{children:e&&u.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:u.jsxs(ze.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden border border-gray-200 dark:border-gray-700",children:[u.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("div",{className:"p-2 rounded-lg bg-purple-100 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400",children:e.type==="audio"?u.jsx(Zd,{className:"w-5 h-5"}):u.jsx(wi,{className:"w-5 h-5"})}),u.jsxs("div",{children:[u.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e.title}),u.jsxs("p",{className:"text-xs text-gray-500",children:["Generated ",new Date(e.created_at).toLocaleString()," • ",e.metadata?.source_signal_count||0," sources"]})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{onClick:n,className:"p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",title:"Copy Content",children:u.jsx(Vh,{className:"w-4 h-4"})}),u.jsx("button",{onClick:r,className:"p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",title:"Download File",children:u.jsx(Xd,{className:"w-4 h-4"})}),u.jsx("div",{className:"w-px h-6 bg-gray-200 dark:bg-gray-700 mx-1"}),u.jsx("button",{onClick:t,className:"p-2 text-gray-500 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:u.jsx(bn,{className:"w-5 h-5"})})]})]}),u.jsx("div",{className:"flex-1 overflow-y-auto p-6 bg-white dark:bg-gray-950",children:e.status&&e.status!=="completed"?u.jsxs("div",{className:"flex flex-col items-center justify-center h-64 gap-4",children:[u.jsx(Nt,{className:"w-12 h-12 animate-spin text-purple-500"}),u.jsxs("div",{className:"text-center",children:[u.jsx("h4",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:e.status==="processing"?"Generating Asset...":"Queued for Desktop..."}),u.jsx("p",{className:"text-sm text-gray-500 max-w-xs mt-1",children:"The RealTimeX Desktop app is processing this request. This modal will update automatically once finished."})]})]}):e.type==="markdown"?u.jsx("div",{className:"prose dark:prose-invert max-w-none",children:u.jsx(ep,{children:e.content||""})}):e.type==="audio"?u.jsxs("div",{className:"flex flex-col items-center justify-center h-64 gap-4",children:[u.jsx("div",{className:"w-16 h-16 rounded-full bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center animate-pulse",children:u.jsx(Zd,{className:"w-8 h-8 text-purple-600 dark:text-purple-400"})}),u.jsx("p",{className:"text-gray-500",children:"Audio playback not yet implemented (Simulated)"}),u.jsxs("audio",{controls:!0,className:"w-full max-w-md mt-4",children:[u.jsx("source",{src:e.content||"",type:"audio/mpeg"}),"Your browser does not support the audio element."]})]}):u.jsx("div",{className:"text-gray-500 text-center py-10",children:"Unsupported asset type"})})]})})})}function Fx({engine:e,onClose:t,onSave:n,onDelete:r}){const{showToast:o}=yc(),[a,l]=A.useState({title:"",type:"newsletter",status:"active",config:{schedule:"",min_score:70,categories:[],custom_prompt:"",max_signals:10,execution_mode:"local"}}),[d,h]=A.useState(!1);A.useEffect(()=>{e&&l({title:e.title,type:e.type,status:e.status,config:{schedule:e.config.schedule||"",min_score:e.config.filters?.min_score||70,categories:Array.isArray(e.config.category)?e.config.category:e.config.category?[e.config.category]:[],custom_prompt:e.config.custom_prompt||"",max_signals:e.config.max_signals||10,execution_mode:e.config.execution_mode||"local"}})},[e]);const p=async()=>{try{const x={title:a.title,type:a.type,status:a.status,config:{schedule:a.config.schedule,filters:{min_score:a.config.min_score,category:a.config.category},custom_prompt:a.config.custom_prompt,max_signals:a.config.max_signals,execution_mode:a.config.execution_mode}};if(e){const{data:w,error:b}=await se.from("engines").update(x).eq("id",e.id).select().single();if(b)throw b;n(w),o("Engine updated successfully","success")}else{const{data:{user:w}}=await se.auth.getUser();if(!w)throw new Error("Not authenticated");const{data:b,error:S}=await se.from("engines").insert({...x,user_id:w.id}).select().single();if(S)throw S;n(b),o("Engine created successfully","success")}t()}catch(x){console.error("Save error:",x),o(x.message||"Failed to save engine","error")}},m=async()=>{if(!(!e||!r))try{const{error:x}=await se.from("engines").delete().eq("id",e.id);if(x)throw x;r(e.id),o("Engine deleted","success"),t()}catch(x){o(x.message||"Failed to delete engine","error")}},y=()=>{h(!1),t()};return!e&&!t?null:u.jsx(Rt,{children:u.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:u.jsxs(ze.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-2xl max-h-[85vh] flex flex-col overflow-hidden border border-gray-200 dark:border-gray-700",children:[u.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800",children:[u.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:e?"Edit Engine":"Create Engine"}),u.jsx("button",{onClick:y,className:"p-2 text-gray-500 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:u.jsx(bn,{className:"w-5 h-5"})})]}),u.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Engine Name"}),u.jsx("input",{type:"text",value:a.title,onChange:x=>l({...a,title:x.target.value}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-purple-500 focus:border-transparent",placeholder:"e.g., Daily Tech Brief"})]}),u.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Type"}),u.jsxs("select",{value:a.type,onChange:x=>l({...a,type:x.target.value}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",children:[u.jsx("option",{value:"newsletter",children:"Newsletter"}),u.jsx("option",{value:"thread",children:"Thread"}),u.jsx("option",{value:"audio",children:"Audio Brief"}),u.jsx("option",{value:"report",children:"Report"})]})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Status"}),u.jsxs("select",{value:a.status,onChange:x=>l({...a,status:x.target.value}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",children:[u.jsx("option",{value:"active",children:"Active"}),u.jsx("option",{value:"paused",children:"Paused"}),u.jsx("option",{value:"draft",children:"Draft"})]})]})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Execution Environment"}),u.jsxs("select",{value:a.config.execution_mode,onChange:x=>l({...a,config:{...a.config,execution_mode:x.target.value}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",children:[u.jsx("option",{value:"local",children:"Local (Alchemy LLM)"}),u.jsx("option",{value:"desktop",children:"RealTimeX Desktop (Agent Swarm)"})]}),u.jsx("p",{className:"text-[10px] text-gray-500 mt-1",children:a.config.execution_mode==="desktop"?"Delegates heavy tasks like Audio/Video to the desktop app.":"Runs simple Markdown tasks directly in Alchemy."})]})]}),u.jsxs("div",{className:"space-y-4",children:[u.jsx("h4",{className:"font-medium text-gray-900 dark:text-gray-100",children:"Signal Filters"}),u.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Min Score"}),u.jsx("input",{type:"number",min:"0",max:"100",value:a.config.min_score,onChange:x=>l({...a,config:{...a.config,min_score:parseInt(x.target.value)||0}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Max Signals"}),u.jsx("input",{type:"number",min:"1",max:"50",value:a.config.max_signals,onChange:x=>l({...a,config:{...a.config,max_signals:parseInt(x.target.value)||10}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"})]})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Category Filter (multi-select)"}),u.jsxs("select",{multiple:!0,value:a.config.categories,onChange:x=>{const w=Array.from(x.target.selectedOptions,b=>b.value);l({...a,config:{...a.config,categories:w}})},className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 min-h-[100px]",children:[u.jsx("option",{value:"AI & ML",children:"AI & ML"}),u.jsx("option",{value:"Technology",children:"Technology"}),u.jsx("option",{value:"Business",children:"Business"}),u.jsx("option",{value:"Finance",children:"Finance"}),u.jsx("option",{value:"Science",children:"Science"}),u.jsx("option",{value:"Politics",children:"Politics"})]}),u.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Hold Cmd/Ctrl to select multiple categories"})]})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Schedule (optional)"}),u.jsx("input",{type:"text",value:a.config.schedule,onChange:x=>l({...a,config:{...a.config,schedule:x.target.value}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",placeholder:"e.g., Daily @ 9am, Manual"}),u.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Note: Scheduling is not yet automated"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Custom Prompt Override (optional)"}),u.jsx("textarea",{value:a.config.custom_prompt,onChange:x=>l({...a,config:{...a.config,custom_prompt:x.target.value}}),rows:4,className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 resize-none",placeholder:"Override the default prompt for this engine type..."})]})]}),u.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50",children:[e&&r?d?u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("span",{className:"text-sm text-red-600 font-medium",children:"Really delete?"}),u.jsx("button",{onClick:m,className:"px-3 py-1.5 bg-red-600 text-white text-xs rounded-lg hover:bg-red-700 transition-colors",children:"Confirm"}),u.jsx("button",{onClick:()=>h(!1),className:"px-3 py-1.5 text-gray-500 hover:text-gray-700 text-xs rounded-lg",children:"Cancel"})]}):u.jsxs("button",{onClick:()=>h(!0),className:"flex items-center gap-2 px-4 py-2 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:[u.jsx(Wh,{className:"w-4 h-4"}),"Delete"]}):u.jsx("div",{}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx("button",{onClick:y,className:"px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:"Cancel"}),u.jsxs("button",{onClick:p,className:"flex items-center gap-2 px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors",children:[u.jsx(fr,{className:"w-4 h-4"}),"Save"]})]})]})]})})})}const A5=({engine:e,onRun:t,onEdit:n,onToggle:r,onViewBrief:o,isLoading:a})=>{const l=!!e.config.tag,d={newsletter:l?u.jsx(qh,{className:"w-5 h-5 text-blue-500"}):u.jsx(wi,{className:"w-5 h-5 text-emerald-500"}),thread:u.jsx(Xt,{className:"w-5 h-5 text-blue-500"}),audio:u.jsx(Zd,{className:"w-5 h-5 text-purple-500"}),report:u.jsx(Ml,{className:"w-5 h-5 text-orange-500"})};return u.jsxs(ze.div,{layout:!0,initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:`p-5 rounded-2xl border ${e.status==="active"?"bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700 shadow-sm":"bg-gray-50 dark:bg-gray-900 border-dashed border-gray-300 dark:border-gray-700 opacity-75"} transition-all hover:shadow-md group`,children:[u.jsxs("div",{className:"flex justify-between items-start mb-4",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("div",{className:"p-2 rounded-xl bg-gray-100 dark:bg-gray-800",children:d[e.type]||u.jsx(wi,{className:"w-5 h-5"})}),u.jsxs("div",{children:[u.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e.title}),u.jsxs("p",{className:"text-xs text-gray-500 capitalize",children:[l?"Topic":e.type," Pipeline"]})]})]}),u.jsxs("div",{className:"flex gap-1",children:[u.jsx("button",{onClick:()=>r(e.id,e.status),className:"p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:e.status==="active"?u.jsx(PS,{className:"w-4 h-4"}):u.jsx(Xg,{className:"w-4 h-4"})}),u.jsx("button",{onClick:()=>o(e.id),title:"View Production Brief JSON",className:"p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:u.jsx(Hx,{className:"w-4 h-4"})}),u.jsx("button",{onClick:()=>n(e.id),className:"p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:u.jsx(Ml,{className:"w-4 h-4"})})]})]}),u.jsxs("div",{className:"space-y-2 mb-4",children:[u.jsxs("div",{className:"text-xs text-gray-500 flex justify-between",children:[u.jsx("span",{children:"Last Run"}),u.jsx("span",{children:e.last_run_at?new Date(e.last_run_at).toLocaleDateString():"Never"})]}),u.jsxs("div",{className:"text-xs text-gray-500 flex justify-between",children:[u.jsx("span",{children:"Schedule"}),u.jsx("span",{children:e.config.schedule||"Manual"})]})]}),u.jsxs("button",{onClick:()=>t(e.id),disabled:a||e.status!=="active",className:"w-full flex items-center justify-center gap-2 py-2 rounded-xl bg-gray-900 dark:bg-white text-white dark:text-gray-900 font-medium hover:opacity-90 disabled:opacity-50 transition-all text-sm",children:[a?u.jsx(Nt,{className:"w-4 h-4 animate-spin"}):u.jsx(Xg,{className:"w-4 h-4"}),a?"Running...":"Run Engine"]})]})};function P5(){const[e,t]=A.useState([]),[n,r]=A.useState(!0),[o,a]=A.useState(new Set),[l,d]=A.useState(null),[h,p]=A.useState(null),[m,y]=A.useState(!1),[x,w]=A.useState(null),[b,S]=A.useState(!1),[k,_]=A.useState(!1),{showToast:E}=yc();A.useEffect(()=>{(async()=>R())();const J=se.channel("asset-updates").on("postgres_changes",{event:"UPDATE",schema:"public",table:"assets"},q=>{const ie=q.new;d(oe=>oe?.id===ie.id?ie:oe),ie.status==="completed"&&q.old.status!=="completed"&&E(`Asset "${ie.title}" is ready!`,"success")}).subscribe();return()=>{se.removeChannel(J)}},[]);const N=async()=>{if(!k)try{_(!0),E("Scanning for new categories and topics...","info");const{data:{session:ee}}=await se.auth.getSession(),J=ks(),q={"Content-Type":"application/json","x-user-id":ee?.user?.id||""};if(ee?.access_token&&(q.Authorization=`Bearer ${ee.access_token}`),J&&(q["x-supabase-url"]=J.url,q["x-supabase-key"]=J.anonKey),!(await fetch("/api/engines/ensure-defaults",{method:"POST",headers:q})).ok)throw new Error("Failed to generate engines");E("Engine discovery complete!","success"),await R()}catch(ee){console.error("Failed to generate engines:",ee),E("Discovery failed. Check settings.","error")}finally{_(!1)}},R=async()=>{try{r(!0);const{data:{user:ee}}=await se.auth.getUser();if(!ee)return;const{data:J,error:q}=await se.from("engines").select("*").eq("user_id",ee.id).order("created_at",{ascending:!1});if(q)throw q;t(J)}catch(ee){console.error("Error fetching engines:",ee),E("Failed to load engines","error")}finally{r(!1)}},M=async ee=>{if(!o.has(ee))try{a(C=>new Set(C).add(ee)),E("Starting engine run...","info");const{data:{session:J}}=await se.auth.getSession(),q=J?.access_token,ie=ks(),oe={"Content-Type":"application/json","x-user-id":J?.user?.id||""};q&&(oe.Authorization=`Bearer ${q}`),ie&&(oe["x-supabase-url"]=ie.url,oe["x-supabase-key"]=ie.anonKey);const G=await fetch(`/api/engines/${ee}/run`,{method:"POST",headers:oe});if(!G.ok){const C=await G.json();throw new Error(C.error||"Run failed")}const de=await G.json();de.status==="completed"?E(`Engine run complete! Created: ${de.title}`,"success"):E(`Engine run started on Desktop. Tracking as: ${de.id}`,"info"),d(de),t(C=>C.map(D=>D.id===ee?{...D,last_run_at:new Date().toISOString()}:D))}catch(J){console.error("Engine run error:",J),E(J.message||"Failed to run engine","error")}finally{a(J=>{const q=new Set(J);return q.delete(ee),q})}},O=async ee=>{try{y(!0);const{data:{session:J}}=await se.auth.getSession(),q=ks(),ie={"Content-Type":"application/json","x-user-id":J?.user?.id||""};J?.access_token&&(ie.Authorization=`Bearer ${J.access_token}`),q&&(ie["x-supabase-url"]=q.url,ie["x-supabase-key"]=q.anonKey);const oe=await fetch(`/api/engines/${ee}/brief`,{headers:ie});if(!oe.ok)throw new Error("Failed to fetch brief");const G=await oe.json();p(G)}catch{E("Failed to generate production brief","error")}finally{y(!1)}},V=async(ee,J)=>{const q=J==="active"?"paused":"active";t(ie=>ie.map(oe=>oe.id===ee?{...oe,status:q}:oe));try{const{error:ie}=await se.from("engines").update({status:q}).eq("id",ee);if(ie)throw ie;E(`Engine ${q==="active"?"resumed":"paused"}`,"success")}catch{t(oe=>oe.map(G=>G.id===ee?{...G,status:J}:G)),E("Failed to update status","error")}},$=()=>{S(!0)},W=ee=>{const J=e.find(q=>q.id===ee);J&&w(J)},he=ee=>{t(J=>J.find(ie=>ie.id===ee.id)?J.map(ie=>ie.id===ee.id?ee:ie):[ee,...J])},ne=ee=>{t(J=>J.filter(q=>q.id!==ee))},le=()=>{w(null),S(!1)};return u.jsxs("div",{className:"h-full flex flex-col bg-gray-50/50 dark:bg-[#0A0A0A]",children:[u.jsx("div",{className:"flex-none p-6 border-b border-gray-200 dark:border-gray-800 bg-white/50 dark:bg-gray-900/50 backdrop-blur-sm z-10 sticky top-0",children:u.jsxs("div",{className:"flex justify-between items-center max-w-7xl mx-auto w-full",children:[u.jsxs("div",{children:[u.jsx("h2",{className:"text-2xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-purple-500 to-blue-500",children:"Transmute Engine"}),u.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:"Active Generation Pipelines & Assets"})]}),u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsxs("button",{onClick:N,disabled:k,className:"flex items-center gap-2 px-4 py-2 bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 rounded-xl font-medium hover:bg-purple-100 dark:hover:bg-purple-900/40 transition-all border border-purple-200 dark:border-purple-800 disabled:opacity-50",children:[k?u.jsx(Nt,{className:"w-4 h-4 animate-spin"}):u.jsx(Xt,{className:"w-4 h-4"}),"Generate Engines"]}),u.jsxs("button",{onClick:$,className:"flex items-center gap-2 px-4 py-2 bg-gray-900 dark:bg-white text-white dark:text-gray-900 rounded-xl font-medium hover:opacity-90 transition-opacity shadow-lg shadow-purple-500/10",children:[u.jsx(Hh,{className:"w-4 h-4"}),"New Engine"]})]})]})}),u.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:u.jsx("div",{className:"max-w-7xl mx-auto w-full",children:n?u.jsx("div",{className:"flex items-center justify-center h-64",children:u.jsx(Nt,{className:"w-8 h-8 animate-spin text-purple-500"})}):e.length===0?u.jsxs("div",{className:"flex flex-col items-center justify-center h-96 text-center",children:[u.jsx("div",{className:"w-16 h-16 rounded-2xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-4",children:u.jsx(Xt,{className:"w-8 h-8 text-gray-400"})}),u.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"No Engines Configured"}),u.jsx("p",{className:"text-gray-500 max-w-sm mt-2 mb-6",children:"Create your first pipeline to automatically turn signals into newsletters, threads, or audio briefs."}),u.jsx("button",{onClick:$,className:"px-6 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",children:"Create Engine"})]}):u.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:u.jsx(Rt,{children:e.map(ee=>u.jsx(A5,{engine:ee,onRun:M,onEdit:W,onToggle:V,onViewBrief:O,isLoading:o.has(ee.id)},ee.id))})})})}),u.jsx(Rt,{children:h&&u.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/60 backdrop-blur-md",children:u.jsxs(ze.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden border border-gray-200 dark:border-gray-700",children:[u.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("div",{className:"p-2 rounded-lg bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400",children:u.jsx(Hx,{className:"w-5 h-5"})}),u.jsxs("div",{children:[u.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:"Production Brief JSON"}),u.jsx("p",{className:"text-xs text-gray-500",children:"Stateless & Self-Contained Contract"})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{onClick:()=>{navigator.clipboard.writeText(JSON.stringify(h,null,2)),E("JSON copied to clipboard","info")},className:"p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",children:u.jsx(Vh,{className:"w-4 h-4"})}),u.jsx("button",{onClick:()=>p(null),className:"p-2 text-gray-500 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:u.jsx(bn,{className:"w-5 h-5"})})]})]}),u.jsx("div",{className:"flex-1 overflow-y-auto p-4 bg-[#0D1117] font-mono text-sm",children:u.jsx("pre",{className:"text-blue-300",children:JSON.stringify(h,null,2)})}),u.jsx("div",{className:"p-4 border-t border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50 text-[10px] text-gray-500 text-center",children:"This JSON contains the full context (Signals + User Persona) required for the Desktop Studio."})]})})}),m&&u.jsx("div",{className:"fixed inset-0 z-[70] flex items-center justify-center bg-black/20 backdrop-blur-sm",children:u.jsx(Nt,{className:"w-10 h-10 animate-spin text-white"})}),u.jsx(T5,{asset:l,onClose:()=>d(null)}),x&&u.jsx(Fx,{engine:x,onClose:le,onSave:he,onDelete:ne}),b&&u.jsx(Fx,{engine:null,onClose:le,onSave:he})]})}class R5{audioContext=null;enabled=!0;constructor(){}getAudioContext(){return this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext)),this.audioContext}setEnabled(t){this.enabled=t}isEnabled(){return this.enabled}playTone(t,n,r=.3){if(this.enabled)try{const o=this.getAudioContext(),a=o.createOscillator(),l=o.createGain();a.connect(l),l.connect(o.destination),a.frequency.value=t,a.type="sine",l.gain.setValueAtTime(r,o.currentTime),l.gain.exponentialRampToValueAtTime(.01,o.currentTime+n),a.start(o.currentTime),a.stop(o.currentTime+n)}catch(o){console.warn("[Sound] Failed to play tone:",o)}}playSequence(t,n=.3){if(!this.enabled)return;let r=0;t.forEach(o=>{setTimeout(()=>{this.playTone(o.freq,o.duration,n)},r),r+=o.delay})}syncStart(){this.playSequence([{freq:261.63,duration:.15,delay:0},{freq:329.63,duration:.15,delay:100},{freq:392,duration:.2,delay:100}],.2)}signalFound(){this.playSequence([{freq:392,duration:.1,delay:0},{freq:523.25,duration:.15,delay:80}],.25)}syncComplete(){this.playSequence([{freq:261.63,duration:.12,delay:0},{freq:329.63,duration:.12,delay:80},{freq:392,duration:.12,delay:80},{freq:523.25,duration:.2,delay:80}],.2)}error(){this.playSequence([{freq:329.63,duration:.15,delay:0},{freq:261.63,duration:.2,delay:100}],.3)}click(){this.playTone(440,.05,.15)}}const So=new R5;function O5(){const[e,t]=A.useState([]),[n,r]=A.useState([]),[o,a]=A.useState("discovery"),[l,d]=A.useState(!1),[h,p]=A.useState(null),[m,y]=A.useState(!0),[x,w]=A.useState(!tx),[b,S]=A.useState(!0),[k,_]=A.useState(!1),[E,N]=A.useState(!1),[R,M]=A.useState(null),[O,V]=A.useState(!1),[$,W]=A.useState(!1),[he,ne]=A.useState(!1),[le,ee]=A.useState(!0),[J,q]=A.useState(()=>localStorage.getItem("theme")||"dark"),[ie,oe]=A.useState(null),G=A.useRef(null);A.useMemo(()=>{const ue=n.length;let xe=0,me=0,ge=null;for(const Ke of n){xe+=Ke.score,Ke.score>me&&(me=Ke.score);const Gt=new Date(Ke.date);(!ge||Gt>new Date(ge.date))&&(ge=Ke)}const Ae=ue?Math.round(xe/ue):0,Ve=ge?new Date(ge.date):null;return{total:ue,average:Ae,top:me,latestTimestamp:Ve,latestTitle:ge?.title??ge?.category??null}},[n]),A.useEffect(()=>{(async()=>{if(!tx){w(!0),y(!1);return}try{const{data:me,error:ge}=await se.from("init_state").select("is_initialized").single();ge?(console.warn("[App] Init check error (might be fresh DB):",ge),ge.code==="42P01"&&S(!1)):S(me.is_initialized>0);const{data:{session:Ae}}=await se.auth.getSession();p(Ae?.user??null)}catch(me){console.error("[App] Status check failed:",me)}finally{y(!1)}})();const{data:{subscription:xe}}=se.auth.onAuthStateChange((me,ge)=>{p(ge?.user??null)});return()=>xe.unsubscribe()},[]),A.useEffect(()=>{document.documentElement.setAttribute("data-theme",J),localStorage.setItem("theme",J)},[J]);const[de,C]=A.useState({});A.useEffect(()=>{(async()=>{if(!h)return;const{data:xe}=await se.from("alchemy_settings").select("sync_start_date, last_sync_checkpoint").eq("user_id",h.id).maybeSingle();xe&&C(xe)})()},[h,O]),A.useEffect(()=>{if(!h)return;(async()=>{const{data:me}=await se.from("alchemy_settings").select("sound_enabled").eq("user_id",h.id).maybeSingle();if(me){const ge=me.sound_enabled??!0;ee(ge),So.setEnabled(ge)}})();const xe=se.channel("processing_events").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events",filter:`user_id=eq.${h.id}`},me=>{const ge=me.new;ge.agent_state==="Mining"&&!$&&(W(!0),ne(!0),le&&So.syncStart()),ge.agent_state==="Signal"&&le&&So.signalFound(),ge.agent_state==="Completed"&&(W(!1),le&&(ge.metadata?.errors>0?So.error():So.syncComplete()),setTimeout(()=>{ne(!1)},5e3),D())}).subscribe();return()=>{se.removeChannel(xe)}},[h,$,le]),A.useEffect(()=>{const ue=new EventSource("/events");return ue.onmessage=xe=>{const me=JSON.parse(xe.data);me.type==="history"?t(ge=>[...me.data,...ge].slice(0,100)):t(ge=>[me,...ge].slice(0,100))},D(),()=>ue.close()},[h]),A.useEffect(()=>{G.current&&G.current.scrollIntoView({behavior:"smooth"})},[e]);const D=async()=>{try{if(h){const{data:xe,error:me}=await se.from("signals").select("*").order("created_at",{ascending:!1});if(!me&&xe){r(xe.map(ge=>({id:ge.id,title:ge.title,score:ge.score,summary:ge.summary,date:ge.created_at,category:ge.category,entities:ge.entities})));return}}const ue=await Je.get("/api/signals");r(ue.data)}catch(ue){console.error("Failed to fetch signals",ue)}},K=async()=>{d(!0);try{await Je.post("/api/mine"),D()}catch(ue){console.error("Mining failed:",ue)}finally{d(!1)}},T=(ue,xe)=>{ue==="logs"?(oe(xe),a("logs")):a(ue)};return m?u.jsx("div",{className:"flex items-center justify-center h-screen bg-bg",children:u.jsx("div",{className:"w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin"})}):x?u.jsx(hb,{onComplete:()=>w(!1)}):h?u.jsx(TP,{children:u.jsx(OP,{children:u.jsxs("div",{className:"flex h-screen w-screen overflow-hidden bg-bg text-fg",children:[u.jsxs(ze.aside,{animate:{width:k?72:240},className:"glass m-4 mr-0 flex flex-col relative",children:[u.jsxs("div",{className:`px-4 py-3 pb-4 flex items-center gap-3 ${k?"justify-center":""}`,children:[u.jsx("div",{className:"w-10 h-10 min-w-[40px] bg-gradient-to-br from-primary to-accent rounded-xl flex items-center justify-center shadow-lg glow-primary",children:u.jsx(Xt,{className:"text-white fill-current",size:24})}),!k&&u.jsx(ze.h1,{initial:{opacity:0},animate:{opacity:1},className:"text-xl font-bold tracking-tight",children:"Alchemist"})]}),u.jsxs("nav",{className:"flex-1 flex flex-col gap-1 px-3",children:[u.jsx(si,{active:o==="discovery",onClick:()=>a("discovery"),icon:u.jsx(jS,{size:20}),label:"Discovery",collapsed:k}),u.jsx(si,{active:o==="chat",onClick:()=>a("chat"),icon:u.jsx(Qd,{size:20}),label:"Chat",collapsed:k}),u.jsx(si,{active:o==="transmute",onClick:()=>a("transmute"),icon:u.jsx(Xt,{size:20}),label:"Transmute",collapsed:k}),u.jsx(si,{active:o==="engine",onClick:()=>a("engine"),icon:u.jsx(Ml,{size:20}),label:"Settings",collapsed:k}),u.jsx(si,{active:o==="logs",onClick:()=>a("logs"),icon:u.jsx(zl,{size:20}),label:"System Logs",collapsed:k}),u.jsx(si,{active:o==="account",onClick:()=>a("account"),icon:u.jsx(tc,{size:20}),label:"Account",collapsed:k})]}),u.jsx("div",{className:"px-3 pb-2",children:u.jsxs("button",{onClick:()=>q(J==="dark"?"light":"dark"),className:`w-full flex items-center ${k?"justify-center":"gap-3"} px-4 py-2.5 rounded-lg text-fg/40 hover:text-fg hover:bg-surface/50 transition-all text-xs font-medium`,title:k?J==="dark"?"Switch to Light Mode":"Switch to Dark Mode":"",children:[u.jsx("div",{className:"min-w-[20px] flex justify-center",children:J==="dark"?u.jsx(zS,{size:18}):u.jsx(AS,{size:18})}),!k&&u.jsx(ze.span,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"whitespace-nowrap",children:J==="dark"?"Light Mode":"Dark Mode"})]})}),u.jsxs("div",{className:"px-3 pb-3",children:[u.jsx("button",{onClick:()=>_(!k),className:`w-full flex items-center px-4 py-2.5 rounded-lg text-fg/40 hover:text-fg hover:bg-surface/50 transition-all text-xs font-medium ${k?"justify-center":"gap-3"}`,children:k?u.jsx(gS,{size:20}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"min-w-[20px] flex justify-center",children:u.jsx(mS,{size:20})}),u.jsx("span",{children:"Collapse"})]})}),u.jsxs("button",{onClick:()=>N(!0),className:"w-full flex items-center justify-center gap-2 px-3 py-2 mt-2 text-[10px] font-mono text-fg/30 hover:text-primary hover:bg-surface/30 rounded-lg transition-all group",title:"View Changelog",children:[!k&&u.jsxs(u.Fragment,{children:[u.jsx(eh,{size:12,className:"group-hover:text-primary transition-colors"}),u.jsxs("span",{children:["v","1.0.52"]})]}),k&&u.jsx(eh,{size:14,className:"group-hover:text-primary transition-colors"})]})]})]}),u.jsxs("main",{className:"flex-1 flex flex-col p-4 gap-4 overflow-hidden relative",children:[o==="discovery"&&u.jsxs(u.Fragment,{children:[u.jsxs("header",{className:"flex justify-between items-center px-4 py-2",children:[u.jsxs("div",{children:[u.jsx("h2",{className:"text-2xl font-bold",children:"Discovery"}),u.jsx("p",{className:"text-sm text-fg/50",children:"Passive intelligence mining from your browser history."})]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsxs("button",{onClick:()=>V(!0),className:"px-6 py-3 glass hover:bg-surface transition-colors flex items-center gap-2 text-sm font-medium",children:[u.jsx(Ml,{size:16}),u.jsxs("div",{className:"flex flex-col items-start",children:[u.jsx("span",{children:"Sync Settings"}),u.jsx("span",{className:"text-[10px] text-fg/40 font-mono",children:de.sync_start_date?`From: ${new Date(de.sync_start_date).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:de.last_sync_checkpoint?`Checkpoint: ${new Date(de.last_sync_checkpoint).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:"All time"})]})]}),u.jsxs("button",{onClick:K,disabled:$,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-105 active:scale-95 transition-all flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100",children:[u.jsx(ec,{size:18,className:$?"animate-spin":""}),$?"Syncing...":"Sync History"]})]})]}),u.jsx(rR,{onOpenUrl:ue=>window.open(ue,"_blank","noopener,noreferrer"),onCopyText:ue=>{navigator.clipboard.writeText(ue)}})]}),o==="chat"&&u.jsx(N5,{}),o==="transmute"&&u.jsx(P5,{}),o==="engine"&&u.jsx(RP,{}),o==="account"&&u.jsx(UP,{}),o==="logs"&&u.jsx(JP,{initialState:ie}),u.jsx(DP,{isExpanded:he,onToggle:()=>ne(!he),onNavigate:T,liftUp:o==="chat"})]}),u.jsx(VP,{signal:R,onClose:()=>M(null)}),u.jsx(qP,{isOpen:O,onClose:()=>V(!1)}),u.jsx(C5,{isOpen:E,onClose:()=>N(!1)})]})})}):u.jsx(jP,{onAuthSuccess:()=>D(),isInitialized:b})}function si({active:e,icon:t,label:n,onClick:r,collapsed:o}){return u.jsx("button",{onClick:r,title:o?n:"",className:`w-full flex items-center ${o?"justify-center":"gap-3"} px-4 py-3 rounded-xl transition-all ${e?"bg-primary/10 text-primary shadow-sm":"text-fg/60 hover:bg-surface hover:text-fg"}`,children:o?Mo.cloneElement(t,{className:e?"text-primary":""}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"min-w-[20px] flex justify-center",children:Mo.cloneElement(t,{className:e?"text-primary":""})}),u.jsx(ze.span,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"font-semibold text-sm whitespace-nowrap",children:n})]})})}function I5(){Je.interceptors.request.use(async e=>{try{const{data:{session:t}}=await se.auth.getSession();t?.access_token&&(e.headers.Authorization=`Bearer ${t.access_token}`);const n=ks();n&&(e.headers["x-supabase-url"]=n.url,e.headers["x-supabase-key"]=n.anonKey)}catch(t){console.error("[Axios] Error injecting headers:",t)}return e})}I5();rS.createRoot(document.getElementById("root")).render(u.jsx(Mo.StrictMode,{children:u.jsx(O5,{})}));
|
|
125
|
+
Failed to load changelog.`)}finally{a(!1)}};return u.jsx(Rt,{children:e&&u.jsxs(u.Fragment,{children:[u.jsx(ze.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:t,className:"fixed inset-0 bg-black/60 backdrop-blur-sm z-50"}),u.jsx(ze.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:20},transition:{type:"spring",damping:25,stiffness:300},className:"fixed inset-0 z-50 flex items-center justify-center p-4 pointer-events-none",children:u.jsxs("div",{className:"glass w-full max-w-3xl max-h-[80vh] overflow-hidden pointer-events-auto shadow-2xl",children:[u.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx($x,{size:24,className:"text-primary"}),u.jsx("h2",{className:"text-xl font-bold",children:"Release Notes"})]}),u.jsx("button",{onClick:t,className:"p-2 hover:bg-surface rounded-lg transition-colors",children:u.jsx(bn,{size:20,className:"text-fg/60"})})]}),u.jsx("div",{className:"p-6 overflow-y-auto custom-scrollbar max-h-[calc(80vh-88px)]",children:o?u.jsx("div",{className:"flex items-center justify-center py-12",children:u.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-primary border-t-transparent"})}):u.jsx(ep,{components:{h1:({children:d})=>u.jsx("h1",{className:"text-2xl font-bold text-fg mb-6 mt-0",children:d}),h2:({children:d})=>u.jsx("h2",{className:"text-xl font-bold text-fg mt-8 mb-3 pb-2 border-b border-border first:mt-0",children:d}),h3:({children:d})=>u.jsx("h3",{className:"text-lg font-bold text-primary mt-6 mb-2",children:d}),p:({children:d})=>u.jsx("p",{className:"text-sm text-fg/70 mb-3 leading-relaxed",children:d}),ul:({children:d})=>u.jsx("ul",{className:"list-none space-y-1 mb-4 ml-0",children:d}),li:({children:d})=>u.jsx("li",{className:"text-sm text-fg/80 ml-4 mb-1 before:content-['•'] before:mr-2 before:text-primary",children:d}),a:({href:d,children:h})=>u.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:text-primary/80 underline transition-colors",children:h}),code:({children:d})=>u.jsx("code",{className:"bg-surface/50 text-accent px-1.5 py-0.5 rounded text-xs font-mono border border-border",children:d}),strong:({children:d})=>u.jsx("strong",{className:"font-bold text-fg",children:d})},children:n})})]})})]})})}function T5({asset:e,onClose:t}){const n=()=>{e.content&&navigator.clipboard.writeText(e.content)},r=()=>{if(!e.content)return;const o=new Blob([e.content],{type:"text/markdown"}),a=URL.createObjectURL(o),l=document.createElement("a");l.href=a,l.download=`${e.title.replace(/[^a-z0-9]/gi,"_").toLowerCase()}.md`,document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(a)};return u.jsx(Rt,{children:e&&u.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:u.jsxs(ze.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden border border-gray-200 dark:border-gray-700",children:[u.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("div",{className:"p-2 rounded-lg bg-purple-100 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400",children:e.type==="audio"?u.jsx(Zd,{className:"w-5 h-5"}):u.jsx(wi,{className:"w-5 h-5"})}),u.jsxs("div",{children:[u.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e.title}),u.jsxs("p",{className:"text-xs text-gray-500",children:["Generated ",new Date(e.created_at).toLocaleString()," • ",e.metadata?.source_signal_count||0," sources"]})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{onClick:n,className:"p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",title:"Copy Content",children:u.jsx(Vh,{className:"w-4 h-4"})}),u.jsx("button",{onClick:r,className:"p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",title:"Download File",children:u.jsx(Xd,{className:"w-4 h-4"})}),u.jsx("div",{className:"w-px h-6 bg-gray-200 dark:bg-gray-700 mx-1"}),u.jsx("button",{onClick:t,className:"p-2 text-gray-500 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:u.jsx(bn,{className:"w-5 h-5"})})]})]}),u.jsx("div",{className:"flex-1 overflow-y-auto p-6 bg-white dark:bg-gray-950",children:e.status&&e.status!=="completed"?u.jsxs("div",{className:"flex flex-col items-center justify-center h-64 gap-4",children:[u.jsx(Nt,{className:"w-12 h-12 animate-spin text-purple-500"}),u.jsxs("div",{className:"text-center",children:[u.jsx("h4",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:e.status==="processing"?"Generating Asset...":"Queued for Desktop..."}),u.jsx("p",{className:"text-sm text-gray-500 max-w-xs mt-1",children:"The RealTimeX Desktop app is processing this request. This modal will update automatically once finished."})]})]}):e.type==="markdown"?u.jsx("div",{className:"prose dark:prose-invert max-w-none",children:u.jsx(ep,{children:e.content||""})}):e.type==="audio"?u.jsxs("div",{className:"flex flex-col items-center justify-center h-64 gap-4",children:[u.jsx("div",{className:"w-16 h-16 rounded-full bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center animate-pulse",children:u.jsx(Zd,{className:"w-8 h-8 text-purple-600 dark:text-purple-400"})}),u.jsx("p",{className:"text-gray-500",children:"Audio playback not yet implemented (Simulated)"}),u.jsxs("audio",{controls:!0,className:"w-full max-w-md mt-4",children:[u.jsx("source",{src:e.content||"",type:"audio/mpeg"}),"Your browser does not support the audio element."]})]}):u.jsx("div",{className:"text-gray-500 text-center py-10",children:"Unsupported asset type"})})]})})})}function Fx({engine:e,onClose:t,onSave:n,onDelete:r}){const{showToast:o}=yc(),[a,l]=A.useState({title:"",type:"newsletter",status:"active",config:{schedule:"",min_score:70,categories:[],custom_prompt:"",max_signals:10,execution_mode:"local"}}),[d,h]=A.useState(!1);A.useEffect(()=>{e&&l({title:e.title,type:e.type,status:e.status,config:{schedule:e.config.schedule||"",min_score:e.config.filters?.min_score||70,categories:Array.isArray(e.config.category)?e.config.category:e.config.category?[e.config.category]:[],custom_prompt:e.config.custom_prompt||"",max_signals:e.config.max_signals||10,execution_mode:e.config.execution_mode||"local"}})},[e]);const p=async()=>{try{const x={title:a.title,type:a.type,status:a.status,config:{schedule:a.config.schedule,filters:{min_score:a.config.min_score,category:a.config.category},custom_prompt:a.config.custom_prompt,max_signals:a.config.max_signals,execution_mode:a.config.execution_mode}};if(e){const{data:w,error:b}=await se.from("engines").update(x).eq("id",e.id).select().single();if(b)throw b;n(w),o("Engine updated successfully","success")}else{const{data:{user:w}}=await se.auth.getUser();if(!w)throw new Error("Not authenticated");const{data:b,error:S}=await se.from("engines").insert({...x,user_id:w.id}).select().single();if(S)throw S;n(b),o("Engine created successfully","success")}t()}catch(x){console.error("Save error:",x),o(x.message||"Failed to save engine","error")}},m=async()=>{if(!(!e||!r))try{const{error:x}=await se.from("engines").delete().eq("id",e.id);if(x)throw x;r(e.id),o("Engine deleted","success"),t()}catch(x){o(x.message||"Failed to delete engine","error")}},y=()=>{h(!1),t()};return!e&&!t?null:u.jsx(Rt,{children:u.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:u.jsxs(ze.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-2xl max-h-[85vh] flex flex-col overflow-hidden border border-gray-200 dark:border-gray-700",children:[u.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800",children:[u.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:e?"Edit Engine":"Create Engine"}),u.jsx("button",{onClick:y,className:"p-2 text-gray-500 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:u.jsx(bn,{className:"w-5 h-5"})})]}),u.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Engine Name"}),u.jsx("input",{type:"text",value:a.title,onChange:x=>l({...a,title:x.target.value}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-purple-500 focus:border-transparent",placeholder:"e.g., Daily Tech Brief"})]}),u.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Type"}),u.jsxs("select",{value:a.type,onChange:x=>l({...a,type:x.target.value}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",children:[u.jsx("option",{value:"newsletter",children:"Newsletter"}),u.jsx("option",{value:"thread",children:"Thread"}),u.jsx("option",{value:"audio",children:"Audio Brief"}),u.jsx("option",{value:"report",children:"Report"})]})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Status"}),u.jsxs("select",{value:a.status,onChange:x=>l({...a,status:x.target.value}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",children:[u.jsx("option",{value:"active",children:"Active"}),u.jsx("option",{value:"paused",children:"Paused"}),u.jsx("option",{value:"draft",children:"Draft"})]})]})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Execution Environment"}),u.jsxs("select",{value:a.config.execution_mode,onChange:x=>l({...a,config:{...a.config,execution_mode:x.target.value}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",children:[u.jsx("option",{value:"local",children:"Local (Alchemy LLM)"}),u.jsx("option",{value:"desktop",children:"RealTimeX Desktop (Agent Swarm)"})]}),u.jsx("p",{className:"text-[10px] text-gray-500 mt-1",children:a.config.execution_mode==="desktop"?"Delegates heavy tasks like Audio/Video to the desktop app.":"Runs simple Markdown tasks directly in Alchemy."})]})]}),u.jsxs("div",{className:"space-y-4",children:[u.jsx("h4",{className:"font-medium text-gray-900 dark:text-gray-100",children:"Signal Filters"}),u.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Min Score"}),u.jsx("input",{type:"number",min:"0",max:"100",value:a.config.min_score,onChange:x=>l({...a,config:{...a.config,min_score:parseInt(x.target.value)||0}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Max Signals"}),u.jsx("input",{type:"number",min:"1",max:"50",value:a.config.max_signals,onChange:x=>l({...a,config:{...a.config,max_signals:parseInt(x.target.value)||10}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"})]})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Category Filter (multi-select)"}),u.jsxs("select",{multiple:!0,value:a.config.categories,onChange:x=>{const w=Array.from(x.target.selectedOptions,b=>b.value);l({...a,config:{...a.config,categories:w}})},className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 min-h-[100px]",children:[u.jsx("option",{value:"AI & ML",children:"AI & ML"}),u.jsx("option",{value:"Technology",children:"Technology"}),u.jsx("option",{value:"Business",children:"Business"}),u.jsx("option",{value:"Finance",children:"Finance"}),u.jsx("option",{value:"Science",children:"Science"}),u.jsx("option",{value:"Politics",children:"Politics"})]}),u.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Hold Cmd/Ctrl to select multiple categories"})]})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Schedule (optional)"}),u.jsx("input",{type:"text",value:a.config.schedule,onChange:x=>l({...a,config:{...a.config,schedule:x.target.value}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",placeholder:"e.g., Daily @ 9am, Manual"}),u.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Note: Scheduling is not yet automated"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Custom Prompt Override (optional)"}),u.jsx("textarea",{value:a.config.custom_prompt,onChange:x=>l({...a,config:{...a.config,custom_prompt:x.target.value}}),rows:4,className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 resize-none",placeholder:"Override the default prompt for this engine type..."})]})]}),u.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50",children:[e&&r?d?u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("span",{className:"text-sm text-red-600 font-medium",children:"Really delete?"}),u.jsx("button",{onClick:m,className:"px-3 py-1.5 bg-red-600 text-white text-xs rounded-lg hover:bg-red-700 transition-colors",children:"Confirm"}),u.jsx("button",{onClick:()=>h(!1),className:"px-3 py-1.5 text-gray-500 hover:text-gray-700 text-xs rounded-lg",children:"Cancel"})]}):u.jsxs("button",{onClick:()=>h(!0),className:"flex items-center gap-2 px-4 py-2 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:[u.jsx(Wh,{className:"w-4 h-4"}),"Delete"]}):u.jsx("div",{}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx("button",{onClick:y,className:"px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:"Cancel"}),u.jsxs("button",{onClick:p,className:"flex items-center gap-2 px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors",children:[u.jsx(fr,{className:"w-4 h-4"}),"Save"]})]})]})]})})})}const A5=({engine:e,onRun:t,onEdit:n,onToggle:r,onViewBrief:o,isLoading:a})=>{const l=!!e.config.tag,d={newsletter:l?u.jsx(qh,{className:"w-5 h-5 text-blue-500"}):u.jsx(wi,{className:"w-5 h-5 text-emerald-500"}),thread:u.jsx(Xt,{className:"w-5 h-5 text-blue-500"}),audio:u.jsx(Zd,{className:"w-5 h-5 text-purple-500"}),report:u.jsx(Ml,{className:"w-5 h-5 text-orange-500"})};return u.jsxs(ze.div,{layout:!0,initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:`p-5 rounded-2xl border ${e.status==="active"?"bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700 shadow-sm":"bg-gray-50 dark:bg-gray-900 border-dashed border-gray-300 dark:border-gray-700 opacity-75"} transition-all hover:shadow-md group`,children:[u.jsxs("div",{className:"flex justify-between items-start mb-4",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("div",{className:"p-2 rounded-xl bg-gray-100 dark:bg-gray-800",children:d[e.type]||u.jsx(wi,{className:"w-5 h-5"})}),u.jsxs("div",{children:[u.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e.title}),u.jsxs("p",{className:"text-xs text-gray-500 capitalize",children:[l?"Topic":e.type," Pipeline"]})]})]}),u.jsxs("div",{className:"flex gap-1",children:[u.jsx("button",{onClick:()=>r(e.id,e.status),className:"p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:e.status==="active"?u.jsx(PS,{className:"w-4 h-4"}):u.jsx(Xg,{className:"w-4 h-4"})}),u.jsx("button",{onClick:()=>o(e.id),title:"View Production Brief JSON",className:"p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:u.jsx(Hx,{className:"w-4 h-4"})}),u.jsx("button",{onClick:()=>n(e.id),className:"p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:u.jsx(Ml,{className:"w-4 h-4"})})]})]}),u.jsxs("div",{className:"space-y-2 mb-4",children:[u.jsxs("div",{className:"text-xs text-gray-500 flex justify-between",children:[u.jsx("span",{children:"Last Run"}),u.jsx("span",{children:e.last_run_at?new Date(e.last_run_at).toLocaleDateString():"Never"})]}),u.jsxs("div",{className:"text-xs text-gray-500 flex justify-between",children:[u.jsx("span",{children:"Schedule"}),u.jsx("span",{children:e.config.schedule||"Manual"})]})]}),u.jsxs("button",{onClick:()=>t(e.id),disabled:a||e.status!=="active",className:"w-full flex items-center justify-center gap-2 py-2 rounded-xl bg-gray-900 dark:bg-white text-white dark:text-gray-900 font-medium hover:opacity-90 disabled:opacity-50 transition-all text-sm",children:[a?u.jsx(Nt,{className:"w-4 h-4 animate-spin"}):u.jsx(Xg,{className:"w-4 h-4"}),a?"Running...":"Run Engine"]})]})};function P5(){const[e,t]=A.useState([]),[n,r]=A.useState(!0),[o,a]=A.useState(new Set),[l,d]=A.useState(null),[h,p]=A.useState(null),[m,y]=A.useState(!1),[x,w]=A.useState(null),[b,S]=A.useState(!1),[k,_]=A.useState(!1),{showToast:E}=yc();A.useEffect(()=>{(async()=>R())();const J=se.channel("asset-updates").on("postgres_changes",{event:"UPDATE",schema:"public",table:"assets"},q=>{const ie=q.new;d(oe=>oe?.id===ie.id?ie:oe),ie.status==="completed"&&q.old.status!=="completed"&&E(`Asset "${ie.title}" is ready!`,"success")}).subscribe();return()=>{se.removeChannel(J)}},[]);const N=async()=>{if(!k)try{_(!0),E("Scanning for new categories and topics...","info");const{data:{session:ee}}=await se.auth.getSession(),J=ks(),q={"Content-Type":"application/json","x-user-id":ee?.user?.id||""};if(ee?.access_token&&(q.Authorization=`Bearer ${ee.access_token}`),J&&(q["x-supabase-url"]=J.url,q["x-supabase-key"]=J.anonKey),!(await fetch("/api/engines/ensure-defaults",{method:"POST",headers:q})).ok)throw new Error("Failed to generate engines");E("Engine discovery complete!","success"),await R()}catch(ee){console.error("Failed to generate engines:",ee),E("Discovery failed. Check settings.","error")}finally{_(!1)}},R=async()=>{try{r(!0);const{data:{user:ee}}=await se.auth.getUser();if(!ee)return;const{data:J,error:q}=await se.from("engines").select("*").eq("user_id",ee.id).order("created_at",{ascending:!1});if(q)throw q;t(J)}catch(ee){console.error("Error fetching engines:",ee),E("Failed to load engines","error")}finally{r(!1)}},M=async ee=>{if(!o.has(ee))try{a(C=>new Set(C).add(ee)),E("Starting engine run...","info");const{data:{session:J}}=await se.auth.getSession(),q=J?.access_token,ie=ks(),oe={"Content-Type":"application/json","x-user-id":J?.user?.id||""};q&&(oe.Authorization=`Bearer ${q}`),ie&&(oe["x-supabase-url"]=ie.url,oe["x-supabase-key"]=ie.anonKey);const G=await fetch(`/api/engines/${ee}/run`,{method:"POST",headers:oe});if(!G.ok){const C=await G.json();throw new Error(C.error||"Run failed")}const de=await G.json();de.status==="completed"?E(`Engine run complete! Created: ${de.title}`,"success"):E(`Engine run started on Desktop. Tracking as: ${de.id}`,"info"),d(de),t(C=>C.map(D=>D.id===ee?{...D,last_run_at:new Date().toISOString()}:D))}catch(J){console.error("Engine run error:",J),E(J.message||"Failed to run engine","error")}finally{a(J=>{const q=new Set(J);return q.delete(ee),q})}},O=async ee=>{try{y(!0);const{data:{session:J}}=await se.auth.getSession(),q=ks(),ie={"Content-Type":"application/json","x-user-id":J?.user?.id||""};J?.access_token&&(ie.Authorization=`Bearer ${J.access_token}`),q&&(ie["x-supabase-url"]=q.url,ie["x-supabase-key"]=q.anonKey);const oe=await fetch(`/api/engines/${ee}/brief`,{headers:ie});if(!oe.ok)throw new Error("Failed to fetch brief");const G=await oe.json();p(G)}catch{E("Failed to generate production brief","error")}finally{y(!1)}},V=async(ee,J)=>{const q=J==="active"?"paused":"active";t(ie=>ie.map(oe=>oe.id===ee?{...oe,status:q}:oe));try{const{error:ie}=await se.from("engines").update({status:q}).eq("id",ee);if(ie)throw ie;E(`Engine ${q==="active"?"resumed":"paused"}`,"success")}catch{t(oe=>oe.map(G=>G.id===ee?{...G,status:J}:G)),E("Failed to update status","error")}},$=()=>{S(!0)},W=ee=>{const J=e.find(q=>q.id===ee);J&&w(J)},he=ee=>{t(J=>J.find(ie=>ie.id===ee.id)?J.map(ie=>ie.id===ee.id?ee:ie):[ee,...J])},ne=ee=>{t(J=>J.filter(q=>q.id!==ee))},le=()=>{w(null),S(!1)};return u.jsxs("div",{className:"h-full flex flex-col bg-gray-50/50 dark:bg-[#0A0A0A]",children:[u.jsx("div",{className:"flex-none p-6 border-b border-gray-200 dark:border-gray-800 bg-white/50 dark:bg-gray-900/50 backdrop-blur-sm z-10 sticky top-0",children:u.jsxs("div",{className:"flex justify-between items-center max-w-7xl mx-auto w-full",children:[u.jsxs("div",{children:[u.jsx("h2",{className:"text-2xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-purple-500 to-blue-500",children:"Transmute Engine"}),u.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:"Active Generation Pipelines & Assets"})]}),u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsxs("button",{onClick:N,disabled:k,className:"flex items-center gap-2 px-4 py-2 bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 rounded-xl font-medium hover:bg-purple-100 dark:hover:bg-purple-900/40 transition-all border border-purple-200 dark:border-purple-800 disabled:opacity-50",children:[k?u.jsx(Nt,{className:"w-4 h-4 animate-spin"}):u.jsx(Xt,{className:"w-4 h-4"}),"Generate Engines"]}),u.jsxs("button",{onClick:$,className:"flex items-center gap-2 px-4 py-2 bg-gray-900 dark:bg-white text-white dark:text-gray-900 rounded-xl font-medium hover:opacity-90 transition-opacity shadow-lg shadow-purple-500/10",children:[u.jsx(Hh,{className:"w-4 h-4"}),"New Engine"]})]})]})}),u.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:u.jsx("div",{className:"max-w-7xl mx-auto w-full",children:n?u.jsx("div",{className:"flex items-center justify-center h-64",children:u.jsx(Nt,{className:"w-8 h-8 animate-spin text-purple-500"})}):e.length===0?u.jsxs("div",{className:"flex flex-col items-center justify-center h-96 text-center",children:[u.jsx("div",{className:"w-16 h-16 rounded-2xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-4",children:u.jsx(Xt,{className:"w-8 h-8 text-gray-400"})}),u.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"No Engines Configured"}),u.jsx("p",{className:"text-gray-500 max-w-sm mt-2 mb-6",children:"Create your first pipeline to automatically turn signals into newsletters, threads, or audio briefs."}),u.jsx("button",{onClick:$,className:"px-6 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",children:"Create Engine"})]}):u.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:u.jsx(Rt,{children:e.map(ee=>u.jsx(A5,{engine:ee,onRun:M,onEdit:W,onToggle:V,onViewBrief:O,isLoading:o.has(ee.id)},ee.id))})})})}),u.jsx(Rt,{children:h&&u.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/60 backdrop-blur-md",children:u.jsxs(ze.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden border border-gray-200 dark:border-gray-700",children:[u.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("div",{className:"p-2 rounded-lg bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400",children:u.jsx(Hx,{className:"w-5 h-5"})}),u.jsxs("div",{children:[u.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:"Production Brief JSON"}),u.jsx("p",{className:"text-xs text-gray-500",children:"Stateless & Self-Contained Contract"})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{onClick:()=>{navigator.clipboard.writeText(JSON.stringify(h,null,2)),E("JSON copied to clipboard","info")},className:"p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",children:u.jsx(Vh,{className:"w-4 h-4"})}),u.jsx("button",{onClick:()=>p(null),className:"p-2 text-gray-500 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:u.jsx(bn,{className:"w-5 h-5"})})]})]}),u.jsx("div",{className:"flex-1 overflow-y-auto p-4 bg-[#0D1117] font-mono text-sm",children:u.jsx("pre",{className:"text-blue-300",children:JSON.stringify(h,null,2)})}),u.jsx("div",{className:"p-4 border-t border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50 text-[10px] text-gray-500 text-center",children:"This JSON contains the full context (Signals + User Persona) required for the Desktop Studio."})]})})}),m&&u.jsx("div",{className:"fixed inset-0 z-[70] flex items-center justify-center bg-black/20 backdrop-blur-sm",children:u.jsx(Nt,{className:"w-10 h-10 animate-spin text-white"})}),u.jsx(T5,{asset:l,onClose:()=>d(null)}),x&&u.jsx(Fx,{engine:x,onClose:le,onSave:he,onDelete:ne}),b&&u.jsx(Fx,{engine:null,onClose:le,onSave:he})]})}class R5{audioContext=null;enabled=!0;constructor(){}getAudioContext(){return this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext)),this.audioContext}setEnabled(t){this.enabled=t}isEnabled(){return this.enabled}playTone(t,n,r=.3){if(this.enabled)try{const o=this.getAudioContext(),a=o.createOscillator(),l=o.createGain();a.connect(l),l.connect(o.destination),a.frequency.value=t,a.type="sine",l.gain.setValueAtTime(r,o.currentTime),l.gain.exponentialRampToValueAtTime(.01,o.currentTime+n),a.start(o.currentTime),a.stop(o.currentTime+n)}catch(o){console.warn("[Sound] Failed to play tone:",o)}}playSequence(t,n=.3){if(!this.enabled)return;let r=0;t.forEach(o=>{setTimeout(()=>{this.playTone(o.freq,o.duration,n)},r),r+=o.delay})}syncStart(){this.playSequence([{freq:261.63,duration:.15,delay:0},{freq:329.63,duration:.15,delay:100},{freq:392,duration:.2,delay:100}],.2)}signalFound(){this.playSequence([{freq:392,duration:.1,delay:0},{freq:523.25,duration:.15,delay:80}],.25)}syncComplete(){this.playSequence([{freq:261.63,duration:.12,delay:0},{freq:329.63,duration:.12,delay:80},{freq:392,duration:.12,delay:80},{freq:523.25,duration:.2,delay:80}],.2)}error(){this.playSequence([{freq:329.63,duration:.15,delay:0},{freq:261.63,duration:.2,delay:100}],.3)}click(){this.playTone(440,.05,.15)}}const So=new R5;function O5(){const[e,t]=A.useState([]),[n,r]=A.useState([]),[o,a]=A.useState("discovery"),[l,d]=A.useState(!1),[h,p]=A.useState(null),[m,y]=A.useState(!0),[x,w]=A.useState(!tx),[b,S]=A.useState(!0),[k,_]=A.useState(!1),[E,N]=A.useState(!1),[R,M]=A.useState(null),[O,V]=A.useState(!1),[$,W]=A.useState(!1),[he,ne]=A.useState(!1),[le,ee]=A.useState(!0),[J,q]=A.useState(()=>localStorage.getItem("theme")||"dark"),[ie,oe]=A.useState(null),G=A.useRef(null);A.useMemo(()=>{const ue=n.length;let xe=0,me=0,ge=null;for(const Ke of n){xe+=Ke.score,Ke.score>me&&(me=Ke.score);const Gt=new Date(Ke.date);(!ge||Gt>new Date(ge.date))&&(ge=Ke)}const Ae=ue?Math.round(xe/ue):0,Ve=ge?new Date(ge.date):null;return{total:ue,average:Ae,top:me,latestTimestamp:Ve,latestTitle:ge?.title??ge?.category??null}},[n]),A.useEffect(()=>{(async()=>{if(!tx){w(!0),y(!1);return}try{const{data:me,error:ge}=await se.from("init_state").select("is_initialized").single();ge?(console.warn("[App] Init check error (might be fresh DB):",ge),ge.code==="42P01"&&S(!1)):S(me.is_initialized>0);const{data:{session:Ae}}=await se.auth.getSession();p(Ae?.user??null)}catch(me){console.error("[App] Status check failed:",me)}finally{y(!1)}})();const{data:{subscription:xe}}=se.auth.onAuthStateChange((me,ge)=>{p(ge?.user??null)});return()=>xe.unsubscribe()},[]),A.useEffect(()=>{document.documentElement.setAttribute("data-theme",J),localStorage.setItem("theme",J)},[J]);const[de,C]=A.useState({});A.useEffect(()=>{(async()=>{if(!h)return;const{data:xe}=await se.from("alchemy_settings").select("sync_start_date, last_sync_checkpoint").eq("user_id",h.id).maybeSingle();xe&&C(xe)})()},[h,O]),A.useEffect(()=>{if(!h)return;(async()=>{const{data:me}=await se.from("alchemy_settings").select("sound_enabled").eq("user_id",h.id).maybeSingle();if(me){const ge=me.sound_enabled??!0;ee(ge),So.setEnabled(ge)}})();const xe=se.channel("processing_events").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events",filter:`user_id=eq.${h.id}`},me=>{const ge=me.new;ge.agent_state==="Mining"&&!$&&(W(!0),ne(!0),le&&So.syncStart()),ge.agent_state==="Signal"&&le&&So.signalFound(),ge.agent_state==="Completed"&&(W(!1),le&&(ge.metadata?.errors>0?So.error():So.syncComplete()),setTimeout(()=>{ne(!1)},5e3),D())}).subscribe();return()=>{se.removeChannel(xe)}},[h,$,le]),A.useEffect(()=>{const ue=new EventSource("/events");return ue.onmessage=xe=>{const me=JSON.parse(xe.data);me.type==="history"?t(ge=>[...me.data,...ge].slice(0,100)):t(ge=>[me,...ge].slice(0,100))},D(),()=>ue.close()},[h]),A.useEffect(()=>{G.current&&G.current.scrollIntoView({behavior:"smooth"})},[e]);const D=async()=>{try{if(h){const{data:xe,error:me}=await se.from("signals").select("*").order("created_at",{ascending:!1});if(!me&&xe){r(xe.map(ge=>({id:ge.id,title:ge.title,score:ge.score,summary:ge.summary,date:ge.created_at,category:ge.category,entities:ge.entities})));return}}const ue=await Je.get("/api/signals");r(ue.data)}catch(ue){console.error("Failed to fetch signals",ue)}},K=async()=>{d(!0);try{await Je.post("/api/mine"),D()}catch(ue){console.error("Mining failed:",ue)}finally{d(!1)}},T=(ue,xe)=>{ue==="logs"?(oe(xe),a("logs")):a(ue)};return m?u.jsx("div",{className:"flex items-center justify-center h-screen bg-bg",children:u.jsx("div",{className:"w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin"})}):x?u.jsx(hb,{onComplete:()=>w(!1)}):h?u.jsx(TP,{children:u.jsx(OP,{children:u.jsxs("div",{className:"flex h-screen w-screen overflow-hidden bg-bg text-fg",children:[u.jsxs(ze.aside,{animate:{width:k?72:240},className:"glass m-4 mr-0 flex flex-col relative",children:[u.jsxs("div",{className:`px-4 py-3 pb-4 flex items-center gap-3 ${k?"justify-center":""}`,children:[u.jsx("div",{className:"w-10 h-10 min-w-[40px] bg-gradient-to-br from-primary to-accent rounded-xl flex items-center justify-center shadow-lg glow-primary",children:u.jsx(Xt,{className:"text-white fill-current",size:24})}),!k&&u.jsx(ze.h1,{initial:{opacity:0},animate:{opacity:1},className:"text-xl font-bold tracking-tight",children:"Alchemist"})]}),u.jsxs("nav",{className:"flex-1 flex flex-col gap-1 px-3",children:[u.jsx(si,{active:o==="discovery",onClick:()=>a("discovery"),icon:u.jsx(jS,{size:20}),label:"Discovery",collapsed:k}),u.jsx(si,{active:o==="chat",onClick:()=>a("chat"),icon:u.jsx(Qd,{size:20}),label:"Chat",collapsed:k}),u.jsx(si,{active:o==="transmute",onClick:()=>a("transmute"),icon:u.jsx(Xt,{size:20}),label:"Transmute",collapsed:k}),u.jsx(si,{active:o==="engine",onClick:()=>a("engine"),icon:u.jsx(Ml,{size:20}),label:"Settings",collapsed:k}),u.jsx(si,{active:o==="logs",onClick:()=>a("logs"),icon:u.jsx(zl,{size:20}),label:"System Logs",collapsed:k}),u.jsx(si,{active:o==="account",onClick:()=>a("account"),icon:u.jsx(tc,{size:20}),label:"Account",collapsed:k})]}),u.jsx("div",{className:"px-3 pb-2",children:u.jsxs("button",{onClick:()=>q(J==="dark"?"light":"dark"),className:`w-full flex items-center ${k?"justify-center":"gap-3"} px-4 py-2.5 rounded-lg text-fg/40 hover:text-fg hover:bg-surface/50 transition-all text-xs font-medium`,title:k?J==="dark"?"Switch to Light Mode":"Switch to Dark Mode":"",children:[u.jsx("div",{className:"min-w-[20px] flex justify-center",children:J==="dark"?u.jsx(zS,{size:18}):u.jsx(AS,{size:18})}),!k&&u.jsx(ze.span,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"whitespace-nowrap",children:J==="dark"?"Light Mode":"Dark Mode"})]})}),u.jsxs("div",{className:"px-3 pb-3",children:[u.jsx("button",{onClick:()=>_(!k),className:`w-full flex items-center px-4 py-2.5 rounded-lg text-fg/40 hover:text-fg hover:bg-surface/50 transition-all text-xs font-medium ${k?"justify-center":"gap-3"}`,children:k?u.jsx(gS,{size:20}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"min-w-[20px] flex justify-center",children:u.jsx(mS,{size:20})}),u.jsx("span",{children:"Collapse"})]})}),u.jsxs("button",{onClick:()=>N(!0),className:"w-full flex items-center justify-center gap-2 px-3 py-2 mt-2 text-[10px] font-mono text-fg/30 hover:text-primary hover:bg-surface/30 rounded-lg transition-all group",title:"View Changelog",children:[!k&&u.jsxs(u.Fragment,{children:[u.jsx(eh,{size:12,className:"group-hover:text-primary transition-colors"}),u.jsxs("span",{children:["v","1.0.53"]})]}),k&&u.jsx(eh,{size:14,className:"group-hover:text-primary transition-colors"})]})]})]}),u.jsxs("main",{className:"flex-1 flex flex-col p-4 gap-4 overflow-hidden relative",children:[o==="discovery"&&u.jsxs(u.Fragment,{children:[u.jsxs("header",{className:"flex justify-between items-center px-4 py-2",children:[u.jsxs("div",{children:[u.jsx("h2",{className:"text-2xl font-bold",children:"Discovery"}),u.jsx("p",{className:"text-sm text-fg/50",children:"Passive intelligence mining from your browser history."})]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsxs("button",{onClick:()=>V(!0),className:"px-6 py-3 glass hover:bg-surface transition-colors flex items-center gap-2 text-sm font-medium",children:[u.jsx(Ml,{size:16}),u.jsxs("div",{className:"flex flex-col items-start",children:[u.jsx("span",{children:"Sync Settings"}),u.jsx("span",{className:"text-[10px] text-fg/40 font-mono",children:de.sync_start_date?`From: ${new Date(de.sync_start_date).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:de.last_sync_checkpoint?`Checkpoint: ${new Date(de.last_sync_checkpoint).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:"All time"})]})]}),u.jsxs("button",{onClick:K,disabled:$,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-105 active:scale-95 transition-all flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100",children:[u.jsx(ec,{size:18,className:$?"animate-spin":""}),$?"Syncing...":"Sync History"]})]})]}),u.jsx(rR,{onOpenUrl:ue=>window.open(ue,"_blank","noopener,noreferrer"),onCopyText:ue=>{navigator.clipboard.writeText(ue)}})]}),o==="chat"&&u.jsx(N5,{}),o==="transmute"&&u.jsx(P5,{}),o==="engine"&&u.jsx(RP,{}),o==="account"&&u.jsx(UP,{}),o==="logs"&&u.jsx(JP,{initialState:ie}),u.jsx(DP,{isExpanded:he,onToggle:()=>ne(!he),onNavigate:T,liftUp:o==="chat"})]}),u.jsx(VP,{signal:R,onClose:()=>M(null)}),u.jsx(qP,{isOpen:O,onClose:()=>V(!1)}),u.jsx(C5,{isOpen:E,onClose:()=>N(!1)})]})})}):u.jsx(jP,{onAuthSuccess:()=>D(),isInitialized:b})}function si({active:e,icon:t,label:n,onClick:r,collapsed:o}){return u.jsx("button",{onClick:r,title:o?n:"",className:`w-full flex items-center ${o?"justify-center":"gap-3"} px-4 py-3 rounded-xl transition-all ${e?"bg-primary/10 text-primary shadow-sm":"text-fg/60 hover:bg-surface hover:text-fg"}`,children:o?Mo.cloneElement(t,{className:e?"text-primary":""}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"min-w-[20px] flex justify-center",children:Mo.cloneElement(t,{className:e?"text-primary":""})}),u.jsx(ze.span,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"font-semibold text-sm whitespace-nowrap",children:n})]})})}function I5(){Je.interceptors.request.use(async e=>{try{const{data:{session:t}}=await se.auth.getSession();t?.access_token&&(e.headers.Authorization=`Bearer ${t.access_token}`);const n=ks();n&&(e.headers["x-supabase-url"]=n.url,e.headers["x-supabase-key"]=n.anonKey)}catch(t){console.error("[Axios] Error injecting headers:",t)}return e})}I5();rS.createRoot(document.getElementById("root")).render(u.jsx(Mo.StrictMode,{children:u.jsx(O5,{})}));
|
package/dist/index.html
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
10
10
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
11
11
|
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;700&family=Outfit:wght@300;400;600;800&display=swap" rel="stylesheet">
|
|
12
|
-
<script type="module" crossorigin src="/assets/index-
|
|
12
|
+
<script type="module" crossorigin src="/assets/index-D5nmpTYI.js"></script>
|
|
13
13
|
<link rel="stylesheet" crossorigin href="/assets/index-BcolxI8u.css">
|
|
14
14
|
</head>
|
|
15
15
|
<body>
|
package/package.json
CHANGED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
-- Variable Dimension Embedding Support Migration
|
|
2
|
+
-- Enables agnostic model switching by supporting multiple embedding dimensions
|
|
3
|
+
-- Strategy: Partial indexes per dimension + explicit casting in queries
|
|
4
|
+
|
|
5
|
+
-- 1. Drop existing HNSW index (requires fixed dimension)
|
|
6
|
+
DROP INDEX IF EXISTS idx_vectors_embedding;
|
|
7
|
+
|
|
8
|
+
-- Drop old match_vectors functions (different signatures exist from previous migrations)
|
|
9
|
+
DROP FUNCTION IF EXISTS match_vectors(vector(1536), FLOAT, INT, UUID);
|
|
10
|
+
DROP FUNCTION IF EXISTS match_vectors(vector(1536), TEXT, FLOAT, INT, UUID);
|
|
11
|
+
|
|
12
|
+
-- 2. Change to variable dimension vector (remove fixed dimension constraint)
|
|
13
|
+
-- This allows storing embeddings of any dimension
|
|
14
|
+
ALTER TABLE alchemy_vectors
|
|
15
|
+
ALTER COLUMN embedding TYPE vector;
|
|
16
|
+
|
|
17
|
+
-- 3. Create partial indexes per dimension (common models)
|
|
18
|
+
-- These indexes are used when queries explicitly cast to the matching dimension
|
|
19
|
+
-- NOTE: pgvector HNSW has 2000 dimension limit; larger dimensions use sequential scan
|
|
20
|
+
|
|
21
|
+
-- 384 dimensions (all-minilm)
|
|
22
|
+
CREATE INDEX idx_vectors_embed_384 ON alchemy_vectors
|
|
23
|
+
USING hnsw ((embedding::vector(384)) vector_cosine_ops)
|
|
24
|
+
WHERE array_length(embedding::real[], 1) = 384;
|
|
25
|
+
|
|
26
|
+
-- 768 dimensions (nomic-embed-text)
|
|
27
|
+
CREATE INDEX idx_vectors_embed_768 ON alchemy_vectors
|
|
28
|
+
USING hnsw ((embedding::vector(768)) vector_cosine_ops)
|
|
29
|
+
WHERE array_length(embedding::real[], 1) = 768;
|
|
30
|
+
|
|
31
|
+
-- 1024 dimensions (mxbai-embed-large, bge-large)
|
|
32
|
+
CREATE INDEX idx_vectors_embed_1024 ON alchemy_vectors
|
|
33
|
+
USING hnsw ((embedding::vector(1024)) vector_cosine_ops)
|
|
34
|
+
WHERE array_length(embedding::real[], 1) = 1024;
|
|
35
|
+
|
|
36
|
+
-- 1536 dimensions (text-embedding-3-small, text-embedding-ada-002)
|
|
37
|
+
CREATE INDEX idx_vectors_embed_1536 ON alchemy_vectors
|
|
38
|
+
USING hnsw ((embedding::vector(1536)) vector_cosine_ops)
|
|
39
|
+
WHERE array_length(embedding::real[], 1) = 1536;
|
|
40
|
+
|
|
41
|
+
-- NOTE: text-embedding-3-large (3072 dimensions) exceeds HNSW 2000-dim limit
|
|
42
|
+
-- Queries for 3072-dim vectors will use sequential scan (acceptable for typical datasets)
|
|
43
|
+
|
|
44
|
+
-- 4. Update match_vectors function to use explicit casting for partial index
|
|
45
|
+
-- Queries MUST cast to the target dimension to trigger the partial index
|
|
46
|
+
CREATE OR REPLACE FUNCTION match_vectors(
|
|
47
|
+
query_embedding vector,
|
|
48
|
+
target_model TEXT DEFAULT 'text-embedding-3-small',
|
|
49
|
+
target_dimensions INT DEFAULT 1536,
|
|
50
|
+
match_threshold FLOAT DEFAULT 0.5,
|
|
51
|
+
match_count INT DEFAULT 10,
|
|
52
|
+
target_user_id UUID DEFAULT auth.uid()
|
|
53
|
+
)
|
|
54
|
+
RETURNS TABLE (
|
|
55
|
+
id UUID,
|
|
56
|
+
signal_id UUID,
|
|
57
|
+
similarity FLOAT,
|
|
58
|
+
title TEXT,
|
|
59
|
+
summary TEXT,
|
|
60
|
+
url TEXT,
|
|
61
|
+
category TEXT
|
|
62
|
+
)
|
|
63
|
+
LANGUAGE plpgsql
|
|
64
|
+
AS $$
|
|
65
|
+
BEGIN
|
|
66
|
+
-- Use dynamic SQL to apply explicit dimension casting
|
|
67
|
+
-- This triggers the partial index for the specified dimension
|
|
68
|
+
RETURN QUERY EXECUTE format(
|
|
69
|
+
'SELECT
|
|
70
|
+
v.id,
|
|
71
|
+
v.signal_id,
|
|
72
|
+
(1 - (v.embedding::vector(%s) <=> $1::vector(%s)))::FLOAT AS similarity,
|
|
73
|
+
s.title,
|
|
74
|
+
s.summary,
|
|
75
|
+
s.url,
|
|
76
|
+
s.category
|
|
77
|
+
FROM alchemy_vectors v
|
|
78
|
+
JOIN signals s ON s.id = v.signal_id
|
|
79
|
+
WHERE v.user_id = $2
|
|
80
|
+
AND v.model = $3
|
|
81
|
+
AND array_length(v.embedding::real[], 1) = %s
|
|
82
|
+
AND 1 - (v.embedding::vector(%s) <=> $1::vector(%s)) > $4
|
|
83
|
+
ORDER BY v.embedding::vector(%s) <=> $1::vector(%s)
|
|
84
|
+
LIMIT $5',
|
|
85
|
+
target_dimensions, target_dimensions,
|
|
86
|
+
target_dimensions,
|
|
87
|
+
target_dimensions, target_dimensions,
|
|
88
|
+
target_dimensions, target_dimensions
|
|
89
|
+
)
|
|
90
|
+
USING query_embedding, target_user_id, target_model, match_threshold, match_count;
|
|
91
|
+
END;
|
|
92
|
+
$$;
|
|
93
|
+
|
|
94
|
+
-- 5. Add comment for documentation
|
|
95
|
+
COMMENT ON FUNCTION match_vectors(vector, TEXT, INT, FLOAT, INT, UUID) IS
|
|
96
|
+
'Semantic similarity search with variable dimension support.
|
|
97
|
+
Queries MUST specify target_dimensions to trigger partial indexes.
|
|
98
|
+
Filters by model name to ensure only same-model vectors are compared.
|
|
99
|
+
Note: HNSW indexes limited to 2000 dimensions; larger vectors use sequential scan.';
|