Repository navigation
fix(cli): forward interrupt signal to gateway tts convert requests - #194128
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 changesForward the CLI invocation’s abort signal to Gateway TTS conversion requests and document caller cancellation. Example: Press Ctrl+C while
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this PR for merge: it repairs a current cancellation defect with the smallest complete change, and no actionable defects remain. Exact-head CI is still pending. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe inference CLI sends TTS conversion requests through the shared Gateway client; the invocation scope owns caller cancellation while the Gateway independently owns accepted synthesis. flowchart LR
A[CLI invocation scope] --> B[TTS convert command]
B --> C[Shared Gateway client]
A -->|Abort signal| C
C --> D[Gateway TTS handler]
D --> E[Speech provider]
C --> F[CLI result or interrupted exit]
Technical reviewBest possible solution: Merge the existing signal forwarding and consolidated regression once the ordinary exact-head gates pass. Do we have a high-confidence way to reproduce the issue? Yes: current-main source omits the captured signal, and supplied shipped-entry main/candidate receipts demonstrate forced termination before the fix and cooperative caller cancellation afterward; no target code was executed during this review. Is this the best way to solve the issue? Yes: passing the existing invocation signal to the existing Gateway cancellation owner restores the invariant without introducing another lifecycle mechanism. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 2808e34b4ad3. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +1, Tests -3, Docs +1. Total -1 across 3 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: No label 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 (4 earlier review cycles)
Reviewed November 6, 2026, 10:25 AM ET / 15:25 UTC (Revision 5). |
`infer tts convert --gateway` did not pass the invocation's abort signal to the gateway call, so Ctrl+C did not cancel the pending RPC and the CLI hung until it was force-killed. The existing signal (from getAsyncWorkSignal) is now forwarded, as openclaw#192896 did for model and embedding runs. Uninterrupted runs are unchanged.
4e969c0 to
c8b42e9
Compare
|
@clawsweeper re-review Both blocking items from the prior review (head
|
|
🦞👀 Re-review progress:
|
Real PTY SIGINT proof: shipped CLI + live Gateway + slow HTTP TTS fixtureReproducing the #192896 / #191635 recipe end to end against the exact head
Results
Head aborts the pending caller RPC and exits naturally (130) in <100 ms; Base hangs until the launcher force-kills it (~2.04s). 4/4 clean, red/green fully separated, Uninterrupted control (Head, same harness)No Ctrl+C; the fixture holds only 3s so the request completes. The CLI exits {
"ok": true,
"capability": "tts.convert",
"transport": "gateway",
"provider": "openai",
"attempts": [],
"outputs": [
{
"path": "/tmp/oc-proof-home/.openclaw/media/tool-speech-synthesis/voice---c21955f0-a3bd-49c4-8366-abebc0860d25.mp3",
"format": "mp3",
"voiceCompatible": false
}
]
}All runs are secretless (synthetic |
|
@clawsweeper re-review The redacted PTY receipts (head-1/head-2/base-1/base-2 result JSONs + transcripts) are now inline in the PR body (see "Shipped-run PTY receipts" section) and archived under |
|
🦞👀 Re-review progress:
|
|
Maintainer shipped-entry proof on actual current main and the contributor candidate
Main holds the caller RPC through the launcher's 2-second grace and is killed. Candidate exits naturally with 130 in 60 ms, closes the caller RPC in 35 ms, and prints no late TTS envelope. The driver's safety kill did not fire. Both uninterrupted controls exit 0 with the same full result envelope (excluding only their owned output path), real Gateway success receipts and verified 2,044-byte RIFF/WAVE output files. Both actual provider requests match apart from their unique text correlation marker. Custody control: after the interrupted caller exits, Gateway-owned synthesis still receives its valid HTTP response and the fixture observes response completion on both lanes. This fix cancels the caller RPC, not Gateway-owned synthesis. The upstream HTTP request is deliberately not claimed to cancel. Each lane used its own explicit profile, HOME, OPENCLAW_HOME/STATE/CONFIG, workspace and four unique loopback ports. The exact built binary's Focused Collector sourcespins.json {"pr":194128,"main":"2a2cd2931454fe75687b2dec1104289b9a66c273","candidate":"c8b42e94bcb8338ab0aa77a40b45f94dc5be9e9d","image":"node:24.22.1","container":"bugloop-194128","scope":"one-line existing caller signal forwarding; Gateway-owned synthesis unchanged"}
build.sh set -eu
corepack enable
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
tts-fixture.mjs import http from 'node:http';
import net from 'node:net';
const [providerPort,rpcPort,controlPort,gatewayPort]=process.argv.slice(2).map(Number);
const now=()=>Number(process.hrtime.bigint())/1e6;
const state={active:null,runs:{}};
const wav=Buffer.alloc(2044);
wav.write('RIFF');wav.writeUInt32LE(2036,4);wav.write('WAVEfmt ',8);wav.writeUInt32LE(16,16);wav.writeUInt16LE(1,20);wav.writeUInt16LE(1,22);wav.writeUInt32LE(16000,24);wav.writeUInt32LE(32000,28);wav.writeUInt16LE(2,32);wav.writeUInt16LE(16,34);wav.write('data',36);wav.writeUInt32LE(2000,40);
const provider=http.createServer((req,res)=>{
if(req.method!=='POST'||req.url!=='/v1/audio/speech'){res.writeHead(404);res.end();return;}
let body='';req.on('data',b=>body+=b);req.on('end',()=>{
const payload=JSON.parse(body),r=state.runs[payload.input];
if(!r){res.writeHead(400);res.end();return;}
r.providerRequest=payload;r.held={at:now(),settled:false};
res.on('finish',()=>r.providerFinishedAt=now());
res.on('close',()=>r.providerClosedAt=now());
setTimeout(()=>{r.held.settled=true;r.providerRespondedAt=now();res.writeHead(200,{'content-type':'audio/wav','content-length':wav.length});res.end(wav);},r.delayMs);
});
});
class Observer{
constructor(direction){this.direction=direction;this.buffer=Buffer.alloc(0);this.upgraded=false;this.run=null;}
feed(data){
this.buffer=Buffer.concat([this.buffer,data]);
if(!this.upgraded){const i=this.buffer.indexOf('\r\n\r\n');if(i<0)return;this.buffer=this.buffer.subarray(i+4);this.upgraded=true;}
while(this.buffer.length>=2){
const first=this.buffer[0],second=this.buffer[1];let length=second&127,pos=2;
if(length===126){if(this.buffer.length<4)return;length=this.buffer.readUInt16BE(2);pos=4;}
else if(length===127){if(this.buffer.length<10)return;length=Number(this.buffer.readBigUInt64BE(2));pos=10;}
let mask;if(second&128){if(this.buffer.length<pos+4)return;mask=this.buffer.subarray(pos,pos+4);pos+=4;}
if(this.buffer.length<pos+length)return;
const payload=Buffer.from(this.buffer.subarray(pos,pos+length));this.buffer=this.buffer.subarray(pos+length);
if(mask)for(let i=0;i<payload.length;i++)payload[i]^=mask[i%4];
if((first&15)!==1)continue;
let v;try{v=JSON.parse(payload.toString());}catch{continue;}
if(this.direction==='caller'&&v.method==='tts.convert'&&state.active){this.run=state.active;const r=state.runs[this.run];r.request=v;r.rpcStartedAt=now();}
if(this.direction==='gateway'&&v.type==='res'&&v.id===state.runs[state.active]?.request?.id){state.runs[state.active].receipt=v;state.runs[state.active].receiptAt=now();}
}
}
}
const rpc=net.createServer(caller=>{
const upstream=net.connect(gatewayPort,'127.0.0.1'),out=new Observer('caller'),incoming=new Observer('gateway');
const closed=()=>{if(out.run&&!state.runs[out.run].callerClosedAt)state.runs[out.run].callerClosedAt=now();};
caller.on('data',b=>{out.feed(b);upstream.write(b);});upstream.on('data',b=>{incoming.feed(b);caller.write(b);});
caller.on('end',()=>{closed();upstream.end();});caller.on('close',closed);caller.on('error',()=>upstream.destroy());upstream.on('error',()=>caller.destroy());upstream.on('end',()=>caller.end());
});
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],[rpc,rpcPort],[control,controlPort]].map(([s,p])=>new Promise(r=>s.listen(p,'127.0.0.1',r))));
console.log(JSON.stringify({ready:true,providerPort,rpcPort,controlPort,gatewayPort}));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']: (root/name).mkdir()
ports=[]
while len(ports)<4:
p=port()
if p not in ports:ports.append(p)
providerPort,rpcPort,controlPort,gatewayPort=ports
config=root/'config.json';profile='p194128'+lane+uuid.uuid4().hex[:6];token='synthetic-'+uuid.uuid4().hex
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),'OPENCLAW_DISABLE_BONJOUR':'1','OPENCLAW_SKIP_CHANNELS':'1','NO_COLOR':'1','TERM':'xterm-256color'}
cfg={'gateway':{'mode':'local','bind':'loopback','port':gatewayPort,'auth':{'mode':'token','token':token},'controlUi':{'enabled':False}},'tts':{'provider':'openai','providers':{'openai':{'apiKey':'synthetic-fixture-key','baseUrl':'http://127.0.0.1:'+str(providerPort)+'/v1','model':'tts-1','voice':'alloy','responseFormat':'wav'}}},'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':['openai'],'entries':{'openai':{'enabled':True}},'slots':{'memory':'none'}}}
config.write_text(json.dumps(cfg,indent=2));before=config.read_bytes();fixture=gateway=None;logs=[]
try:
for name in ['fixture','gateway']:
f=(OUT/(lane+'-'+name+'.log')).open('wb');logs.append(f)
fixture=subprocess.Popen(['node','/proof/tts-fixture.mjs']+list(map(str,ports)),stdout=logs[0],stderr=subprocess.STDOUT);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':ports};print(json.dumps(paths),flush=True);(OUT/(lane+'-paths.json')).write_text(json.dumps(paths,indent=2))
gateway=subprocess.Popen(['node',str(repo/'openclaw.mjs'),'--profile',profile,'gateway','run','--allow-unconfigured'],cwd=repo,env=env,stdout=logs[1],stderr=subprocess.STDOUT);ready(gatewayPort,'/readyz')
clientenv={**env,'OPENCLAW_GATEWAY_URL':'ws://127.0.0.1:'+str(rpcPort),'OPENCLAW_GATEWAY_TOKEN':token}
for case,interrupt,delay in [('control',False,3000),('read',True,20000)]:
run='TTS_'+lane+'_'+case+'_'+uuid.uuid4().hex[:8];get(controlPort,'/arm?run='+run+'&delay='+str(delay))
args=['infer','tts','convert','--gateway','--text',run,'--provider','openai','--model','openai/tts-1','--voice','alloy','--json']
row=terminal(repo,clientenv,profile,args,controlPort,run,interrupt);row.update(lane=lane,case=case,run=run)
deadline=time.monotonic()+25
while time.monotonic()<deadline:
wire=get(controlPort,'/state?run='+run)
if not wire.get('held') or wire.get('providerFinishedAt'):break
time.sleep(.05)
row['wire']=wire;row['callerCloseAfterSignalMs']=wire.get('callerClosedAt',0)-row['signalAt']['at'] if row['signalAt'] and wire.get('callerClosedAt') 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') and wire.get('providerRequest'),'Real Gateway RPC and HTTP synthesis must run'
assert wire['providerRequest']['input']==run and wire['providerRequest']['response_format']=='wav',wire
if interrupt:
assert row['signalAt'] and row['result'] is None and row['signalAt']['bytesBefore']==0,row
assert wire['providerFinishedAt']>row['exitAt'],'Gateway-owned synthesis must retain its lifetime'
if lane=='cand':assert row['exitCode']==130 and row['signalToExitMs']<2000 and row['callerCloseAfterSignalMs']<2000,row
else:assert row['exitCode']==-9 and row['signalToExitMs']>=2000,row
else:
assert row['exitCode']==0 and row['result']['ok'] and row['result']['capability']=='tts.convert',row
assert wire.get('receipt',{}).get('ok') is True,wire
asset=pathlib.Path(row['result']['outputs'][0]['path']);assert str(asset).startswith(str(root/'state')+'/'),asset
audio=asset.read_bytes();assert len(audio)==2044 and audio[:4]==b'RIFF' and audio[8:12]==b'WAVE',asset
row['audioBytes']=len(audio);(OUT/(lane+'-control.json')).write_text(json.dumps(row,indent=2))
assert config.read_bytes()==before
summary.append({k:row[k] for k in ['lane','case','run','exitCode','signalToExitMs','callerCloseAfterSignalMs']});(OUT/'summary.json').write_text(json.dumps(summary,indent=2))
finally:
stop(gateway);stop(fixture)
for log in logs:log.close()
print(json.dumps({'evidence':str(OUT),'summary':summary}),flush=True) |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Additional regression receipt: copied the final |
|
Landed in b8ce04a. Thanks @wangmiao0668000666. Ctrl+C now stops the TTS CLI right away. |
…penclaw#194128) fix(tts): stop the TTS CLI on Ctrl+C The text-to-speech CLI did not pass the invocation's cancel signal to its Gateway call, so Ctrl+C left the request open until the CLI was force-killed about 2 seconds later. The existing signal is now forwarded, as for the other infer commands. Synthesis that the Gateway already owns still finishes on the Gateway. Evidence: built CLI against a real Gateway and a slow local TTS provider. Main was killed after 2,012 ms; with this change the CLI exits with 130 in 60 ms and the caller RPC closes in 35 ms. Uninterrupted runs return matching results and valid WAV files on both refs. Details: openclaw#194128 (comment). Thanks @wangmiao0668000666. Co-authored-by: Ayaan Zaidi <[email protected]>
fix(cli): cancel interrupted tts gateway RPCs openclaw capability tts status, providers --gateway, personas --gateway and the --gateway state changes (enable, disable, set-provider, set-persona) ignored Ctrl+C. The Gateway request got no abort signal, so the command waited until its 30-second timeout or a forced kill. The abort signal is now passed to these Gateway calls, as tts convert already does since #194128. The client stops waiting; the Gateway can still finish a write it already received. Evidence: built openclaw from main and from this change, each with a real Gateway, in Docker on node 24.22.1. A local relay held the tts replies for 25 s, and Ctrl+C was sent in a real terminal 1 s after the request reached the Gateway. tts status: main was force-killed after 2174 ms with the connection still open; this change exits with code 130 after 28 ms and closes the connection. set-provider: 2273 ms and killed on main, exit 130 after 22 ms with this change. In both builds the Gateway had already written the setting before Ctrl+C. Runs without Ctrl+C give the same output on both. Details: #195206 (comment). Thanks @shuisadev and @SunnyShu0925. Co-authored-by: SunnyShu <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
fix(cli): cancel interrupted tts gateway RPCs openclaw capability tts status, providers --gateway, personas --gateway and the --gateway state changes (enable, disable, set-provider, set-persona) ignored Ctrl+C. The Gateway request got no abort signal, so the command waited until its 30-second timeout or a forced kill. The abort signal is now passed to these Gateway calls, as tts convert already does since openclaw#194128. The client stops waiting; the Gateway can still finish a write it already received. Evidence: built openclaw from main and from this change, each with a real Gateway, in Docker on node 24.22.1. A local relay held the tts replies for 25 s, and Ctrl+C was sent in a real terminal 1 s after the request reached the Gateway. tts status: main was force-killed after 2174 ms with the connection still open; this change exits with code 130 after 28 ms and closes the connection. set-provider: 2273 ms and killed on main, exit 130 after 22 ms with this change. In both builds the Gateway had already written the setting before Ctrl+C. Runs without Ctrl+C give the same output on both. Details: openclaw#195206 (comment). Thanks @shuisadev and @SunnyShu0925. Co-authored-by: SunnyShu <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
What Problem This Solves
infer tts convert --gatewayobtains the invocation signal but did not pass it tocallGateway. Ctrl+C left the caller RPC pending until the normal launcher force-killed it after its 2-second interrupt grace.Why This Change Was Made
Forward the already-captured signal through the existing Gateway cancellation owner. One production line, following the model/embedding (#192896) and audio (#193893) caller boundaries. The caller exits 130 promptly without publishing a late TTS result. Gateway-owned synthesis keeps its existing lifetime; no local-TTS, timeout, output-custody, schema, auth, Doctor or update change.
The original commit and credit belong to wangmiao0668000666. Maintainer follow-up only documents the operator behavior.
Evidence
Real built current-main/candidate Gateway proof and collector sources
Secretless Docker
node:24.22.1, independently installed and built main2a2cd2931454fe75687b2dec1104289b9a66c273and candidatec8b42e94bcb8338ab0aa77a40b45f94dc5be9e9d. Shippedopenclaw.mjs, normal launcher, real PTY Ctrl+C, actual Gateway and OpenAI speech plugin, faithful slow loopback HTTP speech provider. No inverse-patched bundle, fake Gateway or injected error.The final head only adds documentation to the exercised candidate runtime.
Checks and simplification
scripts/run-tsgo.mjs.The existing signal and RPC owner are sufficient; no wrapper or new state. Against merge base
3a5fb5825d9c820576d3334c9a2d2b4a364fb612: production +1/-0, tests +6/-9 (net -3), docs +1. No allocation files. Existing interrupt table is extended without adding a new suite or dropping assertions.Fresh exact-head CI and ClawSweeper review are requested after push. The lead maintainer performs the merge, not this worker.