Repository navigation
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis PR forwards CLI interruption to video description requests through the existing shared media execution scope. Example: Press Ctrl+C while
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review This PR fixes a current video-inference cancellation bug with a focused implementation and convincing shipped-CLI proof; no actionable defects were found, and exact-head CI remains pending. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe inference CLI resolves the file and agent configuration, then calls the shared media runtime, which owns provider execution, cancellation, and resource cleanup before returning a description envelope. flowchart LR
A[CLI invocation] --> B[Invocation abort signal]
A --> C[Video file helper]
B --> C
C --> D[Shared media execution scope]
D --> E[Provider HTTP request]
E --> F[Description or cancellation]
F --> G[Cleanup and CLI output]
Technical reviewBest possible solution: Retain this focused fix so video shares audio's existing cancellation and cleanup owner. Do we have a high-confidence way to reproduce the issue? Current-main source drops the invocation context on video, and the supplied built-CLI before/after receipt independently demonstrates the resulting pending HTTP request; no target code was executed during this review. Is this the best way to solve the issue? The smallest complete repair forwards the existing context and shares the existing guarded-fetch/process scope, preserving audio behavior without adding another cancellation owner. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 4a29006e89e7. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +11, Tests 0, Docs +3. Total +14 across 4 files. Added test files: 0. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed November 6, 2026, 1:27 PM ET / 18:27 UTC (Revision 2). |
|
CI attribution for contributor head a8edb95, run 42263175652:
That path contains neither changed production module. The main fix already exists as b46bad88b708, changing auth-policy's snapshot import from
|
|
Maintainer acceptance: normal built current main vs contributor candidate, real MP4, real HTTP, real terminal Main The shipped
Main twice keeps HTTP open until the normal launcher kills it after ~2.09 seconds. Candidate twice exits naturally 130 in 95/87 ms, closes HTTP in 1.03/0.79 ms, and prints no late description. The driver's safety kill never fires. Interrupted requests do not complete a response. Both uninterrupted controls exit 0 with byte-identical full result envelopes, exact description Every lane has an explicit unique profile, owned HOME/OPENCLAW_HOME/state/config/workspace/tmp and unique loopback ports. The exact built binary resolves its config and agent SQLite paths before collection; those paths are recorded and config bytes remain unchanged. The first collection stopped after a successful control because the collector expected a shorter default prompt; the assertion was corrected to the observed complete existing prompt, not loosened. No product red was claimed from that collector assertion. Focused checks: 133 tests passed (17 runtime + 6 existing audio authority/retry controls + 110 CLI consumer cases); scoped test/runtime/CLI typecheck, canonical typed lint and formatting passed. The final pre-abort table copied onto current main has audio PASS and video FAIL (video resolves a no-attachment result rather than rejecting the cancellation reason). Candidate passes both. Simplification retains one existing scope owner: audio's guarded-fetch/owned-process scope moves to the common file runner, and video forwards the existing execution context. Existing one-argument callers and the plugin facade remain unchanged; only the direct helper accepts the optional existing context. No model-precedence, security policy, retry, schema, auth, Doctor or update changes. Source +29/-18 (gross 47, net +11); tests +35/-35 (net 0); docs +3. Allocation removed. Original CI reds attributed and owned growth repaired. Runnable collector and build sourcespins.json {"pr":194251,"main":"2fa5c4160a2b8fec2cfd37e92acda3a7bb786cc5","candidate":"a8edb953a861e323fa551b09da611271ff2856f4","originalCiMainParent":"8662f3bf78dc7d644d207c8afb6f2f8b8f5750b0","originalCiRun":42263175652,"image":"node:24.22.1","container":"bugloop-194251","scope":"Existing MediaExecutionContext passed to video owner; audio authority/process scope lifted unchanged"}
build.sh set -eu
corepack enable
apt-get update > /proof/apt.log 2>&1
apt-get install -y ffmpeg >> /proof/apt.log 2>&1
for lane in base cand; do
cd /work/$lane
pnpm install --frozen-lockfile > /proof/install-$lane.log 2>&1
node --import ./scripts/tsx.mjs scripts/build-all.mts runtime > /proof/build-$lane.log 2>&1
done
cd /work/ci-base
pnpm install --frozen-lockfile > /proof/install-ci-base.log 2>&1
ffmpeg -y -f lavfi -i color=c=blue:s=160x120:d=1 -c:v libx264 -pix_fmt yuv420p /work/runs/blue.mp4 > /proof/mp4-generation.log 2>&1
ffprobe -v error -show_entries stream=codec_name,width,height -show_entries format=duration,size -of json /work/runs/blue.mp4 > /proof/mp4-metadata.json
video-fixture.mjs import http from 'node:http';
import fs from 'node:fs';
import {createHash} from 'node:crypto';
const [providerPort,controlPort]=process.argv.slice(2).map(Number);
const now=()=>Number(process.hrtime.bigint())/1e6;
const sha=b=>createHash('sha256').update(b).digest('hex');
const video=fs.readFileSync('/work/runs/blue.mp4');
if(video.subarray(4,8).toString()!=='ftyp')throw Error('Real MP4 required');
const state={active:null,runs:{},videoBytes:video.length,videoSha256:sha(video)};
const provider=http.createServer((req,res)=>{
if(req.method!=='POST'||req.url!=='/v1/chat/completions'){res.writeHead(404);res.end();return;}
let body='';req.on('data',b=>body+=b);req.on('end',()=>{
const r=state.runs[state.active],payload=JSON.parse(body),parts=payload.messages[0].content;
const url=parts.find(p=>p.type==='video_url').video_url.url;
const uploaded=Buffer.from(url.split(',')[1],'base64');
r.request={method:req.method,path:req.url,model:payload.model,prompt:parts.find(p=>p.type==='text').text,bodySha256:sha(body),videoBytes:uploaded.length,videoSha256:sha(uploaded),authMatchesSynthetic:req.headers.authorization==='Bearer synthetic-video-fixture-key'};
if(!uploaded.equals(video)||!r.request.authMatchesSynthetic)throw Error('Unexpected real provider request');
r.held={at:now(),settled:false};
res.on('finish',()=>r.responseFinishedAt=now());res.on('close',()=>r.peerClosedAt=now());
setTimeout(()=>{
r.held.settled=true;
if(res.destroyed){r.responseSent=false;return;}
const response=JSON.stringify({id:'synthetic-video-description',object:'chat.completion',model:payload.model,choices:[{index:0,message:{role:'assistant',content:'A solid blue frame.'},finish_reason:'stop'}]});
r.responseSent=true;res.writeHead(200,{'content-type':'application/json','content-length':Buffer.byteLength(response)});res.end(response);
},r.delayMs);
});
});
const control=http.createServer((req,res)=>{
const url=new URL(req.url,'http://127.0.0.1');
if(url.pathname==='/arm'){const run=url.searchParams.get('run');state.active=run;state.runs[run]={run,delayMs:Number(url.searchParams.get('delay'))};}
res.setHeader('content-type','application/json');res.end(JSON.stringify(url.searchParams.has('run')?state.runs[url.searchParams.get('run')]:state));
});
await Promise.all([[provider,providerPort],[control,controlPort]].map(([s,p])=>new Promise(r=>s.listen(p,'127.0.0.1',r))));
console.log(JSON.stringify({ready:true,providerPort,controlPort,videoBytes:video.length,videoSha256:sha(video)}));pty-proof.py import errno,http.client,json,os,pathlib,pty,re,select,signal,socket,subprocess,sys,time,uuid
ROOT=pathlib.Path('/proof'); OUT=ROOT/('native-'+str(int(time.time()))+'-'+uuid.uuid4().hex[:6]);OUT.mkdir(); summary=[]
assert sys.platform=='linux' and subprocess.check_output(['node','--version'],text=True).strip()=='v24.22.1'
def port():
with socket.socket() as s:s.bind(('127.0.0.1',0));return s.getsockname()[1]
def get(p,path='/'):
c=http.client.HTTPConnection('127.0.0.1',p,timeout=2);c.request('GET',path);r=c.getresponse();data=r.read();c.close();return json.loads(data)
def ready(p,path='/'):
for _ in range(100):
try:return get(p,path)
except (OSError,ValueError):time.sleep(.1)
raise RuntimeError('Endpoint not ready '+str(p)+path)
def cli(repo,env,profile,args):
r=subprocess.run(['node',str(repo/'openclaw.mjs'),'--profile',profile]+args,cwd=repo,env=env,capture_output=True,text=True,timeout=120)
if r.returncode:raise RuntimeError('Setup CLI '+repr(args)+'\n'+r.stdout+'\n'+r.stderr)
return json.loads(r.stdout)
def stop(p):
if p and p.poll() is None:
p.terminate()
try:p.wait(timeout=10)
except subprocess.TimeoutExpired:p.kill();p.wait()
def terminal(repo,env,profile,args,control,run,interrupt):
pid,master=pty.fork()
if pid==0:os.chdir(repo);os.execvpe('node',['node',str(repo/'openclaw.mjs'),'--profile',profile]+args,env)
data=bytearray();status=None;closed=False;sent=None;started=time.monotonic();killed=False
try:
while status is None or not closed:
if not closed and select.select([master],[],[],.01)[0]:
try:
b=os.read(master,65536)
if b:data.extend(b)
else:closed=True
except OSError as e:
if e.errno!=errno.EIO:raise
closed=True
state=get(control,'/state?run='+run)
if interrupt and sent is None and state.get('held') and time.monotonic()-started>.1:
sent={'at':time.monotonic()*1000,'foregroundGroup':os.tcgetpgrp(master),'isTerminal':os.isatty(master),'bytesBefore':len(data)};os.write(master,b'\x03')
if status is None:
ended,raw=os.waitpid(pid,os.WNOHANG)
if ended:status=raw;exitAt=time.monotonic()*1000
if time.monotonic()-started>90 and status is None:
killed=True;os.killpg(pid,signal.SIGKILL)
if status is not None and closed:break
(OUT/(run+'.pty.log')).write_bytes(data)
return {'exitCode':os.waitstatus_to_exitcode(status),'output':data.decode(errors='replace'),'signalAt':sent,'exitAt':exitAt,'signalToExitMs':exitAt-sent['at'] if sent else None,'safetyKill':killed}
finally:
os.close(master)
if status is None:os.killpg(pid,signal.SIGKILL);os.waitpid(pid,0)
for lane in ['base','cand']:
repo=pathlib.Path('/work')/lane;root=pathlib.Path('/work/runs')/(OUT.name+'-'+lane);root.mkdir(parents=True)
for name in ['home','state','workspace','tmp']: (root/name).mkdir()
providerPort=port();controlPort=port()
while controlPort==providerPort:controlPort=port()
config=root/'config.json';profile='p194251'+lane+uuid.uuid4().hex[:6]
env={'PATH':os.environ['PATH'],'HOME':str(root/'home'),'OPENCLAW_HOME':str(root/'home'),'OPENCLAW_STATE_DIR':str(root/'state'),'OPENCLAW_CONFIG_PATH':str(config),'TMPDIR':str(root/'tmp'),'OPENCLAW_DISABLE_BONJOUR':'1','NO_COLOR':'1','TERM':'xterm-256color'}
cfg={'gateway':{'mode':'local'},'models':{'providers':{'moonshot':{'baseUrl':'http://127.0.0.1:'+str(providerPort)+'/v1','apiKey':'synthetic-video-fixture-key','api':'openai-completions','models':[],'request':{'allowPrivateNetwork':True}}}},'tools':{'media':{'models':[{'provider':'moonshot','model':'kimi-k2.6','capabilities':['video']}],'video':{'enabled':True}}},'update':{'checkOnStart':False},'discovery':{'mdns':{'mode':'off'}},'agents':{'ownership':'explicit','defaults':{'workspace':str(root/'workspace'),'systemAgent':{'agentId':'main'},'authInheritance':{'agentId':'main'},'sessionStore':{'agentId':'main'},'skipBootstrap':True},'entries':{'main':{}}},'plugins':{'allow':['moonshot'],'entries':{'moonshot':{'enabled':True}},'slots':{'memory':'none'}}}
config.write_text(json.dumps(cfg,indent=2));before=config.read_bytes();fixture=None
try:
log=(OUT/(lane+'-fixture.log')).open('wb')
fixture=subprocess.Popen(['node','/proof/video-fixture.mjs',str(providerPort),str(controlPort)],stdout=log,stderr=subprocess.STDOUT);info=ready(controlPort)
assert cli(repo,env,profile,['config','file','--json'])['path']==str(config)
db=cli(repo,env,profile,['sessions','--agent','main','--json'])['path'];assert db.startswith(str(root/'state')+'/')
paths={'lane':lane,'profile':profile,'config':str(config),'database':db,'state':str(root/'state'),'ports':[providerPort,controlPort],'videoBytes':info['videoBytes'],'videoSha256':info['videoSha256']};print(json.dumps(paths),flush=True);(OUT/(lane+'-paths.json')).write_text(json.dumps(paths,indent=2))
for case,interrupt,delay in [('control',False,1000),('read1',True,20000),('read2',True,20000)]:
run='VIDEO_'+lane+'_'+case+'_'+uuid.uuid4().hex[:8];get(controlPort,'/arm?run='+run+'&delay='+str(delay))
args=['infer','video','describe','--file','/work/runs/blue.mp4','--agent','main','--model','moonshot/kimi-k2.6','--json']
row=terminal(repo,env,profile,args,controlPort,run,interrupt);row.update(lane=lane,case=case,run=run)
deadline=time.monotonic()+3
while time.monotonic()<deadline:
wire=get(controlPort,'/state?run='+run)
if wire.get('peerClosedAt'):break
time.sleep(.02)
row['wire']=wire;row['peerCloseAfterSignalMs']=wire.get('peerClosedAt',0)-row['signalAt']['at'] if row['signalAt'] and wire.get('peerClosedAt') else None
clean=re.sub(r'\x1b\[[0-?]*[ -/]*[@-~]','',row['output']);row['result']=None
if '{' in clean:
try:row['result']=json.JSONDecoder().raw_decode(clean[clean.index('{'):])[0]
except ValueError:pass
(OUT/(run+'.json')).write_text(json.dumps(row,indent=2));print(json.dumps({k:v for k,v in row.items() if k not in ['output','wire']}),flush=True)
assert not row['safetyKill'];assert wire.get('request'),'The real provider POST must arrive before interrupt'
assert wire['request']['videoSha256']==info['videoSha256'] and wire['request']['videoBytes']==info['videoBytes'],wire
assert wire['request']['model']=='kimi-k2.6' and wire['request']['prompt']=='Describe the video. Respond in at most 500 characters.',wire
if interrupt:
assert row['signalAt'] and row['result'] is None and not wire.get('responseSent') and row['signalAt']['bytesBefore']==0,row
if lane=='cand':assert row['exitCode']==130 and row['signalToExitMs']<1000 and row['peerCloseAfterSignalMs']<1000,row
else:assert row['exitCode']==-9 and row['signalToExitMs']>=1000 and row['peerCloseAfterSignalMs']>=1000,row
else:
assert row['exitCode']==0 and row['result']['ok'] and row['result']['capability']=='video.describe' and 'A solid blue frame.' in row['output'],row
assert wire.get('responseFinishedAt'),wire
assert config.read_bytes()==before
summary.append({k:row[k] for k in ['lane','case','run','exitCode','signalToExitMs','peerCloseAfterSignalMs']});(OUT/'summary.json').write_text(json.dumps(summary,indent=2))
finally:
stop(fixture);log.close()
print(json.dumps({'evidence':str(OUT),'summary':summary}),flush=True) |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
…94251) fix(infer): stop video runs on Ctrl+C `openclaw infer video` dropped its execution context, and with it the cancel signal, so Ctrl+C left the provider request open until the CLI was force-killed about 2 seconds later. The existing execution context is now passed through, as audio already does. Uninterrupted runs are unchanged. Evidence: built CLI with a real MP4 against a slow local video-provider fixture, twice per ref. Main needed SIGKILL after about 2,090 ms; with this change the CLI exits with 130 in under 100 ms and the HTTP request closes within 1.1 ms. Uninterrupted output and request bodies are identical. Details: openclaw#194251 (comment). Thanks @Alix-007. Co-authored-by: Ayaan Zaidi <[email protected]>
|
Thanks @obviyus for repeating the real PTY/HTTP acceptance, consolidating the tests and landing the fix! |
…94251) fix(infer): stop video runs on Ctrl+C `openclaw infer video` dropped its execution context, and with it the cancel signal, so Ctrl+C left the provider request open until the CLI was force-killed about 2 seconds later. The existing execution context is now passed through, as audio already does. Uninterrupted runs are unchanged. Evidence: built CLI with a real MP4 against a slow local video-provider fixture, twice per ref. Main needed SIGKILL after about 2,090 ms; with this change the CLI exits with 130 in under 100 ms and the HTTP request closes within 1.1 ms. Uninterrupted output and request bodies are identical. Details: openclaw#194251 (comment). Thanks @Alix-007. Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit 3af1447) Release adaptation: Forward video execution signal/assertCurrent and move existing guarded fetch/process scope to shared file owner. Retain baseline audio CLI and filesystem resolution: excluded HOLD audio/path migration not imported. Only13-line cancel regression, no fixture refactor. Follow-up dispositions: 577dd00 fix: send infer audio/video --model files only to the requested model (openclaw#190287); bcb47e8 feat(google): add Nano Banana 2.1 image model as the default (openclaw#200468); 6f5d3b3 fix: local path commands pick a neighboring file when a symlinked folder is followed by `..` (openclaw#200031); 3577724 fix(auth): only the running Gateway refreshes shared OAuth sign-ins (openclaw#198214); 81daea9 fix(cli): run infer model run through the Gateway that owns state (openclaw#198141); 22b1aac fix(media): cancel interrupted attachment downloads (openclaw#194399); e43ec1e fix(infer): cancel interrupted image descriptions (openclaw#194391) Validation: Baseline canceled-video assertion fails with16controls passing; candidate17/17passes,194251-green.log. Existing audio cancellation and workspace/cleanup behavior retained. Real MP4/CLI interrupt proof remains upstream-attributed, not locally rerun. Co-authored-by: RomneyDa <[email protected]> (cherry picked from commit 853a96335df6193815789ebcc02d38af11123fcf) (cherry picked from commit 2ea2570de7f13823a8174590bfddfbfabdbcd915)
What Problem This Solves
Ctrl+C during
openclaw infer video describeleft the provider HTTP request pending until the normal launcher force-killed the CLI. The audio path already forwarded the invocation's execution context; video dropped it.Why This Change Was Made
Forward the existing
MediaExecutionContextto video and move audio's existing guarded-fetch/owned-command scope to the shared file runner. One owner retains cancellation and cleanup policy. Existing audio authority/retry behavior, one-argument callers and plugin facade are unchanged; the direct video helper only gains an optional existing execution context.No model-precedence change (adjacent #190287 remains separate), new SDK entrypoint, config, schema, auth, retry, Doctor or update change. Alix-007's original commit and credit are preserved.
Evidence
Maintainer real-MP4, built-CLI acceptance and collector sources
Independently installed/built current main
2fa5c4160a2b8fec2cfd37e92acda3a7bb786cc5and contributor candidate in secretless Dockernode:24.22.1. The shippedopenclaw.mjs, normal launcher, real controlling PTY and VINTR exercise the public CLI against a faithful slow Moonshot-compatible HTTP provider with a real H.264 MP4. No runtime replacement or injected errors.Final head changes only tests/allocation metadata relative to the exercised candidate production runtime.
Checks and simplification
d4ae77eae296fd8eb1f90f7a4ebb5d77fa2e6ad9: production +29/-18 (gross 47, net +11); tests +35/-35 (net 0); docs +3.CI attribution
Original CI classification and exact-main-parent receipt
The owned +17 test-line failure is repaired. The other original red (
registry-runtime.system.test.ts, snapshot readers independent of config IO/mutation facades) fails identically on exact CI main parent8662f3bf78dc7d644d207c8afb6f2f8b8f5750b0under hosted-like pinned Bun. Its import path is outside this diff and main already contains the unrelated fixb46bad88b708. No CI job rerun or unrelated source repair.Fresh review and CI are requested on the exact pushed head. Lead maintainer merges; this worker does not merge.