@realtimex/realtimex-alchemy 1.0.45 → 1.0.46

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 CHANGED
@@ -5,6 +5,13 @@ 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.46] - 2026-01-26
9
+
10
+ ### Fixed
11
+ - **Browser Mining**: Fixed Safari history extraction query and timestamp conversion (CFAbsoluteTime).
12
+ - **Browser Mining**: Updated Chrome/Edge timestamp logic to use BigInt for high-precision microsecond conversion, resolving potential checkpoint drift.
13
+ - **Sync Logic**: Switched history extraction order to Ascending (oldest first) to ensure checkpoints correctly advance from the start date.
14
+
8
15
  ## [1.0.45] - 2026-01-26
9
16
 
10
17
  ### Security
@@ -6,9 +6,9 @@ import { CONFIG } from '../config/index.js';
6
6
  import { ProcessingEventService } from './ProcessingEventService.js';
7
7
  import { UrlNormalizer } from '../utils/UrlNormalizer.js';
8
8
  export class MinerService {
9
- // Timestamp conversion constants
10
- static WEBKIT_EPOCH_OFFSET_MS = 11644473600000; // Milliseconds between 1601-01-01 (WebKit epoch) and 1970-01-01 (Unix epoch)
11
- static SAFARI_EPOCH_OFFSET_SEC = 978307200; // Seconds between 1970-01-01 (Unix epoch) and 2001-01-01 (Safari epoch)
9
+ // Timestamp conversion constants (using BigInt for precision)
10
+ static WEBKIT_EPOCH_OFFSET_MS = 11644473600000n; // Milliseconds between 1601-01-01 and 1970-01-01
11
+ static SAFARI_EPOCH_OFFSET_SEC = 978307200; // Seconds between 1970-01-01 and 2001-01-01
12
12
  static SANITY_CHECK_THRESHOLD = 3000000000000; // Timestamp threshold for Year ~2065, used to detect invalid/raw format timestamps
13
13
  processingEvents = ProcessingEventService.getInstance();
14
14
  debugMode = false;
@@ -155,20 +155,24 @@ export class MinerService {
155
155
  SELECT url, title, visit_count, last_visit_date as last_visit_time
156
156
  FROM moz_places
157
157
  WHERE last_visit_date > ? AND url LIKE 'http%'
158
- ORDER BY last_visit_date DESC
158
+ ORDER BY last_visit_date ASC
159
159
  LIMIT ?
160
160
  `;
161
161
  }
162
162
  else {
163
163
  // Chrome, Edge, Brave, Arc, Safari (usually)
164
164
  if (source.browser === 'safari') {
165
- // Safari uses Core Data timestamp (seconds since 2001-01-01)
166
- // Not fully implemented yet, but keeping placeholder
165
+ // Safari: Join visits and items
167
166
  query = `
168
- SELECT url, title, visit_count, last_visit_time
169
- FROM history_items
170
- WHERE last_visit_time > ?
171
- ORDER BY last_visit_time DESC
167
+ SELECT
168
+ i.url,
169
+ i.title,
170
+ i.visit_count,
171
+ v.visit_time as last_visit_time
172
+ FROM history_visits v
173
+ JOIN history_items i ON v.history_item = i.id
174
+ WHERE v.visit_time > ?
175
+ ORDER BY v.visit_time ASC
172
176
  LIMIT ?
173
177
  `;
174
178
  }
@@ -177,7 +181,7 @@ export class MinerService {
177
181
  SELECT url, title, visit_count, last_visit_time
178
182
  FROM urls
179
183
  WHERE last_visit_time > ?
180
- ORDER BY last_visit_time DESC
184
+ ORDER BY last_visit_time ASC
181
185
  LIMIT ?
182
186
  `;
183
187
  }
@@ -239,8 +243,10 @@ export class MinerService {
239
243
  if (skippedDuplicates > 0 || skippedNonContent > 0 || skippedBlacklist > 0) {
240
244
  this.debug(`URL Filtering: ${skippedDuplicates} duplicates, ${skippedNonContent} non-content, ${skippedBlacklist} blacklisted`);
241
245
  }
242
- if (entries.length > 0) {
243
- const newestTime = Math.max(...entries.map(e => e.last_visit_time));
246
+ if (rows.length > 0) {
247
+ // Since we order ASC, the last row is the latest time in this batch
248
+ const lastRow = rows[rows.length - 1];
249
+ const newestTime = this.toUnixMs(lastRow.last_visit_time, source.browser);
244
250
  await this.saveCheckpoint(source.path, newestTime, supabase, userId);
245
251
  // Also update last_sync_checkpoint in settings for global tracking
246
252
  if (userId && settings) {
@@ -261,29 +267,36 @@ export class MinerService {
261
267
  return Date.now();
262
268
  if (browser === 'firefox') {
263
269
  // Firefox: Microseconds -> Milliseconds
264
- return Math.floor(timestamp / 1000);
270
+ return Number(BigInt(timestamp) / 1000n);
265
271
  }
266
272
  else if (browser === 'safari') {
267
- // Safari: Seconds since 2001-01-01 -> Unix Ms
268
- return Math.floor((timestamp + MinerService.SAFARI_EPOCH_OFFSET_SEC) * 1000);
273
+ // Safari: Seconds (float) since 2001 -> Unix Ms
274
+ // Safari uses floats (CFAbsoluteTime), keep as Number
275
+ return Math.floor((Number(timestamp) + MinerService.SAFARI_EPOCH_OFFSET_SEC) * 1000);
269
276
  }
270
277
  else {
271
- // Chrome/Webkit: Microseconds since 1601-01-01 -> Unix Ms
272
- return Math.floor((timestamp / 1000) - MinerService.WEBKIT_EPOCH_OFFSET_MS);
278
+ // Chrome/Webkit: Microseconds since 1601 -> Unix Ms
279
+ const ts = BigInt(timestamp);
280
+ const microDiff = ts - (MinerService.WEBKIT_EPOCH_OFFSET_MS * 1000n);
281
+ return Number(microDiff / 1000n);
273
282
  }
274
283
  }
275
284
  fromUnixMs(unixMs, browser) {
276
285
  if (!unixMs)
277
- return 0; // Default to beginning of time
286
+ return 0;
278
287
  if (browser === 'firefox') {
279
- return unixMs * 1000;
288
+ // Firefox: Milliseconds -> Microseconds (BigInt)
289
+ return BigInt(unixMs) * 1000n;
280
290
  }
281
291
  else if (browser === 'safari') {
292
+ // Safari: Unix Ms -> Seconds since 2001 (Float)
282
293
  return (unixMs / 1000) - MinerService.SAFARI_EPOCH_OFFSET_SEC;
283
294
  }
284
295
  else {
285
- // Chrome/Webkit
286
- return (unixMs + MinerService.WEBKIT_EPOCH_OFFSET_MS) * 1000;
296
+ // Chrome/Webkit: Unix Ms -> Microseconds since 1601 (BigInt)
297
+ // (UnixMs + OffsetMs) * 1000 = Microseconds
298
+ const unixBig = BigInt(unixMs);
299
+ return (unixBig + MinerService.WEBKIT_EPOCH_OFFSET_MS) * 1000n;
287
300
  }
288
301
  }
289
302
  async getCheckpoint(browser, supabase) {
@@ -122,4 +122,4 @@ ${e.content}`:""}`,h=new Blob([d],{type:"text/markdown"}),p=URL.createObjectURL(
122
122
  `}),n}function P0(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function R0(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=R0(n,{file:r,...t});await e.run(o,r)}:function(n,r){return R0(n,{file:r,...e||t})}}function O0(e){if(e)throw e}var Vd,I0;function YI(){if(I0)return Vd;I0=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,_=arguments[0],k=1,S=arguments.length,E=!1;for(typeof _=="boolean"&&(E=_,_=arguments[1]||{},k=2),(_==null||typeof _!="object"&&typeof _!="function")&&(_={});k<S;++k)if(p=arguments[k],p!=null)for(m in p)y=d(_,m),x=d(p,m),_!==x&&(E&&x&&(a(x)||(w=o(x)))?(w?(w=!1,b=y&&o(y)?y:[]):b=y&&a(y)?y:{},l(_,{name:m,newValue:h(E,b,x)})):typeof x<"u"&&l(_,{name:m,newValue:x}));return _},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 Qn={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 Qb{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"?Qn.basename(this.path):void 0}set basename(t){Kd(t,"basename"),Wd(t,"basename"),this.path=Qn.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?Qn.dirname(this.path):void 0}set dirname(t){D0(this.basename,"dirname"),this.path=Qn.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?Qn.extname(this.path):void 0}set extname(t){if(Wd(t,"extname"),D0(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=Qn.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"?Qn.basename(this.path,this.extname):void 0}set stem(t){Kd(t,"stem"),Wd(t,"stem"),this.path=Qn.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 Wt(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(Qn.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+Qn.sep+"`")}function Kd(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function D0(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),M0("processSync","process",n),r;function o(a,l){n=!0,O0(a),r=l}}run(t,n,r){L0(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),M0("runSync","run",r),o;function a(l,d){O0(l),o=d,r=!0}}stringify(t,n){this.freeze();const r=Nl(n),o=this.compiler||this.Compiler;return Jd("stringify",o),L0(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 _=r[x][1];Fh(_)&&Fh(w)&&(w=qd(!0,_,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 L0(e){if(!Fh(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function M0(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function Nl(e){return p5(e)?e:new Qb(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",z0=[],U0={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||z0,n=e.remarkPlugins||z0,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...U0}:U0;return f5().use(eI).use(n).use(JI,r).use(t)}function b5(e){const t=e.children||"",n=new Qb;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 Xb(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],_=Fd[w];(_===null||_.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(lS,{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]=T.useState([]),[l,d]=T.useState(""),[h,p]=T.useState(!1),[m,y]=T.useState(!1),x=T.useRef(null),w=T.useRef(null);T.useEffect(()=>{e?b(e):(a([]),t([]))},[e,t]),T.useEffect(()=>{x.current&&x.current.scrollIntoView({behavior:"smooth"})},[o,m]);const b=async S=>{try{const{data:{session:E}}=await ne.auth.getSession();if(!E)return;const N=await Ke.get(`/api/chat/sessions/${S}/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)}},_=async S=>{if(S?.preventDefault(),!l.trim()||h)return;const E=l.trim();d(""),w.current&&(w.current.style.height="auto");const{data:{session:N}}=await ne.auth.getSession();if(!N)return;const R=N.user.id;p(!0),y(!0);try{let M=e;if(!M){const V=await Ke.post("/api/chat/sessions",{},{headers:{"x-user-id":R}});if(V.data.success)M=V.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(V=>[...V,O]);const q=await Ke.post("/api/chat/message",{sessionId:M,content:E},{headers:{"x-user-id":R}});if(q.data.success){const V=q.data.message;a(W=>[...W,V]),V.context_sources&&t(V.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=S=>{S.key==="Enter"&&!S.shiftKey&&(S.preventDefault(),_())};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(DS,{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((S,E)=>u.jsx("button",{onClick:()=>d(S),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:S},E))})]}):u.jsxs(u.Fragment,{children:[o.map((S,E)=>u.jsx(_5,{message:S},S.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:_,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:S=>{d(S.target.value),S.target.style.height="auto",S.target.style.height=S.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(OS,{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($0,{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(wn,{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]=T.useState(null),[n,r]=T.useState([]),[o,a]=T.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]=T.useState(""),[o,a]=T.useState(!0);T.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(Pt,{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($0,{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(wn,{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(Pt,{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(wn,{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(Et,{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 F0({engine:e,onClose:t,onSave:n,onDelete:r}){const{showToast:o}=yc(),[a,l]=T.useState({title:"",type:"newsletter",status:"active",config:{schedule:"",min_score:70,categories:[],custom_prompt:"",max_signals:10,execution_mode:"local"}}),[d,h]=T.useState(!1);T.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 ne.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 ne.auth.getUser();if(!w)throw new Error("Not authenticated");const{data:b,error:_}=await ne.from("engines").insert({...x,user_id:w.id}).select().single();if(_)throw _;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 ne.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(Pt,{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(wn,{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(Yt,{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(AS,{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(H0,{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(Et,{className:"w-4 h-4 animate-spin"}):u.jsx(Xg,{className:"w-4 h-4"}),a?"Running...":"Run Engine"]})]})};function P5(){const[e,t]=T.useState([]),[n,r]=T.useState(!0),[o,a]=T.useState(new Set),[l,d]=T.useState(null),[h,p]=T.useState(null),[m,y]=T.useState(!1),[x,w]=T.useState(null),[b,_]=T.useState(!1),[k,S]=T.useState(!1),{showToast:E}=yc();T.useEffect(()=>{(async()=>R())();const J=ne.channel("asset-updates").on("postgres_changes",{event:"UPDATE",schema:"public",table:"assets"},H=>{const re=H.new;d(ae=>ae?.id===re.id?re:ae),re.status==="completed"&&H.old.status!=="completed"&&E(`Asset "${re.title}" is ready!`,"success")}).subscribe();return()=>{ne.removeChannel(J)}},[]);const N=async()=>{if(!k)try{S(!0),E("Scanning for new categories and topics...","info");const{data:{session:ee}}=await ne.auth.getSession(),J=ks(),H={"Content-Type":"application/json","x-user-id":ee?.user?.id||""};if(ee?.access_token&&(H.Authorization=`Bearer ${ee.access_token}`),J&&(H["x-supabase-url"]=J.url,H["x-supabase-key"]=J.anonKey),!(await fetch("/api/engines/ensure-defaults",{method:"POST",headers:H})).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{S(!1)}},R=async()=>{try{r(!0);const{data:{user:ee}}=await ne.auth.getUser();if(!ee)return;const{data:J,error:H}=await ne.from("engines").select("*").eq("user_id",ee.id).order("created_at",{ascending:!1});if(H)throw H;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 ne.auth.getSession(),H=J?.access_token,re=ks(),ae={"Content-Type":"application/json","x-user-id":J?.user?.id||""};H&&(ae.Authorization=`Bearer ${H}`),re&&(ae["x-supabase-url"]=re.url,ae["x-supabase-key"]=re.anonKey);const K=await fetch(`/api/engines/${ee}/run`,{method:"POST",headers:ae});if(!K.ok){const C=await K.json();throw new Error(C.error||"Run failed")}const ue=await K.json();ue.status==="completed"?E(`Engine run complete! Created: ${ue.title}`,"success"):E(`Engine run started on Desktop. Tracking as: ${ue.id}`,"info"),d(ue),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 H=new Set(J);return H.delete(ee),H})}},O=async ee=>{try{y(!0);const{data:{session:J}}=await ne.auth.getSession(),H=ks(),re={"Content-Type":"application/json","x-user-id":J?.user?.id||""};J?.access_token&&(re.Authorization=`Bearer ${J.access_token}`),H&&(re["x-supabase-url"]=H.url,re["x-supabase-key"]=H.anonKey);const ae=await fetch(`/api/engines/${ee}/brief`,{headers:re});if(!ae.ok)throw new Error("Failed to fetch brief");const K=await ae.json();p(K)}catch{E("Failed to generate production brief","error")}finally{y(!1)}},q=async(ee,J)=>{const H=J==="active"?"paused":"active";t(re=>re.map(ae=>ae.id===ee?{...ae,status:H}:ae));try{const{error:re}=await ne.from("engines").update({status:H}).eq("id",ee);if(re)throw re;E(`Engine ${H==="active"?"resumed":"paused"}`,"success")}catch{t(ae=>ae.map(K=>K.id===ee?{...K,status:J}:K)),E("Failed to update status","error")}},V=()=>{_(!0)},W=ee=>{const J=e.find(H=>H.id===ee);J&&w(J)},he=ee=>{t(J=>J.find(re=>re.id===ee.id)?J.map(re=>re.id===ee.id?ee:re):[ee,...J])},se=ee=>{t(J=>J.filter(H=>H.id!==ee))},ie=()=>{w(null),_(!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(Et,{className:"w-4 h-4 animate-spin"}):u.jsx(Yt,{className:"w-4 h-4"}),"Generate Engines"]}),u.jsxs("button",{onClick:V,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(Et,{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(Yt,{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:V,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(Pt,{children:e.map(ee=>u.jsx(A5,{engine:ee,onRun:M,onEdit:W,onToggle:q,onViewBrief:O,isLoading:o.has(ee.id)},ee.id))})})})}),u.jsx(Pt,{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(H0,{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(wn,{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(Et,{className:"w-10 h-10 animate-spin text-white"})}),u.jsx(T5,{asset:l,onClose:()=>d(null)}),x&&u.jsx(F0,{engine:x,onClose:ie,onSave:he,onDelete:se}),b&&u.jsx(F0,{engine:null,onClose:ie,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]=T.useState([]),[n,r]=T.useState([]),[o,a]=T.useState("discovery"),[l,d]=T.useState(!1),[h,p]=T.useState(null),[m,y]=T.useState(!0),[x,w]=T.useState(!t0),[b,_]=T.useState(!0),[k,S]=T.useState(!1),[E,N]=T.useState(!1),[R,M]=T.useState(null),[O,q]=T.useState(!1),[V,W]=T.useState(!1),[he,se]=T.useState(!1),[ie,ee]=T.useState(!0),[J,H]=T.useState(()=>localStorage.getItem("theme")||"dark"),[re,ae]=T.useState(null),K=T.useRef(null);T.useMemo(()=>{const ce=n.length;let ye=0,pe=0,me=null;for(const Ge of n){ye+=Ge.score,Ge.score>pe&&(pe=Ge.score);const Kt=new Date(Ge.date);(!me||Kt>new Date(me.date))&&(me=Ge)}const Ae=ce?Math.round(ye/ce):0,$e=me?new Date(me.date):null;return{total:ce,average:Ae,top:pe,latestTimestamp:$e,latestTitle:me?.title??me?.category??null}},[n]),T.useEffect(()=>{(async()=>{if(!t0){w(!0),y(!1);return}try{const{data:pe,error:me}=await ne.from("init_state").select("is_initialized").single();me?(console.warn("[App] Init check error (might be fresh DB):",me),me.code==="42P01"&&_(!1)):_(pe.is_initialized>0);const{data:{session:Ae}}=await ne.auth.getSession();p(Ae?.user??null)}catch(pe){console.error("[App] Status check failed:",pe)}finally{y(!1)}})();const{data:{subscription:ye}}=ne.auth.onAuthStateChange((pe,me)=>{p(me?.user??null)});return()=>ye.unsubscribe()},[]),T.useEffect(()=>{document.documentElement.setAttribute("data-theme",J),localStorage.setItem("theme",J)},[J]);const[ue,C]=T.useState({});T.useEffect(()=>{(async()=>{if(!h)return;const{data:ye}=await ne.from("alchemy_settings").select("sync_start_date, last_sync_checkpoint").eq("user_id",h.id).maybeSingle();ye&&C(ye)})()},[h,O]),T.useEffect(()=>{if(!h)return;(async()=>{const{data:pe}=await ne.from("alchemy_settings").select("sound_enabled").eq("user_id",h.id).maybeSingle();if(pe){const me=pe.sound_enabled??!0;ee(me),So.setEnabled(me)}})();const ye=ne.channel("processing_events").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events",filter:`user_id=eq.${h.id}`},pe=>{const me=pe.new;me.agent_state==="Mining"&&!V&&(W(!0),se(!0),ie&&So.syncStart()),me.agent_state==="Signal"&&ie&&So.signalFound(),me.agent_state==="Completed"&&(W(!1),ie&&(me.metadata?.errors>0?So.error():So.syncComplete()),setTimeout(()=>{se(!1)},5e3),D())}).subscribe();return()=>{ne.removeChannel(ye)}},[h,V,ie]),T.useEffect(()=>{const ce=new EventSource("/events");return ce.onmessage=ye=>{const pe=JSON.parse(ye.data);pe.type==="history"?t(me=>[...pe.data,...me].slice(0,100)):t(me=>[pe,...me].slice(0,100))},D(),()=>ce.close()},[h]),T.useEffect(()=>{K.current&&K.current.scrollIntoView({behavior:"smooth"})},[e]);const D=async()=>{try{if(h){const{data:ye,error:pe}=await ne.from("signals").select("*").order("created_at",{ascending:!1});if(!pe&&ye){r(ye.map(me=>({id:me.id,title:me.title,score:me.score,summary:me.summary,date:me.created_at,category:me.category,entities:me.entities})));return}}const ce=await Ke.get("/api/signals");r(ce.data)}catch(ce){console.error("Failed to fetch signals",ce)}},G=async()=>{d(!0);try{await Ke.post("/api/mine"),D()}catch(ce){console.error("Mining failed:",ce)}finally{d(!1)}},A=(ce,ye)=>{ce==="logs"?(ae(ye),a("logs")):a(ce)};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(db,{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(Yt,{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(_S,{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(Yt,{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:()=>H(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(MS,{size:18}):u.jsx(TS,{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:()=>S(!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(mS,{size:20}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"min-w-[20px] flex justify-center",children:u.jsx(pS,{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.45"]})]}),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:()=>q(!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:ue.sync_start_date?`From: ${new Date(ue.sync_start_date).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:ue.last_sync_checkpoint?`Checkpoint: ${new Date(ue.last_sync_checkpoint).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:"All time"})]})]}),u.jsxs("button",{onClick:G,disabled:V,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:V?"animate-spin":""}),V?"Syncing...":"Sync History"]})]})]}),u.jsx(rR,{onOpenUrl:ce=>window.open(ce,"_blank","noopener,noreferrer"),onCopyText:ce=>{navigator.clipboard.writeText(ce)}})]}),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:re}),u.jsx(DP,{isExpanded:he,onToggle:()=>se(!he),onNavigate:A,liftUp:o==="chat"})]}),u.jsx(VP,{signal:R,onClose:()=>M(null)}),u.jsx(qP,{isOpen:O,onClose:()=>q(!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(){Ke.interceptors.request.use(async e=>{try{const{data:{session:t}}=await ne.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();nS.createRoot(document.getElementById("root")).render(u.jsx(Mo.StrictMode,{children:u.jsx(O5,{})}));
125
+ Failed to load changelog.`)}finally{a(!1)}};return u.jsx(Pt,{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($0,{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(wn,{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(Pt,{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(wn,{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(Et,{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 F0({engine:e,onClose:t,onSave:n,onDelete:r}){const{showToast:o}=yc(),[a,l]=T.useState({title:"",type:"newsletter",status:"active",config:{schedule:"",min_score:70,categories:[],custom_prompt:"",max_signals:10,execution_mode:"local"}}),[d,h]=T.useState(!1);T.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 ne.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 ne.auth.getUser();if(!w)throw new Error("Not authenticated");const{data:b,error:_}=await ne.from("engines").insert({...x,user_id:w.id}).select().single();if(_)throw _;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 ne.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(Pt,{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(wn,{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(Yt,{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(AS,{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(H0,{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(Et,{className:"w-4 h-4 animate-spin"}):u.jsx(Xg,{className:"w-4 h-4"}),a?"Running...":"Run Engine"]})]})};function P5(){const[e,t]=T.useState([]),[n,r]=T.useState(!0),[o,a]=T.useState(new Set),[l,d]=T.useState(null),[h,p]=T.useState(null),[m,y]=T.useState(!1),[x,w]=T.useState(null),[b,_]=T.useState(!1),[k,S]=T.useState(!1),{showToast:E}=yc();T.useEffect(()=>{(async()=>R())();const J=ne.channel("asset-updates").on("postgres_changes",{event:"UPDATE",schema:"public",table:"assets"},H=>{const re=H.new;d(ae=>ae?.id===re.id?re:ae),re.status==="completed"&&H.old.status!=="completed"&&E(`Asset "${re.title}" is ready!`,"success")}).subscribe();return()=>{ne.removeChannel(J)}},[]);const N=async()=>{if(!k)try{S(!0),E("Scanning for new categories and topics...","info");const{data:{session:ee}}=await ne.auth.getSession(),J=ks(),H={"Content-Type":"application/json","x-user-id":ee?.user?.id||""};if(ee?.access_token&&(H.Authorization=`Bearer ${ee.access_token}`),J&&(H["x-supabase-url"]=J.url,H["x-supabase-key"]=J.anonKey),!(await fetch("/api/engines/ensure-defaults",{method:"POST",headers:H})).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{S(!1)}},R=async()=>{try{r(!0);const{data:{user:ee}}=await ne.auth.getUser();if(!ee)return;const{data:J,error:H}=await ne.from("engines").select("*").eq("user_id",ee.id).order("created_at",{ascending:!1});if(H)throw H;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 ne.auth.getSession(),H=J?.access_token,re=ks(),ae={"Content-Type":"application/json","x-user-id":J?.user?.id||""};H&&(ae.Authorization=`Bearer ${H}`),re&&(ae["x-supabase-url"]=re.url,ae["x-supabase-key"]=re.anonKey);const K=await fetch(`/api/engines/${ee}/run`,{method:"POST",headers:ae});if(!K.ok){const C=await K.json();throw new Error(C.error||"Run failed")}const ue=await K.json();ue.status==="completed"?E(`Engine run complete! Created: ${ue.title}`,"success"):E(`Engine run started on Desktop. Tracking as: ${ue.id}`,"info"),d(ue),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 H=new Set(J);return H.delete(ee),H})}},O=async ee=>{try{y(!0);const{data:{session:J}}=await ne.auth.getSession(),H=ks(),re={"Content-Type":"application/json","x-user-id":J?.user?.id||""};J?.access_token&&(re.Authorization=`Bearer ${J.access_token}`),H&&(re["x-supabase-url"]=H.url,re["x-supabase-key"]=H.anonKey);const ae=await fetch(`/api/engines/${ee}/brief`,{headers:re});if(!ae.ok)throw new Error("Failed to fetch brief");const K=await ae.json();p(K)}catch{E("Failed to generate production brief","error")}finally{y(!1)}},q=async(ee,J)=>{const H=J==="active"?"paused":"active";t(re=>re.map(ae=>ae.id===ee?{...ae,status:H}:ae));try{const{error:re}=await ne.from("engines").update({status:H}).eq("id",ee);if(re)throw re;E(`Engine ${H==="active"?"resumed":"paused"}`,"success")}catch{t(ae=>ae.map(K=>K.id===ee?{...K,status:J}:K)),E("Failed to update status","error")}},V=()=>{_(!0)},W=ee=>{const J=e.find(H=>H.id===ee);J&&w(J)},he=ee=>{t(J=>J.find(re=>re.id===ee.id)?J.map(re=>re.id===ee.id?ee:re):[ee,...J])},se=ee=>{t(J=>J.filter(H=>H.id!==ee))},ie=()=>{w(null),_(!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(Et,{className:"w-4 h-4 animate-spin"}):u.jsx(Yt,{className:"w-4 h-4"}),"Generate Engines"]}),u.jsxs("button",{onClick:V,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(Et,{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(Yt,{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:V,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(Pt,{children:e.map(ee=>u.jsx(A5,{engine:ee,onRun:M,onEdit:W,onToggle:q,onViewBrief:O,isLoading:o.has(ee.id)},ee.id))})})})}),u.jsx(Pt,{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(H0,{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(wn,{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(Et,{className:"w-10 h-10 animate-spin text-white"})}),u.jsx(T5,{asset:l,onClose:()=>d(null)}),x&&u.jsx(F0,{engine:x,onClose:ie,onSave:he,onDelete:se}),b&&u.jsx(F0,{engine:null,onClose:ie,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]=T.useState([]),[n,r]=T.useState([]),[o,a]=T.useState("discovery"),[l,d]=T.useState(!1),[h,p]=T.useState(null),[m,y]=T.useState(!0),[x,w]=T.useState(!t0),[b,_]=T.useState(!0),[k,S]=T.useState(!1),[E,N]=T.useState(!1),[R,M]=T.useState(null),[O,q]=T.useState(!1),[V,W]=T.useState(!1),[he,se]=T.useState(!1),[ie,ee]=T.useState(!0),[J,H]=T.useState(()=>localStorage.getItem("theme")||"dark"),[re,ae]=T.useState(null),K=T.useRef(null);T.useMemo(()=>{const ce=n.length;let ye=0,pe=0,me=null;for(const Ge of n){ye+=Ge.score,Ge.score>pe&&(pe=Ge.score);const Kt=new Date(Ge.date);(!me||Kt>new Date(me.date))&&(me=Ge)}const Ae=ce?Math.round(ye/ce):0,$e=me?new Date(me.date):null;return{total:ce,average:Ae,top:pe,latestTimestamp:$e,latestTitle:me?.title??me?.category??null}},[n]),T.useEffect(()=>{(async()=>{if(!t0){w(!0),y(!1);return}try{const{data:pe,error:me}=await ne.from("init_state").select("is_initialized").single();me?(console.warn("[App] Init check error (might be fresh DB):",me),me.code==="42P01"&&_(!1)):_(pe.is_initialized>0);const{data:{session:Ae}}=await ne.auth.getSession();p(Ae?.user??null)}catch(pe){console.error("[App] Status check failed:",pe)}finally{y(!1)}})();const{data:{subscription:ye}}=ne.auth.onAuthStateChange((pe,me)=>{p(me?.user??null)});return()=>ye.unsubscribe()},[]),T.useEffect(()=>{document.documentElement.setAttribute("data-theme",J),localStorage.setItem("theme",J)},[J]);const[ue,C]=T.useState({});T.useEffect(()=>{(async()=>{if(!h)return;const{data:ye}=await ne.from("alchemy_settings").select("sync_start_date, last_sync_checkpoint").eq("user_id",h.id).maybeSingle();ye&&C(ye)})()},[h,O]),T.useEffect(()=>{if(!h)return;(async()=>{const{data:pe}=await ne.from("alchemy_settings").select("sound_enabled").eq("user_id",h.id).maybeSingle();if(pe){const me=pe.sound_enabled??!0;ee(me),So.setEnabled(me)}})();const ye=ne.channel("processing_events").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events",filter:`user_id=eq.${h.id}`},pe=>{const me=pe.new;me.agent_state==="Mining"&&!V&&(W(!0),se(!0),ie&&So.syncStart()),me.agent_state==="Signal"&&ie&&So.signalFound(),me.agent_state==="Completed"&&(W(!1),ie&&(me.metadata?.errors>0?So.error():So.syncComplete()),setTimeout(()=>{se(!1)},5e3),D())}).subscribe();return()=>{ne.removeChannel(ye)}},[h,V,ie]),T.useEffect(()=>{const ce=new EventSource("/events");return ce.onmessage=ye=>{const pe=JSON.parse(ye.data);pe.type==="history"?t(me=>[...pe.data,...me].slice(0,100)):t(me=>[pe,...me].slice(0,100))},D(),()=>ce.close()},[h]),T.useEffect(()=>{K.current&&K.current.scrollIntoView({behavior:"smooth"})},[e]);const D=async()=>{try{if(h){const{data:ye,error:pe}=await ne.from("signals").select("*").order("created_at",{ascending:!1});if(!pe&&ye){r(ye.map(me=>({id:me.id,title:me.title,score:me.score,summary:me.summary,date:me.created_at,category:me.category,entities:me.entities})));return}}const ce=await Ke.get("/api/signals");r(ce.data)}catch(ce){console.error("Failed to fetch signals",ce)}},G=async()=>{d(!0);try{await Ke.post("/api/mine"),D()}catch(ce){console.error("Mining failed:",ce)}finally{d(!1)}},A=(ce,ye)=>{ce==="logs"?(ae(ye),a("logs")):a(ce)};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(db,{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(Yt,{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(_S,{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(Yt,{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:()=>H(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(MS,{size:18}):u.jsx(TS,{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:()=>S(!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(mS,{size:20}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"min-w-[20px] flex justify-center",children:u.jsx(pS,{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.46"]})]}),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:()=>q(!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:ue.sync_start_date?`From: ${new Date(ue.sync_start_date).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:ue.last_sync_checkpoint?`Checkpoint: ${new Date(ue.last_sync_checkpoint).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:"All time"})]})]}),u.jsxs("button",{onClick:G,disabled:V,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:V?"animate-spin":""}),V?"Syncing...":"Sync History"]})]})]}),u.jsx(rR,{onOpenUrl:ce=>window.open(ce,"_blank","noopener,noreferrer"),onCopyText:ce=>{navigator.clipboard.writeText(ce)}})]}),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:re}),u.jsx(DP,{isExpanded:he,onToggle:()=>se(!he),onNavigate:A,liftUp:o==="chat"})]}),u.jsx(VP,{signal:R,onClose:()=>M(null)}),u.jsx(qP,{isOpen:O,onClose:()=>q(!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(){Ke.interceptors.request.use(async e=>{try{const{data:{session:t}}=await ne.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();nS.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-D2SNunU5.js"></script>
12
+ <script type="module" crossorigin src="/assets/index-DgmsaloF.js"></script>
13
13
  <link rel="stylesheet" crossorigin href="/assets/index-BcolxI8u.css">
14
14
  </head>
15
15
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@realtimex/realtimex-alchemy",
3
- "version": "1.0.45",
3
+ "version": "1.0.46",
4
4
  "description": "Passive Intelligence engine for RealTimeX Alchemy. Transmute your reading time into high-density insights.",
5
5
  "type": "module",
6
6
  "main": "dist/api/index.js",