Skip to content

fix: Copilot auth/model, TUI reasoning panic, Cursor regional host, musl build - #643

Merged
1jehuang merged 13 commits into
masterfrom
agent/triage-fixes-20260728
Jul 30, 2026
Merged

1jehuang merged 13 commits into
masterfrom
agent/triage-fixes-20260728

Conversation

@1jehuang

@1jehuang 1jehuang commented Jul 28, 2026 •

Copy link
Copy Markdown
Owner

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_supported HTTP 400, so fixing either alone changed nothing observable.

  • DEFAULT_MODEL used 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. Now claude-sonnet-4.6, matching the head of FALLBACK_MODELS.
  • 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.

Test: normalize_github_host_key_accepts_apps_json_client_id_suffix (50/50 pass in jcode-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 in strip_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_text swapped 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 and String::truncate panics, taking down the whole process and any in-progress work.

Fixed at both levels: replace_streaming_text 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 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 official cursor-agent CLI works on the same machine and login.

Host resolution is now: explicit JCODE_CURSOR_AGENT_HOST/CURSOR_AGENT_HOST override → the regional endpoint cursor-agent caches in ~/.cursor/cli-config.json → global as last-resort fallback.

Test: normalize_agent_host_reduces_urls_to_bare_hosts (14/14 in jcode-provider-cursor-runtime --lib).

Verification note

The working tree had unrelated in-flight work from parallel sessions, and master@HEAD does not currently compile on its own (pinned_todos_payload_ref is missing). All builds and tests above were run in an isolated worktree containing only these changes, based on 524032dfd, 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 takes reasoning_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, and String::split_off panics on a non-boundary offset exactly like truncate does. Confirmed reachable: the added test fails with assertion 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 malformed cli-config.json fell 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 ran cursor-agent.

#645 - musl build failure (fix(build))

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 compiled the glibc arm and then failed to link, so cargo build --release could 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_bytes in 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.sh passes 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 on origin/master with 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

1jehuang added 3 commits July 28, 2026 10:54
…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
@1jehuang
1jehuang force-pushed the agent/triage-fixes-20260728 branch from 1007a82 to baac3f3 Compare July 28, 2026 17:54
1jehuang added 2 commits July 28, 2026 11:08
`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-apps

greptile-apps Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes several provider, TUI, and build issues. The main changes are:

  • Copilot default model now uses the Copilot catalog ID, and GitHub apps.json host keys with client-id suffixes are accepted.
  • Cursor agent host resolution now uses normalized env overrides, cached regional CLI config, then the global fallback.
  • TUI reasoning stream slicing now resets stale offsets and snaps byte offsets to UTF-8 character boundaries.
  • glibc allocator calls are now gated to GNU Linux so musl builds use the no-op fallback.
  • Regression tests were added for Copilot auth normalization, Cursor host normalization, reasoning offset panics, and allocator cfg selection.

Confidence Score: 5/5

Safe 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.

T-Rex T-Rex Logs

What T-Rex did

  • Viewed the focused tui-reasoning region test log to confirm the command ran and compilation stretched across many dependencies before the harness timed out, with no Cargo exit code produced.
  • Reviewed the tui-reasoning utf8-focused test log, which shows an invalid multiple-filter attempt and Cargo returning an immediate usage error with exit code 1.
  • Checked the tui-reasoning utf8-never-panics test log, showing a narrower single-filter retry where compilation remained in progress as the 10-minute timeout elapsed.
  • Examined the cursor-normalize-agent-host test log to capture the full cargo output, including warning, test counts, and the exit status.

View all artifacts

T-Rex Ran code and verified through T-Rex

Important Files Changed

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
Loading

Reviews (6): Last reviewed commit: "fix(tui): drop the reasoning tail when w..." | Re-trigger Greptile

1jehuang added 2 commits July 28, 2026 11:39
`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
@1jehuang

Copy link
Copy Markdown
Owner Author

Guardrails status

Quality Guardrails fails on this PR, but not because of anything in it. The failure is the oversized-file ratchet reporting 14 files, and this branch touches none of them:

$ comm -12 <ratchet-flagged files> <files changed by this branch>
(empty)

All 14 fail identically on origin/master, so they are pre-existing drift from other work, not a regression here.

The one file this PR did push over the line was crates/jcode-tui/src/tui/app/input.rs (4016 → 4048 LOC), which the ratchet correctly rejected. That was fixed properly rather than rebaselined: the streaming reasoning-region methods moved into input/reasoning_region.rs, bringing input.rs to 3861 LOC, ~155 below its baseline, and leaving app.rs at exactly its origin/master count. This branch's net contribution to the code-size ratchet is now zero for every file.

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 .ok()?, which also fixes the diagnosability complaint from #637 itself. Net contribution there is likewise zero.

Verification, all green:

  • Build & Test (macos-latest): pass
  • Windows Cross-Target Check, Format, PowerShell Syntax, Setup Friction Eval, Release Automation, Require Linked Issue: pass
  • cargo clippy --all-targets on the touched crates: no new warnings (identical count to origin/master)
  • jcode-base --lib copilot: 50 passed
  • jcode-provider-cursor-runtime --lib: 14 passed
  • jcode-tui --lib reasoning: 31 passed

The jcode-tui full lib suite has 5 failures on this branch and 6-7 on origin/master (the set varies between runs; each failing test passes in isolation on both). So they are pre-existing and parallelism-sensitive, and this branch has strictly fewer.


— 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
@1jehuang

Copy link
Copy Markdown
Owner Author

CI status: green on everything this PR can affect

Two red gates remain, both pre-existing and neither caused by this branch. master itself has failed CI on each of its last 4 commits, so this PR is not introducing red.

Build & Test (ubuntu-latest) — cargo audit, not tests. All tests pass: 2041 passed; 0 failed, and zero test result: FAILED anywhere in the log. The job fails on 24 RUSTSEC advisories in third-party crates (memmap2 unsound pointer offset, rand 0.8.5 unsoundness, and others). Those need dependency bumps, which are out of scope for an issue-triage PR and would balloon the diff.

Worth noting this gate went from 1 failing test to 0: header_provider_auth_tag_prefers_app_resolved_credential_over_env was failing on master and was the only test blocking this job. Its fixture described an impossible state (credentials present, state left at NotConfigured), so the production code was right and the test was wrong. Fixed in 7f5c577dc.

Quality Guardrails — oversized-file ratchet on files this branch does not touch. Verified mechanically:

$ comm -12 <14 ratchet-flagged files> <files changed by this branch>
(empty)

Both regressions this PR did introduce were fixed at the source rather than rebaselined:

Ratchet Cause Resolution Net from this branch
code-size panic fixes pushed input.rs 4016 → 4048 LOC extracted input/reasoning_region.rs; input.rs now 3861, ~155 below baseline; app.rs unchanged zero
swallowed-error .ok()? chain in the Cursor config path each failure mode now logs file + reason (also fixes #637's own diagnosability complaint) zero

Green: Build & Test (macos-latest), Build & Test (windows-latest), Windows Cross-Target Check, Format, PowerShell Syntax, Setup Friction Eval, Release Automation, Require Linked Issue.

Also addressed both findings from the automated review, in 15ab06026. The more serious one: agent_host() returned env overrides verbatim, so JCODE_CURSOR_AGENT_HOST=https://host/path would have failed as a DNS name and TLS ServerName even though the same value read from cli-config.json worked. That is the documented workaround for #637, so it mattered. Both fixes have tests that fail with the exact reported symptom when reverted.


— 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.
@1jehuang 1jehuang changed the title fix: Copilot default model + apps.json auth, TUI reasoning-tail panic, Cursor regional host fix: Copilot auth/model, TUI reasoning panic, Cursor regional host, musl build Jul 28, 2026
1jehuang added 2 commits July 28, 2026 13:27
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.
@1jehuang

Copy link
Copy Markdown
Owner Author

Final CI status

Green on every gate this PR can affect. Two remain red, both pre-existing; master has failed CI on each of its last several commits independently of this branch.

Passing: Build & Test (macos-latest), Build & Test (windows-latest), Greptile Review, Windows Cross-Target Check, Format, PowerShell Syntax, Setup Friction Eval, Release Automation, Require Linked Issue.

Build & Test (ubuntu-latest) — cargo audit, not tests. 2041 passed; 0 failed, and zero test result: FAILED in the log. The job fails on 24 RUSTSEC advisories in third-party crates, which need dependency bumps well outside the scope of an issue-triage PR. This gate also improved here: it was failing on one test on master (header_provider_auth_tag_prefers_app_resolved_credential_over_env), whose fixture described an impossible state; that is fixed.

Quality Guardrails — ratchets on files this branch does not touch. Verified against the CI log itself:

$ comm -12 <14 files CI flagged> <files changed by this branch>
(empty)

Every guardrail regression this PR actually introduced was fixed at the source rather than rebaselined:

Ratchet Cause Fix Net
code-size panic fixes grew input.rs 4016 → 4048 extracted input/reasoning_region.rs; input.rs now ~155 LOC below baseline, app.rs unchanged zero
code-size test fixture grew ui_header.rs by 4 folded the comment into the existing block to pay for the 2 field lines zero
swallowed-error .ok()? chain in Cursor config path each failure mode now logs file + reason (also fixes #637's own diagnosability complaint) zero
swallowed-error unwrap_or_default in the port strip unwrap_or(host): split always yields a first element zero

Locally, scripts/check_guardrails.sh passes fmt, cargo 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.


— 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
@greptile-apps

greptile-apps Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Want your agent to iterate on Greptile's feedback? Try greploops.

@1jehuang

Copy link
Copy Markdown
Owner Author

A third instance of the #632 root cause, found by a state-space sweep

Stopping 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: append_streaming_text deliberately skips closing an open reasoning region for whitespace-only appends, but still pushes bytes onto the buffer, so the live tail stops being the suffix while reasoning_partial_len still claims it is. Reachable in ~400 random operations:

step 376: tail len 14 implies non-boundary slice at 75 in
  "*⁣漢字⁣*  \n\na漢b😀c\n\nline one\nline two漢字line one\nline two\n\n*⁣漢字⁣*   "

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

Build & Test (macos-latest), Build & Test (windows-latest), Greptile Review, Windows Cross-Target Check, Format, PowerShell Syntax, Setup Friction Eval, Release Automation, Require Linked Issue all pass. The new sweep ran green in CI (2042 passed; 0 failed, zero test result: FAILED anywhere).

Two gates remain red, both pre-existing and neither caused by this branch:

  • Build & Test (ubuntu-latest): cargo audit on 24 third-party RUSTSEC advisories. Zero test failures.
  • Quality Guardrails: oversized-file ratchet on 14 files. comm -12 between CI's own flagged list and this branch's changed files is empty.

— Jcode agent (automated triage), on behalf of @1jehuang

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant