kaizen-agent 1.64.3 → 1.65.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli/install.ts +9 -0
- package/cli/roadmap.ts +74 -0
- package/cli/skills.ts +1 -1
- package/cli/web.ts +55 -1
- package/commands/kaizen-concept.md +6 -0
- package/commands/kaizen-roadmap.md +6 -0
- package/package.json +4 -2
- package/skills/kaizen/SKILL.md +12 -0
- package/skills/kaizen/roadmap.md +25 -0
- package/skills/kaizen/spec-main.md +27 -0
- package/skills/kaizen/spec-plan.md +37 -11
- package/skills/kaizen-concept/SKILL.md +262 -0
- package/skills/kaizen-concept/skill.json +1 -0
- package/skills/kaizen-help/SKILL.md +2 -0
- package/web/board/chat.ts +4 -3
- package/web/board/run-view.ts +18 -3
- package/web/board/ws-tabs.ts +9 -0
- package/web/board.js +102 -102
- package/web/notebook.js +1 -1
- package/web/term.js +1 -1
- package/web/video.js +1 -1
- package/cli/__pycache__/computer-helper.cpython-314.pyc +0 -0
- package/cli/accounts.test.ts +0 -126
- package/cli/add-project.test.ts +0 -169
- package/cli/agent-prefs.test.ts +0 -127
- package/cli/automations.test.ts +0 -167
- package/cli/backlog.test.ts +0 -133
- package/cli/board.test.ts +0 -381
- package/cli/browser.test.ts +0 -132
- package/cli/chat.test.ts +0 -274
- package/cli/chatgpt.test.ts +0 -158
- package/cli/computer.test.ts +0 -155
- package/cli/docs.test.ts +0 -94
- package/cli/handoff.test.ts +0 -133
- package/cli/html.test.ts +0 -19
- package/cli/install.test.ts +0 -237
- package/cli/knowledge.test.ts +0 -179
- package/cli/localsend.test.ts +0 -84
- package/cli/logo.test.ts +0 -18
- package/cli/notes.test.ts +0 -249
- package/cli/onboarding.test.ts +0 -70
- package/cli/project-tree.test.ts +0 -40
- package/cli/pty.test.ts +0 -330
- package/cli/release.test.ts +0 -12
- package/cli/report.test.ts +0 -59
- package/cli/resources.test.ts +0 -50
- package/cli/restart.test.ts +0 -222
- package/cli/settings.test.ts +0 -168
- package/cli/setup.test.ts +0 -78
- package/cli/shell-agent.test.ts +0 -23
- package/cli/skills.test.ts +0 -95
- package/cli/sources.test.ts +0 -851
- package/cli/state.test.ts +0 -1639
- package/cli/term-image.test.ts +0 -23
- package/cli/usage.test.ts +0 -291
- package/cli/versions.test.ts +0 -154
- package/cli/video.test.ts +0 -545
- package/cli/web-accept.test.ts +0 -55
- package/cli/web-decide.test.ts +0 -54
- package/cli/web-pr.test.ts +0 -52
- package/cli/web-skills.test.ts +0 -32
- package/cli/web-symlink.test.ts +0 -29
- package/cli/workers.test.ts +0 -319
- package/cli/worktree.test.ts +0 -452
- package/cli/writeback.test.ts +0 -102
- package/skills/media/kaizen-video/scripts/__pycache__/intake.cpython-314.pyc +0 -0
- package/skills/media/kaizen-video/scripts/__pycache__/make_film.cpython-314.pyc +0 -0
- package/skills/media/kaizen-video/scripts/__pycache__/make_tiktok.cpython-314.pyc +0 -0
- package/skills/media/kaizen-video/scripts/__pycache__/render_cut.cpython-314.pyc +0 -0
- package/skills/media/kaizen-video/scripts/__pycache__/sfx.cpython-314.pyc +0 -0
- package/skills/media/kaizen-video/scripts/__pycache__/srt.cpython-314.pyc +0 -0
- package/skills/media/kaizen-video/scripts/__pycache__/transcribe.cpython-314.pyc +0 -0
- package/skills/media/kaizen-video/scripts/__pycache__/vo.cpython-314.pyc +0 -0
- package/web/board/search.test.ts +0 -20
- package/web/board/settings-pages.test.ts +0 -28
- package/web/board/settings-voice.test.ts +0 -18
- package/web/board/toast.test.ts +0 -77
- package/web/board/ws-board.test.ts +0 -77
- package/web/board/ws-name.test.ts +0 -10
- package/web/board/ws-tabs.test.ts +0 -213
- package/web/term-font.test.ts +0 -22
package/web/notebook.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/* kaizen notebook
|
|
1
|
+
/* kaizen notebook ada6d903316fe7d4 -- generated by bun run build:web from web/notebook.ts; do not edit */
|
|
2
2
|
var Ja=null,eh=(e)=>{Ja=e};function Am(e,t,i){Vr++,Ja?.(e,t,i)}var Vr=0,Ka="",Ur=!1,As=!1;async function Nr(){if(Ur){As=!0;return}Ur=!0;do{As=!1;let e=Vr;try{let t=await fetch("/state?all=1");if(!t.ok)continue;let i=await t.text(),n=i.replace(/"now":\d+\}$/,"");if(n===Ka)continue;let{cards:s,projects:r,rail:o,agents:l}=JSON.parse(i);if(!As&&e===Vr)Ka=n,Am(s,[...r,...o??[]],l)}catch{}}while(As);Ur=!1}var Xm={S:{project:null,projects:[],cards:[],now:Date.now(),all:!1,dir:null},all:new URLSearchParams(location.search).get("all")!=="0",dir:null,openKey:null,mode:null,modeKey:null,menuKey:null,flash:new Set,tab:"request",lastTab:"request",runDoc:null,clearMenu:!1,sevMenu:!1,wantTerm:null,wantPty:null,shells:[],setQ:"",setScope:"all",setPage:null,setBack:!1,pageGen:0,PL:[],shown:new Set((()=>{try{return JSON.parse(localStorage.getItem("kz-show"))||[]}catch(e){return[]}})())};var N=(e)=>document.getElementById(e),Zm=(e)=>String(e).replace(/[&<>"]/g,(t)=>({"&":"&","<":"<",">":">",'"':"""})[t]);class Gr{s;constructor(e){this.s=e}toString(){return this.s}}var bt=(e)=>new Gr(String(e)),th=(e)=>e instanceof Gr?e.s:Array.isArray(e)?e.map(th).join(""):e==null||e===!1?"":Zm(e),R=(e,...t)=>bt(e.reduce((i,n,s)=>i+th(t[s-1])+n));var Pw=bt('<div aria-busy="true" aria-label="Loading"><span class="skel" style="height:16px;width:35%;margin:20px 0 14px"></span>'+'<span class="skel" style="height:44px;margin-bottom:10px"></span>'.repeat(4)+"</div>");function Xs(e){let t=document.createElement("dialog");return t.className="kz",t.innerHTML=`<form class="inl" method="dialog">${e}</form>`,t.onclose=()=>t.remove(),t.onclick=(i)=>{if(i.target===t)t.close()},document.body.appendChild(t),t.showModal(),t}var Mm=!1;try{Mm=localStorage.getItem("kz-res-disk")==="1"}catch{}var mi=(e,t)=>{let i=t-e;return i<3600000?Math.round(i/60000)+"m":i<86400000?Math.round(i/3600000)+"h":Math.round(i/86400000)+"d"};var Kr=(e)=>typeof e==="string"?[e]:e.kids.flatMap(Kr);var Jr=(e,t)=>`ws:${e}:${t}`,rh=(e)=>e.kind==="run"&&e.status==="done"&&e.accept!=="needs"&&!e.archived&&e.git==="pending";var oh=3000,Ms=new Map,vn=(e)=>e.key+"@"+(e.born??0),ih={conflict:0,failed:0,asking:0,working:1,done:2},Zs={conflict:"Conflict",failed:"Land failed",asking:"Asking",working:"Working",done:"Done"},Rm={conflict:"fail",failed:"fail",asking:"wait",working:"build",done:"done"};function jm(e,t,i=Ms){if(e.land)return e.land==="conflict"?"conflict":"failed";if(e.asking)return"asking";if(e.busy)return i.set(vn(e),t),"working";return t-(i.get(vn(e))??-1/0)<oh?"working":"done"}var lh=(e,t,i=Ms)=>Math.min(1/0,...e.filter((n)=>!n.asking&&!n.busy&&i.has(vn(n))).map((n)=>oh-(t-i.get(vn(n)))).filter((n)=>n>0)),ah=(e,t=Ms)=>{let i=new Set(e.map(vn));for(let n of t.keys())if(!i.has(n))t.delete(n)},hh=(e,t,i,n,s,r=Ms)=>e.filter((o)=>o.dir===t&&n({state:o.dir,ws:o.ws})===i).map((o)=>({a:o,st:jm(o,s,r)})).sort((o,l)=>ih[o.st]-ih[l.st]),nh=({a:e,st:t})=>(e.land?"":e.last)||`${Zs[t]} - ${e.name}`,sh=(e,t)=>!e?"":t-e<60000?"now":mi(e,t),Lm=(e,t)=>e+"\x00"+t;function ch(e,t,i){let n=Lm(t,i);if(e[n])delete e[n];else e[n]=!0;return e}var Em=["claude","codex","gemini"],Hr=(e)=>R`<svg aria-hidden="true"><use href="#i-${Em.includes(e.agent??"")?e.agent:"ai"}"/></svg>`,Fr=(e)=>R`<i class="si ${Rm[e]}"></i>`,_m=R`<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 9l6 6 6-6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`;function fh(e,t,i,n,s){if(!e.length)return"";let r=R`data-dir="${n}" data-ws="${s}"`;if(e.length===1){let a=e[0];return R`<div class="wag"><button type="button" class="aone" data-term="${a.a.key}" ${r} title="${a.a.name}: open its terminal">${Fr(a.st)}${Hr(a.a)}<span class="atx">${Zs[a.st]} - ${a.a.name}</span><small>${sh(a.a.at,t)}</small></button></div>`}let o=R`<button type="button" class="wchev${i?" on":""}" data-wopen ${r} aria-expanded="${String(i)}" aria-label="${String(e.length)} agents: ${i?"hide":"show"} the list">${_m}</button>`;if(i)return R`<div class="wag"><span class="aht">${String(e.length)} agents</span>${o}</div><div class="alist">${e.map((a)=>R`<button type="button" class="arow" data-term="${a.a.key}" ${r} title="${nh(a)}">${Fr(a.st)}${Hr(a.a)}<span class="atx">${nh(a)}</span><small>${sh(a.a.at,t)}</small></button>`)}</div>`;let l=["conflict","failed","asking","working","done"].map((a)=>({st:a,rs:e.filter((h)=>h.st===a)})).filter((a)=>a.rs.length);return R`<div class="wag"><span class="chips">${l.map((a)=>R`<span class="chip">${Fr(a.st)}${a.rs.map((h)=>R`<button type="button" class="amark" data-term="${h.a.key}" ${r} title="${h.a.name} - ${Zs[a.st]}: open its terminal" aria-label="${h.a.name} - ${Zs[a.st]}: open its terminal">${Hr(h.a)}</button>`)}</span>`)}</span>${o}</div>`}function eo(e){return e.toLowerCase().trim().replace(/[^a-z0-9/._-]+/g,"-").replace(/\.{2,}/g,".").replace(/\/{2,}/g,"/").replace(/(^|\/)[-.]+/g,"$1").slice(0,60).replace(/[-./]+(\/|$)/g,"$1").replace(/\/$/,"").replace(/\.lock(\/|$)/g,"-lock$1")}var zm=(e)=>e.includes("\\")?"\\":"/";async function Ut(e,t){try{let i=await fetch(e,t?{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}:void 0),n=await i.json().catch(()=>({}));return{ok:i.ok,d:i.ok?n:{error:n.error||n.why||"that did not work"}}}catch{return{ok:!1,d:{error:"kaizen is offline"}}}}function Pn(e={}){let t=Xs(""),i=t.querySelector("form");t.setAttribute("aria-label","Add a project");let n=e.start==="ws",s=(u)=>i.elements.namedItem(u),r=(u,d,p,O)=>(u.disabled=d,u.textContent=d?p:O),o=n?"":R`<button type="button" class="btn ghost" data-a="back">Back to add options</button>`,l=(u)=>R`<small class="att err" role="alert"></small><div class="row">${o}<button type="button" class="btn ghost" data-a="x">Cancel</button><button class="btn pri" data-a="go">${u}</button></div>`,a=(u)=>i.querySelector(".err").textContent=u,h=(u,d)=>{a(d);try{localStorage.setItem("kz-proj",u)}catch{}setTimeout(()=>location.href="/",900)},c=async(u,d)=>{let p=await Ut("/pick-folder",{});if(p.d.path)u.value=d?p.d.path.replace(/[\\/]+$/,"")+zm(p.d.path)+d():p.d.path},f=(u)=>{let d=uh();if(t.classList.toggle("wsnew",u==="ws"),u==="menu")i.innerHTML=R`<b>Add a project</b><small class="att">Add a project to get started with kaizen.</small><button type="button" class="btn opt" data-go="folder"><b>Existing folder</b><small>A project, a Git repo, or any folder</small></button><small class="att">Other ways to add</small><button type="button" class="btn opt" data-go="clone"><b>Clone from URL</b><small>Clone a remote Git repository</small></button><button type="button" class="btn opt" data-go="create"><b>Create new project</b><small>Start from an empty folder</small></button>${d.length?R`<button type="button" class="btn opt" data-go="ws"><b>New workspace</b><small>A branch in its own folder, in a project you have</small></button>`:""}<div class="row"><button type="button" class="btn ghost" data-a="x">Cancel</button></div>`.toString(),i.querySelectorAll("[data-go]").forEach((O)=>O.onclick=()=>f(O.dataset.go)),i.onsubmit=(O)=>O.preventDefault();else if(u==="folder")i.innerHTML=R`<b>Existing folder</b><small class="att">Pick a folder, or type its path. A .kaizen folder is added to it.</small><div class="row"><input name="path" placeholder="/path/to/folder" aria-label="Folder" autocomplete="off" spellcheck="false" required><button type="button" class="btn ghost" data-a="pick">Pick…</button></div>${l("Add project")}`.toString(),s("path").focus(),i.onsubmit=async(O)=>{O.preventDefault();let g=i.querySelector("[data-a=go]");r(g,!0,"Adding...","Add project");let b=await Ut("/add-project",{path:s("path").value.trim()});r(g,!1,"","Add project"),b.ok?h(b.d.dir,b.d.already?"Project already added":"Project added"):a(b.d.error)},i.querySelector("[data-a=pick]").onclick=()=>c(s("path"));else if(u==="clone"){i.innerHTML=R`<b>Clone from URL</b><small class="att">Enter the Git URL (https or ssh) and choose where to clone it.</small><input name="url" placeholder="https://github.com/user/repo.git" aria-label="Git URL" autocomplete="off" spellcheck="false" required><div class="row"><input name="to" placeholder="Folder to clone into" aria-label="Clone into" autocomplete="off" spellcheck="false"><button type="button" class="btn ghost" data-a="pick">Pick…</button></div>${l("Clone")}`.toString(),s("url").focus();let O="",g="",b=async()=>{let y=s("url").value.trim();if(!y)return!1;let S=await Ut("/clone",{url:y,check:!0});if(!S.ok)return a(S.d.error),!1;if(a(""),O=S.d.name,!s("to").value.trim()||s("to").value===g)s("to").value=g=S.d.to;return!0};s("url").onchange=b,i.querySelector("[data-a=pick]").onclick=async()=>await b()?c(s("to"),()=>O):s("url").focus(),i.onsubmit=async(y)=>{if(y.preventDefault(),!await b())return;let S=i.querySelector("[data-a=go]");r(S,!0,"Cloning...","Clone");let x=await Ut("/clone",{url:s("url").value.trim(),to:s("to").value.trim()||void 0});r(S,!1,"","Clone"),x.ok?h(x.d.dir,"Cloned"):a(x.d.error)}}else if(u==="create"){i.innerHTML=R`<b>Create a new project</b><small class="att">Name it and kaizen will create the folder with a .kaizen inside.</small><input name="name" placeholder="my-project" aria-label="Name" autocomplete="off" spellcheck="false" required><div class="row"><input name="to" placeholder="Folder to create" aria-label="Create in" autocomplete="off" spellcheck="false"><button type="button" class="btn ghost" data-a="pick">Pick…</button></div><label class="att"><input type="checkbox" name="git" checked> Git repository</label>${l("Create project")}`.toString(),s("name").focus();let O="";s("name").oninput=async()=>{let g=s("name").value.trim();if(!g||/[\\/:*?"<>|]/.test(g)||s("to").value.trim()&&s("to").value!==O)return;let b=await Ut("/new-project",{name:g,check:!0});if(b.ok&&s("name").value.trim()===g)s("to").value=O=b.d.to},i.querySelector("[data-a=pick]").onclick=()=>c(s("to"),()=>s("name").value.trim()),i.onsubmit=async(g)=>{g.preventDefault();let b=i.querySelector("[data-a=go]");r(b,!0,"Creating...","Create project");let y=await Ut("/new-project",{name:s("name").value.trim(),to:s("to").value.trim()||void 0,git:s("git").checked});if(r(b,!1,"","Create project"),!y.ok)return a(y.d.error);h(y.d.dir,y.d.git===!1?"Project created, but git init failed":"Project created")}}else{let O=d.some((S)=>S.dir===e.dir)?e.dir:d[0]?.dir,g=/Mac/.test(navigator.platform)?"⌘":"Ctrl";i.innerHTML=R`<b>New workspace</b><label class="att">Project<select name="project" aria-label="Project">${d.map((S)=>R`<option value="${S.dir}"${S.dir===O?" selected":""}>${S.name}</option>`)}</select></label><div class="wsfrom"><span class="att" id="wsfl">Create from <i>[Optional]</i></span><label class="wsbase">from <select name="base" aria-label="Start from branch"></select></label></div><input name="name" placeholder="What is this workspace for?" aria-labelledby="wsfl" autocomplete="off" spellcheck="false"><details class="wsadv"><summary>Advanced</summary><label class="att">Branch name<input name="branch" placeholder="feature/my-branch" aria-label="Branch name" autocomplete="off" spellcheck="false"></label></details><small class="att err" role="alert"></small><div class="row">${o}<button type="button" class="btn ghost" data-a="x">Cancel</button><button class="btn pri" data-a="go">Create workspace</button><kbd class="wskey" aria-hidden="true">${g} ↵</kbd></div>`.toString(),s("name").focus();let b=i.elements.namedItem("base");s("name").oninput=()=>s("branch").placeholder=eo(s("name").value)||"feature/my-branch";let y=async()=>{let S=await Ut("/branches?dir="+encodeURIComponent(s("project").value)),{def:x="",branches:v=[]}=S.ok?S.d:{};b.innerHTML=v.map((X)=>R`<option${X===x?" selected":""}>${X}</option>`.toString()).join("")||'<option value="">current branch</option>'};i.elements.namedItem("project").onchange=y,y(),i.onkeydown=(S)=>{if(S.key==="Enter"&&(S.ctrlKey||S.metaKey))S.preventDefault(),i.requestSubmit()},i.onsubmit=async(S)=>{S.preventDefault();let x=s("project").value,v=i.querySelector("[data-a=go]");if(v.disabled)return;a("");let X=s("branch").value.trim()||eo(s("name").value)||"workspace-"+Math.random().toString(36).slice(2,6);r(v,!0,"Creating...","Create workspace");let T=await Ut("/worktree",{dir:x,branch:X,base:b.value||void 0});r(v,!1,"","Create workspace"),T.ok?(t.close(),location.href=Vt(x,T.d.path)):a(T.d.error)}}i.querySelector("[data-a=x]").onclick=()=>t.close();let p=i.querySelector("[data-a=back]");if(p)p.onclick=()=>f("menu")};f(e.start??"menu")}function dh(e,t){let i=t.toLowerCase().split(/\s+/).filter(Boolean);if(!i.length)return e;let n=t.trim().toLowerCase(),s=(r)=>{let o=r.title.toLowerCase();return o.startsWith(n)?0:o.includes(n)?1:2};return e.filter((r)=>{let o=(r.title+" "+(r.sub??"")+" "+r.hay).toLowerCase();return i.every((l)=>o.includes(l))}).sort((r,o)=>s(r)-s(o)||(o.at??0)-(r.at??0))}var js=(e,t)=>!dispatchEvent(new CustomEvent(e,{cancelable:!0,detail:t})),gi=(e,t)=>()=>{let i=document.querySelector(`.rail a[data-view="${e}"]`);i?i.click():location.href=t},ph=(e,t)=>{if(!js("kz-open-ws",{dir:e,ws:t}))location.href=Vt(e,t)},mh=()=>{try{return JSON.parse(localStorage.getItem("kz-runtabs")||"{}")}catch{return{}}},Ym=(e,t,i)=>{if(js("kz-open-tab",{dir:e,ws:t,id:i}))return;let n=mh(),s=n[Jr(e,t)],r=s?.screens?.find((o)=>Kr(o.tree).includes(i));if(r)try{s.on=r.id,localStorage.setItem("kz-runtabs",JSON.stringify(n))}catch{}location.href=Vt(e,t)},qm=["local","preview","note","history","shell"],Dm=(e)=>{try{return localStorage.getItem("kz-browse:"+e)?.replace(/^https?:\/\//,"").replace(/\/$/,"")}catch{}},Wm={ws:'<circle cx="6" cy="6" r="2"/><circle cx="6" cy="18" r="2"/><circle cx="18" cy="8" r="2"/><path d="M6 8v8M18 10c0 4-6 3-12 6"/>',run:'<path d="M5 4l14 8-14 8z"/>',idea:'<path d="M9 18h6M10 21h4M12 3a6 6 0 0 0-4 10.5c.7.7 1 1.5 1 2.5h6c0-1 .3-1.8 1-2.5A6 6 0 0 0 12 3z"/>',chat:'<path d="M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.6A8 8 0 1 1 21 12z"/>',term:'<path d="M4 17l6-5-6-5M12 19h8"/>',proj:'<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>',page:'<rect x="4" y="4" width="16" height="16" rx="2"/><path d="M4 9h16"/>',act:'<path d="M13 3L5 14h6l-1 7 8-11h-6z"/>',tab:'<rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 9h8V5"/>',plus:'<path d="M12 5v14M5 12h14"/>',search:'<circle cx="11" cy="11" r="7"/><path d="M20 20l-4-4"/>'},gh=(e)=>bt(`<svg viewBox="0 0 24 24" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${Wm[e]}</g></svg>`),bh=[];function Bm(){let{cards:e,projects:t=[],agents:i=[]}=kh(),n=Date.now(),s=new URLSearchParams(location.search),r=s.get("id")&&e.find((u)=>u.kind==="run"&&u.state===s.get("dir")&&u.id===s.get("id")),o=s.get("ws")??(r?Yi(r,t):null),l=[],a=mh(),h=new Map;for(let u of e){let d=u.state+"\x00"+Yi(u,t);h.set(d,Math.max(h.get(d)??0,u.moved??0))}for(let u of t){let d=Ve(u.dir,t);for(let p of u.workspaces??[]){let O=s.get("dir")===u.dir&&o===p.path,g=h.get(u.dir+"\x00"+p.path);l.push({group:O?"Current":"Workspaces",title:bi(p),sub:d,when:g?mi(g,n):void 0,hay:`${bi(p)} ${d} ${p.path} workspace`,at:O?1/0:g??0,ico:"ws",act:()=>ph(u.dir,p.path)});let b=Jr(u.dir,p.path),y=a[b];for(let S of y?.tabs??[]){if(!qm.includes(S.kind)||y.hidden?.includes(S.id))continue;let x=S.kind==="local"&&Dm(b)||S.title;l.push({group:"Tabs",title:x,sub:`${bi(p)} · ${d}`,hay:`${x} ${S.title} ${S.kind} ${S.note??""} ${bi(p)} ${d} tab`,ico:"tab",act:()=>Ym(u.dir,p.path,S.id)})}}l.push({group:"Projects",title:d,hay:`${d} ${u.dir} project`,ico:"proj",act:()=>{let p=u.workspaces?.find((O)=>O.main)??u.workspaces?.[0];p?ph(u.dir,p.path):gi("board","/?view=board")()}})}for(let u of e.filter((d)=>!d.archived)){let d=yi(u);l.push({group:u.kind==="run"?"Runs":"Tasks",title:no(u)||u.id,sub:Ve(u.state,t),when:u.moved?mi(u.moved,n):void 0,hay:`${no(u)} ${u.id??""} ${u.text??""} ${Ve(u.state,t)} ${d}`,at:u.moved??0,dot:d,ico:u.kind==="run"?"run":"idea",act:()=>{if(!js("kz-open-card",{dir:u.state,id:u.kind==="run"?u.id:void 0,text:u.text}))location.href=Sh(u)}})}for(let u of bh){let d=Date.parse(u.updated)||0;l.push({group:"Chats & terminals",title:u.title||"Chat",sub:u.project?Ve(u.project,t):void 0,when:d?mi(d,n):void 0,hay:`${u.title} chat ${u.project??""}`,at:d,dot:u.busy?"build":void 0,ico:"chat",act:()=>{try{sessionStorage.setItem("kz-chat",u.id)}catch{}gi("home","/")()}})}for(let u of i)l.push({group:"Chats & terminals",title:u.name||u.agent||"Terminal",sub:Ve(u.dir,t),hay:`${u.name} ${u.agent??""} ${u.run??""} ${u.last??""} ${Ve(u.dir,t)} terminal agent`,at:u.at??u.born??0,dot:u.asking?"wait":u.busy?"build":"done",ico:"term",act:()=>{if(!js("kz-open-term",{dir:u.dir,ws:u.ws,key:u.key}))location.href=Vt(u.dir,u.ws??"")}});let c=(u)=>()=>N(u)?.click(),f=[["Home","page",gi("home","/"),"chat"],["Icebox","page",gi("sources","/?view=icebox"),"requests sources gathered"],["Tasks","page",gi("tasks","/?view=tasks"),"backlog"],["Board","page",gi("board","/?view=board"),"kanban runs"],["Notes","page",()=>location.href="/notebook","notebook docs"],["Settings","page",gi("settings","/?view=settings"),"preferences config"],["New task","act",()=>N("newtop")?N("newtop").click():location.href="/?view=board","create add run"],["Add a project","act",()=>Pn({dir:null}),"clone folder create workspace"],["Toggle theme","act",c("themet"),"dark light"],["Collapse or expand menu","act",c("fold"),"sidebar rail"],["Keyboard shortcuts","act",c("kbd"),"keys help"],["Report an issue","act",()=>open("/issue","_blank","noopener"),"bug feedback"]];for(let[u,d,p,O]of f)l.push({group:"Actions",title:u,hay:`${u} ${O??""}`,ico:d,act:p});return l}var Im=["Current","Workspaces","Tabs","Chats & terminals","Runs","Tasks","Projects","Actions"],Um={Workspaces:5,Tabs:4,"Chats & terminals":5,Runs:5,Tasks:3,Projects:5},H=null,nt=[],st=0;function Rs(){let e=H.querySelector("input").value,t=Bm(),i=e.trim()?dh(t,e):t.slice().sort((o,l)=>(l.at??0)-(o.at??0));nt=[];let n=e.trim()?[...new Set(i.map((o)=>o.group))]:Im;for(let o of n){let l=i.filter((a)=>a.group===o);nt.push(...l.slice(0,e.trim()?8:Um[o]??l.length))}if(e.trim())nt.push({group:"Create",title:`New task "${e.trim()}"`,hay:"",ico:"plus",act:()=>Vm(e.trim())});st=Math.min(st,nt.length-1);let s=H.querySelector(".gs-list"),r="";s.innerHTML=String(R`${nt.map((o,l)=>{let a=o.group!==r?(r=o.group,R`<div class="gs-h" role="presentation">${o.group}</div>`):"";return R`${a}<div class="gs-i" role="option" id="gs-${l}" data-n="${l}" aria-selected="${String(l===st)}">${gh(o.ico)}${o.dot?R`<span class="si ${o.dot}"></span>`:""}<span class="gs-t">${o.title}</span>${o.sub?R`<span class="gs-s">${o.sub}</span>`:""}${o.when?R`<span class="gs-w">${o.when}</span>`:""}</div>`})}${nt.length===1&&e.trim()?R`<div class="gs-none">No results</div>`:""}`),io(st),H.querySelector(".gs-live").textContent=`${nt.length} result${nt.length===1?"":"s"} found`}function io(e){H.querySelector(`#gs-${st}`)?.setAttribute("aria-selected","false"),st=e;let t=H.querySelector(`#gs-${e}`);t?.setAttribute("aria-selected","true"),H.querySelector("input").setAttribute("aria-activedescendant","gs-"+e),t?.scrollIntoView({block:"nearest"})}function Vm(e){if(!N("newtop"))return void(location.href="/?view=board");N("newtop").click();let t=document.querySelector("dialog[open] textarea");if(t)t.value=e,t.dispatchEvent(new Event("input",{bubbles:!0}))}function Oh(e){let t=nt[e];if(!t)return;H.close(),t.act()}function to(){if(H)return H.querySelector("input").focus();H=document.createElement("dialog"),H.className="gs",H.setAttribute("aria-label","Search"),H.innerHTML=String(R`<div class="gs-box"><div class="gs-q">${gh("search")}<input type="text" placeholder="Search" aria-label="Search" role="combobox" aria-expanded="true" aria-controls="gs-list" autocomplete="off" spellcheck="false"></div><div class="gs-list" id="gs-list" role="listbox"></div><span class="gs-live" role="status" aria-live="polite"></span></div>`),document.body.append(H);let e=H.querySelector("input");st=0,e.oninput=()=>(st=0,Rs()),e.onkeydown=(i)=>{let n={ArrowDown:1,ArrowUp:-1}[i.key]??(i.ctrlKey&&i.key==="n"?1:i.ctrlKey&&i.key==="p"?-1:0);if(n)i.preventDefault(),io((st+n+nt.length)%nt.length);else if(i.key==="Enter")i.preventDefault(),Oh(st)};let t=H.querySelector(".gs-list");t.onclick=(i)=>{let n=i.target.closest(".gs-i");if(n)Oh(+n.dataset.n)},t.onpointermove=(i)=>{let n=i.target.closest(".gs-i");if(n&&+n.dataset.n!==st)io(+n.dataset.n)},H.onclick=(i)=>i.target===H&&H.close(),H.onclose=()=>(H.remove(),H=null),H.showModal(),Rs(),fetch("/chats").then((i)=>i.json()).then((i)=>{if(bh=i.chats??[],H)Rs()}).catch(()=>{})}var Nm=`dialog.gs{border:0;padding:0;margin:14vh auto auto;background:none;width:min(560px,calc(100vw - 32px));color:var(--ink);overflow:visible}
|
|
3
3
|
dialog.gs::backdrop{background:rgb(0 0 0/.35)}
|
|
4
4
|
.gs-box{display:flex;flex-direction:column;max-height:min(480px,72vh);background:var(--bg);border:1px solid var(--line);border-radius:10px;box-shadow:0 16px 40px rgb(0 0 0/.25);overflow:hidden}
|
package/web/term.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/* kaizen terminal
|
|
1
|
+
/* kaizen terminal ada6d903316fe7d4 -- generated by bun run build:web from web/term.ts; do not edit */
|
|
2
2
|
(()=>{var{defineProperty:Fo,getOwnPropertyDescriptor:sl}=Object,rl=(e,t)=>{for(var i in t)Fo(e,i,{get:t[i],enumerable:!0})},he=(e,t,i,s)=>{for(var r=s>1?void 0:s?sl(t,i):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(r=(s?o(t,i,r):o(r))||r);return s&&r&&Fo(t,i,r),r},O=(e,t)=>(i,s)=>t(i,s,e),Pn="Terminal input",dr={get:()=>Pn,set:(e)=>Pn=e},On="Too much output to announce, navigate to rows manually to read",ur={get:()=>On,set:(e)=>On=e};function nl(e){return e.replace(/\r?\n/g,"\r")}function ol(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function al(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function hl(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let r=e.clipboardData.getData("text/plain");Wo(r,t,i,s)}}function Wo(e,t,i,s){e=nl(e),e=ol(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function zo(e,t,i){let s=i.getBoundingClientRect(),r=e.clientX-s.left-10,n=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${r}px`,t.style.top=`${n}px`,t.style.zIndex="1000",t.focus()}function In(e,t,i,s,r){zo(e,t,i),r&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function Nt(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Ss(e,t=0,i=e.length){let s="";for(let r=t;r<i;++r){let n=e[r];n>65535?(n-=65536,s+=String.fromCharCode((n>>10)+55296)+String.fromCharCode(n%1024+56320)):s+=String.fromCharCode(n)}return s}var ll=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let i=e.length;if(!i)return 0;let s=0,r=0;if(this._interim){let n=e.charCodeAt(r++);56320<=n&&n<=57343?t[s++]=(this._interim-55296)*1024+n-56320+65536:(t[s++]=this._interim,t[s++]=n),this._interim=0}for(let n=r;n<i;++n){let o=e.charCodeAt(n);if(55296<=o&&o<=56319){if(++n>=i)return this._interim=o,s;let a=e.charCodeAt(n);56320<=a&&a<=57343?t[s++]=(o-55296)*1024+a-56320+65536:(t[s++]=o,t[s++]=a);continue}o!==65279&&(t[s++]=o)}return s}},cl=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let s=0,r,n,o,a,l=0,h=0;if(this.interim[0]){let u=!1,g=this.interim[0];g&=(g&224)===192?31:(g&240)===224?15:7;let p=0,b;for(;(b=this.interim[++p]&63)&&p<4;)g<<=6,g|=b;let k=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,B=k-p;for(;h<B;){if(h>=i)return 0;if(b=e[h++],(b&192)!==128){h--,u=!0;break}else this.interim[p++]=b,g<<=6,g|=b&63}u||(k===2?g<128?h--:t[s++]=g:k===3?g<2048||g>=55296&&g<=57343||g===65279||(t[s++]=g):g<65536||g>1114111||(t[s++]=g)),this.interim.fill(0)}let d=i-4,c=h;for(;c<i;){for(;c<d&&!((r=e[c])&128)&&!((n=e[c+1])&128)&&!((o=e[c+2])&128)&&!((a=e[c+3])&128);)t[s++]=r,t[s++]=n,t[s++]=o,t[s++]=a,c+=4;if(r=e[c++],r<128)t[s++]=r;else if((r&224)===192){if(c>=i)return this.interim[0]=r,s;if(n=e[c++],(n&192)!==128){c--;continue}if(l=(r&31)<<6|n&63,l<128){c--;continue}t[s++]=l}else if((r&240)===224){if(c>=i)return this.interim[0]=r,s;if(n=e[c++],(n&192)!==128){c--;continue}if(c>=i)return this.interim[0]=r,this.interim[1]=n,s;if(o=e[c++],(o&192)!==128){c--;continue}if(l=(r&15)<<12|(n&63)<<6|o&63,l<2048||l>=55296&&l<=57343||l===65279)continue;t[s++]=l}else if((r&248)===240){if(c>=i)return this.interim[0]=r,s;if(n=e[c++],(n&192)!==128){c--;continue}if(c>=i)return this.interim[0]=r,this.interim[1]=n,s;if(o=e[c++],(o&192)!==128){c--;continue}if(c>=i)return this.interim[0]=r,this.interim[1]=n,this.interim[2]=o,s;if(a=e[c++],(a&192)!==128){c--;continue}if(l=(r&7)<<18|(n&63)<<12|(o&63)<<6|a&63,l<65536||l>1114111)continue;t[s++]=l}}return s}},Ho="",Ft=" ",Oi=class e{constructor(){this.fg=0,this.bg=0,this.extended=new cs}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},cs=class e{constructor(t=0,i=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=i}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},et=class e extends Oi{constructor(){super(...arguments);this.content=0,this.fg=0,this.bg=0,this.extended=new cs,this.combinedData=""}static fromCharData(t){let i=new e;return i.setFromCharData(t),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Nt(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let r=t[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(s-55296)*1024+r-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Nn="di$target",_r="di$dependencies",Ys=new Map;function dl(e){return e[_r]||[]}function Me(e){if(Ys.has(e))return Ys.get(e);let t=function(i,s,r){if(arguments.length!==3)throw Error("@IServiceName-decorator can only be used to decorate a parameter");ul(t,i,r)};return t._id=e,Ys.set(e,t),t}function ul(e,t,i){t[Nn]===t?t[_r].push({id:e,index:i}):(t[_r]=[{id:e,index:i}],t[Nn]=t)}var Ne=Me("BufferService"),$o=Me("CoreMouseService"),Qt=Me("CoreService"),_l=Me("CharsetService"),Hr=Me("InstantiationService"),Uo=Me("LogService"),Fe=Me("OptionsService"),Ko=Me("OscLinkService"),fl=Me("UnicodeService"),Ii=Me("DecorationService"),fr=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let s=[],r=this._optionsService.rawOptions.linkHandler,n=new et,o=i.getTrimmedLength(),a=-1,l=-1,h=!1;for(let d=0;d<o;d++)if(!(l===-1&&!i.hasContent(d))){if(i.loadCell(d,n),n.hasExtendedAttrs()&&n.extended.urlId)if(l===-1){l=d,a=n.extended.urlId;continue}else h=n.extended.urlId!==a;else l!==-1&&(h=!0);if(h||l!==-1&&d===o-1){let c=this._oscLinkService.getLinkData(a)?.uri;if(c){let u={start:{x:l+1,y:e},end:{x:d+(!h&&d===o-1?1:0),y:e}},g=!1;if(!r?.allowNonHttpProtocols)try{let p=new URL(c);["http:","https:"].includes(p.protocol)||(g=!0)}catch{g=!0}g||s.push({text:c,range:u,activate:(p,b)=>r?r.activate(p,b,u):gl(p,b),hover:(p,b)=>r?.hover?.(p,b,u),leave:(p,b)=>r?.leave?.(p,b,u)})}h=!1,n.hasExtendedAttrs()&&n.extended.urlId?(l=d,a=n.extended.urlId):(l=-1,a=-1)}}t(s)}};fr=he([O(0,Ne),O(1,Fe),O(2,Ko)],fr);function gl(e,t){if(confirm(`Do you want to navigate to ${t}?
|
|
3
3
|
|
|
4
4
|
WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var ws=Me("CharSizeService"),wt=Me("CoreBrowserService"),$r=Me("MouseService"),bt=Me("RenderService"),pl=Me("SelectionService"),qo=Me("CharacterJoinerService"),ni=Me("ThemeService"),Vo=Me("LinkProviderService"),vl=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?Fn.isErrorNoTelemetry(e)?new Fn(e.message+`
|
package/web/video.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/* kaizen video page
|
|
1
|
+
/* kaizen video page ada6d903316fe7d4 -- generated by bun run build:web from web/video.ts; do not edit */
|
|
2
2
|
(()=>{var ht=null,bt=(e)=>{ht=e};function dn(e,t,n){Oe++,ht?.(e,t,n)}var Oe=0,gt="",De=!1,we=!1;async function qe(){if(De){we=!0;return}De=!0;do{we=!1;let e=Oe;try{let t=await fetch("/state?all=1");if(!t.ok)continue;let n=await t.text(),a=n.replace(/"now":\d+\}$/,"");if(a===gt)continue;let{cards:s,projects:r,rail:l,agents:i}=JSON.parse(n);if(!we&&e===Oe)gt=a,dn(s,[...r,...l??[]],i)}catch{}}while(we);De=!1}var un={S:{project:null,projects:[],cards:[],now:Date.now(),all:!1,dir:null},all:new URLSearchParams(location.search).get("all")!=="0",dir:null,openKey:null,mode:null,modeKey:null,menuKey:null,flash:new Set,tab:"request",lastTab:"request",runDoc:null,clearMenu:!1,sevMenu:!1,wantTerm:null,wantPty:null,shells:[],setQ:"",setScope:"all",setPage:null,setBack:!1,pageGen:0,PL:[],shown:new Set((()=>{try{return JSON.parse(localStorage.getItem("kz-show"))||[]}catch(e){return[]}})())};var M=(e)=>document.getElementById(e),pn=(e)=>String(e).replace(/[&<>"]/g,(t)=>({"&":"&","<":"<",">":">",'"':"""})[t]);class Fe{s;constructor(e){this.s=e}toString(){return this.s}}var K=(e)=>new Fe(String(e)),vt=(e)=>e instanceof Fe?e.s:Array.isArray(e)?e.map(vt).join(""):e==null||e===!1?"":pn(e),w=(e,...t)=>K(e.reduce((n,a,s)=>n+vt(t[s-1])+a));var os=K('<div aria-busy="true" aria-label="Loading"><span class="skel" style="height:16px;width:35%;margin:20px 0 14px"></span>'+'<span class="skel" style="height:44px;margin-bottom:10px"></span>'.repeat(4)+"</div>");function $e(e){let t=document.createElement("dialog");return t.className="kz",t.innerHTML=`<form class="inl" method="dialog">${e}</form>`,t.onclose=()=>t.remove(),t.onclick=(n)=>{if(n.target===t)t.close()},document.body.appendChild(t),t.showModal(),t}var mn=!1;try{mn=localStorage.getItem("kz-res-disk")==="1"}catch{}var te=(e,t)=>{let n=t-e;return n<3600000?Math.round(n/60000)+"m":n<86400000?Math.round(n/3600000)+"h":Math.round(n/86400000)+"d"};var We=(e)=>typeof e==="string"?[e]:e.kids.flatMap(We);var Ve=(e,t)=>`ws:${e}:${t}`,kt=(e)=>e.kind==="run"&&e.status==="done"&&e.accept!=="needs"&&!e.archived&&e.git==="pending";var xt=3000,xe=new Map,me=(e)=>e.key+"@"+(e.born??0),yt={conflict:0,failed:0,asking:0,working:1,done:2},ke={conflict:"Conflict",failed:"Land failed",asking:"Asking",working:"Working",done:"Done"},fn={conflict:"fail",failed:"fail",asking:"wait",working:"build",done:"done"};function gn(e,t,n=xe){if(e.land)return e.land==="conflict"?"conflict":"failed";if(e.asking)return"asking";if(e.busy)return n.set(me(e),t),"working";return t-(n.get(me(e))??-1/0)<xt?"working":"done"}var Et=(e,t,n=xe)=>Math.min(1/0,...e.filter((a)=>!a.asking&&!a.busy&&n.has(me(a))).map((a)=>xt-(t-n.get(me(a)))).filter((a)=>a>0)),Mt=(e,t=xe)=>{let n=new Set(e.map(me));for(let a of t.keys())if(!n.has(a))t.delete(a)},St=(e,t,n,a,s,r=xe)=>e.filter((l)=>l.dir===t&&a({state:l.dir,ws:l.ws})===n).map((l)=>({a:l,st:gn(l,s,r)})).sort((l,i)=>yt[l.st]-yt[i.st]),wt=({a:e,st:t})=>(e.land?"":e.last)||`${ke[t]} - ${e.name}`,$t=(e,t)=>!e?"":t-e<60000?"now":te(e,t),hn=(e,t)=>e+"\x00"+t;function Lt(e,t,n){let a=hn(t,n);if(e[a])delete e[a];else e[a]=!0;return e}var bn=["claude","codex","gemini"],Ke=(e)=>w`<svg aria-hidden="true"><use href="#i-${bn.includes(e.agent??"")?e.agent:"ai"}"/></svg>`,Ue=(e)=>w`<i class="si ${fn[e]}"></i>`,vn=w`<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 9l6 6 6-6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`;function Tt(e,t,n,a,s){if(!e.length)return"";let r=w`data-dir="${a}" data-ws="${s}"`;if(e.length===1){let u=e[0];return w`<div class="wag"><button type="button" class="aone" data-term="${u.a.key}" ${r} title="${u.a.name}: open its terminal">${Ue(u.st)}${Ke(u.a)}<span class="atx">${ke[u.st]} - ${u.a.name}</span><small>${$t(u.a.at,t)}</small></button></div>`}let l=w`<button type="button" class="wchev${n?" on":""}" data-wopen ${r} aria-expanded="${String(n)}" aria-label="${String(e.length)} agents: ${n?"hide":"show"} the list">${vn}</button>`;if(n)return w`<div class="wag"><span class="aht">${String(e.length)} agents</span>${l}</div><div class="alist">${e.map((u)=>w`<button type="button" class="arow" data-term="${u.a.key}" ${r} title="${wt(u)}">${Ue(u.st)}${Ke(u.a)}<span class="atx">${wt(u)}</span><small>${$t(u.a.at,t)}</small></button>`)}</div>`;let i=["conflict","failed","asking","working","done"].map((u)=>({st:u,rs:e.filter((k)=>k.st===u)})).filter((u)=>u.rs.length);return w`<div class="wag"><span class="chips">${i.map((u)=>w`<span class="chip">${Ue(u.st)}${u.rs.map((k)=>w`<button type="button" class="amark" data-term="${k.a.key}" ${r} title="${k.a.name} - ${ke[u.st]}: open its terminal" aria-label="${k.a.name} - ${ke[u.st]}: open its terminal">${Ke(k.a)}</button>`)}</span>`)}</span>${l}</div>`}function Je(e){return e.toLowerCase().trim().replace(/[^a-z0-9/._-]+/g,"-").replace(/\.{2,}/g,".").replace(/\/{2,}/g,"/").replace(/(^|\/)[-.]+/g,"$1").slice(0,60).replace(/[-./]+(\/|$)/g,"$1").replace(/\/$/,"").replace(/\.lock(\/|$)/g,"-lock$1")}var yn=(e)=>e.includes("\\")?"\\":"/";async function Y(e,t){try{let n=await fetch(e,t?{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}:void 0),a=await n.json().catch(()=>({}));return{ok:n.ok,d:n.ok?a:{error:a.error||a.why||"that did not work"}}}catch{return{ok:!1,d:{error:"kaizen is offline"}}}}function fe(e={}){let t=$e(""),n=t.querySelector("form");t.setAttribute("aria-label","Add a project");let a=e.start==="ws",s=(o)=>n.elements.namedItem(o),r=(o,c,p,b)=>(o.disabled=c,o.textContent=c?p:b),l=a?"":w`<button type="button" class="btn ghost" data-a="back">Back to add options</button>`,i=(o)=>w`<small class="att err" role="alert"></small><div class="row">${l}<button type="button" class="btn ghost" data-a="x">Cancel</button><button class="btn pri" data-a="go">${o}</button></div>`,u=(o)=>n.querySelector(".err").textContent=o,k=(o,c)=>{u(c);try{localStorage.setItem("kz-proj",o)}catch{}setTimeout(()=>location.href="/",900)},L=async(o,c)=>{let p=await Y("/pick-folder",{});if(p.d.path)o.value=c?p.d.path.replace(/[\\/]+$/,"")+yn(p.d.path)+c():p.d.path},f=(o)=>{let c=jt();if(t.classList.toggle("wsnew",o==="ws"),o==="menu")n.innerHTML=w`<b>Add a project</b><small class="att">Add a project to get started with kaizen.</small><button type="button" class="btn opt" data-go="folder"><b>Existing folder</b><small>A project, a Git repo, or any folder</small></button><small class="att">Other ways to add</small><button type="button" class="btn opt" data-go="clone"><b>Clone from URL</b><small>Clone a remote Git repository</small></button><button type="button" class="btn opt" data-go="create"><b>Create new project</b><small>Start from an empty folder</small></button>${c.length?w`<button type="button" class="btn opt" data-go="ws"><b>New workspace</b><small>A branch in its own folder, in a project you have</small></button>`:""}<div class="row"><button type="button" class="btn ghost" data-a="x">Cancel</button></div>`.toString(),n.querySelectorAll("[data-go]").forEach((b)=>b.onclick=()=>f(b.dataset.go)),n.onsubmit=(b)=>b.preventDefault();else if(o==="folder")n.innerHTML=w`<b>Existing folder</b><small class="att">Pick a folder, or type its path. A .kaizen folder is added to it.</small><div class="row"><input name="path" placeholder="/path/to/folder" aria-label="Folder" autocomplete="off" spellcheck="false" required><button type="button" class="btn ghost" data-a="pick">Pick…</button></div>${i("Add project")}`.toString(),s("path").focus(),n.onsubmit=async(b)=>{b.preventDefault();let v=n.querySelector("[data-a=go]");r(v,!0,"Adding...","Add project");let y=await Y("/add-project",{path:s("path").value.trim()});r(v,!1,"","Add project"),y.ok?k(y.d.dir,y.d.already?"Project already added":"Project added"):u(y.d.error)},n.querySelector("[data-a=pick]").onclick=()=>L(s("path"));else if(o==="clone"){n.innerHTML=w`<b>Clone from URL</b><small class="att">Enter the Git URL (https or ssh) and choose where to clone it.</small><input name="url" placeholder="https://github.com/user/repo.git" aria-label="Git URL" autocomplete="off" spellcheck="false" required><div class="row"><input name="to" placeholder="Folder to clone into" aria-label="Clone into" autocomplete="off" spellcheck="false"><button type="button" class="btn ghost" data-a="pick">Pick…</button></div>${i("Clone")}`.toString(),s("url").focus();let b="",v="",y=async()=>{let C=s("url").value.trim();if(!C)return!1;let x=await Y("/clone",{url:C,check:!0});if(!x.ok)return u(x.d.error),!1;if(u(""),b=x.d.name,!s("to").value.trim()||s("to").value===v)s("to").value=v=x.d.to;return!0};s("url").onchange=y,n.querySelector("[data-a=pick]").onclick=async()=>await y()?L(s("to"),()=>b):s("url").focus(),n.onsubmit=async(C)=>{if(C.preventDefault(),!await y())return;let x=n.querySelector("[data-a=go]");r(x,!0,"Cloning...","Clone");let E=await Y("/clone",{url:s("url").value.trim(),to:s("to").value.trim()||void 0});r(x,!1,"","Clone"),E.ok?k(E.d.dir,"Cloned"):u(E.d.error)}}else if(o==="create"){n.innerHTML=w`<b>Create a new project</b><small class="att">Name it and kaizen will create the folder with a .kaizen inside.</small><input name="name" placeholder="my-project" aria-label="Name" autocomplete="off" spellcheck="false" required><div class="row"><input name="to" placeholder="Folder to create" aria-label="Create in" autocomplete="off" spellcheck="false"><button type="button" class="btn ghost" data-a="pick">Pick…</button></div><label class="att"><input type="checkbox" name="git" checked> Git repository</label>${i("Create project")}`.toString(),s("name").focus();let b="";s("name").oninput=async()=>{let v=s("name").value.trim();if(!v||/[\\/:*?"<>|]/.test(v)||s("to").value.trim()&&s("to").value!==b)return;let y=await Y("/new-project",{name:v,check:!0});if(y.ok&&s("name").value.trim()===v)s("to").value=b=y.d.to},n.querySelector("[data-a=pick]").onclick=()=>L(s("to"),()=>s("name").value.trim()),n.onsubmit=async(v)=>{v.preventDefault();let y=n.querySelector("[data-a=go]");r(y,!0,"Creating...","Create project");let C=await Y("/new-project",{name:s("name").value.trim(),to:s("to").value.trim()||void 0,git:s("git").checked});if(r(y,!1,"","Create project"),!C.ok)return u(C.d.error);k(C.d.dir,C.d.git===!1?"Project created, but git init failed":"Project created")}}else{let b=c.some((x)=>x.dir===e.dir)?e.dir:c[0]?.dir,v=/Mac/.test(navigator.platform)?"⌘":"Ctrl";n.innerHTML=w`<b>New workspace</b><label class="att">Project<select name="project" aria-label="Project">${c.map((x)=>w`<option value="${x.dir}"${x.dir===b?" selected":""}>${x.name}</option>`)}</select></label><div class="wsfrom"><span class="att" id="wsfl">Create from <i>[Optional]</i></span><label class="wsbase">from <select name="base" aria-label="Start from branch"></select></label></div><input name="name" placeholder="What is this workspace for?" aria-labelledby="wsfl" autocomplete="off" spellcheck="false"><details class="wsadv"><summary>Advanced</summary><label class="att">Branch name<input name="branch" placeholder="feature/my-branch" aria-label="Branch name" autocomplete="off" spellcheck="false"></label></details><small class="att err" role="alert"></small><div class="row">${l}<button type="button" class="btn ghost" data-a="x">Cancel</button><button class="btn pri" data-a="go">Create workspace</button><kbd class="wskey" aria-hidden="true">${v} ↵</kbd></div>`.toString(),s("name").focus();let y=n.elements.namedItem("base");s("name").oninput=()=>s("branch").placeholder=Je(s("name").value)||"feature/my-branch";let C=async()=>{let x=await Y("/branches?dir="+encodeURIComponent(s("project").value)),{def:E="",branches:U=[]}=x.ok?x.d:{};y.innerHTML=U.map((G)=>w`<option${G===E?" selected":""}>${G}</option>`.toString()).join("")||'<option value="">current branch</option>'};n.elements.namedItem("project").onchange=C,C(),n.onkeydown=(x)=>{if(x.key==="Enter"&&(x.ctrlKey||x.metaKey))x.preventDefault(),n.requestSubmit()},n.onsubmit=async(x)=>{x.preventDefault();let E=s("project").value,U=n.querySelector("[data-a=go]");if(U.disabled)return;u("");let G=s("branch").value.trim()||Je(s("name").value)||"workspace-"+Math.random().toString(36).slice(2,6);r(U,!0,"Creating...","Create workspace");let pe=await Y("/worktree",{dir:E,branch:G,base:y.value||void 0});r(U,!1,"","Create workspace"),pe.ok?(t.close(),location.href=X(E,pe.d.path)):u(pe.d.error)}}n.querySelector("[data-a=x]").onclick=()=>t.close();let p=n.querySelector("[data-a=back]");if(p)p.onclick=()=>f("menu")};f(e.start??"menu")}function Ct(e,t){let n=t.toLowerCase().split(/\s+/).filter(Boolean);if(!n.length)return e;let a=t.trim().toLowerCase(),s=(r)=>{let l=r.title.toLowerCase();return l.startsWith(a)?0:l.includes(a)?1:2};return e.filter((r)=>{let l=(r.title+" "+(r.sub??"")+" "+r.hay).toLowerCase();return n.every((i)=>l.includes(i))}).sort((r,l)=>s(r)-s(l)||(l.at??0)-(r.at??0))}var Me=(e,t)=>!dispatchEvent(new CustomEvent(e,{cancelable:!0,detail:t})),ne=(e,t)=>()=>{let n=document.querySelector(`.rail a[data-view="${e}"]`);n?n.click():location.href=t},Ht=(e,t)=>{if(!Me("kz-open-ws",{dir:e,ws:t}))location.href=X(e,t)},At=()=>{try{return JSON.parse(localStorage.getItem("kz-runtabs")||"{}")}catch{return{}}},wn=(e,t,n)=>{if(Me("kz-open-tab",{dir:e,ws:t,id:n}))return;let a=At(),s=a[Ve(e,t)],r=s?.screens?.find((l)=>We(l.tree).includes(n));if(r)try{s.on=r.id,localStorage.setItem("kz-runtabs",JSON.stringify(a))}catch{}location.href=X(e,t)},$n=["local","preview","note","history","shell"],kn=(e)=>{try{return localStorage.getItem("kz-browse:"+e)?.replace(/^https?:\/\//,"").replace(/\/$/,"")}catch{}},xn={ws:'<circle cx="6" cy="6" r="2"/><circle cx="6" cy="18" r="2"/><circle cx="18" cy="8" r="2"/><path d="M6 8v8M18 10c0 4-6 3-12 6"/>',run:'<path d="M5 4l14 8-14 8z"/>',idea:'<path d="M9 18h6M10 21h4M12 3a6 6 0 0 0-4 10.5c.7.7 1 1.5 1 2.5h6c0-1 .3-1.8 1-2.5A6 6 0 0 0 12 3z"/>',chat:'<path d="M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.6A8 8 0 1 1 21 12z"/>',term:'<path d="M4 17l6-5-6-5M12 19h8"/>',proj:'<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>',page:'<rect x="4" y="4" width="16" height="16" rx="2"/><path d="M4 9h16"/>',act:'<path d="M13 3L5 14h6l-1 7 8-11h-6z"/>',tab:'<rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 9h8V5"/>',plus:'<path d="M12 5v14M5 12h14"/>',search:'<circle cx="11" cy="11" r="7"/><path d="M20 20l-4-4"/>'},Rt=(e)=>K(`<svg viewBox="0 0 24 24" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${xn[e]}</g></svg>`),Bt=[];function En(){let{cards:e,projects:t=[],agents:n=[]}=Pt(),a=Date.now(),s=new URLSearchParams(location.search),r=s.get("id")&&e.find((o)=>o.kind==="run"&&o.state===s.get("dir")&&o.id===s.get("id")),l=s.get("ws")??(r?de(r,t):null),i=[],u=At(),k=new Map;for(let o of e){let c=o.state+"\x00"+de(o,t);k.set(c,Math.max(k.get(c)??0,o.moved??0))}for(let o of t){let c=z(o.dir,t);for(let p of o.workspaces??[]){let b=s.get("dir")===o.dir&&l===p.path,v=k.get(o.dir+"\x00"+p.path);i.push({group:b?"Current":"Workspaces",title:se(p),sub:c,when:v?te(v,a):void 0,hay:`${se(p)} ${c} ${p.path} workspace`,at:b?1/0:v??0,ico:"ws",act:()=>Ht(o.dir,p.path)});let y=Ve(o.dir,p.path),C=u[y];for(let x of C?.tabs??[]){if(!$n.includes(x.kind)||C.hidden?.includes(x.id))continue;let E=x.kind==="local"&&kn(y)||x.title;i.push({group:"Tabs",title:E,sub:`${se(p)} · ${c}`,hay:`${E} ${x.title} ${x.kind} ${x.note??""} ${se(p)} ${c} tab`,ico:"tab",act:()=>wn(o.dir,p.path,x.id)})}}i.push({group:"Projects",title:c,hay:`${c} ${o.dir} project`,ico:"proj",act:()=>{let p=o.workspaces?.find((b)=>b.main)??o.workspaces?.[0];p?Ht(o.dir,p.path):ne("board","/?view=board")()}})}for(let o of e.filter((c)=>!c.archived)){let c=ae(o);i.push({group:o.kind==="run"?"Runs":"Tasks",title:Ye(o)||o.id,sub:z(o.state,t),when:o.moved?te(o.moved,a):void 0,hay:`${Ye(o)} ${o.id??""} ${o.text??""} ${z(o.state,t)} ${c}`,at:o.moved??0,dot:c,ico:o.kind==="run"?"run":"idea",act:()=>{if(!Me("kz-open-card",{dir:o.state,id:o.kind==="run"?o.id:void 0,text:o.text}))location.href=Nt(o)}})}for(let o of Bt){let c=Date.parse(o.updated)||0;i.push({group:"Chats & terminals",title:o.title||"Chat",sub:o.project?z(o.project,t):void 0,when:c?te(c,a):void 0,hay:`${o.title} chat ${o.project??""}`,at:c,dot:o.busy?"build":void 0,ico:"chat",act:()=>{try{sessionStorage.setItem("kz-chat",o.id)}catch{}ne("home","/")()}})}for(let o of n)i.push({group:"Chats & terminals",title:o.name||o.agent||"Terminal",sub:z(o.dir,t),hay:`${o.name} ${o.agent??""} ${o.run??""} ${o.last??""} ${z(o.dir,t)} terminal agent`,at:o.at??o.born??0,dot:o.asking?"wait":o.busy?"build":"done",ico:"term",act:()=>{if(!Me("kz-open-term",{dir:o.dir,ws:o.ws,key:o.key}))location.href=X(o.dir,o.ws??"")}});let L=(o)=>()=>M(o)?.click(),f=[["Home","page",ne("home","/"),"chat"],["Icebox","page",ne("sources","/?view=icebox"),"requests sources gathered"],["Tasks","page",ne("tasks","/?view=tasks"),"backlog"],["Board","page",ne("board","/?view=board"),"kanban runs"],["Notes","page",()=>location.href="/notebook","notebook docs"],["Settings","page",ne("settings","/?view=settings"),"preferences config"],["New task","act",()=>M("newtop")?M("newtop").click():location.href="/?view=board","create add run"],["Add a project","act",()=>fe({dir:null}),"clone folder create workspace"],["Toggle theme","act",L("themet"),"dark light"],["Collapse or expand menu","act",L("fold"),"sidebar rail"],["Keyboard shortcuts","act",L("kbd"),"keys help"],["Report an issue","act",()=>open("/issue","_blank","noopener"),"bug feedback"]];for(let[o,c,p,b]of f)i.push({group:"Actions",title:o,hay:`${o} ${b??""}`,ico:c,act:p});return i}var Mn=["Current","Workspaces","Tabs","Chats & terminals","Runs","Tasks","Projects","Actions"],Sn={Workspaces:5,Tabs:4,"Chats & terminals":5,Runs:5,Tasks:3,Projects:5},S=null,D=[],O=0;function Ee(){let e=S.querySelector("input").value,t=En(),n=e.trim()?Ct(t,e):t.slice().sort((l,i)=>(i.at??0)-(l.at??0));D=[];let a=e.trim()?[...new Set(n.map((l)=>l.group))]:Mn;for(let l of a){let i=n.filter((u)=>u.group===l);D.push(...i.slice(0,e.trim()?8:Sn[l]??i.length))}if(e.trim())D.push({group:"Create",title:`New task "${e.trim()}"`,hay:"",ico:"plus",act:()=>Ln(e.trim())});O=Math.min(O,D.length-1);let s=S.querySelector(".gs-list"),r="";s.innerHTML=String(w`${D.map((l,i)=>{let u=l.group!==r?(r=l.group,w`<div class="gs-h" role="presentation">${l.group}</div>`):"";return w`${u}<div class="gs-i" role="option" id="gs-${i}" data-n="${i}" aria-selected="${String(i===O)}">${Rt(l.ico)}${l.dot?w`<span class="si ${l.dot}"></span>`:""}<span class="gs-t">${l.title}</span>${l.sub?w`<span class="gs-s">${l.sub}</span>`:""}${l.when?w`<span class="gs-w">${l.when}</span>`:""}</div>`})}${D.length===1&&e.trim()?w`<div class="gs-none">No results</div>`:""}`),Ge(O),S.querySelector(".gs-live").textContent=`${D.length} result${D.length===1?"":"s"} found`}function Ge(e){S.querySelector(`#gs-${O}`)?.setAttribute("aria-selected","false"),O=e;let t=S.querySelector(`#gs-${e}`);t?.setAttribute("aria-selected","true"),S.querySelector("input").setAttribute("aria-activedescendant","gs-"+e),t?.scrollIntoView({block:"nearest"})}function Ln(e){if(!M("newtop"))return void(location.href="/?view=board");M("newtop").click();let t=document.querySelector("dialog[open] textarea");if(t)t.value=e,t.dispatchEvent(new Event("input",{bubbles:!0}))}function It(e){let t=D[e];if(!t)return;S.close(),t.act()}function _e(){if(S)return S.querySelector("input").focus();S=document.createElement("dialog"),S.className="gs",S.setAttribute("aria-label","Search"),S.innerHTML=String(w`<div class="gs-box"><div class="gs-q">${Rt("search")}<input type="text" placeholder="Search" aria-label="Search" role="combobox" aria-expanded="true" aria-controls="gs-list" autocomplete="off" spellcheck="false"></div><div class="gs-list" id="gs-list" role="listbox"></div><span class="gs-live" role="status" aria-live="polite"></span></div>`),document.body.append(S);let e=S.querySelector("input");O=0,e.oninput=()=>(O=0,Ee()),e.onkeydown=(n)=>{let a={ArrowDown:1,ArrowUp:-1}[n.key]??(n.ctrlKey&&n.key==="n"?1:n.ctrlKey&&n.key==="p"?-1:0);if(a)n.preventDefault(),Ge((O+a+D.length)%D.length);else if(n.key==="Enter")n.preventDefault(),It(O)};let t=S.querySelector(".gs-list");t.onclick=(n)=>{let a=n.target.closest(".gs-i");if(a)It(+a.dataset.n)},t.onpointermove=(n)=>{let a=n.target.closest(".gs-i");if(a&&+a.dataset.n!==O)Ge(+a.dataset.n)},S.onclick=(n)=>n.target===S&&S.close(),S.onclose=()=>(S.remove(),S=null),S.showModal(),Ee(),fetch("/chats").then((n)=>n.json()).then((n)=>{if(Bt=n.chats??[],S)Ee()}).catch(()=>{})}var Tn=`dialog.gs{border:0;padding:0;margin:14vh auto auto;background:none;width:min(560px,calc(100vw - 32px));color:var(--ink);overflow:visible}
|
|
3
3
|
dialog.gs::backdrop{background:rgb(0 0 0/.35)}
|
|
4
4
|
.gs-box{display:flex;flex-direction:column;max-height:min(480px,72vh);background:var(--bg);border:1px solid var(--line);border-radius:10px;box-shadow:0 16px 40px rgb(0 0 0/.25);overflow:hidden}
|
|
Binary file
|
package/cli/accounts.test.ts
DELETED
|
@@ -1,126 +0,0 @@
|
|
|
1
|
-
import { afterEach, beforeEach, expect, test } from "bun:test";
|
|
2
|
-
import { existsSync, mkdirSync, mkdtempSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
|
|
3
|
-
import { tmpdir } from "node:os";
|
|
4
|
-
import { join } from "node:path";
|
|
5
|
-
import { accountDir, addAccount, signedIn, renameAccount, linkKaizen, readAccounts, removeAccount, resolveAccount, setDefaultAccount } from "./accounts.ts";
|
|
6
|
-
import { claudeUsageAt } from "./usage.ts";
|
|
7
|
-
|
|
8
|
-
let t: string;
|
|
9
|
-
beforeEach(() => { t = mkdtempSync(join(tmpdir(), "kz-acct-")); process.env.KAIZEN_ACCOUNTS_HOME = t; });
|
|
10
|
-
afterEach(() => { delete process.env.KAIZEN_ACCOUNTS_HOME; rmSync(t, { recursive: true, force: true }); });
|
|
11
|
-
const add = (tool = "claude", name = "Work") => (addAccount(tool, name) as { id: string }).id;
|
|
12
|
-
|
|
13
|
-
test("no accounts: normal login, no env", () => {
|
|
14
|
-
expect(resolveAccount("claude", undefined, false)).toEqual({});
|
|
15
|
-
expect(resolveAccount("gemini", undefined, false)).toEqual({});
|
|
16
|
-
});
|
|
17
|
-
test("default, pick and normal login resolve; modes are private", () => {
|
|
18
|
-
const id = add();
|
|
19
|
-
setDefaultAccount("claude", "");
|
|
20
|
-
if (process.platform !== "win32") { // no POSIX modes there
|
|
21
|
-
expect(statSync(accountDir(id)).mode & 0o777).toBe(0o700);
|
|
22
|
-
expect(statSync(join(t, "accounts.json")).mode & 0o777).toBe(0o600);
|
|
23
|
-
}
|
|
24
|
-
expect(resolveAccount("claude", undefined, false)).toEqual({});
|
|
25
|
-
setDefaultAccount("claude", id);
|
|
26
|
-
expect(resolveAccount("claude", undefined, false)).toMatchObject({ dir: accountDir(id), envVar: "CLAUDE_CONFIG_DIR" });
|
|
27
|
-
expect(resolveAccount("claude", "", false)).toEqual({});
|
|
28
|
-
expect(resolveAccount("codex", undefined, false)).toEqual({});
|
|
29
|
-
});
|
|
30
|
-
test("missing, unknown, wrong-tool or Windows accounts refuse, with no fallback", () => {
|
|
31
|
-
const id = add();
|
|
32
|
-
setDefaultAccount("claude", id);
|
|
33
|
-
rmSync(accountDir(id), { recursive: true });
|
|
34
|
-
expect(resolveAccount("claude", undefined, false).error).toMatch(/missing/);
|
|
35
|
-
expect(resolveAccount("claude", "abcdefgh1234", false).error).toMatch(/no longer/);
|
|
36
|
-
expect(resolveAccount("codex", id, false).error).toMatch(/no longer/);
|
|
37
|
-
mkdirSync(accountDir(id));
|
|
38
|
-
expect(resolveAccount("claude", id, true).error).toMatch(/Windows/);
|
|
39
|
-
});
|
|
40
|
-
test("remove keeps the folder unless asked; ids can't leave the folder", () => {
|
|
41
|
-
const id = add();
|
|
42
|
-
setDefaultAccount("claude", id);
|
|
43
|
-
expect(removeAccount(id)).toBeNull();
|
|
44
|
-
expect(existsSync(accountDir(id))).toBe(true);
|
|
45
|
-
expect(readAccounts().default.claude).toBeUndefined();
|
|
46
|
-
const b = add("codex", "B");
|
|
47
|
-
expect(removeAccount(b, true)).toBeNull();
|
|
48
|
-
expect(existsSync(accountDir(b))).toBe(false);
|
|
49
|
-
for (const bad of ["../x", "..", "a/b", ""]) expect(removeAccount(bad, true)).toBe("unknown account");
|
|
50
|
-
expect(existsSync(t)).toBe(true);
|
|
51
|
-
});
|
|
52
|
-
test("names are validated", () => {
|
|
53
|
-
expect("error" in addAccount("gemini", "x")).toBe(true);
|
|
54
|
-
add();
|
|
55
|
-
expect("error" in addAccount("claude", "Work")).toBe(true);
|
|
56
|
-
});
|
|
57
|
-
test("kaizen's links follow into an account folder", () => {
|
|
58
|
-
const from = join(t, "from"), target = join(t, "skill-src");
|
|
59
|
-
mkdirSync(join(from, "skills"), { recursive: true });
|
|
60
|
-
mkdirSync(target);
|
|
61
|
-
symlinkSync(target, join(from, "skills", "kaizen"));
|
|
62
|
-
symlinkSync(target, join(from, "skills", "other"));
|
|
63
|
-
linkKaizen(join(t, "acct"), "claude", from);
|
|
64
|
-
expect(readlinkSync(join(t, "acct/skills/kaizen"))).toBe(realpathSync(target));
|
|
65
|
-
expect(existsSync(join(t, "acct/skills/other"))).toBe(false);
|
|
66
|
-
});
|
|
67
|
-
test("usage reads the account folder; a 401 says sign in, with no token in the answer", async () => {
|
|
68
|
-
const dir = join(t, "c");
|
|
69
|
-
mkdirSync(dir);
|
|
70
|
-
await Bun.write(join(dir, ".credentials.json"), JSON.stringify({ claudeAiOauth: { accessToken: "tok-secret" } }));
|
|
71
|
-
let header = "";
|
|
72
|
-
const r = await claudeUsageAt(dir, (async (_: string, o: any) => { header = o.headers.authorization; return new Response("", { status: 401 }); }) as any);
|
|
73
|
-
expect(header).toContain("tok-secret");
|
|
74
|
-
expect(r).toMatchObject({ expired: true });
|
|
75
|
-
expect(JSON.stringify(r)).not.toContain("tok-secret");
|
|
76
|
-
expect(await claudeUsageAt(join(t, "none"))).toBeNull();
|
|
77
|
-
});
|
|
78
|
-
|
|
79
|
-
test.skipIf(process.platform === "win32")("a run resumes on its own account and finds its conversation there, in a child with a fake claude", async () => {
|
|
80
|
-
const dir = join(t, "proj"), id = add();
|
|
81
|
-
mkdirSync(join(dir, ".kaizen", "runs", "r1"), { recursive: true });
|
|
82
|
-
writeFileSync(join(dir, ".kaizen", "runs", "r1", "state.json"), "{}");
|
|
83
|
-
mkdirSync(join(t, "bin"));
|
|
84
|
-
writeFileSync(join(t, "bin", "claude"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
|
|
85
|
-
const go = (pick: string) => {
|
|
86
|
-
const script = `const { launchRun } = await import(${JSON.stringify(join(import.meta.dir, "state.ts"))});
|
|
87
|
-
const r = launchRun({ severity: null, where: null, text: "x", raw: "x" }, ${JSON.stringify(dir)}, "r1", { agent: "claude", cwd: ${JSON.stringify(dir)}, card: true, ...${pick} });
|
|
88
|
-
console.log(JSON.stringify(r)); process.exit(0);`;
|
|
89
|
-
return JSON.parse(Bun.spawnSync([process.execPath, "-e", script], { env: { ...process.env, PATH: `${join(t, "bin")}:${process.env.PATH}` } }).stdout.toString());
|
|
90
|
-
};
|
|
91
|
-
const first = go(`{ account: ${JSON.stringify(id)} }`);
|
|
92
|
-
if (!first.ok) return; // no pseudo-terminal here
|
|
93
|
-
const sid = first.cmd[first.cmd.indexOf("--session-id") + 1];
|
|
94
|
-
// macOS's temp path has two spellings; the launch keeps the one it was given.
|
|
95
|
-
for (const d of [dir, realpathSync(dir)]) {
|
|
96
|
-
const convo = join(accountDir(id), "projects", d.replace(/[^A-Za-z0-9]/g, "-"));
|
|
97
|
-
mkdirSync(convo, { recursive: true });
|
|
98
|
-
writeFileSync(join(convo, `${sid}.jsonl`), "{}\n");
|
|
99
|
-
}
|
|
100
|
-
// Every caller of firstSession, the board's Resume among them, with no env set here.
|
|
101
|
-
const { firstSession, manualCommand } = await import("./state.ts");
|
|
102
|
-
expect(firstSession(join(dir, ".kaizen"), "r1", "claude", realpathSync(dir))?.sessionId).toBe(sid);
|
|
103
|
-
expect(manualCommand("/p", "claude", "", [], "CLAUDE_CONFIG_DIR='/a b'")).toBe("cd '/p' && CLAUDE_CONFIG_DIR='/a b' claude");
|
|
104
|
-
const again = go("{}");
|
|
105
|
-
expect(again.cmd).toContain("--resume");
|
|
106
|
-
expect(again.cmd).toContain(sid);
|
|
107
|
-
rmSync(accountDir(id), { recursive: true });
|
|
108
|
-
expect(go("{}").why).toMatch(/missing/);
|
|
109
|
-
}, 20000);
|
|
110
|
-
|
|
111
|
-
test("no name: the tool's, numbered; rename after", () => {
|
|
112
|
-
addAccount("claude", "");
|
|
113
|
-
const b = (addAccount("claude", "") as { id: string }).id;
|
|
114
|
-
expect(readAccounts().accounts.map((x) => x.name)).toEqual(["Claude", "Claude 2"]);
|
|
115
|
-
expect(renameAccount(b, "Work")).toBeNull();
|
|
116
|
-
expect(renameAccount(b, "Claude")).toMatch(/taken/);
|
|
117
|
-
expect(renameAccount(b, "")).toBeTruthy();
|
|
118
|
-
expect(renameAccount("nope", "x")).toBe("unknown account");
|
|
119
|
-
});
|
|
120
|
-
|
|
121
|
-
test("signed in follows the tool's login file", () => {
|
|
122
|
-
const id = add("codex", "C");
|
|
123
|
-
expect(signedIn(accountDir(id), "codex")).toBe(false);
|
|
124
|
-
writeFileSync(join(accountDir(id), "auth.json"), "{}");
|
|
125
|
-
expect(signedIn(accountDir(id), "codex")).toBe(true);
|
|
126
|
-
});
|
package/cli/add-project.test.ts
DELETED
|
@@ -1,169 +0,0 @@
|
|
|
1
|
-
// The checks behind the board's "Add a project" sheet: every URL, path, branch and base
|
|
2
|
-
// a web page can send is tested here, and each refusal has a case.
|
|
3
|
-
import { test, expect } from "bun:test";
|
|
4
|
-
import { mkdtempSync, mkdirSync, writeFileSync, existsSync, realpathSync, readFileSync, symlinkSync } from "node:fs";
|
|
5
|
-
import { join } from "node:path";
|
|
6
|
-
import { tmpdir } from "node:os";
|
|
7
|
-
import { gitUrl, destDir, cloneInto, branchesOf, winBad, dirSize, ignoreKaizen } from "./add-project.ts";
|
|
8
|
-
import { run, addWorktree, type Run } from "./worktree.ts";
|
|
9
|
-
|
|
10
|
-
const tmp = () => realpathSync(mkdtempSync(join(tmpdir(), "addp-")));
|
|
11
|
-
|
|
12
|
-
test("gitUrl accepts https, ssh and user@host:path, and names the repository", () => {
|
|
13
|
-
expect(gitUrl("https://github.com/o/repo.git")).toEqual({ url: "https://github.com/o/repo.git", name: "repo" });
|
|
14
|
-
expect(gitUrl(" https://gitlab.example.com:8443/g/sub/repo/ ")).toMatchObject({ name: "repo" });
|
|
15
|
-
expect(gitUrl("ssh://git@host.example/o/repo")).toMatchObject({ name: "repo" });
|
|
16
|
-
expect(gitUrl("git@github.com:o/repo.git")).toEqual({ url: "git@github.com:o/repo.git", name: "repo" });
|
|
17
|
-
});
|
|
18
|
-
|
|
19
|
-
test("gitUrl refuses options, helper transports, plain http, local paths, credentials and odd characters", () => {
|
|
20
|
-
for (const bad of [
|
|
21
|
-
"", " ", 5, null,
|
|
22
|
-
"--upload-pack=touch /tmp/x", "-oProxyCommand=id", "--help",
|
|
23
|
-
"ext::sh -c id", "ext::sh -c id%s", "fd::3", "file:///etc", "/etc/passwd", "./repo", "C:\\repo", "~/repo",
|
|
24
|
-
"http://github.com/o/r.git", "git://github.com/o/r.git", "ftp://h/o/r",
|
|
25
|
-
"https://github.com/o/r .git", "https://github.com/o/r\n--x", "https://github.com/o/r\0",
|
|
26
|
-
"https://user:pw@github.com/o/r.git",
|
|
27
|
-
"https://-evil.example/o/r.git", "ssh://-oProxyCommand=id/o/r", "ssh://git@-oProxyCommand=id/o/r",
|
|
28
|
-
"-oProxyCommand=id@host:o/r", "git@-bad:o/r", "git@host:/abs/path",
|
|
29
|
-
"https://github.com/o/../r.git", "https://github.com/", "https://github.com/o/.git", "https://github.com/o/..",
|
|
30
|
-
"https://github.com/o/r$(id)", "https://github.com/o/r;id", "https://github.com/o/r|id",
|
|
31
|
-
"https://" + "a".repeat(600) + "/r",
|
|
32
|
-
]) expect(gitUrl(bad), String(bad)).toHaveProperty("error");
|
|
33
|
-
});
|
|
34
|
-
|
|
35
|
-
test("winBad: Windows device names and trailing dots, on every platform", () => {
|
|
36
|
-
for (const n of ["", ".", "..", "con", "NUL.txt", "COM1", "a.", "a ", "a:b", "a|b"]) expect(winBad(n), n).toBe(true);
|
|
37
|
-
for (const n of ["config", "my-project", "a.b", "com10"]) expect(winBad(n), n).toBe(false);
|
|
38
|
-
});
|
|
39
|
-
|
|
40
|
-
test("destDir: resolves ~ and relative paths; refuses root, home, kaizen/git folders, .., bad names and places below a project", () => {
|
|
41
|
-
const home = tmp();
|
|
42
|
-
expect(destDir("~/Projects/x", home)).toEqual({ dir: join(home, "Projects", "x") });
|
|
43
|
-
expect(destDir("x", home)).toEqual({ dir: join(home, "x") });
|
|
44
|
-
expect(destDir(join(home, "y"), home)).toEqual({ dir: join(home, "y") });
|
|
45
|
-
for (const bad of [
|
|
46
|
-
"", " ", 3, undefined, "/", "~", home, home + "/", "~/.kaizen/x", join(home, ".kaizen"),
|
|
47
|
-
"/tmp/a/../../etc", "../x", "~/a/../b", "~/x/.git/y", "~/x/.kaizen", "~/con", "~/a.", "x\0y", "~/" + "a/".repeat(600),
|
|
48
|
-
]) expect(destDir(bad, home), String(bad)).toHaveProperty("error");
|
|
49
|
-
// Below a known project, or below a folder that has a .kaizen: a second .kaizen would shadow the first.
|
|
50
|
-
mkdirSync(join(home, "p", ".kaizen"), { recursive: true });
|
|
51
|
-
expect(destDir(join(home, "p", "sub"), home)).toMatchObject({ error: expect.stringContaining("inside the project") });
|
|
52
|
-
expect(destDir(join(home, "q", "sub"), home, [join(home, "q")])).toMatchObject({ error: expect.stringContaining("inside the project") });
|
|
53
|
-
expect(destDir(join(home, "p"), home, [join(home, "p")])).toEqual({ dir: join(home, "p") }); // the project itself is fine
|
|
54
|
-
expect(destDir(join(home, "other"), home, [join(home, "p")])).toEqual({ dir: join(home, "other") });
|
|
55
|
-
});
|
|
56
|
-
|
|
57
|
-
test("branchesOf lists local and origin branches, the current one, and the remote default first", () => {
|
|
58
|
-
const root = tmp(), remote = join(root, "r.git"), proj = join(root, "p");
|
|
59
|
-
const g = (cwd: string, ...a: string[]) => { const r = run(["git", "-c", "user.email=a@b.c", "-c", "user.name=t", ...a], cwd); if (!r.ok) throw new Error(r.why); return r.out; };
|
|
60
|
-
g(root, "init", "-q", "--bare", "-b", "main", remote);
|
|
61
|
-
g(root, "clone", "-q", remote, proj);
|
|
62
|
-
writeFileSync(join(proj, "a"), "a"); g(proj, "add", "a"); g(proj, "commit", "-qm", "a"); g(proj, "push", "-q", "origin", "HEAD:main");
|
|
63
|
-
g(proj, "remote", "set-head", "origin", "main");
|
|
64
|
-
g(proj, "checkout", "-q", "-b", "dev");
|
|
65
|
-
const b = branchesOf(proj);
|
|
66
|
-
expect(b.current).toBe("dev");
|
|
67
|
-
expect(b.def).toBe("origin/main");
|
|
68
|
-
expect(b.branches.sort()).toEqual(["dev", "main", "origin/main"]);
|
|
69
|
-
expect(branchesOf(root)).toEqual({ current: "", def: "", branches: [] }); // not a repository
|
|
70
|
-
const none: Run = () => ({ ok: false, out: "", why: "git is not installed" });
|
|
71
|
-
expect(branchesOf(proj, none).branches).toEqual([]);
|
|
72
|
-
// addWorktree with a base: the branch starts at the base's tip; unknown or option-like bases are refused.
|
|
73
|
-
const old = g(proj, "rev-parse", "origin/main");
|
|
74
|
-
writeFileSync(join(proj, "b"), "b"); g(proj, "add", "b"); g(proj, "commit", "-qm", "b");
|
|
75
|
-
expect(addWorktree(proj, "f1", run, "--detach")).toMatchObject({ ok: false });
|
|
76
|
-
expect(addWorktree(proj, "f1", run, "-x")).toMatchObject({ ok: false });
|
|
77
|
-
expect(addWorktree(proj, "f1", run, "nope")).toMatchObject({ ok: false });
|
|
78
|
-
expect(addWorktree(proj, "f1", run, "HEAD~1")).toMatchObject({ ok: false });
|
|
79
|
-
expect(existsSync(join(proj, ".kaizen/wt/f1"))).toBe(false);
|
|
80
|
-
const w = addWorktree(proj, "f1", run, "origin/main") as { path: string };
|
|
81
|
-
expect(w.ok).toBe(true);
|
|
82
|
-
expect(g(w.path, "rev-parse", "HEAD")).toBe(old);
|
|
83
|
-
expect(run(["git", "config", "--get", "branch.f1.remote"], w.path).out).toBe(""); // --no-track
|
|
84
|
-
});
|
|
85
|
-
|
|
86
|
-
test("cloneInto: argv is `git clone -- url to` with the protocol allow-list and no prompts; a failure removes what it made", async () => {
|
|
87
|
-
const seen: { cmd: string[]; env: any }[] = [];
|
|
88
|
-
const fake = (code: number) => (cmd: string[], o: any) => { seen.push({ cmd, env: o.env }); return { stderr: "fatal: nope\nfatal: gone", exited: Promise.resolve(code), kill() {} }; };
|
|
89
|
-
const dir = tmp(), to = join(dir, "r");
|
|
90
|
-
expect(await cloneInto("https://h.example/o/r.git", to, fake(0))).toEqual({ ok: true });
|
|
91
|
-
expect(seen[0]!.cmd).toEqual(["git", "clone", "--", "https://h.example/o/r.git", to]);
|
|
92
|
-
expect(seen[0]!.env.GIT_ALLOW_PROTOCOL).toBe("https:ssh");
|
|
93
|
-
expect(seen[0]!.env.GIT_TERMINAL_PROMPT).toBe("0");
|
|
94
|
-
// Failure: the last stderr line is the reason; a folder the call made goes, one that was there stays.
|
|
95
|
-
mkdirSync(to);
|
|
96
|
-
expect(await cloneInto("https://h.example/o/r.git", to, fake(128))).toEqual({ ok: false, why: "fatal: gone" });
|
|
97
|
-
expect(existsSync(to)).toBe(true);
|
|
98
|
-
const mine = join(dir, "mine");
|
|
99
|
-
const mk = (cmd: string[], o: any) => { mkdirSync(mine); return fake(1)(cmd, o); };
|
|
100
|
-
expect((await cloneInto("https://h.example/o/r.git", mine, mk)).ok).toBe(false);
|
|
101
|
-
expect(existsSync(mine)).toBe(false);
|
|
102
|
-
});
|
|
103
|
-
|
|
104
|
-
test("cloneInto against a real local repository (protocol list opened for the test only)", async () => {
|
|
105
|
-
const root = tmp(), src = join(root, "src"), to = join(root, "out");
|
|
106
|
-
const g = (cwd: string, ...a: string[]) => { const r = run(["git", "-c", "user.email=a@b.c", "-c", "user.name=t", ...a], cwd); if (!r.ok) throw new Error(r.why); };
|
|
107
|
-
mkdirSync(src); g(src, "init", "-q", "-b", "main"); writeFileSync(join(src, "f"), "x"); g(src, "add", "f"); g(src, "commit", "-qm", "f");
|
|
108
|
-
// The default protocols refuse a file path, the point of GIT_ALLOW_PROTOCOL.
|
|
109
|
-
expect((await cloneInto(src, to)).ok).toBe(false);
|
|
110
|
-
expect(existsSync(to)).toBe(false);
|
|
111
|
-
expect(await cloneInto(src, to, undefined, "file")).toEqual({ ok: true });
|
|
112
|
-
expect(readFileSync(join(to, "f"), "utf8")).toBe("x");
|
|
113
|
-
});
|
|
114
|
-
|
|
115
|
-
test("gitUrl refuses an ssh user that starts with a dash", () => {
|
|
116
|
-
expect(gitUrl("ssh://-oFoo@host.example/x/r.git")).toHaveProperty("error");
|
|
117
|
-
expect(gitUrl("-oFoo@host.example:x/r.git")).toHaveProperty("error");
|
|
118
|
-
expect(gitUrl("ssh://git@host.example/x/r.git")).toHaveProperty("url");
|
|
119
|
-
});
|
|
120
|
-
|
|
121
|
-
test("destDir: symlinks, case, the ~/.kaizen prefix and places outside home", () => {
|
|
122
|
-
const home = tmp(), out = tmp();
|
|
123
|
-
mkdirSync(join(home, "p", ".kaizen"), { recursive: true });
|
|
124
|
-
mkdirSync(join(home, "empty"));
|
|
125
|
-
symlinkSync(join(home, "empty"), join(home, "ln"));
|
|
126
|
-
expect(destDir(join(home, "ln"), home)).toMatchObject({ error: expect.stringContaining("symbolic link") });
|
|
127
|
-
// An existing folder is canonicalised, so a dir reached through a link into a project is still below it.
|
|
128
|
-
symlinkSync(join(home, "p"), join(home, "via"));
|
|
129
|
-
expect(destDir(join(home, "via", "sub"), home, [join(home, "p")])).toMatchObject({ error: expect.stringContaining("inside the project") });
|
|
130
|
-
for (const bad of ["~/X/.GIT/y", "~/x/.Kaizen", "~/.KAIZEN/x", "~/.kaizen/x"]) expect(destDir(bad, home), bad).toHaveProperty("error");
|
|
131
|
-
expect(destDir("~/.kaizenfoo", home)).toEqual({ dir: join(home, ".kaizenfoo") });
|
|
132
|
-
// Outside home: refused, unless under the Projects folder setting.
|
|
133
|
-
expect(destDir(join(out, "x"), home)).toMatchObject({ error: expect.stringContaining("inside your home") });
|
|
134
|
-
expect(destDir(join(out, "x"), home, [], out)).toEqual({ dir: join(out, "x") });
|
|
135
|
-
});
|
|
136
|
-
|
|
137
|
-
test("cloneInto: a clone that runs past the timeout or the size cap is killed (group) and what it made is removed", async () => {
|
|
138
|
-
const dir = tmp();
|
|
139
|
-
const hang = (made: string) => (cmd: string[], o: any) => {
|
|
140
|
-
let done!: (n: number) => void;
|
|
141
|
-
const exited = new Promise<number>((r) => (done = r));
|
|
142
|
-
mkdirSync(made);
|
|
143
|
-
return { stderr: "", exited, kill() { done(137); } };
|
|
144
|
-
};
|
|
145
|
-
const t = join(dir, "t");
|
|
146
|
-
expect(await cloneInto("https://h.example/o/r.git", t, hang(t), "https:ssh", 30, 1e9, 1e6)).toEqual({ ok: false, why: "git clone timed out" });
|
|
147
|
-
expect(existsSync(t)).toBe(false);
|
|
148
|
-
const c = join(dir, "c");
|
|
149
|
-
const r = await cloneInto("https://h.example/o/r.git", c, hang(c), "https:ssh", 60_000, 100, 10, () => 101);
|
|
150
|
-
expect(r).toMatchObject({ ok: false, why: expect.stringContaining("larger than") });
|
|
151
|
-
expect(existsSync(c)).toBe(false);
|
|
152
|
-
});
|
|
153
|
-
|
|
154
|
-
test("dirSize counts only .git/objects/pack", () => {
|
|
155
|
-
const d = tmp(), p = join(d, ".git", "objects", "pack");
|
|
156
|
-
mkdirSync(p, { recursive: true });
|
|
157
|
-
writeFileSync(join(p, "tmp_pack_x"), "x".repeat(100));
|
|
158
|
-
writeFileSync(join(d, "big.bin"), "y".repeat(5000));
|
|
159
|
-
expect(dirSize(d)).toBe(100);
|
|
160
|
-
expect(dirSize(join(d, "none"))).toBe(0);
|
|
161
|
-
});
|
|
162
|
-
|
|
163
|
-
test("ignoreKaizen writes the .kaizen rules once", () => {
|
|
164
|
-
const d = tmp();
|
|
165
|
-
expect(ignoreKaizen(d)).toBe(true);
|
|
166
|
-
expect(readFileSync(join(d, ".gitignore"), "utf8")).toContain(".kaizen/*");
|
|
167
|
-
expect(ignoreKaizen(d)).toBe(false);
|
|
168
|
-
expect(readFileSync(join(d, ".gitignore"), "utf8").match(/\.kaizen\/\*\n/g)!.length).toBe(1);
|
|
169
|
-
});
|
package/cli/agent-prefs.test.ts
DELETED
|
@@ -1,127 +0,0 @@
|
|
|
1
|
-
import { afterEach, beforeEach, expect, test } from "bun:test";
|
|
2
|
-
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
3
|
-
import { tmpdir } from "node:os";
|
|
4
|
-
import { join } from "node:path";
|
|
5
|
-
import { agentEnabled, argsOf, commandOf, prefersBypass, publicPref, readPrefs, savePrefs, withEnv } from "./agent-prefs.ts";
|
|
6
|
-
import { awakeHolder, inhibitArgv, wantAwake } from "./keep-awake.ts";
|
|
7
|
-
import { agentChoices, detectDefaultAgent, launchPreview, launchRun, keepAwake } from "./state.ts";
|
|
8
|
-
|
|
9
|
-
let dir: string, file: string;
|
|
10
|
-
const known = ["claude", "codex", "cursor"];
|
|
11
|
-
beforeEach(() => {
|
|
12
|
-
dir = mkdtempSync(join(tmpdir(), "kz-prefs-"));
|
|
13
|
-
file = join(dir, "agents.json");
|
|
14
|
-
process.env.KAIZEN_AGENT_PREFS = file;
|
|
15
|
-
});
|
|
16
|
-
afterEach(() => {
|
|
17
|
-
delete process.env.KAIZEN_AGENT_PREFS;
|
|
18
|
-
rmSync(dir, { recursive: true, force: true });
|
|
19
|
-
});
|
|
20
|
-
|
|
21
|
-
test("no file: defaults, and launch parts stay as they were", () => {
|
|
22
|
-
const p = readPrefs(file);
|
|
23
|
-
expect(agentEnabled("claude", p)).toBe(true);
|
|
24
|
-
expect(commandOf("claude", p)).toBe("claude");
|
|
25
|
-
expect(argsOf("claude", p)).toEqual([]);
|
|
26
|
-
expect(prefersBypass("claude", p)).toBe(false);
|
|
27
|
-
expect(withEnv(["claude", "x"], "claude", p, false)).toEqual(["claude", "x"]);
|
|
28
|
-
expect(launchPreview(dir, "claude", p)).toBe("claude");
|
|
29
|
-
});
|
|
30
|
-
|
|
31
|
-
test("the file is private, and env values never reach the page's view", () => {
|
|
32
|
-
expect(savePrefs({ agent: "claude", envName: "TOKEN", envValue: "s3cret" }, known, file)).toEqual({ ok: true });
|
|
33
|
-
if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600); // no POSIX modes there
|
|
34
|
-
expect(JSON.stringify(publicPref("claude", readPrefs(file)))).not.toContain("s3cret");
|
|
35
|
-
expect(publicPref("claude", readPrefs(file)).env).toEqual(["TOKEN"]);
|
|
36
|
-
expect(launchPreview(dir, "claude", readPrefs(file))).not.toContain("s3cret");
|
|
37
|
-
expect(withEnv(["claude"], "claude", readPrefs(file), false)).toEqual(["env", "TOKEN=s3cret", "claude"]);
|
|
38
|
-
expect(savePrefs({ agent: "claude", envRemove: "TOKEN" }, known, file)).toEqual({ ok: true });
|
|
39
|
-
expect(publicPref("claude", readPrefs(file)).env).toEqual([]);
|
|
40
|
-
});
|
|
41
|
-
|
|
42
|
-
test("shell characters and dangerous names are refused, on save and on a hand-edited file", () => {
|
|
43
|
-
for (const command of ["claude; rm -rf /", "$(x)", "a b", "`x`", "-x"]) expect("error" in savePrefs({ agent: "claude", command }, known, file)).toBe(true);
|
|
44
|
-
for (const args of ["a;b", "$(x)", "'q'", "a|b"]) expect("error" in savePrefs({ agent: "claude", args }, known, file)).toBe(true);
|
|
45
|
-
for (const n of ["PATH", "LD_PRELOAD", "DYLD_X", "a b", "1A", "NODE_OPTIONS"]) expect("error" in savePrefs({ agent: "claude", envName: n, envValue: "1" }, known, file)).toBe(true);
|
|
46
|
-
expect("error" in savePrefs({ agent: "claude", envName: "A", envValue: "x\ny" }, known, file)).toBe(true);
|
|
47
|
-
expect("error" in savePrefs({ agent: "nope", enabled: false }, known, file)).toBe(true);
|
|
48
|
-
writeFileSync(file, JSON.stringify({ agents: { claude: { command: "x;y", args: ["$(z)", "--ok"], env: { PATH: "/x", OK: "1" } } } }));
|
|
49
|
-
const p = readPrefs(file);
|
|
50
|
-
expect(commandOf("claude", p)).toBe("claude");
|
|
51
|
-
expect(argsOf("claude", p)).toEqual(["--ok"]);
|
|
52
|
-
expect(Object.keys(p.agents.claude!.env!)).toEqual(["OK"]);
|
|
53
|
-
});
|
|
54
|
-
|
|
55
|
-
test("a metacharacter in an env value stays one argv entry", () => {
|
|
56
|
-
savePrefs({ agent: "claude", envName: "A", envValue: "$(touch x); `y` 'z'" }, known, file);
|
|
57
|
-
expect(withEnv(["claude"], "claude", readPrefs(file), false)[1]).toBe("A=$(touch x); `y` 'z'");
|
|
58
|
-
});
|
|
59
|
-
|
|
60
|
-
test("bypass comes only from the setting; one agent can differ", () => {
|
|
61
|
-
savePrefs({ permissions: "bypass" }, known, file);
|
|
62
|
-
expect(prefersBypass("codex", readPrefs(file))).toBe(true);
|
|
63
|
-
savePrefs({ agent: "codex", agentPermissions: "own" }, known, file);
|
|
64
|
-
expect(prefersBypass("codex", readPrefs(file))).toBe(false);
|
|
65
|
-
expect(launchPreview(dir, "claude", readPrefs(file))).toContain("--dangerously-skip-permissions");
|
|
66
|
-
});
|
|
67
|
-
|
|
68
|
-
test("a disabled agent is not offered, not picked, and refused when named", () => {
|
|
69
|
-
for (const a of known) savePrefs({ agent: a, enabled: false }, known, file);
|
|
70
|
-
const all = ["agy", "opencode", "gemini"];
|
|
71
|
-
for (const a of all) savePrefs({ agent: a, enabled: false }, [...known, ...all], file);
|
|
72
|
-
expect(agentChoices(dir).agents).toEqual([]);
|
|
73
|
-
expect(detectDefaultAgent(dir, "claude").note ?? "").toMatch(/turned off/);
|
|
74
|
-
const r = launchRun({ severity: null, where: null, text: "x", raw: "x" }, dir, undefined, { agent: "claude", cwd: dir });
|
|
75
|
-
expect(r.ok).toBe(false);
|
|
76
|
-
expect(r.why).toMatch(/turned off/);
|
|
77
|
-
});
|
|
78
|
-
|
|
79
|
-
test("keep awake: the holder follows the wanted state and stops", () => {
|
|
80
|
-
let kills = 0, starts = 0;
|
|
81
|
-
const h = awakeHolder(() => (starts++, { kill: () => kills++ }), ["x"]);
|
|
82
|
-
h.sync(wantAwake("auto", true)); h.sync(true);
|
|
83
|
-
expect([starts, h.held()]).toEqual([1, true]);
|
|
84
|
-
h.sync(wantAwake("auto", false));
|
|
85
|
-
expect([kills, h.held()]).toEqual([1, false]);
|
|
86
|
-
h.sync(wantAwake("on", false)); h.stop();
|
|
87
|
-
expect([kills, h.held()]).toEqual([2, false]);
|
|
88
|
-
h.sync(wantAwake("off", true));
|
|
89
|
-
expect(h.held()).toBe(false);
|
|
90
|
-
expect(inhibitArgv("linux", 7)).toContain("--pid=7");
|
|
91
|
-
expect(inhibitArgv("darwin", 7)).toEqual(["caffeinate", "-i", "-w", "7"]);
|
|
92
|
-
expect(inhibitArgv("win32")).toBeNull();
|
|
93
|
-
expect(keepAwake("agent:\n keep_awake: auto\n")).toBe("auto");
|
|
94
|
-
expect(keepAwake("")).toBe("off");
|
|
95
|
-
});
|
|
96
|
-
|
|
97
|
-
test("launch: nothing set keeps the line; bypass and overrides reach it and the session record", () => {
|
|
98
|
-
// A child with a fake claude: a real terminal in this process breaks the suite's other tests.
|
|
99
|
-
mkdirSync(join(dir, ".kaizen"));
|
|
100
|
-
mkdirSync(join(dir, "bin"));
|
|
101
|
-
writeFileSync(join(dir, "bin", "claude"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
|
|
102
|
-
const script = `const { launchRun } = await import(${JSON.stringify(join(import.meta.dir, "state.ts"))});
|
|
103
|
-
const r = launchRun({ severity: null, where: null, text: "x", raw: "x" }, ${JSON.stringify(dir)}, undefined, { agent: "claude", cwd: ${JSON.stringify(dir)}, card: true });
|
|
104
|
-
console.log(JSON.stringify(r)); process.exit(0);`;
|
|
105
|
-
const go = () => JSON.parse(Bun.spawnSync([process.execPath, "-e", script], { env: { ...process.env, PATH: `${join(dir, "bin")}:${process.env.PATH}` } }).stdout.toString());
|
|
106
|
-
const plain = go();
|
|
107
|
-
if (!plain.ok) return; // no pseudo-terminal here
|
|
108
|
-
expect(plain.cmd).not.toContain("--dangerously-skip-permissions");
|
|
109
|
-
expect(plain.cmd[0]).toEndWith("claude");
|
|
110
|
-
savePrefs({ permissions: "bypass" }, known, file);
|
|
111
|
-
savePrefs({ agent: "claude", args: "--verbose", envName: "A", envValue: "secret" }, known, file);
|
|
112
|
-
const r = go();
|
|
113
|
-
expect(r.cmd).toContain("--dangerously-skip-permissions");
|
|
114
|
-
expect(r.cmd).toContain("--verbose");
|
|
115
|
-
expect(JSON.stringify(r)).not.toContain("secret");
|
|
116
|
-
const recs = readdirSync(join(dir, ".kaizen", "sessions")).filter((f) => f.endsWith(".json")).map((f) => JSON.parse(readFileSync(join(dir, ".kaizen", "sessions", f), "utf8")));
|
|
117
|
-
expect(recs.filter((x) => x.yolo).length).toBe(1);
|
|
118
|
-
}, 15000);
|
|
119
|
-
|
|
120
|
-
test("a blank value keeps a saved one; bypass flags are refused as arguments", () => {
|
|
121
|
-
savePrefs({ agent: "claude", envName: "A", envValue: "1" }, known, file);
|
|
122
|
-
savePrefs({ agent: "claude", envName: "A", envValue: "" }, known, file);
|
|
123
|
-
expect(readPrefs(file).agents.claude!.env).toEqual({ A: "1" });
|
|
124
|
-
for (const args of ["--dangerously-skip-permissions", "--yolo", "-y", "--auto"]) expect("error" in savePrefs({ agent: "claude", args }, known, file)).toBe(true);
|
|
125
|
-
writeFileSync(file, JSON.stringify({ agents: { claude: { args: ["--yolo", "--ok"] } } }));
|
|
126
|
-
expect(argsOf("claude", readPrefs(file))).toEqual(["--ok"]);
|
|
127
|
-
});
|