Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion agents/conductors/batch/_batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -2165,6 +2165,10 @@ def _organ(d: dict) -> dict:


def _members_js(d: dict) -> str:
# Packet pages are standalone and do not embed the family click handler.
sys.path.insert(0, str(BRAIN / "board"))
from _theme import PROMPT_GUARD_JS

members = [{"id": s["id"], "slug": s["slug"], "health": s["health"],
"reviewable": s.get("reviewable", True)}
for s in d["members"]]
Expand All @@ -2186,7 +2190,7 @@ def _members_js(d: dict) -> str:
("%%DEFAULT_DECISION%%", organ["default_decision"]),
("%%GITHUB_NEW%%", (f"{home}/new/main" if home else ""))):
js = js.replace(token, value)
return "<script>\n" + js + "</script>"
return "<script>\n" + PROMPT_GUARD_JS + js + "</script>"


def _callout(d: dict) -> str:
Expand Down
1 change: 1 addition & 0 deletions agents/conductors/batch/packet.js
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,7 @@

if (copyBtn) {
copyBtn.addEventListener("click", function () {
if (!guardPrompt(currentMd, copyBtn)) return;
var done = function () { flash(copyBtn, "Copied ✓"); };
var fallback = function () {
try {
Expand Down
48 changes: 42 additions & 6 deletions board/_theme.py
Original file line number Diff line number Diff line change
Expand Up @@ -806,20 +806,56 @@ def boards_footer(links, current):
f'Boards:</li>{chips}</ul>') if chips else ""


# A conservative product budget, not a provider's changing transport limit.
MAX_PROMPT_CHARS = 50_000

# Also embedded by standalone batch packets. Eyes mirrors the ceiling because
# its renderer intentionally works without a Brain checkout.
PROMPT_GUARD_JS = """\
const MAX_PROMPT_CHARS = __MAX_PROMPT_CHARS__;
function promptFits(text){
let count=0;for(const character of text){if(++count>MAX_PROMPT_CHARS)return false;}
return true;
}
function guardPrompt(text, button){
let status=document.getElementById('prompt-budget-status');
if(promptFits(text)){
if(status){if(status.dataset.url)URL.revokeObjectURL(status.dataset.url);status.remove();}
return true;
}
if(!status){status=document.createElement('p');status.id='prompt-budget-status';
status.setAttribute('role','status');status.setAttribute('aria-live','polite');
button.insertAdjacentElement('afterend',status);}
if(status.dataset.url)URL.revokeObjectURL(status.dataset.url);
status.textContent='Not copied: this request exceeds the 50,000-character budget. '+
'Download the complete request and attach the file to your coding chat. Nothing was cut off. ';
const link=document.createElement('a');
link.href=URL.createObjectURL(new Blob([text],{type:'text/plain;charset=utf-8'}));
status.dataset.url=link.href;link.download='dashboard-request.txt';
link.textContent='Download complete request';status.appendChild(link);
return false;
}
""".replace("__MAX_PROMPT_CHARS__", str(MAX_PROMPT_CHARS))

# Shared by every board: one tap on a payload button copies it and flashes ✓.
# The textarea path covers browsers without the async clipboard API.
JS = """\
JS = PROMPT_GUARD_JS + """\
async function copyCmd(b){
const cmd=b.dataset.cmd;
try{await navigator.clipboard.writeText(cmd);}
if(!guardPrompt(cmd,b))return;
let copied=false;
try{await navigator.clipboard.writeText(cmd);copied=true;}
catch(e){const t=document.createElement("textarea");t.value=cmd;
document.body.appendChild(t);t.select();document.execCommand("copy");
t.remove();}
document.body.appendChild(t);
try{t.select();copied=document.execCommand("copy")===true;}
catch(e){copied=false;}finally{t.remove();}}
const old=b.textContent;
b.textContent="\\u2713";b.classList.add("ok");
b.textContent=copied?"\\u2713":"Copy failed";
if(copied)b.classList.add("ok");
setTimeout(()=>{b.textContent=old;b.classList.remove("ok");},1200);}
document.addEventListener("click",e=>{
const b=e.target.closest("button.copy");if(b)copyCmd(b);});
const b=e.target.closest("button.copy");
if(b && guardPrompt(b.dataset.cmd,b))copyCmd(b);});
"""


Expand Down
62 changes: 62 additions & 0 deletions tests/test_prompt_budget.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""Exercise the actual browser guard, including custom board copy handlers."""

import json
import shutil
import subprocess
import sys
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "board"))
import _theme


@pytest.mark.parametrize("length,character", [(50_000, "a"), (50_001, "a"),
(50_000, "🌌"), (50_001, "🌌")])
def test_click_guard_precedes_custom_handler_and_preserves_full_request(length, character):
node = shutil.which("node")
if not node:
pytest.skip("Node is needed to execute the browser contract")
script = r'''
const assert=require('assert');
let handler, status, downloaded, writes=0;
global.document={
addEventListener:(kind,fn)=>handler=fn,
getElementById:()=>status,
createElement:()=>({dataset:{},setAttribute(){},appendChild(){}})
};
global.URL={createObjectURL:blob=>{downloaded=blob;return 'blob:test'},revokeObjectURL(){}};
''' + _theme.JS + r'''
copyCmd=()=>{writes++}; // Heart and other boards may override the copy UI.
const payload=CHARACTER.repeat(LENGTH);
const button={dataset:{cmd:payload},insertAdjacentElement:(where,p)=>status=p};
handler({target:{closest:()=>button}});
assert.equal(writes,LENGTH<=50000?1:0);
if(LENGTH>50000){
assert.match(status.textContent,/Not copied/);
downloaded.text().then(text=>assert.equal(text,payload));
}
'''
script = script.replace("CHARACTER", json.dumps(character)).replace("LENGTH", str(length))
subprocess.run([node, "-e", script], check=True, capture_output=True, text=True)


def test_clipboard_rejection_never_flashes_success():
node = shutil.which("node")
if not node:
pytest.skip("Node is needed to execute the browser contract")
script = r'''
const assert=require('assert');
global.document={addEventListener(){},body:{appendChild(){}},
createElement:()=>({select(){},remove(){}}),execCommand:()=>false};
Object.defineProperty(global,'navigator',{
value:{clipboard:{writeText:async()=>{throw Error('denied')}}}});
document.getElementById=()=>null;
global.setTimeout=()=>{};
''' + _theme.JS + r'''
const b={dataset:{cmd:'Use the health skill.'},textContent:'Copy',
classList:{add(){throw Error('false success')},remove(){}}};
copyCmd(b).then(()=>assert.equal(b.textContent,'Copy failed'));
'''
subprocess.run([node, "-e", script], check=True, capture_output=True, text=True)
Loading