Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix(studios): align audio previews, harden jobs, and validate local artifacts

Dee662caef0519d
diff --git a/cli/src/dsh/studios.integration.spec.ts b/cli/src/dsh/studios.integration.spec.ts
new file mode 100644
index 000000000..bbce16684
--- /dev/null
+++ b/cli/src/dsh/studios.integration.spec.ts
@@ -0,0 +1,86 @@
+// Explicit opt-in: these checks run the real package installers and native local simulations.
+// All index entries and workspaces stay in disposable directories.
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { fileURLToPath } from 'node:url'
+import { env } from '../config/env.js'
+import { installDsh, removeDsh } from './install.js'
+import { installedDsh, invalidateInstalledDsh, listInstalledDsh } from './installed.js'
+import { materializeWorkspace } from './materialize.js'
+import { DshViewerManager } from './viewer.js'
+
+const store = realpathSync(fileURLToPath(new URL('../../../store/', import.meta.url)))
+const packages = ['juce-agent-toolkit', 'foam-agent', 'autoresearch-mlx', 'ableton-ai', 'dimos', 'simskill', 'bonsai-mcp', 'comfy-mcp']
+
+describe.runIf(process.env.HARNESS_STUDIO_INTEGRATION === '1')('specialist studios through the real Harness lifecycle', () => {
+ let root: string
+ let savedRoot: string
+ let manager: DshViewerManager
+ const report: { name: string; checks: string[] }[] = []
+ beforeAll(async () => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'harness-studio-lifecycle-')))
+ savedRoot = env.DSH_DIR
+ env.DSH_DIR = join(root, 'installed')
+ invalidateInstalledDsh()
+ manager = new DshViewerManager({ onUrl: () => {} })
+ const viewer = await installDsh({ source: join(store, 'viewers/studio-viewer'), link: true })
+ expect(viewer.ok, JSON.stringify(viewer)).toBe(true)
+ }, 120_000)
+ afterAll(async () => {
+ await manager?.stopAll()
+ const output = join(store, 'viewers/studio-viewer/test-results')
+ mkdirSync(output, { recursive: true })
+ writeFileSync(join(output, 'lifecycle-report.json'), JSON.stringify(report, null, 2))
+ env.DSH_DIR = savedRoot
+ invalidateInstalledDsh()
+ if (root) rmSync(root, { recursive: true, force: true })
+ })
+ for (const name of packages) it(`${name}: installs, initializes, launches, runs, restores and removes`, async () => {
+ const phases: string[] = []
+ const result = await installDsh({ source: join(store, 'agents', name), expectedId: `autonomous/${name}`, link: true,
+ setupTimeoutMs: 600_000, onProgress: p => phases.push(p.phase) })
+ expect(result.ok, JSON.stringify(result)).toBe(true)
+ if (!result.ok) return
+ expect(phases).toEqual(['clone', 'setup', 'doctor', 'done'])
+ expect(installedDsh(result.installed.id)?.realDir).toBe(result.installed.realDir)
+ const workspace = join(root, `workspace ${name}`)
+ mkdirSync(workspace)
+ const materialized = await materializeWorkspace(result.installed, workspace)
+ expect(materialized.warnings).toEqual([])
+ expect(readFileSync(join(workspace, 'AGENTS.md'), 'utf8')).toContain(`autonomous/${name}`)
+ expect(lstatSync(join(workspace, '.agents/skills', name)).isSymbolicLink()).toBe(true)
+ const verdict = JSON.parse(readFileSync(join(workspace, '.harness/verdict.json'), 'utf8'))
+ expect(verdict.ready).toBe(true)
+ expect(existsSync(join(workspace, verdict.artifact))).toBe(true)
+ await manager.start(name, result.installed, workspace)
+ const url = manager.url(name)
+ expect(url).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/$/)
+ const first = await (await fetch(`${url}api/state`)).json()
+ expect(first.history).toHaveLength(1)
+ const run = await fetch(`${url}api/run`, { method: 'POST', headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ action: first.config.actions[0].id, parameters: first.project.parameters, revision: first.revision }) })
+ expect(run.status).toBe(202)
+ await expect.poll(async () => (await (await fetch(`${url}api/state`)).json()).job.status, { timeout: 120_000, interval: 300 }).toBe('done')
+ const current = await (await fetch(`${url}api/state`)).json()
+ expect(current.history).toHaveLength(2)
+ for (const artifact of current.result.artifacts) expect((await fetch(`${url}artifacts/${artifact.path}`)).status).toBe(200)
+ await manager.stop(name)
+ expect(manager.url(name)).toBe(null)
+ const again = await materializeWorkspace(result.installed, workspace)
+ expect(again.created).toEqual([])
+ expect(again.initLines).toEqual([])
+ await manager.start(name, result.installed, workspace)
+ const restored = await (await fetch(`${manager.url(name)}api/state`)).json()
+ expect(restored.result.id).toBe(current.result.id)
+ expect(restored.history).toHaveLength(2)
+ await manager.stop(name)
+ expect(removeDsh(result.installed.id)).toEqual({ ok: true })
+ expect(installedDsh(result.installed.id)).toBeUndefined()
+ expect(existsSync(join(store, 'agents', name, 'harness.json'))).toBe(true)
+ expect(listInstalledDsh().map(d => d.id)).toEqual(['autonomous/studio-viewer'])
+ report.push({ name, checks: ['install', 'setup', 'doctor', 'index', 'materialize', 'skill discovery', 'verdict',
+ 'viewer launch', 'run', 'artifact downloads', 'stop', 'idempotent materialization', 'restore', 'remove'] })
+ }, 900_000)
+})
diff --git a/store/agents/ableton-ai/toolchain/studio_runtime.py b/store/agents/ableton-ai/toolchain/studio_runtime.py
index 8b8ea016c..799949d4c 100644
--- a/store/agents/ableton-ai/toolchain/studio_runtime.py
+++ b/store/agents/ableton-ai/toolchain/studio_runtime.py
@@ -27,11 +27,16 @@ def contained(path):
def atomic_json(path, data):
path = contained(path)
path.parent.mkdir(parents=True, exist_ok=True)
- with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".studio-", delete=False) as f:
- json.dump(data, f, indent=2, allow_nan=False)
- f.write("\n")
- temp = f.name
- os.replace(temp, path)
+ temp = None
+ try:
+ with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".studio-", delete=False) as f:
+ temp = f.name
+ json.dump(data, f, indent=2, allow_nan=False)
+ f.write("\n")
+ os.replace(temp, path)
+ finally:
+ if temp and os.path.exists(temp):
+ os.unlink(temp)
def command(argv, cwd=None, timeout=120, env=None):
diff --git a/store/agents/ableton-ai/toolchain/workflow.py b/store/agents/ableton-ai/toolchain/workflow.py
index 37ad92683..e345f4601 100644
--- a/store/agents/ableton-ai/toolchain/workflow.py
+++ b/store/agents/ableton-ai/toolchain/workflow.py
@@ -1,7 +1,7 @@
import array
import json
import math
-import random
+import os
import re
import struct
import sys
@@ -12,14 +12,20 @@ SCALES = {"minor": [0, 3, 5, 7, 10], "major": [0, 4, 5, 7, 11], "pentatonic": [0
def notes(p):
- rng = random.Random(p["seed"])
if p["pattern"]:
if not re.fullmatch('[01]{16}',p["pattern"]):
raise ValueError('A custom rhythm must contain sixteen steps')
slots=[i for i,v in enumerate(p["pattern"]) if v=='1']
else:
- slots = sorted(rng.sample(range(16), p["density"]))
- return [{"step": s, "note": 48 + rng.choice(SCALES[p["scale"]]), "velocity": rng.randint(75, 110),
+ # The browser uses this same integer LCG and Fisher–Yates shuffle.
+ state = p["seed"]
+ slots = list(range(16))
+ for i in range(15, 0, -1):
+ state = (state * 1664525 + 1013904223) & 0xffffffff
+ j = state * (i + 1) // 4294967296
+ slots[i], slots[j] = slots[j], slots[i]
+ slots = sorted(slots[:p["density"]])
+ return [{"step": s, "note": 48 + SCALES[p["scale"]][(s+p["seed"]) % 5], "velocity": 75 + (s*17+p["seed"]*13) % 36,
"beat": s / 4 + (p["swing"] / 4 if s % 2 else 0), "length": .22} for s in slots]
@@ -70,7 +76,7 @@ def live(p,out):
from ableton_ai.connection import AbletonConnection
from ableton_ai.config import Settings
try:
- with AbletonConnection(Settings(max_connect_attempts=1,recv_timeout=3,command_delay=0)) as connection:
+ with AbletonConnection(Settings(host=os.environ.get('ABLETON_HOST','localhost'),port=int(os.environ.get('ABLETON_PORT','9877')),max_connect_attempts=1,recv_timeout=3,read_cmd_timeout=3,command_delay=0)) as connection:
snapshot=connection.send_command('get_session_info',retry=False)
except Exception as exc:
raise RuntimeError('Open Ableton Live and enable its AbletonAI Control Surface on port 9877. '+str(exc)) from exc
diff --git a/store/agents/ableton-ai/view.mjs b/store/agents/ableton-ai/view.mjs
index c7bc914c1..4a758380a 100644
--- a/store/agents/ableton-ai/view.mjs
+++ b/store/agents/ableton-ai/view.mjs
@@ -1,17 +1,16 @@
import {canvas,grid,round,words,circle,toolbar,badge,label,tone} from '/graphics.mjs';
-function random(seed){let s=seed;return()=>{s=(s*1664525+1013904223)>>>0;return s/4294967296;};}
+import {groove} from '/music.mjs';
export function mount(stage,api){
- let p=api.getParameters(),playing=false,step=0,interval,lastTick=0,selected=new Set(),oldSeed,oldDensity,recording=new Audio(),result;
+ let p=api.getParameters(),playing=false,step=0,interval,selected=new Set(),recording=new Audio(),result;
label(stage,'Sixteen steps. Endless little possibilities.');badge(stage,'LOCAL SYNTH');
- function pattern(){if(p.pattern)return new Set([...p.pattern].flatMap((v,i)=>v==='1'?[i]:[]));const rnd=random(p.seed),slots=Array.from({length:16},(_,i)=>i);for(let i=15;i>0;i--){const j=Math.floor(rnd()*(i+1));[slots[i],slots[j]]=[slots[j],slots[i]];}return new Set(slots.slice(0,p.density));}
const screen=canvas(stage,(ctx,w,h,t)=>{grid(ctx,w,h);const gap=8,left=24,cell=(w-2*left-7*gap)/8,top=h*.28,rowh=55;for(let i=0;i<16;i++){const x=left+i%8*(cell+gap),y=top+Math.floor(i/8)*(rowh+12),on=selected.has(i);round(ctx,x,y,cell,rowh,8,on?'#e8af7c':'#ffffff09',step===i&&playing?'#fff2d8':'#ffffff15');if(on)circle(ctx,x+cell/2,y+18,3,'#30231e');words(ctx,String(i+1).padStart(2,'0'),x+8,y+rowh-10,on?'#57402e':'#7e6d63',10);}words(ctx,`${p.tempo} BPM`,24,h*.18,'#f2bc88',25);words(ctx,p.scale.toUpperCase(),w-105,h*.18,'#a59285',10);if(playing){const x=24+(t%1)*(w-48);lineProgress(ctx,x,h-95);}},api.signal);
function lineProgress(ctx,x,y){ctx.fillStyle='#f2bc8840';ctx.fillRect(24,y,x-24,2);}
screen.element.setAttribute('aria-label','Sixteen-step sequencer; click a step to toggle it');screen.element.tabIndex=0;
const toggle=i=>{if(selected.has(i))selected.delete(i);else selected.add(i);api.setParameter('pattern',Array.from({length:16},(_,j)=>selected.has(j)?'1':'0').join(''));api.announce(`Step ${i+1} ${selected.has(i)?'on':'off'}`);};
screen.element.addEventListener('click',e=>{const box=screen.element.getBoundingClientRect(),x=e.clientX-box.left,y=e.clientY-box.top,cell=(box.width-48-56)/8;const col=Math.floor((x-24)/(cell+8)),row=Math.floor((y-box.height*.28)/67);if(col>=0&&col<8&&row>=0&&row<2)toggle(row*8+col);});
screen.element.addEventListener('keydown',e=>{if(e.key==='ArrowRight'){step=(step+1)%16;api.announce(`Step ${step+1}`);e.preventDefault();}if(e.key==='ArrowLeft'){step=(step+15)%16;api.announce(`Step ${step+1}`);e.preventDefault();}if(e.key===' '||e.key==='Enter'){toggle(step);e.preventDefault();}});
- function tick(){if(!playing)return;const scales={minor:[0,3,5,7,10],major:[0,4,5,7,11],pentatonic:[0,2,4,7,9]};if(selected.has(step)){const n=scales[p.scale][(step+p.seed)%5];tone(130.8128*2**(n/12),.24,'triangle',.16).catch(()=>api.announce('Audio is unavailable. Download the WAV.'));}step=(step+1)%16;interval=setTimeout(tick,60000/p.tempo/4*(1+(step%2?p.swing:-p.swing)));}
+ function tick(){if(!playing)return;const note=groove(p).find(n=>n.step===step);if(note)tone(440*2**((note.note-69)/12),note.length*60/p.tempo+.15,'sine',note.velocity/127*.32).catch(()=>api.announce('Audio is unavailable. Download the WAV.'));step=(step+1)%16;interval=setTimeout(tick,60000/p.tempo/4*(1+(step%2?p.swing:-p.swing)));}
const bar=toolbar(stage,[['Play loop',b=>{playing=!playing;b.textContent=playing?'Pause loop':'Play loop';b.setAttribute('aria-pressed',String(playing));if(playing)tick();else clearTimeout(interval);}],['New variation',()=>{api.setParameter('pattern','');api.setParameter('seed',p.seed%32+1);}],['Play WAV',async()=>{const file=result?.artifacts.find(a=>a.path.endsWith('.wav'));if(!file){api.announce('Keep a loop first.');return;}recording.src=api.artifactURL(file.path);await recording.play().catch(()=>api.announce('Download the WAV to listen.'));}]]);
api.signal.addEventListener('abort',()=>{clearTimeout(interval);recording.pause();});
- return {update(params,r,motion){const changed=oldSeed!==undefined&&(oldSeed!==params.seed||oldDensity!==params.density);p=params;result=r;oldSeed=p.seed;oldDensity=p.density;if(changed&&p.pattern){api.setParameter('pattern','');return;}selected=pattern();screen.motion(motion);if(!motion&&playing){playing=false;clearTimeout(interval);bar.firstChild.textContent='Play loop';bar.firstChild.setAttribute('aria-pressed','false');}}};
+ return {update(params,r,motion){p=params;result=r;selected=new Set(groove(p).map(n=>n.step));screen.motion(motion);if(!motion&&playing){playing=false;clearTimeout(interval);bar.firstChild.textContent='Play loop';bar.firstChild.setAttribute('aria-pressed','false');}}};
}
diff --git a/store/agents/autoresearch-mlx/toolchain/studio_runtime.py b/store/agents/autoresearch-mlx/toolchain/studio_runtime.py
index 8b8ea016c..799949d4c 100644
--- a/store/agents/autoresearch-mlx/toolchain/studio_runtime.py
+++ b/store/agents/autoresearch-mlx/toolchain/studio_runtime.py
@@ -27,11 +27,16 @@ def contained(path):
def atomic_json(path, data):
path = contained(path)
path.parent.mkdir(parents=True, exist_ok=True)
- with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".studio-", delete=False) as f:
- json.dump(data, f, indent=2, allow_nan=False)
- f.write("\n")
- temp = f.name
- os.replace(temp, path)
+ temp = None
+ try:
+ with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".studio-", delete=False) as f:
+ temp = f.name
+ json.dump(data, f, indent=2, allow_nan=False)
+ f.write("\n")
+ os.replace(temp, path)
+ finally:
+ if temp and os.path.exists(temp):
+ os.unlink(temp)
def command(argv, cwd=None, timeout=120, env=None):
diff --git a/store/agents/bonsai-mcp/toolchain/studio_runtime.py b/store/agents/bonsai-mcp/toolchain/studio_runtime.py
index 8b8ea016c..799949d4c 100644
--- a/store/agents/bonsai-mcp/toolchain/studio_runtime.py
+++ b/store/agents/bonsai-mcp/toolchain/studio_runtime.py
@@ -27,11 +27,16 @@ def contained(path):
def atomic_json(path, data):
path = contained(path)
path.parent.mkdir(parents=True, exist_ok=True)
- with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".studio-", delete=False) as f:
- json.dump(data, f, indent=2, allow_nan=False)
- f.write("\n")
- temp = f.name
- os.replace(temp, path)
+ temp = None
+ try:
+ with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".studio-", delete=False) as f:
+ temp = f.name
+ json.dump(data, f, indent=2, allow_nan=False)
+ f.write("\n")
+ os.replace(temp, path)
+ finally:
+ if temp and os.path.exists(temp):
+ os.unlink(temp)
def command(argv, cwd=None, timeout=120, env=None):
diff --git a/store/agents/bonsai-mcp/view.mjs b/store/agents/bonsai-mcp/view.mjs
index 73e4e2662..a1cf91595 100644
--- a/store/agents/bonsai-mcp/view.mjs
+++ b/store/agents/bonsai-mcp/view.mjs
@@ -24,7 +24,7 @@ export function mount(stage,api){
}
}
const names=p.use==='studio'?['Studio','Reading room']:['Living room','Bedroom'];words(ctx,`${names[selected%2]} · level ${Math.floor(selected/2)+1}`,24,h-70,'#dcebc1',13);
- words(ctx,plan?'PLAN VIEW':'DRAG TO ORBIT',24,24,'#93af85',9);
+
},api.signal);screen.element.setAttribute('aria-label','Interactive building schematic; drag or use arrow keys to orbit');screen.element.tabIndex=0;
screen.element.addEventListener('pointerdown',e=>{drag={x:e.clientX,y:e.clientY,startX:e.clientX,startY:e.clientY};screen.element.setPointerCapture(e.pointerId);});
screen.element.addEventListener('pointermove',e=>{if(!drag||plan)return;angle+=(e.clientX-drag.x)*.008;drag.x=e.clientX;});
diff --git a/store/agents/comfy-mcp/toolchain/studio_runtime.py b/store/agents/comfy-mcp/toolchain/studio_runtime.py
index 8b8ea016c..799949d4c 100644
--- a/store/agents/comfy-mcp/toolchain/studio_runtime.py
+++ b/store/agents/comfy-mcp/toolchain/studio_runtime.py
@@ -27,11 +27,16 @@ def contained(path):
def atomic_json(path, data):
path = contained(path)
path.parent.mkdir(parents=True, exist_ok=True)
- with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".studio-", delete=False) as f:
- json.dump(data, f, indent=2, allow_nan=False)
- f.write("\n")
- temp = f.name
- os.replace(temp, path)
+ temp = None
+ try:
+ with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".studio-", delete=False) as f:
+ temp = f.name
+ json.dump(data, f, indent=2, allow_nan=False)
+ f.write("\n")
+ os.replace(temp, path)
+ finally:
+ if temp and os.path.exists(temp):
+ os.unlink(temp)
def command(argv, cwd=None, timeout=120, env=None):
diff --git a/store/agents/comfy-mcp/toolchain/workflow.py b/store/agents/comfy-mcp/toolchain/workflow.py
index dd513ec0e..6bceda5b9 100644
--- a/store/agents/comfy-mcp/toolchain/workflow.py
+++ b/store/agents/comfy-mcp/toolchain/workflow.py
@@ -52,17 +52,21 @@ def generate(p,out):
def comfy(p,out):
base=os.environ.get('COMFYUI_URL','http://127.0.0.1:8188').rstrip('/')
url=urllib.parse.urlparse(base)
- if url.scheme!='http' or url.hostname not in ('127.0.0.1','localhost','::1') or url.username or url.password or url.path:
+ if url.scheme!='http' or url.hostname not in ('127.0.0.1','localhost','::1') or url.username or url.password or url.path or url.query or url.fragment:
raise ValueError('This local studio expects COMFYUI_URL to be a loopback HTTP address.')
path=contained(workspace()/'workflow.json')
if path.stat().st_size>1_000_000:raise ValueError('workflow.json is too large')
workflow=json.loads(path.read_text())
if not isinstance(workflow,dict) or not workflow or any(not isinstance(v,dict) or not isinstance(v.get('class_type'),str) for v in workflow.values()):
raise ValueError('Save an API-format ComfyUI workflow in workflow.json.')
+ class LocalOnly(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, *args, **kwargs):
+ raise urllib.error.URLError('Local ComfyUI requests cannot follow redirects.')
+ opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),LocalOnly())
def request(endpoint,data=None):
req=urllib.request.Request(base+endpoint,data=json.dumps(data).encode() if data is not None else None,headers={'Content-Type':'application/json'})
try:
- with urllib.request.urlopen(req,timeout=5) as response:
+ with opener.open(req,timeout=5) as response:
return json.loads(response.read(2_000_000))
except urllib.error.URLError as exc:
raise RuntimeError('Start local ComfyUI on port 8188, then run again. '+str(exc)) from exc
@@ -83,7 +87,7 @@ def comfy(p,out):
for output in job['outputs'].values():
for asset in output.get('images',[]):
query=urllib.parse.urlencode({k:asset[k] for k in ['filename','subfolder','type'] if k in asset})
- with urllib.request.urlopen(base+'/view?'+query,timeout=10) as response:
+ with opener.open(base+'/view?'+query,timeout=10) as response:
content=response.read(32*1024*1024+1)
if len(content)>32*1024*1024:raise RuntimeError('A ComfyUI image exceeded the local download limit.')
if not content.startswith(b'\x89PNG\r\n\x1a\n'):raise RuntimeError('This image workflow must produce PNG outputs.')
diff --git a/store/agents/comfy-mcp/view.mjs b/store/agents/comfy-mcp/view.mjs
index 733f039a8..c961d6c21 100644
--- a/store/agents/comfy-mcp/view.mjs
+++ b/store/agents/comfy-mcp/view.mjs
@@ -3,8 +3,8 @@ export function mount(stage,api){
let p=api.getParameters(),result,selected=-1,last='',dialog;
const tag=badge(stage,'PROCEDURAL STUDIES'),info=label(stage,'A family of forms. Pick the one that speaks to you.');
const gallery=el('div','','gallery');stage.append(gallery);
- function close(){dialog?.remove();dialog=null;}
- function inspect(index){const img=result?.data?.images?.[index];if(!img)return;close();selected=index;dialog=el('div','','domain-dialog');dialog.setAttribute('role','dialog');dialog.setAttribute('aria-label','Inspect study');const b=el('button','Close');b.addEventListener('click',()=>{close();gallery.children[index]?.focus();});const picture=el('img');picture.src=api.artifactURL(result.artifacts.find(a=>a.path.endsWith('/'+img.name)).path);picture.alt=img.seed===null?'ComfyUI workflow output':`Procedural study ${img.seed}`;dialog.append(b,el('h2',img.seed===null?'ComfyUI output':`Study ${String(img.seed).padStart(4,'0')}`),picture,el('p',img.seed===null?'Produced by your saved ComfyUI workflow.':`Reproduce this study with seed ${img.seed} and the saved recipe.`));stage.append(dialog);b.focus();api.announce('Study opened.');}
+ function close(){dialog?.close();dialog?.remove();dialog=null;gallery.children[Math.max(0,selected)]?.focus();}
+ function inspect(index){const img=result?.data?.images?.[index];if(!img)return;close();selected=index;dialog=el('dialog','','domain-dialog');dialog.setAttribute('aria-label','Inspect study');const b=el('button','Close');b.addEventListener('click',()=>{close();gallery.children[index]?.focus();});const picture=el('img');picture.src=api.artifactURL(result.artifacts.find(a=>a.path.endsWith('/'+img.name)).path);picture.alt=img.seed===null?'ComfyUI workflow output':`Procedural study ${img.seed}`;dialog.append(b,el('h2',img.seed===null?'ComfyUI output':`Study ${String(img.seed).padStart(4,'0')}`),picture,el('p',img.seed===null?'Produced by your saved ComfyUI workflow.':`Reproduce this study with seed ${img.seed} and the saved recipe.`));stage.append(dialog);dialog.addEventListener('cancel',e=>{e.preventDefault();close();});dialog.showModal();b.focus();api.announce('Study opened.');}
stage.addEventListener('keydown',e=>{if(e.key==='Escape')close();});
toolbar(stage,[['Another family',()=>api.setParameter('seed',p.seed%980+7)],['Inspect favourite',()=>inspect(selected<0?0:selected)]]);
return {update(params,r){p=params;result=r;if(!r?.data?.images){gallery.replaceChildren(el('div','Grow a family of variations to explore.','domain-empty'));return;}if(r.id===last)return;last=r.id;close();gallery.replaceChildren();tag.textContent=r.engine.startsWith('Native')?'COMFYUI OUTPUTS':'PROCEDURAL STUDIES';r.data.images.forEach((img,i)=>{const file=r.artifacts.find(a=>a.path.endsWith('/'+img.name));if(!file)return;const button=el('button');button.type='button';button.setAttribute('aria-label',img.seed===null?`Inspect image ${i+1}`:`Inspect study ${img.seed}`);const image=el('img');image.src=api.artifactURL(file.path);image.alt=img.seed===null?'ComfyUI output':`A ${r.parameters.palette} procedural flower, seed ${img.seed}`;const caption=el('figcaption',img.seed===null?`Output ${i+1}`:`No. ${String(img.seed).padStart(4,'0')} ↗`);button.append(image,caption);button.addEventListener('click',()=>inspect(i));gallery.append(button);});}};
diff --git a/store/agents/dimos/toolchain/studio_runtime.py b/store/agents/dimos/toolchain/studio_runtime.py
index 8b8ea016c..799949d4c 100644
--- a/store/agents/dimos/toolchain/studio_runtime.py
+++ b/store/agents/dimos/toolchain/studio_runtime.py
@@ -27,11 +27,16 @@ def contained(path):
def atomic_json(path, data):
path = contained(path)
path.parent.mkdir(parents=True, exist_ok=True)
- with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".studio-", delete=False) as f:
- json.dump(data, f, indent=2, allow_nan=False)
- f.write("\n")
- temp = f.name
- os.replace(temp, path)
+ temp = None
+ try:
+ with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".studio-", delete=False) as f:
+ temp = f.name
+ json.dump(data, f, indent=2, allow_nan=False)
+ f.write("\n")
+ os.replace(temp, path)
+ finally:
+ if temp and os.path.exists(temp):
+ os.unlink(temp)
def command(argv, cwd=None, timeout=120, env=None):
diff --git a/store/agents/dimos/view.mjs b/store/agents/dimos/view.mjs
index 1cff4e119..b3c8eff44 100644
--- a/store/agents/dimos/view.mjs
+++ b/store/agents/dimos/view.mjs
@@ -4,7 +4,7 @@ export function mount(stage,api){
let p=api.getParameters(),result,showPath=true,replay=true,index=0,now=0,start=0,last='',bounds;
const info=label(stage,'Choose somewhere worth exploring.'),tag=badge(stage,'SIMULATION ONLY');
const screen=canvas(stage,(ctx,w,h,t)=>{
- now=t;const size=Math.min(h-85,w-70),left=(w-size)/2,top=22,s=size/10;bounds={left,top,s};const map=(x,y)=>[left+x*s,top+(10-y)*s];
+ now=t;const size=Math.min(h-145,w-70),left=(w-size)/2,top=70,s=size/10;bounds={left,top,s};const map=(x,y)=>[left+x*s,top+(10-y)*s];
round(ctx,left,top,size,size,12,'#24372b','#ffffff20');
for(let i=1;i<10;i++){line(ctx,[[left+i*s,top],[left+i*s,top+size]],'#ffffff0b',1);line(ctx,[[left,top+i*s],[left+size,top+i*s]],'#ffffff0b',1);}
const blocks=layouts[p.layout];for(const [x,y,bw,bh] of blocks){const [px,py]=map(x-bw/2,y+bh/2);round(ctx,px+4,py+5,bw*s,bh*s,5,'#0a1e1644');round(ctx,px,py,bw*s,bh*s,5,'#66795d','#8da17a');line(ctx,[[px+5,py+7],[px+bw*s-5,py+7]],'#b0c49b55',1);}
@@ -15,7 +15,7 @@ export function mount(stage,api){
if(compatible){if(replay)index=Math.min(result.data.positions.length-1,Math.floor(((t-start)*30)%result.data.positions.length));const frame=result.data.positions[index];position=[frame[1],frame[2]];scrub.value=index;}
const robot=map(...position);circle(ctx,...robot,17,'#bae38912');circle(ctx,...robot,9,'#e5edcc');circle(ctx,robot[0]+3,robot[1]-3,2,'#364d35');
if(w>550){words(ctx,'ROVER 01',24,70,'#a7c292',10);words(ctx,compatible?`${result.data.positions[index][0].toFixed(1)} s`:'READY',24,98,'#dceac7',20);words(ctx,compatible?'Recorded trajectory':'Choose a destination',24,121,'#8da684',9);}
- words(ctx,'1 METRE GRID',left,top+size+20,'#8da684',9);
+
},api.signal);screen.element.setAttribute('aria-label','Office rover mission map; click to select a goal');screen.element.tabIndex=0;
screen.element.addEventListener('click',e=>{const b=screen.element.getBoundingClientRect();const x=Math.max(1,Math.min(9,Math.round((e.clientX-b.left-bounds.left)/bounds.s*2)/2)),y=Math.max(1,Math.min(9,Math.round((10-(e.clientY-b.top-bounds.top)/bounds.s)*2)/2));api.setParameter('goal_x',x);api.setParameter('goal_y',y);api.announce(`Destination ${x} east, ${y} north`);});
screen.element.addEventListener('keydown',e=>{const axes={ArrowLeft:['goal_x',-.5],ArrowRight:['goal_x',.5],ArrowUp:['goal_y',.5],ArrowDown:['goal_y',-.5]};if(axes[e.key]){const [key,delta]=axes[e.key];api.setParameter(key,Math.max(1,Math.min(9,p[key]+delta)));e.preventDefault();}});
diff --git a/store/agents/foam-agent/studio.config.json b/store/agents/foam-agent/studio.config.json
index cc0dd325f..d555bd248 100644
--- a/store/agents/foam-agent/studio.config.json
+++ b/store/agents/foam-agent/studio.config.json
@@ -71,7 +71,7 @@
"min": 80,
"max": 800,
"step": 40,
- "integer": false,
+ "integer": true,
"unit": "",
"hint": ""
}
diff --git a/store/agents/foam-agent/toolchain/studio_runtime.py b/store/agents/foam-agent/toolchain/studio_runtime.py
index 8b8ea016c..799949d4c 100644
--- a/store/agents/foam-agent/toolchain/studio_runtime.py
+++ b/store/agents/foam-agent/toolchain/studio_runtime.py
@@ -27,11 +27,16 @@ def contained(path):
def atomic_json(path, data):
path = contained(path)
path.parent.mkdir(parents=True, exist_ok=True)
- with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".studio-", delete=False) as f:
- json.dump(data, f, indent=2, allow_nan=False)
- f.write("\n")
- temp = f.name
- os.replace(temp, path)
+ temp = None
+ try:
+ with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".studio-", delete=False) as f:
+ temp = f.name
+ json.dump(data, f, indent=2, allow_nan=False)
+ f.write("\n")
+ os.replace(temp, path)
+ finally:
+ if temp and os.path.exists(temp):
+ os.unlink(temp)
def command(argv, cwd=None, timeout=120, env=None):
diff --git a/store/agents/foam-agent/view.mjs b/store/agents/foam-agent/view.mjs
index e76bf3312..39ddfcd64 100644
--- a/store/agents/foam-agent/view.mjs
+++ b/store/agents/foam-agent/view.mjs
@@ -1,24 +1,24 @@
import {canvas,grid,line,words,circle,toolbar,badge,label} from '/graphics.mjs';
export function mount(stage,api){
- let p=api.getParameters(),field,pressure=false,arrows=false,tracers=[],lastT=0;
+ let p=api.getParameters(),field,pressure=false,arrows=false,tracers=[],lastT=0,bounds;
const info=label(stage,'An invitation to follow the flow.'),tag=badge(stage,'FLOW SKETCH');
const screen=canvas(stage,(ctx,w,h,t)=>{
- grid(ctx,w,h,32);const top=38,bottom=h-55,fh=bottom-top,scaleX=(w-48)/120,scaleY=fh/56;
- const speed=p.speed/100,cx=24+36*scaleX,cy=top+28*scaleY;
+ grid(ctx,w,h,32);const scaleX=Math.min((w-48)/120,(h-(w<500?180:155))/56),scaleY=scaleX,left=(w-120*scaleX)/2,top=65,fh=56*scaleY;bounds={left,top,scaleX};
+ const speed=p.speed/100,cx=left+36*scaleX,cy=top+28*scaleY;
if(field){
for(let row=0;row<field.ux.length;row++)for(let col=0;col<field.ux[row].length;col++){
if(field.solid[row][col])continue;
const magnitude=Math.hypot(field.ux[row][col],field.uy[row][col]);
const v=pressure?Math.max(0,Math.min(1,.5+(field.pressure[row][col]-1/3)*20)):Math.min(1,magnitude/.13);
- ctx.fillStyle=`hsla(${205-v*150},60%,${25+v*30}%,${.06+v*.3})`;ctx.fillRect(24+col*2*scaleX,top+row*2*scaleY,2*scaleX+1,2*scaleY+1);
- if(arrows&&col%4===0&&row%4===0){const x=24+col*2*scaleX,y=top+row*2*scaleY;line(ctx,[[x,y],[x+field.ux[row][col]*90,y+field.uy[row][col]*90]],'#d0eeec66',1);}
+ ctx.fillStyle=`hsla(${205-v*150},60%,${25+v*30}%,${.06+v*.3})`;ctx.fillRect(left+col*2*scaleX,top+row*2*scaleY,2*scaleX+1,2*scaleY+1);
+ if(arrows&&col%4===0&&row%4===0){const x=left+col*2*scaleX,y=top+row*2*scaleY;line(ctx,[[x,y],[x+field.ux[row][col]*90,y+field.uy[row][col]*90]],'#d0eeec66',1);}
}
}
- for(let row=0;row<19;row++){
+ if(!field)for(let row=0;row<19;row++){
const y0=top+row/18*fh,points=[];
- for(let x=24;x<w-24;x+=4){const near=Math.exp(-(((x-cx)/(30*scaleX))**2)),dy=(y0-cy),spread=Math.sign(dy)*p.radius*scaleY*Math.exp(-((dy/(p.radius*scaleY*2))**2))*near;points.push([x,y0+spread]);}
+ for(let x=left;x<left+120*scaleX;x+=4){const near=Math.exp(-(((x-cx)/(30*scaleX))**2)),dy=(y0-cy),spread=Math.sign(dy)*p.radius*scaleY*Math.exp(-((dy/(p.radius*scaleY*2))**2))*near;points.push([x,y0+spread]);}
line(ctx,points,field?'#b3e5e41b':'#b3e5e42f',.8);
- if(!field){const x=24+((t*p.speed*22+row*53)%(w-48)),near=Math.exp(-(((x-cx)/(30*scaleX))**2)),dy=y0-cy;circle(ctx,x,y0+Math.sign(dy)*p.radius*scaleY*Math.exp(-((dy/(p.radius*scaleY*2))**2))*near,1.4,'#a1dadba0');}
+ if(!field){const x=left+((t*p.speed*22+row*53)%(120*scaleX)),near=Math.exp(-(((x-cx)/(30*scaleX))**2)),dy=y0-cy;circle(ctx,x,y0+Math.sign(dy)*p.radius*scaleY*Math.exp(-((dy/(p.radius*scaleY*2))**2))*near,1.4,'#a1dadba0');}
}
ctx.fillStyle='#cedad4';ctx.strokeStyle='#f0faf0';ctx.lineWidth=2;ctx.beginPath();
if(p.shape==='square')ctx.rect(cx-p.radius*scaleX,cy-p.radius*scaleY,p.radius*2*scaleX,p.radius*2*scaleY);
@@ -26,12 +26,12 @@ export function mount(stage,api){
ctx.fill();ctx.stroke();
const dt=Math.min(.05,Math.max(0,t-lastT));lastT=t;
if(field&&tracers.length<80&&dt>0)tracers.push({x:1,y:2+Math.random()*52});
- for(const dot of tracers){let ux=speed,uy=0;if(field){const row=Math.max(0,Math.min(field.ux.length-1,Math.floor(dot.y/2))),col=Math.max(0,Math.min(field.ux[0].length-1,Math.floor(dot.x/2)));ux=field.ux[row][col];uy=field.uy[row][col];}dot.x+=ux*dt*120;dot.y+=uy*dt*120;circle(ctx,24+dot.x*scaleX,top+dot.y*scaleY,1.8,'#c6fbf3');}
+ for(const dot of tracers){let ux=speed,uy=0;if(field){const row=Math.max(0,Math.min(field.ux.length-1,Math.floor(dot.y/2))),col=Math.max(0,Math.min(field.ux[0].length-1,Math.floor(dot.x/2)));ux=field.ux[row][col];uy=field.uy[row][col];}dot.x+=ux*dt*120;dot.y+=uy*dt*120;circle(ctx,left+dot.x*scaleX,top+dot.y*scaleY,1.8,'#c6fbf3');}
tracers=tracers.filter(dot=>dot.x<120&&dot.y>0&&dot.y<56);
- words(ctx,pressure?'PRESSURE':'VELOCITY',24,h-23,'#99b9bf',9);words(ctx,field?'Measured field':'Illustrative field',w-132,h-23,'#99b9bf',9);
+ words(ctx,pressure?'PRESSURE':'VELOCITY',left,top+fh+17,'#99b9bf',9);words(ctx,field?'Measured field':'Illustrative field',left+120*scaleX-105,top+fh+17,'#99b9bf',9);
},api.signal);
screen.element.setAttribute('aria-label','Interactive flow field; click to release a tracer');screen.element.tabIndex=0;
- screen.element.addEventListener('click',e=>{const b=screen.element.getBoundingClientRect();tracers.push({x:(e.clientX-b.left-24)/(b.width-48)*120,y:(e.clientY-b.top-38)/(b.height-93)*56});api.announce('Tracer released.');});
+ screen.element.addEventListener('click',e=>{const b=screen.element.getBoundingClientRect();tracers.push({x:(e.clientX-b.left-bounds.left)/bounds.scaleX,y:(e.clientY-b.top-bounds.top)/bounds.scaleX});api.announce('Tracer released.');});
screen.element.addEventListener('keydown',e=>{if(e.key==='Enter'){tracers.push({x:1,y:20});api.announce('Tracer released.');}});
toolbar(stage,[['Show pressure',b=>{pressure=!pressure;b.textContent=pressure?'Show velocity':'Show pressure';b.setAttribute('aria-pressed',String(pressure));}],['Show vectors',b=>{arrows=!arrows;b.textContent=arrows?'Hide vectors':'Show vectors';b.setAttribute('aria-pressed',String(arrows));}],['Release tracers',()=>{for(let i=0;i<15;i++)tracers.push({x:1,y:3+i*3.3});api.announce('Fifteen tracers released.');}]]);
return {update(params,result,motion){p=params;field=result?.data?.ux&&Object.keys(p).every(k=>p[k]===result.parameters[k])?result.data:null;tag.textContent=field?'SIMULATION REPLAY':'FLOW SKETCH';info.textContent=field?'Particles follow your measured velocity field.':'Adjust the body, then run to calculate the flow.';screen.motion(motion);}};
diff --git a/store/agents/juce-agent-toolkit/toolchain/studio_runtime.py b/store/agents/juce-agent-toolkit/toolchain/studio_runtime.py
index 8b8ea016c..799949d4c 100644
--- a/store/agents/juce-agent-toolkit/toolchain/studio_runtime.py
+++ b/store/agents/juce-agent-toolkit/toolchain/studio_runtime.py
@@ -27,11 +27,16 @@ def contained(path):
def atomic_json(path, data):
path = contained(path)
path.parent.mkdir(parents=True, exist_ok=True)
- with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".studio-", delete=False) as f:
- json.dump(data, f, indent=2, allow_nan=False)
- f.write("\n")
- temp = f.name
- os.replace(temp, path)
+ temp = None
+ try:
+ with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".studio-", delete=False) as f:
+ temp = f.name
+ json.dump(data, f, indent=2, allow_nan=False)
+ f.write("\n")
+ os.replace(temp, path)
+ finally:
+ if temp and os.path.exists(temp):
+ os.unlink(temp)
def command(argv, cwd=None, timeout=120, env=None):
diff --git a/store/agents/juce-agent-toolkit/toolchain/workflow.py b/store/agents/juce-agent-toolkit/toolchain/workflow.py
index 14ad76592..48d342118 100644
--- a/store/agents/juce-agent-toolkit/toolchain/workflow.py
+++ b/store/agents/juce-agent-toolkit/toolchain/workflow.py
@@ -13,7 +13,7 @@ def summarize(p, out, engine):
raise ValueError("Expected a 16-bit mono recording")
samples = array.array("h", f.readframes(f.getnframes()))
rate = f.getframerate()
- peak = max(abs(x) for x in samples) / 32768
+ peak = max((abs(x) for x in samples), default=0) / 32768
if peak >= .999 or not samples:
raise ValueError("The recording clipped or was empty")
rms = math.sqrt(sum((x / 32768) ** 2 for x in samples) / len(samples))
diff --git a/store/agents/simskill/studio.config.json b/store/agents/simskill/studio.config.json
index 2a0596054..487335228 100644
--- a/store/agents/simskill/studio.config.json
+++ b/store/agents/simskill/studio.config.json
@@ -15,7 +15,7 @@
"min": 120,
"max": 900,
"step": 60,
- "integer": false,
+ "integer": true,
"unit": "vehicles/hour/approach",
"hint": ""
},
@@ -27,7 +27,7 @@
"min": 10,
"max": 70,
"step": 5,
- "integer": false,
+ "integer": true,
"unit": "s",
"hint": ""
},
@@ -39,7 +39,7 @@
"min": 120,
"max": 480,
"step": 60,
- "integer": false,
+ "integer": true,
"unit": "s",
"hint": ""
},
diff --git a/store/agents/simskill/toolchain/build-sumo.sh b/store/agents/simskill/toolchain/build-sumo.sh
index 5b6ce2858..ebab6938a 100755
--- a/store/agents/simskill/toolchain/build-sumo.sh
+++ b/store/agents/simskill/toolchain/build-sumo.sh
@@ -5,7 +5,7 @@ set -euo pipefail
cd "$(dirname "$0")/.."
. toolchain/runtimes.sh
if [ -x .sumo/bin/sumo ] && [ -x .sumo/bin/netconvert ]; then exit 0; fi
-harness_conda_env .sumo 'xerces-c=3.3.0'
+harness_conda_env .sumo 'xerces-c=3.3.0=h32b985b_2' 'icu=78.3=py313hbf1d544_2' 'libcxx=23.1.1=h19cb2f5_0'
if [ "$(uname -s)" = Darwin ]; then
export SDKROOT="$(xcrun --show-sdk-path)"
if [ -d "$SDKROOT/usr/include/c++/v1" ]; then
diff --git a/store/agents/simskill/toolchain/studio_runtime.py b/store/agents/simskill/toolchain/studio_runtime.py
index 8b8ea016c..799949d4c 100644
--- a/store/agents/simskill/toolchain/studio_runtime.py
+++ b/store/agents/simskill/toolchain/studio_runtime.py
@@ -27,11 +27,16 @@ def contained(path):
def atomic_json(path, data):
path = contained(path)
path.parent.mkdir(parents=True, exist_ok=True)
- with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".studio-", delete=False) as f:
- json.dump(data, f, indent=2, allow_nan=False)
- f.write("\n")
- temp = f.name
- os.replace(temp, path)
+ temp = None
+ try:
+ with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".studio-", delete=False) as f:
+ temp = f.name
+ json.dump(data, f, indent=2, allow_nan=False)
+ f.write("\n")
+ os.replace(temp, path)
+ finally:
+ if temp and os.path.exists(temp):
+ os.unlink(temp)
def command(argv, cwd=None, timeout=120, env=None):
diff --git a/store/agents/simskill/upstream.lock.json b/store/agents/simskill/upstream.lock.json
index 973239f45..5632cd7fa 100644
--- a/store/agents/simskill/upstream.lock.json
+++ b/store/agents/simskill/upstream.lock.json
@@ -19,9 +19,9 @@
"sparse": [
"src",
"build_config",
- "data/xsd",
"tools/build_config",
- "tools/sumolib"
+ "tools/sumolib",
+ "data"
]
}
]
diff --git a/store/tools/studio_runtime.py b/store/tools/studio_runtime.py
index 8b8ea016c..799949d4c 100644
--- a/store/tools/studio_runtime.py
+++ b/store/tools/studio_runtime.py
@@ -27,11 +27,16 @@ def contained(path):
def atomic_json(path, data):
path = contained(path)
path.parent.mkdir(parents=True, exist_ok=True)
- with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".studio-", delete=False) as f:
- json.dump(data, f, indent=2, allow_nan=False)
- f.write("\n")
- temp = f.name
- os.replace(temp, path)
+ temp = None
+ try:
+ with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".studio-", delete=False) as f:
+ temp = f.name
+ json.dump(data, f, indent=2, allow_nan=False)
+ f.write("\n")
+ os.replace(temp, path)
+ finally:
+ if temp and os.path.exists(temp):
+ os.unlink(temp)
def command(argv, cwd=None, timeout=120, env=None):
diff --git a/store/viewers/studio-viewer/server.mjs b/store/viewers/studio-viewer/server.mjs
index 7d78c09dd..f7284996f 100644
--- a/store/viewers/studio-viewer/server.mjs
+++ b/store/viewers/studio-viewer/server.mjs
@@ -1,8 +1,8 @@
import http from 'node:http';
-import {readFile, writeFile, mkdir, readdir, realpath, stat} from 'node:fs/promises';
+import {readFile, writeFile, rename, rm, readdir, realpath, stat} from 'node:fs/promises';
import {resolve, join, relative, sep, extname} from 'node:path';
import {fileURLToPath} from 'node:url';
-import {createHash} from 'node:crypto';
+import {createHash, randomUUID} from 'node:crypto';
import {spawn} from 'node:child_process';
const UI = fileURLToPath(new URL('./web/', import.meta.url));
@@ -28,7 +28,7 @@ export function validateParameters(config, parameters) {
if (Object.keys(parameters).some(k => !keys.has(k))) throw new Problem(400, 'Unknown studio control.');
const out = {};
for (const c of config.controls) {
- const v = parameters[c.id] ?? c.value;
+ const v = Object.hasOwn(parameters,c.id) ? parameters[c.id] : c.value;
if (c.type === 'number') {
if (typeof v !== 'number' || !Number.isFinite(v) || v < c.min || v > c.max || (c.integer && !Number.isInteger(v))) throw new Problem(400, `${c.label} must be between ${c.min} and ${c.max}.`);
} else if (c.type === 'select') {
@@ -58,6 +58,7 @@ export async function createStudio({workspace, packageDir, port = 0, jobTimeout
let job = null;
let child = null;
let timer = null;
+ let starting = false;
const project = async () => jsonFile(workspace, 'studio.json');
const readState = async () => {
const p = await project();
@@ -88,7 +89,9 @@ export async function createStudio({workspace, packageDir, port = 0, jobTimeout
if (req.headers.host !== expectedHost && req.headers.host !== `localhost:${server.address().port}`) throw new Problem(403, 'Open this studio on its local address.');
if (req.headers.origin && req.headers.origin !== `http://${req.headers.host}`) throw new Problem(403, 'Requests must come from this studio.');
const url = new URL(req.url, `http://${expectedHost}`);
- const path = decodeURIComponent(url.pathname);
+ let path;
+ try { path = decodeURIComponent(url.pathname); }
+ catch { throw new Problem(400, 'This address is malformed.'); }
if (req.method === 'GET' && path === '/api/state') return send(200, await readState());
if (req.method === 'GET' && path === '/api/run') {
const id = url.searchParams.get('id');
@@ -102,16 +105,23 @@ export async function createStudio({workspace, packageDir, port = 0, jobTimeout
return send(200, {ok:true});
}
if (req.method === 'POST' && path === '/api/run') {
- if (child) throw new Problem(409, 'A run is already in progress.');
+ if (child || starting) throw new Problem(409, 'A run is already in progress.');
+ starting = true;
+ try {
if (!req.headers['content-type']?.startsWith('application/json')) throw new Problem(415, 'Send studio controls as JSON.');
const input = await body(req);
+ if (!input || Array.isArray(input) || typeof input !== 'object') throw new Problem(400, 'Provide the studio action and controls.');
const action = config.actions.find(a => a.id === input.action);
if (!action) throw new Problem(400, 'Choose a studio action.');
const p = await project();
if (input.revision !== revision(p)) throw new Problem(409, 'The agent changed this project. Refresh to load its latest controls.');
const parameters = validateParameters(config,input.parameters);
- await confined(workspace, 'studio.json');
- await writeFile(join(workspace,'studio.json'), JSON.stringify({...p,parameters},null,2)+'\n');
+ const target = await confined(workspace, 'studio.json');
+ const temporary = join(workspace,`.studio-${randomUUID()}.json`);
+ try {
+ await writeFile(temporary,JSON.stringify({...p,parameters},null,2)+'\n',{flag:'wx'});
+ await rename(temporary,target);
+ } finally { await rm(temporary,{force:true}); }
const script = await confined(packageDir,'toolchain/run.sh');
job = {status:'running', action:action.id, label:action.label, startedAt:new Date().toISOString(), message:'Preparing your run…', log:''};
child = spawn(script, [action.id], {cwd:workspace, detached:true, env:{...process.env,HARNESS_WORKSPACE:workspace,HARNESS_DSH_DIR:packageDir},stdio:['ignore','pipe','pipe']});
@@ -124,6 +134,7 @@ export async function createStudio({workspace, packageDir, port = 0, jobTimeout
});
timer = setTimeout(() => {job = {...job,status:'failed',message:'This run reached its time limit. Your last result is safe.'}; endChild();},jobTimeout);
return send(202,{ok:true});
+ } finally { starting = false; }
}
if (req.method !== 'GET' && req.method !== 'HEAD') throw new Problem(405,'This action is not supported.');
let root = UI, file = path === '/' ? 'index.html':path.slice(1);
diff --git a/store/viewers/studio-viewer/test/music.test.mjs b/store/viewers/studio-viewer/test/music.test.mjs
new file mode 100644
index 000000000..960108179
--- /dev/null
+++ b/store/viewers/studio-viewer/test/music.test.mjs
@@ -0,0 +1,15 @@
+import {test} from 'node:test';
+import assert from 'node:assert/strict';
+import {spawnSync} from 'node:child_process';
+import {fileURLToPath} from 'node:url';
+import {groove} from '../web/music.mjs';
+
+test('audition and MIDI export agree for every seed, scale, density, and custom rhythm',()=>{
+ const cases=[];
+ for(const seed of [1,7,16,32])for(const scale of ['minor','major','pentatonic'])for(const density of [1,4,8,16])for(const pattern of ['', '1000010001000001', '0000000000000000'])for(const swing of [0,.3,.6])cases.push({seed,scale,density,pattern,swing});
+ const cwd=fileURLToPath(new URL('../../../agents/ableton-ai/toolchain/',import.meta.url));
+ const result=spawnSync('python3',['-c','import json,sys;from workflow import notes;print(json.dumps([notes(p) for p in json.load(sys.stdin)]))'],{cwd,input:JSON.stringify(cases),encoding:'utf8'});
+ assert.equal(result.status,0,result.stderr);
+ const exported=JSON.parse(result.stdout);
+ cases.forEach((p,i)=>assert.deepEqual(groove(p),exported[i],JSON.stringify(p)));
+});
diff --git a/store/viewers/studio-viewer/test/runtime_test.py b/store/viewers/studio-viewer/test/runtime_test.py
new file mode 100644
index 000000000..3ec682f16
--- /dev/null
+++ b/store/viewers/studio-viewer/test/runtime_test.py
@@ -0,0 +1,122 @@
+"""Workspace safety and success/failure contracts for every copied runner."""
+import contextlib
+import importlib.util
+import io
+import json
+import math
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+from unittest.mock import patch
+
+STORE = Path(__file__).resolve().parents[3]
+coverage = None
+if os.environ.get('STUDIO_COVERAGE'):
+ from coverage import Coverage
+ coverage = Coverage(branch=True, data_file=None, include=[str(STORE/'tools/studio_runtime.py')])
+ coverage.start()
+sys.path.insert(0, str(STORE/'tools'))
+import studio_runtime as runtime
+
+CONFIG = {'title':'Test studio', 'controls':[
+ {'id':'steps','label':'Steps','type':'number','value':2,'min':1,'max':5,'integer':True},
+ {'id':'shape','label':'Shape','type':'select','value':'round','options':[{'value':'round'},{'value':'square'}]},
+ {'id':'text','label':'Text','type':'text','value':'hello','maxLength':8}], 'actions':[{'id':'make'}]}
+
+class RunnerTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory(prefix='studio-runtime-')
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name).resolve()
+ self.workspace = self.root/'workspace'; self.workspace.mkdir()
+ self.package = self.root/'package'; self.package.mkdir()
+ (self.package/'studio.config.json').write_text(json.dumps(CONFIG))
+ (self.package/'upstream.lock.json').write_text('[]')
+ (self.workspace/'studio.json').write_text(json.dumps({'parameters':{}}))
+ self.enterContext(patch.dict(os.environ, HARNESS_WORKSPACE=str(self.workspace)))
+ self.enterContext(patch.object(runtime,'__file__',str(self.package/'toolchain/studio_runtime.py')))
+ self.enterContext(patch.object(sys,'argv',['run']))
+
+ def call(self, action=None):
+ def make(p, out):
+ (out/'hello.txt').write_text('A real artifact')
+ return {'title':'Done', 'engine':'Test', 'metrics':[runtime.metric('Count',2)],
+ 'files':[{'label':'Text','name':'hello.txt'}]}
+ with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
+ runtime.execute({'make':action or make})
+
+ def test_successful_runs_are_immutable_and_failed_runs_preserve_latest(self):
+ self.call()
+ first=(self.workspace/'out/latest.json').read_bytes()
+ result=json.loads(first)
+ self.assertTrue((self.workspace/result['artifacts'][0]['path']).is_file())
+ self.assertEqual(result['parameters'],{'steps':2,'shape':'round','text':'hello'})
+ self.assertTrue(json.loads((self.workspace/'.harness/verdict.json').read_text())['ready'])
+ def fail(p,out): raise RuntimeError('Please choose another idea')
+ with self.assertRaises(SystemExit): self.call(fail)
+ self.assertEqual((self.workspace/'out/latest.json').read_bytes(), first)
+ verdict=json.loads((self.workspace/'.harness/verdict.json').read_text())
+ self.assertFalse(verdict['ready']); self.assertIn('choose another',verdict['summary'])
+ self.call()
+ self.assertEqual(len(runtime.previous_runs()),2)
+ broken=self.workspace/'out/runs/broken'; broken.mkdir(); (broken/'result.json').write_text('partial')
+ (self.root/'secret').write_text('{}')
+ outside=self.workspace/'out/runs/outside'; outside.mkdir(); (outside/'result.json').symlink_to(self.root/'secret')
+ self.assertEqual(len(runtime.previous_runs()),2)
+
+ def test_input_failures_produce_actionable_verdicts(self):
+ for argv,content in [(['run','unknown'],'{}'), (['run'],'x'*16385), (['run'],'broken'),
+ (['run'],'{}'), (['run'],'{"parameters":{"steps":false}}')]:
+ with self.subTest(argv=argv,content=content[:30]):
+ (self.workspace/'studio.json').write_text(content)
+ with patch.object(sys,'argv',argv), self.assertRaises(SystemExit): self.call()
+ self.assertFalse(json.loads((self.workspace/'.harness/verdict.json').read_text())['ready'])
+ (self.workspace/'studio.json').unlink()
+ with self.assertRaises(SystemExit): self.call()
+
+ def test_rejects_missing_empty_and_escaping_artifacts(self):
+ for name in ['missing.txt','../outside.txt','../../../outside.txt']:
+ with self.subTest(name=name), self.assertRaises(SystemExit):
+ self.call(lambda p,out: {'files':[{'label':'Output','name':name}]})
+ def empty(p,out):
+ (out/'empty').touch()
+ return {'files':[{'label':'Empty','name':'empty'}]}
+ with self.assertRaises(SystemExit): self.call(empty)
+ self.assertFalse((self.workspace/'out/latest.json').exists())
+
+ def test_confinement_and_atomic_writes(self):
+ target=self.workspace/'state.json'
+ runtime.atomic_json(target,{'value':1})
+ with self.assertRaises(ValueError): runtime.atomic_json(target,{'value':math.nan})
+ self.assertEqual(json.loads(target.read_text()),{'value':1})
+ self.assertEqual(list(self.workspace.glob('.studio-*')),[])
+ with self.assertRaises(ValueError): runtime.contained(self.root/'secret')
+ (self.workspace/'escape').symlink_to(self.root,target_is_directory=True)
+ with self.assertRaises(ValueError): runtime.atomic_json(self.workspace/'escape/secret',{})
+ (self.workspace/'.harness').symlink_to(self.root,target_is_directory=True)
+ with self.assertRaises(SystemExit): self.call()
+ self.assertFalse((self.root/'verdict.json').exists())
+
+ def test_control_types_and_boundaries(self):
+ self.assertEqual(runtime.parameters(CONFIG,{'steps':1})['steps'],1)
+ self.assertEqual(runtime.parameters(CONFIG,{'steps':5})['steps'],5)
+ for value in [[],None,{'extra':1},{'steps':True},{'steps':None},{'steps':'2'},
+ {'steps':math.inf},{'steps':0},{'steps':2.5},{'shape':'other'},{'text':1},{'text':'a'*9}]:
+ with self.subTest(value=value), self.assertRaises(ValueError): runtime.parameters(CONFIG,value)
+ self.assertEqual(runtime.metric('X',1,'m'),{'label':'X','value':1,'unit':'m'})
+
+ def test_commands_capture_logs_and_bound_runtime(self):
+ self.assertEqual(runtime.command([sys.executable,'-c','print("hello")']).strip(),'hello')
+ for code in ['import sys;print("helpful",file=sys.stderr);sys.exit(2)','import sys;print("output");sys.exit(2)','raise SystemExit(3)']:
+ with self.assertRaises(RuntimeError): runtime.command([sys.executable,'-c',code])
+ with self.assertRaises(subprocess.TimeoutExpired):
+ runtime.command([sys.executable,'-c','import time;time.sleep(10)'],timeout=.05)
+
+if __name__=='__main__':
+ result=unittest.TextTestRunner(verbosity=2).run(unittest.defaultTestLoader.loadTestsFromTestCase(RunnerTests))
+ if coverage:
+ coverage.stop(); coverage.json_report(outfile=str(Path(__file__).resolve().parent.parent/'test-results/runtime-python-coverage.json'))
+ sys.exit(not result.wasSuccessful())
diff --git a/store/viewers/studio-viewer/test/viewer.test.mjs b/store/viewers/studio-viewer/test/viewer.test.mjs
index 4f0e3e4d5..f08ac849f 100644
--- a/store/viewers/studio-viewer/test/viewer.test.mjs
+++ b/store/viewers/studio-viewer/test/viewer.test.mjs
@@ -1,6 +1,9 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
-import {mkdtemp,mkdir,writeFile,readFile,symlink,rm,realpath} from 'node:fs/promises';
+import {mkdtemp,mkdir,writeFile,readFile,symlink,rm,realpath,open} from 'node:fs/promises';
+import {spawn} from 'node:child_process';
+import {once} from 'node:events';
+import {fileURLToPath} from 'node:url';
import http from 'node:http';
import {tmpdir} from 'node:os';
import {join} from 'node:path';
@@ -8,7 +11,7 @@ import {createStudio,confined,validateParameters} from '../server.mjs';
const config={title:'Test studio',controls:[{id:'speed',label:'Speed',type:'number',value:2,min:1,max:5,integer:true},{id:'mode',label:'Mode',type:'select',value:'a',options:[{value:'a'},{value:'b'}]},{id:'name',label:'Name',type:'text',value:'hello',maxLength:20}],actions:[{id:'run',label:'Make'}]};
const project={spec:1,parameters:{speed:2,mode:'a',name:'hello'}};
-async function fixture(t,script='exit 0',jobTimeout=1000){
+async function fixture(t,script='exit 0',jobTimeout=10000){
const root=await realpath(await mkdtemp(join(tmpdir(),'studio-test-'))),workspace=join(root,'workspace'),packageDir=join(root,'package');
await mkdir(workspace);await mkdir(join(packageDir,'toolchain'),{recursive:true});
await writeFile(join(workspace,'studio.json'),JSON.stringify(project));
@@ -26,16 +29,16 @@ async function until(get,predicate){for(let i=0;i<150;i++){const v=await get();i
test('controls reject invalid input, retain defaults, and enforce native types',()=>{
assert.deepEqual(validateParameters(config,{}),project.parameters);
- for(const p of [null,[],2,{extra:1},{speed:NaN},{speed:'2'},{speed:0},{speed:1.2},{mode:'c'},{name:2},{name:'x'.repeat(21)}])assert.throws(()=>validateParameters(config,p),e=>e.status===400);
+ for(const p of [null,[],2,{extra:1},{speed:NaN},{speed:null},{speed:'2'},{speed:0},{speed:1.2},{mode:'c'},{name:2},{name:'x'.repeat(21)}])assert.throws(()=>validateParameters(config,p),e=>e.status===400);
assert.deepEqual(validateParameters(config,{speed:3,mode:'b',name:'there'}),{speed:3,mode:'b',name:'there'});
const simple={controls:[{id:'v',label:'Value',type:'text',value:''}]};
assert.throws(()=>validateParameters(simple,{v:'x'.repeat(501)}));
});
test('serves the complete local UI and only the installed domain module',async t=>{
const f=await fixture(t);
- for(const path of ['/','/studio.css','/tokens.css','/studio.mjs','/graphics.mjs','/domain.mjs'])assert.equal((await f.req(path)).status,200,path);
+ for(const path of ['/','/studio.css','/tokens.css','/studio.mjs','/graphics.mjs','/music.mjs','/domain.mjs'])assert.equal((await f.req(path)).status,200,path);
assert.equal((await f.req('/not-present')).status,404);
- assert.equal((await f.req('/%E0%A4%A')).status,500);
+ assert.equal((await f.req('/%E0%A4%A')).status,400);
const s=await f.state();assert.deepEqual(s.project,project);assert.deepEqual(s.history,[]);assert.equal(s.result,null);
const head=await fetch(f.studio.url+'/',{method:'HEAD'});assert.equal(await head.text(),'');
});
@@ -45,6 +48,7 @@ test('rejects cross-site requests, unsupported methods, invalid JSON, unknown ac
const wrongHost=await new Promise((ok,fail)=>{const r=http.get(f.studio.url,{headers:{Host:'evil.example'}},res=>{res.resume();res.on('end',()=>ok(res.statusCode));});r.on('error',fail);});
assert.equal(wrongHost,403);
assert.equal((await f.req('/api/run','abc')).status,400);
+ for(const input of ['null','[]','2'])assert.equal((await f.req('/api/run',input)).status,400);
assert.equal((await f.req('/api/run','x'.repeat(17000))).status,413);
assert.equal((await f.req('/api/run',{}, {'Content-Type':'text/plain'})).status,415);
assert.equal((await f.req('/api/run',{action:'bad'})).status,400);
@@ -70,7 +74,16 @@ test('failed, cancelled, and timed-out jobs retain the previous artifact',async
test('records successful history, reads chosen runs, ignores incomplete results',async t=>{
const f=await fixture(t);await mkdir(join(f.workspace,'out/runs/first'),{recursive:true});await mkdir(join(f.workspace,'out/runs/incomplete'));await mkdir(join(f.workspace,'out/runs/broken'));
await writeFile(join(f.workspace,'out/runs/first/result.json'),JSON.stringify({id:'first',title:'My run',metrics:[],engine:'actual'}));await writeFile(join(f.workspace,'out/runs/broken/result.json'),'not json');
- assert.equal((await f.state()).history.length,1);assert.equal((await f.req('/api/run?id=first')).status,200);assert.equal((await f.req('/api/run?id=../studio')).status,400);assert.equal((await f.req('/api/run?id=missing')).status,404);
+ assert.equal((await f.state()).history.length,1);assert.equal((await f.req('/api/run?id=first')).status,200);assert.equal((await f.req('/api/run')).status,400);assert.equal((await f.req('/api/run?id=../studio')).status,400);assert.equal((await f.req('/api/run?id=missing')).status,404);
+ await writeFile(join(f.workspace,'out/latest.json'),'unfinished');assert.equal((await f.req('/api/state')).status,500);
+});
+
+test('cancellation also works when the platform cannot signal a process group',async t=>{
+ const f=await fixture(t,'sleep 10');await f.run();
+ const kill=process.kill;
+ t.mock.method(process,'kill',(pid,signal)=>{if(pid<0)throw Error('process groups unavailable');return kill(pid,signal);});
+ assert.equal((await f.req('/api/cancel',{})).status,200);
+ await until(f.state,s=>s.job.status==='cancelled');
});
test('confines files after symlink resolution and serves artifact downloads',async t=>{
const f=await fixture(t);await mkdir(join(f.workspace,'out'));await writeFile(join(f.root,'secret.txt'),'private');await symlink(join(f.root,'secret.txt'),join(f.workspace,'out/escape.txt'));
@@ -83,3 +96,41 @@ test('confines files after symlink resolution and serves artifact downloads',asy
test('rejects oversized and malformed state without disclosing filesystem paths',async t=>{
const f=await fixture(t);await writeFile(join(f.workspace,'studio.json'),'x'.repeat(8*1024*1024+1));assert.equal((await f.req('/api/state')).status,413);await writeFile(join(f.workspace,'studio.json'),'broken');const r=await f.req('/api/state');assert.equal(r.status,500);assert.ok(!r.data.includes(f.workspace));
});
+
+test('simultaneous submissions start exactly one process',async t=>{
+ const f=await fixture(t,'echo started; sleep 0.5');
+ const revision=(await f.state()).revision;
+ const results=await Promise.all(Array.from({length:8},()=>f.req('/api/run',{action:'run',parameters:project.parameters,revision})));
+ assert.equal(results.filter(r=>r.status===202).length,1);
+ assert.equal(results.filter(r=>r.status===409).length,7);
+ await until(f.state,s=>s.job.status==='done');
+ assert.equal((await f.state()).job.log.trim(),'started');
+});
+
+test('missing executable and corrupt history surface errors and retain the workspace',async t=>{
+ const f=await fixture(t);
+ await writeFile(join(f.packageDir,'toolchain/run.sh'),'#!/definitely-not-an-interpreter\n');
+ assert.equal((await f.run()).status,202);
+ const failed=await until(f.state,s=>s.job.status==='failed');assert.match(failed.job.message,/ENOENT/);
+ assert.deepEqual(JSON.parse(await readFile(join(f.workspace,'studio.json'),'utf8')),project);
+ await mkdir(join(f.root,'outside'));await mkdir(join(f.workspace,'out'));
+ await symlink(join(f.root,'outside'),join(f.workspace,'out/runs'));
+ assert.equal((await f.req('/api/state')).status,403);
+});
+
+test('bounds output size and handles JSON HEAD downloads',async t=>{
+ const f=await fixture(t);await mkdir(join(f.workspace,'out'));
+ const file=await open(join(f.workspace,'out/large.bin'),'w');await file.truncate(256*1024*1024+1);await file.close();
+ assert.equal((await f.req('/artifacts/out/large.bin')).status,413);
+ await writeFile(join(f.workspace,'out/record.json'),'{"answer":42}');
+ const head=await fetch(f.studio.url+'/artifacts/out/record.json',{method:'HEAD'});assert.equal(head.status,200);assert.equal(await head.text(),'');
+});
+
+test('manifest server entry point starts, serves a workspace, and stops cleanly',async t=>{
+ const f=await fixture(t);
+ const child=spawn(process.execPath,[fileURLToPath(new URL('../server.mjs',import.meta.url))],{env:{...process.env,HARNESS_WORKSPACE:f.workspace,HARNESS_DSH_DIR:f.packageDir,HARNESS_VIEWER_PORT:'0'},stdio:['ignore','pipe','pipe']});
+ t.after(()=>child.kill());
+ const [data]=await once(child.stdout,'data');const url=data.toString().match(/http:\/\/127\.0\.0\.1:\d+/)[0];
+ assert.equal((await fetch(url+'/api/state')).status,200);
+ const exited=once(child,'exit');child.kill('SIGTERM');assert.deepEqual(await exited,[0,null]);
+});
diff --git a/store/viewers/studio-viewer/test/workflows_test.py b/store/viewers/studio-viewer/test/workflows_test.py
new file mode 100644
index 000000000..684b87d2a
--- /dev/null
+++ b/store/viewers/studio-viewer/test/workflows_test.py
@@ -0,0 +1,345 @@
+"""Measured local artifacts plus isolated contracts for optional native integrations.
+
+Run once per package with that package's Python, preserving its actual native libraries.
+Socket responders below are protocol fixtures, never evidence of a live application.
+"""
+import array
+import base64
+import contextlib
+import csv
+import hashlib
+import importlib.util
+import io
+import json
+import math
+import os
+from pathlib import Path
+import runpy
+import shutil
+import socket
+import struct
+import sys
+import tempfile
+import threading
+import unittest
+import wave
+import xml.etree.ElementTree as ET
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from unittest.mock import patch
+
+STORE = Path(__file__).resolve().parents[3]
+NAME = os.environ['STUDIO_TEST_PACKAGE']
+PACKAGE = STORE/'agents'/NAME
+coverage = None
+if os.environ.get('STUDIO_COVERAGE'):
+ from coverage import Coverage
+ coverage = Coverage(branch=True,data_file=None,include=[str(PACKAGE/'toolchain/workflow.py'),str(PACKAGE/'template/train.py')])
+ coverage.start()
+sys.path.insert(0,str(PACKAGE/'toolchain'))
+import workflow as w
+
+def tcp_responder(reply, framed=False):
+ listener=socket.socket();listener.bind(('127.0.0.1',0));listener.listen();listener.settimeout(5)
+ requests=[];errors=[]
+ def receive(conn,n):
+ data=b''
+ while len(data)<n:
+ chunk=conn.recv(n-len(data))
+ if not chunk:raise RuntimeError('Incomplete fixture request')
+ data+=chunk
+ return data
+ def serve():
+ try:
+ conn,_=listener.accept()
+ with conn:
+ conn.settimeout(5)
+ payload=receive(conn,struct.unpack('>I',receive(conn,4))[0]) if framed else conn.recv(65536)
+ request=json.loads(payload);requests.append(request)
+ answer=reply(request);data=json.dumps(answer).encode()
+ if framed:data=struct.pack('>I',len(data))+data
+ # Fragment the reply to exercise the actual upstream transport.
+ conn.sendall(data[:3]);conn.sendall(data[3:])
+ except Exception as exc:errors.append(exc)
+ thread=threading.Thread(target=serve,daemon=True);thread.start()
+ try:yield listener.getsockname()[1],requests
+ finally:
+ listener.close();thread.join(6)
+ if errors:raise errors[0]
+
+class StudioCase(unittest.TestCase):
+ def setUp(self):
+ temp=tempfile.TemporaryDirectory(prefix='studio-domain-');self.addCleanup(temp.cleanup)
+ self.root=Path(temp.name).resolve();self.workspace=self.root/'workspace'
+ shutil.copytree(PACKAGE/'template',self.workspace)
+ self.p=json.loads((self.workspace/'studio.json').read_text())['parameters']
+ self.enterContext(patch.dict(os.environ,HARNESS_WORKSPACE=str(self.workspace)))
+ self.counter=0
+ def output(self):
+ self.counter+=1;out=self.workspace/'out'/f'check-{self.counter}';out.mkdir(parents=True);return out
+ def action(self,name,**changes):
+ p={**self.p,**changes};project=json.loads((self.workspace/'studio.json').read_text());project['parameters']=p
+ (self.workspace/'studio.json').write_text(json.dumps(project));out=self.output()
+ with contextlib.redirect_stdout(io.StringIO()):result=getattr(w,name)(p,out)
+ for item in result['files']:self.assertGreater((out/item['name']).stat().st_size,0)
+ json.dumps(result,allow_nan=False)
+ return result,out
+ def test_real_command_entry_point(self):
+ with patch.object(sys,'argv',['run']),contextlib.redirect_stdout(io.StringIO()):
+ runpy.run_path(str(PACKAGE/'toolchain/workflow.py'),run_name='__main__')
+ verdict=json.loads((self.workspace/'.harness/verdict.json').read_text())
+ self.assertTrue(verdict['ready']);self.assertTrue((self.workspace/verdict['artifact']).is_file())
+
+class Instrument(StudioCase):
+ @unittest.skipUnless(os.environ.get('STUDIO_NATIVE_JUCE_WORKSPACE'),'Set STUDIO_NATIVE_JUCE_WORKSPACE for a real native compiler check')
+ def test_native_juce_produces_measured_audio(self):
+ native=Path(os.environ['STUDIO_NATIVE_JUCE_WORKSPACE']).resolve()
+ with patch.dict(os.environ,HARNESS_WORKSPACE=str(native)),contextlib.redirect_stdout(io.StringIO()):
+ out=native/'out/native-validation';out.mkdir(parents=True,exist_ok=True)
+ for shape in ['sine','triangle','saw']:
+ result=w.juce({**self.p,'wave':shape,'duration':1},out)
+ self.assertEqual(result['engine'],'Native JUCE · offline instrument')
+ self.assertGreater(max(abs(x) for x in result['data']['waveform']),.05)
+ def test_waveforms_have_audio_and_correct_rate_without_clipping(self):
+ digests=[]
+ for shape in ['sine','triangle','saw']:
+ result,out=self.action('render',wave=shape,duration=1)
+ with wave.open(str(out/'phrase.wav')) as f:
+ self.assertEqual((f.getnchannels(),f.getsampwidth(),f.getframerate(),f.getnframes()),(1,2,44100,44100))
+ samples=array.array('h',f.readframes(f.getnframes()))
+ self.assertGreater(max(samples),1000);self.assertLess(max(abs(x) for x in samples),32760)
+ self.assertAlmostEqual(samples[0],0,delta=2);digests.append(hashlib.sha256((out/'phrase.wav').read_bytes()).hexdigest())
+ self.assertEqual(len(set(digests)),3)
+ def test_bad_audio_and_missing_native_source_fail(self):
+ for channels,width,frames in [(2,2,b'\0'*8),(1,1,b'\0'*8),(1,2,b''),(1,2,struct.pack('<h',32767))]:
+ out=self.output()
+ with wave.open(str(out/'phrase.wav'),'wb') as f:
+ f.setnchannels(channels);f.setsampwidth(width);f.setframerate(44100);f.writeframes(frames)
+ with self.assertRaises(ValueError):w.summarize(self.p,out,'Test')
+ (self.workspace/'CMakeLists.txt').unlink()
+ with self.assertRaisesRegex(RuntimeError,'CMakeLists'):w.juce(self.p,self.output())
+
+class Flow(StudioCase):
+ def test_three_geometries_export_finite_fields_with_solid_boundaries(self):
+ import numpy as np
+ shapes=[]
+ for shape in ['circle','square','ellipse']:
+ r,out=self.action('simulate',shape=shape,steps=80)
+ field=np.loadtxt(out/'flow.csv',delimiter=',',skiprows=1)
+ self.assertEqual(field.shape,(120*56,6));self.assertTrue(np.isfinite(field).all())
+ solid=field[:,5]==1;self.assertTrue(np.allclose(field[solid,2:4],0))
+ self.assertGreater(field[~solid,2].max(),0);shapes.append(int(solid.sum()))
+ self.assertEqual(r['data']['ux'],json.loads((out/'field.json').read_text())['ux'])
+ self.assertEqual(len(set(shapes)),3)
+ def test_instability_and_missing_openfoam_are_explicit(self):
+ import numpy as np
+ with patch.object(w.np,'isfinite',return_value=np.array([False])),self.assertRaisesRegex(RuntimeError,'unstable'):
+ self.action('simulate',steps=80)
+ with patch.object(w.shutil,'which',return_value=None),self.assertRaisesRegex(RuntimeError,'OpenFOAM'):
+ w.openfoam(self.p,self.output())
+ def test_openfoam_adapter_requires_final_field(self):
+ def command(argv,**kwargs):
+ if argv[0]=='icoFoam':
+ final=Path(argv[-1])/'0.5';final.mkdir();(final/'U').write_text('fixture velocity field')
+ return 'fixture solver log'
+ with patch.object(w.shutil,'which',return_value='/fixture/tool'),patch.object(w,'command',side_effect=command):
+ result,out=self.action('openfoam');self.assertTrue((out/'cavity.zip').is_file())
+ with patch.object(w.shutil,'which',return_value='/fixture/tool'),patch.object(w,'command',return_value=''):
+ with self.assertRaisesRegex(RuntimeError,'final velocity'):w.openfoam(self.p,self.output())
+ shutil.rmtree(self.workspace/'openfoam-cavity')
+ with self.assertRaisesRegex(RuntimeError,'benchmark'):w.openfoam(self.p,self.output())
+
+class Research(StudioCase):
+ def test_saved_model_is_independently_evaluated_and_comparisons_keep_data_fixed(self):
+ import numpy as np
+ result,out=self.action('train',steps=40)
+ with np.load(out/'model.npz',allow_pickle=False) as model:
+ score=w.evaluate(model,(self.workspace/'holdout.txt').read_text())
+ self.assertAlmostEqual(score,result['data']['heldoutBpc'])
+ self.assertGreater(result['data']['curve'][0][1],result['data']['curve'][-1][1])
+ for prior,expected in [(score+1,'New best'),(score-1,'Keep exploring')]:
+ r={**result,'action':'train','data':{**result['data'],'heldoutBpc':prior}}
+ history=self.workspace/'out/runs/previous';history.mkdir(parents=True,exist_ok=True);(history/'result.json').write_text(json.dumps(r))
+ next_result,_=self.action('train',steps=40);self.assertEqual(next_result['data']['status'],expected)
+ (self.workspace/'holdout.txt').write_text('a different held out phrase')
+ changed,_=self.action('train',steps=40);self.assertEqual(changed['data']['status'],'First baseline')
+ def test_model_and_training_validation(self):
+ import numpy as np
+ source=runpy.run_path(str(PACKAGE/'template/train.py'));out=self.output()
+ source['fit']('abcabcaabbcc'*4,{**self.p,'steps':11},out)
+ old=Path.cwd()
+ try:
+ os.chdir(self.workspace)
+ with patch.object(sys,'argv',['train.py',str(self.output())]):runpy.run_path(str(PACKAGE/'template/train.py'),run_name='__main__')
+ finally:os.chdir(old)
+ with np.load(out/'model.npz',allow_pickle=False) as model:
+ data={key:model[key] for key in model.files}
+ self.assertTrue(math.isfinite(w.evaluate(model,'abc!abc!')))
+ with self.assertRaisesRegex(ValueError,'short'):w.evaluate(model,'')
+ data['probabilities'][0,0]=-1
+ with self.assertRaisesRegex(ValueError,'probabilities'):w.evaluate(data,'abc')
+ result,out=self.action('train',steps=40)
+ (out/'training.json').write_text('{"curve":[]}')
+ with patch.object(w,'command',return_value=''),self.assertRaisesRegex(ValueError,'curve'):w.train(self.p,out)
+ (self.workspace/'train.txt').unlink()
+ with self.assertRaisesRegex(RuntimeError,'train.txt'):w.train(self.p,self.output())
+ def test_native_mlx_adapter_gates_platform_preparation_and_metrics(self):
+ with patch.object(w.platform,'system',return_value='Linux'),self.assertRaisesRegex(RuntimeError,'Apple Silicon'):w.mlx(self.p,self.output())
+ with patch.object(w.platform,'system',return_value='Darwin'),patch.object(w.platform,'machine',return_value='arm64'):
+ with self.assertRaisesRegex(RuntimeError,'Prepare'):w.mlx(self.p,self.output())
+ root=self.workspace/'mlx';(root/'.venv/bin').mkdir(parents=True);(root/'.venv/bin/python').touch();(root/'train.py').touch()
+ with patch.object(w,'command',return_value='val_bpb: 1.25'):
+ r,_=self.action('mlx');self.assertEqual(r['metrics'][0]['value'],1.25)
+ with patch.object(w,'command',return_value='no score'),self.assertRaisesRegex(RuntimeError,'val_bpb'):w.mlx(self.p,self.output())
+
+class Music(StudioCase):
+ def test_midi_and_wav_contain_the_saved_events(self):
+ for scale in ['major','minor','pentatonic']:
+ r,out=self.action('render',scale=scale,pattern='1001001001001001',swing=.3)
+ midi=(out/'loop.mid').read_bytes();self.assertEqual(midi[:4],b'MThd');self.assertEqual(struct.unpack('>H',midi[12:14])[0],480)
+ self.assertEqual(int.from_bytes(midi[18:22],'big'),len(midi)-22)
+ self.assertEqual(r['data']['notes'],json.loads((out/'notes.json').read_text()))
+ for n in r['data']['notes']:self.assertIn(bytes([0x90,n['note'],n['velocity']]),midi)
+ with wave.open(str(out/'loop.wav')) as f:self.assertEqual(f.getframerate(),22050);self.assertGreater(f.getnframes(),22050)
+ silent,out=self.action('render',pattern='0'*16);self.assertEqual(silent['data']['notes'],[])
+ with wave.open(str(out/'loop.wav')) as f:self.assertEqual(set(f.readframes(f.getnframes())),{0})
+ with self.assertRaisesRegex(ValueError,'sixteen'):w.notes({**self.p,'pattern':'x'})
+ self.assertEqual(w.variable_length(0),b'\x00');self.assertEqual(w.variable_length(128),b'\x81\x00')
+ def test_ableton_uses_pinned_transport_and_only_reads_session_state(self):
+ for success in [True,False]:
+ response=lambda request:{'status':'success','result':{'tempo':123,'tracks':[{'name':'Piano'}]}} if success else {'status':'error','message':'Fixture session unavailable'}
+ with tcp_responder(response) as (port,requests),patch.dict(os.environ,ABLETON_HOST='127.0.0.1',ABLETON_PORT=str(port)):
+ if success:
+ r,_=self.action('live');self.assertEqual(r['data']['session']['tempo'],123)
+ else:
+ with self.assertRaisesRegex(RuntimeError,'Fixture session unavailable'):w.live(self.p,self.output())
+ self.assertEqual(requests,[{'type':'get_session_info','params':{}}])
+
+class Robot(StudioCase):
+ def test_actual_dynamics_reach_open_goals_in_both_layouts(self):
+ for layout,goal in [('office',(8,7)),('gallery',(8,5)),('office',(1,1))]:
+ r,out=self.action('simulate',layout=layout,goal_x=goal[0],goal_y=goal[1])
+ data=r['data'];self.assertTrue(data['success']);self.assertEqual(data['contacts'],0)
+ self.assertLess(math.dist(data['positions'][-1][1:],goal),.13)
+ self.assertEqual(ET.parse(out/'mission.xml').getroot().tag,'mujoco')
+ def test_bad_goals_unreachable_routes_and_failed_dynamics(self):
+ with self.assertRaisesRegex(ValueError,'inside a wall'):w.plan([4,3],w.obstacles('office'))
+ with self.assertRaisesRegex(ValueError,'no clear route'):w.plan([8,8],[[5,5,20,1]])
+ with patch.object(w.mujoco,'mj_step',return_value=None),self.assertRaisesRegex(RuntimeError,'budget'):
+ w.simulate(self.p,self.output())
+ def test_native_status_never_sends_motion(self):
+ with patch.object(w.shutil,'which',return_value=None),self.assertRaisesRegex(RuntimeError,'not installed'):w.dimos(self.p,self.output())
+ with patch.object(w.shutil,'which',return_value='/fixture/dimos'),patch.object(w,'command',return_value='Fixture daemon ready') as command:
+ r,_=self.action('dimos');command.assert_called_once_with(['/fixture/dimos','status'],timeout=15)
+
+class City(StudioCase):
+ def test_measured_trips_and_light_phases_follow_the_selected_plan(self):
+ summaries=[]
+ for green in [10,70]:
+ r,out=self.action('simulate',green=green,duration=120,demand=360)
+ data=r['data'];self.assertGreater(data['finished'],0);self.assertGreater(len(data['frames']),10)
+ with (out/'trips.csv').open() as f:rows=list(csv.DictReader(f))
+ finished=[row for row in rows if row['finished']=='True']
+ self.assertEqual(data['finished'],len(finished))
+ self.assertAlmostEqual(r['metrics'][0]['value'],round(sum(float(row['time_loss']) for row in finished)/len(finished),1))
+ network=ET.parse(out/'city.net.xml');links=[int(c.get('linkIndex')) for c in network.findall('connection') if c.get('tl')=='C' and c.get('from') in ['WC','EC'] and c.get('dir')=='s']
+ self.assertTrue(links)
+ for phase in data['phases']:
+ if 'y' not in phase['state'].lower() and any(phase['state'][i] in 'Gg' for i in links):self.assertEqual(float(phase['duration']),green)
+ summaries.append(data)
+ self.assertNotEqual(summaries[0]['frames'],summaries[1]['frames'])
+ def test_native_tool_failures_never_become_empty_successes(self):
+ def broken(argv,**kwargs):
+ out=Path(argv[argv.index('--output-file')+1]);out.write_text('<net/>');return ''
+ with patch.object(w,'command',side_effect=broken),self.assertRaisesRegex(RuntimeError,'traffic light'):w.simulate(self.p,self.output())
+ real=w.command
+ def no_trips(argv,**kwargs):
+ result=real(argv,**kwargs)
+ if '--tripinfo-output' in argv:Path(argv[argv.index('--tripinfo-output')+1]).write_text('<tripinfos/>')
+ return result
+ with patch.object(w,'command',side_effect=no_trips),self.assertRaisesRegex(RuntimeError,'No trips'):w.simulate({**self.p,'duration':120},self.output())
+
+class Building(StudioCase):
+ def test_incomplete_ifc_readback_is_rejected(self):
+ original=w.ifcopenshell.open
+ def missing_space(path):
+ model=original(path);model.remove(model.by_type('IfcSpace')[0]);return model
+ with patch.object(w.ifcopenshell,'open',side_effect=missing_space),self.assertRaisesRegex(RuntimeError,'read-back'):self.action('build',storeys=1)
+ def test_ifc_quantities_openings_and_spaces_survive_readback(self):
+ for use,storeys in [('studio',1),('home',3)]:
+ r,out=self.action('build',use=use,storeys=storeys)
+ f=w.ifcopenshell.open(out/'building.ifc')
+ self.assertEqual(f.schema,'IFC4');self.assertEqual(len(f.by_type('IfcSpace')),storeys*2)
+ self.assertEqual(len(f.by_type('IfcWall')),storeys*5);self.assertEqual(len(f.by_type('IfcRelFillsElement')),storeys)
+ with (out/'quantities.csv').open() as stream:rows=list(csv.DictReader(stream))
+ total=sum(float(row['net_area_m2']) for row in rows)
+ self.assertAlmostEqual(total,r['data']['area']);self.assertGreater(total,0)
+ # Tessellation independently checks that the saved products have usable geometry.
+ import ifcopenshell.geom
+ settings=ifcopenshell.geom.settings()
+ shape=ifcopenshell.geom.create_shape(settings,f.by_type('IfcWall')[0]);self.assertGreater(len(shape.geometry.verts),0)
+ def test_bonsai_framed_transport_is_read_only_and_reports_errors(self):
+ for success in [True,False]:
+ def response(request):return {'id':request['id'],'success':success,'result':{'objects':[{'name':'Wall'}]},'error':None if success else 'Fixture bridge failed'}
+ with tcp_responder(response,framed=True) as (port,requests),patch.dict(os.environ,BONSAI_MCP_PORT=str(port),BONSAI_MCP_HOST='127.0.0.1'):
+ if success:
+ r,_=self.action('bonsai');self.assertEqual(r['data']['scene']['objects'][0]['name'],'Wall')
+ else:
+ with self.assertRaisesRegex(RuntimeError,'Fixture bridge failed'):w.bonsai(self.p,self.output())
+ self.assertEqual(requests[0]['command'],'get_scene_info');self.assertEqual(requests[0]['params'],{'limit':50})
+
+class Images(StudioCase):
+ def test_every_palette_has_reproducible_valid_artwork_and_hashes(self):
+ for palette in ['orchard','dusk','citrus']:
+ r,out=self.action('generate',palette=palette,variations=2)
+ recipe=json.loads((out/'recipe.json').read_text());self.assertEqual(len(recipe['images']),2)
+ for image in recipe['images']:
+ content=(out/image['name']).read_bytes();self.assertEqual(hashlib.sha256(content).hexdigest(),image['sha256'])
+ self.assertEqual(ET.fromstring(content).get('viewBox'),'0 0 640 640')
+ self.assertEqual(content.decode(),w.artwork(recipe['parameters'],image['seed']))
+ def test_comfy_validation_and_connection_errors(self):
+ for url in ['https://127.0.0.1:8188','http://example.com','http://u:p@localhost:8188','http://localhost:8188/path','http://localhost:8188?x=1','http://localhost:8188#fragment']:
+ with patch.dict(os.environ,COMFYUI_URL=url),self.assertRaisesRegex(ValueError,'loopback'):w.comfy(self.p,self.output())
+ for content in ['{}','[]','{"1":{}}',' '*1000001]:
+ (self.workspace/'workflow.json').write_text(content)
+ with self.assertRaises(ValueError):w.comfy(self.p,self.output())
+ shutil.copy(PACKAGE/'template/workflow.json',self.workspace/'workflow.json')
+ listener=socket.socket();listener.bind(('127.0.0.1',0));port=listener.getsockname()[1];listener.close()
+ with patch.dict(os.environ,COMFYUI_URL=f'http://127.0.0.1:{port}'),self.assertRaisesRegex(RuntimeError,'Start local ComfyUI'):w.comfy(self.p,self.output())
+ def test_comfy_real_http_job_contract(self):
+ test=self;scenario={'mode':'success'};requests=[]
+ png=base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jT1sAAAAASUVORK5CYII=')
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self,*args):pass
+ def do_POST(self):
+ requests.append((self.path,json.loads(self.rfile.read(int(self.headers['Content-Length'])))))
+ if scenario['mode']=='reject':self.reply({'node_errors':{'1':'unknown node'}})
+ elif scenario['mode']=='redirect':self.send_response(302);self.send_header('Location','http://example.com/');self.end_headers()
+ else:self.reply({'prompt_id':'fixture-job','node_errors':{}})
+ def do_GET(self):
+ if self.path.startswith('/history/'):
+ mode=scenario['mode']
+ if mode=='timeout':self.reply({})
+ elif mode=='pending':self.reply({'fixture-job':{'status':{'status_str':'running'},'outputs':{}}})
+ elif mode=='execution':self.reply({'fixture-job':{'status':{'status_str':'error','messages':['fixture error']}}})
+ else:self.reply({'fixture-job':{'status':{'status_str':'success'},'outputs':{'2':{'images':[] if mode=='empty' else [{'filename':'fixture.png','subfolder':'','type':'output'}]}}}})
+ else:
+ content=b'x'*(32*1024*1024+1) if scenario['mode']=='oversize' else b'not a PNG' if scenario['mode']=='invalid' else png
+ self.send_response(200);self.end_headers();self.wfile.write(content)
+ def reply(self,data):self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(json.dumps(data).encode())
+ server=ThreadingHTTPServer(('127.0.0.1',0),Handler);thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start()
+ self.addCleanup(server.server_close);self.addCleanup(server.shutdown)
+ with patch.dict(os.environ,COMFYUI_URL=f'http://127.0.0.1:{server.server_port}',STUDIO_COMFY_TIMEOUT='.1'):
+ result,out=self.action('comfy');self.assertEqual((out/'comfy-1.png').read_bytes(),png)
+ self.assertEqual(requests[0][0],'/prompt');self.assertEqual(requests[0][1]['prompt'],json.loads((self.workspace/'workflow.json').read_text()))
+ for mode,message in [('reject','rejected'),('execution','execution failed'),('timeout','time limit'),('pending','time limit'),('empty','no images'),('invalid','PNG'),('redirect','redirect'),('oversize','download limit')]:
+ scenario['mode']=mode
+ with self.subTest(mode=mode),self.assertRaisesRegex(RuntimeError,message):w.comfy(self.p,self.output())
+
+CASES={'juce-agent-toolkit':Instrument,'foam-agent':Flow,'autoresearch-mlx':Research,
+ 'ableton-ai':Music,'dimos':Robot,'simskill':City,'bonsai-mcp':Building,'comfy-mcp':Images}
+if __name__=='__main__':
+ result=unittest.TextTestRunner(verbosity=2).run(unittest.defaultTestLoader.loadTestsFromTestCase(CASES[NAME]))
+ if coverage:
+ coverage.stop();coverage.json_report(outfile=str(Path(__file__).resolve().parent.parent/f'test-results/{NAME}-python-coverage.json'))
+ sys.exit(not result.wasSuccessful())
diff --git a/store/viewers/studio-viewer/web/index.html b/store/viewers/studio-viewer/web/index.html
index 1264d5ba7..5f7bc451a 100644
--- a/store/viewers/studio-viewer/web/index.html
+++ b/store/viewers/studio-viewer/web/index.html
@@ -3,7 +3,8 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
- <title>Harness Studio</title>
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 40 40%27%3E%3Crect width=%2740%27 height=%2740%27 rx=%2710%27 fill=%27%232b4034%27/%3E%3Ctext x=%2710%27 y=%2729%27 font-size=%2730%27 fill=%27%23eff1d5%27%3Eh%3C/text%3E%3C/svg%3E">
+<title>Harness Studio</title>
<link rel="stylesheet" href="/studio.css">
</head>
<body>
diff --git a/store/viewers/studio-viewer/web/music.mjs b/store/viewers/studio-viewer/web/music.mjs
new file mode 100644
index 000000000..5d77b0bcc
--- /dev/null
+++ b/store/viewers/studio-viewer/web/music.mjs
@@ -0,0 +1,19 @@
+// Deliberately identical to ableton-ai/toolchain/workflow.py::notes.
+// A shared fixture checks the browser audition against the exported note events.
+export function groove(p) {
+ let slots;
+ if (p.pattern) slots = [...p.pattern].flatMap((v, i) => v === '1' ? [i] : []);
+ else {
+ let state = p.seed;
+ slots = Array.from({length:16}, (_, i) => i);
+ for (let i = 15; i > 0; i--) {
+ state = (state * 1664525 + 1013904223) >>> 0;
+ const j = Math.floor(state / 4294967296 * (i + 1));
+ [slots[i], slots[j]] = [slots[j], slots[i]];
+ }
+ slots = slots.slice(0, p.density).sort((a, b) => a - b);
+ }
+ const scales = {minor:[0,3,5,7,10], major:[0,4,5,7,11], pentatonic:[0,2,4,7,9]};
+ return slots.map(s => ({step:s, note:48+scales[p.scale][(s+p.seed)%5],
+ velocity:75+(s*17+p.seed*13)%36, beat:s/4+(s%2?p.swing/4:0), length:.22}));
+}
diff --git a/store/viewers/studio-viewer/web/studio.css b/store/viewers/studio-viewer/web/studio.css
index 1ea8475f0..b06abf344 100644
--- a/store/viewers/studio-viewer/web/studio.css
+++ b/store/viewers/studio-viewer/web/studio.css
@@ -1,6 +1,8 @@
@import url('/tokens.css');
-*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}button,input,select{font:inherit}button,a,input,select{touch-action:manipulation}button,a{ -webkit-tap-highlight-color:transparent}button{cursor:pointer}button:disabled{cursor:wait;opacity:.55}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid var(--accent);outline-offset:4px}a{color:inherit}button{border:1px solid var(--line);border-radius:9px;padding:9px 13px;background:transparent;color:inherit;transition:background .15s,transform .15s}button:hover:enabled{background:var(--hover)}button:active:enabled{transform:translateY(1px)}[hidden]{display:none!important}#app{max-width:1600px;padding:0 30px;margin:auto}.topbar{height:66px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line)}.wordmark{text-decoration:none;font-size:10px;font-weight:750;letter-spacing:2px;display:flex;gap:9px;align-items:center}.mark{display:grid;place-items:center;width:24px;height:24px;background:var(--ink);color:var(--paper);border-radius:7px;font:italic 24px Georgia;letter-spacing:0}.muted{color:var(--muted)}.connection{font-size:11px;display:flex;align-items:center;gap:7px}.connection:before{content:"";width:6px;height:6px;background:var(--accent);border-radius:100%}.heading{display:flex;align-items:center;justify-content:space-between;gap:24px;padding:28px 0 24px}.eyebrow{font-size:9px;letter-spacing:2px;font-weight:750;color:var(--accent);margin:0 0 7px}h1{font-size:34px;line-height:1.12;letter-spacing:-1.2px;margin:0;font-weight:650}.description{color:var(--muted);max-width:640px;margin:9px 0 0;font-size:13px}.heading-actions{display:flex;align-items:center;gap:9px;flex-shrink:0}.primary{background:var(--accent);border-color:var(--accent);color:white;box-shadow:0 3px 7px #0000000d;white-space:nowrap;font-weight:650}.primary:hover:enabled{background:var(--accent);filter:brightness(1.08)}.quiet{border-color:transparent;color:var(--muted);font-size:12px}.workspace{display:grid;grid-template-columns:minmax(0,1fr) 264px;gap:24px}.canvas-column{min-width:0}.stage-frame{border-radius:16px;background:var(--stage);color:var(--stage-ink);overflow:hidden;box-shadow:0 4px 16px #00000008}.stage-heading{display:flex;justify-content:space-between;align-items:center;padding:15px 20px;font-size:9px;letter-spacing:1.7px;font-weight:600}.icon-button{font-size:10px;color:inherit;border-color:#ffffff24;padding:5px 8px;letter-spacing:0}.icon-button:hover:enabled{background:#ffffff15}.stage{position:relative;min-height:370px;isolation:isolate}.stage svg{display:block;width:100%;height:auto}.stage canvas{display:block;width:100%;height:370px}.stage-caption{display:flex;justify-content:space-between;align-items:center;gap:15px;padding:12px 20px;font-size:10px;color:#b2bcb9;border-top:1px solid #ffffff14}.stage-caption span:last-child{text-align:right;color:var(--stage-accent)}.metrics{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin:15px 0}.metric{padding:17px;background:var(--card);border:1px solid var(--line);border-radius:12px}.metric-label{font-size:10px;color:var(--muted)}.metric-value{display:block;font-size:23px;letter-spacing:-.6px;margin-top:4px}.metric-unit{font-size:11px;color:var(--muted);margin-left:5px;letter-spacing:0}.metric-label:before{content:"";display:inline-block;background:var(--accent);width:5px;height:5px;border-radius:50%;margin:0 6px 1px 0}.result-panel{padding:16px 2px}.panel-heading{display:flex;align-items:center;justify-content:space-between;gap:10px}h2{font-size:12px;font-weight:650;letter-spacing:-.15px;margin:0}.panel-heading .muted{font-size:10px}.result-panel>p{font-size:12px;margin:7px 0 14px}.artifacts{display:flex;flex-wrap:wrap;gap:8px}.artifact{display:inline-flex;align-items:center;gap:7px;text-decoration:none;border:1px solid var(--line);padding:7px 10px;background:var(--card);border-radius:8px;font-size:11px}.artifact:hover{border-color:var(--accent)}.inspector{border-left:1px solid var(--line);padding-left:24px}.small-label{font-size:8px;letter-spacing:1px;color:var(--muted)}#controls{margin:23px 0 10px}.control{display:block;margin-bottom:22px}.control-head{display:flex;justify-content:space-between;align-items:center;margin:0 0 9px;font-size:11px;font-weight:550}.control output{font-variant-numeric:tabular-nums;color:var(--accent);font-size:11px}.control input[type=range]{width:100%;accent-color:var(--accent);display:block;height:5px;cursor:ew-resize;margin:12px 0}.control select,.control input[type=text]{background:var(--card);border:1px solid var(--line);border-radius:8px;width:100%;padding:9px 10px;color:var(--ink);font-size:12px}.control small{display:block;color:var(--muted);font-size:10px;margin-top:6px}.extra-actions{display:flex;gap:8px;flex-direction:column}.extra-actions button{text-align:left;font-size:11px}.extra-actions button:before{content:'↗';margin-right:8px;color:var(--accent)}.tip{display:flex;gap:10px;background:var(--tint);padding:13px;border-radius:10px;margin:20px 0 27px}.spark{color:var(--accent);font-size:19px}.tip p{font-size:11px;margin:1px 0;color:var(--muted)}.history{list-style:none;margin:14px 0 0;padding:0}.history button{display:flex;align-items:center;width:100%;gap:10px;border:0;border-bottom:1px solid var(--line);border-radius:0;text-align:left;padding:12px 0;font-size:11px}.history button:hover:enabled{background:transparent;color:var(--accent)}.history button[aria-current=true]{color:var(--accent)}.history-dot{width:7px;height:7px;background:var(--accent);border-radius:50%;flex-shrink:0}.history-content{flex:1;min-width:0}.history-title{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.history-time{display:block;font-size:9px;color:var(--muted);margin-top:3px}.history-value{font-size:11px;font-variant-numeric:tabular-nums}.text-button{border:0;font-size:10px;padding:0;color:var(--accent)}.notice{border:1px solid var(--line);border-left:3px solid var(--accent);padding:11px 14px;margin-bottom:16px;background:var(--card);font-size:12px;border-radius:6px}.notice.error{border-left-color:#b84636;color:#8b382d}footer{border-top:1px solid var(--line);margin-top:30px;padding:16px 0;display:flex;justify-content:space-between;gap:12px;color:var(--muted);font-size:9px}pre{white-space:pre-wrap;word-break:break-word;max-height:160px;overflow:auto;font:11px/1.5 ui-monospace,monospace;background:var(--card);padding:12px;border-radius:8px}summary{font-size:11px;color:var(--muted);cursor:pointer;margin-top:15px}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.domain-toolbar{position:absolute;z-index:2;bottom:17px;left:20px;right:20px;display:flex;justify-content:center;gap:8px;flex-wrap:wrap}.domain-toolbar button{background:#ffffff10;border-color:#ffffff2e;color:var(--stage-ink);font-size:11px;padding:7px 12px}.domain-toolbar button:hover{background:#ffffff20}.domain-toolbar button[aria-pressed=true]{background:var(--stage-accent);color:var(--stage);border-color:transparent}.domain-label{position:absolute;z-index:1;left:22px;top:5px;max-width:70%;font-size:11px;color:#b6c5bd}.domain-badge{position:absolute;top:8px;right:20px;font-size:9px;letter-spacing:1px;border:1px solid #ffffff20;border-radius:20px;padding:5px 9px;color:var(--stage-accent)}.domain-readout{position:absolute;left:24px;bottom:70px;font-size:12px;color:var(--stage-accent)}.domain-readout strong{display:block;font-size:32px;font-weight:500;color:var(--stage-ink)}.keyboard{position:absolute;bottom:66px;left:12%;right:12%;height:95px;display:flex;gap:3px}.key{flex:1;background:#f6f0df;border:0;border-radius:0 0 7px 7px;color:#706856;display:flex;justify-content:center;align-items:end;padding-bottom:10px;font-size:10px;box-shadow:inset 0 -5px #ddd5bd}.key:hover:enabled,.key[aria-pressed=true]{background:var(--stage-accent);transform:translateY(2px)}.gallery{display:grid;grid-template-columns:repeat(2,1fr);gap:12px;padding:18px 25px 75px}.gallery button{padding:0;overflow:hidden;border:1px solid #ffffff24;border-radius:12px;background:#ffffff07}.gallery img{width:100%;height:145px;object-fit:cover;display:block}.gallery figcaption{padding:7px 10px;color:var(--stage-ink);font-size:10px;text-align:left}.gallery button[aria-pressed=true]{outline:2px solid var(--stage-accent);outline-offset:3px}.domain-dialog{position:absolute;inset:20px;background:var(--stage);border:1px solid #ffffff40;border-radius:14px;padding:20px;z-index:5;overflow:auto}.domain-dialog img{width:100%;max-height:280px;object-fit:contain}.domain-dialog button{float:right;color:var(--stage-ink)}.domain-empty{display:grid;place-items:center;min-height:300px;color:var(--stage-accent);font-size:13px;text-align:center;padding:35px}.chart-tooltip{position:absolute;top:12px;left:24px;font-size:11px;color:var(--stage-accent)}.row-buttons{display:flex;gap:7px}.comparison{color:var(--accent);font-size:11px;padding:10px 0}
+*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}button,input,select{font:inherit}button,a,input,select{touch-action:manipulation}button,a{ -webkit-tap-highlight-color:transparent}button{cursor:pointer}button:disabled{cursor:wait;opacity:.55}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid var(--accent);outline-offset:4px}a{color:inherit}button{border:1px solid var(--line);border-radius:9px;padding:9px 13px;background:transparent;color:inherit;transition:background .15s,transform .15s}button:hover:enabled{background:var(--hover)}button:active:enabled{transform:translateY(1px)}[hidden]{display:none!important}#app{max-width:1600px;padding:0 30px;margin:auto}.topbar{height:66px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line)}.wordmark{text-decoration:none;font-size:10px;font-weight:750;letter-spacing:2px;display:flex;gap:9px;align-items:center}.mark{display:grid;place-items:center;width:24px;height:24px;background:var(--ink);color:var(--paper);border-radius:7px;font:italic 24px Georgia;letter-spacing:0}.muted{color:var(--muted)}.connection{font-size:11px;display:flex;align-items:center;gap:7px}.connection:before{content:"";width:6px;height:6px;background:var(--accent);border-radius:100%}.heading{display:flex;align-items:center;justify-content:space-between;gap:24px;padding:28px 0 24px}.eyebrow{font-size:9px;letter-spacing:2px;font-weight:750;color:var(--accent);margin:0 0 7px}h1{font-size:34px;line-height:1.12;letter-spacing:-1.2px;margin:0;font-weight:650}.description{color:var(--muted);max-width:640px;margin:9px 0 0;font-size:13px}.heading-actions{display:flex;align-items:center;gap:9px;flex-shrink:0}.primary{background:var(--accent);border-color:var(--accent);color:white;box-shadow:0 3px 7px #0000000d;white-space:nowrap;font-weight:650}.primary:hover:enabled{background:var(--accent);filter:brightness(1.08)}.quiet{border-color:transparent;color:var(--muted);font-size:12px}.workspace{display:grid;grid-template-columns:minmax(0,1fr) 264px;gap:24px}.canvas-column{min-width:0}.stage-frame{border-radius:16px;background:var(--stage);color:var(--stage-ink);overflow:hidden;box-shadow:0 4px 16px #00000008}.stage-heading{display:flex;justify-content:space-between;align-items:center;padding:15px 20px;font-size:9px;letter-spacing:1.7px;font-weight:600}.icon-button{font-size:10px;color:inherit;border-color:#ffffff24;padding:5px 8px;letter-spacing:0}.icon-button:hover:enabled{background:#ffffff15}.stage{position:relative;min-height:370px;isolation:isolate}.stage svg{display:block;width:100%;height:auto}.stage canvas{display:block;width:100%;height:370px}.stage-caption{display:flex;justify-content:space-between;align-items:center;gap:15px;padding:12px 20px;font-size:10px;color:#b2bcb9;border-top:1px solid #ffffff14}.stage-caption span:last-child{text-align:right;color:var(--stage-accent)}.metrics{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin:15px 0}.metric{padding:17px;background:var(--card);border:1px solid var(--line);border-radius:12px}.metric-label{font-size:10px;color:var(--muted)}.metric-value{display:block;font-size:23px;letter-spacing:-.6px;margin-top:4px}.metric-unit{font-size:11px;color:var(--muted);margin-left:5px;letter-spacing:0}.metric-label:before{content:"";display:inline-block;background:var(--accent);width:5px;height:5px;border-radius:50%;margin:0 6px 1px 0}.result-panel{padding:16px 2px}.panel-heading{display:flex;align-items:center;justify-content:space-between;gap:10px}h2{font-size:12px;font-weight:650;letter-spacing:-.15px;margin:0}.panel-heading .muted{font-size:10px}.result-panel>p{font-size:12px;margin:7px 0 14px}.artifacts{display:flex;flex-wrap:wrap;gap:8px}.artifact{display:inline-flex;align-items:center;gap:7px;text-decoration:none;border:1px solid var(--line);padding:7px 10px;background:var(--card);border-radius:8px;font-size:11px}.artifact:hover{border-color:var(--accent)}.inspector{border-left:1px solid var(--line);padding-left:24px}.small-label{font-size:8px;letter-spacing:1px;color:var(--muted)}#controls{margin:23px 0 10px}.control{display:block;margin-bottom:22px}.control-head{display:flex;justify-content:space-between;align-items:center;margin:0 0 9px;font-size:11px;font-weight:550}.control output{font-variant-numeric:tabular-nums;color:var(--accent);font-size:11px}.control input[type=range]{width:100%;accent-color:var(--accent);display:block;height:5px;cursor:ew-resize;margin:12px 0}.control select,.control input[type=text]{background:var(--card);border:1px solid var(--line);border-radius:8px;width:100%;padding:9px 10px;color:var(--ink);font-size:12px}.control small{display:block;color:var(--muted);font-size:10px;margin-top:6px}.extra-actions{display:flex;gap:8px;flex-direction:column}.extra-actions button{text-align:left;font-size:11px}.extra-actions button:before{content:'↗';margin-right:8px;color:var(--accent)}.tip{display:flex;gap:10px;background:var(--tint);padding:13px;border-radius:10px;margin:20px 0 27px}.spark{color:var(--accent);font-size:19px}.tip p{font-size:11px;margin:1px 0;color:var(--muted)}.history{list-style:none;margin:14px 0 0;padding:0}.history button{display:flex;align-items:center;width:100%;gap:10px;border:0;border-bottom:1px solid var(--line);border-radius:0;text-align:left;padding:12px 0;font-size:11px}.history button:hover:enabled{background:transparent;color:var(--accent)}.history button[aria-current=true]{color:var(--accent)}.history-dot{width:7px;height:7px;background:var(--accent);border-radius:50%;flex-shrink:0}.history-content{flex:1;min-width:0}.history-title{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.history-time{display:block;font-size:9px;color:var(--muted);margin-top:3px}.history-value{font-size:11px;font-variant-numeric:tabular-nums}.text-button{border:0;font-size:10px;padding:0;color:var(--accent)}.notice{border:1px solid var(--line);border-left:3px solid var(--accent);padding:11px 14px;margin-bottom:16px;background:var(--card);font-size:12px;border-radius:6px}.notice.error{border-left-color:#b84636;color:#8b382d}footer{border-top:1px solid var(--line);margin-top:30px;padding:16px 0;display:flex;justify-content:space-between;gap:12px;color:var(--muted);font-size:9px}pre{white-space:pre-wrap;word-break:break-word;max-height:160px;overflow:auto;font:11px/1.5 ui-monospace,monospace;background:var(--card);padding:12px;border-radius:8px}summary{font-size:11px;color:var(--muted);cursor:pointer;margin-top:15px}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.domain-toolbar{position:absolute;z-index:2;bottom:17px;left:20px;right:20px;display:flex;justify-content:center;gap:8px;flex-wrap:wrap}.domain-toolbar button{background:#ffffff10;border-color:#ffffff2e;color:var(--stage-ink);font-size:11px;padding:7px 12px}.domain-toolbar button:hover{background:#ffffff20}.domain-toolbar button[aria-pressed=true]{background:var(--stage-accent);color:var(--stage);border-color:transparent}.domain-label{position:absolute;z-index:1;left:22px;top:5px;max-width:calc(100% - 230px);font-size:11px;color:#b6c5bd}.domain-badge{position:absolute;top:8px;right:20px;font-size:9px;letter-spacing:1px;border:1px solid #ffffff20;border-radius:20px;padding:5px 9px;color:var(--stage-accent)}.domain-readout{position:absolute;left:24px;bottom:70px;font-size:12px;color:var(--stage-accent)}.domain-readout strong{display:block;font-size:32px;font-weight:500;color:var(--stage-ink)}.keyboard{position:absolute;bottom:66px;left:12%;right:12%;height:95px;display:flex;gap:3px}.key{flex:1;background:#f6f0df;border:0;border-radius:0 0 7px 7px;color:#706856;display:flex;justify-content:center;align-items:end;padding-bottom:10px;font-size:10px;box-shadow:inset 0 -5px #ddd5bd}.key:hover:enabled,.key[aria-pressed=true]{background:var(--stage-accent);transform:translateY(2px)}.gallery{display:grid;grid-template-columns:repeat(2,1fr);gap:12px;padding:48px 25px 75px}.gallery button{padding:0;overflow:hidden;border:1px solid #ffffff24;border-radius:12px;background:#ffffff07}.gallery img{width:100%;height:175px;object-fit:contain;display:block}.gallery figcaption{padding:7px 10px;color:var(--stage-ink);font-size:10px;text-align:left}.gallery button[aria-pressed=true]{outline:2px solid var(--stage-accent);outline-offset:3px}.domain-dialog{position:fixed;inset:0;margin:auto;width:min(650px,calc(100vw - 30px));max-height:calc(100vh - 40px);color:var(--stage-ink);background:var(--stage);border:1px solid #ffffff40;border-radius:14px;padding:20px;z-index:5;overflow:auto}.domain-dialog img{width:100%;max-height:280px;object-fit:contain}.domain-dialog button{float:right;color:var(--stage-ink)}.domain-empty{display:grid;place-items:center;min-height:300px;color:var(--stage-accent);font-size:13px;text-align:center;padding:35px}.chart-tooltip{position:absolute;top:12px;left:24px;font-size:11px;color:var(--stage-accent)}.row-buttons{display:flex;gap:7px}.comparison{color:var(--accent);font-size:11px;padding:10px 0}
@media(min-width:1300px){.stage canvas{height:450px}.stage{min-height:450px}.workspace{grid-template-columns:minmax(0,1fr) 285px}}
@media(max-width:850px){#app{padding:0 19px}.workspace{gap:17px;grid-template-columns:minmax(0,1fr) 215px}.inspector{padding-left:17px}h1{font-size:28px}.heading{gap:12px}.heading-actions{flex-direction:column-reverse;align-items:flex-end}.stage-caption{align-items:start;font-size:9px;padding:11px 15px}.metrics{gap:8px}.metric{padding:12px}.metric-value{font-size:21px}}
-@media(max-width:620px){#app{padding:0 15px}.topbar{height:52px}.wordmark{font-size:9px;letter-spacing:1px}.heading{padding:23px 0 20px;align-items:flex-start}.heading-actions .quiet{display:none}.heading-actions .primary{font-size:11px;padding:9px 10px;margin-top:21px}.description{font-size:11px}h1{font-size:27px}.eyebrow{font-size:8px}.workspace{grid-template-columns:1fr}.inspector{border-left:0;border-top:1px solid var(--line);padding:20px 0 0}#controls{display:grid;grid-template-columns:1fr 1fr;gap:0 20px}.stage{min-height:310px}.stage canvas{height:310px}.stage-heading{padding:12px 15px}.stage-caption{flex-direction:column;gap:4px}.stage-caption span:last-child{text-align:left}.tip{margin:15px 0 20px}.history-section{margin-top:20px}.gallery{padding:20px 15px 80px}.gallery img{height:110px}.keyboard{left:8%;right:8%}.metrics{margin:12px 0}.metric-label{font-size:9px}.metric-value{font-size:20px}.metric-unit{font-size:9px}.metric-label:before{display:none}footer{margin-top:20px}.domain-readout strong{font-size:26px}}
+@media(max-width:620px){#app{padding:0 15px}.topbar{height:52px}.wordmark{font-size:9px;letter-spacing:1px}.heading{padding:23px 0 20px;align-items:flex-start}.heading-actions .quiet{display:none}.heading-actions .primary{font-size:11px;padding:9px 10px;margin-top:21px}.description{font-size:11px}h1{font-size:27px}.eyebrow{font-size:8px}.workspace{grid-template-columns:1fr}.inspector{border-left:0;border-top:1px solid var(--line);padding:20px 0 0}#controls{display:grid;grid-template-columns:1fr 1fr;gap:0 20px}.stage{min-height:310px}.stage canvas{height:310px}.stage-heading{padding:12px 15px}.stage-caption{flex-direction:column;gap:4px}.stage-caption span:last-child{text-align:left}.tip{margin:15px 0 20px}.history-section{margin-top:20px}.gallery{padding:60px 15px 80px}.gallery img{height:110px}.keyboard{left:8%;right:8%}.metrics{margin:12px 0}.metric-label{font-size:9px}.metric-value{font-size:20px}.metric-unit{font-size:9px}.metric-label:before{display:none}footer{margin-top:20px}.domain-readout strong{font-size:26px}.domain-label{top:35px;left:16px;max-width:calc(100% - 32px);font-size:10px}.domain-badge{top:5px;right:15px;font-size:8px}.domain-toolbar{left:12px;right:12px;bottom:14px;gap:6px}.domain-toolbar button{font-size:10px;padding:7px 9px}}
@media(prefers-reduced-motion:reduce){*{transition:none!important;scroll-behavior:auto!important}}
+
+.domain-dialog::backdrop{background:#14241d99;backdrop-filter:blur(5px)}
diff --git a/store/viewers/studio-viewer/web/studio.mjs b/store/viewers/studio-viewer/web/studio.mjs
index 749448ae7..c9553c3e9 100644
--- a/store/viewers/studio-viewer/web/studio.mjs
+++ b/store/viewers/studio-viewer/web/studio.mjs
@@ -1,6 +1,6 @@
const $ = id => document.getElementById(id);
const text = (tag, value, className) => {const e=document.createElement(tag);e.textContent=value;if(className)e.className=className;return e;};
-let state, parameters, domain, draftRevision, dirty=false, selected=null, motion=!matchMedia('(prefers-reduced-motion: reduce)').matches, lastResult='', pending=false;
+let state, parameters, domain, draftRevision, dirty=false, selected=null, motion=!matchMedia('(prefers-reduced-motion: reduce)').matches, lastResult='', pending=false, refreshing=false;
const abort = new AbortController();
const artifactURL = path => '/artifacts/'+path.split('/').map(encodeURIComponent).join('/');
const announce = message => {$('announcement').textContent=message;};
@@ -46,15 +46,17 @@ async function run(action){
try{await api('/api/run',{action,parameters,revision:draftRevision??state.revision});dirty=false;selected=null;await refresh();announce('Run started.');}catch(e){notice(e.message,true);}finally{pending=false;$('run').disabled=state?.job?.status==='running';}
}
async function refresh(){
+ if(refreshing)return;
+ refreshing=true;
try{
const next=await api('/api/state');
const changed=state&&next.revision!==state.revision;
- if(!state){state=next;parameters={...state.project.parameters};const c=state.config;document.title=c.title+' · Harness';$('title').textContent=c.title;$('description').textContent=c.description;$('category').textContent=c.category.toUpperCase();$('scene-label').textContent=c.scene.toUpperCase();$('hint').textContent=c.hint;$('tip').textContent=c.tip;$('credit').textContent=c.credit;$('run').textContent=c.actions[0].label;for(const [key,value] of Object.entries(c.theme??{}))document.documentElement.style.setProperty('--'+key,value);controls(c);for(const a of c.actions.slice(1)){const b=text('button',a.label);b.type='button';b.title=a.description??a.label;b.addEventListener('click',()=>run(a.id));$('extra-actions').append(b);}const module=await import('/domain.mjs');domain=module.mount($('stage'),{getParameters:()=>parameters,setParameter,announce,artifactURL,signal:abort.signal,run:()=>run(c.actions[0].id)});}
+ if(!state){state=next;parameters={...state.project.parameters};const c=state.config;document.title=c.title+' · Harness';$('title').textContent=c.title;$('description').textContent=c.description;$('category').textContent=c.category.toUpperCase();$('scene-label').textContent=c.scene.toUpperCase();$('hint').textContent=c.hint;$('tip').textContent=c.tip;$('credit').textContent=c.credit;$('run').textContent=c.actions[0].label;for(const [key,value] of Object.entries(c.theme??{}))document.documentElement.style.setProperty('--'+key,value);controls(c);for(const a of c.actions.slice(1)){const b=text('button',a.label);b.type='button';b.title=a.description??a.label;b.addEventListener('click',()=>run(a.id));$('extra-actions').append(b);}const module=await import('/domain.mjs');$('stage').replaceChildren();domain=module.mount($('stage'),{getParameters:()=>parameters,setParameter,announce,artifactURL,signal:abort.signal,run:()=>run(c.actions[0].id)});}
state=next;
if(changed&&dirty){$('remote').hidden=false;}else if(changed){parameters={...state.project.parameters};draftRevision=state.revision;controls(state.config);$('remote').hidden=true;}
$('connection').textContent='Workspace connected';$('app').setAttribute('aria-busy','false');
$('dirty').textContent=dirty?'UNSAVED':'SAVED';
- const running=state.job?.status==='running';$('run').disabled=running||pending;
+ const running=state.job?.status==='running';$('run').disabled=running||pending;for(const b of $('extra-actions').children)b.disabled=running||pending;
$('job-details').hidden=!state.job;$('log').textContent=state.job?.log??'';
if(state.job?.status==='failed')notice(state.job.message,true);
else if(running){notice(state.job.message);if(!$('cancel')){const b=text('button','Stop run');b.id='cancel';b.addEventListener('click',async()=>{try{await api('/api/cancel',{});await refresh();}catch(e){notice(e.message,true);}});$('notice').append(' ',b);}}
@@ -62,7 +64,7 @@ async function refresh(){
else if(state.job?.status==='done')notice('');
const stamp=state.result?.id??'';
if(stamp!==lastResult||changed||!lastResult){lastResult=stamp;renderResult(selected??state.result);renderHistory();}
- }catch(e){if(!domain){state=null;$('extra-actions').replaceChildren();}$('connection').textContent='Reconnecting';notice(e.message,true);}
+ }catch(e){if(!domain){state=null;$('extra-actions').replaceChildren();}$('connection').textContent='Reconnecting';notice(e.message,true);}finally{refreshing=false;}
}
$('run').addEventListener('click',()=>run(state.config.actions[0].id));
$('controls').addEventListener('submit',e=>e.preventDefault());