tensaku 0.2.0 → 0.2.2

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f39d9336417186bd0aa9189918ae75cc0d0697d23bc23b6a0013d6a5570e58f3
4
- data.tar.gz: 4516a80465641652eccd34a1c050497e4012cc95b7921b2b3db6c8888506484a
3
+ metadata.gz: 147e87281f8421a4cf77646bcbfe8152a230f1ea4b1e313bb290769cf49fc0e6
4
+ data.tar.gz: 58bf0b7360dbe7570042955a26a3602edc59631ee0de28cee2e56f64c46bf12d
5
5
  SHA512:
6
- metadata.gz: 16125703270857712c2f8d10a7924904b9e06c0402b94923373cbd70e0e8d5cb9f8be7bc1fadefcf8a4e79196f7b56b907d2345502332afd7718aa7a406b4301
7
- data.tar.gz: d1afa738bfc83d439e6d6426643d6485ac41dde8574dfe68630df0e773146e1df22538cc9875c56a46dae203fde39a4412f85f2347b139309634a1b2018f99f0
6
+ metadata.gz: 5578d740e98b26eccdb059529559f8adcd76909b8f3722eef6efc491ec0ea9fa05573c290535575dd609d2eb9988e2e93ae5666c9773ba162094dc34122b6a3b
7
+ data.tar.gz: f4b24cada858233e727833563c9fe1210bf0793c21569bbd6f9bb5bf542c8d5168119860f5707b22ab129600455a71281759b48f6d81f4e8bd8e677f0975485e
data/CHANGELOG.md CHANGED
@@ -1,5 +1,32 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.2 (2026-11-14)
4
+
5
+ ### Overlay
6
+
7
+ - Phones: the open toolbar fits on screens up to 520px wide (it used to stop at 420px, so on a 430px
8
+ phone the first tools were off the left edge), and also when the dock was dragged away from the
9
+ corner. The text editor's bar shortens the file name so Cancel and Save stay on screen. Dragging the
10
+ corner button moves the dock instead of scrolling the page. Touch screens no longer show keyboard
11
+ shortcuts in the element menu and note form, or leave a tool's tip up after a tap.
12
+
13
+ ## 0.2.1 (2026-11-14)
14
+
15
+ ### Agents
16
+
17
+ - An agent takes fewer turns per note. Claude Code loads the tools of the work loop (`list_notes`,
18
+ `start_note`, `resolve_note`, `decline_note`, `ask_question`, `watch_notes`, `channel_ready`) up front
19
+ instead of behind its tool search. Notes from the MCP tools and `tensaku notes` give absolute file
20
+ paths. `resolve_note`, `decline_note` and `ask_question` end with how many open notes are left. With
21
+ Claude Haiku, one note went from 7 or 8 tool calls to 5, and from about 8.5 to 4.5 seconds.
22
+ - A note handed to an agent session, by `watch_notes`, the Claude Code channel or with another tool's
23
+ answer, is started for it at once: the pin shows the agent on it, and the agent doesn't call
24
+ `start_note`. A note an agent finds with `list_notes` still needs `start_note`, so two sessions can't
25
+ both work on it.
26
+ - While an agent works on a note, the page reloads itself whenever the app's files change, so each edit
27
+ shows as it lands instead of when the agent resolves the note. The dev server looks at the files
28
+ under `app/` and `config/locales/` four times a second, only while a note is being worked on.
29
+
3
30
  ## 0.2.0 (2026-11-14)
4
31
 
5
32
  Upgrading from 0.1.0: rerun `bin/rails generate tensaku:install` to replace the `.mcp.json` entry with
data/README.md CHANGED
@@ -10,7 +10,7 @@
10
10
  </p>
11
11
 
12
12
  <p align="center">
13
- Fix your Rails app without leaving the browser.
13
+ Fix your Rails app in the browser.
14
14
  </p>
15
15
 
16
16
  <p align="center">
@@ -128,7 +128,9 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
128
128
  .editor { --line: color-mix(in srgb, currentColor 18%, transparent); --muted: color-mix(in srgb, currentColor 62%, transparent); padding: 0; min-width: 0; max-width: none; border: 1.5px solid var(--akaji); border-radius: 8px; box-shadow: 0 0 0 4px var(--akaji-soft), 0 14px 32px -12px rgba(0, 0, 0, .45); animation: settle .16s var(--spring); }
129
129
  .editor .surface { padding: 8px 10px; white-space: pre-wrap; outline: none; min-height: 1.4em; max-height: 60vh; overflow: auto; caret-color: var(--akaji); }
130
130
  .editor .bar { position: absolute; left: -1.5px; top: calc(100% + 8px); display: flex; gap: 10px; align-items: center; background: var(--tray); color: var(--tray-muted); border: 1px solid var(--tray-line); border-radius: 999px; padding: 4px 4px 4px 12px; font: 11px/1.3 var(--mono); white-space: nowrap; box-shadow: 0 10px 26px -8px rgba(0, 0, 0, .45); }
131
- .editor .bar .actions { display: flex; gap: 4px; }
131
+ /* editor.ts limits the bar to the screen; then the file name shortens, so Cancel and Save stay on it. */
132
+ .editor .bar > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
133
+ .editor .bar .actions { display: flex; gap: 4px; flex: none; }
132
134
  .editor .bar button { font: 600 12px/1.2 var(--sans); padding: 5px 12px; border-radius: 999px; border-color: transparent; color: var(--tray-ink); }
133
135
  .editor .bar button:hover { background: var(--tray-raised); border-color: transparent; }
134
136
  .editor .bar button.primary { background: var(--akaji); border-color: var(--akaji); color: #fff; }
@@ -160,7 +162,8 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
160
162
 
161
163
  /* The tray. The corner button opens it; the selected tool rises and shows its ink. */
162
164
  .dock { position: fixed; display: flex; align-items: center; padding: 4px; border-radius: 999px; background: var(--tray); border: 1px solid var(--tray-line); box-shadow: 0 12px 30px -8px rgba(0, 0, 0, .45); user-select: none; }
163
- .corner { width: 40px; height: 40px; border-radius: 50%; border: none; background: none; color: var(--akaji); display: grid; place-items: center; cursor: pointer; position: relative; padding: 0; flex: none; }
165
+ /* touch-action: dragging the button on a touch screen moves the dock instead of scrolling the page. */
166
+ .corner { width: 40px; height: 40px; border-radius: 50%; border: none; background: none; color: var(--akaji); display: grid; place-items: center; cursor: pointer; position: relative; padding: 0; flex: none; touch-action: none; }
164
167
  .corner .logo { width: 25px; height: 25px; fill: none; stroke: currentColor; stroke-width: 10; stroke-linecap: round; stroke-linejoin: round; transition: transform .5s cubic-bezier(.22, 1, .36, 1), rotate .16s var(--spring); }
165
168
  .corner:hover { background: var(--tray-raised); }
166
169
  .corner:hover .logo { rotate: -8deg; }
@@ -187,17 +190,23 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
187
190
  .tool .tip { position: absolute; bottom: calc(100% + 12px); left: 50%; transform: translateX(-50%) translateY(4px); display: flex; gap: 6px; align-items: center; background: var(--tray); color: var(--tray-ink); border: 1px solid var(--tray-line); font: 600 12px/1 var(--sans); padding: 6px 8px; border-radius: 7px; white-space: nowrap; pointer-events: none; opacity: 0; transition: opacity .12s, transform .12s; }
188
191
  .tool:hover .tip, .tool:focus-visible .tip { opacity: 1; transform: translateX(-50%); }
189
192
  .tool:focus-visible { outline: 2px solid var(--marker); outline-offset: 1px; }
190
- /* On a phone the tools are smaller, and on a screen narrower than the open toolbar its tools scroll
191
- sideways. The dock sits 16px from the right edge and the corner button takes 50px of it. */
192
- @media (max-width: 420px) {
193
+ /* On a phone the tools are smaller, and when the open toolbar is wider than the room left of the
194
+ dock its tools scroll sideways. --dock-right is the dock's distance from the right edge; the corner
195
+ button and the dock's padding take 60px more. */
196
+ @media (max-width: 520px) {
193
197
  .tool { width: 32px; height: 32px; }
194
198
  .tool .icon { width: 20px; height: 20px; }
195
199
  .tool[aria-pressed="true"]::after { bottom: 2px; }
196
200
  .toolbar .sep { margin: 0 2px; }
197
201
  .toolbar { justify-content: safe flex-end; }
198
- .dock.open .toolbar { width: min(var(--tools-width), calc(100vw - 76px)); }
202
+ .dock.open .toolbar { width: min(var(--tools-width), calc(100vw - var(--dock-right, 16px) - 60px)); }
199
203
  .dock.settled .toolbar { overflow-x: auto; scrollbar-width: none; }
200
204
  }
205
+ /* A touch screen has no keyboard shortcuts to show, and a tap leaves :hover on the tapped tool, which
206
+ kept its tip up. */
207
+ @media (hover: none) {
208
+ .tool .tip, .menu kbd, .note-form .hint { display: none; }
209
+ }
201
210
 
202
211
  /* The notes panel: the tray's material, holding the page's Post-its. */
203
212
  .sidebar { position: fixed; top: 12px; right: 12px; bottom: 70px; display: flex; flex-direction: column; width: 360px; max-width: calc(100vw - 24px); overflow: auto; background: var(--tray); color: var(--tray-ink); border: 1px solid var(--tray-line); border-radius: 16px; box-shadow: 0 24px 50px -16px rgba(0, 0, 0, .55); padding: 14px; animation: slide-in .22s var(--spring); }
@@ -350,9 +359,9 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
350
359
  .pin.fresh .stroke { stroke-dashoffset: 0; }
351
360
  .tool:hover .icon, .tool[aria-pressed="true"] .icon, .corner:hover .logo { transform: none; rotate: none; }
352
361
  }
353
- `;var host=document.createElement("tensaku-overlay");host.id="tensaku-overlay";host.setAttribute("data-tensaku-ui","");host.setAttribute("data-turbo-permanent","");var shadow=host.attachShadow({mode:"open"});if("adoptedStyleSheets"in shadow&&typeof CSSStyleSheet<"u"&&"replaceSync"in CSSStyleSheet.prototype){let sheet=new CSSStyleSheet;sheet.replaceSync(overlay_default),shadow.adoptedStyleSheets=[sheet]}else{let style=document.createElement("style");style.textContent=overlay_default,shadow.append(style)}var layer=div("layer"),fixed=div("fixed"),toasts=div("toasts");shadow.append(layer,fixed);fixed.append(toasts);function mount(){if(!host.isConnected)document.documentElement.append(host)}function h(tag,attributes={},...children){let element=document.createElement(tag);for(let[name,value]of Object.entries(attributes)){if(value===void 0||value===null||value===!1)continue;if(name.startsWith("on")&&typeof value==="function")element.addEventListener(name.slice(2),value);else if(name==="className")element.className=value;else element.setAttribute(name,value===!0?"":String(value))}for(let child of children)if(child)element.append(child);return element}function div(className,...children){return h("div",{className},...children)}function toast(message,options={}){let element=div("toast"+(options.error?" error":"")+(options.detail?" detailed":""),h("span",{},message));element.setAttribute("role",options.error?"alert":"status");for(let[label,action]of Object.entries(options.actions??{}))element.append(h("button",{onclick:()=>{element.remove(),action()}},label));if(options.detail)element.append(options.detail);if(toasts.append(element),options.timeout!==0)setTimeout(()=>element.remove(),options.timeout??(options.error?8000:5000));return element}function panel(anchor,className,...children){let element=div("panel "+className,...children);return layer.append(element),place(element,anchor),element}function place(element,anchor,over=!1){let width=element.offsetWidth,left=Math.max(scrollX+8,Math.min(anchor.left,scrollX+innerWidth-width-8)),top=over?anchor.top:anchor.bottom+6;if(!over&&top+element.offsetHeight>scrollY+innerHeight-8&&anchor.top-element.offsetHeight-6>scrollY)top=anchor.top-element.offsetHeight-6;element.style.left=`${left}px`,element.style.top=`${top}px`}function box(rect,className,label){let element=div("box "+className);if(Object.assign(element.style,{left:`${rect.left}px`,top:`${rect.top}px`,width:`${rect.width}px`,height:`${rect.height}px`}),layer.append(element),!label)return[element];let tag=div("label");if(tag.append(label[0]),label[1])tag.append(h("span",{className:"where"},label[1]));return Object.assign(tag.style,{left:`${rect.left}px`,top:`${rect.top}px`}),layer.append(tag),[element,tag]}async function copy(text){try{await navigator.clipboard.writeText(text)}catch{let area=h("textarea",{},text);shadow.append(area),area.select(),document.execCommand("copy"),area.remove()}}function storage(key,fallback){try{let value=localStorage.getItem(`tensaku:${key}`);return value?JSON.parse(value):fallback}catch{return fallback}}function store(key,value){try{localStorage.setItem(`tensaku:${key}`,JSON.stringify(value))}catch{}}function activeInShadow(){return shadow.activeElement}var DEFAULTS={copyFormat:"detailed",notify:!1,shortcuts:{}},current={...DEFAULTS,...storage("settings",{})},listeners=[],settings=()=>current,onSettings=(listener)=>{listeners.push(listener),listener(current)};function changeSettings(change){current={...current,...change},store("settings",current),listeners.forEach((listener)=>listener(current))}var Idiomorph=function(){let noOp=()=>{},defaults={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:noOp,afterNodeAdded:noOp,beforeNodeMorphed:noOp,afterNodeMorphed:noOp,beforeNodeRemoved:noOp,afterNodeRemoved:noOp,beforeAttributeUpdated:noOp},head:{style:"merge",shouldPreserve:(elt)=>elt.getAttribute("im-preserve")==="true",shouldReAppend:(elt)=>elt.getAttribute("im-re-append")==="true",shouldRemove:noOp,afterHeadMorphed:noOp},restoreFocus:!0};function morph(oldNode,newContent,config={}){oldNode=normalizeElement(oldNode);let newNode=normalizeParent(newContent),ctx=createMorphContext(oldNode,newNode,config),morphedNodes=saveAndRestoreFocus(ctx,()=>{return withHeadBlocking(ctx,oldNode,newNode,(ctx2)=>{if(ctx2.morphStyle==="innerHTML")return morphChildren(ctx2,oldNode,newNode),Array.from(oldNode.childNodes);else return morphOuterHTML(ctx2,oldNode,newNode)})});return ctx.pantry.remove(),morphedNodes}function morphOuterHTML(ctx,oldNode,newNode){let oldParent=normalizeParent(oldNode);return morphChildren(ctx,oldParent,newNode,oldNode,oldNode.nextSibling),Array.from(oldParent.childNodes)}function saveAndRestoreFocus(ctx,fn){if(!ctx.config.restoreFocus)return fn();let activeElement=document.activeElement;if(!(activeElement instanceof HTMLInputElement||activeElement instanceof HTMLTextAreaElement))return fn();let{id:activeElementId,selectionStart,selectionEnd}=activeElement,results=fn();if(activeElementId&&activeElementId!==document.activeElement?.getAttribute("id"))activeElement=ctx.target.querySelector(`[id="${activeElementId}"]`),activeElement?.focus();if(activeElement&&!activeElement.selectionEnd&&selectionEnd)activeElement.setSelectionRange(selectionStart,selectionEnd);return results}let morphChildren=function(){function morphChildren2(ctx,oldParent,newParent,insertionPoint=null,endPoint=null){if(oldParent instanceof HTMLTemplateElement&&newParent instanceof HTMLTemplateElement)oldParent=oldParent.content,newParent=newParent.content;insertionPoint||=oldParent.firstChild;for(let newChild of newParent.childNodes){if(insertionPoint&&insertionPoint!=endPoint){let bestMatch=findBestMatch(ctx,newChild,insertionPoint,endPoint);if(bestMatch){if(bestMatch!==insertionPoint)removeNodesBetween(ctx,insertionPoint,bestMatch);morphNode(bestMatch,newChild,ctx),insertionPoint=bestMatch.nextSibling;continue}}if(newChild instanceof Element){let newChildId=newChild.getAttribute("id");if(ctx.persistentIds.has(newChildId)){let movedChild=moveBeforeById(oldParent,newChildId,insertionPoint,ctx);morphNode(movedChild,newChild,ctx),insertionPoint=movedChild.nextSibling;continue}}let insertedNode=createNode(oldParent,newChild,insertionPoint,ctx);if(insertedNode)insertionPoint=insertedNode.nextSibling}while(insertionPoint&&insertionPoint!=endPoint){let tempNode=insertionPoint;insertionPoint=insertionPoint.nextSibling,removeNode(ctx,tempNode)}}function createNode(oldParent,newChild,insertionPoint,ctx){if(ctx.callbacks.beforeNodeAdded(newChild)===!1)return null;if(ctx.idMap.has(newChild)){let newEmptyChild=document.createElement(newChild.tagName);return oldParent.insertBefore(newEmptyChild,insertionPoint),morphNode(newEmptyChild,newChild,ctx),ctx.callbacks.afterNodeAdded(newEmptyChild),newEmptyChild}else{let newClonedChild=document.importNode(newChild,!0);return oldParent.insertBefore(newClonedChild,insertionPoint),ctx.callbacks.afterNodeAdded(newClonedChild),newClonedChild}}let findBestMatch=function(){function findBestMatch2(ctx,node,startPoint,endPoint){let softMatch=null,nextSibling=node.nextSibling,siblingSoftMatchCount=0,cursor2=startPoint;while(cursor2&&cursor2!=endPoint){if(isSoftMatch(cursor2,node)){if(isIdSetMatch(ctx,cursor2,node))return cursor2;if(softMatch===null){if(!ctx.idMap.has(cursor2))softMatch=cursor2}}if(softMatch===null&&nextSibling&&isSoftMatch(cursor2,nextSibling)){if(siblingSoftMatchCount++,nextSibling=nextSibling.nextSibling,siblingSoftMatchCount>=2)softMatch=void 0}if(ctx.activeElementAndParents.includes(cursor2))break;cursor2=cursor2.nextSibling}return softMatch||null}function isIdSetMatch(ctx,oldNode,newNode){let oldSet=ctx.idMap.get(oldNode),newSet=ctx.idMap.get(newNode);if(!newSet||!oldSet)return!1;for(let id of oldSet)if(newSet.has(id))return!0;return!1}function isSoftMatch(oldNode,newNode){let oldElt=oldNode,newElt=newNode;return oldElt.nodeType===newElt.nodeType&&oldElt.tagName===newElt.tagName&&(!oldElt.getAttribute?.("id")||oldElt.getAttribute?.("id")===newElt.getAttribute?.("id"))}return findBestMatch2}();function removeNode(ctx,node){if(ctx.idMap.has(node))moveBefore(ctx.pantry,node,null);else{if(ctx.callbacks.beforeNodeRemoved(node)===!1)return;node.parentNode?.removeChild(node),ctx.callbacks.afterNodeRemoved(node)}}function removeNodesBetween(ctx,startInclusive,endExclusive){let cursor2=startInclusive;while(cursor2&&cursor2!==endExclusive){let tempNode=cursor2;cursor2=cursor2.nextSibling,removeNode(ctx,tempNode)}return cursor2}function moveBeforeById(parentNode,id,after,ctx){let target=ctx.target.getAttribute?.("id")===id&&ctx.target||ctx.target.querySelector(`[id="${id}"]`)||ctx.pantry.querySelector(`[id="${id}"]`);return removeElementFromAncestorsIdMaps(target,ctx),moveBefore(parentNode,target,after),target}function removeElementFromAncestorsIdMaps(element,ctx){let id=element.getAttribute("id");while(element=element.parentNode){let idSet=ctx.idMap.get(element);if(idSet){if(idSet.delete(id),!idSet.size)ctx.idMap.delete(element)}}}function moveBefore(parentNode,element,after){if(parentNode.moveBefore)try{parentNode.moveBefore(element,after)}catch(e){parentNode.insertBefore(element,after)}else parentNode.insertBefore(element,after)}return morphChildren2}(),morphNode=function(){function morphNode2(oldNode,newContent,ctx){if(ctx.ignoreActive&&oldNode===document.activeElement)return null;if(ctx.callbacks.beforeNodeMorphed(oldNode,newContent)===!1)return oldNode;if(oldNode instanceof HTMLHeadElement&&ctx.head.ignore);else if(oldNode instanceof HTMLHeadElement&&ctx.head.style!=="morph")handleHeadElement(oldNode,newContent,ctx);else if(morphAttributes(oldNode,newContent,ctx),!ignoreValueOfActiveElement(oldNode,ctx))morphChildren(ctx,oldNode,newContent);return ctx.callbacks.afterNodeMorphed(oldNode,newContent),oldNode}function morphAttributes(oldNode,newNode,ctx){let type=newNode.nodeType;if(type===1){let oldElt=oldNode,newElt=newNode,oldAttributes=oldElt.attributes,newAttributes=newElt.attributes;for(let newAttribute of newAttributes){if(ignoreAttribute(newAttribute.name,oldElt,"update",ctx))continue;if(oldElt.getAttribute(newAttribute.name)!==newAttribute.value)oldElt.setAttribute(newAttribute.name,newAttribute.value)}for(let i=oldAttributes.length-1;0<=i;i--){let oldAttribute=oldAttributes[i];if(!oldAttribute)continue;if(!newElt.hasAttribute(oldAttribute.name)){if(ignoreAttribute(oldAttribute.name,oldElt,"remove",ctx))continue;oldElt.removeAttribute(oldAttribute.name)}}if(!ignoreValueOfActiveElement(oldElt,ctx))syncInputValue(oldElt,newElt,ctx)}if(type===8||type===3){if(oldNode.nodeValue!==newNode.nodeValue)oldNode.nodeValue=newNode.nodeValue}}function syncInputValue(oldElement,newElement,ctx){if(oldElement instanceof HTMLInputElement&&newElement instanceof HTMLInputElement&&newElement.type!=="file"){let newValue=newElement.value,oldValue=oldElement.value;if(syncBooleanAttribute(oldElement,newElement,"checked",ctx),syncBooleanAttribute(oldElement,newElement,"disabled",ctx),!newElement.hasAttribute("value")){if(!ignoreAttribute("value",oldElement,"remove",ctx))oldElement.value="",oldElement.removeAttribute("value")}else if(oldValue!==newValue){if(!ignoreAttribute("value",oldElement,"update",ctx))oldElement.setAttribute("value",newValue),oldElement.value=newValue}}else if(oldElement instanceof HTMLOptionElement&&newElement instanceof HTMLOptionElement)syncBooleanAttribute(oldElement,newElement,"selected",ctx);else if(oldElement instanceof HTMLTextAreaElement&&newElement instanceof HTMLTextAreaElement){let newValue=newElement.value,oldValue=oldElement.value;if(ignoreAttribute("value",oldElement,"update",ctx))return;if(newValue!==oldValue)oldElement.value=newValue;if(oldElement.firstChild&&oldElement.firstChild.nodeValue!==newValue)oldElement.firstChild.nodeValue=newValue}}function syncBooleanAttribute(oldElement,newElement,attributeName,ctx){let newLiveValue=newElement[attributeName],oldLiveValue=oldElement[attributeName];if(newLiveValue!==oldLiveValue){let ignoreUpdate=ignoreAttribute(attributeName,oldElement,"update",ctx);if(!ignoreUpdate)oldElement[attributeName]=newElement[attributeName];if(newLiveValue){if(!ignoreUpdate)oldElement.setAttribute(attributeName,"")}else if(!ignoreAttribute(attributeName,oldElement,"remove",ctx))oldElement.removeAttribute(attributeName)}}function ignoreAttribute(attr,element,updateType,ctx){if(attr==="value"&&ctx.ignoreActiveValue&&element===document.activeElement)return!0;return ctx.callbacks.beforeAttributeUpdated(attr,element,updateType)===!1}function ignoreValueOfActiveElement(possibleActiveElement,ctx){return!!ctx.ignoreActiveValue&&possibleActiveElement===document.activeElement&&possibleActiveElement!==document.body}return morphNode2}();function withHeadBlocking(ctx,oldNode,newNode,callback){if(ctx.head.block){let oldHead=oldNode.querySelector("head"),newHead=newNode.querySelector("head");if(oldHead&&newHead){let promises=handleHeadElement(oldHead,newHead,ctx);return Promise.all(promises).then(()=>{let newCtx=Object.assign(ctx,{head:{block:!1,ignore:!0}});return callback(newCtx)})}}return callback(ctx)}function handleHeadElement(oldHead,newHead,ctx){let added=[],removed=[],preserved=[],nodesToAppend=[],srcToNewHeadNodes=new Map;for(let newHeadChild of newHead.children)srcToNewHeadNodes.set(newHeadChild.outerHTML,newHeadChild);for(let currentHeadElt of oldHead.children){let inNewContent=srcToNewHeadNodes.has(currentHeadElt.outerHTML),isReAppended=ctx.head.shouldReAppend(currentHeadElt),isPreserved=ctx.head.shouldPreserve(currentHeadElt);if(inNewContent||isPreserved)if(isReAppended)removed.push(currentHeadElt);else srcToNewHeadNodes.delete(currentHeadElt.outerHTML),preserved.push(currentHeadElt);else if(ctx.head.style==="append"){if(isReAppended)removed.push(currentHeadElt),nodesToAppend.push(currentHeadElt)}else if(ctx.head.shouldRemove(currentHeadElt)!==!1)removed.push(currentHeadElt)}nodesToAppend.push(...srcToNewHeadNodes.values());let promises=[];for(let newNode of nodesToAppend){let newElt=document.createRange().createContextualFragment(newNode.outerHTML).firstChild;if(ctx.callbacks.beforeNodeAdded(newElt)!==!1){if("href"in newElt&&newElt.href||"src"in newElt&&newElt.src){let resolve,promise=new Promise(function(_resolve){resolve=_resolve});newElt.addEventListener("load",function(){resolve()}),promises.push(promise)}oldHead.appendChild(newElt),ctx.callbacks.afterNodeAdded(newElt),added.push(newElt)}}for(let removedElement of removed)if(ctx.callbacks.beforeNodeRemoved(removedElement)!==!1)oldHead.removeChild(removedElement),ctx.callbacks.afterNodeRemoved(removedElement);return ctx.head.afterHeadMorphed(oldHead,{added,kept:preserved,removed}),promises}let createMorphContext=function(){function createMorphContext2(oldNode,newContent,config){let{persistentIds,idMap}=createIdMaps(oldNode,newContent),mergedConfig=mergeDefaults(config),morphStyle=mergedConfig.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(morphStyle))throw`Do not understand how to morph style ${morphStyle}`;return{target:oldNode,newContent,config:mergedConfig,morphStyle,ignoreActive:mergedConfig.ignoreActive,ignoreActiveValue:mergedConfig.ignoreActiveValue,restoreFocus:mergedConfig.restoreFocus,idMap,persistentIds,pantry:createPantry(),activeElementAndParents:createActiveElementAndParents(oldNode),callbacks:mergedConfig.callbacks,head:mergedConfig.head}}function mergeDefaults(config){let finalConfig=Object.assign({},defaults);return Object.assign(finalConfig,config),finalConfig.callbacks=Object.assign({},defaults.callbacks,config.callbacks),finalConfig.head=Object.assign({},defaults.head,config.head),finalConfig}function createPantry(){let pantry=document.createElement("div");return pantry.hidden=!0,document.body.insertAdjacentElement("afterend",pantry),pantry}function createActiveElementAndParents(oldNode){let activeElementAndParents=[],elt=document.activeElement;if(elt?.tagName!=="BODY"&&oldNode.contains(elt))while(elt){if(activeElementAndParents.push(elt),elt===oldNode)break;elt=elt.parentElement}return activeElementAndParents}function findIdElements(root){let elements=Array.from(root.querySelectorAll("[id]"));if(root.getAttribute?.("id"))elements.push(root);return elements}function populateIdMapWithTree(idMap,persistentIds,root,elements){for(let elt of elements){let id=elt.getAttribute("id");if(persistentIds.has(id)){let current2=elt;while(current2){let idSet=idMap.get(current2);if(idSet==null)idSet=new Set,idMap.set(current2,idSet);if(idSet.add(id),current2===root)break;current2=current2.parentElement}}}}function createIdMaps(oldContent,newContent){let oldIdElements=findIdElements(oldContent),newIdElements=findIdElements(newContent),persistentIds=createPersistentIds(oldIdElements,newIdElements),idMap=new Map;populateIdMapWithTree(idMap,persistentIds,oldContent,oldIdElements);let newRoot=newContent.__idiomorphRoot||newContent;return populateIdMapWithTree(idMap,persistentIds,newRoot,newIdElements),{persistentIds,idMap}}function createPersistentIds(oldIdElements,newIdElements){let duplicateIds=new Set,oldIdTagNameMap=new Map;for(let{id,tagName}of oldIdElements)if(oldIdTagNameMap.has(id))duplicateIds.add(id);else oldIdTagNameMap.set(id,tagName);let persistentIds=new Set;for(let{id,tagName}of newIdElements)if(persistentIds.has(id))duplicateIds.add(id);else if(oldIdTagNameMap.get(id)===tagName)persistentIds.add(id);for(let id of duplicateIds)persistentIds.delete(id);return persistentIds}return createMorphContext2}(),{normalizeElement,normalizeParent}=function(){let generatedByIdiomorph=new WeakSet;function normalizeElement2(content){if(content instanceof Document)return content.documentElement;else return content}function normalizeParent2(newContent){if(newContent==null)return document.createElement("div");else if(typeof newContent==="string")return normalizeParent2(parseContent(newContent));else if(generatedByIdiomorph.has(newContent))return newContent;else if(newContent instanceof Node)if(newContent.parentNode)return new SlicedParentNode(newContent);else{let dummyParent=document.createElement("div");return dummyParent.append(newContent),dummyParent}else{let dummyParent=document.createElement("div");for(let elt of[...newContent])dummyParent.append(elt);return dummyParent}}class SlicedParentNode{constructor(node){this.originalNode=node,this.realParentNode=node.parentNode,this.previousSibling=node.previousSibling,this.nextSibling=node.nextSibling}get childNodes(){let nodes=[],cursor2=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;while(cursor2&&cursor2!=this.nextSibling)nodes.push(cursor2),cursor2=cursor2.nextSibling;return nodes}querySelectorAll(selector){return this.childNodes.reduce((results,node)=>{if(node instanceof Element){if(node.matches(selector))results.push(node);let nodeList=node.querySelectorAll(selector);for(let i=0;i<nodeList.length;i++)results.push(nodeList[i])}return results},[])}insertBefore(node,referenceNode){return this.realParentNode.insertBefore(node,referenceNode)}moveBefore(node,referenceNode){return this.realParentNode.moveBefore(node,referenceNode)}get __idiomorphRoot(){return this.originalNode}}function parseContent(newContent){let parser=new DOMParser,contentWithSvgsRemoved=newContent.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(contentWithSvgsRemoved.match(/<\/html>/)||contentWithSvgsRemoved.match(/<\/head>/)||contentWithSvgsRemoved.match(/<\/body>/)){let content=parser.parseFromString(newContent,"text/html");if(contentWithSvgsRemoved.match(/<\/html>/))return generatedByIdiomorph.add(content),content;else{let htmlElement=content.firstChild;if(htmlElement)generatedByIdiomorph.add(htmlElement);return htmlElement}}else{let content=parser.parseFromString("<body><template>"+newContent+"</template></body>","text/html").body.querySelector("template").content;return generatedByIdiomorph.add(content),content}}return{normalizeElement:normalizeElement2,normalizeParent:normalizeParent2}}();return{morph,defaults}}();var listeners2=[];function onRefresh(listener){listeners2.push(listener)}function permanent(node){return node instanceof Element&&(node.hasAttribute("data-turbo-permanent")||node.hasAttribute("data-tensaku-permanent")||node.hasAttribute("data-tensaku-ui"))}function herbDevServer(){return Boolean(document.querySelector('meta[name="herb-dev-server-port"]'))}function replaceText(nodes,from,to){let normal=(text)=>text.replace(/\s+/g," ").trim(),target=normal(from);if(!target)return;for(let node of nodes)if(normal(node.data)===target){let lead=node.data.match(/^\s*/)[0],trail=node.data.match(/\s*$/)[0];node.data=lead+to.trim()+trail}else if(node.data.includes(from)&&from.trim())node.data=node.data.replace(from,to)}async function refresh(kind){if(meta().method!=="GET"){toast("Saved. This page came from a form submission, so reload to check it.",{timeout:7000});return}if(kind==="template"&&herbDevServer())return;try{let response=await fetch(location.href,{headers:{Accept:"text/html","X-Tensaku-Refresh":"1"},credentials:"same-origin"});if(!response.ok)throw Error(`HTTP ${response.status}`);let html=await response.text(),next=new DOMParser().parseFromString(html,"text/html");morph(next)}catch(error){toast(`Saved, but refreshing the page failed (${error.message}). Reload to check.`,{error:!0})}}async function refreshAfterAgent(){if(meta().method!=="GET")return;try{let response=await fetch(location.href,{headers:{Accept:"text/html","X-Tensaku-Refresh":"1"},credentials:"same-origin"});if(!response.ok)return;let next=new DOMParser().parseFromString(await response.text(),"text/html");swapStylesheets(next),morph(next)}catch{}}function swapStylesheets(next){let wanted=new Set(((doc)=>Array.from(doc.querySelectorAll('head link[rel="stylesheet"]')).map((link)=>link.getAttribute("href")))(next)),current2=Array.from(document.querySelectorAll('head link[rel="stylesheet"]')),have=new Set(current2.map((link)=>link.getAttribute("href"))),added=Array.from(next.querySelectorAll('head link[rel="stylesheet"]')).filter((link)=>!have.has(link.getAttribute("href")));if(!added.length)return;let stale=current2.filter((link)=>!wanted.has(link.getAttribute("href"))),waiting=added.length;for(let link of added){let copy2=document.importNode(link,!0),done=()=>{if(--waiting===0)stale.forEach((old)=>old.remove())};copy2.addEventListener("load",done),copy2.addEventListener("error",done),document.head.append(copy2)}}function changedByUser(element){if(element instanceof HTMLInputElement){if(element.type==="checkbox"||element.type==="radio")return element.checked!==element.defaultChecked;return element.type!=="file"&&element.value!==element.defaultValue}if(element instanceof HTMLTextAreaElement)return element.value!==element.defaultValue;if(element instanceof HTMLOptionElement)return element.selected!==element.defaultSelected;if(element instanceof HTMLSelectElement)return Array.from(element.options).some((option)=>option.selected!==option.defaultSelected);return!1}var FORM_STATE=new Set(["value","checked","selected"]);function morph(next){let lazyFrames=Array.from(document.querySelectorAll("turbo-frame[src]"));if(Idiomorph.morph(document.body,next.body,{morphStyle:"outerHTML",ignoreActiveValue:!0,restoreFocus:!0,callbacks:{beforeNodeMorphed:(oldNode)=>!permanent(oldNode)&&!(oldNode instanceof HTMLTextAreaElement&&changedByUser(oldNode)),beforeAttributeUpdated:(name,element)=>!(FORM_STATE.has(name)&&changedByUser(element)),beforeNodeRemoved:(node)=>!permanent(node)}}),next.title)document.title=next.title;for(let frame of lazyFrames)if(frame.isConnected&&typeof frame.reload==="function"&&!frame.hasAttribute("complete"))frame.reload();listeners2.forEach((listener)=>listener())}var notes=[],scoped=[],scope=null,openCount=0,agents=[],currentNotes=()=>notes,scopedNotes=()=>scoped,currentAgents=()=>agents,openNotes=()=>openCount,agentLabel=(agent)=>agent.handle?`${agent.name} · ${agent.handle}`:agent.name,listeners3=()=>agents.filter((agent)=>agent.listening).map(agentLabel),closed=(note)=>note.status==="resolved"||note.status==="declined",renderListeners=[],countListeners=[],agentListeners=[],changeListeners=[],onRender=(listener)=>renderListeners.push(listener),onCount=(listener)=>countListeners.push(listener),onAgents=(listener)=>agentListeners.push(listener),onChanges=(listener)=>changeListeners.push(listener),normalized=(list)=>list.map((note)=>({...note,targets:note.targets??[]})),lastSignature="",loadSequence=0,tokenWarned=!1,restartWarned=!1,agentChangedAt,primed=!1;async function load({force=!1}={}){let sequence=++loadSequence,first=!1;try{let data=await api("GET","/notes"+query({url:location.pathname}));if(sequence!==loadSequence)return;if(tokenWarned=!1,primed&&data.changed_at&&data.changed_at!==agentChangedAt)refreshAfterAgent();if(agentChangedAt=data.changed_at,data.restart&&!restartWarned)restartWarned=!0,toast("Tensaku's code changed since this dev server started, so the page runs a newer overlay than the server. Restart the dev server.",{error:!0,timeout:20000});data.notes=data.notes.filter((note)=>!pendingDeletes.has(note.id)),agents=data.agents??[],agentListeners.forEach((listener)=>listener(agents));let signature=location.pathname+JSON.stringify([data.notes,data.open,listeners3()]);if(!force&&signature===lastSignature)return;lastSignature=signature;let after=normalized(data.notes);if(primed&&data.notes.length&&notes.length)changeListeners.forEach((listener)=>listener(notes,after));if(first=!primed,primed=!0,notes=after,openCount=data.open,scope&&scope!=="page"){let all=await scopeNotes(scope);if(sequence!==loadSequence)return;scoped=all}}catch(error){if(sequence!==loadSequence)return;if(error instanceof ApiError&&error.status===403&&!tokenWarned)tokenWarned=!0,toast(`${error.message} Notes can't be loaded until then.`,{error:!0,timeout:15000,actions:{Reload:()=>location.reload()}});return}countListeners.forEach((listener)=>listener(openCount)),render({force,first})}function render(what){renderListeners.forEach((listener)=>listener(what))}var scopeNotes=async(which)=>normalized((await api("GET","/notes"+(which==="archived"?query({archived:"1"}):""))).notes).filter((note)=>!pendingDeletes.has(note.id));async function setScope(which){if(scope=which,which&&which!=="page")scoped=await scopeNotes(which)}var streaming=!1;function poll(){let pending=0,changed=()=>{clearTimeout(pending),pending=window.setTimeout(()=>load(),30)},connect=async()=>{let retry=5000;try{let{token,root}=meta(),response=await fetch(root+"/events",{headers:{"X-Tensaku-Token":token,Accept:"text/event-stream"},credentials:"same-origin"});if(response.status===501)return;if(!response.ok||!response.body)throw Error(`events ${response.status}`);streaming=!0;let reader=response.body.pipeThrough(new TextDecoderStream).getReader(),buffer="";for(;;){let{value,done}=await reader.read();if(done)break;buffer+=value;let events=buffer.split(`
362
+ `;var host=document.createElement("tensaku-overlay");host.id="tensaku-overlay";host.setAttribute("data-tensaku-ui","");host.setAttribute("data-turbo-permanent","");var shadow=host.attachShadow({mode:"open"});if("adoptedStyleSheets"in shadow&&typeof CSSStyleSheet<"u"&&"replaceSync"in CSSStyleSheet.prototype){let sheet=new CSSStyleSheet;sheet.replaceSync(overlay_default),shadow.adoptedStyleSheets=[sheet]}else{let style=document.createElement("style");style.textContent=overlay_default,shadow.append(style)}var layer=div("layer"),fixed=div("fixed"),toasts=div("toasts");shadow.append(layer,fixed);fixed.append(toasts);function mount(){if(!host.isConnected)document.documentElement.append(host)}function h(tag,attributes={},...children){let element=document.createElement(tag);for(let[name,value]of Object.entries(attributes)){if(value===void 0||value===null||value===!1)continue;if(name.startsWith("on")&&typeof value==="function")element.addEventListener(name.slice(2),value);else if(name==="className")element.className=value;else element.setAttribute(name,value===!0?"":String(value))}for(let child of children)if(child)element.append(child);return element}function div(className,...children){return h("div",{className},...children)}function toast(message,options={}){let element=div("toast"+(options.error?" error":"")+(options.detail?" detailed":""),h("span",{},message));element.setAttribute("role",options.error?"alert":"status");for(let[label,action]of Object.entries(options.actions??{}))element.append(h("button",{onclick:()=>{element.remove(),action()}},label));if(options.detail)element.append(options.detail);if(toasts.append(element),options.timeout!==0)setTimeout(()=>element.remove(),options.timeout??(options.error?8000:5000));return element}function panel(anchor,className,...children){let element=div("panel "+className,...children);return layer.append(element),place(element,anchor),element}function place(element,anchor,over=!1){let width=element.offsetWidth,left=Math.max(scrollX+8,Math.min(anchor.left,scrollX+innerWidth-width-8)),top=over?anchor.top:anchor.bottom+6;if(!over&&top+element.offsetHeight>scrollY+innerHeight-8&&anchor.top-element.offsetHeight-6>scrollY)top=anchor.top-element.offsetHeight-6;element.style.left=`${left}px`,element.style.top=`${top}px`}function box(rect,className,label){let element=div("box "+className);if(Object.assign(element.style,{left:`${rect.left}px`,top:`${rect.top}px`,width:`${rect.width}px`,height:`${rect.height}px`}),layer.append(element),!label)return[element];let tag=div("label");if(tag.append(label[0]),label[1])tag.append(h("span",{className:"where"},label[1]));return Object.assign(tag.style,{left:`${rect.left}px`,top:`${rect.top}px`}),layer.append(tag),[element,tag]}async function copy(text){try{await navigator.clipboard.writeText(text)}catch{let area=h("textarea",{},text);shadow.append(area),area.select(),document.execCommand("copy"),area.remove()}}function storage(key,fallback){try{let value=localStorage.getItem(`tensaku:${key}`);return value?JSON.parse(value):fallback}catch{return fallback}}function store(key,value){try{localStorage.setItem(`tensaku:${key}`,JSON.stringify(value))}catch{}}function activeInShadow(){return shadow.activeElement}var DEFAULTS={copyFormat:"detailed",notify:!1,shortcuts:{}},current={...DEFAULTS,...storage("settings",{})},listeners=[],settings=()=>current,onSettings=(listener)=>{listeners.push(listener),listener(current)};function changeSettings(change){current={...current,...change},store("settings",current),listeners.forEach((listener)=>listener(current))}var Idiomorph=function(){let noOp=()=>{},defaults={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:noOp,afterNodeAdded:noOp,beforeNodeMorphed:noOp,afterNodeMorphed:noOp,beforeNodeRemoved:noOp,afterNodeRemoved:noOp,beforeAttributeUpdated:noOp},head:{style:"merge",shouldPreserve:(elt)=>elt.getAttribute("im-preserve")==="true",shouldReAppend:(elt)=>elt.getAttribute("im-re-append")==="true",shouldRemove:noOp,afterHeadMorphed:noOp},restoreFocus:!0};function morph(oldNode,newContent,config={}){oldNode=normalizeElement(oldNode);let newNode=normalizeParent(newContent),ctx=createMorphContext(oldNode,newNode,config),morphedNodes=saveAndRestoreFocus(ctx,()=>{return withHeadBlocking(ctx,oldNode,newNode,(ctx2)=>{if(ctx2.morphStyle==="innerHTML")return morphChildren(ctx2,oldNode,newNode),Array.from(oldNode.childNodes);else return morphOuterHTML(ctx2,oldNode,newNode)})});return ctx.pantry.remove(),morphedNodes}function morphOuterHTML(ctx,oldNode,newNode){let oldParent=normalizeParent(oldNode);return morphChildren(ctx,oldParent,newNode,oldNode,oldNode.nextSibling),Array.from(oldParent.childNodes)}function saveAndRestoreFocus(ctx,fn){if(!ctx.config.restoreFocus)return fn();let activeElement=document.activeElement;if(!(activeElement instanceof HTMLInputElement||activeElement instanceof HTMLTextAreaElement))return fn();let{id:activeElementId,selectionStart,selectionEnd}=activeElement,results=fn();if(activeElementId&&activeElementId!==document.activeElement?.getAttribute("id"))activeElement=ctx.target.querySelector(`[id="${activeElementId}"]`),activeElement?.focus();if(activeElement&&!activeElement.selectionEnd&&selectionEnd)activeElement.setSelectionRange(selectionStart,selectionEnd);return results}let morphChildren=function(){function morphChildren2(ctx,oldParent,newParent,insertionPoint=null,endPoint=null){if(oldParent instanceof HTMLTemplateElement&&newParent instanceof HTMLTemplateElement)oldParent=oldParent.content,newParent=newParent.content;insertionPoint||=oldParent.firstChild;for(let newChild of newParent.childNodes){if(insertionPoint&&insertionPoint!=endPoint){let bestMatch=findBestMatch(ctx,newChild,insertionPoint,endPoint);if(bestMatch){if(bestMatch!==insertionPoint)removeNodesBetween(ctx,insertionPoint,bestMatch);morphNode(bestMatch,newChild,ctx),insertionPoint=bestMatch.nextSibling;continue}}if(newChild instanceof Element){let newChildId=newChild.getAttribute("id");if(ctx.persistentIds.has(newChildId)){let movedChild=moveBeforeById(oldParent,newChildId,insertionPoint,ctx);morphNode(movedChild,newChild,ctx),insertionPoint=movedChild.nextSibling;continue}}let insertedNode=createNode(oldParent,newChild,insertionPoint,ctx);if(insertedNode)insertionPoint=insertedNode.nextSibling}while(insertionPoint&&insertionPoint!=endPoint){let tempNode=insertionPoint;insertionPoint=insertionPoint.nextSibling,removeNode(ctx,tempNode)}}function createNode(oldParent,newChild,insertionPoint,ctx){if(ctx.callbacks.beforeNodeAdded(newChild)===!1)return null;if(ctx.idMap.has(newChild)){let newEmptyChild=document.createElement(newChild.tagName);return oldParent.insertBefore(newEmptyChild,insertionPoint),morphNode(newEmptyChild,newChild,ctx),ctx.callbacks.afterNodeAdded(newEmptyChild),newEmptyChild}else{let newClonedChild=document.importNode(newChild,!0);return oldParent.insertBefore(newClonedChild,insertionPoint),ctx.callbacks.afterNodeAdded(newClonedChild),newClonedChild}}let findBestMatch=function(){function findBestMatch2(ctx,node,startPoint,endPoint){let softMatch=null,nextSibling=node.nextSibling,siblingSoftMatchCount=0,cursor2=startPoint;while(cursor2&&cursor2!=endPoint){if(isSoftMatch(cursor2,node)){if(isIdSetMatch(ctx,cursor2,node))return cursor2;if(softMatch===null){if(!ctx.idMap.has(cursor2))softMatch=cursor2}}if(softMatch===null&&nextSibling&&isSoftMatch(cursor2,nextSibling)){if(siblingSoftMatchCount++,nextSibling=nextSibling.nextSibling,siblingSoftMatchCount>=2)softMatch=void 0}if(ctx.activeElementAndParents.includes(cursor2))break;cursor2=cursor2.nextSibling}return softMatch||null}function isIdSetMatch(ctx,oldNode,newNode){let oldSet=ctx.idMap.get(oldNode),newSet=ctx.idMap.get(newNode);if(!newSet||!oldSet)return!1;for(let id of oldSet)if(newSet.has(id))return!0;return!1}function isSoftMatch(oldNode,newNode){let oldElt=oldNode,newElt=newNode;return oldElt.nodeType===newElt.nodeType&&oldElt.tagName===newElt.tagName&&(!oldElt.getAttribute?.("id")||oldElt.getAttribute?.("id")===newElt.getAttribute?.("id"))}return findBestMatch2}();function removeNode(ctx,node){if(ctx.idMap.has(node))moveBefore(ctx.pantry,node,null);else{if(ctx.callbacks.beforeNodeRemoved(node)===!1)return;node.parentNode?.removeChild(node),ctx.callbacks.afterNodeRemoved(node)}}function removeNodesBetween(ctx,startInclusive,endExclusive){let cursor2=startInclusive;while(cursor2&&cursor2!==endExclusive){let tempNode=cursor2;cursor2=cursor2.nextSibling,removeNode(ctx,tempNode)}return cursor2}function moveBeforeById(parentNode,id,after,ctx){let target=ctx.target.getAttribute?.("id")===id&&ctx.target||ctx.target.querySelector(`[id="${id}"]`)||ctx.pantry.querySelector(`[id="${id}"]`);return removeElementFromAncestorsIdMaps(target,ctx),moveBefore(parentNode,target,after),target}function removeElementFromAncestorsIdMaps(element,ctx){let id=element.getAttribute("id");while(element=element.parentNode){let idSet=ctx.idMap.get(element);if(idSet){if(idSet.delete(id),!idSet.size)ctx.idMap.delete(element)}}}function moveBefore(parentNode,element,after){if(parentNode.moveBefore)try{parentNode.moveBefore(element,after)}catch(e){parentNode.insertBefore(element,after)}else parentNode.insertBefore(element,after)}return morphChildren2}(),morphNode=function(){function morphNode2(oldNode,newContent,ctx){if(ctx.ignoreActive&&oldNode===document.activeElement)return null;if(ctx.callbacks.beforeNodeMorphed(oldNode,newContent)===!1)return oldNode;if(oldNode instanceof HTMLHeadElement&&ctx.head.ignore);else if(oldNode instanceof HTMLHeadElement&&ctx.head.style!=="morph")handleHeadElement(oldNode,newContent,ctx);else if(morphAttributes(oldNode,newContent,ctx),!ignoreValueOfActiveElement(oldNode,ctx))morphChildren(ctx,oldNode,newContent);return ctx.callbacks.afterNodeMorphed(oldNode,newContent),oldNode}function morphAttributes(oldNode,newNode,ctx){let type=newNode.nodeType;if(type===1){let oldElt=oldNode,newElt=newNode,oldAttributes=oldElt.attributes,newAttributes=newElt.attributes;for(let newAttribute of newAttributes){if(ignoreAttribute(newAttribute.name,oldElt,"update",ctx))continue;if(oldElt.getAttribute(newAttribute.name)!==newAttribute.value)oldElt.setAttribute(newAttribute.name,newAttribute.value)}for(let i=oldAttributes.length-1;0<=i;i--){let oldAttribute=oldAttributes[i];if(!oldAttribute)continue;if(!newElt.hasAttribute(oldAttribute.name)){if(ignoreAttribute(oldAttribute.name,oldElt,"remove",ctx))continue;oldElt.removeAttribute(oldAttribute.name)}}if(!ignoreValueOfActiveElement(oldElt,ctx))syncInputValue(oldElt,newElt,ctx)}if(type===8||type===3){if(oldNode.nodeValue!==newNode.nodeValue)oldNode.nodeValue=newNode.nodeValue}}function syncInputValue(oldElement,newElement,ctx){if(oldElement instanceof HTMLInputElement&&newElement instanceof HTMLInputElement&&newElement.type!=="file"){let newValue=newElement.value,oldValue=oldElement.value;if(syncBooleanAttribute(oldElement,newElement,"checked",ctx),syncBooleanAttribute(oldElement,newElement,"disabled",ctx),!newElement.hasAttribute("value")){if(!ignoreAttribute("value",oldElement,"remove",ctx))oldElement.value="",oldElement.removeAttribute("value")}else if(oldValue!==newValue){if(!ignoreAttribute("value",oldElement,"update",ctx))oldElement.setAttribute("value",newValue),oldElement.value=newValue}}else if(oldElement instanceof HTMLOptionElement&&newElement instanceof HTMLOptionElement)syncBooleanAttribute(oldElement,newElement,"selected",ctx);else if(oldElement instanceof HTMLTextAreaElement&&newElement instanceof HTMLTextAreaElement){let newValue=newElement.value,oldValue=oldElement.value;if(ignoreAttribute("value",oldElement,"update",ctx))return;if(newValue!==oldValue)oldElement.value=newValue;if(oldElement.firstChild&&oldElement.firstChild.nodeValue!==newValue)oldElement.firstChild.nodeValue=newValue}}function syncBooleanAttribute(oldElement,newElement,attributeName,ctx){let newLiveValue=newElement[attributeName],oldLiveValue=oldElement[attributeName];if(newLiveValue!==oldLiveValue){let ignoreUpdate=ignoreAttribute(attributeName,oldElement,"update",ctx);if(!ignoreUpdate)oldElement[attributeName]=newElement[attributeName];if(newLiveValue){if(!ignoreUpdate)oldElement.setAttribute(attributeName,"")}else if(!ignoreAttribute(attributeName,oldElement,"remove",ctx))oldElement.removeAttribute(attributeName)}}function ignoreAttribute(attr,element,updateType,ctx){if(attr==="value"&&ctx.ignoreActiveValue&&element===document.activeElement)return!0;return ctx.callbacks.beforeAttributeUpdated(attr,element,updateType)===!1}function ignoreValueOfActiveElement(possibleActiveElement,ctx){return!!ctx.ignoreActiveValue&&possibleActiveElement===document.activeElement&&possibleActiveElement!==document.body}return morphNode2}();function withHeadBlocking(ctx,oldNode,newNode,callback){if(ctx.head.block){let oldHead=oldNode.querySelector("head"),newHead=newNode.querySelector("head");if(oldHead&&newHead){let promises=handleHeadElement(oldHead,newHead,ctx);return Promise.all(promises).then(()=>{let newCtx=Object.assign(ctx,{head:{block:!1,ignore:!0}});return callback(newCtx)})}}return callback(ctx)}function handleHeadElement(oldHead,newHead,ctx){let added=[],removed=[],preserved=[],nodesToAppend=[],srcToNewHeadNodes=new Map;for(let newHeadChild of newHead.children)srcToNewHeadNodes.set(newHeadChild.outerHTML,newHeadChild);for(let currentHeadElt of oldHead.children){let inNewContent=srcToNewHeadNodes.has(currentHeadElt.outerHTML),isReAppended=ctx.head.shouldReAppend(currentHeadElt),isPreserved=ctx.head.shouldPreserve(currentHeadElt);if(inNewContent||isPreserved)if(isReAppended)removed.push(currentHeadElt);else srcToNewHeadNodes.delete(currentHeadElt.outerHTML),preserved.push(currentHeadElt);else if(ctx.head.style==="append"){if(isReAppended)removed.push(currentHeadElt),nodesToAppend.push(currentHeadElt)}else if(ctx.head.shouldRemove(currentHeadElt)!==!1)removed.push(currentHeadElt)}nodesToAppend.push(...srcToNewHeadNodes.values());let promises=[];for(let newNode of nodesToAppend){let newElt=document.createRange().createContextualFragment(newNode.outerHTML).firstChild;if(ctx.callbacks.beforeNodeAdded(newElt)!==!1){if("href"in newElt&&newElt.href||"src"in newElt&&newElt.src){let resolve,promise=new Promise(function(_resolve){resolve=_resolve});newElt.addEventListener("load",function(){resolve()}),promises.push(promise)}oldHead.appendChild(newElt),ctx.callbacks.afterNodeAdded(newElt),added.push(newElt)}}for(let removedElement of removed)if(ctx.callbacks.beforeNodeRemoved(removedElement)!==!1)oldHead.removeChild(removedElement),ctx.callbacks.afterNodeRemoved(removedElement);return ctx.head.afterHeadMorphed(oldHead,{added,kept:preserved,removed}),promises}let createMorphContext=function(){function createMorphContext2(oldNode,newContent,config){let{persistentIds,idMap}=createIdMaps(oldNode,newContent),mergedConfig=mergeDefaults(config),morphStyle=mergedConfig.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(morphStyle))throw`Do not understand how to morph style ${morphStyle}`;return{target:oldNode,newContent,config:mergedConfig,morphStyle,ignoreActive:mergedConfig.ignoreActive,ignoreActiveValue:mergedConfig.ignoreActiveValue,restoreFocus:mergedConfig.restoreFocus,idMap,persistentIds,pantry:createPantry(),activeElementAndParents:createActiveElementAndParents(oldNode),callbacks:mergedConfig.callbacks,head:mergedConfig.head}}function mergeDefaults(config){let finalConfig=Object.assign({},defaults);return Object.assign(finalConfig,config),finalConfig.callbacks=Object.assign({},defaults.callbacks,config.callbacks),finalConfig.head=Object.assign({},defaults.head,config.head),finalConfig}function createPantry(){let pantry=document.createElement("div");return pantry.hidden=!0,document.body.insertAdjacentElement("afterend",pantry),pantry}function createActiveElementAndParents(oldNode){let activeElementAndParents=[],elt=document.activeElement;if(elt?.tagName!=="BODY"&&oldNode.contains(elt))while(elt){if(activeElementAndParents.push(elt),elt===oldNode)break;elt=elt.parentElement}return activeElementAndParents}function findIdElements(root){let elements=Array.from(root.querySelectorAll("[id]"));if(root.getAttribute?.("id"))elements.push(root);return elements}function populateIdMapWithTree(idMap,persistentIds,root,elements){for(let elt of elements){let id=elt.getAttribute("id");if(persistentIds.has(id)){let current2=elt;while(current2){let idSet=idMap.get(current2);if(idSet==null)idSet=new Set,idMap.set(current2,idSet);if(idSet.add(id),current2===root)break;current2=current2.parentElement}}}}function createIdMaps(oldContent,newContent){let oldIdElements=findIdElements(oldContent),newIdElements=findIdElements(newContent),persistentIds=createPersistentIds(oldIdElements,newIdElements),idMap=new Map;populateIdMapWithTree(idMap,persistentIds,oldContent,oldIdElements);let newRoot=newContent.__idiomorphRoot||newContent;return populateIdMapWithTree(idMap,persistentIds,newRoot,newIdElements),{persistentIds,idMap}}function createPersistentIds(oldIdElements,newIdElements){let duplicateIds=new Set,oldIdTagNameMap=new Map;for(let{id,tagName}of oldIdElements)if(oldIdTagNameMap.has(id))duplicateIds.add(id);else oldIdTagNameMap.set(id,tagName);let persistentIds=new Set;for(let{id,tagName}of newIdElements)if(persistentIds.has(id))duplicateIds.add(id);else if(oldIdTagNameMap.get(id)===tagName)persistentIds.add(id);for(let id of duplicateIds)persistentIds.delete(id);return persistentIds}return createMorphContext2}(),{normalizeElement,normalizeParent}=function(){let generatedByIdiomorph=new WeakSet;function normalizeElement2(content){if(content instanceof Document)return content.documentElement;else return content}function normalizeParent2(newContent){if(newContent==null)return document.createElement("div");else if(typeof newContent==="string")return normalizeParent2(parseContent(newContent));else if(generatedByIdiomorph.has(newContent))return newContent;else if(newContent instanceof Node)if(newContent.parentNode)return new SlicedParentNode(newContent);else{let dummyParent=document.createElement("div");return dummyParent.append(newContent),dummyParent}else{let dummyParent=document.createElement("div");for(let elt of[...newContent])dummyParent.append(elt);return dummyParent}}class SlicedParentNode{constructor(node){this.originalNode=node,this.realParentNode=node.parentNode,this.previousSibling=node.previousSibling,this.nextSibling=node.nextSibling}get childNodes(){let nodes=[],cursor2=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;while(cursor2&&cursor2!=this.nextSibling)nodes.push(cursor2),cursor2=cursor2.nextSibling;return nodes}querySelectorAll(selector){return this.childNodes.reduce((results,node)=>{if(node instanceof Element){if(node.matches(selector))results.push(node);let nodeList=node.querySelectorAll(selector);for(let i=0;i<nodeList.length;i++)results.push(nodeList[i])}return results},[])}insertBefore(node,referenceNode){return this.realParentNode.insertBefore(node,referenceNode)}moveBefore(node,referenceNode){return this.realParentNode.moveBefore(node,referenceNode)}get __idiomorphRoot(){return this.originalNode}}function parseContent(newContent){let parser=new DOMParser,contentWithSvgsRemoved=newContent.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(contentWithSvgsRemoved.match(/<\/html>/)||contentWithSvgsRemoved.match(/<\/head>/)||contentWithSvgsRemoved.match(/<\/body>/)){let content=parser.parseFromString(newContent,"text/html");if(contentWithSvgsRemoved.match(/<\/html>/))return generatedByIdiomorph.add(content),content;else{let htmlElement=content.firstChild;if(htmlElement)generatedByIdiomorph.add(htmlElement);return htmlElement}}else{let content=parser.parseFromString("<body><template>"+newContent+"</template></body>","text/html").body.querySelector("template").content;return generatedByIdiomorph.add(content),content}}return{normalizeElement:normalizeElement2,normalizeParent:normalizeParent2}}();return{morph,defaults}}();var listeners2=[];function onRefresh(listener){listeners2.push(listener)}function permanent(node){return node instanceof Element&&(node.hasAttribute("data-turbo-permanent")||node.hasAttribute("data-tensaku-permanent")||node.hasAttribute("data-tensaku-ui"))}function herbDevServer(){return Boolean(document.querySelector('meta[name="herb-dev-server-port"]'))}function replaceText(nodes,from,to){let normal=(text)=>text.replace(/\s+/g," ").trim(),target=normal(from);if(!target)return;for(let node of nodes)if(normal(node.data)===target){let lead=node.data.match(/^\s*/)[0],trail=node.data.match(/\s*$/)[0];node.data=lead+to.trim()+trail}else if(node.data.includes(from)&&from.trim())node.data=node.data.replace(from,to)}async function refresh(kind){if(meta().method!=="GET"){toast("Saved. This page came from a form submission, so reload to check it.",{timeout:7000});return}if(kind==="template"&&herbDevServer())return;try{let response=await fetch(location.href,{headers:{Accept:"text/html","X-Tensaku-Refresh":"1"},credentials:"same-origin"});if(!response.ok)throw Error(`HTTP ${response.status}`);let html=await response.text(),next=new DOMParser().parseFromString(html,"text/html");morph(next)}catch(error){toast(`Saved, but refreshing the page failed (${error.message}). Reload to check.`,{error:!0})}}var agentFetch=0;async function refreshAfterAgent(){if(meta().method!=="GET")return;let sequence=++agentFetch;try{let response=await fetch(location.href,{headers:{Accept:"text/html","X-Tensaku-Refresh":"1"},credentials:"same-origin"});if(!response.ok)return;let html=await response.text();if(sequence!==agentFetch)return;let next=new DOMParser().parseFromString(html,"text/html");swapStylesheets(next),morph(next)}catch{}}function swapStylesheets(next){let wanted=new Set(((doc)=>Array.from(doc.querySelectorAll('head link[rel="stylesheet"]')).map((link)=>link.getAttribute("href")))(next)),current2=Array.from(document.querySelectorAll('head link[rel="stylesheet"]')),have=new Set(current2.map((link)=>link.getAttribute("href"))),added=Array.from(next.querySelectorAll('head link[rel="stylesheet"]')).filter((link)=>!have.has(link.getAttribute("href")));if(!added.length)return;let stale=current2.filter((link)=>!wanted.has(link.getAttribute("href"))),waiting=added.length;for(let link of added){let copy2=document.importNode(link,!0),done=()=>{if(--waiting===0)stale.forEach((old)=>old.remove())};copy2.addEventListener("load",done),copy2.addEventListener("error",done),document.head.append(copy2)}}function changedByUser(element){if(element instanceof HTMLInputElement){if(element.type==="checkbox"||element.type==="radio")return element.checked!==element.defaultChecked;return element.type!=="file"&&element.value!==element.defaultValue}if(element instanceof HTMLTextAreaElement)return element.value!==element.defaultValue;if(element instanceof HTMLOptionElement)return element.selected!==element.defaultSelected;if(element instanceof HTMLSelectElement)return Array.from(element.options).some((option)=>option.selected!==option.defaultSelected);return!1}var FORM_STATE=new Set(["value","checked","selected"]);function morph(next){let lazyFrames=Array.from(document.querySelectorAll("turbo-frame[src]"));if(Idiomorph.morph(document.body,next.body,{morphStyle:"outerHTML",ignoreActiveValue:!0,restoreFocus:!0,callbacks:{beforeNodeMorphed:(oldNode)=>!permanent(oldNode)&&!(oldNode instanceof HTMLTextAreaElement&&changedByUser(oldNode)),beforeAttributeUpdated:(name,element)=>!(FORM_STATE.has(name)&&changedByUser(element)),beforeNodeRemoved:(node)=>!permanent(node)}}),next.title)document.title=next.title;for(let frame of lazyFrames)if(frame.isConnected&&typeof frame.reload==="function"&&!frame.hasAttribute("complete"))frame.reload();listeners2.forEach((listener)=>listener())}var notes=[],scoped=[],scope=null,openCount=0,agents=[],currentNotes=()=>notes,scopedNotes=()=>scoped,currentAgents=()=>agents,openNotes=()=>openCount,agentLabel=(agent)=>agent.handle?`${agent.name} · ${agent.handle}`:agent.name,listeners3=()=>agents.filter((agent)=>agent.listening).map(agentLabel),closed=(note)=>note.status==="resolved"||note.status==="declined",renderListeners=[],countListeners=[],agentListeners=[],changeListeners=[],onRender=(listener)=>renderListeners.push(listener),onCount=(listener)=>countListeners.push(listener),onAgents=(listener)=>agentListeners.push(listener),onChanges=(listener)=>changeListeners.push(listener),normalized=(list)=>list.map((note)=>({...note,targets:note.targets??[]})),lastSignature="",loadSequence=0,tokenWarned=!1,restartWarned=!1,agentChangedAt,primed=!1;async function load({force=!1}={}){let sequence=++loadSequence,first=!1;try{let data=await api("GET","/notes"+query({url:location.pathname}));if(sequence!==loadSequence)return;if(tokenWarned=!1,primed&&data.changed_at&&data.changed_at!==agentChangedAt)refreshAfterAgent();if(agentChangedAt=data.changed_at,data.restart&&!restartWarned)restartWarned=!0,toast("Tensaku's code changed since this dev server started, so the page runs a newer overlay than the server. Restart the dev server.",{error:!0,timeout:20000});data.notes=data.notes.filter((note)=>!pendingDeletes.has(note.id)),agents=data.agents??[],agentListeners.forEach((listener)=>listener(agents));let signature=location.pathname+JSON.stringify([data.notes,data.open,listeners3()]);if(!force&&signature===lastSignature)return;lastSignature=signature;let after=normalized(data.notes);if(primed&&data.notes.length&&notes.length)changeListeners.forEach((listener)=>listener(notes,after));if(first=!primed,primed=!0,notes=after,openCount=data.open,scope&&scope!=="page"){let all=await scopeNotes(scope);if(sequence!==loadSequence)return;scoped=all}}catch(error){if(sequence!==loadSequence)return;if(error instanceof ApiError&&error.status===403&&!tokenWarned)tokenWarned=!0,toast(`${error.message} Notes can't be loaded until then.`,{error:!0,timeout:15000,actions:{Reload:()=>location.reload()}});return}countListeners.forEach((listener)=>listener(openCount)),render({force,first})}function render(what){renderListeners.forEach((listener)=>listener(what))}var scopeNotes=async(which)=>normalized((await api("GET","/notes"+(which==="archived"?query({archived:"1"}):""))).notes).filter((note)=>!pendingDeletes.has(note.id));async function setScope(which){if(scope=which,which&&which!=="page")scoped=await scopeNotes(which)}var streaming=!1;function poll(){let pending=0,changed=()=>{clearTimeout(pending),pending=window.setTimeout(()=>load(),30)},editedPending=0,edited=()=>{clearTimeout(editedPending),editedPending=window.setTimeout(refreshAfterAgent,150)},connect=async()=>{let retry=5000;try{let{token,root}=meta(),response=await fetch(root+"/events",{headers:{"X-Tensaku-Token":token,Accept:"text/event-stream"},credentials:"same-origin"});if(response.status===501)return;if(!response.ok||!response.body)throw Error(`events ${response.status}`);streaming=!0;let reader=response.body.pipeThrough(new TextDecoderStream).getReader(),buffer="";for(;;){let{value,done}=await reader.read();if(done)break;buffer+=value;let events=buffer.split(`
354
363
 
355
- `);if(buffer=events.pop()??"",events.some((event)=>event.startsWith("data:")))changed()}}catch{retry=15000}streaming=!1,setTimeout(connect,retry)},tick=async()=>{if(!streaming&&(document.visibilityState==="visible"||settings().notify))await load();setTimeout(tick,document.visibilityState==="visible"?4000:16000)};connect(),setTimeout(tick,4000)}var localChanges=new Set,changedHere=(id)=>localChanges.delete(id);function replace(note,removed=!1){let swap=(list)=>removed?list.filter((other)=>other.id!==note.id):list.map((other)=>other.id===note.id?note:other);notes=swap(notes),scoped=swap(scoped),lastSignature="",render({force:!0,changed:removed?void 0:note})}function predicted(note,change){let next={...note,thread:[...note.thread??[]]};if(change.comment)next.comment=change.comment;if(change.message)next.thread.push({from:"you",text:change.message,at:new Date().toISOString()});if(change.status)next.status=change.status;if(change.to!==void 0){let chosen=agents.find((agent)=>agent.handle===change.to);Object.assign(next,{status:"open",agent:chosen?agentLabel(chosen):void 0,delivered_at:void 0,delivered_to:void 0,stopped:void 0})}if(next.status==="open"&&(change.comment||change.message||change.to!==void 0))next.sent_at=new Date().toISOString();return next}async function updateNote(note,change,onChange=()=>{}){let after=predicted(note,change);localChanges.add(note.id),replace(after),onChange(after);try{return await api("PATCH",`/notes/${note.id}`,change),load({force:!0}),!0}catch(error){return localChanges.delete(note.id),replace(note),onChange(note),toast(error.message,{error:!0}),!1}}var pendingDeletes=new Map;addEventListener("pagehide",()=>pendingDeletes.forEach((commit)=>commit()));function deleteLater(note){replace(note,!0);let done=!1,commit=()=>{if(done)return;done=!0,pendingDeletes.delete(note.id),api("DELETE",`/notes/${note.id}`).catch((error)=>toast(error.message,{error:!0})).finally(()=>load({force:!0}))};pendingDeletes.set(note.id,commit);let timer=setTimeout(commit,6000);toast("Note deleted",{timeout:6000,actions:{Undo:()=>{done=!0,clearTimeout(timer),pendingDeletes.delete(note.id),load({force:!0})}}})}async function deleteNotes(list){try{for(let note of list)await api("DELETE",`/notes/${note.id}`)}finally{await load({force:!0})}}var PREFIX="[modern-screenshot]",IN_BROWSER=typeof window<"u",SUPPORT_WEB_WORKER=IN_BROWSER&&"Worker"in window,SUPPORT_ATOB=IN_BROWSER&&"atob"in window,SUPPORT_BTOA=IN_BROWSER&&"btoa"in window,USER_AGENT=IN_BROWSER?window.navigator?.userAgent:"",IN_CHROME=USER_AGENT.includes("Chrome"),IN_SAFARI=USER_AGENT.includes("AppleWebKit")&&!IN_CHROME,IN_FIREFOX=USER_AGENT.includes("Firefox"),isContext=(value)=>value&&("__CONTEXT__"in value),isCssFontFaceRule=(rule)=>rule.constructor.name==="CSSFontFaceRule",isCSSImportRule=(rule)=>rule.constructor.name==="CSSImportRule",isLayerBlockRule=(rule)=>rule.constructor.name==="CSSLayerBlockRule",isElementNode=(node)=>node.nodeType===1,isSVGElementNode=(node)=>typeof node.className==="object",isSVGImageElementNode=(node)=>node.tagName==="image",isSVGUseElementNode=(node)=>node.tagName==="use",isHTMLElementNode=(node)=>isElementNode(node)&&typeof node.style<"u"&&!isSVGElementNode(node),isCommentNode=(node)=>node.nodeType===8,isTextNode=(node)=>node.nodeType===3,isImageElement=(node)=>node.tagName==="IMG",isVideoElement=(node)=>node.tagName==="VIDEO",isCanvasElement=(node)=>node.tagName==="CANVAS",isTextareaElement=(node)=>node.tagName==="TEXTAREA",isInputElement=(node)=>node.tagName==="INPUT",isStyleElement=(node)=>node.tagName==="STYLE",isScriptElement=(node)=>node.tagName==="SCRIPT",isSelectElement=(node)=>node.tagName==="SELECT",isSlotElement=(node)=>node.tagName==="SLOT",isIFrameElement=(node)=>node.tagName==="IFRAME",consoleWarn=(...args)=>console.warn(PREFIX,...args);function supportWebp(ownerDocument){let canvas=ownerDocument?.createElement?.("canvas");if(canvas)canvas.height=canvas.width=1;return Boolean(canvas)&&"toDataURL"in canvas&&Boolean(canvas.toDataURL("image/webp").includes("image/webp"))}var isDataUrl=(url)=>url.startsWith("data:");function resolveUrl(url,baseUrl){if(url.match(/^[a-z]+:\/\//i))return url;if(IN_BROWSER&&url.match(/^\/\//))return window.location.protocol+url;if(url.match(/^[a-z]+:/i))return url;if(!IN_BROWSER)return url;let doc=getDocument().implementation.createHTMLDocument(),base=doc.createElement("base"),a=doc.createElement("a");if(doc.head.appendChild(base),doc.body.appendChild(a),baseUrl)base.href=baseUrl;return a.href=url,a.href}function getDocument(target){return(target&&isElementNode(target)?target?.ownerDocument:target)??window.document}var XMLNS="http://www.w3.org/2000/svg";function createSvg(width,height,ownerDocument){let svg=getDocument(ownerDocument).createElementNS(XMLNS,"svg");return svg.setAttributeNS(null,"width",width.toString()),svg.setAttributeNS(null,"height",height.toString()),svg.setAttributeNS(null,"viewBox",`0 0 ${width} ${height}`),svg}function svgToDataUrl(svg,removeControlCharacter){let xhtml=new XMLSerializer().serializeToString(svg);if(removeControlCharacter)xhtml=xhtml.replace(/[\u0000-\u0008\v\f\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/gu,"");return`data:image/svg+xml;charset=utf-8,${encodeURIComponent(xhtml)}`}function readBlob(blob,type){return new Promise((resolve,reject)=>{let reader=new FileReader;if(reader.onload=()=>resolve(reader.result),reader.onerror=()=>reject(reader.error),reader.onabort=()=>reject(Error(`Failed read blob to ${type}`)),type==="dataUrl")reader.readAsDataURL(blob);else if(type==="arrayBuffer")reader.readAsArrayBuffer(blob)})}var blobToDataUrl=(blob)=>readBlob(blob,"dataUrl");function createImage(url,ownerDocument){let img=getDocument(ownerDocument).createElement("img");return img.decoding="sync",img.loading="eager",img.src=url,img}function loadMedia(media,options){return new Promise((resolve)=>{let{timeout,ownerDocument,onError:userOnError,onWarn}=options??{},node=typeof media==="string"?createImage(media,getDocument(ownerDocument)):media,timer=null,removeEventListeners=null;function onResolve(){resolve(node),timer&&clearTimeout(timer),removeEventListeners?.()}if(timeout)timer=setTimeout(onResolve,timeout);if(isVideoElement(node)){let currentSrc=node.currentSrc||node.src;if(!currentSrc){if(node.poster)return loadMedia(node.poster,options).then(resolve);return onResolve()}if(node.readyState>=2)return onResolve();let onLoadeddata=onResolve,onError=(error)=>{onWarn?.("Failed video load",currentSrc,error),userOnError?.(error),onResolve()};removeEventListeners=()=>{node.removeEventListener("loadeddata",onLoadeddata),node.removeEventListener("error",onError)},node.addEventListener("loadeddata",onLoadeddata,{once:!0}),node.addEventListener("error",onError,{once:!0})}else{let currentSrc=isSVGImageElementNode(node)?node.href.baseVal:node.currentSrc||node.src;if(!currentSrc)return onResolve();let onLoad=async()=>{if(isImageElement(node)&&"decode"in node)try{await node.decode()}catch(error){onWarn?.("Failed to decode image, trying to render anyway",node.dataset.originalSrc||currentSrc,error)}onResolve()},onError=(error)=>{onWarn?.("Failed image load",node.dataset.originalSrc||currentSrc,error),onResolve()};if(isImageElement(node)&&node.complete)return onLoad();removeEventListeners=()=>{node.removeEventListener("load",onLoad),node.removeEventListener("error",onError)},node.addEventListener("load",onLoad,{once:!0}),node.addEventListener("error",onError,{once:!0})}})}async function waitUntilLoad(node,options){if(isHTMLElementNode(node))if(isImageElement(node)||isVideoElement(node))await loadMedia(node,options);else await Promise.all(["img","video"].flatMap((selectors)=>{return Array.from(node.querySelectorAll(selectors)).map((el)=>loadMedia(el,options))}))}var uuid=function(){let counter=0,random=()=>`0000${(Math.random()*1679616<<0).toString(36)}`.slice(-4);return()=>{return counter+=1,`u${random()}${counter}`}}();function splitFontFamily(fontFamily){return fontFamily?.split(",").map((val)=>val.trim().replace(/"|'/g,"").toLowerCase()).filter(Boolean)}var uid=0;function createLogger(debug){let prefix=`${PREFIX}[#${uid}]`;return uid++,{time:(label)=>debug&&console.time(`${prefix} ${label}`),timeEnd:(label)=>debug&&console.timeEnd(`${prefix} ${label}`),warn:(...args)=>debug&&consoleWarn(...args)}}function getDefaultRequestInit(bypassingCache){return{cache:bypassingCache?"no-cache":"force-cache"}}async function orCreateContext(node,options){return isContext(node)?node:createContext(node,{...options,autoDestruct:!0})}async function createContext(node,options){let{scale=1,workerUrl,workerNumber=1}=options||{},debug=Boolean(options?.debug),features=options?.features??!0,ownerDocument=node.ownerDocument??(IN_BROWSER?window.document:void 0),ownerWindow=node.ownerDocument?.defaultView??(IN_BROWSER?window:void 0),requests=new Map,context={width:0,height:0,quality:1,type:"image/png",scale,backgroundColor:null,style:null,filter:null,maximumCanvasSize:0,timeout:30000,progress:null,debug,fetch:{requestInit:getDefaultRequestInit(options?.fetch?.bypassingCache),placeholderImage:"data:image/png;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",bypassingCache:!1,...options?.fetch},fetchFn:null,font:{},drawImageInterval:100,workerUrl:null,workerNumber,onCloneEachNode:null,onCloneNode:null,onEmbedNode:null,onCreateForeignObjectSvg:null,includeStyleProperties:null,autoDestruct:!1,...options,__CONTEXT__:!0,log:createLogger(debug),node,ownerDocument,ownerWindow,dpi:scale===1?null:96*scale,svgStyleElement:createStyleElement(ownerDocument),svgDefsElement:ownerDocument?.createElementNS(XMLNS,"defs"),svgStyles:new Map,defaultComputedStyles:new Map,workers:[...Array.from({length:SUPPORT_WEB_WORKER&&workerUrl&&workerNumber?workerNumber:0})].map(()=>{try{let worker=new Worker(workerUrl);return worker.onmessage=async(event)=>{let{url,result}=event.data;if(result)requests.get(url)?.resolve?.(result);else requests.get(url)?.reject?.(Error(`Error receiving message from worker: ${url}`))},worker.onmessageerror=(event)=>{let{url}=event.data;requests.get(url)?.reject?.(Error(`Error receiving message from worker: ${url}`))},worker}catch(error){return context.log.warn("Failed to new Worker",error),null}}).filter(Boolean),fontFamilies:new Map,fontCssTexts:new Map,acceptOfImage:`${[supportWebp(ownerDocument)&&"image/webp","image/svg+xml","image/*","*/*"].filter(Boolean).join(",")};q=0.8`,requests,drawImageCount:0,tasks:[],features,isEnable:(key)=>{if(key==="restoreScrollPosition")return typeof features==="boolean"?!1:features[key]??!1;if(typeof features==="boolean")return features;return features[key]??!0},shadowRoots:[]};context.log.time("wait until load"),await waitUntilLoad(node,{timeout:context.timeout,onWarn:context.log.warn}),context.log.timeEnd("wait until load");let{width,height}=resolveBoundingBox(node,context);return context.width=width,context.height=height,context}function createStyleElement(ownerDocument){if(!ownerDocument)return;let style=ownerDocument.createElement("style"),cssText=style.ownerDocument.createTextNode(`
364
+ `);if(buffer=events.pop()??"",events.includes("data: changed"))changed();if(events.includes("data: edited"))edited()}}catch{retry=15000}streaming=!1,setTimeout(connect,retry)},tick=async()=>{if(!streaming&&(document.visibilityState==="visible"||settings().notify))await load();setTimeout(tick,document.visibilityState==="visible"?4000:16000)};connect(),setTimeout(tick,4000)}var localChanges=new Set,changedHere=(id)=>localChanges.delete(id);function replace(note,removed=!1){let swap=(list)=>removed?list.filter((other)=>other.id!==note.id):list.map((other)=>other.id===note.id?note:other);notes=swap(notes),scoped=swap(scoped),lastSignature="",render({force:!0,changed:removed?void 0:note})}function predicted(note,change){let next={...note,thread:[...note.thread??[]]};if(change.comment)next.comment=change.comment;if(change.message)next.thread.push({from:"you",text:change.message,at:new Date().toISOString()});if(change.status)next.status=change.status;if(change.to!==void 0){let chosen=agents.find((agent)=>agent.handle===change.to);Object.assign(next,{status:"open",agent:chosen?agentLabel(chosen):void 0,delivered_at:void 0,delivered_to:void 0,stopped:void 0})}if(next.status==="open"&&(change.comment||change.message||change.to!==void 0))next.sent_at=new Date().toISOString();return next}async function updateNote(note,change,onChange=()=>{}){let after=predicted(note,change);localChanges.add(note.id),replace(after),onChange(after);try{return await api("PATCH",`/notes/${note.id}`,change),load({force:!0}),!0}catch(error){return localChanges.delete(note.id),replace(note),onChange(note),toast(error.message,{error:!0}),!1}}var pendingDeletes=new Map;addEventListener("pagehide",()=>pendingDeletes.forEach((commit)=>commit()));function deleteLater(note){replace(note,!0);let done=!1,commit=()=>{if(done)return;done=!0,pendingDeletes.delete(note.id),api("DELETE",`/notes/${note.id}`).catch((error)=>toast(error.message,{error:!0})).finally(()=>load({force:!0}))};pendingDeletes.set(note.id,commit);let timer=setTimeout(commit,6000);toast("Note deleted",{timeout:6000,actions:{Undo:()=>{done=!0,clearTimeout(timer),pendingDeletes.delete(note.id),load({force:!0})}}})}async function deleteNotes(list){try{for(let note of list)await api("DELETE",`/notes/${note.id}`)}finally{await load({force:!0})}}var PREFIX="[modern-screenshot]",IN_BROWSER=typeof window<"u",SUPPORT_WEB_WORKER=IN_BROWSER&&"Worker"in window,SUPPORT_ATOB=IN_BROWSER&&"atob"in window,SUPPORT_BTOA=IN_BROWSER&&"btoa"in window,USER_AGENT=IN_BROWSER?window.navigator?.userAgent:"",IN_CHROME=USER_AGENT.includes("Chrome"),IN_SAFARI=USER_AGENT.includes("AppleWebKit")&&!IN_CHROME,IN_FIREFOX=USER_AGENT.includes("Firefox"),isContext=(value)=>value&&("__CONTEXT__"in value),isCssFontFaceRule=(rule)=>rule.constructor.name==="CSSFontFaceRule",isCSSImportRule=(rule)=>rule.constructor.name==="CSSImportRule",isLayerBlockRule=(rule)=>rule.constructor.name==="CSSLayerBlockRule",isElementNode=(node)=>node.nodeType===1,isSVGElementNode=(node)=>typeof node.className==="object",isSVGImageElementNode=(node)=>node.tagName==="image",isSVGUseElementNode=(node)=>node.tagName==="use",isHTMLElementNode=(node)=>isElementNode(node)&&typeof node.style<"u"&&!isSVGElementNode(node),isCommentNode=(node)=>node.nodeType===8,isTextNode=(node)=>node.nodeType===3,isImageElement=(node)=>node.tagName==="IMG",isVideoElement=(node)=>node.tagName==="VIDEO",isCanvasElement=(node)=>node.tagName==="CANVAS",isTextareaElement=(node)=>node.tagName==="TEXTAREA",isInputElement=(node)=>node.tagName==="INPUT",isStyleElement=(node)=>node.tagName==="STYLE",isScriptElement=(node)=>node.tagName==="SCRIPT",isSelectElement=(node)=>node.tagName==="SELECT",isSlotElement=(node)=>node.tagName==="SLOT",isIFrameElement=(node)=>node.tagName==="IFRAME",consoleWarn=(...args)=>console.warn(PREFIX,...args);function supportWebp(ownerDocument){let canvas=ownerDocument?.createElement?.("canvas");if(canvas)canvas.height=canvas.width=1;return Boolean(canvas)&&"toDataURL"in canvas&&Boolean(canvas.toDataURL("image/webp").includes("image/webp"))}var isDataUrl=(url)=>url.startsWith("data:");function resolveUrl(url,baseUrl){if(url.match(/^[a-z]+:\/\//i))return url;if(IN_BROWSER&&url.match(/^\/\//))return window.location.protocol+url;if(url.match(/^[a-z]+:/i))return url;if(!IN_BROWSER)return url;let doc=getDocument().implementation.createHTMLDocument(),base=doc.createElement("base"),a=doc.createElement("a");if(doc.head.appendChild(base),doc.body.appendChild(a),baseUrl)base.href=baseUrl;return a.href=url,a.href}function getDocument(target){return(target&&isElementNode(target)?target?.ownerDocument:target)??window.document}var XMLNS="http://www.w3.org/2000/svg";function createSvg(width,height,ownerDocument){let svg=getDocument(ownerDocument).createElementNS(XMLNS,"svg");return svg.setAttributeNS(null,"width",width.toString()),svg.setAttributeNS(null,"height",height.toString()),svg.setAttributeNS(null,"viewBox",`0 0 ${width} ${height}`),svg}function svgToDataUrl(svg,removeControlCharacter){let xhtml=new XMLSerializer().serializeToString(svg);if(removeControlCharacter)xhtml=xhtml.replace(/[\u0000-\u0008\v\f\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/gu,"");return`data:image/svg+xml;charset=utf-8,${encodeURIComponent(xhtml)}`}function readBlob(blob,type){return new Promise((resolve,reject)=>{let reader=new FileReader;if(reader.onload=()=>resolve(reader.result),reader.onerror=()=>reject(reader.error),reader.onabort=()=>reject(Error(`Failed read blob to ${type}`)),type==="dataUrl")reader.readAsDataURL(blob);else if(type==="arrayBuffer")reader.readAsArrayBuffer(blob)})}var blobToDataUrl=(blob)=>readBlob(blob,"dataUrl");function createImage(url,ownerDocument){let img=getDocument(ownerDocument).createElement("img");return img.decoding="sync",img.loading="eager",img.src=url,img}function loadMedia(media,options){return new Promise((resolve)=>{let{timeout,ownerDocument,onError:userOnError,onWarn}=options??{},node=typeof media==="string"?createImage(media,getDocument(ownerDocument)):media,timer=null,removeEventListeners=null;function onResolve(){resolve(node),timer&&clearTimeout(timer),removeEventListeners?.()}if(timeout)timer=setTimeout(onResolve,timeout);if(isVideoElement(node)){let currentSrc=node.currentSrc||node.src;if(!currentSrc){if(node.poster)return loadMedia(node.poster,options).then(resolve);return onResolve()}if(node.readyState>=2)return onResolve();let onLoadeddata=onResolve,onError=(error)=>{onWarn?.("Failed video load",currentSrc,error),userOnError?.(error),onResolve()};removeEventListeners=()=>{node.removeEventListener("loadeddata",onLoadeddata),node.removeEventListener("error",onError)},node.addEventListener("loadeddata",onLoadeddata,{once:!0}),node.addEventListener("error",onError,{once:!0})}else{let currentSrc=isSVGImageElementNode(node)?node.href.baseVal:node.currentSrc||node.src;if(!currentSrc)return onResolve();let onLoad=async()=>{if(isImageElement(node)&&"decode"in node)try{await node.decode()}catch(error){onWarn?.("Failed to decode image, trying to render anyway",node.dataset.originalSrc||currentSrc,error)}onResolve()},onError=(error)=>{onWarn?.("Failed image load",node.dataset.originalSrc||currentSrc,error),onResolve()};if(isImageElement(node)&&node.complete)return onLoad();removeEventListeners=()=>{node.removeEventListener("load",onLoad),node.removeEventListener("error",onError)},node.addEventListener("load",onLoad,{once:!0}),node.addEventListener("error",onError,{once:!0})}})}async function waitUntilLoad(node,options){if(isHTMLElementNode(node))if(isImageElement(node)||isVideoElement(node))await loadMedia(node,options);else await Promise.all(["img","video"].flatMap((selectors)=>{return Array.from(node.querySelectorAll(selectors)).map((el)=>loadMedia(el,options))}))}var uuid=function(){let counter=0,random=()=>`0000${(Math.random()*1679616<<0).toString(36)}`.slice(-4);return()=>{return counter+=1,`u${random()}${counter}`}}();function splitFontFamily(fontFamily){return fontFamily?.split(",").map((val)=>val.trim().replace(/"|'/g,"").toLowerCase()).filter(Boolean)}var uid=0;function createLogger(debug){let prefix=`${PREFIX}[#${uid}]`;return uid++,{time:(label)=>debug&&console.time(`${prefix} ${label}`),timeEnd:(label)=>debug&&console.timeEnd(`${prefix} ${label}`),warn:(...args)=>debug&&consoleWarn(...args)}}function getDefaultRequestInit(bypassingCache){return{cache:bypassingCache?"no-cache":"force-cache"}}async function orCreateContext(node,options){return isContext(node)?node:createContext(node,{...options,autoDestruct:!0})}async function createContext(node,options){let{scale=1,workerUrl,workerNumber=1}=options||{},debug=Boolean(options?.debug),features=options?.features??!0,ownerDocument=node.ownerDocument??(IN_BROWSER?window.document:void 0),ownerWindow=node.ownerDocument?.defaultView??(IN_BROWSER?window:void 0),requests=new Map,context={width:0,height:0,quality:1,type:"image/png",scale,backgroundColor:null,style:null,filter:null,maximumCanvasSize:0,timeout:30000,progress:null,debug,fetch:{requestInit:getDefaultRequestInit(options?.fetch?.bypassingCache),placeholderImage:"data:image/png;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",bypassingCache:!1,...options?.fetch},fetchFn:null,font:{},drawImageInterval:100,workerUrl:null,workerNumber,onCloneEachNode:null,onCloneNode:null,onEmbedNode:null,onCreateForeignObjectSvg:null,includeStyleProperties:null,autoDestruct:!1,...options,__CONTEXT__:!0,log:createLogger(debug),node,ownerDocument,ownerWindow,dpi:scale===1?null:96*scale,svgStyleElement:createStyleElement(ownerDocument),svgDefsElement:ownerDocument?.createElementNS(XMLNS,"defs"),svgStyles:new Map,defaultComputedStyles:new Map,workers:[...Array.from({length:SUPPORT_WEB_WORKER&&workerUrl&&workerNumber?workerNumber:0})].map(()=>{try{let worker=new Worker(workerUrl);return worker.onmessage=async(event)=>{let{url,result}=event.data;if(result)requests.get(url)?.resolve?.(result);else requests.get(url)?.reject?.(Error(`Error receiving message from worker: ${url}`))},worker.onmessageerror=(event)=>{let{url}=event.data;requests.get(url)?.reject?.(Error(`Error receiving message from worker: ${url}`))},worker}catch(error){return context.log.warn("Failed to new Worker",error),null}}).filter(Boolean),fontFamilies:new Map,fontCssTexts:new Map,acceptOfImage:`${[supportWebp(ownerDocument)&&"image/webp","image/svg+xml","image/*","*/*"].filter(Boolean).join(",")};q=0.8`,requests,drawImageCount:0,tasks:[],features,isEnable:(key)=>{if(key==="restoreScrollPosition")return typeof features==="boolean"?!1:features[key]??!1;if(typeof features==="boolean")return features;return features[key]??!0},shadowRoots:[]};context.log.time("wait until load"),await waitUntilLoad(node,{timeout:context.timeout,onWarn:context.log.warn}),context.log.timeEnd("wait until load");let{width,height}=resolveBoundingBox(node,context);return context.width=width,context.height=height,context}function createStyleElement(ownerDocument){if(!ownerDocument)return;let style=ownerDocument.createElement("style"),cssText=style.ownerDocument.createTextNode(`
356
365
  .______background-clip--text {
357
366
  background-clip: text;
358
367
  -webkit-background-clip: text;
@@ -366,7 +375,7 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
366
375
  ${cssText}
367
376
  }
368
377
  `}),svgStyleElement.appendChild(ownerDocument.createTextNode(allCssText))}if(log.timeEnd("clone node"),await onCloneNode?.(clone),font!==!1&&isElementNode(clone))log.time("embed web font"),await embedWebFont(clone,context),log.timeEnd("embed web font");log.time("embed node"),embedNode(clone,context);let count=tasks.length,current2=0,runTask=async()=>{while(!0){let task=tasks.pop();if(!task)break;try{await task}catch(error){context.log.warn("Failed to run task",error)}progress?.(++current2,count)}};progress?.(current2,count),await Promise.all([...Array.from({length:4})].map(runTask)),log.timeEnd("embed node"),await onEmbedNode?.(clone);let svg=createForeignObjectSvg(clone,context);return svgDefsElement&&svg.insertBefore(svgDefsElement,svg.children[0]),svgStyleElement&&svg.insertBefore(svgStyleElement,svg.children[0]),autoDestruct&&destroyContext(context),await onCreateForeignObjectSvg?.(svg),svg}function createForeignObjectSvg(clone,context){let{width,height}=context,svg=createSvg(width,height,clone.ownerDocument),foreignObject=svg.ownerDocument.createElementNS(svg.namespaceURI,"foreignObject");return foreignObject.setAttributeNS(null,"x","0%"),foreignObject.setAttributeNS(null,"y","0%"),foreignObject.setAttributeNS(null,"width","100%"),foreignObject.setAttributeNS(null,"height","100%"),foreignObject.append(clone),svg.appendChild(foreignObject),svg}async function domToCanvas(node,options){let context=await orCreateContext(node,options),svg=await domToForeignObjectSvg(context),dataUrl=svgToDataUrl(svg,context.isEnable("removeControlCharacter"));if(!context.autoDestruct)context.svgStyleElement=createStyleElement(context.ownerDocument),context.svgDefsElement=context.ownerDocument?.createElementNS(XMLNS,"defs"),context.svgStyles.clear();let image=createImage(dataUrl,svg.ownerDocument);return await imageToCanvas(image,context)}var MARGIN=40,MAX_SIDE=16000,MAX_AREA=40000000,MAX_OUTPUT=1600,isOverlay=(node)=>node instanceof Element&&node.hasAttribute("data-tensaku-ui"),MAX_NODES=2000;function containerOf(rect){let x=Math.min(Math.max(rect.left+rect.width/2,0),innerWidth-1),y=Math.min(Math.max(rect.top+rect.height/2,0),innerHeight-1),contains=(box2,margin)=>box2.left<=rect.left-margin&&box2.top<=rect.top-margin&&box2.right>=rect.right+margin&&box2.bottom>=rect.bottom+margin,node=document.elementsFromPoint(x,y).find((el)=>!el.closest("[data-tensaku-ui]"))??document.body,tight=null;while(node&&node!==document.documentElement){let box2=node.getBoundingClientRect();if(tight??=contains(box2,-0.5)?node:null,tight&&node.getElementsByTagName("*").length>MAX_NODES)return tight;if(contains(box2,MARGIN))return node;node=node.parentElement}return tight??document.body}async function capture(area){try{let rect=new DOMRect(area.x-scrollX,area.y-scrollY,area.width,area.height),node=containerOf(rect),box2=node.getBoundingClientRect(),scale=Math.min(devicePixelRatio||1,2,MAX_SIDE/Math.max(box2.width,box2.height,1),Math.sqrt(MAX_AREA/Math.max(box2.width*box2.height,1))),canvas=await domToCanvas(node,{scale,filter:(n)=>!isOverlay(n),timeout:3000,backgroundColor:getComputedStyle(document.body).backgroundColor||"#fff"}),left=Math.max(rect.left-MARGIN,box2.left),top=Math.max(rect.top-MARGIN,box2.top),width=Math.min(rect.right+MARGIN,box2.right)-left,height=Math.min(rect.bottom+MARGIN,box2.bottom)-top;if(width<1||height<1)return null;let shrink=Math.min(1,MAX_OUTPUT/(Math.max(width,height)*scale)),out=document.createElement("canvas");return out.width=Math.round(width*scale*shrink),out.height=Math.round(height*scale*shrink),out.getContext("2d").drawImage(canvas,(left-box2.left)*scale,(top-box2.top)*scale,width*scale,height*scale,0,0,out.width,out.height),out.toDataURL("image/png")}catch{return null}}var showAgents=()=>{},setAgentsHandler=(handler)=>{showAgents=handler},openAgents=()=>showAgents();function noteForm(anchor,targets,extra={},onDone,heading,at=anchor){let shot=capture(anchor);if(at!==anchor&&!extra.rect&&targets.length===1&&anchor.width&&anchor.height){let fraction=(value)=>Math.round(Math.min(Math.max(value,0),1)*1000)/1000;targets=[{...targets[0],point:[fraction((at.x-anchor.x)/anchor.width),fraction((at.y-anchor.y)/anchor.height)]}]}let textarea=h("textarea",{rows:3,placeholder:"What should change?","aria-label":"Note"}),where=targets.filter((t)=>t.kind!=="translation"&&t.kind!=="markdown").map((t)=>t.stamp??t.tag).filter(Boolean),close=()=>{element.remove(),onDone?.()},picker=agentPicker(storage("assign-to","")),withShot=h("input",{type:"checkbox",checked:storage("screenshots",!0),"aria-label":"Attach a screenshot",onchange:()=>store("screenshots",withShot.checked)}),button=h("button",{type:"button",className:"primary",onclick:()=>save()},"Save note");picker?.addEventListener("change",()=>store("assign-to",picker.value));let save=async()=>{let comment=textarea.value.trim();if(!comment)return textarea.focus();try{let to=picker?.value||void 0,note=await api("POST","/notes",{url:location.pathname,comment,targets,viewport:`${innerWidth}x${innerHeight}`,to,...extra});close();let chosen=currentAgents().find((agent)=>agent.handle===to);toast(chosen?`Note saved and assigned to ${agentLabel(chosen)}`:"Note saved");let png=withShot.checked?await shot:null;if(png)await api("PUT",`/notes/${note.id}/screenshot`,{png}).catch((error)=>toast(`The screenshot wasn't saved: ${error.message}`,{error:!0}));await load()}catch(error){toast(error.message,{error:!0})}};textarea.addEventListener("keydown",(event)=>{if(event.key==="Enter"&&(event.metaKey||event.ctrlKey))event.preventDefault(),save();if(event.key==="Escape")event.preventDefault(),event.stopPropagation(),close()});let title=heading?heading:extra.rect?`Area, ${targets.length} ${targets.length===1?"element":"elements"}`:targets[0]?.tag??"Note",quoted=!heading&&!extra.rect&&targets[0]?.text?`${title} · "${targets[0].text.slice(0,48)}${targets[0].text.length>48?"…":""}"`:title,element=panel(at,"postit note-form",div("head",div("what",div("title",quoted),div("where",where.slice(0,3).join(", ")+(where.length>3?` and ${where.length-3} more`:""))),h("button",{type:"button",className:"icon-button",onclick:close,"aria-label":"Cancel"},icon("close"))),textarea,div("options",h("label",{className:"shot"},withShot,"Screenshot"),picker?h("label",{className:"to"},"Assign to",picker):noAgent()),div("foot",h("span",{className:"hint"},`${isApple?"⌘↵":"Ctrl+Enter"} saves`),h("button",{type:"button",className:"quiet",onclick:close},"Cancel"),button));return textarea.focus(),element}function noAgent(){return h("span",{className:"to"},"Assign to",h("button",{type:"button",className:"link",onclick:openAgents},"no agent connected, connect one"))}function agentPicker(selected){let named=currentAgents().filter((agent)=>agent.handle);if(!named.length)return null;let ordered=[...named.filter((agent)=>agent.listening),...named.filter((agent)=>!agent.listening)],select=h("select",{"aria-label":"Assign to"},h("option",{value:""},"Anyone"),...ordered.map((agent)=>h("option",{value:agent.handle},`${agentLabel(agent)}${agent.listening?"":" (not listening)"}`)));return select.value=ordered.some((agent)=>agent.handle===selected)?selected:"",select}function sourceLines(note){let lines=new Map;for(let target of note.targets){if(!target.file)continue;if(!lines.has(target.file))lines.set(target.file,new Set);if(target.range)lines.get(target.file).add(target.range.split(/[:-]/)[0])}let files=Array.from(lines.keys());if(!files.length)return null;let shortened=files.slice(0,3).map((file)=>{let numbers=Array.from(lines.get(file)).join(", ");return file.split("/").pop()+(numbers?`:${numbers}`:"")});if(files.length>3)shortened.push(`${files.length-3} more`);return h("div",{className:"source",title:files.join(`
369
- `)},shortened.join(" · "))}var STATUS_LABELS={open:"Open",question:"Question",resolved:"Resolved",declined:"Declined"};function noteCard(note,onChange=()=>{}){let update=(change)=>updateNote(note,change,onChange),remove=()=>{deleteLater(note),onChange()},setStatus=async(status2,said)=>{let before=note.status;if(await update({status:status2}))toast(said,{actions:{Undo:()=>update({status:before})}})},tool=(name,label,onclick,className="")=>h("button",{type:"button",className:`icon-button ${className}`,title:label,"aria-label":label,onclick},icon(name)),comment=h("div",{className:"comment"},note.comment),startEditing=()=>{let field=h("textarea",{rows:3,"aria-label":"Edit note"},note.comment),saveEdit=async()=>{let value=field.value.trim();if(!value)return field.focus();if(value===note.comment)return stopEditing();if(await update({comment:value,status:"open"}))toast("Note updated")},stopEditing=()=>{editing.replaceWith(comment),actions.hidden=!1};field.addEventListener("keydown",(event)=>{if(event.stopPropagation(),event.key==="Enter"&&(event.metaKey||event.ctrlKey))event.preventDefault(),saveEdit();if(event.key==="Escape")event.preventDefault(),stopEditing()});let editing=div("editing",field,div("row",h("button",{type:"button",className:"quiet",onclick:stopEditing},"Cancel"),h("button",{type:"button",className:"primary",onclick:saveEdit},"Save")));comment.replaceWith(editing),actions.hidden=!0,field.focus(),field.setSelectionRange(field.value.length,field.value.length)},here=note.url===location.pathname,done=closed(note),actions=div("tools",done?h("button",{type:"button",className:"reopen",title:"Reopen: back to open, without sending it to an agent","aria-label":"Reopen",onclick:()=>setStatus("open","Note reopened")},"Reopen"):tool("check","Mark as done",()=>setStatus("resolved","Marked as done"),"resolve"),tool("pen","Edit",startEditing),tool("trash","Delete",remove,"delete")),answer=null;if(note.status==="question"||note.thread?.at(-1)?.from==="agent"){let asked=note.status==="question",label=asked?"Answer":"Ask for changes",field=h("textarea",{rows:2,placeholder:asked?"Answer the question":"What should change?","aria-label":label}),send=()=>field.value.trim()&&update({message:field.value.trim(),status:"open"});field.addEventListener("keydown",(event)=>{if(event.stopPropagation(),event.key==="Enter"&&(event.metaKey||event.ctrlKey))event.preventDefault(),send()}),answer=div("answer",field,div("row end",h("button",{type:"button",className:"primary",onclick:send},label)))}let thread=threadView(note),missing=!done&&here&&!anchorFor(note)?div("missing","Not found on this page any more."):null,delivered=note.status==="open"&&note.delivered_at&&note.sent_at&&note.delivered_at>=note.sent_at,status=note.status==="working"?note.stopped?`${note.agent??"Agent"} stopped. Anyone can take it`:`${note.agent??"Agent"} is working`:delivered?`Picked up by ${note.delivered_to}`:note.status==="open"?note.agent?`Assigned to ${note.agent}`:"Unassigned":STATUS_LABELS[note.status],owner=currentAgents().find((agent)=>agent.handle&&agentLabel(agent)===note.agent),assignable=note.status==="open"||note.status==="working",picker=assignable?agentPicker(note.status==="open"?owner?.handle??"":""):null,current2=note.status==="open"?owner?.handle??"":null,assignButton=h("button",{type:"button",onclick:async()=>{let chosen=currentAgents().find((agent)=>agent.handle===picker.value),undo=current2===null?void 0:{Undo:()=>update({to:current2})};if(await update({to:picker.value}))toast(chosen?`Note assigned to ${agentLabel(chosen)}`:"Note unassigned: the first session that checks takes it",{actions:undo})}}),syncAssign=()=>{let same=picker?.value===current2;assignButton.disabled=same,assignButton.textContent=same?"Assigned":note.status==="working"?"Reassign":"Assign"};picker?.addEventListener("change",syncAssign),syncAssign();let assignRow=!assignable?null:picker?div("assign",h("label",{className:"to"},"Assign to",picker),assignButton):div("assign",noAgent()),statusLabel=h("span",{},status);return div(`postit note-card ${note.status}`,div("head",h("span",{className:`status ${note.status}`},note.status==="resolved"?icon("check"):null,statusLabel),actions),comment,screenshotView(note),thread,missing,assignRow,answer,sourceLines(note))}function screenshotView(note){if(!note.screenshot)return null;let image=h("img",{alt:"Screenshot",width:note.screenshot.width,height:note.screenshot.height}),url="";return fetch(`${meta().root}/notes/${note.id}/screenshot`,{headers:{"X-Tensaku-Token":meta().token},credentials:"same-origin"}).then((response)=>response.ok?response.blob():null).then((blob)=>{if(blob)image.src=url=URL.createObjectURL(blob)}).catch(()=>{}),h("button",{type:"button",className:"screenshot",title:"Open the screenshot","aria-label":"Open the screenshot",onclick:()=>url&&open(url,"_blank")},image)}var openThreads=new Set;function threadView(note){let entries=note.thread??[];if(!entries.length)return null;let lastAgent=entries.map((entry)=>entry.from).lastIndexOf("agent"),start=openThreads.has(note.id)?0:lastAgent>=0?lastAgent:Math.max(0,entries.length-2),message=(entry)=>div(`message ${entry.from}`,h("span",{className:"who"},entry.from==="you"?"You":entry.agent??"Agent"),h("span",{},entry.text)),view=div("thread"),earlier=start>0?h("button",{type:"button",className:"link earlier",onclick:()=>{openThreads.add(note.id),view.replaceWith(threadView(note))}},`Show ${start} earlier ${start===1?"message":"messages"}`):null;if(earlier)view.append(earlier);return view.append(...entries.slice(start).map(message)),view}var shown=null,shownNote=null;function showNote(note,rect){let onChange=(next)=>{if(!next)shown?.remove()};if(!rect){if(!shown?.isConnected)return;shownNote=note,shown.replaceChildren(noteCard(note,onChange));return}shown?.remove(),shownNote=note,shown=panel(rect,"note-pop",noteCard(note,onChange));let close=(event)=>{if(!event.composedPath().includes(shown))shown?.remove(),document.removeEventListener("pointerdown",close,!0)};setTimeout(()=>document.addEventListener("pointerdown",close,!0))}function closeNote(){if(!shown?.isConnected)return!1;return shown.remove(),!0}onRender(({changed})=>{if(changed){if(shownNote?.id===changed.id)showNote(changed);return}if(!shown?.isConnected||!shownNote)return;let latest=currentNotes().find((note)=>note.id===shownNote.id);if(!latest||JSON.stringify(latest)===JSON.stringify(shownNote))return;let typing=activeInShadow();if(typing?.matches("textarea, input")&&shown.contains(typing)&&typing.value)return;showNote(latest)});var sidebar=null,scope2="page";function toggleSidebar(force){if(!(force??!sidebar?.isConnected)){sidebar?.remove(),setScope(null);return}sidebar??=div("sidebar"),sidebar.setAttribute("role","complementary"),sidebar.setAttribute("aria-label","Tensaku notes"),fixed.append(sidebar),setScope(scope2),renderSidebar()}var sidebarOpen=()=>Boolean(sidebar?.isConnected);onRender(({force})=>{if(!sidebar?.isConnected)return;let typing=activeInShadow();if(force||!(typing?.matches("textarea, input")&&sidebar.contains(typing)))renderSidebar()});async function showScope(next){scope2=next,await setScope(next),renderSidebar()}async function clearDone(done){try{await api("POST","/notes/archive",{ids:done.map((note)=>note.id)}),await load({force:!0}),toast(`Archived ${done.length} done ${done.length===1?"note":"notes"}`)}catch(error){toast(error.message,{error:!0})}}function renderSidebar(){if(!sidebar)return;let format=settings().copyFormat==="short"?"short":void 0,copyAll=async(all)=>{let markdown=await api("GET","/notes.md"+query(all?{format}:{url:location.pathname,format}));await copy(markdown),toast(all?"Copied all open notes":"Copied this page's open notes")},tab=(which,text)=>h("button",{type:"button",role:"tab","aria-selected":String(scope2===which),onclick:()=>showScope(which)},text),card=(note)=>noteCard(note),listed=scope2==="page"?currentNotes():scopedNotes(),grouped=(list)=>scope2==="page"?list.map(card):Array.from(new Set(list.map((note)=>note.url))).flatMap((url)=>[h("a",{className:`page${url===location.pathname?" current":""}`,href:url},url,h("span",{},String(list.filter((note)=>note.url===url).length))),...list.filter((note)=>note.url===url).map(card)]),archive=scope2==="archived",done=archive?[]:listed.filter(closed),body=grouped(archive?listed.slice().reverse():listed.filter((note)=>!closed(note)));if(archive){if(!listed.length)body.push(div("empty","Nothing archived. Archive done moves resolved and declined notes here."))}else if(done.length)body.push(div("section",h("span",{},`Done (${done.length})`),h("button",{type:"button",onclick:()=>clearDone(done)},"Archive done")),...grouped(done));else if(!listed.length)body.push(div("empty",scope2==="page"?"No notes on this page. Select an element or drag over an area to add one.":"No notes yet."));sidebar.replaceChildren(h("header",{},h("strong",{},scope2==="page"?`Notes on ${location.pathname}`:archive?"Archived notes":"Notes on every page"),h("button",{type:"button",className:"icon-button",onclick:()=>toggleSidebar(!1),"aria-label":"Close notes"},icon("close"))),div("tabs",tab("page","This page"),tab("all","All pages"),tab("archived","Archive")),...body,...openNotes()?[sendBar(copyAll)]:[])}function sendBar(copyAll){let names=listeners3(),status=names.length?div("listener on",h("span",{className:"dot"}),names.length===1?`${names[0]} is checking for notes`:`${names.length} agents are checking for notes`):div("listener",h("span",{className:"dot"}),"No agent listening",h("button",{type:"button",className:"link",onclick:openAgents},"Connect one"));return div("copy-bar",div("actions",h("button",{type:"button",onclick:()=>copyAll(!1)},"Copy page"),h("button",{type:"button",onclick:()=>copyAll(!0)},`Copy all (${openNotes()})`)),status)}var SHOWN_AT_ONCE=3,PACE=1200,waiting=[],shownToasts=[],paceTimer=0,whoChanged=(note)=>note.agent??note.thread?.filter((entry)=>entry.from==="agent").pop()?.agent??"The agent";function notify(text,tag){if(document.visibilityState!=="visible"&&settings().notify&&"Notification"in window&&Notification.permission==="granted")new Notification("Tensaku",{body:text,tag})}function announceOne(note,what){let who=whoChanged(note),about=`"${note.comment.length>48?note.comment.slice(0,48)+"…":note.comment}"`,text={resolved:`${who} resolved ${about}`,declined:`${who} declined ${about}`,question:`${who} has a question on ${about}`,message:`${who} replied on ${about}`}[what];return notify(text,`tensaku-${note.id}`),toast(text,{actions:{Show:()=>{let rect=anchorFor(note);if(rect)scrollTo({top:Math.max(0,rect.top-120),behavior:"smooth"}),showNote(note,rect)}}})}function announceSummary(changes){let names=new Set(changes.map((change)=>whoChanged(change.note))),who=names.size===1?Array.from(names)[0]:"Agents",count=(what)=>changes.filter((change)=>change.what===what).length,plural=(n,word)=>`${n} ${word}${n===1?"":"s"}`,parts=[count("resolved")&&`resolved ${plural(count("resolved"),"note")}`,count("declined")&&`declined ${plural(count("declined"),"note")}`,count("question")&&`asked ${plural(count("question"),"question")}`,count("message")&&`replied on ${plural(count("message"),"note")}`].filter(Boolean),text=`${who} ${parts.slice(0,-1).join(", ")}${parts.length>1?" and ":""}${parts[parts.length-1]}`;return notify(text,"tensaku-summary"),toast(text,{timeout:8000,actions:{Show:()=>toggleSidebar(!0)}})}function nextAnnouncement(){if(paceTimer=0,!waiting.length)return;if(shownToasts=shownToasts.filter((element)=>element.isConnected),shownToasts.length<SHOWN_AT_ONCE)if(waiting.length>SHOWN_AT_ONCE)shownToasts.push(announceSummary(waiting.splice(0)));else{let change=waiting.shift();shownToasts.push(announceOne(change.note,change.what))}if(waiting.length)paceTimer=window.setTimeout(nextAnnouncement,PACE)}function announce(note,what){let queued=waiting.findIndex((change)=>change.note.id===note.id);if(queued>=0)waiting.splice(queued,1);if(waiting.push({note,what}),!paceTimer)paceTimer=window.setTimeout(nextAnnouncement)}onChanges((before,after)=>{let old=new Map(before.map((note)=>[note.id,note]));for(let note of after){let previous=old.get(note.id);if(!previous)continue;if(changedHere(note.id))continue;let messages=note.thread?.length??0;if(messages>(previous.thread?.length??0)&&note.thread[messages-1].from==="agent"&&note.status===previous.status)announce(note,"message");else if(note.status!==previous.status&&note.status!=="open"&&note.status!=="working")announce(note,note.status)}});var siClaude={title:"Claude",slug:"claude",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Claude</title><path d="'+this.path+'"/></svg>'},path:"m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z",source:"https://claude.ai",hex:"D97757"};var siCline={title:"Cline",slug:"cline",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Cline</title><path d="'+this.path+'"/></svg>'},path:"m23.365 13.556-1.442-2.895V8.994c0-2.764-2.218-5.002-4.954-5.002h-2.464c.178-.367.276-.779.276-1.213A2.77 2.77 0 0 0 12.018 0a2.77 2.77 0 0 0-2.763 2.779c0 .434.098.846.276 1.213H7.067c-2.736 0-4.954 2.238-4.954 5.002v1.667L.64 13.549c-.149.29-.149.636 0 .927l1.472 2.855v1.667C2.113 21.762 4.33 24 7.067 24h9.902c2.736 0 4.954-2.238 4.954-5.002V17.33l1.44-2.865c.143-.286.143-.622.002-.91m-12.854 2.36a2.27 2.27 0 0 1-2.261 2.273 2.27 2.27 0 0 1-2.261-2.273v-4.042A2.27 2.27 0 0 1 8.249 9.6a2.267 2.267 0 0 1 2.262 2.274zm7.285 0a2.27 2.27 0 0 1-2.26 2.273 2.27 2.27 0 0 1-2.262-2.273v-4.042A2.267 2.267 0 0 1 15.535 9.6a2.267 2.267 0 0 1 2.261 2.274z",source:"https://cline.bot/assets/branding/logos/cline-wordmark-black.svg",hex:"18181B"};var siCursor={title:"Cursor",slug:"cursor",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Cursor</title><path d="'+this.path+'"/></svg>'},path:"M11.503.131 1.891 5.678a.84.84 0 0 0-.42.726v11.188c0 .3.162.575.42.724l9.609 5.55a1 1 0 0 0 .998 0l9.61-5.55a.84.84 0 0 0 .42-.724V6.404a.84.84 0 0 0-.42-.726L12.497.131a1.01 1.01 0 0 0-.996 0M2.657 6.338h18.55c.263 0 .43.287.297.515L12.23 22.918c-.062.107-.229.064-.229-.06V12.335a.59.59 0 0 0-.295-.51l-9.11-5.257c-.109-.063-.064-.23.061-.23",source:"https://cursor.com/brand",hex:"000000"};var siGithubcopilot={title:"GitHub Copilot",slug:"githubcopilot",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>GitHub Copilot</title><path d="'+this.path+'"/></svg>'},path:"M23.922 16.997C23.061 18.492 18.063 22.02 12 22.02 5.937 22.02.939 18.492.078 16.997A.641.641 0 0 1 0 16.741v-2.869a.883.883 0 0 1 .053-.22c.372-.935 1.347-2.292 2.605-2.656.167-.429.414-1.055.644-1.517a10.098 10.098 0 0 1-.052-1.086c0-1.331.282-2.499 1.132-3.368.397-.406.89-.717 1.474-.952C7.255 2.937 9.248 1.98 11.978 1.98c2.731 0 4.767.957 6.166 2.093.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086.23.462.477 1.088.644 1.517 1.258.364 2.233 1.721 2.605 2.656a.841.841 0 0 1 .053.22v2.869a.641.641 0 0 1-.078.256Zm-11.75-5.992h-.344a4.359 4.359 0 0 1-.355.508c-.77.947-1.918 1.492-3.508 1.492-1.725 0-2.989-.359-3.782-1.259a2.137 2.137 0 0 1-.085-.104L4 11.746v6.585c1.435.779 4.514 2.179 8 2.179 3.486 0 6.565-1.4 8-2.179v-6.585l-.098-.104s-.033.045-.085.104c-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.545-3.508-1.492a4.359 4.359 0 0 1-.355-.508Zm2.328 3.25c.549 0 1 .451 1 1v2c0 .549-.451 1-1 1-.549 0-1-.451-1-1v-2c0-.549.451-1 1-1Zm-5 0c.549 0 1 .451 1 1v2c0 .549-.451 1-1 1-.549 0-1-.451-1-1v-2c0-.549.451-1 1-1Zm3.313-6.185c.136 1.057.403 1.913.878 2.497.442.544 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.15.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.319-.862-2.824-1.025-1.487-.161-2.192.138-2.533.529-.269.307-.437.808-.438 1.578v.021c0 .265.021.562.063.893Zm-1.626 0c.042-.331.063-.628.063-.894v-.02c-.001-.77-.169-1.271-.438-1.578-.341-.391-1.046-.69-2.533-.529-1.505.163-2.347.537-2.824 1.025-.462.472-.705 1.179-.705 2.319 0 1.211.175 1.926.558 2.361.365.414 1.084.751 2.657.751 1.21 0 1.902-.394 2.344-.938.475-.584.742-1.44.878-2.497Z",source:"https://primer.style/foundations/icons/copilot-24",hex:"000000",license:{type:"MIT",url:"https://spdx.org/licenses/MIT"}};var siGooglegemini={title:"Google Gemini",slug:"googlegemini",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Google Gemini</title><path d="'+this.path+'"/></svg>'},path:"M11.04 19.32Q12 21.51 12 24q0-2.49.93-4.68.96-2.19 2.58-3.81t3.81-2.55Q21.51 12 24 12q-2.49 0-4.68-.93a12.3 12.3 0 0 1-3.81-2.58 12.3 12.3 0 0 1-2.58-3.81Q12 2.49 12 0q0 2.49-.96 4.68-.93 2.19-2.55 3.81a12.3 12.3 0 0 1-3.81 2.58Q2.49 12 0 12q2.49 0 4.68.96 2.19.93 3.81 2.55t2.55 3.81",source:"https://gemini.google.com",hex:"8E75B2"};var siOpencode={title:"OpenCode",slug:"opencode",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>OpenCode</title><path d="'+this.path+'"/></svg>'},path:"M22 24H2V0h20zM17 4.8H7v14.4h10z",source:"https://github.com/anomalyco/opencode/blob/1251a870cb384543c150c4a72fb101b55eec971b/packages/identity/mark.svg",hex:"000000"};var siWindsurf={title:"Windsurf",slug:"windsurf",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Windsurf</title><path d="'+this.path+'"/></svg>'},path:"M23.55 5.067c-1.2038-.002-2.1806.973-2.1806 2.1765v4.8676c0 .972-.8035 1.7594-1.7597 1.7594-.568 0-1.1352-.286-1.4718-.7659l-4.9713-7.1003c-.4125-.5896-1.0837-.941-1.8103-.941-1.1334 0-2.1533.9635-2.1533 2.153v4.8957c0 .972-.7969 1.7594-1.7596 1.7594-.57 0-1.1363-.286-1.4728-.7658L.4076 5.1598C.2822 4.9798 0 5.0688 0 5.2882v4.2452c0 .2147.0656.4228.1884.599l5.4748 7.8183c.3234.462.8006.8052 1.3509.9298 1.3771.313 2.6446-.747 2.6446-2.0977v-4.893c0-.972.7875-1.7593 1.7596-1.7593h.003a1.798 1.798 0 0 1 1.4718.7658l4.9723 7.0994c.4135.5905 1.05.941 1.8093.941 1.1587 0 2.1515-.9645 2.1515-2.153v-4.8948c0-.972.7875-1.7594 1.7596-1.7594h.194a.22.22 0 0 0 .2204-.2202v-4.622a.22.22 0 0 0-.2203-.2203Z",source:"https://windsurf.com/brand",hex:"0B100F",guidelines:"https://windsurf.com/brand"};var siZedindustries={title:"Zed Industries",slug:"zedindustries",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Zed Industries</title><path d="'+this.path+'"/></svg>'},path:"M2.25 1.5a.75.75 0 0 0-.75.75v16.5H0V2.25A2.25 2.25 0 0 1 2.25 0h20.095c1.002 0 1.504 1.212.795 1.92L10.764 14.298h3.486V12.75h1.5v1.922a1.125 1.125 0 0 1-1.125 1.125H9.264l-2.578 2.578h11.689V9h1.5v9.375a1.5 1.5 0 0 1-1.5 1.5H5.185L2.562 22.5H21.75a.75.75 0 0 0 .75-.75V5.25H24v16.5A2.25 2.25 0 0 1 21.75 24H1.655C.653 24 .151 22.788.86 22.08L13.19 9.75H9.75v1.5h-1.5V9.375A1.125 1.125 0 0 1 9.375 8.25h5.314l2.625-2.625H5.625V15h-1.5V5.625a1.5 1.5 0 0 1 1.5-1.5h13.19L21.438 1.5z",source:"https://github.com/zed-industries/zed/blob/ccc939124fa2f366b3029926447fd0a0c46a85c7/assets/icons/logo_96.svg",hex:"084CCF"};var CLIENTS=[[/claude/i,siClaude],[/cursor/i,siCursor],[/gemini/i,siGooglegemini],[/opencode/i,siOpencode],[/copilot/i,siGithubcopilot],[/windsurf/i,siWindsurf],[/\bzed\b/i,siZedindustries],[/cline/i,siCline]];function readable(hex){let[r,g,b]=[0,2,4].map((i)=>parseInt(hex.slice(i,i+2),16));return 0.2126*r+0.7152*g+0.0722*b>90}function clientIcon(name){let brand=CLIENTS.find(([pattern])=>pattern.test(name))?.[1];if(!brand)return icon("plane");let svg=document.createElementNS("http://www.w3.org/2000/svg","svg");svg.setAttribute("class","client"),svg.setAttribute("viewBox","0 0 24 24"),svg.setAttribute("aria-hidden","true"),svg.setAttribute("focusable","false");let path=document.createElementNS("http://www.w3.org/2000/svg","path");if(path.setAttribute("d",brand.path),svg.append(path),readable(brand.hex))svg.style.color=`#${brand.hex}`;return svg}var popover=null,popoverTool=null,rendered=()=>[],popoverOpen=(tool)=>tool?popoverTool===tool:Boolean(popover);function closePopover(){popover?.remove(),popover=null,popoverTool?.setAttribute("aria-pressed","false"),popoverTool=null}function togglePopover(tool,dock,render2){let same=popoverTool===tool;if(closePopover(),same)return;rendered=render2,popover=div("popover",...render2()),popover.addEventListener("keydown",(event)=>event.stopPropagation());let rect=dock.getBoundingClientRect();popover.style.right=`${Math.max(12,innerWidth-rect.right)}px`,popover.style.bottom=`${innerHeight-rect.top+12}px`,fixed.append(popover),popoverTool=tool,tool.setAttribute("aria-pressed","true")}function redrawPopover(tool){if(popover&&(!tool||popoverTool===tool))popover.replaceChildren(...rendered())}function closeOutside(event){if(popover&&!event.composedPath().some((node)=>node===popover||node===popoverTool))closePopover()}var ago=(date)=>{let seconds=Math.round((Date.now()-date.getTime())/1000);return seconds<60?"just now":seconds<3600?`${Math.round(seconds/60)} min ago`:`${Math.round(seconds/3600)} h ago`};var PROMPTS={watch:"Watch my Tensaku notes",once:"Do my Tensaku notes",install:"bin/rails generate tensaku:install",channel:"claude --dangerously-load-development-channels server:tensaku"};function copyRow(text,done){return div("command",h("code",{},text),h("button",{type:"button",className:"icon-button",title:"Copy","aria-label":`Copy ${text}`,onclick:async()=>{await copy(text),toast(done)}},icon("copy")))}var DID={start_note:"started",resolve_note:"resolved",decline_note:"declined",ask_question:"asked on",reply_to_note:"replied on",get_note:"read",list_notes:"listed the notes",watch_notes:"checked for notes",current_selection:"read the selection"};function lastAction(agent){if(agent.working.length)return agent.working.map((note)=>h("a",{className:"doing",href:note.url,title:`“${note.comment}”`},`Working on ${note.id}: “${note.comment}”`));let last=agent.last,did=last?`${DID[last.tool]??last.tool}${last.note?` ${last.note}`:""} ${ago(new Date(last.at))}`:null,waiting2=agent.channel?"Live: notes reach its chat as you save them":"Waiting for your notes",text=agent.listening?`${waiting2}${did?` · ${did}`:""}`:did?`Last ${did}`:"No calls yet";return[h("span",{className:"doing"},text)]}function agentRow(agent){return div(`agent${agent.listening?" listening":""}${agent.channel?" live":""}${agent.working.length?" working":""}`,div("who",h("strong",{},clientIcon(agent.name),agentLabel(agent)),h("span",{className:"where"},agent.folder??"")),agent.outdated?div("outdated","Runs older Tensaku code. Reconnect it (/mcp in Claude Code) or restart it."):null,...lastAction(agent))}var idleOpen=!1;function renderAgents(){let agents2=currentAgents(),listening=agents2.filter((agent)=>agent.listening),idle=agents2.filter((agent)=>!agent.listening),ask=(lead)=>[h("p",{},lead),copyRow(PROMPTS.watch,"Copied. Paste it into your agent's chat."),h("p",{className:"where"},"It waits for notes and takes each one as you save it."),copyRow(PROMPTS.once,"Copied. Paste it into your agent's chat."),h("p",{className:"where"},"It works through the open notes, then stops."),h("p",{},h("strong",{},"Claude Code, without asking: "),"start it with Tensaku as a channel, and each note you save starts it working. Experimental, and it asks you to confirm at start:"),copyRow(PROMPTS.channel,"Copied. Run it in the app's folder.")],rest=listening.length&&idle.length?[h("button",{type:"button",className:"idle-toggle","aria-expanded":String(idleOpen),onclick:()=>{idleOpen=!idleOpen,redrawPopover()}},`${idle.length} more connected, not listening`),...idleOpen?idle.map(agentRow):[]]:idle.map(agentRow);return[h("h3",{},"Agents"),...agents2.length?[...listening.map(agentRow),...rest,...listening.length?[]:[div("connect",...ask("None is listening. Agents read notes when you ask them to, so say this in your agent's chat:"))]]:[div("empty","No agent connected."),div("connect",h("p",{},h("strong",{},"Set up once per project. "),"Run this in the app, then restart your agent. It adds Tensaku to Claude Code, Codex, Cursor, Gemini CLI and OpenCode:"),copyRow(PROMPTS.install,"Copied. Run it in the app, then restart your agent."),h("p",{className:"where"},"Already set up? Start your agent in this project and it shows here. In Claude Code, /mcp reconnects it."),...ask("Then say this in your agent's chat:"))]]}var CONTEXT=26,MAX_LINES=3;function sharedEnds(before,after){let prefix=0;while(prefix<before.length&&before[prefix]===after[prefix])prefix++;let suffix=0;while(suffix<before.length-prefix&&suffix<after.length-prefix&&before[before.length-1-suffix]===after[after.length-1-suffix])suffix++;while(prefix>0&&/\w/.test(before[prefix-1]))prefix--;while(suffix>0&&/\w/.test(before[before.length-suffix]))suffix--;return{prefix,suffix}}function row(sign,line,{prefix,suffix}){let end=line.length-suffix,head=prefix>CONTEXT?`…${line.slice(prefix-CONTEXT,prefix).replace(/^\S*\s/,"")}`:line.slice(0,prefix).trimStart(),tail=suffix>CONTEXT?`${line.slice(end,end+CONTEXT).replace(/\s\S*$/,"")}…`:line.slice(end);return div(`diff-row ${sign==="-"?"removed":"added"}`,h("span",{className:"diff-sign"},sign),head,h("mark",{},line.slice(prefix,end)),tail)}function diffRows({removed,added}){let count=Math.max(removed.length,added.length),rows=[];for(let index=0;index<Math.min(count,MAX_LINES);index++){let ends=sharedEnds(removed[index]??"",added[index]??"");if(removed[index]!==void 0)rows.push(row("-",removed[index],ends));if(added[index]!==void 0)rows.push(row("+",added[index],ends))}if(count>MAX_LINES)rows.push(div("diff-more",`${count-MAX_LINES} more ${count-MAX_LINES===1?"line":"lines"} changed`));return div("diff",...rows)}var INTERPOLATION=/(%\{[^}]+\})/;function finish(result,kind,verb,actions){if(!result.changed)return;let where=result.diff?`${result.file}:${result.diff.line}`:result.file??"";if(toast(`${verb} ${where}`.trim(),{timeout:result.diff?8000:void 0,detail:result.diff?diffRows(result.diff):void 0,actions}),result.warning)toast(result.warning,{timeout:8000});refresh(kind)}function report(error){let message=error instanceof Error?error.message:String(error);toast(message,{error:!0,actions:error instanceof ApiError&&error.stale?{Reload:()=>location.reload()}:void 0})}function rangeAfter(range,text){let[,path,startLine,startColumn]=range.match(/^(.+):(\d+):(\d+)-/),lines=text.split(`
370
- `),endLine=Number(startLine)+lines.length-1,endColumn=(lines.length===1?Number(startColumn)-1:0)+utf8Length(lines[lines.length-1]);return`${path}:${startLine}:${startColumn}-${endLine}:${endColumn}`}var textNodesOf2=(stamp)=>Array.from(document.querySelectorAll(`[${STAMP}="${CSS.escape(stamp)}"]`)).flatMap((el)=>Array.from(el.childNodes).filter((node)=>node.nodeType===Node.TEXT_NODE));function showTranslation(key,from,to){if(INTERPOLATION.test(from))return;replaceText(nodesForKey(key),from,to),elementsWithAttributeKey(key).forEach(({element:el,name})=>{if(el.getAttribute(name)===from)el.setAttribute(name,to)})}var HISTORY_LIMIT=50,HISTORY_KEY="tensaku:history",done=[],undone=[];try{let saved=JSON.parse(sessionStorage.getItem(HISTORY_KEY)??"null");if(saved&&Array.isArray(saved.done)&&Array.isArray(saved.undone))({done,undone}=saved)}catch{}function persist(){try{sessionStorage.setItem(HISTORY_KEY,JSON.stringify({done,undone}))}catch{}}var nextId=()=>Math.max(0,...done.map((entry)=>entry.id),...undone.map((entry)=>entry.id))+1;function record(element,label,op,file){let entry={id:nextId(),label,key:element?undoKey(element):null,file,at:new Date().toISOString(),op};if(done.push(entry),done.length>HISTORY_LIMIT)done.shift();return undone=[],persist(),entry}function editHistory(){return{done:done.slice().reverse(),undone:undone.slice().reverse()}}var canUndo=()=>done.length>0,canRedo=()=>undone.length>0;async function undo(entry=done[done.length-1]){if(!entry||!done.includes(entry))return toast("That edit was undone already.");try{let result=await apply(entry.op,!0);done=done.filter((item)=>item!==entry),undone.push(entry),persist(),finish(result,sourceKind(entry.op),`Undid ${entry.label}`,{Redo:()=>redo(entry)})}catch(error){report(error)}}async function redo(entry=undone[undone.length-1]){if(!entry||undone[undone.length-1]!==entry)return toast("Only the latest undone edit can be redone.");try{let result=await apply(entry.op,!1);undone.pop(),done.push(entry),persist(),finish(result,sourceKind(entry.op),`Redid ${entry.label}`,{Undo:()=>undo(entry)})}catch(error){report(error)}}var sourceKind=(op)=>op.kind==="attribute"?"template":op.kind;function undoFor(element){let key=undoKey(element);return key?done.slice().reverse().find((entry)=>entry.key===key):void 0}async function apply(op,reverse){let verb=reverse?"undone":"redone",stale=(what)=>new ApiError(`The ${what} changed since the edit, so it can't be ${verb} here.`,409,!0);if(op.kind==="template"){let texts=(await api("GET","/source"+query({stamp:op.stamp}))).pieces.filter((p)=>p.kind==="text"),edits=op.changes.map(({index,from,to})=>{let[current3,target2]=reverse?[to,from]:[from,to],now=texts[index];if(!now||now.text!==current3)throw stale("text");return{piece:now,current:current3,target:target2}}),result2=await api("POST","/text",{stamp:op.stamp,edits:edits.map(({piece,target:target2})=>({start:piece.start,end:piece.end,original:piece.raw,text:target2}))}),nodes=textNodesOf2(op.stamp);return edits.forEach(({current:current3,target:target2})=>replaceText(nodes,current3,target2)),result2}if(op.kind==="attribute"){let result2={};for(let{name,index,from,to}of op.changes){let[current3,target2]=reverse?[to,from]:[from,to],now=(await api("GET","/source"+query({stamp:op.stamp}))).attributes.find((a)=>a.name===name)?.pieces.filter((p)=>p.kind==="text")[index];if(!now||now.text!==current3)throw stale("attribute");result2=await api("POST","/attribute",{stamp:op.stamp,name,start:now.start,end:now.end,original:now.raw,text:target2}),document.querySelectorAll(`[${STAMP}="${CSS.escape(op.stamp)}"]`).forEach((el)=>{let value=el.getAttribute(name);if(value!==null)el.setAttribute(name,value.replace(current3,target2))})}return{...result2,changed:!0}}if(op.kind==="translation"){let result2={};for(let{locale,from,to}of op.changes){let[current3,target2]=reverse?[to,from]:[from,to],saved=await api("POST","/translation",{locale,key:op.key,original:current3,text:target2});result2={...saved,file:result2.file??saved.file,changed:!0},showTranslation({locale,key:op.key},current3,target2)}return result2}let[current2,target]=reverse?[op.to,op.from]:[op.from,op.to],result=await api("POST","/markdown",{range:op.range,original:op.prefix+current2,text:target,tag:op.tag});return op.range=rangeAfter(op.range,op.prefix+target),result}function undoKey(element){let translation=translationOf(element);return element.getAttribute(STAMP)??element.getAttribute(MARKDOWN)??(translation?`${translation.locale}.${translation.key}`:null)}var UNDO_KEYS=isApple?"⌘Z and ⇧⌘Z":"Ctrl+Z and Ctrl+Y";function renderHistory(){let{done:done2,undone:undone2}=editHistory(),row2=(entry,action)=>div(`entry${undone2.includes(entry)?" undone":""}`,div("what",h("span",{},entry.label),h("span",{className:"where"},`${entry.file??""} · ${ago(new Date(entry.at))}`)),action),button=(text,run)=>h("button",{type:"button",onclick:async()=>{await run(),closePopover()}},text);return[h("h3",{},"Edit history",h("span",{className:"where"},`Saves in this tab. ${UNDO_KEYS} undo and redo.`)),...done2.length||undone2.length?[...done2.map((entry)=>row2(entry,button("Undo",()=>undo(entry)))),...undone2.map((entry,i)=>row2(entry,i===0?button("Redo",()=>redo(entry)):h("span",{className:"where"},"undone")))]:[div("empty","No edits yet.")]]}var current2="off",listeners4=[],mode=()=>current2,onMode=(listener)=>listeners4.push(listener);function setMode(next){current2=next,listeners4.forEach((listener)=>listener(next))}var paused=null;function togglePause(){if(paused)return paused.style.remove(),paused.animations.forEach((animation)=>{try{animation.play()}catch{}}),paused.media.forEach((media2)=>media2.play().catch(()=>{})),paused=null,!1;let animations=document.getAnimations().filter((animation)=>{let target=animation.effect?.target;return animation.playState==="running"&&!(target&&isUi(target))});animations.forEach((animation)=>animation.pause());let media=Array.from(document.querySelectorAll("video, audio")).filter((element)=>!element.paused);media.forEach((element)=>element.pause());let style=document.createElement("style");return style.setAttribute("data-tensaku-pause",""),style.textContent="*, *::before, *::after { animation-play-state: paused !important; transition: none !important; }",document.head.append(style),paused={animations,media,style},!0}var pinLayer=div("pins");layer.append(pinLayer);function setPinsHidden(hidden){pinLayer.hidden=hidden}var drawn=new Map;onRender(({first})=>{if(first)currentNotes().forEach((note)=>drawn.set(note.id,note.status));drawPins()});function drawPins(){pinLayer.replaceChildren(),currentNotes().forEach((note,index)=>{let phrase=phraseRects(note);for(let r of phrase){let mark=div(`phrase ${note.status}`);Object.assign(mark.style,{left:`${r.left}px`,top:`${r.top}px`,width:`${r.width}px`,height:`${r.height}px`}),pinLayer.append(mark)}let point=phrase.length?null:pointFor(note),rect=phrase.length?phrase[phrase.length-1]:point??anchorFor(note);if(!rect)return;let fresh=drawn.get(note.id)!==note.status;drawn.set(note.id,note.status);let pin=h("button",{className:`pin ${note.status}${fresh?" fresh":""}`,title:note.comment,"aria-label":`Note ${index+1}: ${note.comment}`,"data-note":note.id},note.status==="resolved"?icon("check"):note.status==="declined"?icon("close"):String(index+1));Object.assign(pin.style,{left:`${point?point.x:rect.right}px`,top:`${rect.top}px`}),pin.addEventListener("click",(event)=>{event.stopPropagation(),showNote(note,rect)}),pinLayer.append(pin)})}var SHORTCUT_TOOLS={select:"Select",edit:"Edit",notes:"Notes",agents:"Agents",pins:"Hide or show pins",clear:"Delete this page's notes",pause:"Pause animations",history:"Edit history",settings:"Settings"},DEFAULTS2={select:"alt+shift+KeyT",edit:"alt+shift+KeyE",notes:"alt+shift+KeyN"};function shortcutFor(tool){let own=settings().shortcuts;return tool in own?own[tool]:DEFAULTS2[tool]??null}var isDefault=(tool)=>!(tool in settings().shortcuts);function setShortcut(tool,keys){let shortcuts={...settings().shortcuts},taken=keys?toolFor(keys):null;if(taken&&taken!==tool)shortcuts[taken]=null;if(keys===(DEFAULTS2[tool]??null))delete shortcuts[tool];else shortcuts[tool]=keys;return changeSettings({shortcuts}),taken&&taken!==tool?taken:null}var resetShortcuts=()=>changeSettings({shortcuts:{}});function toolFor(keys){return Object.keys(SHORTCUT_TOOLS).find((tool)=>shortcutFor(tool)===keys)??null}function toolForEvent(event){return event.code?toolFor(keysOf(event)):null}function keysOf(event){return[...[event.ctrlKey&&"ctrl",event.altKey&&"alt",event.shiftKey&&"shift",event.metaKey&&"meta"].filter(Boolean),event.code].join("+")}var isModifierKey=(event)=>["Alt","Shift","Control","Meta"].includes(event.key),hasCommandModifier=(event)=>event.altKey||event.ctrlKey||event.metaKey,APPLE_KEYS={alt:"⌥",shift:"⇧",ctrl:"⌃",meta:"⌘"},OTHER_KEYS={alt:"Alt",shift:"Shift",ctrl:"Ctrl",meta:"Meta"};function keysLabel(keys){let parts=keys.split("+"),key=parts.pop().replace(/^(Key|Digit)/,""),names=isApple?APPLE_KEYS:OTHER_KEYS;return[...parts.map((part)=>names[part]??part),key].join(isApple?"":"+")}var panel2=null,recording=null,hooks={toggled:()=>{},moveDockHome:()=>{}},setSettingsHooks=(given)=>{hooks=given},settingsOpen=()=>Boolean(panel2?.isConnected);function toggleSettings(force){let show=force??!settingsOpen();if(stopRecording(),!show){panel2?.remove(),hooks.toggled();return}panel2??=div("sidebar settings"),panel2.setAttribute("role","complementary"),panel2.setAttribute("aria-label","Tensaku settings"),fixed.append(panel2),render2(),hooks.toggled()}function render2(){if(!panel2)return;let prefs=settings(),choice=(value,text)=>h("button",{type:"button","aria-pressed":String(prefs.copyFormat===value),onclick:()=>{changeSettings({copyFormat:value}),render2()}},text),notify2=h("input",{type:"checkbox",checked:prefs.notify});notify2.addEventListener("change",async()=>{let on=notify2.checked;if(on&&"Notification"in window&&Notification.permission==="default")await Notification.requestPermission();let allowed="Notification"in window&&Notification.permission==="granted";if(on&&!allowed)toast("The browser blocked notifications for this site.",{error:!0});changeSettings({notify:on&&allowed}),render2()});let customized=Object.keys(SHORTCUT_TOOLS).some((tool)=>!isDefault(tool));panel2.replaceChildren(h("header",{},h("strong",{},"Settings"),h("button",{type:"button",className:"icon-button",onclick:()=>toggleSettings(!1),"aria-label":"Close settings"},icon("close"))),h("section",{},h("h4",{},"Notes"),div("setting",h("span",{},"Copy notes as"),div("segmented",choice("detailed","Detailed"),choice("short","One line each"))),h("label",{className:"check"},notify2,h("span",{},"Notify me",h("span",{className:"where"},"When an agent answers while this tab is in the background.")))),h("section",{},h("h4",{},"Keyboard shortcuts",customized?h("button",{type:"button",className:"link",onclick:()=>{resetShortcuts(),render2()}},"Reset all"):null),h("p",{className:"where"},"Click a shortcut and press the new keys, with Alt, Ctrl or Cmd. Escape cancels."),...Object.entries(SHORTCUT_TOOLS).map(([tool,name])=>shortcutRow(tool,name)),h("h5",{},"Always on"),...fixedShortcuts().map(([keys,what])=>div("shortcut always",h("span",{},what),h("kbd",{},keys)))),h("section",{},h("h4",{},"Toolbar"),div("setting",h("button",{type:"button",onclick:()=>hooks.moveDockHome()},"Move the toolbar back to the corner"))))}function shortcutRow(tool,name){let keys=shortcutFor(tool),waiting2=recording===tool,record2=h("button",{type:"button",className:`keys${waiting2?" recording":""}`,"aria-label":`Change the shortcut for ${name}`,onclick:()=>startRecording(tool)},waiting2?"Press keys…":keys?h("kbd",{},keysLabel(keys)):h("span",{className:"none"},"None")),clear=keys&&!waiting2?h("button",{type:"button",className:"icon-button","aria-label":`Remove the shortcut for ${name}`,onclick:()=>{setShortcut(tool,null),render2()}},icon("close")):null;return div(`shortcut${isDefault(tool)?"":" changed"}`,h("span",{},name),record2,clear)}function startRecording(tool){stopRecording(),recording=tool,addEventListener("keydown",onRecordKey,!0),render2()}function stopRecording(){recording=null,removeEventListener("keydown",onRecordKey,!0)}function onRecordKey(event){if(!recording||!settingsOpen()){stopRecording();return}if(isModifierKey(event))return;event.preventDefault(),event.stopImmediatePropagation();let tool=recording;if(stopRecording(),event.key==="Escape"){render2();return}if(!hasCommandModifier(event)){toast("Use Alt, Ctrl or Cmd with the key, so typing never triggers it.",{error:!0}),render2();return}let keys=keysOf(event),moved=setShortcut(tool,keys);if(moved)toast(`${keysLabel(keys)} no longer does ${SHORTCUT_TOOLS[moved]}.`);render2()}function fixedShortcuts(){let click=(keys)=>isApple?`${keys} click`:`${keys}+click`,alt=isApple?"⌥":"Alt",shift=isApple?"⇧":"Shift";return[[click(alt),"Menu for an element"],[click(isApple?alt+shift:`${alt}+${shift}`),"Note on an element"],[click(shift),"Pick several elements, in select mode"],["N","Note the picked elements"],["Esc","Close a menu or panel, or leave the mode"]]}var INK={highlighter:"#ffe14d",pen:"#e0344f",pad:"#fff1a1"},count=h("span",{className:"count",hidden:!0}),corner=h("button",{className:"corner",type:"button",title:"Tensaku","aria-label":"Tensaku","aria-expanded":"false"},logo(),count);function tool(name,ink,text){let tip=h("span",{className:"tip","aria-hidden":"true"},text),button=h("button",{type:"button",className:"tool","aria-pressed":"false","aria-label":text},icon(name,ink),tip);return button.style.setProperty("--ink-color",ink),button}function action(name,text){return h("button",{type:"button",className:"tool","aria-label":text},icon(name),h("span",{className:"tip","aria-hidden":"true"},text))}function setTip(button,text){button.setAttribute("aria-label",text),button.querySelector(".tip").firstChild.textContent=text}var setIcon=(button,name,ink)=>button.replaceChild(icon(name,ink),button.querySelector("svg")),selectTool=tool("highlighter",INK.highlighter,"Select"),editTool=tool("pen",INK.pen,"Edit"),notesTool=tool("pad",INK.pad,"Notes"),notesBadge=h("span",{className:"badge",hidden:!0});notesTool.append(notesBadge);var pinsTool=action("eye","Hide pins"),pauseTool=action("pause","Pause animations"),clearTool=action("trash","Delete this page's notes"),historyTool=action("history","Edit history"),settingsTool=action("sliders","Settings"),agentsTool=action("plane","No agent connected");agentsTool.classList.add("agents");var agentsBadge=h("span",{className:"badge",hidden:!0});agentsTool.append(agentsBadge);var tools=div("tools",selectTool,editTool,div("sep"),notesTool,agentsTool,pinsTool,clearTool,div("sep"),pauseTool,historyTool,settingsTool),toolbar=div("toolbar",tools);new ResizeObserver(()=>toolbar.style.setProperty("--tools-width",`${tools.offsetWidth}px`)).observe(tools);var dock=div("dock",toolbar,corner);fixed.append(dock);var shortcutButtons={select:selectTool,edit:editTool,notes:notesTool,agents:agentsTool,pins:pinsTool,clear:clearTool,pause:pauseTool,history:historyTool,settings:settingsTool};onSettings(()=>{for(let[name,button]of Object.entries(shortcutButtons)){let keys=shortcutFor(name),tip=button.querySelector(".tip");if(tip.querySelector("kbd")?.remove(),keys)tip.append(h("kbd",{},keysLabel(keys)))}});function pressShortcut(name){setToolbar(!0),shortcutButtons[name].click()}var toolbarOpen=()=>dock.classList.contains("open"),settling=0;function setToolbar(open2){if(open2===toolbarOpen())return;if(dock.classList.toggle("open",open2),corner.setAttribute("aria-expanded",String(open2)),clearTimeout(settling),dock.classList.remove("settled"),open2)settling=window.setTimeout(()=>dock.classList.add("settled"),280)}function placeDock(){let position=storage("dock",{right:16,bottom:16});dock.style.right=`${Math.min(Math.max(position.right,4),innerWidth-52)}px`,dock.style.bottom=`${Math.min(Math.max(position.bottom,4),innerHeight-52)}px`}var dragged=!1;corner.addEventListener("pointerdown",(event)=>{let start={x:event.clientX,y:event.clientY,right:parseFloat(dock.style.right),bottom:parseFloat(dock.style.bottom)};dragged=!1,corner.setPointerCapture(event.pointerId);let move=(e)=>{let dx=e.clientX-start.x,dy=e.clientY-start.y;if(!dragged&&Math.hypot(dx,dy)<4)return;dragged=!0,corner.style.cursor="grabbing",dock.style.right=`${start.right-dx}px`,dock.style.bottom=`${start.bottom-dy}px`},up=()=>{if(corner.removeEventListener("pointermove",move),corner.removeEventListener("pointerup",up),corner.style.cursor="",dragged)store("dock",{right:parseFloat(dock.style.right),bottom:parseFloat(dock.style.bottom)})};corner.addEventListener("pointermove",move),corner.addEventListener("pointerup",up)});corner.addEventListener("click",()=>{if(dragged)return;if(setToolbar(!toolbarOpen()),toolbarOpen())return;toggleSidebar(!1),toggleSettings(!1),setMode("off")});function closeToolbar(){if(!toolbarOpen())return!1;return setToolbar(!1),!0}function syncButtons(){selectTool.setAttribute("aria-pressed",String(mode()==="inspect")),editTool.setAttribute("aria-pressed",String(mode()==="edit")),notesTool.setAttribute("aria-pressed",String(sidebarOpen())),settingsTool.setAttribute("aria-pressed",String(settingsOpen())),corner.classList.toggle("active",mode()!=="off")}onMode((next)=>{if(next!=="off")setToolbar(!0);syncButtons()});function closeSidePanel(){if(settingsOpen())return toggleSettings(!1),!0;if(!sidebarOpen())return!1;return toggleSidebar(!1),syncButtons(),!0}selectTool.addEventListener("click",()=>setMode(mode()==="inspect"?"off":"inspect"));editTool.addEventListener("click",()=>setMode(mode()==="edit"?"off":"edit"));notesTool.addEventListener("click",()=>{toggleSettings(!1),toggleSidebar(),syncButtons()});onCount((n)=>{count.hidden=n===0,count.textContent=String(n),notesBadge.hidden=n===0,notesBadge.textContent=String(n),setTip(notesTool,n?`Notes (${n})`:"Notes")});setSettingsHooks({toggled:syncButtons,moveDockHome:()=>{store("dock",{right:16,bottom:16}),placeDock()}});settingsTool.addEventListener("click",()=>{if(closePopover(),!settingsOpen())toggleSidebar(!1);toggleSettings()});historyTool.addEventListener("click",()=>togglePopover(historyTool,dock,renderHistory));var pinsHidden=storage("pinsHidden",!1);function syncPins(){setPinsHidden(pinsHidden),pinsTool.setAttribute("aria-pressed",String(pinsHidden)),setIcon(pinsTool,pinsHidden?"eye-off":"eye"),setTip(pinsTool,pinsHidden?"Show pins":"Hide pins")}pinsTool.addEventListener("click",()=>{pinsHidden=!pinsHidden,store("pinsHidden",pinsHidden),syncPins()});pauseTool.addEventListener("click",()=>{let paused2=togglePause();pauseTool.setAttribute("aria-pressed",String(paused2)),setIcon(pauseTool,paused2?"play":"pause"),setTip(pauseTool,paused2?"Resume animations":"Pause animations")});var confirmClear=0;clearTool.addEventListener("click",async()=>{let total=currentNotes().length;if(!total){toast("No notes on this page");return}if(!confirmClear){clearTool.classList.add("confirm"),setTip(clearTool,`Delete ${total} ${total===1?"note":"notes"}? Click again`),confirmClear=window.setTimeout(resetClear,3000);return}resetClear();try{await deleteNotes(currentNotes()),toast(`Deleted ${total} ${total===1?"note":"notes"}`)}catch(error){toast(error.message,{error:!0})}});function resetClear(){clearTimeout(confirmClear),confirmClear=0,clearTool.classList.remove("confirm"),setTip(clearTool,"Delete this page's notes")}var names=(list)=>list.map(agentLabel).join(", "),agentsSignature="[]";onAgents((agents2)=>{let signature=JSON.stringify(agents2);if(signature===agentsSignature)return;agentsSignature=signature;let listening=agents2.filter((agent)=>agent.listening);agentsTool.classList.toggle("connected",agents2.length>0),agentsTool.classList.toggle("listening",listening.length>0),setIcon(agentsTool,listening.length?"plane-flying":"plane",listening.length?"#2fa872":void 0),agentsBadge.hidden=agents2.length<2,agentsBadge.textContent=String(agents2.length),setTip(agentsTool,listening.length?`${names(listening)} listening`:agents2.length?`${names(agents2)} connected`:"No agent connected"),redrawPopover(agentsTool)});agentsTool.addEventListener("click",()=>togglePopover(agentsTool,dock,renderAgents));setAgentsHandler(()=>{if(setToolbar(!0),!popoverOpen(agentsTool))togglePopover(agentsTool,dock,renderAgents)});var open2=null,composing=(event)=>event.isComposing||event.keyCode===229;function isEditing(){return open2!==null}function closeEditor(){open2?.close()}async function edit(element,kind=editKind(element)){closeEditor();try{if(kind==="translation")await editTranslation(element,translationOf(element));else if(kind==="markdown")await editMarkdown(element);else if(kind==="template")await editTemplate(element);else if(kind==="attributes")await editAttributes(element);else toast("This text comes from Ruby, so it can't be edited here. Leave a note instead.")}catch(error){report(error)}}var normal=(text)=>text.replace(/\s+/g," ").trim();function assertRendered(element,texts){let rendered2=normal(element.textContent??""),from=0;for(let text of texts.map(normal).filter(Boolean)){let at=rendered2.indexOf(text,from);if(at<0)throw new ApiError("The file changed since the page was rendered. Reload the page and try again.",409,!0);from=at+text.length}}function field(text,multiline=!1){let span=h("span",{className:"editable",spellcheck:"true"},text);if(span.contentEditable="plaintext-only",span.contentEditable!=="plaintext-only")span.contentEditable="true";if(span.dataset.original=text,span.addEventListener("paste",(event)=>{event.preventDefault(),document.execCommand("insertText",!1,event.clipboardData?.getData("text/plain")??"")}),!multiline)span.addEventListener("keydown",(event)=>{if(event.key==="Enter"&&event.shiftKey&&!composing(event))event.preventDefault()});return span}var valueOf=(span)=>(span.innerText??span.textContent??"").replace(/ /g," ").replace(/\n$/,"");function chip(label,title){return h("span",{className:"chip",title,contenteditable:"false"},label)}function backgroundOf(element){for(let node=element;node;node=node.parentElement){let color=getComputedStyle(node).backgroundColor,alpha=color.match(/rgba?\([^)]*,\s*([\d.]+)\)/)?.[1];if(color!=="transparent"&&(alpha===void 0||Number(alpha)>0.6))return color}return"#fff"}var INSET={x:11.5,y:9.5};function frame(element,surface,info,save,extra=[],warning){let rect=contentRect(element),computed=getComputedStyle(element);Object.assign(surface.style,{fontFamily:computed.fontFamily,fontSize:computed.fontSize,fontWeight:computed.fontWeight,lineHeight:computed.lineHeight,letterSpacing:computed.letterSpacing,textAlign:computed.textAlign,color:computed.color}),surface.classList.add("surface");let status=h("span",{},info),close=()=>{container.remove(),open2=null,document.removeEventListener("keydown",keys,!0)},saveAndClose=async()=>{if(container.dataset.saving)return;container.dataset.saving="1",status.textContent="Saving…";try{await save(),close()}catch(error){delete container.dataset.saving,status.textContent=info,report(error)}},container=div("panel editor",surface,...extra,div("bar",h("span",{},status,warning?h("strong",{className:"ink-warning"},` · ${warning}`):null),div("actions",h("button",{onclick:close,type:"button"},"Cancel"),h("button",{className:"primary",onclick:saveAndClose,type:"button"},"Save"))));container.setAttribute("role","dialog"),container.setAttribute("aria-label","Tensaku editor"),container.style.background=backgroundOf(element),container.style.color=computed.color,container.style.minWidth=`${Math.max(rect.width+INSET.x*2,240)}px`,container.style.maxWidth=`${Math.max(rect.width+INSET.x*2,480)}px`,layer.append(container),place(container,new DOMRect(rect.left-INSET.x,rect.top-INSET.y,rect.width+INSET.x*2,rect.height),!0);let keys=(event)=>{if(!container.isConnected)return;if(event.key==="Escape")event.preventDefault(),event.stopPropagation(),close();if(event.key!=="Enter"||composing(event)||!activeInShadow()?.classList.contains("editable"))return;if(surface.dataset.newlines!==void 0?event.metaKey||event.ctrlKey:!event.shiftKey)event.preventDefault(),saveAndClose()};return document.addEventListener("keydown",keys,!0),container.addEventListener("focusout",()=>{setTimeout(()=>{let active=activeInShadow();if(container.isConnected&&!container.dataset.saving&&!(active&&container.contains(active)))saveAndClose()},150)}),open2={element:container,save:saveAndClose,close},container.querySelector(".editable")?.focus(),container}var NESTED_STYLES=["fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","textTransform","color"];function nestedElement(piece,host2,unchanged){if(piece.tag==="br"||piece.tag.startsWith("br.")||piece.tag.startsWith("br#"))return document.createElement("br");let child=piece.stamp?host2?.querySelector(`[${STAMP}="${CSS.escape(piece.stamp)}"]`):null,computed=child?getComputedStyle(child):null;if(computed&&(computed.display==="none"||computed.position==="absolute"||computed.position==="fixed"))return null;let text=child?visibleText(child,80):piece.label;if(!text)return h("span",{className:"chip mark",title:`<${piece.tag}>`,contenteditable:"false"});let span=h("span",{className:"nested",contenteditable:"false"},text);if(computed){if(NESTED_STYLES.forEach((name)=>{span.style[name]=computed[name]}),!computed.display.startsWith("inline"))span.style.display="block"}if(child&&editKind(child))span.classList.add("link"),span.title="Edit this element on its own",span.addEventListener("click",()=>{if(unchanged())edit(child)});return span}function pieceSurface(pieces,host2){let surface=div(""),fields=[],unchanged=()=>fields.every(({span,piece})=>valueOf(span)===piece.text);for(let piece of pieces)if(piece.kind==="text"){if(!piece.text.trim()){if(surface.lastChild&&surface.lastChild.nodeName!=="BR")surface.append(" ");continue}let span=field(piece.text);fields.push({span,piece}),surface.append(span)}else if(piece.kind==="ruby")surface.append(chip(piece.code.length>30?piece.code.slice(0,29)+"…":piece.code,piece.code));else if(piece.kind==="element"){let node=nestedElement(piece,host2,unchanged);if(node)surface.append(node)}return{surface,fields}}async function editTemplate(element){let stamp=stampOf(element),info=await api("GET","/source"+query({stamp:stamp.value}));if(indexPieces(info.pieces),!info.editable){if(editableAttributes(element).length)return editAttributes(element);throw Error(info.helper?"This element comes from a helper, so its text can't be edited here.":"This element has no static text to edit.")}assertRendered(element,info.pieces.filter((p)=>p.kind==="text").map((p)=>p.text));let{surface,fields}=pieceSurface(info.pieces,element),copies=copiesOf(element);frame(element,surface,`${info.file}:${stamp.line}`,async()=>{let changed=fields.filter(({span,piece})=>valueOf(span)!==piece.text);if(!changed.length)return;await saveTemplate(element,stamp.value,changed.map(({span,piece})=>({piece,text:valueOf(span)})))},[],copies>1?`this edits all ${copies} copies`:void 0)}async function saveTemplate(element,stamp,changes){let result=await api("POST","/text",{stamp,edits:changes.map(({piece,text})=>({start:piece.start,end:piece.end,original:piece.raw,text}))}),nodes=textNodesOf2(stamp);changes.forEach(({piece,text})=>replaceText(nodes,piece.text,text));let entry=result.changed?record(element,`edit in ${stamp}`,{kind:"template",stamp,changes:changes.map(({piece,text})=>({index:piece.index??-1,from:piece.text,to:text}))},result.file):void 0;afterSave(result,"template",entry)}async function editAttributes(element){let stamp=stampOf(element),description=stamp?await api("GET","/source"+query({stamp:stamp.value})):null,names2=editableAttributes(element),rows=[],savers=[],templateFields=[];for(let name of names2){let key=attributeKey(element,name);if(key){let entry=(await api("GET","/translation"+query({key:key.key}))).locales[key.locale];if(!entry?.editable||entry.value===null)continue;assertRendered(attributeNode(element,name),staticParts(entry.value));let{surface:surface3,read}=interpolationSurface(entry.value);rows.push(div("attr",h("span",{className:"name",title:`${key.locale}.${key.key}`},`${name} (t)`),div("value",surface3))),savers.push(async()=>{let text=read();if(text===entry.value)return;await saveTranslations(element,key,[{locale:key.locale,from:entry.value,to:text}]),entry.value=text});continue}let attribute=description?.attributes.find((a)=>a.name===name);if(!attribute||!attribute.pieces.some((p)=>p.kind==="text"))continue;assertRendered(attributeNode(element,name),attribute.pieces.filter((p)=>p.kind==="text").map((p)=>p.text));let{surface:surface2,fields}=pieceSurface(attribute.pieces);rows.push(div("attr",h("span",{className:"name"},name),div("value",surface2))),fields.forEach(({span,piece})=>templateFields.push({name,span,piece}))}if(templateFields.length)savers.push(()=>saveAttributePieces(element,stamp.value,templateFields));if(!rows.length)throw Error("Nothing here can be edited. Leave a note instead.");let surface=div("");surface.append(...rows),frame(element,surface,description?`${description.file}:${stamp.line} attributes`:"attributes",async()=>{for(let save of savers)await save()})}async function saveAttributePieces(element,stamp,fields){let changed=fields.map(({name,span,piece})=>({name,piece,text:valueOf(span)})).filter(({piece,text})=>text!==piece.text).sort((a,b)=>b.piece.start-a.piece.start);if(!changed.length)return;let saved=[],last={};try{for(let{name,piece,text}of changed){last=await api("POST","/attribute",{stamp,name,start:piece.start,end:piece.end,original:piece.raw,text}),document.querySelectorAll(`[${STAMP}="${CSS.escape(stamp)}"]`).forEach((el)=>{let current3=el.getAttribute(name);if(current3!==null)el.setAttribute(name,current3.replace(piece.text,text))});let index=fields.filter((field2)=>field2.name===name).findIndex((field2)=>field2.piece===piece);saved.push({name,index,from:piece.text,to:text}),piece.text=text}}finally{if(saved.length){let names2=Array.from(new Set(saved.map((change)=>change.name))).join(", "),entry=record(element,names2,{kind:"attribute",stamp,changes:saved},last.file);afterSave({...last,changed:!0},"template",entry)}}}function interpolationSurface(value){let surface=div("");for(let part of value.split(INTERPOLATION)){if(!part)continue;surface.append(INTERPOLATION.test(part)?chip(part):field(part,!0))}if(!surface.querySelector(".editable"))surface.prepend(field("",!0));return{surface,read:()=>Array.from(surface.childNodes).map((node)=>node.classList?.contains("chip")?node.textContent:valueOf(node)).join("")}}async function editTranslation(element,key){let{locales}=await api("GET","/translation"+query({key:key.key})),entry=locales[key.locale];if(!entry?.editable||entry.value===null)throw Error(`${key.locale}.${key.key} isn't in a writable locale file (it may come from a gem).`);assertRendered(element,staticParts(entry.value));let main=interpolationSurface(entry.value),others=Object.entries(locales).filter(([locale])=>locale!==key.locale),otherRows=div("");otherRows.hidden=!0;let otherReaders=[];for(let[locale,other]of others)if(other.editable&&other.value!==null){let surface=interpolationSurface(other.value);otherReaders.push({locale,entry:other,read:surface.read}),otherRows.append(div("locale",h("span",{className:"code"},locale),surface.surface))}else otherRows.append(div("locale",h("span",{className:"code"},locale),h("em",{className:"ink-muted"},other.value===null?"missing":`${other.value} (not writable)`)));let toggle=others.length?h("button",{className:"link",type:"button",onclick:()=>{otherRows.hidden=!otherRows.hidden,toggle.textContent=otherRows.hidden?`Other locales (${others.length})`:"Hide other locales"}},`Other locales (${others.length})`):null,extra=toggle?[div("locale",h("span",{className:"code"},""),toggle),otherRows]:[];frame(element,main.surface,`${key.locale}.${key.key} · ${entry.file}:${entry.line}`,async()=>{let changes=[{locale:key.locale,entry,read:main.read},...otherReaders].flatMap(({locale,entry:entry2,read})=>{let to=read();return to===entry2.value?[]:[{locale,from:entry2.value,to,entry:entry2}]});await saveTranslations(element,key,changes,(change)=>{change.entry.value=change.to})},extra)}async function saveTranslations(element,key,changes,onSaved=()=>{}){let saved=[],result={};try{for(let change of changes){let reply=await api("POST","/translation",{locale:change.locale,key:key.key,original:change.from,text:change.to});if(showTranslation({locale:change.locale,key:key.key},change.from,change.to),onSaved(change),reply.changed)saved.push({locale:change.locale,from:change.from,to:change.to});result={...reply,file:result.file??reply.file,changed:result.changed||reply.changed}}}finally{let label=saved.length>1?`${key.key} in ${saved.length} locales`:key.key,entry=saved.length?record(element,label,{kind:"translation",key:key.key,changes:saved},result.file):void 0;if(saved.length)afterSave(result,"translation",entry)}}async function editMarkdown(element){let range=element.getAttribute(MARKDOWN),tag=element.tagName.toLowerCase(),info=await api("GET","/markdown"+query({range,tag}));if(!info.editable)throw Error("This Markdown block can only get notes.");let words=info.text.replace(/^\s*(?:[-*+]|\d{1,9}[.)])\s+(?:\[[ xX]\]\s+)?/gm,"").replace(/\]\([^)]*\)/g,"").replace(/[*_`#>\[\]]/g,"");assertRendered(element,words.split(`
378
+ `)},shortened.join(" · "))}var STATUS_LABELS={open:"Open",question:"Question",resolved:"Resolved",declined:"Declined"};function noteCard(note,onChange=()=>{}){let update=(change)=>updateNote(note,change,onChange),remove=()=>{deleteLater(note),onChange()},setStatus=async(status2,said)=>{let before=note.status;if(await update({status:status2}))toast(said,{actions:{Undo:()=>update({status:before})}})},tool=(name,label,onclick,className="")=>h("button",{type:"button",className:`icon-button ${className}`,title:label,"aria-label":label,onclick},icon(name)),comment=h("div",{className:"comment"},note.comment),startEditing=()=>{let field=h("textarea",{rows:3,"aria-label":"Edit note"},note.comment),saveEdit=async()=>{let value=field.value.trim();if(!value)return field.focus();if(value===note.comment)return stopEditing();if(await update({comment:value,status:"open"}))toast("Note updated")},stopEditing=()=>{editing.replaceWith(comment),actions.hidden=!1};field.addEventListener("keydown",(event)=>{if(event.stopPropagation(),event.key==="Enter"&&(event.metaKey||event.ctrlKey))event.preventDefault(),saveEdit();if(event.key==="Escape")event.preventDefault(),stopEditing()});let editing=div("editing",field,div("row",h("button",{type:"button",className:"quiet",onclick:stopEditing},"Cancel"),h("button",{type:"button",className:"primary",onclick:saveEdit},"Save")));comment.replaceWith(editing),actions.hidden=!0,field.focus(),field.setSelectionRange(field.value.length,field.value.length)},here=note.url===location.pathname,done=closed(note),actions=div("tools",done?h("button",{type:"button",className:"reopen",title:"Reopen: back to open, without sending it to an agent","aria-label":"Reopen",onclick:()=>setStatus("open","Note reopened")},"Reopen"):tool("check","Mark as done",()=>setStatus("resolved","Marked as done"),"resolve"),tool("pen","Edit",startEditing),tool("trash","Delete",remove,"delete")),answer=null;if(note.status==="question"||note.thread?.at(-1)?.from==="agent"){let asked=note.status==="question",label=asked?"Answer":"Ask for changes",field=h("textarea",{rows:2,placeholder:asked?"Answer the question":"What should change?","aria-label":label}),send=()=>field.value.trim()&&update({message:field.value.trim(),status:"open"});field.addEventListener("keydown",(event)=>{if(event.stopPropagation(),event.key==="Enter"&&(event.metaKey||event.ctrlKey))event.preventDefault(),send()}),answer=div("answer",field,div("row end",h("button",{type:"button",className:"primary",onclick:send},label)))}let thread=threadView(note),missing=!done&&here&&!anchorFor(note)?div("missing","Not found on this page any more."):null,status=note.status==="working"?note.stopped?`${note.agent??"Agent"} stopped. Anyone can take it`:`${note.agent??"Agent"} is working`:note.status==="open"?note.agent?`Assigned to ${note.agent}`:"Unassigned":STATUS_LABELS[note.status],owner=currentAgents().find((agent)=>agent.handle&&agentLabel(agent)===note.agent),assignable=note.status==="open"||note.status==="working",picker=assignable?agentPicker(note.status==="open"?owner?.handle??"":""):null,current2=note.status==="open"?owner?.handle??"":null,assignButton=h("button",{type:"button",onclick:async()=>{let chosen=currentAgents().find((agent)=>agent.handle===picker.value),undo=current2===null?void 0:{Undo:()=>update({to:current2})};if(await update({to:picker.value}))toast(chosen?`Note assigned to ${agentLabel(chosen)}`:"Note unassigned: the first session that checks takes it",{actions:undo})}}),syncAssign=()=>{let same=picker?.value===current2;assignButton.disabled=same,assignButton.textContent=same?"Assigned":note.status==="working"?"Reassign":"Assign"};picker?.addEventListener("change",syncAssign),syncAssign();let assignRow=!assignable?null:picker?div("assign",h("label",{className:"to"},"Assign to",picker),assignButton):div("assign",noAgent()),statusLabel=h("span",{},status);return div(`postit note-card ${note.status}`,div("head",h("span",{className:`status ${note.status}`},note.status==="resolved"?icon("check"):null,statusLabel),actions),comment,screenshotView(note),thread,missing,assignRow,answer,sourceLines(note))}function screenshotView(note){if(!note.screenshot)return null;let image=h("img",{alt:"Screenshot",width:note.screenshot.width,height:note.screenshot.height}),url="";return fetch(`${meta().root}/notes/${note.id}/screenshot`,{headers:{"X-Tensaku-Token":meta().token},credentials:"same-origin"}).then((response)=>response.ok?response.blob():null).then((blob)=>{if(blob)image.src=url=URL.createObjectURL(blob)}).catch(()=>{}),h("button",{type:"button",className:"screenshot",title:"Open the screenshot","aria-label":"Open the screenshot",onclick:()=>url&&open(url,"_blank")},image)}var openThreads=new Set;function threadView(note){let entries=note.thread??[];if(!entries.length)return null;let lastAgent=entries.map((entry)=>entry.from).lastIndexOf("agent"),start=openThreads.has(note.id)?0:lastAgent>=0?lastAgent:Math.max(0,entries.length-2),message=(entry)=>div(`message ${entry.from}`,h("span",{className:"who"},entry.from==="you"?"You":entry.agent??"Agent"),h("span",{},entry.text)),view=div("thread"),earlier=start>0?h("button",{type:"button",className:"link earlier",onclick:()=>{openThreads.add(note.id),view.replaceWith(threadView(note))}},`Show ${start} earlier ${start===1?"message":"messages"}`):null;if(earlier)view.append(earlier);return view.append(...entries.slice(start).map(message)),view}var shown=null,shownNote=null;function showNote(note,rect){let onChange=(next)=>{if(!next)shown?.remove()};if(!rect){if(!shown?.isConnected)return;shownNote=note,shown.replaceChildren(noteCard(note,onChange));return}shown?.remove(),shownNote=note,shown=panel(rect,"note-pop",noteCard(note,onChange));let close=(event)=>{if(!event.composedPath().includes(shown))shown?.remove(),document.removeEventListener("pointerdown",close,!0)};setTimeout(()=>document.addEventListener("pointerdown",close,!0))}function closeNote(){if(!shown?.isConnected)return!1;return shown.remove(),!0}onRender(({changed})=>{if(changed){if(shownNote?.id===changed.id)showNote(changed);return}if(!shown?.isConnected||!shownNote)return;let latest=currentNotes().find((note)=>note.id===shownNote.id);if(!latest||JSON.stringify(latest)===JSON.stringify(shownNote))return;let typing=activeInShadow();if(typing?.matches("textarea, input")&&shown.contains(typing)&&typing.value)return;showNote(latest)});var sidebar=null,scope2="page";function toggleSidebar(force){if(!(force??!sidebar?.isConnected)){sidebar?.remove(),setScope(null);return}sidebar??=div("sidebar"),sidebar.setAttribute("role","complementary"),sidebar.setAttribute("aria-label","Tensaku notes"),fixed.append(sidebar),setScope(scope2),renderSidebar()}var sidebarOpen=()=>Boolean(sidebar?.isConnected);onRender(({force})=>{if(!sidebar?.isConnected)return;let typing=activeInShadow();if(force||!(typing?.matches("textarea, input")&&sidebar.contains(typing)))renderSidebar()});async function showScope(next){scope2=next,await setScope(next),renderSidebar()}async function clearDone(done){try{await api("POST","/notes/archive",{ids:done.map((note)=>note.id)}),await load({force:!0}),toast(`Archived ${done.length} done ${done.length===1?"note":"notes"}`)}catch(error){toast(error.message,{error:!0})}}function renderSidebar(){if(!sidebar)return;let format=settings().copyFormat==="short"?"short":void 0,copyAll=async(all)=>{let markdown=await api("GET","/notes.md"+query(all?{format}:{url:location.pathname,format}));await copy(markdown),toast(all?"Copied all open notes":"Copied this page's open notes")},tab=(which,text)=>h("button",{type:"button",role:"tab","aria-selected":String(scope2===which),onclick:()=>showScope(which)},text),card=(note)=>noteCard(note),listed=scope2==="page"?currentNotes():scopedNotes(),grouped=(list)=>scope2==="page"?list.map(card):Array.from(new Set(list.map((note)=>note.url))).flatMap((url)=>[h("a",{className:`page${url===location.pathname?" current":""}`,href:url},url,h("span",{},String(list.filter((note)=>note.url===url).length))),...list.filter((note)=>note.url===url).map(card)]),archive=scope2==="archived",done=archive?[]:listed.filter(closed),body=grouped(archive?listed.slice().reverse():listed.filter((note)=>!closed(note)));if(archive){if(!listed.length)body.push(div("empty","Nothing archived. Archive done moves resolved and declined notes here."))}else if(done.length)body.push(div("section",h("span",{},`Done (${done.length})`),h("button",{type:"button",onclick:()=>clearDone(done)},"Archive done")),...grouped(done));else if(!listed.length)body.push(div("empty",scope2==="page"?"No notes on this page. Select an element or drag over an area to add one.":"No notes yet."));sidebar.replaceChildren(h("header",{},h("strong",{},scope2==="page"?`Notes on ${location.pathname}`:archive?"Archived notes":"Notes on every page"),h("button",{type:"button",className:"icon-button",onclick:()=>toggleSidebar(!1),"aria-label":"Close notes"},icon("close"))),div("tabs",tab("page","This page"),tab("all","All pages"),tab("archived","Archive")),...body,...openNotes()?[sendBar(copyAll)]:[])}function sendBar(copyAll){let names=listeners3(),status=names.length?div("listener on",h("span",{className:"dot"}),names.length===1?`${names[0]} is checking for notes`:`${names.length} agents are checking for notes`):div("listener",h("span",{className:"dot"}),"No agent listening",h("button",{type:"button",className:"link",onclick:openAgents},"Connect one"));return div("copy-bar",div("actions",h("button",{type:"button",onclick:()=>copyAll(!1)},"Copy page"),h("button",{type:"button",onclick:()=>copyAll(!0)},`Copy all (${openNotes()})`)),status)}var SHOWN_AT_ONCE=3,PACE=1200,waiting=[],shownToasts=[],paceTimer=0,whoChanged=(note)=>note.agent??note.thread?.filter((entry)=>entry.from==="agent").pop()?.agent??"The agent";function notify(text,tag){if(document.visibilityState!=="visible"&&settings().notify&&"Notification"in window&&Notification.permission==="granted")new Notification("Tensaku",{body:text,tag})}function announceOne(note,what){let who=whoChanged(note),about=`"${note.comment.length>48?note.comment.slice(0,48)+"…":note.comment}"`,text={resolved:`${who} resolved ${about}`,declined:`${who} declined ${about}`,question:`${who} has a question on ${about}`,message:`${who} replied on ${about}`}[what];return notify(text,`tensaku-${note.id}`),toast(text,{actions:{Show:()=>{let rect=anchorFor(note);if(rect)scrollTo({top:Math.max(0,rect.top-120),behavior:"smooth"}),showNote(note,rect)}}})}function announceSummary(changes){let names=new Set(changes.map((change)=>whoChanged(change.note))),who=names.size===1?Array.from(names)[0]:"Agents",count=(what)=>changes.filter((change)=>change.what===what).length,plural=(n,word)=>`${n} ${word}${n===1?"":"s"}`,parts=[count("resolved")&&`resolved ${plural(count("resolved"),"note")}`,count("declined")&&`declined ${plural(count("declined"),"note")}`,count("question")&&`asked ${plural(count("question"),"question")}`,count("message")&&`replied on ${plural(count("message"),"note")}`].filter(Boolean),text=`${who} ${parts.slice(0,-1).join(", ")}${parts.length>1?" and ":""}${parts[parts.length-1]}`;return notify(text,"tensaku-summary"),toast(text,{timeout:8000,actions:{Show:()=>toggleSidebar(!0)}})}function nextAnnouncement(){if(paceTimer=0,!waiting.length)return;if(shownToasts=shownToasts.filter((element)=>element.isConnected),shownToasts.length<SHOWN_AT_ONCE)if(waiting.length>SHOWN_AT_ONCE)shownToasts.push(announceSummary(waiting.splice(0)));else{let change=waiting.shift();shownToasts.push(announceOne(change.note,change.what))}if(waiting.length)paceTimer=window.setTimeout(nextAnnouncement,PACE)}function announce(note,what){let queued=waiting.findIndex((change)=>change.note.id===note.id);if(queued>=0)waiting.splice(queued,1);if(waiting.push({note,what}),!paceTimer)paceTimer=window.setTimeout(nextAnnouncement)}onChanges((before,after)=>{let old=new Map(before.map((note)=>[note.id,note]));for(let note of after){let previous=old.get(note.id);if(!previous)continue;if(changedHere(note.id))continue;let messages=note.thread?.length??0;if(messages>(previous.thread?.length??0)&&note.thread[messages-1].from==="agent"&&note.status===previous.status)announce(note,"message");else if(note.status!==previous.status&&note.status!=="open"&&note.status!=="working")announce(note,note.status)}});var siClaude={title:"Claude",slug:"claude",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Claude</title><path d="'+this.path+'"/></svg>'},path:"m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z",source:"https://claude.ai",hex:"D97757"};var siCline={title:"Cline",slug:"cline",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Cline</title><path d="'+this.path+'"/></svg>'},path:"m23.365 13.556-1.442-2.895V8.994c0-2.764-2.218-5.002-4.954-5.002h-2.464c.178-.367.276-.779.276-1.213A2.77 2.77 0 0 0 12.018 0a2.77 2.77 0 0 0-2.763 2.779c0 .434.098.846.276 1.213H7.067c-2.736 0-4.954 2.238-4.954 5.002v1.667L.64 13.549c-.149.29-.149.636 0 .927l1.472 2.855v1.667C2.113 21.762 4.33 24 7.067 24h9.902c2.736 0 4.954-2.238 4.954-5.002V17.33l1.44-2.865c.143-.286.143-.622.002-.91m-12.854 2.36a2.27 2.27 0 0 1-2.261 2.273 2.27 2.27 0 0 1-2.261-2.273v-4.042A2.27 2.27 0 0 1 8.249 9.6a2.267 2.267 0 0 1 2.262 2.274zm7.285 0a2.27 2.27 0 0 1-2.26 2.273 2.27 2.27 0 0 1-2.262-2.273v-4.042A2.267 2.267 0 0 1 15.535 9.6a2.267 2.267 0 0 1 2.261 2.274z",source:"https://cline.bot/assets/branding/logos/cline-wordmark-black.svg",hex:"18181B"};var siCursor={title:"Cursor",slug:"cursor",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Cursor</title><path d="'+this.path+'"/></svg>'},path:"M11.503.131 1.891 5.678a.84.84 0 0 0-.42.726v11.188c0 .3.162.575.42.724l9.609 5.55a1 1 0 0 0 .998 0l9.61-5.55a.84.84 0 0 0 .42-.724V6.404a.84.84 0 0 0-.42-.726L12.497.131a1.01 1.01 0 0 0-.996 0M2.657 6.338h18.55c.263 0 .43.287.297.515L12.23 22.918c-.062.107-.229.064-.229-.06V12.335a.59.59 0 0 0-.295-.51l-9.11-5.257c-.109-.063-.064-.23.061-.23",source:"https://cursor.com/brand",hex:"000000"};var siGithubcopilot={title:"GitHub Copilot",slug:"githubcopilot",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>GitHub Copilot</title><path d="'+this.path+'"/></svg>'},path:"M23.922 16.997C23.061 18.492 18.063 22.02 12 22.02 5.937 22.02.939 18.492.078 16.997A.641.641 0 0 1 0 16.741v-2.869a.883.883 0 0 1 .053-.22c.372-.935 1.347-2.292 2.605-2.656.167-.429.414-1.055.644-1.517a10.098 10.098 0 0 1-.052-1.086c0-1.331.282-2.499 1.132-3.368.397-.406.89-.717 1.474-.952C7.255 2.937 9.248 1.98 11.978 1.98c2.731 0 4.767.957 6.166 2.093.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086.23.462.477 1.088.644 1.517 1.258.364 2.233 1.721 2.605 2.656a.841.841 0 0 1 .053.22v2.869a.641.641 0 0 1-.078.256Zm-11.75-5.992h-.344a4.359 4.359 0 0 1-.355.508c-.77.947-1.918 1.492-3.508 1.492-1.725 0-2.989-.359-3.782-1.259a2.137 2.137 0 0 1-.085-.104L4 11.746v6.585c1.435.779 4.514 2.179 8 2.179 3.486 0 6.565-1.4 8-2.179v-6.585l-.098-.104s-.033.045-.085.104c-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.545-3.508-1.492a4.359 4.359 0 0 1-.355-.508Zm2.328 3.25c.549 0 1 .451 1 1v2c0 .549-.451 1-1 1-.549 0-1-.451-1-1v-2c0-.549.451-1 1-1Zm-5 0c.549 0 1 .451 1 1v2c0 .549-.451 1-1 1-.549 0-1-.451-1-1v-2c0-.549.451-1 1-1Zm3.313-6.185c.136 1.057.403 1.913.878 2.497.442.544 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.15.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.319-.862-2.824-1.025-1.487-.161-2.192.138-2.533.529-.269.307-.437.808-.438 1.578v.021c0 .265.021.562.063.893Zm-1.626 0c.042-.331.063-.628.063-.894v-.02c-.001-.77-.169-1.271-.438-1.578-.341-.391-1.046-.69-2.533-.529-1.505.163-2.347.537-2.824 1.025-.462.472-.705 1.179-.705 2.319 0 1.211.175 1.926.558 2.361.365.414 1.084.751 2.657.751 1.21 0 1.902-.394 2.344-.938.475-.584.742-1.44.878-2.497Z",source:"https://primer.style/foundations/icons/copilot-24",hex:"000000",license:{type:"MIT",url:"https://spdx.org/licenses/MIT"}};var siGooglegemini={title:"Google Gemini",slug:"googlegemini",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Google Gemini</title><path d="'+this.path+'"/></svg>'},path:"M11.04 19.32Q12 21.51 12 24q0-2.49.93-4.68.96-2.19 2.58-3.81t3.81-2.55Q21.51 12 24 12q-2.49 0-4.68-.93a12.3 12.3 0 0 1-3.81-2.58 12.3 12.3 0 0 1-2.58-3.81Q12 2.49 12 0q0 2.49-.96 4.68-.93 2.19-2.55 3.81a12.3 12.3 0 0 1-3.81 2.58Q2.49 12 0 12q2.49 0 4.68.96 2.19.93 3.81 2.55t2.55 3.81",source:"https://gemini.google.com",hex:"8E75B2"};var siOpencode={title:"OpenCode",slug:"opencode",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>OpenCode</title><path d="'+this.path+'"/></svg>'},path:"M22 24H2V0h20zM17 4.8H7v14.4h10z",source:"https://github.com/anomalyco/opencode/blob/1251a870cb384543c150c4a72fb101b55eec971b/packages/identity/mark.svg",hex:"000000"};var siWindsurf={title:"Windsurf",slug:"windsurf",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Windsurf</title><path d="'+this.path+'"/></svg>'},path:"M23.55 5.067c-1.2038-.002-2.1806.973-2.1806 2.1765v4.8676c0 .972-.8035 1.7594-1.7597 1.7594-.568 0-1.1352-.286-1.4718-.7659l-4.9713-7.1003c-.4125-.5896-1.0837-.941-1.8103-.941-1.1334 0-2.1533.9635-2.1533 2.153v4.8957c0 .972-.7969 1.7594-1.7596 1.7594-.57 0-1.1363-.286-1.4728-.7658L.4076 5.1598C.2822 4.9798 0 5.0688 0 5.2882v4.2452c0 .2147.0656.4228.1884.599l5.4748 7.8183c.3234.462.8006.8052 1.3509.9298 1.3771.313 2.6446-.747 2.6446-2.0977v-4.893c0-.972.7875-1.7593 1.7596-1.7593h.003a1.798 1.798 0 0 1 1.4718.7658l4.9723 7.0994c.4135.5905 1.05.941 1.8093.941 1.1587 0 2.1515-.9645 2.1515-2.153v-4.8948c0-.972.7875-1.7594 1.7596-1.7594h.194a.22.22 0 0 0 .2204-.2202v-4.622a.22.22 0 0 0-.2203-.2203Z",source:"https://windsurf.com/brand",hex:"0B100F",guidelines:"https://windsurf.com/brand"};var siZedindustries={title:"Zed Industries",slug:"zedindustries",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Zed Industries</title><path d="'+this.path+'"/></svg>'},path:"M2.25 1.5a.75.75 0 0 0-.75.75v16.5H0V2.25A2.25 2.25 0 0 1 2.25 0h20.095c1.002 0 1.504 1.212.795 1.92L10.764 14.298h3.486V12.75h1.5v1.922a1.125 1.125 0 0 1-1.125 1.125H9.264l-2.578 2.578h11.689V9h1.5v9.375a1.5 1.5 0 0 1-1.5 1.5H5.185L2.562 22.5H21.75a.75.75 0 0 0 .75-.75V5.25H24v16.5A2.25 2.25 0 0 1 21.75 24H1.655C.653 24 .151 22.788.86 22.08L13.19 9.75H9.75v1.5h-1.5V9.375A1.125 1.125 0 0 1 9.375 8.25h5.314l2.625-2.625H5.625V15h-1.5V5.625a1.5 1.5 0 0 1 1.5-1.5h13.19L21.438 1.5z",source:"https://github.com/zed-industries/zed/blob/ccc939124fa2f366b3029926447fd0a0c46a85c7/assets/icons/logo_96.svg",hex:"084CCF"};var CLIENTS=[[/claude/i,siClaude],[/cursor/i,siCursor],[/gemini/i,siGooglegemini],[/opencode/i,siOpencode],[/copilot/i,siGithubcopilot],[/windsurf/i,siWindsurf],[/\bzed\b/i,siZedindustries],[/cline/i,siCline]];function readable(hex){let[r,g,b]=[0,2,4].map((i)=>parseInt(hex.slice(i,i+2),16));return 0.2126*r+0.7152*g+0.0722*b>90}function clientIcon(name){let brand=CLIENTS.find(([pattern])=>pattern.test(name))?.[1];if(!brand)return icon("plane");let svg=document.createElementNS("http://www.w3.org/2000/svg","svg");svg.setAttribute("class","client"),svg.setAttribute("viewBox","0 0 24 24"),svg.setAttribute("aria-hidden","true"),svg.setAttribute("focusable","false");let path=document.createElementNS("http://www.w3.org/2000/svg","path");if(path.setAttribute("d",brand.path),svg.append(path),readable(brand.hex))svg.style.color=`#${brand.hex}`;return svg}var popover=null,popoverTool=null,rendered=()=>[],popoverOpen=(tool)=>tool?popoverTool===tool:Boolean(popover);function closePopover(){popover?.remove(),popover=null,popoverTool?.setAttribute("aria-pressed","false"),popoverTool=null}function togglePopover(tool,dock,render2){let same=popoverTool===tool;if(closePopover(),same)return;rendered=render2,popover=div("popover",...render2()),popover.addEventListener("keydown",(event)=>event.stopPropagation());let rect=dock.getBoundingClientRect();popover.style.right=`${Math.max(12,innerWidth-rect.right)}px`,popover.style.bottom=`${innerHeight-rect.top+12}px`,fixed.append(popover),popoverTool=tool,tool.setAttribute("aria-pressed","true")}function redrawPopover(tool){if(popover&&(!tool||popoverTool===tool))popover.replaceChildren(...rendered())}function closeOutside(event){if(popover&&!event.composedPath().some((node)=>node===popover||node===popoverTool))closePopover()}var ago=(date)=>{let seconds=Math.round((Date.now()-date.getTime())/1000);return seconds<60?"just now":seconds<3600?`${Math.round(seconds/60)} min ago`:`${Math.round(seconds/3600)} h ago`};var PROMPTS={watch:"Watch my Tensaku notes",once:"Do my Tensaku notes",install:"bin/rails generate tensaku:install",channel:"claude --dangerously-load-development-channels server:tensaku"};function copyRow(text,done){return div("command",h("code",{},text),h("button",{type:"button",className:"icon-button",title:"Copy","aria-label":`Copy ${text}`,onclick:async()=>{await copy(text),toast(done)}},icon("copy")))}var DID={start_note:"started",resolve_note:"resolved",decline_note:"declined",ask_question:"asked on",reply_to_note:"replied on",get_note:"read",list_notes:"listed the notes",watch_notes:"checked for notes",current_selection:"read the selection"};function lastAction(agent){if(agent.working.length)return agent.working.map((note)=>h("a",{className:"doing",href:note.url,title:`“${note.comment}”`},`Working on ${note.id}: “${note.comment}”`));let last=agent.last,did=last?`${DID[last.tool]??last.tool}${last.note?` ${last.note}`:""} ${ago(new Date(last.at))}`:null,waiting2=agent.channel?"Live: notes reach its chat as you save them":"Waiting for your notes",text=agent.listening?`${waiting2}${did?` · ${did}`:""}`:did?`Last ${did}`:"No calls yet";return[h("span",{className:"doing"},text)]}function agentRow(agent){return div(`agent${agent.listening?" listening":""}${agent.channel?" live":""}${agent.working.length?" working":""}`,div("who",h("strong",{},clientIcon(agent.name),agentLabel(agent)),h("span",{className:"where"},agent.folder??"")),agent.outdated?div("outdated","Runs older Tensaku code. Reconnect it (/mcp in Claude Code) or restart it."):null,...lastAction(agent))}var idleOpen=!1;function renderAgents(){let agents2=currentAgents(),listening=agents2.filter((agent)=>agent.listening),idle=agents2.filter((agent)=>!agent.listening),ask=(lead)=>[h("p",{},lead),copyRow(PROMPTS.watch,"Copied. Paste it into your agent's chat."),h("p",{className:"where"},"It waits for notes and takes each one as you save it."),copyRow(PROMPTS.once,"Copied. Paste it into your agent's chat."),h("p",{className:"where"},"It works through the open notes, then stops."),h("p",{},h("strong",{},"Claude Code, without asking: "),"start it with Tensaku as a channel, and each note you save starts it working. Experimental, and it asks you to confirm at start:"),copyRow(PROMPTS.channel,"Copied. Run it in the app's folder.")],rest=listening.length&&idle.length?[h("button",{type:"button",className:"idle-toggle","aria-expanded":String(idleOpen),onclick:()=>{idleOpen=!idleOpen,redrawPopover()}},`${idle.length} more connected, not listening`),...idleOpen?idle.map(agentRow):[]]:idle.map(agentRow);return[h("h3",{},"Agents"),...agents2.length?[...listening.map(agentRow),...rest,...listening.length?[]:[div("connect",...ask("None is listening. Agents read notes when you ask them to, so say this in your agent's chat:"))]]:[div("empty","No agent connected."),div("connect",h("p",{},h("strong",{},"Set up once per project. "),"Run this in the app, then restart your agent. It adds Tensaku to Claude Code, Codex, Cursor, Gemini CLI and OpenCode:"),copyRow(PROMPTS.install,"Copied. Run it in the app, then restart your agent."),h("p",{className:"where"},"Already set up? Start your agent in this project and it shows here. In Claude Code, /mcp reconnects it."),...ask("Then say this in your agent's chat:"))]]}var CONTEXT=26,MAX_LINES=3;function sharedEnds(before,after){let prefix=0;while(prefix<before.length&&before[prefix]===after[prefix])prefix++;let suffix=0;while(suffix<before.length-prefix&&suffix<after.length-prefix&&before[before.length-1-suffix]===after[after.length-1-suffix])suffix++;while(prefix>0&&/\w/.test(before[prefix-1]))prefix--;while(suffix>0&&/\w/.test(before[before.length-suffix]))suffix--;return{prefix,suffix}}function row(sign,line,{prefix,suffix}){let end=line.length-suffix,head=prefix>CONTEXT?`…${line.slice(prefix-CONTEXT,prefix).replace(/^\S*\s/,"")}`:line.slice(0,prefix).trimStart(),tail=suffix>CONTEXT?`${line.slice(end,end+CONTEXT).replace(/\s\S*$/,"")}…`:line.slice(end);return div(`diff-row ${sign==="-"?"removed":"added"}`,h("span",{className:"diff-sign"},sign),head,h("mark",{},line.slice(prefix,end)),tail)}function diffRows({removed,added}){let count=Math.max(removed.length,added.length),rows=[];for(let index=0;index<Math.min(count,MAX_LINES);index++){let ends=sharedEnds(removed[index]??"",added[index]??"");if(removed[index]!==void 0)rows.push(row("-",removed[index],ends));if(added[index]!==void 0)rows.push(row("+",added[index],ends))}if(count>MAX_LINES)rows.push(div("diff-more",`${count-MAX_LINES} more ${count-MAX_LINES===1?"line":"lines"} changed`));return div("diff",...rows)}var INTERPOLATION=/(%\{[^}]+\})/;function finish(result,kind,verb,actions){if(!result.changed)return;let where=result.diff?`${result.file}:${result.diff.line}`:result.file??"";if(toast(`${verb} ${where}`.trim(),{timeout:result.diff?8000:void 0,detail:result.diff?diffRows(result.diff):void 0,actions}),result.warning)toast(result.warning,{timeout:8000});refresh(kind)}function report(error){let message=error instanceof Error?error.message:String(error);toast(message,{error:!0,actions:error instanceof ApiError&&error.stale?{Reload:()=>location.reload()}:void 0})}function rangeAfter(range,text){let[,path,startLine,startColumn]=range.match(/^(.+):(\d+):(\d+)-/),lines=text.split(`
379
+ `),endLine=Number(startLine)+lines.length-1,endColumn=(lines.length===1?Number(startColumn)-1:0)+utf8Length(lines[lines.length-1]);return`${path}:${startLine}:${startColumn}-${endLine}:${endColumn}`}var textNodesOf2=(stamp)=>Array.from(document.querySelectorAll(`[${STAMP}="${CSS.escape(stamp)}"]`)).flatMap((el)=>Array.from(el.childNodes).filter((node)=>node.nodeType===Node.TEXT_NODE));function showTranslation(key,from,to){if(INTERPOLATION.test(from))return;replaceText(nodesForKey(key),from,to),elementsWithAttributeKey(key).forEach(({element:el,name})=>{if(el.getAttribute(name)===from)el.setAttribute(name,to)})}var HISTORY_LIMIT=50,HISTORY_KEY="tensaku:history",done=[],undone=[];try{let saved=JSON.parse(sessionStorage.getItem(HISTORY_KEY)??"null");if(saved&&Array.isArray(saved.done)&&Array.isArray(saved.undone))({done,undone}=saved)}catch{}function persist(){try{sessionStorage.setItem(HISTORY_KEY,JSON.stringify({done,undone}))}catch{}}var nextId=()=>Math.max(0,...done.map((entry)=>entry.id),...undone.map((entry)=>entry.id))+1;function record(element,label,op,file){let entry={id:nextId(),label,key:element?undoKey(element):null,file,at:new Date().toISOString(),op};if(done.push(entry),done.length>HISTORY_LIMIT)done.shift();return undone=[],persist(),entry}function editHistory(){return{done:done.slice().reverse(),undone:undone.slice().reverse()}}var canUndo=()=>done.length>0,canRedo=()=>undone.length>0;async function undo(entry=done[done.length-1]){if(!entry||!done.includes(entry))return toast("That edit was undone already.");try{let result=await apply(entry.op,!0);done=done.filter((item)=>item!==entry),undone.push(entry),persist(),finish(result,sourceKind(entry.op),`Undid ${entry.label}`,{Redo:()=>redo(entry)})}catch(error){report(error)}}async function redo(entry=undone[undone.length-1]){if(!entry||undone[undone.length-1]!==entry)return toast("Only the latest undone edit can be redone.");try{let result=await apply(entry.op,!1);undone.pop(),done.push(entry),persist(),finish(result,sourceKind(entry.op),`Redid ${entry.label}`,{Undo:()=>undo(entry)})}catch(error){report(error)}}var sourceKind=(op)=>op.kind==="attribute"?"template":op.kind;function undoFor(element){let key=undoKey(element);return key?done.slice().reverse().find((entry)=>entry.key===key):void 0}async function apply(op,reverse){let verb=reverse?"undone":"redone",stale=(what)=>new ApiError(`The ${what} changed since the edit, so it can't be ${verb} here.`,409,!0);if(op.kind==="template"){let texts=(await api("GET","/source"+query({stamp:op.stamp}))).pieces.filter((p)=>p.kind==="text"),edits=op.changes.map(({index,from,to})=>{let[current3,target2]=reverse?[to,from]:[from,to],now=texts[index];if(!now||now.text!==current3)throw stale("text");return{piece:now,current:current3,target:target2}}),result2=await api("POST","/text",{stamp:op.stamp,edits:edits.map(({piece,target:target2})=>({start:piece.start,end:piece.end,original:piece.raw,text:target2}))}),nodes=textNodesOf2(op.stamp);return edits.forEach(({current:current3,target:target2})=>replaceText(nodes,current3,target2)),result2}if(op.kind==="attribute"){let result2={};for(let{name,index,from,to}of op.changes){let[current3,target2]=reverse?[to,from]:[from,to],now=(await api("GET","/source"+query({stamp:op.stamp}))).attributes.find((a)=>a.name===name)?.pieces.filter((p)=>p.kind==="text")[index];if(!now||now.text!==current3)throw stale("attribute");result2=await api("POST","/attribute",{stamp:op.stamp,name,start:now.start,end:now.end,original:now.raw,text:target2}),document.querySelectorAll(`[${STAMP}="${CSS.escape(op.stamp)}"]`).forEach((el)=>{let value=el.getAttribute(name);if(value!==null)el.setAttribute(name,value.replace(current3,target2))})}return{...result2,changed:!0}}if(op.kind==="translation"){let result2={};for(let{locale,from,to}of op.changes){let[current3,target2]=reverse?[to,from]:[from,to],saved=await api("POST","/translation",{locale,key:op.key,original:current3,text:target2});result2={...saved,file:result2.file??saved.file,changed:!0},showTranslation({locale,key:op.key},current3,target2)}return result2}let[current2,target]=reverse?[op.to,op.from]:[op.from,op.to],result=await api("POST","/markdown",{range:op.range,original:op.prefix+current2,text:target,tag:op.tag});return op.range=rangeAfter(op.range,op.prefix+target),result}function undoKey(element){let translation=translationOf(element);return element.getAttribute(STAMP)??element.getAttribute(MARKDOWN)??(translation?`${translation.locale}.${translation.key}`:null)}var UNDO_KEYS=isApple?"⌘Z and ⇧⌘Z":"Ctrl+Z and Ctrl+Y";function renderHistory(){let{done:done2,undone:undone2}=editHistory(),row2=(entry,action)=>div(`entry${undone2.includes(entry)?" undone":""}`,div("what",h("span",{},entry.label),h("span",{className:"where"},`${entry.file??""} · ${ago(new Date(entry.at))}`)),action),button=(text,run)=>h("button",{type:"button",onclick:async()=>{await run(),closePopover()}},text);return[h("h3",{},"Edit history",h("span",{className:"where"},`Saves in this tab. ${UNDO_KEYS} undo and redo.`)),...done2.length||undone2.length?[...done2.map((entry)=>row2(entry,button("Undo",()=>undo(entry)))),...undone2.map((entry,i)=>row2(entry,i===0?button("Redo",()=>redo(entry)):h("span",{className:"where"},"undone")))]:[div("empty","No edits yet.")]]}var current2="off",listeners4=[],mode=()=>current2,onMode=(listener)=>listeners4.push(listener);function setMode(next){current2=next,listeners4.forEach((listener)=>listener(next))}var paused=null;function togglePause(){if(paused)return paused.style.remove(),paused.animations.forEach((animation)=>{try{animation.play()}catch{}}),paused.media.forEach((media2)=>media2.play().catch(()=>{})),paused=null,!1;let animations=document.getAnimations().filter((animation)=>{let target=animation.effect?.target;return animation.playState==="running"&&!(target&&isUi(target))});animations.forEach((animation)=>animation.pause());let media=Array.from(document.querySelectorAll("video, audio")).filter((element)=>!element.paused);media.forEach((element)=>element.pause());let style=document.createElement("style");return style.setAttribute("data-tensaku-pause",""),style.textContent="*, *::before, *::after { animation-play-state: paused !important; transition: none !important; }",document.head.append(style),paused={animations,media,style},!0}var pinLayer=div("pins");layer.append(pinLayer);function setPinsHidden(hidden){pinLayer.hidden=hidden}var drawn=new Map;onRender(({first})=>{if(first)currentNotes().forEach((note)=>drawn.set(note.id,note.status));drawPins()});function drawPins(){pinLayer.replaceChildren(),currentNotes().forEach((note,index)=>{let phrase=phraseRects(note);for(let r of phrase){let mark=div(`phrase ${note.status}`);Object.assign(mark.style,{left:`${r.left}px`,top:`${r.top}px`,width:`${r.width}px`,height:`${r.height}px`}),pinLayer.append(mark)}let point=phrase.length?null:pointFor(note),rect=phrase.length?phrase[phrase.length-1]:point??anchorFor(note);if(!rect)return;let fresh=drawn.get(note.id)!==note.status;drawn.set(note.id,note.status);let pin=h("button",{className:`pin ${note.status}${fresh?" fresh":""}`,title:note.comment,"aria-label":`Note ${index+1}: ${note.comment}`,"data-note":note.id},note.status==="resolved"?icon("check"):note.status==="declined"?icon("close"):String(index+1));Object.assign(pin.style,{left:`${point?point.x:rect.right}px`,top:`${rect.top}px`}),pin.addEventListener("click",(event)=>{event.stopPropagation(),showNote(note,rect)}),pinLayer.append(pin)})}var SHORTCUT_TOOLS={select:"Select",edit:"Edit",notes:"Notes",agents:"Agents",pins:"Hide or show pins",clear:"Delete this page's notes",pause:"Pause animations",history:"Edit history",settings:"Settings"},DEFAULTS2={select:"alt+shift+KeyT",edit:"alt+shift+KeyE",notes:"alt+shift+KeyN"};function shortcutFor(tool){let own=settings().shortcuts;return tool in own?own[tool]:DEFAULTS2[tool]??null}var isDefault=(tool)=>!(tool in settings().shortcuts);function setShortcut(tool,keys){let shortcuts={...settings().shortcuts},taken=keys?toolFor(keys):null;if(taken&&taken!==tool)shortcuts[taken]=null;if(keys===(DEFAULTS2[tool]??null))delete shortcuts[tool];else shortcuts[tool]=keys;return changeSettings({shortcuts}),taken&&taken!==tool?taken:null}var resetShortcuts=()=>changeSettings({shortcuts:{}});function toolFor(keys){return Object.keys(SHORTCUT_TOOLS).find((tool)=>shortcutFor(tool)===keys)??null}function toolForEvent(event){return event.code?toolFor(keysOf(event)):null}function keysOf(event){return[...[event.ctrlKey&&"ctrl",event.altKey&&"alt",event.shiftKey&&"shift",event.metaKey&&"meta"].filter(Boolean),event.code].join("+")}var isModifierKey=(event)=>["Alt","Shift","Control","Meta"].includes(event.key),hasCommandModifier=(event)=>event.altKey||event.ctrlKey||event.metaKey,APPLE_KEYS={alt:"⌥",shift:"⇧",ctrl:"⌃",meta:"⌘"},OTHER_KEYS={alt:"Alt",shift:"Shift",ctrl:"Ctrl",meta:"Meta"};function keysLabel(keys){let parts=keys.split("+"),key=parts.pop().replace(/^(Key|Digit)/,""),names=isApple?APPLE_KEYS:OTHER_KEYS;return[...parts.map((part)=>names[part]??part),key].join(isApple?"":"+")}var panel2=null,recording=null,hooks={toggled:()=>{},moveDockHome:()=>{}},setSettingsHooks=(given)=>{hooks=given},settingsOpen=()=>Boolean(panel2?.isConnected);function toggleSettings(force){let show=force??!settingsOpen();if(stopRecording(),!show){panel2?.remove(),hooks.toggled();return}panel2??=div("sidebar settings"),panel2.setAttribute("role","complementary"),panel2.setAttribute("aria-label","Tensaku settings"),fixed.append(panel2),render2(),hooks.toggled()}function render2(){if(!panel2)return;let prefs=settings(),choice=(value,text)=>h("button",{type:"button","aria-pressed":String(prefs.copyFormat===value),onclick:()=>{changeSettings({copyFormat:value}),render2()}},text),notify2=h("input",{type:"checkbox",checked:prefs.notify});notify2.addEventListener("change",async()=>{let on=notify2.checked;if(on&&"Notification"in window&&Notification.permission==="default")await Notification.requestPermission();let allowed="Notification"in window&&Notification.permission==="granted";if(on&&!allowed)toast("The browser blocked notifications for this site.",{error:!0});changeSettings({notify:on&&allowed}),render2()});let customized=Object.keys(SHORTCUT_TOOLS).some((tool)=>!isDefault(tool));panel2.replaceChildren(h("header",{},h("strong",{},"Settings"),h("button",{type:"button",className:"icon-button",onclick:()=>toggleSettings(!1),"aria-label":"Close settings"},icon("close"))),h("section",{},h("h4",{},"Notes"),div("setting",h("span",{},"Copy notes as"),div("segmented",choice("detailed","Detailed"),choice("short","One line each"))),h("label",{className:"check"},notify2,h("span",{},"Notify me",h("span",{className:"where"},"When an agent answers while this tab is in the background.")))),h("section",{},h("h4",{},"Keyboard shortcuts",customized?h("button",{type:"button",className:"link",onclick:()=>{resetShortcuts(),render2()}},"Reset all"):null),h("p",{className:"where"},"Click a shortcut and press the new keys, with Alt, Ctrl or Cmd. Escape cancels."),...Object.entries(SHORTCUT_TOOLS).map(([tool,name])=>shortcutRow(tool,name)),h("h5",{},"Always on"),...fixedShortcuts().map(([keys,what])=>div("shortcut always",h("span",{},what),h("kbd",{},keys)))),h("section",{},h("h4",{},"Toolbar"),div("setting",h("button",{type:"button",onclick:()=>hooks.moveDockHome()},"Move the toolbar back to the corner"))))}function shortcutRow(tool,name){let keys=shortcutFor(tool),waiting2=recording===tool,record2=h("button",{type:"button",className:`keys${waiting2?" recording":""}`,"aria-label":`Change the shortcut for ${name}`,onclick:()=>startRecording(tool)},waiting2?"Press keys…":keys?h("kbd",{},keysLabel(keys)):h("span",{className:"none"},"None")),clear=keys&&!waiting2?h("button",{type:"button",className:"icon-button","aria-label":`Remove the shortcut for ${name}`,onclick:()=>{setShortcut(tool,null),render2()}},icon("close")):null;return div(`shortcut${isDefault(tool)?"":" changed"}`,h("span",{},name),record2,clear)}function startRecording(tool){stopRecording(),recording=tool,addEventListener("keydown",onRecordKey,!0),render2()}function stopRecording(){recording=null,removeEventListener("keydown",onRecordKey,!0)}function onRecordKey(event){if(!recording||!settingsOpen()){stopRecording();return}if(isModifierKey(event))return;event.preventDefault(),event.stopImmediatePropagation();let tool=recording;if(stopRecording(),event.key==="Escape"){render2();return}if(!hasCommandModifier(event)){toast("Use Alt, Ctrl or Cmd with the key, so typing never triggers it.",{error:!0}),render2();return}let keys=keysOf(event),moved=setShortcut(tool,keys);if(moved)toast(`${keysLabel(keys)} no longer does ${SHORTCUT_TOOLS[moved]}.`);render2()}function fixedShortcuts(){let click=(keys)=>isApple?`${keys} click`:`${keys}+click`,alt=isApple?"⌥":"Alt",shift=isApple?"⇧":"Shift";return[[click(alt),"Menu for an element"],[click(isApple?alt+shift:`${alt}+${shift}`),"Note on an element"],[click(shift),"Pick several elements, in select mode"],["N","Note the picked elements"],["Esc","Close a menu or panel, or leave the mode"]]}var INK={highlighter:"#ffe14d",pen:"#e0344f",pad:"#fff1a1"},count=h("span",{className:"count",hidden:!0}),corner=h("button",{className:"corner",type:"button",title:"Tensaku","aria-label":"Tensaku","aria-expanded":"false"},logo(),count);function tool(name,ink,text){let tip=h("span",{className:"tip","aria-hidden":"true"},text),button=h("button",{type:"button",className:"tool","aria-pressed":"false","aria-label":text},icon(name,ink),tip);return button.style.setProperty("--ink-color",ink),button}function action(name,text){return h("button",{type:"button",className:"tool","aria-label":text},icon(name),h("span",{className:"tip","aria-hidden":"true"},text))}function setTip(button,text){button.setAttribute("aria-label",text),button.querySelector(".tip").firstChild.textContent=text}var setIcon=(button,name,ink)=>button.replaceChild(icon(name,ink),button.querySelector("svg")),selectTool=tool("highlighter",INK.highlighter,"Select"),editTool=tool("pen",INK.pen,"Edit"),notesTool=tool("pad",INK.pad,"Notes"),notesBadge=h("span",{className:"badge",hidden:!0});notesTool.append(notesBadge);var pinsTool=action("eye","Hide pins"),pauseTool=action("pause","Pause animations"),clearTool=action("trash","Delete this page's notes"),historyTool=action("history","Edit history"),settingsTool=action("sliders","Settings"),agentsTool=action("plane","No agent connected");agentsTool.classList.add("agents");var agentsBadge=h("span",{className:"badge",hidden:!0});agentsTool.append(agentsBadge);var tools=div("tools",selectTool,editTool,div("sep"),notesTool,agentsTool,pinsTool,clearTool,div("sep"),pauseTool,historyTool,settingsTool),toolbar=div("toolbar",tools);new ResizeObserver(()=>toolbar.style.setProperty("--tools-width",`${tools.offsetWidth}px`)).observe(tools);var dock=div("dock",toolbar,corner);fixed.append(dock);var shortcutButtons={select:selectTool,edit:editTool,notes:notesTool,agents:agentsTool,pins:pinsTool,clear:clearTool,pause:pauseTool,history:historyTool,settings:settingsTool};onSettings(()=>{for(let[name,button]of Object.entries(shortcutButtons)){let keys=shortcutFor(name),tip=button.querySelector(".tip");if(tip.querySelector("kbd")?.remove(),keys)tip.append(h("kbd",{},keysLabel(keys)))}});function pressShortcut(name){setToolbar(!0),shortcutButtons[name].click()}var toolbarOpen=()=>dock.classList.contains("open"),settling=0;function setToolbar(open2){if(open2===toolbarOpen())return;if(dock.classList.toggle("open",open2),corner.setAttribute("aria-expanded",String(open2)),clearTimeout(settling),dock.classList.remove("settled"),open2)settling=window.setTimeout(()=>dock.classList.add("settled"),280)}function moveDock(right,bottom){dock.style.right=`${right}px`,dock.style.bottom=`${bottom}px`,dock.style.setProperty("--dock-right",`${right}px`)}function placeDock(){let position=storage("dock",{right:16,bottom:16});moveDock(Math.min(Math.max(position.right,4),innerWidth-52),Math.min(Math.max(position.bottom,4),innerHeight-52))}var dragged=!1;corner.addEventListener("pointerdown",(event)=>{let start={x:event.clientX,y:event.clientY,right:parseFloat(dock.style.right),bottom:parseFloat(dock.style.bottom)};dragged=!1,corner.setPointerCapture(event.pointerId);let move=(e)=>{let dx=e.clientX-start.x,dy=e.clientY-start.y;if(!dragged&&Math.hypot(dx,dy)<4)return;dragged=!0,corner.style.cursor="grabbing",moveDock(start.right-dx,start.bottom-dy)},up=()=>{if(corner.removeEventListener("pointermove",move),corner.removeEventListener("pointerup",up),corner.removeEventListener("pointercancel",up),corner.style.cursor="",dragged)store("dock",{right:parseFloat(dock.style.right),bottom:parseFloat(dock.style.bottom)})};corner.addEventListener("pointermove",move),corner.addEventListener("pointerup",up),corner.addEventListener("pointercancel",up)});corner.addEventListener("click",()=>{if(dragged)return;if(setToolbar(!toolbarOpen()),toolbarOpen())return;toggleSidebar(!1),toggleSettings(!1),setMode("off")});function closeToolbar(){if(!toolbarOpen())return!1;return setToolbar(!1),!0}function syncButtons(){selectTool.setAttribute("aria-pressed",String(mode()==="inspect")),editTool.setAttribute("aria-pressed",String(mode()==="edit")),notesTool.setAttribute("aria-pressed",String(sidebarOpen())),settingsTool.setAttribute("aria-pressed",String(settingsOpen())),corner.classList.toggle("active",mode()!=="off")}onMode((next)=>{if(next!=="off")setToolbar(!0);syncButtons()});function closeSidePanel(){if(settingsOpen())return toggleSettings(!1),!0;if(!sidebarOpen())return!1;return toggleSidebar(!1),syncButtons(),!0}selectTool.addEventListener("click",()=>setMode(mode()==="inspect"?"off":"inspect"));editTool.addEventListener("click",()=>setMode(mode()==="edit"?"off":"edit"));notesTool.addEventListener("click",()=>{toggleSettings(!1),toggleSidebar(),syncButtons()});onCount((n)=>{count.hidden=n===0,count.textContent=String(n),notesBadge.hidden=n===0,notesBadge.textContent=String(n),setTip(notesTool,n?`Notes (${n})`:"Notes")});setSettingsHooks({toggled:syncButtons,moveDockHome:()=>{store("dock",{right:16,bottom:16}),placeDock()}});settingsTool.addEventListener("click",()=>{if(closePopover(),!settingsOpen())toggleSidebar(!1);toggleSettings()});historyTool.addEventListener("click",()=>togglePopover(historyTool,dock,renderHistory));var pinsHidden=storage("pinsHidden",!1);function syncPins(){setPinsHidden(pinsHidden),pinsTool.setAttribute("aria-pressed",String(pinsHidden)),setIcon(pinsTool,pinsHidden?"eye-off":"eye"),setTip(pinsTool,pinsHidden?"Show pins":"Hide pins")}pinsTool.addEventListener("click",()=>{pinsHidden=!pinsHidden,store("pinsHidden",pinsHidden),syncPins()});pauseTool.addEventListener("click",()=>{let paused2=togglePause();pauseTool.setAttribute("aria-pressed",String(paused2)),setIcon(pauseTool,paused2?"play":"pause"),setTip(pauseTool,paused2?"Resume animations":"Pause animations")});var confirmClear=0;clearTool.addEventListener("click",async()=>{let total=currentNotes().length;if(!total){toast("No notes on this page");return}if(!confirmClear){clearTool.classList.add("confirm"),setTip(clearTool,`Delete ${total} ${total===1?"note":"notes"}? Click again`),confirmClear=window.setTimeout(resetClear,3000);return}resetClear();try{await deleteNotes(currentNotes()),toast(`Deleted ${total} ${total===1?"note":"notes"}`)}catch(error){toast(error.message,{error:!0})}});function resetClear(){clearTimeout(confirmClear),confirmClear=0,clearTool.classList.remove("confirm"),setTip(clearTool,"Delete this page's notes")}var names=(list)=>list.map(agentLabel).join(", "),agentsSignature="[]";onAgents((agents2)=>{let signature=JSON.stringify(agents2);if(signature===agentsSignature)return;agentsSignature=signature;let listening=agents2.filter((agent)=>agent.listening);agentsTool.classList.toggle("connected",agents2.length>0),agentsTool.classList.toggle("listening",listening.length>0),setIcon(agentsTool,listening.length?"plane-flying":"plane",listening.length?"#2fa872":void 0),agentsBadge.hidden=agents2.length<2,agentsBadge.textContent=String(agents2.length),setTip(agentsTool,listening.length?`${names(listening)} listening`:agents2.length?`${names(agents2)} connected`:"No agent connected"),redrawPopover(agentsTool)});agentsTool.addEventListener("click",()=>togglePopover(agentsTool,dock,renderAgents));setAgentsHandler(()=>{if(setToolbar(!0),!popoverOpen(agentsTool))togglePopover(agentsTool,dock,renderAgents)});var open2=null,composing=(event)=>event.isComposing||event.keyCode===229;function isEditing(){return open2!==null}function closeEditor(){open2?.close()}async function edit(element,kind=editKind(element)){closeEditor();try{if(kind==="translation")await editTranslation(element,translationOf(element));else if(kind==="markdown")await editMarkdown(element);else if(kind==="template")await editTemplate(element);else if(kind==="attributes")await editAttributes(element);else toast("This text comes from Ruby, so it can't be edited here. Leave a note instead.")}catch(error){report(error)}}var normal=(text)=>text.replace(/\s+/g," ").trim();function assertRendered(element,texts){let rendered2=normal(element.textContent??""),from=0;for(let text of texts.map(normal).filter(Boolean)){let at=rendered2.indexOf(text,from);if(at<0)throw new ApiError("The file changed since the page was rendered. Reload the page and try again.",409,!0);from=at+text.length}}function field(text,multiline=!1){let span=h("span",{className:"editable",spellcheck:"true"},text);if(span.contentEditable="plaintext-only",span.contentEditable!=="plaintext-only")span.contentEditable="true";if(span.dataset.original=text,span.addEventListener("paste",(event)=>{event.preventDefault(),document.execCommand("insertText",!1,event.clipboardData?.getData("text/plain")??"")}),!multiline)span.addEventListener("keydown",(event)=>{if(event.key==="Enter"&&event.shiftKey&&!composing(event))event.preventDefault()});return span}var valueOf=(span)=>(span.innerText??span.textContent??"").replace(/ /g," ").replace(/\n$/,"");function chip(label,title){return h("span",{className:"chip",title,contenteditable:"false"},label)}function backgroundOf(element){for(let node=element;node;node=node.parentElement){let color=getComputedStyle(node).backgroundColor,alpha=color.match(/rgba?\([^)]*,\s*([\d.]+)\)/)?.[1];if(color!=="transparent"&&(alpha===void 0||Number(alpha)>0.6))return color}return"#fff"}var INSET={x:11.5,y:9.5};function frame(element,surface,info,save,extra=[],warning){let rect=contentRect(element),computed=getComputedStyle(element);Object.assign(surface.style,{fontFamily:computed.fontFamily,fontSize:computed.fontSize,fontWeight:computed.fontWeight,lineHeight:computed.lineHeight,letterSpacing:computed.letterSpacing,textAlign:computed.textAlign,color:computed.color}),surface.classList.add("surface");let status=h("span",{},info),close=()=>{container.remove(),open2=null,document.removeEventListener("keydown",keys,!0)},saveAndClose=async()=>{if(container.dataset.saving)return;container.dataset.saving="1",status.textContent="Saving…";try{await save(),close()}catch(error){delete container.dataset.saving,status.textContent=info,report(error)}},bar=div("bar",h("span",{},status,warning?h("strong",{className:"ink-warning"},` · ${warning}`):null),div("actions",h("button",{onclick:close,type:"button"},"Cancel"),h("button",{className:"primary",onclick:saveAndClose,type:"button"},"Save"))),container=div("panel editor",surface,...extra,bar);container.setAttribute("role","dialog"),container.setAttribute("aria-label","Tensaku editor"),container.style.background=backgroundOf(element),container.style.color=computed.color;let room=innerWidth-16;container.style.minWidth=`${Math.min(Math.max(rect.width+INSET.x*2,240),room)}px`,container.style.maxWidth=`${Math.min(Math.max(rect.width+INSET.x*2,480),room)}px`,layer.append(container),place(container,new DOMRect(rect.left-INSET.x,rect.top-INSET.y,rect.width+INSET.x*2,rect.height),!0),bar.style.maxWidth=`${innerWidth-8-container.getBoundingClientRect().left}px`;let keys=(event)=>{if(!container.isConnected)return;if(event.key==="Escape")event.preventDefault(),event.stopPropagation(),close();if(event.key!=="Enter"||composing(event)||!activeInShadow()?.classList.contains("editable"))return;if(surface.dataset.newlines!==void 0?event.metaKey||event.ctrlKey:!event.shiftKey)event.preventDefault(),saveAndClose()};return document.addEventListener("keydown",keys,!0),container.addEventListener("focusout",()=>{setTimeout(()=>{let active=activeInShadow();if(container.isConnected&&!container.dataset.saving&&!(active&&container.contains(active)))saveAndClose()},150)}),open2={element:container,save:saveAndClose,close},container.querySelector(".editable")?.focus(),container}var NESTED_STYLES=["fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","textTransform","color"];function nestedElement(piece,host2,unchanged){if(piece.tag==="br"||piece.tag.startsWith("br.")||piece.tag.startsWith("br#"))return document.createElement("br");let child=piece.stamp?host2?.querySelector(`[${STAMP}="${CSS.escape(piece.stamp)}"]`):null,computed=child?getComputedStyle(child):null;if(computed&&(computed.display==="none"||computed.position==="absolute"||computed.position==="fixed"))return null;let text=child?visibleText(child,80):piece.label;if(!text)return h("span",{className:"chip mark",title:`<${piece.tag}>`,contenteditable:"false"});let span=h("span",{className:"nested",contenteditable:"false"},text);if(computed){if(NESTED_STYLES.forEach((name)=>{span.style[name]=computed[name]}),!computed.display.startsWith("inline"))span.style.display="block"}if(child&&editKind(child))span.classList.add("link"),span.title="Edit this element on its own",span.addEventListener("click",()=>{if(unchanged())edit(child)});return span}function pieceSurface(pieces,host2){let surface=div(""),fields=[],unchanged=()=>fields.every(({span,piece})=>valueOf(span)===piece.text);for(let piece of pieces)if(piece.kind==="text"){if(!piece.text.trim()){if(surface.lastChild&&surface.lastChild.nodeName!=="BR")surface.append(" ");continue}let span=field(piece.text);fields.push({span,piece}),surface.append(span)}else if(piece.kind==="ruby")surface.append(chip(piece.code.length>30?piece.code.slice(0,29)+"…":piece.code,piece.code));else if(piece.kind==="element"){let node=nestedElement(piece,host2,unchanged);if(node)surface.append(node)}return{surface,fields}}async function editTemplate(element){let stamp=stampOf(element),info=await api("GET","/source"+query({stamp:stamp.value}));if(indexPieces(info.pieces),!info.editable){if(editableAttributes(element).length)return editAttributes(element);throw Error(info.helper?"This element comes from a helper, so its text can't be edited here.":"This element has no static text to edit.")}assertRendered(element,info.pieces.filter((p)=>p.kind==="text").map((p)=>p.text));let{surface,fields}=pieceSurface(info.pieces,element),copies=copiesOf(element);frame(element,surface,`${info.file}:${stamp.line}`,async()=>{let changed=fields.filter(({span,piece})=>valueOf(span)!==piece.text);if(!changed.length)return;await saveTemplate(element,stamp.value,changed.map(({span,piece})=>({piece,text:valueOf(span)})))},[],copies>1?`this edits all ${copies} copies`:void 0)}async function saveTemplate(element,stamp,changes){let result=await api("POST","/text",{stamp,edits:changes.map(({piece,text})=>({start:piece.start,end:piece.end,original:piece.raw,text}))}),nodes=textNodesOf2(stamp);changes.forEach(({piece,text})=>replaceText(nodes,piece.text,text));let entry=result.changed?record(element,`edit in ${stamp}`,{kind:"template",stamp,changes:changes.map(({piece,text})=>({index:piece.index??-1,from:piece.text,to:text}))},result.file):void 0;afterSave(result,"template",entry)}async function editAttributes(element){let stamp=stampOf(element),description=stamp?await api("GET","/source"+query({stamp:stamp.value})):null,names2=editableAttributes(element),rows=[],savers=[],templateFields=[];for(let name of names2){let key=attributeKey(element,name);if(key){let entry=(await api("GET","/translation"+query({key:key.key}))).locales[key.locale];if(!entry?.editable||entry.value===null)continue;assertRendered(attributeNode(element,name),staticParts(entry.value));let{surface:surface3,read}=interpolationSurface(entry.value);rows.push(div("attr",h("span",{className:"name",title:`${key.locale}.${key.key}`},`${name} (t)`),div("value",surface3))),savers.push(async()=>{let text=read();if(text===entry.value)return;await saveTranslations(element,key,[{locale:key.locale,from:entry.value,to:text}]),entry.value=text});continue}let attribute=description?.attributes.find((a)=>a.name===name);if(!attribute||!attribute.pieces.some((p)=>p.kind==="text"))continue;assertRendered(attributeNode(element,name),attribute.pieces.filter((p)=>p.kind==="text").map((p)=>p.text));let{surface:surface2,fields}=pieceSurface(attribute.pieces);rows.push(div("attr",h("span",{className:"name"},name),div("value",surface2))),fields.forEach(({span,piece})=>templateFields.push({name,span,piece}))}if(templateFields.length)savers.push(()=>saveAttributePieces(element,stamp.value,templateFields));if(!rows.length)throw Error("Nothing here can be edited. Leave a note instead.");let surface=div("");surface.append(...rows),frame(element,surface,description?`${description.file}:${stamp.line} attributes`:"attributes",async()=>{for(let save of savers)await save()})}async function saveAttributePieces(element,stamp,fields){let changed=fields.map(({name,span,piece})=>({name,piece,text:valueOf(span)})).filter(({piece,text})=>text!==piece.text).sort((a,b)=>b.piece.start-a.piece.start);if(!changed.length)return;let saved=[],last={};try{for(let{name,piece,text}of changed){last=await api("POST","/attribute",{stamp,name,start:piece.start,end:piece.end,original:piece.raw,text}),document.querySelectorAll(`[${STAMP}="${CSS.escape(stamp)}"]`).forEach((el)=>{let current3=el.getAttribute(name);if(current3!==null)el.setAttribute(name,current3.replace(piece.text,text))});let index=fields.filter((field2)=>field2.name===name).findIndex((field2)=>field2.piece===piece);saved.push({name,index,from:piece.text,to:text}),piece.text=text}}finally{if(saved.length){let names2=Array.from(new Set(saved.map((change)=>change.name))).join(", "),entry=record(element,names2,{kind:"attribute",stamp,changes:saved},last.file);afterSave({...last,changed:!0},"template",entry)}}}function interpolationSurface(value){let surface=div("");for(let part of value.split(INTERPOLATION)){if(!part)continue;surface.append(INTERPOLATION.test(part)?chip(part):field(part,!0))}if(!surface.querySelector(".editable"))surface.prepend(field("",!0));return{surface,read:()=>Array.from(surface.childNodes).map((node)=>node.classList?.contains("chip")?node.textContent:valueOf(node)).join("")}}async function editTranslation(element,key){let{locales}=await api("GET","/translation"+query({key:key.key})),entry=locales[key.locale];if(!entry?.editable||entry.value===null)throw Error(`${key.locale}.${key.key} isn't in a writable locale file (it may come from a gem).`);assertRendered(element,staticParts(entry.value));let main=interpolationSurface(entry.value),others=Object.entries(locales).filter(([locale])=>locale!==key.locale),otherRows=div("");otherRows.hidden=!0;let otherReaders=[];for(let[locale,other]of others)if(other.editable&&other.value!==null){let surface=interpolationSurface(other.value);otherReaders.push({locale,entry:other,read:surface.read}),otherRows.append(div("locale",h("span",{className:"code"},locale),surface.surface))}else otherRows.append(div("locale",h("span",{className:"code"},locale),h("em",{className:"ink-muted"},other.value===null?"missing":`${other.value} (not writable)`)));let toggle=others.length?h("button",{className:"link",type:"button",onclick:()=>{otherRows.hidden=!otherRows.hidden,toggle.textContent=otherRows.hidden?`Other locales (${others.length})`:"Hide other locales"}},`Other locales (${others.length})`):null,extra=toggle?[div("locale",h("span",{className:"code"},""),toggle),otherRows]:[];frame(element,main.surface,`${key.locale}.${key.key} · ${entry.file}:${entry.line}`,async()=>{let changes=[{locale:key.locale,entry,read:main.read},...otherReaders].flatMap(({locale,entry:entry2,read})=>{let to=read();return to===entry2.value?[]:[{locale,from:entry2.value,to,entry:entry2}]});await saveTranslations(element,key,changes,(change)=>{change.entry.value=change.to})},extra)}async function saveTranslations(element,key,changes,onSaved=()=>{}){let saved=[],result={};try{for(let change of changes){let reply=await api("POST","/translation",{locale:change.locale,key:key.key,original:change.from,text:change.to});if(showTranslation({locale:change.locale,key:key.key},change.from,change.to),onSaved(change),reply.changed)saved.push({locale:change.locale,from:change.from,to:change.to});result={...reply,file:result.file??reply.file,changed:result.changed||reply.changed}}}finally{let label=saved.length>1?`${key.key} in ${saved.length} locales`:key.key,entry=saved.length?record(element,label,{kind:"translation",key:key.key,changes:saved},result.file):void 0;if(saved.length)afterSave(result,"translation",entry)}}async function editMarkdown(element){let range=element.getAttribute(MARKDOWN),tag=element.tagName.toLowerCase(),info=await api("GET","/markdown"+query({range,tag}));if(!info.editable)throw Error("This Markdown block can only get notes.");let words=info.text.replace(/^\s*(?:[-*+]|\d{1,9}[.)])\s+(?:\[[ xX]\]\s+)?/gm,"").replace(/\]\([^)]*\)/g,"").replace(/[*_`#>\[\]]/g,"");assertRendered(element,words.split(`
371
380
  `).map((line)=>line.trim().split(/\s+/).slice(0,6).join(" ")).slice(0,8));let surface=div("");if(tag==="ul"||tag==="ol")surface.dataset.newlines="";if(info.prefix.trim())surface.append(chip(info.prefix.trim())," ");let text=field(info.text,!0);surface.append(text),frame(element,surface,`${info.file}:${info.range.split(":")[0]} (Markdown)`,async()=>{let value=valueOf(text);if(value===info.text)return;await saveMarkdown(element,range,info.original,info.prefix,value,info.text,tag)})}async function saveMarkdown(element,range,original,prefix,text,previous,tag){let result=await api("POST","/markdown",{range,original,text,tag});if(!tag?.match(/^[uo]l$/)&&!/[*_`\[\]<>#]/.test(previous+text))replaceText(Array.from(element.childNodes).filter((n)=>n.nodeType===Node.TEXT_NODE),previous,text);let entry=result.changed?record(element,"Markdown edit",{kind:"markdown",range:rangeAfter(range,prefix+text),prefix,from:previous,to:text,tag},result.file):void 0;afterSave(result,"markdown",entry)}function indexPieces(pieces){let index=0;for(let piece of pieces)if(piece.kind==="text")piece.index=index++}var staticParts=(value)=>value.split(INTERPOLATION).filter((part)=>part&&!INTERPOLATION.test(part));function attributeNode(element,name){let node=document.createElement("span");return node.textContent=element.getAttribute(name)??"",node}function afterSave(result,kind,entry){finish(result,kind,"Saved",entry?{Undo:()=>undo(entry)}:void 0)}var TAB=(()=>{try{let id=sessionStorage.getItem("tensaku-tab")??Math.random().toString(36).slice(2,10);return sessionStorage.setItem("tensaku-tab",id),id}catch{return Math.random().toString(36).slice(2,10)}})();function sendSelection(targets,text){api("POST","/selection",{url:location.pathname,tab:TAB,targets,text}).catch(()=>{})}var hoverBoxes=[],current3=null;function clearHover(){current3=null,hoverBoxes.forEach((b)=>b.remove()),hoverBoxes=[]}function label(element){let stamp=stampOf(element)??nearestStamp(element),md=element.getAttribute(MARKDOWN)?.match(/^(.+):(\d+):\d+-/),key=translationOf(element),where=key?`${key.locale}.${key.key}`:md?`${md[1]}:${md[2]}`:stamp?`${stamp.file}:${stamp.line}`:"";return[tagLabel(element),where]}function highlight(element,className=""){clearHover(),current3=element,hoverBoxes=box(documentRect(element),className,label(element))}var stamped=(element)=>Boolean(element&&!isUi(element)&&element!==document.body&&(element.hasAttribute(STAMP)||element.hasAttribute(MARKDOWN)));function step(element,key){if(key==="ArrowUp"){for(let node=element.parentElement;node&&node!==document.body;node=node.parentElement)if(stamped(node))return node;return null}if(key==="ArrowDown")return Array.from(element.querySelectorAll(`[${STAMP}], [${MARKDOWN}]`)).find((child)=>stamped(child)&&child.offsetParent!==null)??null;let parent=step(element,"ArrowUp")??document.body,siblings=Array.from(parent.querySelectorAll(`[${STAMP}], [${MARKDOWN}]`)).filter((node)=>stamped(node)&&step(node,"ArrowUp")===(parent===document.body?null:parent)),index=siblings.indexOf(element);return siblings[index+(key==="ArrowRight"?1:-1)]??null}function selectKey(event){if(mode()!=="inspect"||!current3||menu||isEditing()||activeInShadow()?.matches("textarea, input, [contenteditable]")||typingInPage())return!1;if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(event.key)&&!event.altKey&&!event.metaKey&&!event.ctrlKey){let next=step(current3,event.key);if(event.preventDefault(),!next)return!0;return highlight(next),next.scrollIntoView({block:"nearest"}),!0}if(event.key==="Enter")return event.preventDefault(),openMenu(current3),!0;if(event.key.toLowerCase()==="c"&&(event.metaKey||event.ctrlKey)&&!getSelection()?.toString())return event.preventDefault(),copy(reference(current3)).then(()=>toast("Copied reference")),!0;return!1}var picked=[],pickedBoxes=[],pickBar=null,hasPicked=()=>picked.length>0;function clearPicked(){picked=[],drawPicked()}function togglePicked(element){clearHover();let index=picked.indexOf(element);if(index>=0)picked.splice(index,1);else picked.push(element);drawPicked()}function pickedRect(){let rects=picked.map(documentRect),left=Math.min(...rects.map((r)=>r.left)),top=Math.min(...rects.map((r)=>r.top));return new DOMRect(left,top,Math.max(...rects.map((r)=>r.right))-left,Math.max(...rects.map((r)=>r.bottom))-top)}function notePicked(){if(!picked.length)return;let elements=picked,targets=elements.flatMap((element)=>targetsFor(element).slice(0,1));pickBar?.remove(),pickBar=null,noteForm(pickedRect(),targets,{},clearPicked,`${elements.length} ${elements.length===1?"element":"elements"}`)}function drawPicked(){if(pickedBoxes.forEach((b)=>b.remove()),pickBar?.remove(),pickBar=null,pickedBoxes=picked.flatMap((element,index)=>box(documentRect(element),"selected",[`${index+1} ${tagLabel(element)}`,""])),!picked.length)return;pickBar=panel(documentRect(picked[picked.length-1]),"menu pick",h("h3",{},`${picked.length} selected`,h("span",{className:"where"},"Shift-click to add or remove")),h("button",{type:"button",onclick:notePicked},icon("pad"),h("span",{},"Add note"),h("kbd",{},"N")),h("button",{type:"button",onclick:clearPicked},icon("close"),h("span",{},"Clear"),h("kbd",{},"Esc"))),pickBar.dataset.tensakuMenu=""}function pickKey(event){if(!pickBar||isEditing()||activeInShadow()?.matches("textarea"))return!1;if(event.key.toLowerCase()==="n"&&!event.metaKey&&!event.ctrlKey&&!event.altKey)return event.preventDefault(),notePicked(),!0;if(event.key==="Escape")return clearPicked(),!0;return!1}var menu=null,menuOpen=()=>menu!==null;function closeMenu(){if(menu?.remove(),menu=null,mode()==="off")clearHover()}function reference(element){let stamp=nearestStamp(element),lines=[`${meta().method} ${location.pathname}${location.search} → ${stamp?`${stamp.file}:${stamp.line}:${stamp.column}`:"(no source stamp)"}`],text=visibleText(element,200);lines.push(`<${tagLabel(element)}>${text?` "${text}"`:""}`);let key=translationOf(element);if(key)lines.push(`Translation: ${key.locale}.${key.key}`);let md=element.closest(`[${MARKDOWN}]`)?.getAttribute(MARKDOWN);if(md)lines.push(`Markdown: ${md}`);let context=contextOf(element);if(context.partials.length>1)lines.push(`Partials: ${context.partials.join(" < ")}`);if(context.controller)lines.push(`Stimulus: ${context.controller}`);if(context.frame)lines.push(`Turbo Frame: #${context.frame}`);let copies=copiesOf(element);if(copies>1)lines.push(`Rendered ${copies} times on this page (loop or repeated partial)`);return lines.join(`
372
381
  `)}var hasAttributes=(element)=>["alt","title","placeholder","aria-label"].some((name)=>element.hasAttribute(name));function openMenu(element,selectedText,at){closeMenu();let rect=documentRect(element),spot=at??rect,kind=editKind(element),item=(name,text,action2,shortcut)=>h("button",{type:"button",onclick:()=>{closeMenu(),action2()}},icon(name),h("span",{},text),shortcut?h("kbd",{},shortcut):null),undoable=undoFor(element),list=element.closest(`ul[${MARKDOWN}], ol[${MARKDOWN}]`),[tag,where]=label(element);menu=panel(spot,"menu",h("h3",{},tag,h("span",{className:"where"},where)),kind?item(kind==="attributes"?"tag":"pen",kind==="attributes"?"Edit attributes":"Edit text",()=>edit(element,kind),"E"):null,kind&&kind!=="attributes"&&hasAttributes(element)?item("tag","Edit attributes",()=>edit(element,"attributes")):null,list&&list!==element?item("pen","Edit the whole list",()=>edit(list,"markdown"),"L"):null,item("pad",selectedText?"Note on selected text":"Add note",()=>noteForm(rect,targetsFor(element,selectedText),{},void 0,void 0,spot),"N"),item("copy","Copy reference",async()=>{await copy(reference(element)),toast("Copied reference")},"C"),undoable?item("undo",`Undo ${undoable.label}`,()=>undo(undoable),"U"):null,item("code","Open in editor",()=>openInEditor(element),"O")),menu.dataset.tensakuMenu="",menu.addEventListener("keydown",(event)=>event.stopPropagation()),menu.querySelector("button")?.focus(),sendSelection(targetsFor(element,selectedText),visibleText(element,300))}function menuKey(event){if(!menu||event.key.length!==1||!"cneluo".includes(event.key.toLowerCase())||event.metaKey||event.ctrlKey||event.altKey)return;let match=Array.from(menu.querySelectorAll("button")).find((button)=>button.querySelector("kbd")?.textContent===event.key.toUpperCase());if(match)event.preventDefault(),match.click()}async function openInEditor(element){let md=element.closest(`[${MARKDOWN}]`)?.getAttribute(MARKDOWN)?.match(/^(.+):(\d+):\d+-/),stamp=nearestStamp(element),[file,line]=md&&(!stamp||element.closest(`[${STAMP}]`)?.contains(element.closest(`[${MARKDOWN}]`)))?[md[1],md[2]]:stamp?[stamp.file,String(stamp.line)]:[];if(!file)return toast("This element has no source position.",{error:!0});try{let{url}=await api("GET","/editor"+query({file,line}));if(url)location.href=url;else toast(`Set RAILS_EDITOR (vscode, cursor, zed, …) to open files from here. ${file}:${line}`,{timeout:8000})}catch(error){toast(error.message,{error:!0})}}var EDITABLE_BATCH=5000,outlines=[],asking=!1;function editableElements(){let elements=new Set;return document.body.querySelectorAll(`[${STAMP}], [${MARKDOWN}], *`).forEach((element)=>{if(isUi(element)||!element.offsetParent&&getComputedStyle(element).position!=="fixed")return;if(editKind(element))elements.add(element)}),Array.from(elements)}function drawOutlines(){if(outlines.forEach((b)=>b.remove()),outlines=[],mode()!=="edit")return;let elements=editableElements(),unknown=Array.from(new Set(elements.filter((element)=>element.hasAttribute(STAMP)&&hasOwnText(element)).map((element)=>element.getAttribute(STAMP)).filter((stamp)=>!templateText.has(stamp)))).slice(0,EDITABLE_BATCH);if(unknown.length){if(asking)return;asking=!0,api("POST","/editable",{stamps:unknown}).then(({editable})=>unknown.forEach((stamp)=>templateText.set(stamp,editable[stamp]??!1))).catch(()=>unknown.forEach((stamp)=>templateText.set(stamp,!0))).finally(()=>{asking=!1,drawOutlines()});return}for(let element of elements)outlines.push(...box(documentRect(element),"edit"))}var pending=[];function onDocument(type,listener,options){pending.push(()=>document.addEventListener(type,listener,options))}function onWindow(type,listener){pending.push(()=>addEventListener(type,listener))}onMode((next)=>{if(next!=="inspect"&&hasPicked())clearPicked();clearHover(),closeMenu(),drawOutlines(),syncCursor()});function syncCursor(){document.documentElement.style.cursor=altHeld||mode()==="inspect"?cursor("highlighter",INK.highlighter):mode()==="edit"?cursor("pen",INK.pen):""}var altHeld=!1,pointer=null,altPreviews=(event)=>event.altKey&&!event.metaKey&&!event.ctrlKey&&!isEditing()&&!typingInPage()&&!activeInShadow()?.matches("textarea, input");function setAltHeld(held){if(held===altHeld)return;if(altHeld=held,syncCursor(),!held){if(mode()!=="inspect")clearHover();return}let under=pointer&&!menuOpen()?document.elementFromPoint(pointer.x,pointer.y):null,element=under&&!isUi(under)?sourceElement(under):null;if(element)highlight(element)}var drag=null,suppressClick=!1;function pageTarget(event){let target=event.composedPath()[0];if(isUi(target)||target instanceof Node&&isUi(target.parentElement))return null;return sourceElement(target)}onDocument("mousemove",(event)=>{if(drag)return updateDrag(event);if(pointer={x:event.clientX,y:event.clientY},setAltHeld(altPreviews(event)),mode()==="off"&&!altHeld||menuOpen()||isEditing())return;let element=pageTarget(event);if(!element)return clearHover();let editing=mode()==="edit"&&!altHeld;if(editing&&!editKind(element))return clearHover();highlight(element,editing?"hover-edit":"")},!0);onDocument("mousedown",(event)=>{if(event.button!==0||isUi(event.target))return;let altDrag=event.altKey;if(altDrag)event.preventDefault();if(mode()!=="inspect"&&!altDrag||menuOpen()||isEditing())return;if(event.shiftKey){event.preventDefault();return}drag={x:event.pageX,y:event.pageY,area:null}},!0);function updateDrag(event){if(!drag)return;let width=Math.abs(event.pageX-drag.x),height=Math.abs(event.pageY-drag.y);if(!drag.area&&Math.hypot(width,height)<8)return;if(!drag.area)clearHover(),drag.area=div("area"),layer.append(drag.area);Object.assign(drag.area.style,{left:`${Math.min(event.pageX,drag.x)}px`,top:`${Math.min(event.pageY,drag.y)}px`,width:`${width}px`,height:`${height}px`}),event.preventDefault()}onDocument("mouseup",(event)=>{if(!drag)return;let area=drag.area,start=drag;if(drag=null,!area)return;suppressClick=!0;let rect=new DOMRect(Math.min(event.pageX,start.x),Math.min(event.pageY,start.y),Math.abs(event.pageX-start.x),Math.abs(event.pageY-start.y)),elements=elementsInArea(rect),highlights=elements.flatMap((element)=>box(documentRect(element),"selected")),targets=elements.flatMap((element)=>targetsFor(element).slice(0,1));noteForm(rect,targets,{rect:{x:Math.round(rect.x),y:Math.round(rect.y),width:Math.round(rect.width),height:Math.round(rect.height)}},()=>{area.remove(),highlights.forEach((b)=>b.remove())},void 0,new DOMRect(event.pageX,event.pageY,0,0)),sendSelection(targets,"")},!0);onDocument("click",(event)=>{if(suppressClick){suppressClick=!1,event.preventDefault(),event.stopPropagation();return}if(isUi(event.target))return;let element=pageTarget(event),at=new DOMRect(event.pageX,event.pageY,0,0),selectedIn=(within)=>{let selection=getSelection()?.toString().trim();return selection&&within.contains(getSelection().anchorNode)?selection:void 0};if(event.altKey&&element){if(event.preventDefault(),event.stopImmediatePropagation(),closeMenu(),event.shiftKey)noteForm(documentRect(element),targetsFor(element,selectedIn(element)),{},void 0,void 0,at);else openMenu(element,selectedIn(element),at);return}if(mode()==="off"&&!menuOpen())return;if(event.preventDefault(),event.stopImmediatePropagation(),menuOpen()||isEditing()){closeMenu();return}if(!element)return;if(mode()==="edit"){let kind=editKind(element);if(kind)edit(element,kind);return}if(event.shiftKey){togglePicked(element);return}if(hasPicked())clearPicked();openMenu(element,selectedIn(element),at)},!0);onDocument("pointerdown",closeOutside,!0);function undoKeys(event){if(!(isApple?event.metaKey:event.ctrlKey)||event.altKey||isEditing()||typingInPage()||activeInShadow()?.matches("textarea, input, [contenteditable]"))return!1;let key=event.key.toLowerCase(),wantsRedo=key==="z"&&event.shiftKey||!isApple&&key==="y";if(key==="z"&&!event.shiftKey&&canUndo())return event.preventDefault(),undo(),!0;if(wantsRedo&&canRedo())return event.preventDefault(),redo(),!0;return!1}onDocument("keydown",(event)=>{if(event.key==="Alt")setAltHeld(altPreviews(event));let shortcut=hasCommandModifier(event)?toolForEvent(event):null;if(shortcut){event.preventDefault(),pressShortcut(shortcut);return}if(undoKeys(event))return;if(menuKey(event),selectKey(event))return;if(pickKey(event))return;if(event.key==="Escape")escape()},!0);function escape(){if(isEditing()||typingInPage())return;let field2=activeInShadow();if(field2?.matches("textarea, input, [contenteditable]")){field2.blur();return}if(popoverOpen())closePopover();else if(menuOpen())closeMenu();else if(closeNote()||closeSidePanel())return;else if(mode()!=="off")setMode("off");else closeToolbar()}onDocument("keyup",(event)=>{if(event.key==="Alt")setAltHeld(!1)},!0);onWindow("blur",()=>setAltHeld(!1));var redraw=0;function scheduleRedraw(){cancelAnimationFrame(redraw),redraw=requestAnimationFrame(()=>{if(drawPins(),drawOutlines(),hasPicked())drawPicked()})}onWindow("resize",()=>{placeDock(),scheduleRedraw()});var path=location.pathname;function pageChanged(){path=location.pathname,closeMenu(),clearPicked(),closeEditor(),clearHover(),load(),scheduleRedraw()}onDocument("turbo:load",pageChanged);onDocument("turbo:frame-load",scheduleRedraw);onWindow("popstate",pageChanged);pending.push(()=>onRefresh(()=>{templateText.clear(),scheduleRedraw(),load()}));pending.push(()=>setInterval(()=>{if(location.pathname!==path)pageChanged();else drawPins()},1000));onDocument("scroll",(event)=>{if(event.target!==document&&!isUi(event.target))scheduleRedraw()},{capture:!0,passive:!0});function boot(){if(window.__tensaku)return;window.__tensaku=!0,pending.forEach((add)=>add()),watch(),mount(),placeDock(),load(),poll(),syncPins(),new MutationObserver(()=>mount()).observe(document.documentElement,{childList:!0})}boot();})();
@@ -0,0 +1,30 @@
1
+ module Tensaku
2
+ # Notices an agent's edits to the app's files, so the page can show each one as it lands instead of
3
+ # waiting for the agent to resolve its note. The dev server only looks while a note is being worked
4
+ # on (Notes.working?), and then compares a stamp of the files under DIRS a few times a second.
5
+ # Builds of a CSS or JS watcher land in app/assets/builds, so they count as edits too.
6
+ module Edits
7
+ DIRS = %w[app config/locales].freeze
8
+
9
+ # Several open tabs share one look at the files.
10
+ FRESH = 0.2
11
+ LOCK = Mutex.new
12
+
13
+ module_function
14
+
15
+ # The number of files and the sum of their modification times: a change to any file, or a file
16
+ # added or deleted, changes it.
17
+ def stamp(root = Tensaku.root)
18
+ LOCK.synchronize do
19
+ now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
20
+ return @stamp if @stamp && @root == root && now - @at < FRESH
21
+
22
+ files = DIRS.flat_map { Dir.glob(File.join(root.to_s, it, "**", "*")) }
23
+ newest = files.sum(0.0) { File.mtime(it).to_f rescue 0.0 }
24
+ @root = root
25
+ @at = now
26
+ @stamp = [ files.size, newest ]
27
+ end
28
+ end
29
+ end
30
+ end
@@ -15,6 +15,9 @@ module Tensaku
15
15
  # checking in, and to write a comment so a closed tab is noticed.
16
16
  STREAM_CHECK = 10
17
17
 
18
+ # While an agent works on a note, the stream also looks at the app's files this often (Edits).
19
+ EDIT_CHECK = 0.25
20
+
18
21
  # /notes/ID and /notes/ID/screenshot.
19
22
  NOTE_PATH = %r{\A/notes/([a-z0-9]+)(?:/screenshot)?\z}
20
23
 
@@ -122,9 +125,10 @@ module Tensaku
122
125
  end
123
126
  end
124
127
 
125
- # Server-sent events: one "changed" event whenever the notes or the agents change (Project.version),
128
+ # Server-sent events: a "changed" event whenever the notes or the agents change (Project.version),
126
129
  # and one right away, so the page loads the notes when told instead of asking every few seconds.
127
- # The stream sleeps on the doorbell until a write rings it.
130
+ # While an agent works on a note, an "edited" event whenever the app's files change (Edits), so the
131
+ # page shows each edit as it lands. The stream sleeps on the doorbell until a write rings it.
128
132
  # The connection is taken over from the web server (Rack hijack) and served from a thread of its
129
133
  # own, so an open tab doesn't hold one of the server's threads. A server without hijack answers
130
134
  # 501, and the page polls instead.
@@ -142,13 +146,24 @@ module Tensaku
142
146
  def stream(io)
143
147
  Doorbell.listen(Tensaku.root) do |doorbell|
144
148
  io.write("HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ncache-control: no-store\r\nconnection: close\r\n\r\n")
145
- last = nil
149
+ last = files = nil
150
+ quiet = 0.0
146
151
  loop do
147
152
  version = Project.version
148
- io.write(version == last ? ": ping\n\n" : "data: changed\n\n")
149
- io.flush
150
- last = version
151
- doorbell.wait(STREAM_CHECK)
153
+ stamp = Edits.stamp if Notes.working?
154
+ events = []
155
+ events << "data: changed\n\n" if version != last
156
+ events << "data: edited\n\n" if stamp && files && stamp != files
157
+ # A comment now and then, so a closed tab is noticed.
158
+ events << ": ping\n\n" if events.empty? && quiet >= STREAM_CHECK
159
+ if events.any?
160
+ io.write(events.join)
161
+ io.flush
162
+ quiet = 0.0
163
+ end
164
+ last, files = version, stamp
165
+ wait = stamp ? EDIT_CHECK : STREAM_CHECK
166
+ quiet += wait unless doorbell.wait(wait)
152
167
  end
153
168
  end
154
169
  rescue IOError, SystemCallError
data/lib/tensaku/mcp.rb CHANGED
@@ -13,9 +13,9 @@ module Tensaku
13
13
  class Mcp
14
14
  PROTOCOL_VERSIONS = %w[2025-11-25 2025-06-18 2025-03-26 2024-11-05].freeze
15
15
 
16
- CHANNEL_INSTRUCTIONS = " This server may also be a Claude Code channel. Its events arrive as <channel source=\"tensaku\"> messages. The first one asks you to call channel_ready with a code: do that, then tell the person in one line that Tensaku notes now arrive in this chat. Each later event holds notes the person saved on the page, already yours: work through them like notes from watch_notes. There's no need to call watch_notes while the channel works."
16
+ CHANNEL_INSTRUCTIONS = " This server may also be a Claude Code channel. Its events arrive as <channel source=\"tensaku\"> messages. The first one asks you to call channel_ready with a code: do that, then tell the person in one line that Tensaku notes now arrive in this chat, and end your turn. Each later event holds notes the person saved on the page, already yours and started: work through them like notes from watch_notes. There's no need to call watch_notes while the channel works."
17
17
 
18
- INSTRUCTIONS = "Tensaku notes are comments a person left on pages of this Rails app, each with the file and line that rendered the element. Work through open notes one at a time: start_note, make the change, then resolve_note with a one-line reply before the next note, so the page shows progress as it happens. Ask a question when a note is unclear, and decline_note when the change shouldn't be made. When the person asks you to watch or listen for notes, call watch_notes in a loop, and tell them the session name its first answer gives you (such as amber-fox), which the page shows next to your name. A note belongs to the session the person assigned it to, was handed it or started it: call start_note before you change anything for a note, and leave notes another session owns. A note with a screenshot says so; get_screenshot returns it. Once you have called watch_notes, notes sent while you work come with the answer of whichever Tensaku tool you call next, already yours: work through them, and call watch_notes again only when you have nothing else to do."
18
+ INSTRUCTIONS = "Tensaku notes are comments a person left on pages of this Rails app. Each note names the absolute path and line of the file that rendered what it points at: open that file directly, without searching for it. Work through open notes one at a time: make the change, then resolve_note with a one-line reply before the next note, so the page shows progress as it happens. While you work on a note, the page reloads itself whenever you save a file, so the person sees each edit as it lands. Check your work as far as the change needs: a small, clear change (a word, a class, a color) can be resolved right after the edit. Notes handed to you by watch_notes, a channel event or another tool's answer are already started; for a note you found with list_notes, call start_note first, in the same turn as you read the file. A list already has each note's whole text, so get_note isn't needed for a note you listed, and the answer of resolve_note, decline_note and ask_question says how many open notes are left, so don't list again to find out. Ask a question when a note is unclear, and decline_note when the change shouldn't be made. When the person asks you to watch or listen for notes, call watch_notes in a loop, and tell them the session name its first answer gives you (such as amber-fox), which the page shows next to your name. A note belongs to the session the person assigned it to, was handed it or started it: leave notes another session owns. A note with a screenshot says so; get_screenshot returns it. Once you have called watch_notes, notes sent while you work come with the answer of whichever Tensaku tool you call next, already yours: work through them, and call watch_notes again only when you have nothing else to do."
19
19
 
20
20
  # Claude Code registers its channel listener a moment after initialization, and drops what comes
21
21
  # before it (seen in its debug log), so the hello waits, and is sent once more until answered.
@@ -6,13 +6,14 @@ module Tensaku
6
6
 
7
7
  # app names the app in each heading, for an agent that sees notes from several apps. With
8
8
  # latest: true each thread is cut down to what is new (see latest_thread). session, the agent
9
- # session the list is for, adds whether each note is its own.
10
- def list(notes, app: nil, latest: false, session: nil)
9
+ # session the list is for, adds whether each note is its own. absolute: true gives file paths from
10
+ # the filesystem root, which an agent can open without looking for the app first.
11
+ def list(notes, app: nil, latest: false, session: nil, absolute: false)
11
12
  notes = Array(notes)
12
13
  return "No notes." if notes.empty?
13
14
 
14
15
  base = Project.base_url
15
- notes.map { note(it, base:, app:, latest:, session:) }.join("\n\n")
16
+ notes.map { note(it, base:, app:, latest:, session:, absolute:) }.join("\n\n")
16
17
  end
17
18
 
18
19
  # One line per note, for a chat where the detailed form is too long.
@@ -26,11 +27,12 @@ module Tensaku
26
27
  end.join("\n")
27
28
  end
28
29
 
29
- def note(note, base: Project.base_url, app: nil, latest: false, session: nil)
30
+ def note(note, base: Project.base_url, app: nil, latest: false, session: nil, absolute: false)
30
31
  page = base && note["url"].to_s.start_with?("/") ? "#{base.chomp("/")}#{note["url"]}" : note["url"]
31
32
  lines = [ "## Tensaku note #{note["id"]} (#{note["status"]}) on #{page}#{" in #{app}" if app}", "" ]
32
33
  if session && ACTIVE.include?(note["status"])
33
- lines << if note["session"] == session then "*Yours.*"
34
+ lines << if note["session"] == session && note["status"] == "working" then "*Yours, and started: make the change, then resolve it.*"
35
+ elsif note["session"] == session then "*Yours. Call start_note before you change anything.*"
34
36
  elsif note["stopped"] then "*Its session stopped while working on it, so it is nobody's now. Part of the change may already be made: check the file before you redo it. Call start_note to take it.*"
35
37
  else "*Nobody's yet: call start_note before you work on it, so no other session takes it.*"
36
38
  end
@@ -40,7 +42,7 @@ module Tensaku
40
42
  targets = Array(note["targets"])
41
43
  if targets.any?
42
44
  lines << ""
43
- targets.each { lines << "- #{target(it)}" }
45
+ targets.each { lines << "- #{target(it, absolute:)}" }
44
46
  end
45
47
  if (rect = note["rect"])
46
48
  lines << "" << "Area: #{rect["width"]}x#{rect["height"]} at (#{rect["x"]}, #{rect["y"]}) in a #{note["viewport"] || "unknown"} viewport"
@@ -66,8 +68,9 @@ module Tensaku
66
68
  [ thread.size - kept.size, kept ]
67
69
  end
68
70
 
69
- def target(target)
70
- location = [ target["file"], target["range"] ].compact.join(":")
71
+ def target(target, absolute: false)
72
+ file = target["file"] && absolute ? Tensaku.root.expand_path.join(target["file"]).to_s : target["file"]
73
+ location = [ file, target["range"] ].compact.join(":")
71
74
  parts = [ target["kind"] ]
72
75
  parts << "`#{target["tag"]}`" if target["tag"]
73
76
  parts << "`#{target["key"]}` (#{target["locale"]})" if target["key"]
data/lib/tensaku/notes.rb CHANGED
@@ -61,6 +61,11 @@ module Tensaku
61
61
  end
62
62
  end
63
63
 
64
+ # Whether an agent is working on a note in this app, so its edits are worth watching for (Edits).
65
+ def working?
66
+ Project.read { |db, app| db.get_first_value("SELECT 1 FROM notes WHERE project = ? AND archived_at IS NULL AND status = 'working' LIMIT 1", [ app ]) }.present?
67
+ end
68
+
64
69
  def find(id)
65
70
  id = text(id)
66
71
  raise NotFound, "No note #{id.inspect}" unless id.match?(ID)
@@ -251,8 +256,10 @@ module Tensaku
251
256
  end
252
257
 
253
258
  # sent_between, and the notes found become session's in the same transaction: delivered_at and
254
- # delivered_to say they arrived. Two sessions scanning at once can't both get a note. updated_at and
255
- # sent_at stay: delivery isn't a change the person or the agent made.
259
+ # delivered_to say they arrived. Two sessions scanning at once can't both get a note. A note handed
260
+ # over is started (working) for that session, so the page shows the agent on it at once and the agent
261
+ # doesn't spend a turn on start_note. updated_at and sent_at stay: delivery isn't a change the person
262
+ # or the agent made.
256
263
  #
257
264
  # A session busy with a note leaves new ones to a listening session that has nothing to do, except
258
265
  # the notes the person sent to it.
@@ -267,7 +274,7 @@ module Tensaku
267
274
  # background, or with the answer of another call.
268
275
  next if note["session"] == session && note["delivered_at"].to_s >= note["sent_at"].to_s
269
276
 
270
- save(db, app, note.merge("session" => session, "agent" => note["session"] == session ? note["agent"] || agent : agent, "delivered_at" => now, "delivered_to" => agent))
277
+ save(db, app, note.merge("status" => "working", "session" => session, "agent" => note["session"] == session ? note["agent"] || agent : agent, "delivered_at" => now, "delivered_to" => agent))
271
278
  end
272
279
  end
273
280
  end
@@ -10,6 +10,10 @@ module Tensaku
10
10
  module Tools
11
11
  BY_ID = { type: "object", properties: { id: { type: "string" } }, required: %w[id] }.freeze
12
12
 
13
+ # The tools of the work loop. Claude Code loads these up front instead of behind its tool search,
14
+ # which saves the agent a turn before its first Tensaku call.
15
+ ALWAYS_LOAD = %w[list_notes start_note resolve_note decline_note ask_question watch_notes channel_ready].freeze
16
+
13
17
  TOOLS = [
14
18
  {
15
19
  name: "list_notes",
@@ -34,12 +38,12 @@ module Tensaku
34
38
  },
35
39
  {
36
40
  name: "start_note",
37
- description: "Mark a note as being worked on before you make the change. The pin on the page shows that an agent has picked it up, and the note becomes this session's. Fails when the note belongs to another running agent session: then leave it. Call resolve_note as soon as the change is made.",
41
+ description: "Mark a note you found with list_notes as being worked on before you make the change. The pin on the page shows that an agent has picked it up, and the note becomes this session's. Notes handed to you (by watch_notes, a channel event or another tool's answer) are already started, so skip this for them. Fails when the note belongs to another running agent session: then leave it. Call resolve_note as soon as the change is made.",
38
42
  inputSchema: BY_ID
39
43
  },
40
44
  {
41
45
  name: "resolve_note",
42
- description: "Mark a note resolved as soon as its change is made, before starting the next note. Only a note you started with start_note can be resolved. The person is watching the page, so don't save these up for the end. The reply is shown next to a green pin: say in one line what changed and where (for example: changed the heading in app/views/pages/_hero.html.erb:4).",
46
+ description: "Mark a note resolved as soon as its change is made, before starting the next note. Only a note that is started for you (by start_note, or handed to you) can be resolved. The person is watching the page, so don't save these up for the end. The reply is shown next to a green pin: say in one line what changed and where (for example: changed the heading in app/views/pages/_hero.html.erb:4).",
43
47
  inputSchema: { type: "object", properties: { id: { type: "string" }, reply: { type: "string" } }, required: %w[id reply] }
44
48
  },
45
49
  {
@@ -78,10 +82,13 @@ module Tensaku
78
82
  description: "What the person last selected in the Tensaku overlay (elements with file and line), for questions like 'what is this?'.",
79
83
  inputSchema: { type: "object", properties: {} }
80
84
  }
81
- ].freeze
85
+ ].map { ALWAYS_LOAD.include?(it[:name]) ? it.merge(_meta: { "anthropic/alwaysLoad": true }) : it }.freeze
82
86
 
83
87
  NAMES = TOOLS.map { it[:name] }.freeze
84
88
 
89
+ # Tools that close or pause a note. Their answer ends with how many open notes are left (Session#call).
90
+ CLOSING = %w[resolve_note decline_note ask_question].freeze
91
+
85
92
  private
86
93
 
87
94
  # Lists this session's notes. Notes another running session owns are left out and counted.
@@ -100,7 +107,7 @@ module Tensaku
100
107
 
101
108
  def get_note(arguments)
102
109
  app, note = Notes.locate(apps, arguments["id"])
103
- result(Tensaku.with_root(app) { Notes::Markdown.note(note, app: app_label(app)) })
110
+ result(Tensaku.with_root(app) { Notes::Markdown.note(note, app: app_label(app), absolute: true) })
104
111
  end
105
112
 
106
113
  def get_screenshot(arguments)
@@ -117,7 +124,7 @@ module Tensaku
117
124
 
118
125
  def resolve_note(arguments)
119
126
  note = change(arguments["id"], status: "resolved", message: arguments["reply"], started: true)
120
- result("Resolved note #{note["id"]}.#{" Call watch_notes to keep listening." if @watched && !@channel}")
127
+ result("Resolved note #{note["id"]}.")
121
128
  end
122
129
 
123
130
  def decline_note(arguments)
@@ -152,7 +159,7 @@ module Tensaku
152
159
 
153
160
  start_channel
154
161
  waiting = per_app { Notes.list(status: Notes::ACTIVE, session: id).size }.sum(&:last)
155
- result("Tensaku's channel works. Notes the person saves on the page arrive in this chat as #{label}, already yours. Tell the person in one line#{", and that #{waiting} earlier #{waiting == 1 ? "note is" : "notes are"} open (list_notes has them), without starting on them unless they ask" if waiting.positive?}.")
162
+ result("Tensaku's channel works. Notes the person saves on the page arrive in this chat as #{label}, already yours. Tell the person in one line#{", and that #{waiting} earlier #{waiting == 1 ? "note is" : "notes are"} open (list_notes has them), without starting on them unless they ask" if waiting.positive?}, then end your turn. Each note arrives here as a new message, so there is nothing to look for or prepare until then.")
156
163
  end
157
164
 
158
165
  def current_selection(_arguments)
@@ -95,6 +95,7 @@ module Tensaku
95
95
  seen!
96
96
  result = run(name, arguments)
97
97
  handed = result.delete(:handed) || (news(result) unless result[:isError] || %w[list_notes watch_notes].include?(name))
98
+ result[:content].first[:text] += " #{left(except: Array(handed))}" if Tools::CLOSING.include?(name.to_s) && !result[:isError]
98
99
  log(name, started, result, handed)
99
100
  result
100
101
  end
@@ -112,12 +113,22 @@ module Tensaku
112
113
  result("Tensaku hit an error: #{error.class}: #{error.message}", error: true)
113
114
  end
114
115
 
116
+ # How many open notes this session may take, besides those handed over in this answer, so an agent
117
+ # that closed a note knows whether to list again without a call to find out.
118
+ def left(except: [])
119
+ open = per_app { Notes.list(status: "open", session: id).map { it["id"] } }.flat_map(&:last) - except
120
+ other = "other " if except.any?
121
+ return "#{open.size} #{other}open #{open.size == 1 ? "note is" : "notes are"} left: list_notes has #{open.size == 1 ? "it" : "them"}." if open.any?
122
+
123
+ "No #{other}open notes left.#{" Call watch_notes to keep listening." if @watched && !@channel && except.empty?}"
124
+ end
125
+
115
126
  def news(result)
116
127
  if @watched
117
128
  found = claim_since(@checked_at)
118
129
  return [] if found.empty?
119
130
 
120
- result[:content] << { type: "text", text: "Notes the person saved while you worked. They are yours now; work through them next:\n\n#{notes_markdown(found)}" }
131
+ result[:content] << { type: "text", text: "Notes the person saved while you worked. They are yours and already started; work through them next:\n\n#{notes_markdown(found)}" }
121
132
  ids(found)
122
133
  else
123
134
  now = Time.now.utc
@@ -192,7 +203,7 @@ module Tensaku
192
203
  loop do
193
204
  found = claim_since(@checked_at)
194
205
  if found.any?
195
- @push.call("Notes the person saved on the page. They are yours: work through them one at a time with start_note and resolve_note.\n\n#{notes_markdown(found)}", kind: "notes", notes: ids(found).join(" "))
206
+ @push.call("Notes the person saved on the page. They are yours and already started: work through them one at a time, resolving each as soon as its change is made.\n\n#{notes_markdown(found)}", kind: "notes", notes: ids(found).join(" "))
196
207
  log("channel", Process.clock_gettime(Process::CLOCK_MONOTONIC), { content: [] }, ids(found))
197
208
  end
198
209
  doorbell.wait(RECHECK)
@@ -247,7 +258,7 @@ module Tensaku
247
258
  # Notes from several apps ([[app, notes], ...]) as one Markdown text, or "" when there are none.
248
259
  def notes_markdown(found)
249
260
  found.filter_map do |app, notes|
250
- Tensaku.with_root(app) { Notes::Markdown.list(notes, app: app_label(app), latest: true, session: id) } if notes.any?
261
+ Tensaku.with_root(app) { Notes::Markdown.list(notes, app: app_label(app), latest: true, session: id, absolute: true) } if notes.any?
251
262
  end.join("\n\n")
252
263
  end
253
264
 
@@ -1,3 +1,3 @@
1
1
  module Tensaku
2
- VERSION = "0.2.0"
2
+ VERSION = "0.2.2"
3
3
  end
data/lib/tensaku.rb CHANGED
@@ -21,6 +21,7 @@ module Tensaku
21
21
  autoload :Build, "tensaku/build"
22
22
  autoload :Mcp, "tensaku/mcp"
23
23
  autoload :Caches, "tensaku/caches"
24
+ autoload :Edits, "tensaku/edits"
24
25
  autoload :I18nMarkers, "tensaku/i18n"
25
26
 
26
27
  module Source
@@ -58,11 +58,15 @@ A note looks like this:
58
58
 
59
59
  1. List the open notes (`list_notes`, or `tensaku notes`). Each is marked *Yours* or *Nobody's yet*;
60
60
  notes other sessions hold aren't listed.
61
- 2. Call `start_note` on the note you take, before you change anything, so the person sees it's being
62
- worked on and no other session takes it. If it fails, leave that note. `resolve_note` refuses a
63
- note you didn't start, and a note the person took back from you. A note marked as stopped was
61
+ 2. Call `start_note` on a note you took from `list_notes`, before you change anything, so the person
62
+ sees it's being worked on and no other session takes it. If it fails, leave that note. Notes handed
63
+ to you by `watch_notes`, a channel event or another tool's answer are already started: skip
64
+ `start_note` for them. `resolve_note` refuses a note that isn't started for you, and a note the
65
+ person took back from you. A note marked as stopped was
64
66
  started by a session that ended: part of its change may already be in the file. Then open the
65
- target file at the range, read the comment, and make the change. Look at
67
+ target file at the range, read the comment, and make the change. Notes from the MCP tools and
68
+ `tensaku notes` give the file's absolute path, so open it directly instead of searching for it, and
69
+ read it in the same turn as `start_note` when you need one. Look at
66
70
  `context.partials` when the fix belongs in a parent template, and at the translation target when the
67
71
  text comes from a locale file (change every locale that needs it).
68
72
  3. Read the note's `thread`: the person's answers to earlier questions are there. Use `reply_to_note`
@@ -81,7 +85,9 @@ amber-fox): the page shows it next to your name.
81
85
  Take the notes one at a time, and resolve each before you start the next. The person is watching the page,
82
86
  so don't make every change first and update the notes at the end. These calls are small: `start_note` and
83
87
  `resolve_note` answer with one line. `list_notes` already has each note's text, so don't call
84
- `get_note` after it, unless a thread says earlier messages were left out and you need them.
88
+ `get_note` after it, unless a thread says earlier messages were left out and you need them. The answer
89
+ of `resolve_note`, `decline_note` and `ask_question` says how many open notes are left, so don't list
90
+ again to find out.
85
91
 
86
92
  In Claude Code, Tensaku may arrive as a channel: a `<channel source="tensaku">` message asks you to
87
93
  call `channel_ready` with a code, and later ones hold notes the person saved, already yours. Work
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: tensaku
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.0
4
+ version: 0.2.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - David Afonso
@@ -114,6 +114,7 @@ files:
114
114
  - lib/tensaku/caches.rb
115
115
  - lib/tensaku/cli.rb
116
116
  - lib/tensaku/doorbell.rb
117
+ - lib/tensaku/edits.rb
117
118
  - lib/tensaku/endpoints.rb
118
119
  - lib/tensaku/file_write.rb
119
120
  - lib/tensaku/guard.rb
@@ -161,5 +162,5 @@ required_rubygems_version: !ruby/object:Gem::Requirement
161
162
  requirements: []
162
163
  rubygems_version: 4.0.20
163
164
  specification_version: 4
164
- summary: Fix your Rails app without leaving the browser.
165
+ summary: Fix your Rails app in the browser.
165
166
  test_files: []