Skip to content

fix(kilocode): cancel failed model discovery bodies - #109950

Merged
steipete merged 2 commits into
openclaw:mainfrom
sunlit-deng:sunlit/fix/kilocode-model-discovery-body
Jul 21, 2026
Merged

steipete merged 2 commits into
openclaw:mainfrom
sunlit-deng:sunlit/fix/kilocode-model-discovery-body

Conversation

@sunlit-deng

@sunlit-deng sunlit-deng commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where a failed Kilocode model discovery response could leave its response body unread while OpenClaw falls back to the static Kilocode catalog.

Why This Change Was Made

The non-OK discovery branch now cancels the response body before returning the fallback catalog, matching the cleanup behavior used by sibling provider discovery paths.

User Impact

Kilocode setup/model refresh failures keep the existing fallback behavior without holding a failed HTTP response stream open.

Evidence

  • Standalone local streaming-server proof: node --import tsx proof-live.mjs imports the production discoverKilocodeModels() module, routes only the fixed Kilocode URL's network boundary to a node:http loopback server, returns HTTP 500 with a streaming body, verifies the static catalog fallback, and prints the server-side failed response close event after fallback. The full proof-live.mjs source is included below.
  • Local HTTP server regression: node scripts/run-vitest.mjs extensions/kilocode/provider-models.test.ts -- -t "falls back to static catalog on HTTP error" passed with the committed loopback regression.
  • Full focused suite: node scripts/run-vitest.mjs extensions/kilocode/provider-models.test.ts passed 10 tests.
$ node --import tsx proof-live.mjs
[kilocode-models] Failed to discover models: HTTP 500, using static catalog
entrypoint: extensions/kilocode/provider-models.ts discoverKilocodeModels()
dependency-boundary: local node:http streaming server for fixed Kilocode URL
server-status: 500
fallback-model: kilo-auto/balanced
model-count: 1
response-close-observed: yes
server-write-count-before-close: 2
guard-release-called: yes

$ node scripts/run-vitest.mjs extensions/kilocode/provider-models.test.ts -- -t "falls back to static catalog on HTTP error"
Test Files  1 passed (1)
Tests  1 passed | 9 skipped (10)

$ node scripts/run-vitest.mjs extensions/kilocode/provider-models.test.ts
Test Files  1 passed (1)
Tests  10 passed (10)

The local-server proof is committed in extensions/kilocode/provider-models.test.ts: the server returns a non-OK streaming response, discoverKilocodeModels() returns the unchanged static Kilocode catalog, and the test asserts the server observed the failed response close.

standalone proof source
#!/usr/bin/env node
import { createServer } from "node:http";
import { registerHooks } from "node:module";
import { setTimeout as delay } from "node:timers/promises";

function listenOnLoopback(server) {
  return new Promise((resolve, reject) => {
    server.once("error", reject);
    server.listen(0, "127.0.0.1", () => {
      server.off("error", reject);
      const address = server.address();
      if (!address || typeof address === "string") {
        reject(new Error("expected local server to listen on a TCP port"));
        return;
      }
      resolve(`http://127.0.0.1:${address.port}/models`);
    });
  });
}

function waitForClose(timeoutMs) {
  return Promise.race([
    globalThis.__kilocodeProofResponseClosed,
    delay(timeoutMs).then(() => {
      throw new Error("timed out waiting for failed response close");
    }),
  ]);
}

delete process.env.NODE_ENV;
delete process.env.VITEST;

let closeObserved = false;
let writeCount = 0;
let releaseCalled = false;
let resolveResponseClosed;
globalThis.__kilocodeProofResponseClosed = new Promise((resolve) => {
  resolveResponseClosed = resolve;
});

const server = createServer((_request, response) => {
  response.writeHead(500, { "Content-Type": "text/plain" });
  response.write("temporary failure\n");
  writeCount += 1;
  const interval = setInterval(() => {
    writeCount += 1;
    response.write("stream body that should not be fully read\n");
  }, 10);
  response.on("close", () => {
    clearInterval(interval);
    closeObserved = true;
    resolveResponseClosed();
  });
});

const localModelsUrl = await listenOnLoopback(server);
globalThis.__kilocodeProofLocalModelsUrl = localModelsUrl;
globalThis.__kilocodeProofRelease = () => {
  releaseCalled = true;
};

registerHooks({
  resolve(specifier, context, nextResolve) {
    if (specifier === "openclaw/plugin-sdk/ssrf-runtime") {
      return {
        url:
          "data:text/javascript," +
          encodeURIComponent(`
export async function fetchWithSsrFGuard(params) {
  const response = await fetch(globalThis.__kilocodeProofLocalModelsUrl, params.init);
  return {
    response,
    finalUrl: globalThis.__kilocodeProofLocalModelsUrl,
    release: async () => globalThis.__kilocodeProofRelease(),
  };
}

export function ssrfPolicyFromHttpBaseUrlAllowedHostname(baseUrl) {
  return { allowedHostnames: [new URL(baseUrl).hostname] };
}
`),
        shortCircuit: true,
      };
    }
    return nextResolve(specifier, context);
  },
});

try {
  const { discoverKilocodeModels } = await import("./extensions/kilocode/provider-models.ts");
  const models = await discoverKilocodeModels();
  await waitForClose(1000);
  const fallback = models.find((model) => model.id === "kilo-auto/balanced");

  console.log("entrypoint: extensions/kilocode/provider-models.ts discoverKilocodeModels()");
  console.log("dependency-boundary: local node:http streaming server for fixed Kilocode URL");
  console.log("server-status: 500");
  console.log(`fallback-model: ${fallback?.id ?? "missing"}`);
  console.log(`model-count: ${models.length}`);
  console.log(`response-close-observed: ${closeObserved ? "yes" : "no"}`);
  console.log(`server-write-count-before-close: ${writeCount}`);
  console.log(`guard-release-called: ${releaseCalled ? "yes" : "no"}`);

  if (!fallback || !closeObserved || !releaseCalled || writeCount <= 0) {
    process.exitCode = 1;
  }
} finally {
  server.close();
}
regression proof excerpt
it("falls back to static catalog on HTTP error", async () => {
  let writeCount = 0;
  let resolveResponseClosed!: () => void;
  const responseClosed = new Promise<void>((resolve) => {
    resolveResponseClosed = resolve;
  });
  const server = createServer((_request, response) => {
    response.writeHead(500, { "Content-Type": "text/plain" });
    response.write("temporary failure\n");
    writeCount += 1;
    const interval = setInterval(() => {
      writeCount += 1;
      response.write("stream body that should not be fully read\n");
    }, 10);
    response.on("close", () => {
      clearInterval(interval);
      serverClosedFailedResponse = true;
      resolveResponseClosed();
    });
  });

  const localModelsUrl = await listenOnLoopback(server);
  const mockFetch = vi.fn(async (_url: string, init?: RequestInit) =>
    fetch(localModelsUrl, init),
  );

  try {
    await withFetchPathTest(mockFetch, async () => {
      const models = await discoverKilocodeModels();
      expect(models).toStrictEqual(EXPECTED_STATIC_KILOCODE_MODELS);
    });
    await responseClosed;
    expect(serverClosedFailedResponse).toBe(true);
    expect(writeCount).toBeGreaterThan(0);
  } finally {
    server.close();
  }
});

AI-assisted: built with Codex

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. labels Jul 17, 2026
@clawsweeper

clawsweeper Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 17, 2026, 10:16 AM ET / 14:16 UTC.

Summary
Cancels non-OK Kilocode model-discovery response bodies before returning the static fallback catalog and adds streaming-response closure coverage.

PR surface: Source +1, Tests +51. Total +52 across 2 files.

Reproducibility: yes. at source level: a non-OK streaming discovery response enters the fallback branch without consuming its body on current baseline behavior, and the loopback-server scenario directly exercises that path. The submitted after-fix proof observes the connection closing.

Review metrics: none identified.

Merge readiness
Overall: 🦞 diamond lobster
Proof: 🦞 diamond lobster
Patch quality: 🦞 diamond lobster
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Risk before merge

  • [P1] The PR base is behind current main, so merge approval should use a refreshed exact head and confirm the focused Kilocode test remains green after rebasing.

Maintainer options:

  1. Decide the mitigation before merge
    Land the focused cancellation and streaming regression unchanged after refreshing onto current main, preserving the existing static fallback while reliably releasing failed discovery streams.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Next step before merge

  • No automated repair remains; refresh the behind branch if required, rerun exact-head checks, and proceed through normal maintainer merge review.

Security
Cleared: The two-file patch adds no dependency, credential, permission, install, publishing, or executable supply-chain surface, and canceling an unused response narrows network-resource exposure.

Review details

Best possible solution:

Land the focused cancellation and streaming regression unchanged after refreshing onto current main, preserving the existing static fallback while reliably releasing failed discovery streams.

Do we have a high-confidence way to reproduce the issue?

Yes at source level: a non-OK streaming discovery response enters the fallback branch without consuming its body on current baseline behavior, and the loopback-server scenario directly exercises that path. The submitted after-fix proof observes the connection closing.

Is this the best way to solve the issue?

Yes. Canceling the unused response body at the owning provider branch is the narrowest maintainable fix, preserves fallback semantics, follows the Web Streams lifecycle contract, and is backed by a real streaming regression.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against b319493a529c.

Label changes

Label justifications:

  • P2: This is a bounded provider resource-cleanup bug with limited blast radius and preserved user-visible fallback behavior.
  • 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. Sufficient (live_output): After-fix live output from the production discovery entry point and a loopback streaming server shows fallback success, server-side response closure, bounded writes, and guard release.
  • proof: sufficient: Contributor real behavior proof is sufficient. After-fix live output from the production discovery entry point and a loopback streaming server shows fallback success, server-side response closure, bounded writes, and guard release.
Evidence reviewed

PR surface:

Source +1, Tests +51. Total +52 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 1 0 +1
Tests 1 55 4 +51
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 56 4 +52

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs extensions/kilocode/provider-models.test.ts -- -t "falls back to static catalog on HTTP error".
  • [P1] node scripts/run-vitest.mjs extensions/kilocode/provider-models.test.ts.

What I checked:

Likely related people:

  • pandemicsyn: Prior merged Provider/KiloCode catalog and malformed-discovery work credits this account, and the repository's live routing signals also identify them for this plugin area. (role: prior Kilocode feature contributor; confidence: medium; files: extensions/kilocode/provider-models.ts, extensions/kilocode/provider-models.test.ts)
  • vincentkoc: Prior merged Kilocode model-discovery behavior credits this account alongside recent provider and model-catalog maintenance, making them a strong review-routing candidate. (role: recent provider-area contributor; confidence: medium; files: extensions/kilocode/provider-models.ts, extensions/kilocode/provider-models.test.ts, docs/concepts/model-providers.md)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (4 earlier review cycles)
  • reviewed 2026-07-17T11:32:40.732Z sha e631e03781851971d6ca15cd188386135dbc6fe0 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-17T12:18:09.381Z sha 4a06ba0379e3cdffaeb1bf4c26aaa62549e4fb31 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-17T12:51:02.077Z sha 17caad99e3942fe5d0ae1baaa6d1adb2d743ff88 :: needs changes before merge. :: [P2] Revert the unmatched API baseline checksums
  • reviewed 2026-07-17T13:33:38.840Z sha 36ae254f26831f99b5d30dc2b4f5b48fcca67483 :: needs maintainer review before merge. :: none

@sunlit-deng

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@sunlit-deng
sunlit-deng force-pushed the sunlit/fix/kilocode-model-discovery-body branch from 4a06ba0 to 17caad9 Compare July 17, 2026 12:47
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: S and removed size: XS labels Jul 17, 2026
@sunlit-deng

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 17, 2026
@sunlit-deng
sunlit-deng force-pushed the sunlit/fix/kilocode-model-discovery-body branch from 17caad9 to 36ae254 Compare July 17, 2026 13:29
@openclaw-barnacle openclaw-barnacle Bot removed the docs Improvements or additions to documentation label Jul 17, 2026
@sunlit-deng

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@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 rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jul 17, 2026
@steipete steipete self-assigned this Jul 21, 2026
@steipete
steipete force-pushed the sunlit/fix/kilocode-model-discovery-body branch from 36ae254 to d167c85 Compare July 21, 2026 02:01
@steipete
steipete merged commit a31f6aa into openclaw:main Jul 21, 2026
92 of 94 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 21, 2026
* fix(kilocode): cancel failed model discovery bodies

* test(kilocode): prove failed discovery closes response
steipete pushed a commit to xydt-juyaohui/openclaw that referenced this pull request Aug 2, 2026
…rowing

postGitHubDeviceFlowForm now drops the unread response stream before it
raises on a non-OK HTTP status. GitHub OAuth error responses ship a JSON
body (`{error, error_description}`) that this helper never consumes, so
the underlying fetch connection previously stayed open holding the
payload until the caller's release() ran, keeping the device-flow socket
half-drained on every 4xx/5xx.

Mirrors the recently-merged qqbot/kilocode/tlon fixes for the same
'cancel body before throwing' pattern (openclaw#110008, openclaw#109950, openclaw#112059).
steipete added a commit that referenced this pull request Aug 2, 2026
…rowing (#112268)

* fix(github-copilot): cancel unread device-flow error bodies before throwing

postGitHubDeviceFlowForm now drops the unread response stream before it
raises on a non-OK HTTP status. GitHub OAuth error responses ship a JSON
body (`{error, error_description}`) that this helper never consumes, so
the underlying fetch connection previously stayed open holding the
payload until the caller's release() ran, keeping the device-flow socket
half-drained on every 4xx/5xx.

Mirrors the recently-merged qqbot/kilocode/tlon fixes for the same
'cancel body before throwing' pattern (#110008, #109950, #112059).

* style(github-copilot): clarify response release ordering

---------

Co-authored-by: Peter Steinberger <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 3, 2026
…rowing (openclaw#112268)

* fix(github-copilot): cancel unread device-flow error bodies before throwing

postGitHubDeviceFlowForm now drops the unread response stream before it
raises on a non-OK HTTP status. GitHub OAuth error responses ship a JSON
body (`{error, error_description}`) that this helper never consumes, so
the underlying fetch connection previously stayed open holding the
payload until the caller's release() ran, keeping the device-flow socket
half-drained on every 4xx/5xx.

Mirrors the recently-merged qqbot/kilocode/tlon fixes for the same
'cancel body before throwing' pattern (openclaw#110008, openclaw#109950, openclaw#112059).

* style(github-copilot): clarify response release ordering

---------

Co-authored-by: Peter Steinberger <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: kilocode 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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants