10 Commits

Author SHA1 Message Date
github-actions[bot]
c7c843eb5a This build was committed by a bot. 2026-09-01 00:25:13 +00:00
1acd908afc Feat: Implement Global Sune Sync logic
Co-authored-by: gemini-3-flash-preview <noreply@google.com>
2026-08-31 17:24:57 -07:00
0b3f97246b Feat: Add Sune repo sync UI to left sidebar
Co-authored-by: gemini-3-flash-preview <noreply@google.com>
2026-08-31 17:24:51 -07:00
c9663c037b Feat: Add Sune sync DOM elements
Co-authored-by: gemini-3-flash-preview <noreply@google.com>
2026-08-31 17:24:48 -07:00
github-actions[bot]
553fe1a835 This build was committed by a bot. 2026-08-31 22:52:30 +00:00
c727f40d91 Fix: Non-greedy sune ID matching in gcStorage
Co-authored-by: gemini-3.7-flash <noreply@google.com>
2026-08-31 15:52:13 -07:00
github-actions[bot]
2faea0aa01 This build was committed by a bot. 2026-08-31 21:42:05 +00:00
c8d9d66e7f Feat: Add Sune storage API and storage GC
Co-authored-by: gemini-3.7-flash <noreply@google.com>
2026-08-31 14:41:52 -07:00
github-actions[bot]
e7ffe2d606 This build was committed by a bot. 2026-08-31 21:09:57 +00:00
a023ad0423 Refactor: Remove storage key from sune
Co-authored-by: gemini-3.7-flash <noreply@google.com>
2026-08-31 14:09:41 -07:00
6 changed files with 174 additions and 19 deletions

View File

@@ -324,7 +324,9 @@ var el = window.el = Object.fromEntries([
"threadRepoInput",
"threadBackBtn",
"threadFolderBtn",
"threadSyncBtn"
"threadSyncBtn",
"suneRepoInput",
"suneSyncBtn"
].map((id) => [id, document.getElementById(id)]));
//#endregion
//#region src/utils.js
@@ -875,6 +877,77 @@ var __vitePreload = function preload(baseModule, deps, importerUrl) {
var DEFAULT_MODEL = "openrouter/free";
var icons = () => window.lucide && lucide.createIcons();
var haptic = () => /android/i.test(navigator.userAgent) && navigator.vibrate?.(1);
var SYSTEM_KEYS = new Set([
"sunes_v1",
"active_sune_id",
"thread_repo_url",
"sune_repo_url",
"user_name",
"user_avatar",
"provider",
"openrouter_api_key",
"openai_api_key",
"google_api_key",
"claude_api_key",
"cloudflare_api_key",
"master_prompt",
"title_model",
"gh_token",
"custom_key_1"
]);
var gcStorage = () => {
try {
const alive = new Set(sunes.map((s) => s.id));
Object.keys(localStorage).forEach((k) => {
if (SYSTEM_KEYS.has(k) || /^(t_|rem_t_|rem_index_|localforage|threads_)/.test(k)) return;
const m = k.match(/^sune_([^_]+)_/);
if (m && alive.has(m[1])) return;
localStorage.removeItem(k);
});
} catch {}
};
var cleanSuneStorage = (id) => {
if (!id) return;
const p = `sune_${id}_`;
Object.keys(localStorage).forEach((k) => {
if (k.startsWith(p)) localStorage.removeItem(k);
});
};
var suneStorage = {
get(k, def = null) {
const id = SUNE.id;
if (!id) return def;
const v = localStorage.getItem(`sune_${id}_${k}`);
if (v === null) return def;
try {
return JSON.parse(v);
} catch {
return v;
}
},
set(k, v) {
const id = SUNE.id;
if (id) localStorage.setItem(`sune_${id}_${k}`, JSON.stringify(v));
},
remove(k) {
const id = SUNE.id;
if (id) localStorage.removeItem(`sune_${id}_${k}`);
},
clear() {
const id = SUNE.id;
if (id) cleanSuneStorage(id);
},
keys() {
const id = SUNE.id;
if (!id) return [];
const p = `sune_${id}_`;
return Object.keys(localStorage).filter((k) => k.startsWith(p)).map((k) => k.slice(p.length));
},
key(k) {
const id = SUNE.id;
return id ? `sune_${id}_${k}` : k;
}
};
var su = {
key: "sunes_v1",
activeKey: "active_sune_id",
@@ -923,11 +996,11 @@ var makeSune = (p = {}) => ({
avatar: p.avatar || "",
url: p.url || "",
updatedAt: p.updatedAt || Date.now(),
settings: Object.assign({}, defaultSettings, p.settings || {}),
storage: p.storage || {}
settings: Object.assign({}, defaultSettings, p.settings || {})
});
var sunes = (su.load() || []).map(makeSune);
var SUNE = window.SUNE = new Proxy({
storage: suneStorage,
get list() {
return sunes;
},
@@ -949,6 +1022,8 @@ var SUNE = window.SUNE = new Proxy({
const curId = this.id;
sunes = sunes.filter((s) => s.id !== id);
su.save(sunes);
cleanSuneStorage(id);
gcStorage();
if (sunes.length === 0) {
const def = this.create({ name: "Default" });
this.setActive(def.id);
@@ -1078,7 +1153,7 @@ var SUNE = window.SUNE = new Proxy({
if (!a) return false;
const i = sunes.findIndex((s) => s.id === a.id);
if (i < 0) return false;
const isTopLevel = /^(name|avatar|url|pinned|storage)$/.test(p), target = isTopLevel ? sunes[i] : sunes[i].settings;
const isTopLevel = /^(name|avatar|url|pinned)$/.test(p), target = isTopLevel ? sunes[i] : sunes[i].settings;
let value = v;
if (!isTopLevel) {
if (p === "system_prompt") value = v || "";
@@ -1962,8 +2037,10 @@ USER.logMany = async (msgs) => {
await THREAD.persist();
};
async function init() {
const u = localStorage.getItem("thread_repo_url") || "";
gcStorage();
const u = localStorage.getItem("thread_repo_url") || "", suR = localStorage.getItem("sune_repo_url") || "";
el.threadRepoInput.value = u;
el.suneRepoInput.value = suR;
el.threadFolderBtn.classList.toggle("hidden", !u.startsWith("gh://"));
el.threadBackBtn.classList.toggle("hidden", !u.startsWith("gh://") || u.split("/").length <= 3);
await THREAD.load();
@@ -2140,6 +2217,53 @@ $(el.threadSyncBtn).on("click", async () => {
alert("Sync failed: " + e.message);
}
});
$(el.suneRepoInput).on("change", () => {
localStorage.setItem("sune_repo_url", el.suneRepoInput.value.trim());
});
$(el.suneSyncBtn).on("click", async () => {
const u = el.suneRepoInput.value.trim();
if (!u.startsWith("gh://")) return;
const mode = confirm("Sync Sunes:\nOK = Upload (Push)\nCancel = Download (Pull)"), info = parseGhUrl(u);
try {
if (mode) {
const data = {
version: 1,
sunes: SUNE.list,
activeId: SUNE.id,
storage: {}
};
SUNE.list.forEach((s) => {
const p = `sune_${s.id}_`;
Object.keys(localStorage).forEach((k) => {
if (k.startsWith(p)) data.storage[k] = localStorage.getItem(k);
});
});
const x = await ghApi(`${info.apiPath}/sunes.json?ref=${info.branch}`);
await ghApi(`${info.apiPath}/sunes.json`, "PUT", {
message: "Sync Sunes",
content: utob(JSON.stringify(data, null, 2)),
branch: info.branch,
sha: x?.sha
});
alert("Sunes pushed.");
} else {
const text = await ghGetFileContent(info, "sunes.json");
if (!text) throw new Error("sunes.json not found");
const data = JSON.parse(text);
if (data.sunes) {
sunes = data.sunes.map(makeSune);
SUNE.save();
if (data.activeId) SUNE.setActive(data.activeId);
}
if (data.storage) Object.entries(data.storage).forEach(([k, v]) => localStorage.setItem(k, v));
renderSidebar();
await reflectActiveSune();
alert("Sunes pulled.");
}
} catch (e) {
alert("Sync failed: " + e.message);
}
});
init();
var accountTabs = {
General: ["accountTabGeneral", "accountPanelGeneral"],
@@ -2160,6 +2284,7 @@ function openAccountSettings() {
el.set_api_key_claude.value = USER.apiKeyClaude || "";
el.set_api_key_cf.value = USER.apiKeyCloudflare || "";
el.set_api_key_custom1.value = USER.customKey1 || "";
el.set_api_key_custom1.value = USER.customKey1 || "";
el.set_master_prompt.value = USER.masterPrompt || "";
el.set_title_model.value = USER.titleModel;
el.set_gh_token.value = USER.githubToken || "";
@@ -2252,8 +2377,8 @@ el.importAccountSettingsInput.onchange = async (e) => {
apiKeyOpenRouter: "apiKeyOR",
apiKeyOpenAI: "apiKeyOAI",
apiKeyGoogle: "apiKeyG",
apiKeyClaude: "apiKeyC",
apiKeyCloudflare: "apiKeyCF",
apiKeyClaude: "apiKeyClaude",
apiKeyCloudflare: "apiKeyCloudflare",
customKey1: "customKey1",
masterPrompt: "masterPrompt",
titleModel: "titleModel",
@@ -2481,6 +2606,9 @@ Object.assign(window, {
ghApi,
parseGhUrl,
ghGetFileContent,
pullThreads
pullThreads,
suneStorage,
gcStorage,
cleanSuneStorage
});
//#endregion

10
dist/index.html vendored
View File

@@ -13,7 +13,7 @@
<script defer src="//unpkg.com/alpinejs"></script>
<script type="module" crossorigin src="/assets/index-CAlY_Fnl.js"></script>
<script type="module" crossorigin src="/assets/index-BgxroUTU.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-DUC1RW1F.css">
<link rel="manifest" href="/manifest.webmanifest"><script id="vite-plugin-pwa:register-sw" src="/registerSW.js"></script></head>
<body class="bg-white text-gray-900 selection:bg-black/10" x-data @click.window="if($event.target.closest('button')) haptic(); if(!document.getElementById('threadPopover').contains($event.target)&&!$event.target.closest('[data-thread-menu]')) hideThreadPopover(); if(!document.getElementById('sunePopover').contains($event.target)&&!$event.target.closest('[data-sune-menu]')) hideSunePopover(); if(!document.getElementById('userMenu').contains($event.target)&&!document.getElementById('userMenuBtn').contains($event.target)) document.getElementById('userMenu').classList.add('hidden')">
@@ -44,7 +44,13 @@
</div>
<div id="sidebarOverlayLeft" class="fixed inset-0 z-40 bg-black/20 hidden" @click="document.getElementById('sidebarLeft').classList.add('-translate-x-full');$el.classList.add('hidden');document.getElementById('sidebarRight').classList.add('translate-x-full');document.getElementById('sidebarOverlayRight').classList.add('hidden');hideThreadPopover();hideSunePopover()"></div>
<aside id="sidebarLeft" class="fixed inset-y-0 left-0 z-50 w-72 max-w-[85vw] bg-white border-r border-gray-200 shadow-xl transform -translate-x-full transition-transform duration-200 ease-out flex flex-col">
<div class="p-3 border-b flex items-center gap-2"><button id="newSuneBtn" class="px-3 py-2 rounded-xl bg-black text-white text-sm hover:bg-black/90">New sune</button><span class="text-xs text-gray-500">Click name to equip</span></div>
<div class="p-2 border-b flex flex-col gap-2">
<input id="suneRepoInput" type="text" placeholder="gh://owner/sunes" class="w-full h-9 rounded-lg border-0 bg-gray-100 px-3 text-xs font-mono focus:ring-2 focus:ring-black focus:bg-white"/>
<div class="flex items-center justify-between gap-2">
<button id="newSuneBtn" class="px-3 py-1.5 rounded-lg bg-black text-white text-[10px] font-bold uppercase tracking-wider hover:bg-black/90 transition">New Sune</button>
<button id="suneSyncBtn" class="px-3 py-1.5 rounded-lg bg-gray-100 text-gray-900 text-[10px] font-bold uppercase tracking-wider hover:bg-gray-200 transition flex items-center gap-1"><i data-lucide="refresh-cw" class="h-3 w-3"></i><span>Sync</span></button>
</div>
</div>
<div id="suneList" class="flex-1 overflow-y-auto divide-y"></div>
<div class="p-3 border-t relative flex items-center gap-2">
<button id="userMenuBtn" class="flex-1 flex items-center justify-between px-3 py-2 rounded-xl bg-gray-100 hover:bg-gray-200 active:scale-[.99] transition" @click.stop="document.getElementById('userMenu').classList.toggle('hidden')"><span class="flex items-center gap-2"><span id="userMenuAvatar" class="h-6 w-6 rounded-full bg-gray-900 text-white flex items-center justify-center overflow-hidden shrink-0">👤</span><span class="text-sm">User</span></span><i data-lucide="chevron-down" class="h-4 w-4"></i></button>

2
dist/sw.js vendored
View File

@@ -1 +1 @@
if(!self.define){let e,s={};const i=(i,n)=>(i=new URL(i+".js",n).href,s[i]||new Promise(s=>{if("document"in self){const e=document.createElement("script");e.src=i,e.onload=s,document.head.appendChild(e)}else e=i,importScripts(i),s()}).then(()=>{let e=s[i];if(!e)throw new Error(`Module ${i} didnt register its module`);return e}));self.define=(n,r)=>{const t=e||("document"in self?document.currentScript.src:"")||location.href;if(s[t])return;let o={};const l=e=>i(e,t),d={module:{uri:t},exports:o,require:l};s[t]=Promise.all(n.map(e=>d[e]||l(e))).then(e=>(r(...e),o))}}define(["./workbox-9c191d2f"],function(e){"use strict";self.skipWaiting(),e.clientsClaim(),e.precacheAndRoute([{url:"registerSW.js",revision:"1872c500de691dce40960bb85481de07"},{url:"index.html",revision:"a803b47dd5e78160a07e19aeed859e51"},{url:"assets/index-DUC1RW1F.css",revision:null},{url:"assets/index-CAlY_Fnl.js",revision:null},{url:"manifest.webmanifest",revision:"7a6c5c6ab9cb5d3605d21df44c6b17a2"}],{}),e.cleanupOutdatedCaches(),e.registerRoute(new e.NavigationRoute(e.createHandlerBoundToURL("index.html")))});
if(!self.define){let e,s={};const i=(i,n)=>(i=new URL(i+".js",n).href,s[i]||new Promise(s=>{if("document"in self){const e=document.createElement("script");e.src=i,e.onload=s,document.head.appendChild(e)}else e=i,importScripts(i),s()}).then(()=>{let e=s[i];if(!e)throw new Error(`Module ${i} didnt register its module`);return e}));self.define=(n,r)=>{const t=e||("document"in self?document.currentScript.src:"")||location.href;if(s[t])return;let o={};const d=e=>i(e,t),l={module:{uri:t},exports:o,require:d};s[t]=Promise.all(n.map(e=>l[e]||d(e))).then(e=>(r(...e),o))}}define(["./workbox-9c191d2f"],function(e){"use strict";self.skipWaiting(),e.clientsClaim(),e.precacheAndRoute([{url:"registerSW.js",revision:"1872c500de691dce40960bb85481de07"},{url:"index.html",revision:"4dfde2d75701f65ce92ab40f913497db"},{url:"assets/index-DUC1RW1F.css",revision:null},{url:"assets/index-BgxroUTU.js",revision:null},{url:"manifest.webmanifest",revision:"7a6c5c6ab9cb5d3605d21df44c6b17a2"}],{}),e.cleanupOutdatedCaches(),e.registerRoute(new e.NavigationRoute(e.createHandlerBoundToURL("index.html")))});

View File

@@ -19,6 +19,6 @@ export const el = window.el = Object.fromEntries(
'importAccountSettings','exportAccountSettings',
'importAccountSettingsInput','accountTabUser','accountPanelUser','set_user_name',
'userAvatarPreview','setUserAvatarBtn','userAvatarInput','threadRepoInput','threadBackBtn',
'threadFolderBtn','threadSyncBtn'
'threadFolderBtn','threadSyncBtn','suneRepoInput','suneSyncBtn'
].map(id => [id, document.getElementById(id)])
);

View File

@@ -17,11 +17,24 @@ const DEFAULT_MODEL='openrouter/free'
const icons=()=>window.lucide&&lucide.createIcons()
const haptic=()=>/android/i.test(navigator.userAgent)&&navigator.vibrate?.(1)
const SYSTEM_KEYS=new Set(['sunes_v1','active_sune_id','thread_repo_url','sune_repo_url','user_name','user_avatar','provider','openrouter_api_key','openai_api_key','google_api_key','claude_api_key','cloudflare_api_key','master_prompt','title_model','gh_token','custom_key_1'])
const gcStorage=()=>{try{const alive=new Set(sunes.map(s=>s.id));Object.keys(localStorage).forEach(k=>{if(SYSTEM_KEYS.has(k)||/^(t_|rem_t_|rem_index_|localforage|threads_)/.test(k))return;const m=k.match(/^sune_([^_]+)_/);if(m&&alive.has(m[1]))return;localStorage.removeItem(k)})}catch{}}
const cleanSuneStorage=id=>{if(!id)return;const p=`sune_${id}_`;Object.keys(localStorage).forEach(k=>{if(k.startsWith(p))localStorage.removeItem(k)})}
const suneStorage={
get(k,def=null){const id=SUNE.id;if(!id)return def;const v=localStorage.getItem(`sune_${id}_${k}`);if(v===null)return def;try{return JSON.parse(v)}catch{return v}},
set(k,v){const id=SUNE.id;if(id)localStorage.setItem(`sune_${id}_${k}`,JSON.stringify(v))},
remove(k){const id=SUNE.id;if(id)localStorage.removeItem(`sune_${id}_${k}`)},
clear(){const id=SUNE.id;if(id)cleanSuneStorage(id)},
keys(){const id=SUNE.id;if(!id)return[];const p=`sune_${id}_`;return Object.keys(localStorage).filter(k=>k.startsWith(p)).map(k=>k.slice(p.length))},
key(k){const id=SUNE.id;return id?`sune_${id}_${k}`:k}
}
const su={key:'sunes_v1',activeKey:'active_sune_id',load(){try{return JSON.parse(localStorage.getItem(this.key)||'[]')}catch{return[]}},save(list){localStorage.setItem(this.key,JSON.stringify(list||[]))},getActiveId(){return localStorage.getItem(this.activeKey)||null},setActiveId(id){localStorage.setItem(this.activeKey,id||'')}}
const defaultSettings={model:DEFAULT_MODEL,temperature:'',top_p:'',top_k:'',frequency_penalty:'',repetition_penalty:'',min_p:'',top_a:'',verbosity:'',reasoning_effort:'default',system_prompt:'',html:'',extension_html:"<sune src='https://raw.githubusercontent.com/sune-org/store/refs/heads/main/sync.sune' private></sune>",hide_composer:false,include_thoughts:false,img_output:false,aspect_ratio:'1:1',image_size:'1K',ignore_master_prompt:false}
const makeSune=(p={})=>({id:p.id||gid(),name:p.name?.trim()||'Default',pinned:!!p.pinned,avatar:p.avatar||'',url:p.url||'',updatedAt:p.updatedAt||Date.now(),settings:Object.assign({},defaultSettings,p.settings||{}),storage:p.storage||{}})
const makeSune=(p={})=>({id:p.id||gid(),name:p.name?.trim()||'Default',pinned:!!p.pinned,avatar:p.avatar||'',url:p.url||'',updatedAt:p.updatedAt||Date.now(),settings:Object.assign({},defaultSettings,p.settings||{})})
let sunes=(su.load()||[]).map(makeSune)
const SUNE=window.SUNE=new Proxy({get list(){return sunes},get id(){return su.getActiveId()},get active(){return sunes.find(a=>a.id===su.getActiveId())||sunes[0]},get:id=>sunes.find(s=>s.id===id),setActive:id=>su.setActiveId(id||''),create(p={}){const s=makeSune(p);sunes.unshift(s);su.save(sunes);return s},delete(id){const curId=this.id;sunes=sunes.filter(s=>s.id!==id);su.save(sunes);if(sunes.length===0){const def=this.create({name:'Default'});this.setActive(def.id)}else if(curId===id)this.setActive(sunes[0].id)},save:()=>su.save(sunes)},{get(t,p){if(p==='fetchDotSune')return async g=>{try{const u=g.startsWith('http')?g:(()=>{const[a,b]=g.split('@'),[c,d]=a.split('/'),[e,...f]=b.split('/');return`https://raw.githubusercontent.com/${c}/${d}/${e}/${f.join('/')}`})(),j=await(await fetch(u)).json(),l=sunes.length;sunes.unshift(...(Array.isArray(j)?j:j?.sunes||[]).filter(s=>s?.id&&!t.get(s.id)).map(s=>makeSune(s)));sunes.length>l&&t.save()}catch{}};if(p==='attach')return async files=>{const arr=[];for(const f of files||[])arr.push(await toAttach(f));const clean=arr.filter(Boolean);if(!clean.length)return;await ensureThreadOnFirstUser('(attachments)');addMessage({role:'assistant',content:clean,...activeMeta()});await THREAD.persist()};if(p==='log')return async s=>{const t=String(s??'').trim();if(!t)return;await ensureThreadOnFirstUser(t);addMessage({role:'assistant',content:[{type:'text',text:t}],...activeMeta()});await THREAD.persist()};if(p==='lastReply')return [...state.messages].reverse().find(m=>m.role==='assistant');if(p==='infer')return async()=>{if(state.busy||!SUNE.model||state.abortRequested){state.abortRequested=false;return};await ensureThreadOnFirstUser('Sune Inference');const th=THREAD.active;if(th&&!th.title)(async()=>THREAD.setTitle(th.id,await generateTitleWithAI(state.messages)||'Sune Inference'))();state.busy=true;setBtnStop();const a=SUNE.active,suneMeta={sune_name:a.name,model:SUNE.model,avatar:a.avatar||''},streamId=sid(),suneBubble=addSuneBubbleStreaming(suneMeta,streamId);suneBubble.dataset.mid=streamId;suneBubble.innerHTML=SUNE_LOGO_SVG;const assistantMsg=Object.assign({id:streamId,role:'assistant',content:[{type:'text',text:''}]},suneMeta);state.messages.push(assistantMsg);THREAD.persist(false);state.stream={rid:null,bubble:null,meta:null,text:'',done:false};let buf='',completed=false;const onDelta=(delta,done,imgs)=>{if(imgs){if(!assistantMsg.images)assistantMsg.images=[];assistantMsg.images.push(...imgs)}buf+=delta;state.stream.text=buf;assistantMsg.content[0].text=buf;renderMarkdown(suneBubble,partsToText(assistantMsg),{enhance:false});if(done&&!completed){completed=true;setBtnSend();state.busy=false;enhanceCodeBlocks(suneBubble,true);THREAD.persist(true);el.composer.dispatchEvent(new CustomEvent('sune:newSuneResponse',{detail:{message:assistantMsg}}));state.stream={rid:null,bubble:null,meta:null,text:'',done:false}}else if(!done)THREAD.persist(false)};await streamChat(onDelta,streamId)};if(p==='getByName')return n=>sunes.find(s=>s.name.toLowerCase()===(n||'').trim().toLowerCase());if(p==='handoff')return async n=>{await new Promise(r=>setTimeout(r,4000));const s=sunes.find(s=>s.name.toLowerCase()===(n||'').trim().toLowerCase());if(!s)return;SUNE.setActive(s.id);renderSidebar();await reflectActiveSune();await SUNE.infer()};if(p in t)return t[p];const a=t.active;if(!a)return;if(p in a.settings)return a.settings[p];if(p in a)return a[p]},set(t,p,v){const a=t.active;if(!a)return false;const i=sunes.findIndex(s=>s.id===a.id);if(i<0)return false;const isTopLevel=/^(name|avatar|url|pinned|storage)$/.test(p),target=isTopLevel?sunes[i]:sunes[i].settings;let value=v;if(!isTopLevel){if(p==='system_prompt')value=v||''}if(target[p]!==value){target[p]=value;sunes[i].updatedAt=Date.now();su.save(sunes)}return true}})
const SUNE=window.SUNE=new Proxy({storage:suneStorage,get list(){return sunes},get id(){return su.getActiveId()},get active(){return sunes.find(a=>a.id===su.getActiveId())||sunes[0]},get:id=>sunes.find(s=>s.id===id),setActive:id=>su.setActiveId(id||''),create(p={}){const s=makeSune(p);sunes.unshift(s);su.save(sunes);return s},delete(id){const curId=this.id;sunes=sunes.filter(s=>s.id!==id);su.save(sunes);cleanSuneStorage(id);gcStorage();if(sunes.length===0){const def=this.create({name:'Default'});this.setActive(def.id)}else if(curId===id)this.setActive(sunes[0].id)},save:()=>su.save(sunes)},{get(t,p){if(p==='fetchDotSune')return async g=>{try{const u=g.startsWith('http')?g:(()=>{const[a,b]=g.split('@'),[c,d]=a.split('/'),[e,...f]=b.split('/');return`https://raw.githubusercontent.com/${c}/${d}/${e}/${f.join('/')}`})(),j=await(await fetch(u)).json(),l=sunes.length;sunes.unshift(...(Array.isArray(j)?j:j?.sunes||[]).filter(s=>s?.id&&!t.get(s.id)).map(s=>makeSune(s)));sunes.length>l&&t.save()}catch{}};if(p==='attach')return async files=>{const arr=[];for(const f of files||[])arr.push(await toAttach(f));const clean=arr.filter(Boolean);if(!clean.length)return;await ensureThreadOnFirstUser('(attachments)');addMessage({role:'assistant',content:clean,...activeMeta()});await THREAD.persist()};if(p==='log')return async s=>{const t=String(s??'').trim();if(!t)return;await ensureThreadOnFirstUser(t);addMessage({role:'assistant',content:[{type:'text',text:t}],...activeMeta()});await THREAD.persist()};if(p==='lastReply')return [...state.messages].reverse().find(m=>m.role==='assistant');if(p==='infer')return async()=>{if(state.busy||!SUNE.model||state.abortRequested){state.abortRequested=false;return};await ensureThreadOnFirstUser('Sune Inference');const th=THREAD.active;if(th&&!th.title)(async()=>THREAD.setTitle(th.id,await generateTitleWithAI(state.messages)||'Sune Inference'))();state.busy=true;setBtnStop();const a=SUNE.active,suneMeta={sune_name:a.name,model:SUNE.model,avatar:a.avatar||''},streamId=sid(),suneBubble=addSuneBubbleStreaming(suneMeta,streamId);suneBubble.dataset.mid=streamId;suneBubble.innerHTML=SUNE_LOGO_SVG;const assistantMsg=Object.assign({id:streamId,role:'assistant',content:[{type:'text',text:''}]},suneMeta);state.messages.push(assistantMsg);THREAD.persist(false);state.stream={rid:null,bubble:null,meta:null,text:'',done:false};let buf='',completed=false;const onDelta=(delta,done,imgs)=>{if(imgs){if(!assistantMsg.images)assistantMsg.images=[];assistantMsg.images.push(...imgs)}buf+=delta;state.stream.text=buf;assistantMsg.content[0].text=buf;renderMarkdown(suneBubble,partsToText(assistantMsg),{enhance:false});if(done&&!completed){completed=true;setBtnSend();state.busy=false;enhanceCodeBlocks(suneBubble,true);THREAD.persist(true);el.composer.dispatchEvent(new CustomEvent('sune:newSuneResponse',{detail:{message:assistantMsg}}));state.stream={rid:null,bubble:null,meta:null,text:'',done:false}}else if(!done)THREAD.persist(false)};await streamChat(onDelta,streamId)};if(p==='getByName')return n=>sunes.find(s=>s.name.toLowerCase()===(n||'').trim().toLowerCase());if(p==='handoff')return async n=>{await new Promise(r=>setTimeout(r,4000));const s=sunes.find(s=>s.name.toLowerCase()===(n||'').trim().toLowerCase());if(!s)return;SUNE.setActive(s.id);renderSidebar();await reflectActiveSune();await SUNE.infer()};if(p in t)return t[p];const a=t.active;if(!a)return;if(p in a.settings)return a.settings[p];if(p in a)return a[p]},set(t,p,v){const a=t.active;if(!a)return false;const i=sunes.findIndex(s=>s.id===a.id);if(i<0)return false;const isTopLevel=/^(name|avatar|url|pinned)$/.test(p),target=isTopLevel?sunes[i]:sunes[i].settings;let value=v;if(!isTopLevel){if(p==='system_prompt')value=v||''}if(target[p]!==value){target[p]=value;sunes[i].updatedAt=Date.now();su.save(sunes)}return true}})
if(!sunes.length){const def=SUNE.create({name:'Default'});SUNE.setActive(def.id)}
const state=window.state={messages:[],busy:false,controller:null,currentThreadId:null,abortRequested:false,attachments:[],stream:{rid:null,bubble:null,meta:null,text:'',done:false}}
const getModelShort=m=>{const mm=m||SUNE.model||'';return mm.includes('/')?mm.split('/').pop():mm}
@@ -142,7 +155,7 @@ USER.logMany = async msgs => {
await THREAD.persist();
};
async function init(){const u=localStorage.getItem('thread_repo_url')||'';el.threadRepoInput.value=u;el.threadFolderBtn.classList.toggle('hidden',!u.startsWith('gh://'));el.threadBackBtn.classList.toggle('hidden',!u.startsWith('gh://')||u.split('/').length<=3);await THREAD.load();await renderThreads();await Promise.allSettled(STICKY_SUNES.map(s=>SUNE.fetchDotSune(s)));renderSidebar();renderUserUI();await reflectActiveSune();clearChat();icons();kbBind();kbUpdate()}
async function init(){gcStorage();const u=localStorage.getItem('thread_repo_url')||'',suR=localStorage.getItem('sune_repo_url')||'';el.threadRepoInput.value=u;el.suneRepoInput.value=suR;el.threadFolderBtn.classList.toggle('hidden',!u.startsWith('gh://'));el.threadBackBtn.classList.toggle('hidden',!u.startsWith('gh://')||u.split('/').length<=3);await THREAD.load();await renderThreads();await Promise.allSettled(STICKY_SUNES.map(s=>SUNE.fetchDotSune(s)));renderSidebar();renderUserUI();await reflectActiveSune();clearChat();icons();kbBind();kbUpdate()}
$(window).on('resize',()=>{hideThreadPopover();hideSunePopover()})
const htmlTabs={index:['htmlTab_index','htmlEditor'],extension:['htmlTab_extension','extensionHtmlEditor']};function showHtmlTab(key){Object.entries(htmlTabs).forEach(([k,[tb,pn]])=>{const a=k===key;el[tb].classList.toggle('border-black',a);el[tb].classList.toggle('border-transparent',!a);el[tb].classList.toggle('hover:border-gray-300',!a);el[pn].classList.toggle('hidden',!a)})}
el.htmlTab_index.textContent='index.html';el.htmlTab_extension.textContent='extension.html';
@@ -152,9 +165,11 @@ $(el.threadRepoInput).on('change',async()=>{const u=el.threadRepoInput.value.tri
$(el.threadBackBtn).on('click',()=>{const u=el.threadRepoInput.value.trim();if(!u.startsWith('gh://'))return;const p=u.split('/');if(p.length>3){p.pop();el.threadRepoInput.value=p.join('/');el.threadRepoInput.dispatchEvent(new Event('change'))}});
$(el.threadFolderBtn).on('click',async()=>{const n=prompt('Folder name:');if(!n)return;THREAD.list.unshift({id:n.trim(),title:n.trim(),type:'folder',updatedAt:Date.now()});await THREAD.save();await renderThreads()});
$(el.threadSyncBtn).on('click',async()=>{const u=el.threadRepoInput.value.trim();if(!u.startsWith('gh://'))return;const mode=confirm('Sync Threads:\nOK = Upload (Push)\nCancel = Download (Pull)');const info=parseGhUrl(u);try{if(mode){const remoteItems=await ghApi(`${info.apiPath}?ref=${info.branch}`)||[],remoteMap={};remoteItems.forEach(i=>{const d=deserializeThreadName(i.name);if(d)remoteMap[d.id]={name:i.name,sha:i.sha}});const toRemove=[];for(const t of THREAD.list){if(t.status==='deleted'){if(remoteMap[t.id]){await ghApi(`${info.apiPath}/${remoteMap[t.id].name}`,'DELETE',{message:`Delete thread ${t.id}`,sha:remoteMap[t.id].sha,branch:info.branch});await localforage.removeItem('rem_t_'+t.id)}toRemove.push(t.id);continue}if(t.type!=='thread')continue;if(t.status==='modified'||t.status==='new'){const newName=serializeThreadName(t);let msgs=await localforage.getItem('rem_t_'+t.id);if((!msgs||!Array.isArray(msgs))&&remoteMap[t.id]){const text=await ghGetFileContent(info,remoteMap[t.id].name);if(text){try{msgs=JSON.parse(text);await localforage.setItem('rem_t_'+t.id,msgs)}catch(e){console.error(e)}}}if(remoteMap[t.id]&&remoteMap[t.id].name!==newName){await ghApi(`${info.apiPath}/${remoteMap[t.id].name}`,'DELETE',{message:`Rename thread ${t.id}`,sha:remoteMap[t.id].sha,branch:info.branch})}const x=await ghApi(`${info.apiPath}/${newName}?ref=${info.branch}`);await ghApi(`${info.apiPath}/${newName}`,'PUT',{message:`Sync thread ${t.id}`,content:utob(JSON.stringify(msgs||[],null,2)),branch:info.branch,sha:x?.sha});t.status='synced'}}THREAD.list=THREAD.list.filter(x=>!toRemove.includes(x.id));await THREAD.save();alert('Pushed to GitHub.')}else{await pullThreads();alert('Pulled from GitHub.')}await renderThreads()}catch(e){alert('Sync failed: '+e.message)}});
$(el.suneRepoInput).on('change',()=>{localStorage.setItem('sune_repo_url',el.suneRepoInput.value.trim())});
$(el.suneSyncBtn).on('click',async()=>{const u=el.suneRepoInput.value.trim();if(!u.startsWith('gh://'))return;const mode=confirm('Sync Sunes:\nOK = Upload (Push)\nCancel = Download (Pull)'),info=parseGhUrl(u);try{if(mode){const data={version:1,sunes:SUNE.list,activeId:SUNE.id,storage:{}};SUNE.list.forEach(s=>{const p=`sune_${s.id}_`;Object.keys(localStorage).forEach(k=>{if(k.startsWith(p))data.storage[k]=localStorage.getItem(k)})});const x=await ghApi(`${info.apiPath}/sunes.json?ref=${info.branch}`);await ghApi(`${info.apiPath}/sunes.json`,'PUT',{message:'Sync Sunes',content:utob(JSON.stringify(data,null,2)),branch:info.branch,sha:x?.sha});alert('Sunes pushed.')}else{const text=await ghGetFileContent(info,'sunes.json');if(!text)throw new Error('sunes.json not found');const data=JSON.parse(text);if(data.sunes){sunes=data.sunes.map(makeSune);SUNE.save();if(data.activeId)SUNE.setActive(data.activeId)}if(data.storage){Object.entries(data.storage).forEach(([k,v])=>localStorage.setItem(k,v))}renderSidebar();await reflectActiveSune();alert('Sunes pulled.')}}catch(e){alert('Sync failed: '+e.message)}});
init()
const accountTabs={General:['accountTabGeneral','accountPanelGeneral'],API:['accountTabAPI','accountPanelAPI'],User:['accountTabUser','accountPanelUser']};function showAccountTab(key){Object.entries(accountTabs).forEach(([k,[tb,pn]])=>{el[tb].classList.toggle('border-black',k===key);el[pn].classList.toggle('hidden',k!==key)})}
function openAccountSettings(){el.set_provider.value=USER.provider||'openrouter';el.set_api_key_or.value=USER.apiKeyOpenRouter||'';el.set_api_key_oai.value=USER.apiKeyOpenAI||'';el.set_api_key_g.value=USER.apiKeyGoogle||'';el.set_api_key_claude.value=USER.apiKeyClaude||'';el.set_api_key_cf.value=USER.apiKeyCloudflare||'';el.set_api_key_custom1.value=USER.customKey1||'';el.set_master_prompt.value=USER.masterPrompt||'';el.set_title_model.value=USER.titleModel;el.set_gh_token.value=USER.githubToken||'';el.set_user_name.value=USER.name;el.userAvatarPreview.src=USER.avatar||'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';el.userAvatarPreview.classList.toggle('bg-gray-200',!USER.avatar);showAccountTab('General');el.accountSettingsModal.classList.remove('hidden')}
function openAccountSettings(){el.set_provider.value=USER.provider||'openrouter';el.set_api_key_or.value=USER.apiKeyOpenRouter||'';el.set_api_key_oai.value=USER.apiKeyOpenAI||'';el.set_api_key_g.value=USER.apiKeyGoogle||'';el.set_api_key_claude.value=USER.apiKeyClaude||'';el.set_api_key_cf.value=USER.apiKeyCloudflare||'';el.set_api_key_custom1.value=USER.customKey1||'';el.set_api_key_custom1.value=USER.customKey1||'';el.set_master_prompt.value=USER.masterPrompt||'';el.set_title_model.value=USER.titleModel;el.set_gh_token.value=USER.githubToken||'';el.set_user_name.value=USER.name;el.userAvatarPreview.src=USER.avatar||'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';el.userAvatarPreview.classList.toggle('bg-gray-200',!USER.avatar);showAccountTab('General');el.accountSettingsModal.classList.remove('hidden')}
function closeAccountSettings(){el.accountSettingsModal.classList.add('hidden')}
$(el.accountSettingsOption).on('click',()=>{el.userMenu.classList.add('hidden');openAccountSettings()})
$(el.closeAccountSettings).on('click',closeAccountSettings)
@@ -167,7 +182,7 @@ $(el.accountPanelAPI).on('click',e=>{const b=e.target.closest('[data-reveal-for]
el.accountTabGeneral.onclick=()=>showAccountTab('General');el.accountTabAPI.onclick=()=>showAccountTab('API');el.accountTabUser.onclick=()=>showAccountTab('User')
el.exportAccountSettings.onclick=()=>dl(`sune-account-${ts()}.json`,{v:1,provider:USER.provider,apiKeyOpenRouter:USER.apiKeyOpenRouter,apiKeyOpenAI:USER.apiKeyOpenAI,apiKeyGoogle:USER.apiKeyGoogle,apiKeyClaude:USER.apiKeyClaude,apiKeyCloudflare:USER.apiKeyCloudflare,customKey1:USER.customKey1,masterPrompt:USER.masterPrompt,titleModel:USER.titleModel,githubToken:USER.githubToken,userName:USER.name,userAvatar:USER.avatar});
el.importAccountSettings.onclick=()=>{el.importAccountSettingsInput.value='';el.importAccountSettingsInput.click()};
el.importAccountSettingsInput.onchange=async e=>{const f=e.target.files?.[0];if(!f)return;try{const d=JSON.parse(await f.text());if(!d||typeof d!=='object')throw new Error('Invalid');const m={provider:'provider',apiKeyOpenRouter:'apiKeyOR',apiKeyOpenAI:'apiKeyOAI',apiKeyGoogle:'apiKeyG',apiKeyClaude:'apiKeyC',apiKeyCloudflare:'apiKeyCF',customKey1:'customKey1',masterPrompt:'masterPrompt',titleModel:'titleModel',githubToken:'ghToken',name:'userName',avatar:'userAvatar'};Object.entries(m).forEach(([p,k])=>{const v=d[p]??d[k];if(typeof v==='string')USER[p]=v});renderUserUI();openAccountSettings();alert('Imported.')}catch{alert('Import failed')}};
el.importAccountSettingsInput.onchange=async e=>{const f=e.target.files?.[0];if(!f)return;try{const d=JSON.parse(await f.text());if(!d||typeof d!=='object')throw new Error('Invalid');const m={provider:'provider',apiKeyOpenRouter:'apiKeyOR',apiKeyOpenAI:'apiKeyOAI',apiKeyGoogle:'apiKeyG',apiKeyClaude:'apiKeyClaude',apiKeyCloudflare:'apiKeyCloudflare',customKey1:'customKey1',masterPrompt:'masterPrompt',titleModel:'titleModel',githubToken:'ghToken',name:'userName',avatar:'userAvatar'};Object.entries(m).forEach(([p,k])=>{const v=d[p]??d[k];if(typeof v==='string')USER[p]=v});renderUserUI();openAccountSettings();alert('Imported.')}catch{alert('Import failed')}};
const getBubbleById=id=>el.messages.querySelector(`.msg-bubble[data-mid="${CSS.escape(id)}"]`)
async function syncActiveThread(){const id=THREAD.getLastAssistantMessageId();if(!id)return false;if(await cacheStore.getItem(id)==='done'){if(state.busy){setBtnSend();state.busy=false;state.controller=null}return false}if(!state.busy){state.busy=true;state.controller={abort:()=>{const ws=new WebSocket(HTTP_BASE.replace('https','wss'));ws.onopen=function(){this.send(JSON.stringify({type:'stop',rid:id}));this.close()}}};setBtnStop()}const bubble=getBubbleById(id);if(!bubble){if(state.busy){setBtnSend();state.busy=false;state.controller=null;}return false;}const msgIdx=state.messages.findIndex(x=>x.id===id);const localText=msgIdx>=0?partsToText(state.messages[msgIdx]):(bubble.textContent||'');const j=await(fetch(HTTP_BASE+'?uid='+encodeURIComponent(id)).then(r=>r.ok?r.json():null).catch(()=>null));const finalise=(t,c,imgs)=>{const tempMsg={content:c,images:imgs};renderMarkdown(bubble,partsToText(tempMsg),{enhance:false});enhanceCodeBlocks(bubble,true);if(msgIdx>=0){state.messages[msgIdx].content=c;state.messages[msgIdx].images=imgs}else state.messages.push({id,role:'assistant',content:c,images:imgs,...activeMeta()});THREAD.persist();setBtnSend();state.busy=false;cacheStore.setItem(id,'done');state.controller=null;el.composer.dispatchEvent(new CustomEvent('sune:newSuneResponse',{detail:{message:state.messages.find(m=>m.id===id)}}))};if(!j||j.rid!==id){if(j&&j.error){const t=localText+'\n\n'+j.error;finalise(t,[{type:'text',text:t}])}else{await cacheStore.setItem(id,'done');if(state.busy){setBtnSend();state.busy=false;state.controller=null;}}return false}const serverText=j.text||'',isDone=j.error||j.done||j.phase==='done';const finalText=(serverText.length>=localText.length||isDone)?serverText:localText;const display=partsToText({content:[{type:'text',text:finalText}],images:j.images});if(display)renderMarkdown(bubble,display,{enhance:false});if(isDone){if(finalText!==localText){finalise(finalText,[{type:'text',text:finalText}],j.images)}else{await cacheStore.setItem(id,'done');if(state.busy){setBtnSend();state.busy=false;state.controller=null}}return false}await cacheStore.setItem(id,'busy');return true}
let syncLoopRunning=false
@@ -180,4 +195,4 @@ const getActiveJar=()=>!el.htmlEditor.classList.contains('hidden')?jars.html:jar
$(el.copyHTML).on('click',async()=>{const jar=getActiveJar();await copyToClipboard(jar?jar.toString():'')})
$(el.pasteHTML).on('click',async()=>{try{const t=await navigator.clipboard.readText();const jar=getActiveJar();if(jar)jar.updateCode(t)}catch{}})
Object.assign(window,{icons,haptic,clamp,num,int,gid,esc,positionPopover,sid,fmtSize,asDataURL,b64,makeSune,getModelShort,resolveSuneSrc,processSuneIncludes,renderSuneHTML,reflectActiveSune,suneRow,renderUserUI,enhanceCodeBlocks,getSuneLabel,_createMessageRow,msgRow,partsToText,copyToClipboard,addSuneBubbleStreaming,clearChat,payloadWithSampling,setBtnStop,setBtnSend,localDemoReply,titleFrom,serializeThreadName,deserializeThreadName,ensureThreadOnFirstUser,generateTitleWithAI,threadRow,renderThreads,hideThreadPopover,showThreadPopover,hideSunePopover,showSunePopover,updateAttachBadge,toAttach,ensureJars,openSettings,closeSettings,showTab,dl,ts,kbUpdate,kbBind,activeMeta,init,showHtmlTab,showAccountTab,openAccountSettings,closeAccountSettings,getBubbleById,syncActiveThread,syncWhileBusy,onForeground,getActiveJar,imgToWebp,cacheStore,ghApi,parseGhUrl,ghGetFileContent,pullThreads});
Object.assign(window,{icons,haptic,clamp,num,int,gid,esc,positionPopover,sid,fmtSize,asDataURL,b64,makeSune,getModelShort,resolveSuneSrc,processSuneIncludes,renderSuneHTML,reflectActiveSune,suneRow,renderUserUI,enhanceCodeBlocks,getSuneLabel,_createMessageRow,msgRow,partsToText,copyToClipboard,addSuneBubbleStreaming,clearChat,payloadWithSampling,setBtnStop,setBtnSend,localDemoReply,titleFrom,serializeThreadName,deserializeThreadName,ensureThreadOnFirstUser,generateTitleWithAI,threadRow,renderThreads,hideThreadPopover,showThreadPopover,hideSunePopover,showSunePopover,updateAttachBadge,toAttach,ensureJars,openSettings,closeSettings,showTab,dl,ts,kbUpdate,kbBind,activeMeta,init,showHtmlTab,showAccountTab,openAccountSettings,closeAccountSettings,getBubbleById,syncActiveThread,syncWhileBusy,onForeground,getActiveJar,imgToWebp,cacheStore,ghApi,parseGhUrl,ghGetFileContent,pullThreads,suneStorage,gcStorage,cleanSuneStorage});

View File

@@ -1,6 +1,12 @@
<div id="sidebarOverlayLeft" class="fixed inset-0 z-40 bg-black/20 hidden" @click="document.getElementById('sidebarLeft').classList.add('-translate-x-full');$el.classList.add('hidden');document.getElementById('sidebarRight').classList.add('translate-x-full');document.getElementById('sidebarOverlayRight').classList.add('hidden');hideThreadPopover();hideSunePopover()"></div>
<aside id="sidebarLeft" class="fixed inset-y-0 left-0 z-50 w-72 max-w-[85vw] bg-white border-r border-gray-200 shadow-xl transform -translate-x-full transition-transform duration-200 ease-out flex flex-col">
<div class="p-3 border-b flex items-center gap-2"><button id="newSuneBtn" class="px-3 py-2 rounded-xl bg-black text-white text-sm hover:bg-black/90">New sune</button><span class="text-xs text-gray-500">Click name to equip</span></div>
<div class="p-2 border-b flex flex-col gap-2">
<input id="suneRepoInput" type="text" placeholder="gh://owner/sunes" class="w-full h-9 rounded-lg border-0 bg-gray-100 px-3 text-xs font-mono focus:ring-2 focus:ring-black focus:bg-white"/>
<div class="flex items-center justify-between gap-2">
<button id="newSuneBtn" class="px-3 py-1.5 rounded-lg bg-black text-white text-[10px] font-bold uppercase tracking-wider hover:bg-black/90 transition">New Sune</button>
<button id="suneSyncBtn" class="px-3 py-1.5 rounded-lg bg-gray-100 text-gray-900 text-[10px] font-bold uppercase tracking-wider hover:bg-gray-200 transition flex items-center gap-1"><i data-lucide="refresh-cw" class="h-3 w-3"></i><span>Sync</span></button>
</div>
</div>
<div id="suneList" class="flex-1 overflow-y-auto divide-y"></div>
<div class="p-3 border-t relative flex items-center gap-2">
<button id="userMenuBtn" class="flex-1 flex items-center justify-between px-3 py-2 rounded-xl bg-gray-100 hover:bg-gray-200 active:scale-[.99] transition" @click.stop="document.getElementById('userMenu').classList.toggle('hidden')"><span class="flex items-center gap-2"><span id="userMenuAvatar" class="h-6 w-6 rounded-full bg-gray-900 text-white flex items-center justify-center overflow-hidden shrink-0">👤</span><span class="text-sm">User</span></span><i data-lucide="chevron-down" class="h-4 w-4"></i></button>