mirror of
https://github.com/multipleof4/sune.git
synced 2026-02-04 10:08:00 +00:00
Feat: Remote thread deletion and path safety
This commit is contained in:
@@ -47,7 +47,7 @@ const generateTitleWithAI=async messages=>{const model=USER.titleModel,apiKey=US
|
|||||||
const threadRow=t=>`<div class=\"relative flex items-center gap-2 px-3 py-2 ${t.pinned?'bg-yellow-50':''}\"><button data-open-thread=\"${t.id}\" data-type=\"${t.type||'thread'}\" class=\"flex-1 text-left truncate flex items-center gap-2\">${t.type==='folder'?'<i data-lucide="folder" class="h-4 w-4"></i>':''}${t.pinned?'📌 ':''}${esc(t.title||'Untitled')}${t.status==='modified'?'*':(t.status==='new'?'+':'')}</button><button data-thread-menu=\"${t.id}\" class=\"h-8 w-8 rounded hover:bg-gray-100 flex items-center justify-center\" title=\"More\"><i data-lucide=\"more-horizontal\" class="h-4 w-4"></i></button></div>`
|
const threadRow=t=>`<div class=\"relative flex items-center gap-2 px-3 py-2 ${t.pinned?'bg-yellow-50':''}\"><button data-open-thread=\"${t.id}\" data-type=\"${t.type||'thread'}\" class=\"flex-1 text-left truncate flex items-center gap-2\">${t.type==='folder'?'<i data-lucide="folder" class="h-4 w-4"></i>':''}${t.pinned?'📌 ':''}${esc(t.title||'Untitled')}${t.status==='modified'?'*':(t.status==='new'?'+':'')}</button><button data-thread-menu=\"${t.id}\" class=\"h-8 w-8 rounded hover:bg-gray-100 flex items-center justify-center\" title=\"More\"><i data-lucide=\"more-horizontal\" class="h-4 w-4"></i></button></div>`
|
||||||
let sortedThreads=[],isAddingThreads=false;const THREAD_PAGE_SIZE=50;
|
let sortedThreads=[],isAddingThreads=false;const THREAD_PAGE_SIZE=50;
|
||||||
async function renderThreads(){
|
async function renderThreads(){
|
||||||
sortedThreads=[...THREAD.list].sort((a,b)=>(b.pinned-a.pinned)||(b.updatedAt-a.updatedAt));
|
sortedThreads=[...THREAD.list].filter(t=>t.status!=='deleted').sort((a,b)=>(b.pinned-a.pinned)||(b.updatedAt-a.updatedAt));
|
||||||
el.threadList.innerHTML=sortedThreads.slice(0,THREAD_PAGE_SIZE).map(threadRow).join('');
|
el.threadList.innerHTML=sortedThreads.slice(0,THREAD_PAGE_SIZE).map(threadRow).join('');
|
||||||
el.threadList.scrollTop=0;
|
el.threadList.scrollTop=0;
|
||||||
isAddingThreads=false;
|
isAddingThreads=false;
|
||||||
@@ -70,7 +70,7 @@ $(el.threadList).on('scroll',()=>{
|
|||||||
}
|
}
|
||||||
isAddingThreads=false;
|
isAddingThreads=false;
|
||||||
});
|
});
|
||||||
$(el.threadPopover).on('click',async e=>{const act=e.target.closest('[data-action]')?.getAttribute('data-action');if(!act||!menuThreadId)return;const th=THREAD.get(menuThreadId);if(!th)return;const u=el.threadRepoInput.value.trim(),prefix=u.startsWith('gh://')?'rem_t_':'t_';if(act==='pin'){th.pinned=!th.pinned}else if(act==='rename'){const nv=prompt('Rename to:',th.title);if(nv!=null){th.title=titleFrom(nv);th.updatedAt=Date.now();if(u.startsWith('gh://'))th.status='modified'}}else if(act==='delete'){if(confirm('Delete this chat?')){THREAD.list=THREAD.list.filter(x=>x.id!==th.id);await localforage.removeItem(prefix+th.id);if(state.currentThreadId===th.id){state.currentThreadId=null;clearChat()}}}else if(act==='count_tokens'){const msgs=await localforage.getItem(prefix+th.id)||[];let totalChars=0;for(const m of msgs){if(!m||!m.role||m.role==='system')continue;totalChars+=String(partsToText(m)||'').length}const tokens=Math.max(0,Math.ceil(totalChars/4));const k=tokens>=1000?Math.round(tokens/1000)+'k':String(tokens);alert(tokens+' tokens ('+k+')')}else if(act==='export'){const msgs=await localforage.getItem(prefix+th.id)||[];dl(`thread-${(th.title||'thread').replace(/\W/g,'_')}-${ts()}.json`,{...th,messages:msgs})}hideThreadPopover();await THREAD.save();renderThreads()})
|
$(el.threadPopover).on('click',async e=>{const act=e.target.closest('[data-action]')?.getAttribute('data-action');if(!act||!menuThreadId)return;const th=THREAD.get(menuThreadId);if(!th)return;const u=el.threadRepoInput.value.trim(),prefix=u.startsWith('gh://')?'rem_t_':'t_';if(act==='pin'){th.pinned=!th.pinned}else if(act==='rename'){const nv=prompt('Rename to:',th.title);if(nv!=null){th.title=titleFrom(nv);th.updatedAt=Date.now();if(u.startsWith('gh://'))th.status='modified'}}else if(act==='delete'){if(confirm('Delete this chat?')){if(u.startsWith('gh://')){th.status='deleted';th.updatedAt=Date.now()}else{THREAD.list=THREAD.list.filter(x=>x.id!==th.id);await localforage.removeItem(prefix+th.id)}if(state.currentThreadId===th.id){state.currentThreadId=null;clearChat()}}}else if(act==='count_tokens'){const msgs=await localforage.getItem(prefix+th.id)||[];let totalChars=0;for(const m of msgs){if(!m||!m.role||m.role==='system')continue;totalChars+=String(partsToText(m)||'').length}const tokens=Math.max(0,Math.ceil(totalChars/4));const k=tokens>=1000?Math.round(tokens/1000)+'k':String(tokens);alert(tokens+' tokens ('+k+')')}else if(act==='export'){const msgs=await localforage.getItem(prefix+th.id)||[];dl(`thread-${(th.title||'thread').replace(/\W/g,'_')}-${ts()}.json`,{...th,messages:msgs})}hideThreadPopover();await THREAD.save();renderThreads()})
|
||||||
$(el.suneList).on('click',async e=>{const menuBtn=e.target.closest('[data-sune-menu]');if(menuBtn){e.stopPropagation();showSunePopover(menuBtn,menuBtn.getAttribute('[data-sune-menu]')?menuBtn.getAttribute('[data-sune-menu]'):menuBtn.getAttribute('data-sune-menu'));return}const btn=e.target.closest('[data-sune-id]');if(!btn)return;const id=btn.getAttribute('data-sune-id');if(id){if(state.busy){state.controller?.disconnect?.();setBtnSend();state.busy=false;state.controller=null};SUNE.setActive(id);renderSidebar();await reflectActiveSune();state.currentThreadId=null;clearChat();document.getElementById('sidebarLeft').classList.add('-translate-x-full');document.getElementById('sidebarOverlayLeft').classList.add('hidden')}})
|
$(el.suneList).on('click',async e=>{const menuBtn=e.target.closest('[data-sune-menu]');if(menuBtn){e.stopPropagation();showSunePopover(menuBtn,menuBtn.getAttribute('[data-sune-menu]')?menuBtn.getAttribute('[data-sune-menu]'):menuBtn.getAttribute('data-sune-menu'));return}const btn=e.target.closest('[data-sune-id]');if(!btn)return;const id=btn.getAttribute('data-sune-id');if(id){if(state.busy){state.controller?.disconnect?.();setBtnSend();state.busy=false;state.controller=null};SUNE.setActive(id);renderSidebar();await reflectActiveSune();state.currentThreadId=null;clearChat();document.getElementById('sidebarLeft').classList.add('-translate-x-full');document.getElementById('sidebarOverlayLeft').classList.add('hidden')}})
|
||||||
$(el.sunePopover).on('click',async e=>{const act=e.target.closest('[data-action]')?.getAttribute('data-action');if(!act||!menuSuneId)return;const s=SUNE.get(menuSuneId);if(!s)return;const updateAndRender=async()=>{s.updatedAt=Date.now();SUNE.save();renderSidebar();await reflectActiveSune()};if(act==='pin'){s.pinned=!s.pinned;await updateAndRender()}else if(act==='rename'){const n=prompt('Rename sune to:',s.name);if(n!=null){s.name=n.trim();await updateAndRender()}}else if(act==='pfp'){const i=document.createElement('input');i.type='file';i.accept='image/*';i.onchange=async()=>{const f=i.files?.[0];if(!f)return;try{s.avatar=await imgToWebp(f);await updateAndRender()}catch{}};i.click()}else if(act==='export')dl(`sune-${(s.name||'sune').replace(/\W/g,'_')}-${ts()}.sune`,[s]);hideSunePopover()})
|
$(el.sunePopover).on('click',async e=>{const act=e.target.closest('[data-action]')?.getAttribute('data-action');if(!act||!menuSuneId)return;const s=SUNE.get(menuSuneId);if(!s)return;const updateAndRender=async()=>{s.updatedAt=Date.now();SUNE.save();renderSidebar();await reflectActiveSune()};if(act==='pin'){s.pinned=!s.pinned;await updateAndRender()}else if(act==='rename'){const n=prompt('Rename sune to:',s.name);if(n!=null){s.name=n.trim();await updateAndRender()}}else if(act==='pfp'){const i=document.createElement('input');i.type='file';i.accept='image/*';i.onchange=async()=>{const f=i.files?.[0];if(!f)return;try{s.avatar=await imgToWebp(f);await updateAndRender()}catch{}};i.click()}else if(act==='export')dl(`sune-${(s.name||'sune').replace(/\W/g,'_')}-${ts()}.sune`,[s]);hideSunePopover()})
|
||||||
function updateAttachBadge(){const n=state.attachments.length;el.attachBadge.textContent=String(n);el.attachBadge.classList.toggle('hidden',n===0)}
|
function updateAttachBadge(){const n=state.attachments.length;el.attachBadge.textContent=String(n);el.attachBadge.classList.toggle('hidden',n===0)}
|
||||||
@@ -112,10 +112,10 @@ el.htmlTab_index.textContent='index.html';el.htmlTab_extension.textContent='exte
|
|||||||
el.htmlTab_index.onclick=()=>showHtmlTab('index');el.htmlTab_extension.onclick=()=>showHtmlTab('extension');
|
el.htmlTab_index.onclick=()=>showHtmlTab('index');el.htmlTab_extension.onclick=()=>showHtmlTab('extension');
|
||||||
const ghApi=async(path,method='GET',body=null)=>{const t=USER.githubToken;if(!t)throw new Error('No GH token');const r=await fetch(`https://api.github.com/repos/${path}`,{method,headers:{'Authorization':`token ${t}`,'Accept':'application/vnd.github.v3+json','Content-Type':'application/json'},body:body?JSON.stringify(body):null});if(!r.ok&&r.status!==404)throw new Error(`GH API ${r.status}`);return r.status===404?null:r.json()};
|
const ghApi=async(path,method='GET',body=null)=>{const t=USER.githubToken;if(!t)throw new Error('No GH token');const r=await fetch(`https://api.github.com/repos/${path}`,{method,headers:{'Authorization':`token ${t}`,'Accept':'application/vnd.github.v3+json','Content-Type':'application/json'},body:body?JSON.stringify(body):null});if(!r.ok&&r.status!==404)throw new Error(`GH API ${r.status}`);return r.status===404?null:r.json()};
|
||||||
const parseGhUrl=u=>{const p=u.substring(5).split('/'),owner=p[0],repoPart=p[1]||'',branch=repoPart.includes('@')?repoPart.split('@')[1]:'main',repo=repoPart.split('@')[0],path=p.slice(2).join('/');const dirPath=path?path+'/':'';return{owner,repo,branch,path,full:`${owner}/${repo}/contents/${dirPath}index.json?ref=${branch}`,dir:`${owner}/${repo}/contents/${dirPath}`}};
|
const parseGhUrl=u=>{const p=u.substring(5).split('/'),owner=p[0],repoPart=p[1]||'',branch=repoPart.includes('@')?repoPart.split('@')[1]:'main',repo=repoPart.split('@')[0],path=p.slice(2).join('/');const dirPath=path?path+'/':'';return{owner,repo,branch,path,full:`${owner}/${repo}/contents/${dirPath}index.json?ref=${branch}`,dir:`${owner}/${repo}/contents/${dirPath}`}};
|
||||||
$(el.threadRepoInput).on('change',async()=>{const u=el.threadRepoInput.value.trim();localStorage.setItem('thread_repo_url',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()});
|
$(el.threadRepoInput).on('change',async()=>{const u=el.threadRepoInput.value.trim();localStorage.setItem('thread_repo_url',u);if(state.currentThreadId){state.currentThreadId=null;clearChat()}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()});
|
||||||
$(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.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.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 idxFile=await ghApi(info.full),sha=idxFile?.sha;for(const t of THREAD.list){if(t.type==='thread'&&(t.status==='modified'||t.status==='new')){const msgs=await localforage.getItem('rem_t_'+t.id),fPath=`${info.dir}${t.id}.json`,ex=await ghApi(fPath+'?ref='+info.branch);await ghApi(fPath,'PUT',{message:`Sync thread ${t.id}`,content:utob(JSON.stringify(msgs,null,2)),branch:info.branch,sha:ex?.sha});t.status='synced'}}await ghApi(info.full,'PUT',{message:'Update index.json',content:utob(JSON.stringify(THREAD.list,null,2)),branch:info.branch,sha});alert('Pushed to GitHub.')}else{const idxFile=await ghApi(info.full);if(!idxFile){THREAD.list=[];await THREAD.save();alert('Remote is empty. Local list cleared.')}else{const remoteList=JSON.parse(btou(idxFile.content));THREAD.list=remoteList.map(t=>({...t,status:'synced'}));await THREAD.save();alert('Pulled from GitHub.')}}await renderThreads()}catch(e){alert('Sync failed: '+e.message)}});
|
$(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 idxFile=await ghApi(info.full),sha=idxFile?.sha,toRemove=[];for(const t of THREAD.list){if(t.type!=='thread')continue;const fPath=`${info.dir}${t.id}.json`;if(t.status==='deleted'){const ex=await ghApi(fPath+'?ref='+info.branch);if(ex?.sha)await ghApi(fPath,'DELETE',{message:`Delete thread ${t.id}`,sha:ex.sha,branch:info.branch});await localforage.removeItem('rem_t_'+t.id);toRemove.push(t.id)}else if(t.status==='modified'||t.status==='new'){const msgs=await localforage.getItem('rem_t_'+t.id),ex=await ghApi(fPath+'?ref='+info.branch);await ghApi(fPath,'PUT',{message:`Sync thread ${t.id}`,content:utob(JSON.stringify(msgs,null,2)),branch:info.branch,sha:ex?.sha});t.status='synced'}}THREAD.list=THREAD.list.filter(x=>!toRemove.includes(x.id));await ghApi(info.full,'PUT',{message:'Update index.json',content:utob(JSON.stringify(THREAD.list,null,2)),branch:info.branch,sha});alert('Pushed to GitHub.')}else{const idxFile=await ghApi(info.full);if(!idxFile){THREAD.list=[];await THREAD.save();alert('Remote is empty. Local list cleared.')}else{const remoteList=JSON.parse(btou(idxFile.content));THREAD.list=remoteList.map(t=>({...t,status:'synced'}));await THREAD.save();alert('Pulled from GitHub.')}}await renderThreads()}catch(e){alert('Sync failed: '+e.message)}});
|
||||||
init()
|
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)})}
|
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_master_prompt.value=USER.masterPrompt||'';el.set_title_model.value=USER.titleModel;el.set_gh_token.value=USER.githubToken||'';const sa=USER.gcpSA;el.gcpSAUploadBtn.textContent=sa&&sa.project_id?`Uploaded: ${sa.project_id}`:'Upload .json';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);el.set_donor.checked=USER.donor;const updateProv=()=>{const d=el.set_donor.checked;Array.from(el.set_provider.options).forEach(o=>{if(o.value!=='openrouter'){o.disabled=!d;if(!d)o.hidden=true;else o.hidden=false}});if(!d&&el.set_provider.value!=='openrouter')el.set_provider.value='openrouter'};updateProv();el.set_donor.onchange=updateProv;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_master_prompt.value=USER.masterPrompt||'';el.set_title_model.value=USER.titleModel;el.set_gh_token.value=USER.githubToken||'';const sa=USER.gcpSA;el.gcpSAUploadBtn.textContent=sa&&sa.project_id?`Uploaded: ${sa.project_id}`:'Upload .json';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);el.set_donor.checked=USER.donor;const updateProv=()=>{const d=el.set_donor.checked;Array.from(el.set_provider.options).forEach(o=>{if(o.value!=='openrouter'){o.disabled=!d;if(!d)o.hidden=true;else o.hidden=false}});if(!d&&el.set_provider.value!=='openrouter')el.set_provider.value='openrouter'};updateProv();el.set_donor.onchange=updateProv;showAccountTab('General');el.accountSettingsModal.classList.remove('hidden')}
|
||||||
|
|||||||
Reference in New Issue
Block a user