Skip to content

fix(cli): forward interrupt signal to gateway tts convert requests - #194128

Merged
obviyus merged 2 commits into
openclaw:mainfrom
wangmiao0668000666:fix/tts-gateway-signal
Nov 6, 2026
Merged

obviyus merged 2 commits into
openclaw:mainfrom
wangmiao0668000666:fix/tts-gateway-signal

Conversation

@wangmiao0668000666

@wangmiao0668000666 wangmiao0668000666 commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

infer tts convert --gateway obtains the invocation signal but did not pass it to callGateway. 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 main 2a2cd2931454fe75687b2dec1104289b9a66c273 and candidate c8b42e94bcb8338ab0aa77a40b45f94dc5be9e9d. Shipped openclaw.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.

  • Main once: exit SIGKILL after 2,012 ms; caller RPC stays open 2,009 ms after Ctrl+C.
  • Candidate once: natural exit 130 in 60 ms; caller RPC closes in 35 ms; no late result.
  • Both uninterrupted controls: exit 0, identical result envelope except owned output path, actual Gateway success receipt, verified 2,044-byte PCM WAV.
  • Gateway-owned synthesis still completes its HTTP response after either interrupted caller exits, preserving the existing lifetime.
  • Exact binary config and SQLite resolution, explicit profiles, owned HOME/config/state/workspace, unique ports and unchanged config bytes recorded.

The final head only adds documentation to the exercised candidate runtime.

Checks and simplification

  • Focused capability CLI suite: 111 passed, including pending TTS interruption and accepted-output custody cases.
  • Focused touched-test/runtime typecheck: passed via scripts/run-tsgo.mjs.
  • Canonical typed lint: passed (2 files).
  • Formatting: passed.

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.

@clawsweeper

clawsweeper Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added cli CLI command changes size: XS labels Nov 6, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 6, 2026
@clawsweeper

clawsweeper Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Forward the CLI invocation’s abort signal to Gateway TTS conversion requests and document caller cancellation.

Example: Press Ctrl+C while openclaw infer tts convert --gateway --text hello --json awaits speech synthesis.

  • Before: The caller RPC remains pending until the launcher kills the CLI after its interrupt grace period.
  • After: The caller RPC closes promptly, the CLI exits naturally with status 130, and no late result is printed.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A minimal, correct repair with shipped-entry comparative proof and a consolidated regression; prior proof and test-budget concerns are resolved.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied Docker proof exercises the shipped launcher under real PTY Ctrl+C through an actual Gateway and speech plugin against a slow loopback HTTP provider: candidate exits 130, closes the caller RPC, and suppresses late output; paired uninterrupted controls return valid audio, and Gateway-owned synthesis retains its lifetime. The final head adds documentation only.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Ctrl+C acknowledges interruption but leaves a pending Gateway TTS caller waiting until the launcher force-kills the CLI.
Reason: A one-line repair restores established invocation cancellation behavior while preserving the documented independent synthesis lifetime.

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
Reviewed head: 4c5327d21a8f15510803a52c9eaeeb4078619780

Before merge

None.

Findings

None.

Agent review details

How this fits together

The 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]
Loading

Technical review

Best 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

  • Gateway TTS caller cancellation keeps the original intent (b655b24: The prior custody repair captured the invocation signal to prevent late destination writes while deliberately preserving completed synthesis and media lifetime.)
  • Existing cancellation regression matrix keeps the original intent (958ae1a: Exercise pending-work cancellation, output suppression, and cleanup through the registered CLI; the later audio repair extended the same matrix.)
  • Image test option formatting keeps the original intent (997c741: Consolidate redundant fixture setup without losing distinct behavior coverage; this PR only compacts an unchanged options object.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Exact introduced change: The introduced production change adds only the existing signal to callGateway; the test extends the existing cancellation matrix and preserves output-suppression and cleanup assertions. (src/cli/capability-cli/tts-runtime.ts:69, 4c5327d21a8f)
  • Current main still lacks forwarding: Current main captures getAsyncWorkSignal but omits it from the tts.convert Gateway call. (src/cli/capability-cli/tts-runtime.ts:59, 2808e34b4ad3)
  • Existing cancellation owner: callGateway rejects an already-aborted signal, stops its client on abort, removes listeners, and checks cancellation before request dispatch; the capability command suppresses output after accepted interruption. (src/gateway/call.ts:729, 4c5327d21a8f)
  • Shipped-entry proof: obviyus supplied independently built main/candidate results through the shipped launcher, real PTY SIGINT, actual Gateway and bundled OpenAI speech provider in secretless Docker. Candidate exits 130, closes its caller RPC, and prints no late envelope; both uninterrupted controls produce valid WAV output, and Gateway-owned synthesis completes after interrupted callers exit. The full previously truncated collector source was read at fix(cli): forward interrupt signal to gateway tts convert requests #194128 (comment). (c8b42e94bcb8)
  • Regression and proof reuse: The maintainer reports the final TTS cancellation case failing on unchanged frozen-main production and all 111 candidate cases passing at fix(cli): forward interrupt signal to gateway tts convert requests #194128 (comment); the final head changes only documentation relative to the exercised candidate. (src/cli/capability-cli.test.ts:961, 4c5327d21a8f)
  • History and intended ownership: Feature history covers the domain split, atomic publication, remote-output rejection, and accepted-interruption custody repair. The latter deliberately preserves synthesis lifetime; this PR respects that boundary. A scoped old-name git log -S search stopped at unavailable blob a65212618cdbfb2fd38cb8a0798ef54156743f19, so the original pre-split introduction remains unknown. (src/cli/capability-cli/tts-runtime.ts:47, b655b248d0a5)

Likely related people:

  • Peter Steinberger: Raw commit 9c065c8 adds src/cli/capability-cli/tts-runtime.ts:55 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 9c065c895e78; files: src/cli/capability-cli/tts-runtime.ts)
  • Ayaan Zaidi: Raw commit 958ae1a adds src/cli/capability-cli.test.ts:962 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 958ae1a20482; files: src/cli/capability-cli.test.ts)

PR surface

Source +1, Tests -3, Docs +1. Total -1 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 1 0 +1
Tests 1 6 9 -3
Docs 1 1 0 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 8 9 -1

Preflight source

Source 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

Metric Value Why it matters
Production versus test LOC Production +1/-0; tests +6/-9 The fix reuses the existing signal and RPC owner, while extending cancellation coverage without net test growth.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: A bounded CLI cancellation defect forces launcher escalation during pending Gateway TTS requests.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (4 earlier review cycles)
  • reviewed 2026-11-06T13:07:27.783Z sha 4e969c06e87eecc059cf131a52b7bb21df9ff909 :: needs real behavior proof before merge. :: [P2] Consolidate the TTS regression to satisfy the test-line budget
  • reviewed 2026-11-06T14:12:29.922Z sha c8b42e9 :: needs real behavior proof before merge. :: none
  • reviewed 2026-11-06T14:19:28.847Z sha c8b42e9 :: needs real behavior proof before merge. :: none
  • reviewed 2026-11-06T14:34:20.518Z sha c8b42e9 :: needs maintainer review before merge. :: none

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.
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Both blocking items from the prior review (head 4e969c06e8) are addressed on the current head c8b42e94bcb:

  1. Real behavior proof added — Shipped CLI (openclaw.mjs) + real built Gateway (gateway run --allow-unconfigured --bind loopback, token auth) + a local HTTP TTS fixture holding /v1/audio/speech for 20s, driven under a real controlling terminal (pty.fork). Ctrl+C while tts.convert is pending:

    • Head (2 repeats): exit 130 in ~98 ms (99.2ms / 97.6ms) — caller RPC closes, natural exit.
    • Base (2 repeats, same harness, signal line removed from the built runtime): hangs ~2.04s (2044.8ms / 2043.3ms), then launcher SIGKILL → exit -9.
    • 4/4 clean, red/green fully separated. Evidence artifacts under .artifacts/proof-194128/.
  2. Test-line budget (P2) — The v1 tts.test-support.ts registration module (18 net lines) was removed. v2 adds the TTS case as a row of the existing cancels pending %s execution it.each matrix at capability-cli.test.ts (no new file), reusing the same pending-Gateway mock already installed there. checks-fast-baseline-ratchets (line-cap + test-lines) is green on the current head.

@clawsweeper

clawsweeper Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Nov 6, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 6, 2026
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

Real PTY SIGINT proof: shipped CLI + live Gateway + slow HTTP TTS fixture

Reproducing the #192896 / #191635 recipe end to end against the exact head c8b42e94bcb:

  • Shipped CLI: /repo/openclaw.mjs infer tts convert --gateway --text hello --provider openai --model openai/tts-1 --voice alloy --json
  • Real Gateway: openclaw.mjs gateway run --port 18789 --allow-unconfigured --bind loopback, token auth (OPENCLAW_GATEWAY_TOKEN=test-token)
  • Slow HTTP TTS fixture: local POST /v1/audio/speech that holds the response 20s before returning a valid WAV (the pending request is what Ctrl+C must cancel)
  • Real controlling terminal: pty.fork(); the driver writes Ctrl+C to the foreground process group while tts.convert is pending, then records exit code and time-from-signal-to-exit (monotonic). No runtime monkeypatches, no fake Gateway, no injected errors; the CLI and Gateway run from the built dist in the same container.

Results

Lane Repeat After Ctrl+C signal→exit Exit
Head (fix) 1 Command interrupted by SIGINT. Waiting for cleanup before exiting. 99.2 ms 130
Head (fix) 2 same banner 97.6 ms 130
Base (no signal line in built runtime) 1 same banner 2044.8 ms -9 (SIGKILL)
Base (no signal line) 2 same banner 2043.3 ms -9 (SIGKILL)

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, harnessSafetyKill: false on every run.

Uninterrupted control (Head, same harness)

No Ctrl+C; the fixture holds only 3s so the request completes. The CLI exits 0 and prints the full tts.convert envelope — nothing suppressed, no late result:

{
  "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 OPENAI_API_KEY=sk-test-synthetic, loopback-only); no real provider, credentials, or endpoints were contacted. Full transcripts and result JSONs are archived under .artifacts/proof-194128/.

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@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 .artifacts/proof-194128/. They show pending tts.convert execution interrupted by SIGINT: HEAD exits 130 in <100 ms with no late result (caller cancellation), BASE hangs ~2.04 s then launcher SIGKILL (-9); Gateway-owned synthesis is held at the 20 s fixture in every run and untouched by this change. Uninterrupted control = the full 111-test capability-cli.test.ts suite green on the current head.

@clawsweeper

clawsweeper Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Nov 6, 2026
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 6, 2026
@obviyus

obviyus commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator

Maintainer shipped-entry proof on actual current main and the contributor candidate

  • Main: 2a2cd2931454fe75687b2dec1104289b9a66c273 (normal independently built source, not an inverse-edited bundle).
  • Candidate runtime: c8b42e94bcb8338ab0aa77a40b45f94dc5be9e9d; final head 4c5327d21a8f15510803a52c9eaeeb4078619780 adds only the operator documentation sentence. Contributor wangmiao0668000666's commit is preserved.
  • Secretless Docker node:24.22.1, normal shipped openclaw.mjs launcher, actual built Gateway and bundled OpenAI speech provider. No real API credentials. No Gateway protocol fixture or runtime patching.
  • Faithful local POST /v1/audio/speech: request model tts-1, voice alloy, requested wav; valid 2,044-byte PCM WAV response. Ordinary HTTP response latency: 20 seconds for interrupted runs, 3 seconds for controls, no injected failure.
  • Real controlling terminal via pty.fork; VINTR is written only after the real provider has received the synthesis request. A passive raw TCP/WebSocket observer forwards bytes unchanged and records the actual tts.convert caller request, Gateway receipt and caller closure.
Lane/case Exit VINTR → exit VINTR → caller RPC close
base/control 0 — —
base/read -9 2012.3 ms 2009.1 ms
cand/control 0 — —
cand/read 130 59.5 ms 34.5 ms

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 config file --json and sessions --agent main --json resolved the task-owned config and SQLite paths; config bytes were unchanged after every run. One setup-only attempt stopped at the intentional explicit-credential requirement for a URL override; the correction supplied the task's synthetic token. No product verdict was taken from that attempt.

Focused src/cli/capability-cli.test.ts: 111 passed, including pending TTS interruption and existing accepted-output custody cases. Focused touched-test/runtime typecheck, canonical typed lint (2 files), and formatting passed. Simplification: the existing signal and existing Gateway cancellation owner are reused; no new wrapper, API, schema, auth, retry or lifecycle policy. Source +1/-0, tests +6/-9 (net -3), docs +1; no allocation.

Collector sources

pins.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)

@obviyus

obviyus commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Nov 6, 2026
@obviyus

obviyus commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator

Additional regression receipt: copied the final capability-cli.test.ts into the independently built frozen-main container (2a2cd29), leaving main production code unchanged, and selected cancels pending tts execution. That case fails (Error: exit 1 through the existing CLI runtime mock); 110 unrelated cases were deliberately skipped. The candidate full suite passes all 111 cases, including this TTS row. The TTS runtime difference from frozen main remains exactly the one signal argument. The real shipped-entry red/green and RPC-close evidence is in #194128 (comment).

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 6, 2026
@obviyus
obviyus merged commit b8ce04a into openclaw:main Nov 6, 2026
116 of 117 checks passed
@obviyus

obviyus commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator

Landed in b8ce04a. Thanks @wangmiao0668000666. Ctrl+C now stops the TTS CLI right away.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 7, 2026
…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]>
obviyus added a commit that referenced this pull request Nov 8, 2026
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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 9, 2026
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]>
@wangmiao0668000666
wangmiao0668000666 deleted the fix/tts-gateway-signal branch November 11, 2026 00:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: XS status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants