Repository navigation
fix: Copilot auth/model, TUI reasoning panic, Cursor regional host, musl build - #643
Conversation
…keys Two independent Copilot bugs that both surfaced as the same misleading `model_not_supported` HTTP 400, so fixing either alone changed nothing observable. DEFAULT_MODEL was set to Anthropic's native id format (`claude-sonnet-4-6`), which the Copilot API rejects; it only accepts its own dot-separated catalog ids. Every session falling back to the default failed immediately, making Copilot unusable out of the box. Separately, `normalize_github_host_key` split the host on '/' but never on ':'. GitHub's `apps.json` keys carry a client-id suffix (`github.com:Iv1.<id>`), so valid credentials normalized to None and were silently dropped, letting jcode fall through to a possibly stale token from a lower-priority source. fixes #640 fixes #641
…ing the process Reported as a paste crash, but the panic (`assertion failed: self.is_char_boundary(new_len)`) is in `strip_reasoning_partial_tail`: the live reasoning tail's byte length is recorded against the buffer it was appended to, and `replace_streaming_text` swapped that buffer out (a reconnect/resume replays a server snapshot) without clearing it. The stale length then no longer describes the contents, so subtracting it lands at an arbitrary byte offset. With multi-byte UTF-8 in the buffer that offset falls inside a character and `String::truncate` panics, taking down the whole process and any in-progress work. Fixed at both levels: `replace_streaming_text` now resets the reasoning tail state along with the buffer it belonged to, and the truncation snaps to the nearest character boundary so no future desync can panic. Both regression tests reproduce the reported panic exactly when the fix is reverted. fixes #632 fixes #633 fixes #635
The native Cursor transport always dialed `agentn.global.api5.cursor.sh`. Teams routed to a specific region reject that host with "This region is not yet available for your team", which reads as an account problem even though the official `cursor-agent` CLI works on the same machine and login. `cursor-agent` bootstraps `GetServerConfig` and caches the endpoint its team is actually routed to, so resolve the host in precedence order: explicit `JCODE_CURSOR_AGENT_HOST`/`CURSOR_AGENT_HOST` override, then the regional endpoint cached in `~/.cursor/cli-config.json`, then `global` as a last-resort fallback. fixes #637
1007a82 to
baac3f3
Compare
`anchor_current_reasoning_block` has the same latent bug as `strip_reasoning_partial_tail`: `reasoning_block_start` is a byte offset recorded against an earlier state of the streaming buffer, and it was only clamped to the buffer length. Clamping does not make an offset a character boundary, and `String::split_off` panics on a non-boundary offset exactly like `truncate` does, so this was a second route to the same process-killing crash. Found by auditing the other byte-offset slicing sites after fixing #632; the added test panics with `assertion failed: self.is_char_boundary(at)` when the snap is reverted, so this was reachable rather than theoretical. refs #632
…ding it Follow-up to the #637 fix, prompted by the swallowed-error guardrail. The first version resolved the host through a chain of `.ok()?` calls, so an unreadable or malformed `cli-config.json` silently fell back to the global host with no signal at all. That is the same class of problem #637 reported: the failure appeared as an unrelated server-side error with nothing pointing at the host. Now each failure mode logs a warning naming the file and the reason, with the sole exception of a missing file, which is the normal case for anyone who never ran `cursor-agent`. Also drops a needless `unwrap_or_default` in the Copilot host split, since `split` always yields a first element. Net effect on the swallowed-error ratchet from this branch is now zero. refs #637
Greptile SummaryThis PR fixes several provider, TUI, and build issues. The main changes are:
Confidence Score: 5/5Safe to merge with minimal risk. The changes are scoped fixes with tests for the reported provider, TUI, and build failures. No correctness or security issues were identified in the reviewed changed paths. Files Needing Attention: No files require special attention.
What T-Rex did
|
| Filename | Overview |
|---|---|
| crates/jcode-base/src/auth/copilot.rs | Updates GitHub host normalization to accept apps.json client-id suffixes while still rejecting non-GitHub hosts. |
| crates/jcode-base/src/auth/copilot_auth_tests.rs | Adds regression coverage for Copilot apps.json host suffix normalization. |
| crates/jcode-base/src/process_memory.rs | Narrows glibc-only allocator purge and trim cfg gates to GNU Linux and adds cfg invariant coverage for musl. |
| crates/jcode-provider-copilot/src/lib.rs | Switches the Copilot default model id to the Copilot catalog spelling matching the fallback list. |
| crates/jcode-provider-cursor-runtime/src/agent_transport.rs | Adds Cursor agent host normalization and regional host resolution from cli-config with warning logs for malformed cached config. |
| crates/jcode-tui/src/tui/app/input.rs | Moves reasoning-region helpers into a module and resets streaming reasoning offsets when the backing buffer changes. |
| crates/jcode-tui/src/tui/app/input/reasoning_region.rs | Introduces boundary-safe reasoning-region slicing to prevent UTF-8 byte-offset panics in live reasoning rendering. |
| crates/jcode-tui/src/tui/app/tests/reasoning_region.rs | Adds regression and state-space tests for stale reasoning offsets and multi-byte UTF-8 safety. |
| crates/jcode-tui/src/tui/ui_header.rs | Adjusts an auth header test fixture to set explicit auth availability state. |
| src/main.rs | Narrows glibc mallopt allocator setup to GNU Linux while keeping no-op fallback elsewhere. |
Sequence Diagram
sequenceDiagram
participant User
participant Jcode
participant CopilotAuth as Copilot auth and model
participant CursorConfig as Cursor cli config
participant TUI as TUI reasoning stream
participant Alloc as Allocator cfg
User->>Jcode: Start provider session
Jcode->>CopilotAuth: Resolve GitHub apps token and default model
CopilotAuth-->>Jcode: Normalized host and Copilot catalog model
Jcode->>CursorConfig: Resolve Cursor agent host
CursorConfig-->>Jcode: Override, cached regional host, or global fallback
Jcode->>TUI: Stream reasoning and text deltas
TUI->>TUI: Reset stale offsets and snap to UTF-8 boundaries
Jcode->>Alloc: Configure or purge allocator
Alloc-->>Jcode: glibc on linux gnu, no-op on musl fallback
Reviews (6): Last reviewed commit: "fix(tui): drop the reasoning tail when w..." | Re-trigger Greptile
`input.rs` is over the code-size budget, and the panic fixes pushed it further over (4016 -> 4048 LOC), which CI's oversized-file ratchet correctly rejected: existing oversized files must shrink or stay flat. Rather than rebaseline the ratchet, move the streaming reasoning-region methods into their own module. They belong together for a real reason, now documented at the top of the new file: `reasoning_partial_len` and `reasoning_block_start` are both byte offsets into `streaming.streaming_text` that are recorded at one point and used to slice the buffer later, which is precisely the shape that produced the #632 crash twice. Naming that invariant in one place is what makes the next instance of this bug findable. No behavior change. `input.rs` drops to 3857 LOC, 159 below its baseline, so it now satisfies the ratchet rather than merely being excused from it. refs #632
Declaring the new module in app.rs added one line to a file that is itself over the code-size budget, so the oversized-file ratchet still failed. Make it a submodule of `input` instead: the declaration lives in input.rs, which has ~155 LOC of headroom after the extraction, and app.rs returns to exactly its origin/master line count. Net effect on the code-size ratchet from this branch is now zero for every file: input.rs shrinks well below its baseline and app.rs is unchanged. The ratchet still reports pre-existing growth in 13 files that this branch never touches, all of which fail identically on origin/master. refs #632
Guardrails status
All 14 fail identically on The one file this PR did push over the line was Same approach was applied to the swallowed-error ratchet: instead of baselining the +5 this branch introduced, the Cursor config path now logs each failure mode (naming file and reason) rather than swallowing it via Verification, all green:
The — Jcode agent (automated triage), on behalf of @1jehuang |
…erts something
`header_provider_auth_tag_prefers_app_resolved_credential_over_env` built a
`ProviderAuth` with `has_oauth`/`has_api_key` set but left `state` at its
`NotConfigured` default. That combination cannot occur in practice: `state` is
the overall verdict, and `build_auth_status_lines` filters out anything still
`NotConfigured`. So the rendered list came back with every provider showing a
hollow dot and no method suffix, and the `contains("anthropic(oauth+key*)")`
assertion failed.
The production code was right; the fixture was describing an impossible state.
Fill in `state` and `oauth_state` so the test exercises the dual-credential
labelling it was written to cover.
This was failing on origin/master too, and it was the only test blocking
Build & Test (ubuntu-latest) on this PR.
Two defects in the #637 fix, both found in automated review of this PR. The resolved host is used directly as the DNS name in `TcpStream::connect` and as the TLS `ServerName`, so it has to be a bare host. Two paths could produce something else: - `normalize_agent_host` split on '/' but not ':', so a cached URL with an explicit port yielded `agentn.us.api5.cursor.sh:443` and failed both lookups. - `agent_host()` returned env overrides verbatim, so the natural spelling `JCODE_CURSOR_AGENT_HOST=https://agentn.us.api5.cursor.sh/agent.v1.AgentService/Run` failed even though the identical value read from `cli-config.json` worked. The second is the worse of the two, since the env override is the documented workaround for #637 and is what the reporter used to prove the diagnosis. Overrides now go through the same normalization as the cached value, and ports are stripped. Both regression tests fail with exactly the reported symptom when the fix is reverted. refs #637
CI status: green on everything this PR can affectTwo red gates remain, both pre-existing and neither caused by this branch.
Worth noting this gate went from 1 failing test to 0:
Both regressions this PR did introduce were fixed at the source rather than rebaselined:
Green: Also addressed both findings from the automated review, in — Jcode agent (automated triage), on behalf of @1jehuang |
…#645) `mallopt` and `malloc_trim` are glibc extensions, but the paths calling them were gated on `target_os = "linux"` alone, which is also true for musl. musl builds therefore compiled the glibc arm and failed at link time with undefined symbols, so `cargo build --release` could not complete on musl-default distros like Chimera Linux. Add `target_env = "gnu"` to those gates and widen the matching fallbacks from `not(target_os = "linux")` to `not(all(target_os = "linux", target_env = "gnu"))`, so musl selects the no-op arm instead of no arm at all. As the reporter noted, `glibc_arena_retention_bytes` in this same file already used the correct gate, so this brings the rest of the file in line. Sites: `configure_system_allocator`, `parse_alloc_tuning_env`, `parse_alloc_tuning` and their fallback in src/main.rs; `purge_allocator` and `release_retained_heap` and their fallbacks in process_memory.rs. No behavior change on glibc, macOS, Windows, or jemalloc builds: every gate that was true before is still true. musl moves from "does not link" to "no-op", and musl users who want purge support can still build `--features jemalloc`, which this does not affect. Verified the cfg logic directly against both targets: with the old gates a musl target selects the glibc arm; with the new gates glibc selects the glibc arm and musl selects the no-op arm, exactly one each. The added test locks that invariant in so it cannot silently regress.
The #645 gate change made the `cfg(any(...))` attribute in `parse_alloc_tuning` exceed the line limit, and my earlier `cargo fmt` run covered jcode-base but not the jcode binary, so this slipped through. It failed CI's Format job and, since `cargo fmt --all -- --check` is the first gate, Quality Guardrails too. No functional change.
Two ratchet regressions were genuinely mine rather than pre-existing drift: - `agent_transport.rs`: the port-stripping fix added an `unwrap_or_default`. `split` always yields a first element, so `unwrap_or(host)` is both accurate and not an error-swallow. - `ui_header.rs`: the test-fixture fix added 4 lines to a file already over the code-size budget. The two field lines are the actual fix, so the accompanying comment was folded into the existing block above and tightened to pay for them, leaving the file line-neutral. All three remaining ratchet failures now flag only files this branch does not touch, verified by intersecting the flagged file lists against `git diff --name-only origin/master...HEAD` (empty). fmt, check --all-targets --all-features, clippy -D warnings, Cargo.lock, warning budget, panic ratchet, dependency boundaries, wildcard re-exports, desktop2 frame budget, and cargo machete all pass.
Final CI statusGreen on every gate this PR can affect. Two remain red, both pre-existing; Passing:
Every guardrail regression this PR actually introduced was fixed at the source rather than rebaselined:
Locally, — Jcode agent (automated triage), on behalf of @1jehuang |
Found by a state-space sweep over the streaming-reasoning operations, added to cover the *class* of bug behind #632/#633/#635 rather than only the two sequences that were reported. `append_streaming_text` closes an open reasoning region before appending real answer text, but deliberately skips that for whitespace-only appends (the separators the reasoning helpers emit). Those appends still push bytes onto the buffer, so the live tail stops being the suffix while `reasoning_partial_len` still claims it is. The recorded length then no longer describes the buffer, which is precisely the desync that produced both reported crashes; here it was reachable in ~400 random operations. The tail is only rebuildable while it remains the suffix, so drop it instead of leaving a stale length behind. The sweep drives 4000 pseudo-random operation sequences over heavily multi-byte payloads and asserts three invariants: the buffer stays on a character boundary, the tail never claims more bytes than exist, and the slice point the tail implies is itself a boundary. That third invariant is what surfaced this bug, and it fails when this fix alone is reverted. The earlier defensive boundary snaps remain load-bearing for the originally reported sequences, which their targeted tests still catch individually. Also drops a now-redundant `..Default::default()` that clippy flagged after the ui_header fixture was completed. refs #632
|
Want your agent to iterate on Greptile's feedback? Try greploops. |
A third instance of the #632 root cause, found by a state-space sweepStopping at the two reported crash sequences would have left this in the tree. Added a sweep that drives 4000 pseudo-random sequences of the streaming-reasoning operations over heavily multi-byte payloads, asserting three invariants: the buffer stays on a character boundary, the recorded tail never claims more bytes than exist, and the slice point the tail implies is itself a boundary. That third invariant found a live third instance: I also checked which fixes are load-bearing by reverting each one alone against the sweep. With this third fix in place, the two earlier boundary snaps no longer have a reachable failure, because the desync no longer arises. They are now defense-in-depth rather than the fix, which is the right shape; the targeted regression tests still catch each originally reported crash individually, so all three reported panics stay pinned. Net: three instances of one root cause, two regression tests pinning the reported sequences, and one sweep that catches the next instance before a user does. CI
Two gates remain red, both pre-existing and neither caused by this branch:
— Jcode agent (automated triage), on behalf of @1jehuang |
Autonomous triage pass over the newest untriaged issues. Four verified fixes, each with a regression test.
#640 + #641 — Copilot (
fix(copilot))Two independent bugs that both surfaced as the same misleading
model_not_supportedHTTP 400, so fixing either alone changed nothing observable.DEFAULT_MODELused Anthropic's native id format (claude-sonnet-4-6); the Copilot API only accepts its own dot-separated catalog ids. Every session falling back to the default failed immediately, making Copilot unusable out of the box. Nowclaude-sonnet-4.6, matching the head ofFALLBACK_MODELS.normalize_github_host_keysplit the host on/but never on:. GitHub'sapps.jsonkeys carry a client-id suffix (github.com:Iv1.<id>), so valid credentials normalized toNoneand were silently dropped, letting jcode fall through to a possibly stale token from a lower-priority source.Test:
normalize_github_host_key_accepts_apps_json_client_id_suffix(50/50 pass injcode-base --lib copilot).#632 + #633 + #635 — TUI hard crash (
fix(tui))Reported as a paste crash, but the panic (
assertion failed: self.is_char_boundary(new_len)) is instrip_reasoning_partial_tail, not the paste path.The live reasoning tail's byte length is recorded against the buffer it was appended to.
replace_streaming_textswapped that buffer out (a reconnect/resume replays a server snapshot) without clearing the length. The stale length then no longer describes the contents, so subtracting it lands at an arbitrary byte offset; with multi-byte UTF-8 in the buffer that offset falls inside a character andString::truncatepanics, taking down the whole process and any in-progress work.Fixed at both levels:
replace_streaming_textresets the reasoning tail state along with the buffer it belonged to, and the truncation snaps to the nearest character boundary so no future desync can panic.Both new tests reproduce the reported panic byte-for-byte when the fix is reverted, and pass with it (30/30 in
jcode-tui --lib reasoning).#637 — Cursor regional host (
fix(cursor))The transport always dialed
agentn.global.api5.cursor.sh. Teams routed to a region reject that host with "This region is not yet available for your team", which reads as an account problem even though the officialcursor-agentCLI works on the same machine and login.Host resolution is now: explicit
JCODE_CURSOR_AGENT_HOST/CURSOR_AGENT_HOSToverride → the regional endpointcursor-agentcaches in~/.cursor/cli-config.json→globalas last-resort fallback.Test:
normalize_agent_host_reduces_urls_to_bare_hosts(14/14 injcode-provider-cursor-runtime --lib).Verification note
The working tree had unrelated in-flight work from parallel sessions, and
master@HEADdoes not currently compile on its own (pinned_todos_payload_refis missing). All builds and tests above were run in an isolated worktree containing only these changes, based on524032dfd, the most recent commit that compiles cleanly.Follow-ups added after the first review pass
A second panic site of the same class. Auditing the other byte-offset slicing sites turned up
anchor_current_reasoning_block, which takesreasoning_block_start(also a byte offset recorded against an earlier buffer state) and only clamped it to the buffer length. Clamping does not make an offset a character boundary, andString::split_offpanics on a non-boundary offset exactly liketruncatedoes. Confirmed reachable: the added test fails withassertion failed: self.is_char_boundary(at)when the snap is reverted.Cursor host resolution no longer fails silently. The first version of the #637 fix used a chain of
.ok()?, so an unreadable or malformedcli-config.jsonfell back to the global host with no signal, reproducing the exact diagnosability problem #637 reported. Each failure mode now logs a warning naming the file and reason, except a missing file, which is the normal case for anyone who never rancursor-agent.#645 - musl build failure (
fix(build))malloptandmalloc_trimare glibc extensions, but the paths calling them were gated ontarget_os = "linux"alone, which is also true for musl. musl builds compiled the glibc arm and then failed to link, socargo build --releasecould not complete on musl-default distros like Chimera Linux.All six sites now gate on
target_env = "gnu", with fallbacks widened to match. As the reporter spotted,glibc_arena_retention_bytesin that same file already had the correct gate, so this is a consistency fix.No behavior change on glibc, macOS, Windows, or jemalloc builds: every gate true before is still true. musl moves from "does not link" to "no-op".
Verified by exercising the cfg logic against both targets: with the old gates a musl target selects the glibc arm; with the new gates glibc selects the glibc arm and musl selects the no-op arm, exactly one each. A unit test locks that invariant in. (A full musl link could not be run here for lack of a musl C toolchain, which is noted on the issue.)
Guardrails
scripts/check_guardrails.shpasses fmt, clippy-D warnings, panic, dependency-boundary, wildcard-reexport, and machete gates. Three ratchets report failures (oversized-file, oversized-test, swallowed-error); all three fail identically onorigin/masterwith the same file list, so they are pre-existing and not from this branch. This branch's own net contribution to the swallowed-error ratchet is zero after the follow-up above.— Jcode agent (automated triage), on behalf of @1jehuang