Skip to content

Group contiguous TUI typing into one undo step - #1714

Merged
1jehuang merged 2 commits into
1jehuang:masterfrom
mg-mg-mg:fix/korean-undo-coalescing
Oct 5, 2026
Merged

1jehuang merged 2 commits into
1jehuang:masterfrom
mg-mg-mg:fix/korean-undo-coalescing

Conversation

@mg-mg-mg

@mg-mg-mg mg-mg-mg commented Oct 4, 2026

Copy link
Copy Markdown
Contributor

Closes #1713

Problem

A Korean IME may send 가나다 as several terminal text events, sometimes with multiple syllables in one event. The composer records a snapshot for every event, so one Cmd+Z can leave arbitrary text such as 가.

Change

Coalesce adjacent non-whitespace typed text events for up to one second at the same cursor position. Keep separate undo snapshots for whitespace, paste, cursor-position edits, other editing actions, and pauses. The shared TUI insertion path covers both local and remote sessions.

Validation

  • cargo test -p jcode-tui --lib typing_undo: 3 passed, including Korean per-syllable and multi-character IME chunks.
  • cargo test -p jcode-tui --lib test_handle_key_: 20 passed.
  • cargo fmt --all -- --check: passed.
  • cargo build --profile selfdev -p jcode --bin jcode: passed, reports v0.90.0-dev (1358df8).
  • Full jcode-tui --lib serial test run: 2455 passed, 1 unrelated prompt-entry shimmer color assertion failed. No live daemon or running sessions were replaced.

Tradeoff

Terminals expose committed text events rather than the underlying IME composition. A short positional typing burst gives consistent undo grouping without imposing Hangul-specific rules.

Terminal IMEs can deliver several committed Korean syllables across one or more text events. Coalesce adjacent typing within a short burst while preserving separate undo steps for paste, whitespace, navigation edits, and other operations.

Tested: cargo test -p jcode-tui --lib typing_undo (3 passed); cargo test -p jcode-tui --lib test_handle_key_ (20 passed); cargo fmt --all -- --check (passed). Full lib: 2455 passed, 1 unrelated shimmer assertion failed serially.
@greptile-apps

greptile-apps Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Changes how typing undo groups keystrokes in the text input.

No outstanding issues block merging.

Summary

The PR groups contiguous TUI typing into one undo step while preserving separate undo steps for other edits.

Reviews (2) · Last reviewed commit: "Keep external composer edits outside typ..."

Comment thread crates/jcode-tui/src/tui/app/input.rs Resolved
Comment thread crates/jcode-tui/src/tui/app/input.rs Resolved
A same-length transcript replacement and a swallowed picker separator left a stale typing marker. Reset it at those boundaries so the next character captures the currently visible draft as its own undo step.

Tested: cargo test -p jcode-tui --lib typing_undo (5 passed); cargo test -p jcode-tui --lib test_handle_key_ (20 passed); cargo test -p jcode-tui --lib test_handle_server_event_transcript (2 passed); cargo fmt --all -- --check (passed)
@1jehuang
1jehuang merged commit 8441779 into 1jehuang:master Oct 5, 2026
1 check passed
1jehuang added a commit that referenced this pull request Oct 5, 2026
KooshaPari added a commit to KooshaPari/KCode that referenced this pull request Oct 17, 2026
* fix(desktop_selfdev): bring instance description under the 25-token cap

* fix(clippy): allow the intentional label-registry test lock, name the publish hook type

* dev_cargo: apply the parallel front-end through RUSTC_WRAPPER

Switch scripts/rustc-parallel-frontend from RUSTC_WORKSPACE_WRAPPER to
RUSTC_WRAPPER. Cargo hashes a workspace wrapper path into crate metadata, so
wrapped and raw cargo builds (rust-analyzer, CI) produced separate artifacts.
A rustc wrapper is metadata- and fingerprint-neutral. The wrapper now threads
any local crate (sources outside CARGO_HOME), which includes path dependencies,
and skips build-script compiler probes.

desktop_selfdev no longer injects a workspace wrapper: Jcode Desktop now sets
the same wrapper repo-wide in its .cargo/config.toml, and an inherited
workspace wrapper would split the hot-reload plugin ABI from the host, so it is
stripped from Desktop commands.

* chore(release): prepare v0.89.1

* fix(anthropic): rewrite orphaned tool_results as text instead of 400ing

* fix(cursor): route native MCP tool results back to the Cursor stream

MultiProvider::native_result_sender returned None for the Cursor provider,
so after jcode executed a Cursor-requested MCP tool locally the result was
dropped and AgentService waited forever for it. Delegate to the active
Cursor runtime's bridge and add a regression test.

* fix(cursor): answer AgentService mcp_state requests so MCP tool calls proceed

Cursor's AgentService now sends McpStateExecArgs (ExecServerMessage field
36) for the ccbridge server before it dispatches an McpArgs call. jcode
decoded it as Unknown and never replied, so every Cursor turn that tried to
call a jcode tool stalled on heartbeat frames and ended without running
the tool. Reply with McpStateSuccess listing the bridged tools as ready, and
log any other unsupported exec request instead of ignoring it silently.

Verified live against Cursor: the MCP round trip now completes in ~6s
(4/4) where the previous build stalled 30s and never ran the tool (4/4).

* fix(cursor): send model ids Cursor actually serves (grok-4.6, claude-opus-5-5, ...)

jcode reduced every Cursor model to a bare base id, but AgentService only
accepts some of those. Verified live on 2026-09-29: grok-4.7 and
composer-2.5 work, while grok-4.6, claude-opus-5-5, claude-opus-5 and
gpt-5.6-sol fail with ERROR_BAD_MODEL_NAME. Cursor's catalog serves them
as cursor-grok-4.6-high, claude-opus-5-5-high, and so on.

Resolve against the live GetUsableModels catalog instead: exact catalog
ids go through verbatim, base ids map to the catalog variant Cursor labels
with the plain model name, and /fast switches to the -fast sibling. The
catalog is fetched inline (5s bound) when the background prefetch has not
landed yet. grok-4.6 keeps an offline alias for when no catalog is
reachable.

* fix(cursor): answer AgentService allowlist prechecks instead of stalling

Cursor's protocol defines MCP/shell/web-fetch allowlist precheck exec
requests (fields 42/41/43) that it can send before dispatching a tool.
Like the mcp_state request, an unanswered precheck leaves the turn hanging
with heartbeats. Pre-approve jcode's own ccbridge tools (jcode enforces its
own permissions at execution time) and deny Cursor's native shell and
fetch, which jcode rejects anyway.

Not observed on the Auto model in 10 live runs. This closes the remaining
unanswered-exec paths for models such as Grok 4.7 that could not be tested
on a free account.

* chore(release): prepare v0.89.2

* feat(cloud): /cloud and /local move a live session to a cloud host and back

- jcode cloud move|return|where|attach (+ hidden receive/activate/export)
  run a staged, locally coordinated handoff: prepare, transfer, verify,
  commit. Failures before commit change nothing locally.
- Conversation has one owner at a time via per-machine session leases with a
  shared migration epoch. Moved or stale copies refuse turns and never
  overwrite the transcript. The daemon reloads stale live agents on resume.
- Code moves as a git bundle + snapshot commit (HEAD, branch, staged,
  unstaged, untracked, allowlisted .env) restored at the same absolute path.
  Return 3-way merges cloud work into the current local tree. Conflicts leave
  local files untouched and keep cloud work at refs/jcode-cloud/<id>/cloud.
- The agent gets a migration notice (host, repo state, cold caches,
  toolchain hints, processes and MCPs that did not move). Dangling tool calls
  from an agent-initiated move are closed.
- /cloud and /local in the TUI reattach over native SSH and auto-continue.
- JCODE_SESSION_ID is exported to agent shell tools.
- e2e scripts: CLI round trip in bwrap, real agent turns against a fake
  model, and the interactive TUI over a user-level sshd.

* fix(tools): conversation_search snippets no longer split multi-byte chars

The snippet window was cut at raw byte offsets around the match, so a
50-byte edge landing inside a char like '·' panicked the tool task. It
also took offsets from the lowercased copy, which can differ in length
from the original. Offsets now map back through a per-char index and the
window widens to whole characters.

* fix(openrouter): name the billing limit on 402 instead of blaming the network

An OpenAI-compatible endpoint that answered 402 (for example an API key
whose token allowance is used up) was reported with 'check network
connectivity, DNS/TLS', which sent users to debug a network that works.
HTTP error hints now follow the status: 402 names the billing limit and
points at the dashboard, another key, or /model; 401/403 point at the key;
a remote 404 at the base URL and model. Local servers and other statuses
keep their endpoint-specific advice.

* fix(anthropic): move late tool_results up to directly follow their tool_use

A session failed every request with 400 "tool_use ids were found
without tool_result blocks immediately after". The results existed, but
nine messages later: the assistant made two bash calls, a second
assistant message with its own calls followed and was answered, more
turns were written (a scheduled-task wake-up), and only then were the
first two results persisted. The existing repair only handled calls
with no result anywhere (inject a placeholder) and results with no call
(rewrite as text), so this history stayed unsendable.

format_messages now moves each result that is not in the turn right
after its call up to directly follow the call's turn. Back-to-back
assistant messages and one-user-message-per-result are treated as one
turn, since they are merged later anyway, so already-correct histories
are left alone.

Checked on the real session: without the fix the formatter leaves
messages.599 toolu_01SuyJ... and toolu_013Kx... unanswered (the exact
ids in the 400); with it every tool_use is answered in the next message
and roles alternate. Regression test mirrors that shape.

* fix(tools): conversation_search snippet matches like the search and maps offsets without a byte table

The snippet now looks up the match in the same whole-message lowercased copy the
search uses, so word-final sigma hits are found. The match range is mapped back
to the original text by walking chars and summing lowercased lengths, which
needs O(1) extra memory instead of a usize per byte.

* fix(anthropic): move a late tool_result together with its image, label and tool references

When a late tool_result is moved up to follow its tool_use, also move the
blocks that belong to it: the images right after it, each image's
[Attached image ...] label, and ToolReference blocks for the same call.
Unrelated blocks stay where they were.

* fix(anthropic): answer tool_uses whose result was displaced to a later turn

A tool result that arrives after another assistant turn is found by the
dangling check, so no synthetic result is injected, and then the orphan
rewrite turns it into text. The call was left with no tool_result in the
next message and the request failed with a 400. After the orphan rewrite,
inject an error tool_result for any tool_use not answered in the next user
message, or add a user message when the next message is not one.

* telemetry: per-response usage_report with correct model/session attribution

Spend was only measurable from session_end, which (a) drops sessions that
never end cleanly or crash (~20% of turn tokens in a Sep 22 sample), (b) reads
a process-global telemetry session, so swarm/background/desktop agents in one
server get their tokens and model label mixed, and (c) never saw compaction
summaries or memory sidecar calls at all.

Client:
- New `usage_report` event, sent in the background once per provider response
  with the caller's own session id, the provider/model that served it, source
  (agent/compaction/sidecar) and token counts. No content.
- Both agent turn loops report with request-time provider/model.
- Provider::complete_simple_with_usage returns stream usage; compaction and
  the sidecar provider path record it. Sidecar direct OpenAI (JSON and SSE)
  and Claude paths parse and record usage, including cache buckets.
- A 4xx for usage_report never trips the process-wide telemetry breaker, so
  shipping the client before the worker cannot disable other telemetry.

Worker:
- Accepts and validates usage_report, upserts daily_model_usage (migration
  0027) instead of storing a raw events row; firehose keeps per-response
  detail via provider_end/model_end/step.
- model-usage.sql dashboard reads the rollup (thousands of rows, no D1 CPU
  limit issues).

TELEMETRY.md documents the event and its retention.

* telemetry: emit usage_report from the local TUI turn loop

The standalone TUI loop (used by ambient visible cycles) streams directly from
the provider without going through Agent, so it never produced usage_report.
Record per-call usage (latest-snapshot semantics, request-time model) before
the interleave early-continue so interrupted calls are still counted.

* telemetry: count usage from agent streams that fail mid-response

A provider stream that errors (or is retried after context-limit compaction)
returned before usage_report was emitted, dropping tokens the provider had
already reported. Record the reported usage on both error exits.

* feat(tui): report agent state, resume command, and release to herdr

Inside a herdr pane (HERDR_ENV=1), report idle/working state and the
jcode --resume command for the current session via
"$HERDR_BIN_PATH" pane report-agent, and release the pane on quit.
Reports run on a background thread with latest-wins coalescing, a 2s
timeout, and timestamp seq numbers so they stay ordered across reloads.
See https://herdr.dev/docs/add-herdr-support/

* chore(release): prepare v0.89.3

* docs: update weekly stars chart

* fix(provider): classify GLM-5.3 context window

* fix(update): explain git-managed auto-update skip

* fix(update): clarify git checkout update advice

* feat(websearch): provider-native server-side web search (engine = "native")

Adds an opt-in websearch engine that uses the model provider's own search
instead of scraping from the local machine (#1620).

- Anthropic: attach the web_search server tool (max_uses, allowed/blocked
  domains, tool version with allowed_callers=["direct"] on newer versions),
  parse server_tool_use / web_search_tool_result blocks from the SSE stream,
  store them verbatim and replay them unmodified (encrypted_content).
  pause_turn resumes the turn without a synthetic user message.
- OpenAI Responses: attach the hosted web_search tool (not on *-codex*
  models), store web_search_call items and replay them in input.
- New ContentBlock/StreamEvent::ProviderNative carries provider-executed
  items. Other providers (or requests without the tool) get a text summary.
- Native searches render as regular web_search tool rows, live and on resume.
- The local websearch tool is replaced when the native tool is attached and
  falls back to fallback_engines otherwise.

* websearch: label downgraded native search summaries

When stored native search items are replayed as text (other provider, or
native search turned off), say that only titles/URLs remain. Otherwise the
model can mistake the summary for the full results it originally read and
retract a correct earlier answer, as seen in a live test.

* docs: update weekly stars chart

* agent: skill installs no longer invalidate the prompt cache

The Available Skills section lives in the cached system prompt, so
installing a skill mid-session rewrote the prefix and forced a KV cache
miss on the whole conversation. Freeze the list per session (like the
AGENTS.md snapshot) and announce later installs once in a transcript
system-reminder, mirroring late MCP tool announcements.

* fix(openai): end fresh websocket streams on terminal error frames

OpenAI reports usage limits with an error frame and keeps the socket open.
The fresh-socket loop forwarded the error but kept waiting for
response.completed, so post-login validation (and Desktop's OAuth Connect
step) hung indefinitely.

* websearch: prefer provider-native search by default; respect session tool policy

Review follow-ups for #1622:
- websearch.prefer_native (default true, JCODE_WEBSEARCH_PREFER_NATIVE):
  use the provider's hosted search wherever supported, local engines otherwise.
- Attach the hosted/server tool only when the session offers websearch, so
  allowed/disabled tool policy also governs provider-side search.
- OpenAI: hosted search only on first-party/ChatGPT backends; downgrade stored
  web_search_call items to text when the request does not declare the tool
  (incl. compact requests and Copilot Responses).
- Anthropic: OAuth counts as first-party even with an API-key gateway base.
- Redact provider-native items in export copies.
- Include native search query/URLs in compaction text.
- Retry rollback removes the attempt's native search rows.
- Track native websearch env vars in the config reload fingerprint.

* test(tui): retry rollback discards aborted native search rows

* anthropic: only skip prefill repair for turns ending on a server tool block

A turn that searched natively and then produced text (e.g. interrupted
mid-answer) ended on an assistant message containing raw server blocks,
which skipped the trailing-assistant repair from #600 and risked a 400.
Only a turn whose last block is a raw server tool block has the shape of a
pause_turn resume.

* websearch: never replace an SDK custom websearch tool with provider search

Provider-native search swapped out any tool named `websearch`, including an
SDK app's own callback registered under that name. Only jcode's built-in
local tool is replaced now, identified by name and built-in description.

* sdk: document provider-native web search and test its bridge events

Native searches already reach SDK clients as ordinary web_search tool
events and history rows. Document that in the TypeScript README and Rust
SDK docs, and pin the bridge translation with a test.

* release: v0.90.0

* docs: update weekly stars chart

* fix(anthropic): repair orphaned native web searches

* test(anthropic): cover orphaned native web-search history

* test(anthropic): register native web-search repair tests

* fix(anthropic): drop orphaned native web searches

* test(anthropic): cover dropped orphaned native searches

* Fix cargo test -p jcode-app-core: Stream does not implement Debug

The jcode-app-core lib test target does not compile, which blocks every
test in the crate:

  error[E0277]: `jcode_base::transport::Stream` doesn't implement
               `std::fmt::Debug`
     --> crates/jcode-app-core/src/tool/communicate/transport.rs:159:14

Result::expect_err requires T: Debug, and Stream does not implement it.

Only the test target is affected. A normal cargo build exits 0, which
is why this goes unnoticed: the crate builds fine and only its tests are
broken.

There are two occurrences. The second is under #[cfg(unix)], so only
the first fails on Windows. Both are rewritten to an explicit match,
which keeps both assertions intact: the call must fail, and the error
message must equal SERVER_NOT_RUNNING.

Fixes #1649

* Re-arm auto-poke when open work appears, so the completion-gate breaker cannot silence it

The completion-gate circuit breaker clears auto_poke_incomplete_todos when it
exhausts TODO_COMPLETION_GATE_MAX_ATTEMPTS. The only place that flag was
restored was the all-complete branch, which re-arms it to auto_poke_default_on.

Those two facts do not meet. The breaker lives inside the incomplete.is_empty()
branch, so it can only trip while every todo is complete, and the restore lives
in that same branch. An agent that added open work immediately after the
breaker fired never re-entered it, so auto_poke_incomplete_todos stayed false.

That flag is the first condition in schedule_auto_poke_followup_if_needed, so
with it false the whole function returned false immediately: no incomplete-todo
nag, and no deferred gate digest either, for the rest of the session. One
breaker trip silenced the feature permanently, with only /poke off and on
recovering it.

The re-arm therefore has to happen before that guard, not inside the body the
guard skips. It is placed at the top of the function and only acts when
auto_poke_default_on is set, so an explicit /poke off still wins.

This also fixes the digest path, which the same guard blocked.

Tests: test_open_work_rearms_auto_poke_after_completion_gate_breaker in
crates/jcode-tui/src/tui/app/tests/state_model_poke_03.rs drives the exact
post-breaker state and asserts open work both re-arms the flag and produces a
poke.

Proven red/green, not assumed: with this commit's change reverted and the test
left in place, it FAILS at the auto_poke_incomplete_todos assertion. With the
change, it passes. `cargo test --profile selfdev -p jcode-tui
test_open_work_rearms_auto_poke` -> 1 passed, 2450 filtered out.

Note: an earlier attempt placed the re-arm inside the incomplete branch, next to
the existing todo_completion_gate_attempts reset. That compiles and looks right,
but it is unreachable, because the guard at the top of the function returns
first when the flag is false. The regression test is what caught it.

* Match a pinned @Provider variant against the catalog by its base id

The panel reported a 200K context window for `stealth/space-bunny-alpha@Stealth`
while OpenRouter's own catalog entry for `stealth/space-bunny-alpha` carries
`context_length: 1000000`. All 465 models in the cached catalog carry
`context_length`, so nothing was missing from the data.

The lookup was an exact string match on the id as the runtime carries it:

    cache.models.iter().find(|m| m.id == model_id)

with `model_id` = `stealth/space-bunny-alpha@Stealth`, while the catalog lists
`stealth/space-bunny-alpha`. A pinned `<model>@<Provider>` suffix is routing
syntax, not part of the catalog id, so every catalog entry missed and
context_window() fell through to DEFAULT_CONTEXT_LIMIT (200_000). The live
frame confirmed the cost: context_total_chars 1209890 against a 200K budget.

Only the profile prefix (`<profile>:<model>`, issue #403) was being stripped;
the variant suffix had no handling anywhere in the crate.

Both catalog lookups now try the pinned id and then its base. Nothing about
the catalog or the model picker changes: this only makes the lookup reach an
entry that was already there.

Test: pinned_variant_suffix_still_matches_the_catalog_entry in
crates/jcode-provider-openrouter-runtime/src/openrouter_catalog_merge_tests.rs
runs a real `/models` fetch and pins the model with the variant suffix.

Proven red/green: with this change reverted and the test left in place it fails
`left: 200000, right: 1000000`. With the change it passes.

Crate suite: 141 passed / 6 failed. The 6 failures are pre-existing and
unrelated (profile autodetection, api-key-from-env-file, opencode session
header); verified by running the same suite on a clean tree with both of my
files stashed, which gives the identical 6 failures at 140 passed / 6 failed.
Reported rather than worked around, per the repository's own rule.

models.dev was considered as the data source and rejected: the value is already
on disk from OpenRouter's own /models, and adding a second catalog risks
changing picker and catalog behaviour for no gain. models.dev independently
agrees on 1000000, which is a useful cross-check.

No config change is required for this fix. The per-model context_window entry
added to the local config is now redundant for this model and can be dropped.

* Read the context window live instead of a field only refreshed on account switch

The panel reported 200K for `stealth/space-bunny-alpha@Stealth` even after the
catalog lookup was fixed to match a pinned `@Provider` suffix. The lookup fix was
proven by a red/green test (`left: 200000, right: 1000000`), and the live panel
still read 200000, so the symptom has a second cause.

`App::context_limit` is a stored field assigned in exactly two places, both on
account switch (auth.rs, after an Anthropic or OpenAI account change). Nothing
assigns it on model change: not the picker, not session restore, not catalog
arrival, not reload. The info widget reads that field (tui_state.rs), and both
compaction-budget sites seed from it, so a model that changes any other way keeps
whatever the last account switch happened to see.

Measured before this change, live: context_limit 200000 with context_total_chars
1209960. A 200K budget under a 1M window compacts roughly five times too early.

The three consumption points now read `provider.context_window()` directly:

- tui_state.rs: the info widget summary
- conversation_state.rs: both `manager.set_budget(...)` sites

That makes the value correct regardless of when the model last changed, instead of
requiring a refresh at each of the seven `provider.set_model` call sites in the TUI,
which would be fragile and easy to miss again.

The cached field is left in place for the paths that already keep it in sync.

Live verification pending: this must be confirmed by reloading and reading
context_limit back from the panel before the symptom is considered fixed.

* Carry the server-resolved context window to the client on ModelChanged

A remote client cannot derive its own context window. Its provider is an inert
placeholder with no model catalog, and the static resolver has no entry for a model
it does not recognise, so `update_context_limit_for_model` fell through to the
generic 200K default. Measured live on this machine: a route pinned to
`stealth/space-bunny-alpha@Stealth`, whose OpenRouter catalog entry carries
`context_length: 1000000`, reported `context_limit: 200000` with 1.2-1.4M context
chars already accumulated. A 200K budget under a 1M window compacts about five times
too early.

Two earlier commits in this branch are correct but do not reach this symptom: the
catalog lookup fix (4014cc2c4) applies on the server, and reading the window live
instead of from the account-switch-only cache (5a5b4c8a2) still asks the client's own
placeholder. The number never crossed the wire.

- protocol: `ServerEvent::ModelChanged` gains `context_window: Option<u64>`,
  `default` + skipped when absent so older peers stay compatible
- server: `Agent::provider_context_window()` added; every ModelChanged construction
  site fills it, including the failure paths and the midstream model fallback
- client: `update_context_limit_for_model` takes the server value and prefers it over
  local derivation; the ModelChanged handler passes it through

`send_model_changed_result` needed the agent threaded in to report it; its three
callers all already hold one.

Verified: `cargo check -p jcode-tui` exits 0. Live verification of the panel value is
recorded separately and is the claim that matters.

* Fix cargo test -p jcode-app-core: Stream does not implement Debug

The jcode-app-core lib test target does not compile, which blocks every
test in the crate:

  error[E0277]: `jcode_base::transport::Stream` doesn't implement
               `std::fmt::Debug`
     --> crates/jcode-app-core/src/tool/communicate/transport.rs:159:14

Result::expect_err requires T: Debug, and Stream does not implement it.

Only the test target is affected. A normal cargo build exits 0, which
is why this goes unnoticed: the crate builds fine and only its tests are
broken.

There are two occurrences. The second is under #[cfg(unix)], so only
the first fails on Windows. Both are rewritten to an explicit match,
which keeps both assertions intact: the call must fail, and the error
message must equal SERVER_NOT_RUNNING.

Fixes #1649

* Cover the context_window protocol field and update test call sites

* pricing: fall back to cross-provider catalog match for openai-compatible profiles

models.dev has 216 providers but no 'kilocode' entry, so openai-compatible
reseller profiles resolved no pricing and spend widgets showed $0.0000.
Resellers bill vendor tokens under vendor ids, so match the same model id
against the other provider tables: exact-id matches win over bare names,
modal price wins among candidates, alphabetically-first provider breaks
ties deterministically. First-party providers never take the fallback.

* Report the restored route to a resuming client so it learns the real context window

* Display the server-resolved context window instead of the client placeholder

* Honour a configured context_window over the static Claude table on a custom endpoint

* Keep the compaction budget in step with the panel's context window

* Add .gitattributes so line endings do not depend on each contributor's global config

Without it, text=auto is decided by core.autocrlf per machine, so the same file
is CRLF for one contributor and LF for the next. Edits written by tooling that
emits LF then land inside a CRLF working tree.

Kept minimal on purpose: a single rule, text=auto, which normalises in the
repository and converts on checkout, and still lets git detect binaries so it
is safe to apply to the whole tree.

Scope, measured rather than assumed. This makes the stored form consistent
across machines. It does NOT silence the repeated "LF will be replaced by CRLF"
warning during staging. That warning comes from core.safecrlf, which defaults
to warn and is per-machine configuration that a repository file cannot set.
Verified both halves: with only .gitattributes the warning still appears;
adding core.safecrlf=false locally removes it.

Committed blobs were never polluted (13 of 13 files edited this way contained
no CR), so neither half is about repairing bad commits.

* Fix cargo test -p jcode-app-core: Stream does not implement Debug

The jcode-app-core lib test target does not compile, which blocks every
test in the crate:

  error[E0277]: `jcode_base::transport::Stream` doesn't implement
               `std::fmt::Debug`
     --> crates/jcode-app-core/src/tool/communicate/transport.rs:159:14

Result::expect_err requires T: Debug, and Stream does not implement it.

Only the test target is affected. A normal cargo build exits 0, which
is why this goes unnoticed: the crate builds fine and only its tests are
broken.

There are two occurrences. The second is under #[cfg(unix)], so only
the first fails on Windows. Both are rewritten to an explicit match,
which keeps both assertions intact: the call must fail, and the error
message must equal SERVER_NOT_RUNNING.

Fixes #1649

* Stop the empty-post-tool continuation from keeping its own signal true

* rustfmt: apply formatting across the context-window changes

* rustfmt: apply formatting to the recovery predicate change

* docs: update weekly stars chart

* fix(tui): scrub late OSC 11 color replies from the composer (#970)

Terminals such as Orca's Electron terminal answer the startup background
query after it times out, so crossterm types the reply body
(11;rgb:3030/3434/4646) into the draft one key at a time. Recognize a
complete OSC 10-19 color reply in the accumulated input and remove it,
remapping the cursor. Partial replies and ordinary text are left alone.

Fixes #970

* ci: allow fork PR builds without an unused SSH deploy key

* fix(provider): explicit worker model transport beats inherited session route

A worker model override such as openai-api:gpt-5.5 or a configured provider prefix carries its own transport, while the child session still holds its parent's saved route. Honor the explicit model before the inherited route metadata so the worker does not run on the coordinator's provider.

* fix(ci): clear clippy 1.99 and macOS warning-budget failures

Bump async-trait to 0.1.92 so #[async_trait] traits no longer trip
clippy::double_must_use on clippy 1.99. Gate the linux-only
DEFAULT_ARENA_MAX and parse_cmdline so macOS cargo check is warning
free again, and fix the macOS-only clippy lints behind cfg blocks.

Closes #1675

* fix(test): restore blocking mode on accepted sockets

* test(tui): limit clean Changes assertion to file rows

* feat(gmail): add update_draft, list_drafts, and delete_draft actions

update_draft revises a draft in place (same draft ID), merging omitted
fields from the current draft and preserving reply threading, so agents
no longer pile up duplicate drafts when iterating on wording.

* feat(tui): Esc with a pending follow-up prompt stops the turn and runs it

Typing a new prompt while a turn runs and then pressing Esc now means
"stop this and run my new prompt" instead of "stop everything".

- The agent leaves soft interrupts queued on a cancelled turn instead of
  injecting them into history with no reply.
- Local and remote Esc keep the follow-up queued and leave auto-poke on.
  Staged interleave images return to the composer.
- Remote servers send Done before Interrupted, so dispatch waits for
  Interrupted (or a 3s deadline) to keep the late event from ending the
  new turn.
- Turn-end pokes yield to a pending user follow-up.

* fix: bound malformed tool call recovery across turn loops

* fix(agent): keep non-object streamed tool arguments so malformed calls get corrected

A model that streamed null (or another non-object) as tool arguments had
them coerced to {}. The tool then ran with missing arguments, validation
never saw the malformed call, and the bounded schema-correction recovery
never triggered, so a model repeating the call looped without limit.
Empty argument text is still a no-argument call.

* fix(openrouter): keep non-string streamed tool arguments for validation

OpenAI-compatible APIs may send tool arguments as a complete JSON value
instead of a string fragment. Those were dropped, so a null or array
argument looked like a no-argument call and never reached validation.

* fix(herdr): keep reporting state when herdr rejects the resume command

herdr 0.9.1 and older do not know the `--` resume separator that
`pane report-agent` gained in 0.9.2. They exit 2 ("unknown option: --")
and drop the whole report, so after the first session report a jcode
pane stopped updating: it stayed `idle` while working and never recorded
its session id.

When a report that carried a resume command fails with exit code 2,
retry it once without the resume command and remember that for the rest
of the process. Any other failure (timeout, spawn error, other exit
codes) is left alone so a transient error cannot disable resume on a
herdr that supports it. The session id is now sent even when no valid
resume command is available.

run_herdr now returns the exit status instead of a bool so the caller
can tell a usage error apart from other failures.

* fix(herdr): close spawned panes when jcode exits cleanly

The herdr launcher splits a pane and starts jcode with `pane run`, which
types the command into the new pane's interactive shell. Unlike the tmux
and zellij branches, where the pane's process is jcode itself, that shell
outlives jcode, so every swarm worker left an empty shell pane behind
after `swarm stop` or /quit.

Run `<jcode command> && exit` instead. A clean exit closes the shell and
herdr closes the pane with it; a non-zero exit keeps the pane open so
the error stays readable.

* test(herdr): make the fake herdr fixture independent of TMPDIR

The fake herdr script embedded the log path in single quotes, so a TMPDIR
containing an apostrophe broke both fallback tests. Log next to the
script via $0 instead. Reported by Greptile on #1696.

* pricing: scope cross-provider fallback and split missing cache rates

Address Greptile findings on the cross-provider pricing fallback:

- Only fall back to a cross-provider match for `openai-compatible:`
  profiles that models.dev does not map to a provider at all. A mapped
  profile keeps its own table as the authority, so a model missing there
  stays unpriced instead of inheriting an unrelated provider's rate.
- Key missing cache rates (`None`) distinctly from explicitly free ones
  (`0.0`) when counting modal prices. Merging them let a missing/zero rate
  join a majority and outvote listings that agree on a paid cache rate.
- Strengthen the exact-id-over-bare-name test: two competing bare-name
  listings now outnumber the exact match, so the test fails if exact and
  bare candidates are ever combined.

Tests: `cargo test -p jcode-base --lib model_pricing` 8/8 passed with the
two new tests failing on the pre-fix code; clippy and rustfmt clean.

* feat(usage): show Kimi Code, Cursor, and Z.ai Coding Plan quota in /usage

Kimi Code and Z.ai previously fell back to a key-status probe plus the
local pay-as-you-go spend estimate, and Cursor only showed key validity.
All three providers expose real quota windows that /usage now renders:

- Kimi Code: GET api.kimi.com/coding/v1/usages, accepting the usage
  summary, limits[] window descriptor, and legacy usages map response
  shapes; the local spend line is dropped since the plan is flat-rate.
- Cursor: POST api2.cursor.sh DashboardService/GetCurrentPeriodUsage
  with any direct credential (auth.json, vscdb, or exchanged API key),
  showing Included/Auto/API percent used and the billing cycle end.
  The previous /v0/me key-status probe is kept as a fallback.
- Z.ai: GET open.bigmodel.cn/api/monitor/usage/quota/limit shows the
  GLM Coding Plan 5-hour/weekly/MCP monthly windows when the key is a
  plan key; pay-as-you-go keys keep the existing probe + spend line.

Reset timestamps from all endpoints accept RFC3339 strings or epoch
seconds/milliseconds, including decimal-string protobuf int64 encoding.

Rendering: limit names pad to one width across the whole report (not
just within a provider) and usage-bar percentages right-align so the
percent sign and resets suffix line up across rows. Applies to the TUI
usage card, the usage overlay, and the CLI usage report.

* fix(usage): address Greptile review findings on quota fallbacks

- Kimi: explicit quota windows (limits[] / usages map) now take priority
  over the usage summary when both describe the same bucket, so the weekly
  bar shows the explicit window instead of being shadowed by the summary.
- Kimi: a successful but empty quota payload now reports "no quota windows
  returned" instead of a bare entry.
- Cursor: token-exchange failures fall back to the /v0/me key-status probe
  instead of returning only a credentials error.
- Cursor: a 200 dashboard response without recognizable planUsage fields
  falls back to the key-status probe instead of an empty "Cursor Pro".

* fix(usage): address second round of Greptile findings

- Kimi: an empty successful quota payload now sets an error instead of a
  note, so the usage overlay no longer labels unknown capacity healthy.
- Cursor: a dashboard response carrying membership info but no usage
  fields keeps the plan label instead of falling back to the API-key
  probe, which native-only logins cannot satisfy.

* subscription_api: billing status, hard cap, billing portal, and sign-out helpers for desktop account menu

* test(tui): isolate default auto-poke tests from concurrent config writes

* docs(anthropic): restore split doc comment on dedupe_tool_results

* Stop a remote client from downgrading the server-reported context window

The server resolves the window for a model chosen server-side and sends it on attach, but the startup and model-switch paths then call update_context_limit_for_model with None. For a model absent from the static catalog that fell through to the client's inert provider and its generic 200_000 default, overwriting a correct 1M value and moving the compaction budget with it. Measured on stealth/space-bunny-alpha@Stealth: the panel showed 200000 while the route carried 1000000, which is what the user was reading against the reminder's 1M figure.

(cherry picked from commit 58ee47a7e87a67d2b70707c1c1e2202664091719)

* subscription_api: native subscribe checkout and in-place plan change

* fix(tui): don't announce a model switch when resume re-reports the same model

* style(id): return the session-name selection directly (clippy let_and_return)

* fix: idle-vs-interrupted disposition in PID crash detector (extends #988)

#988 fixed one-shot jcode run sessions left Active with stale PID
markers, misread as crashes on next startup. The same false-positive
fires from find_crashed_via_pid_files(): any daemon restart stamps
every owned session Crashed, including idle sessions whose users quit
cleanly (observed: 526 stale Crashed stamps, 4 sessions blaming the
same dead daemon PID, false crash banner on next launch).

Applies the same idle-vs-interrupted rule #988 established for the
disconnect path at detection time, using the existing streaming_pids/
markers: leftover marker = mid-turn = Crashed; no marker = idle =
mark_closed(). StreamingGuard clears the marker on every orderly exit,
so presence proves interruption. Missing/unreadable marker dir fails
toward crash (fail-noisy, never fail-silent).

Tests: 2 new (idle-no-marker, leftover-marker-means-interrupted);
session::crash 7/7, session+transcript 124/124 green.

* Group contiguous composer typing into one undo step

Terminal IMEs can deliver several committed Korean syllables across one or more text events. Coalesce adjacent typing within a short burst while preserving separate undo steps for paste, whitespace, navigation edits, and other operations.

Tested: cargo test -p jcode-tui --lib typing_undo (3 passed); cargo test -p jcode-tui --lib test_handle_key_ (20 passed); cargo fmt --all -- --check (passed). Full lib: 2455 passed, 1 unrelated shimmer assertion failed serially.

* chore(ci): refresh code-size baseline to current master

The ratchet had been red on master since the August baseline, so every PR
inherited a failing Quality Guardrails job. Re-baseline to today's sizes so
the check catches new growth again.

* refactor(agent): move turn loop unit tests into sibling files

Offsets the growth from #1691 so the code-size ratchet stays green, and
tighten the MALFORMED_TOOL_CALL_ERROR_PREFIX doc (no client keys off it yet).

* fix(session): make journal replay idempotent so an interrupted checkpoint cannot duplicate history (#1632)

A checkpoint writes the snapshot and then deletes the journal. Dying between
the two steps left a journal whose messages were already in the snapshot, and
load blindly appended them again. The duplicated tool_use/tool_result run made
Anthropic 400 every later request.

- Skip the stale journal prefix whose message ids are already loaded, and drop
  any individually repeated message ids during replay (both load paths).
- Repair snapshots that already contain duplicated message ids, and force a
  clean checkpoint on the next save.
- Anthropic formatter backstop: keep only the first tool_use per id.

* fix(markdown): don't render escaped-bracket prose as display math

* chore(ci): refresh test-size, panic and swallowed-error baselines

Like the code-size ratchet, these had been red on master for weeks, so every
PR inherited a failing Quality Guardrails job. Re-baseline to current master
so the checks catch new regressions again.

* refactor(anthropic): split history repairs into their own module

After merging #1572 and #1565, lib.rs grew past its budget. Move the
tool_use/tool_result repair passes into history_repair.rs and the new
late-result tests into late_tool_result_tests.rs. Update the displaced-result
test: the late result is now moved up and paired instead of being answered
with a synthetic error and rewritten as text.

* fix(images): never store or send image formats providers reject (#1712)

Reading a .bmp/.ico (or dropping a .bmp/.tif) stored an image/bmp,
image/x-icon or image/tiff block. Every provider rejects those, and since the
block is replayed on every request the session was permanently bricked.

- New jcode_base::image_normalize: detect format from magic bytes, pass
  PNG/JPEG/GIF/WebP through, re-encode BMP/ICO/TIFF to PNG, refuse
  HEIC/AVIF/SVG/corrupt data with a reason. Enable image's bmp/ico/tiff
  decoders.
- read tool, drag-and-drop paste and generated images all use it; refused
  files produce text only.
- Outbound clamp converts or omits any non-provider image on the request
  copy, which also recovers sessions already holding a bad block. Omitted
  tool images fold their note into the tool_result to keep parallel results
  contiguous. Also catches TIFF bytes behind an image/png label.

* Keep external composer edits outside typing undo bursts

A same-length transcript replacement and a swallowed picker separator left a stale typing marker. Reset it at those boundaries so the next character captures the currently visible draft as its own undo step.

Tested: cargo test -p jcode-tui --lib typing_undo (5 passed); cargo test -p jcode-tui --lib test_handle_key_ (20 passed); cargo test -p jcode-tui --lib test_handle_server_event_transcript (2 passed); cargo fmt --all -- --check (passed)

* fix(tui): keep #1712 inside the guardrail budgets and de-flake drop tests

- move input.rs inline tests into input/inline_tests.rs and
  input/terminal_control_sequence_tests.rs (4463 -> 4096 LOC)
- log why a dropped image could not be read instead of a bare .ok()?
- run the drop-path tests under the env lock with JCODE_SSH_REMOTE cleared;
  they failed whenever an SSH test ran concurrently

* chore(ci): accept size growth from #1682 Esc redirect

* fix: self-heal image 400s and drain session saves on SIGTERM (#1712, #1632)

#1712 layer 3: when a provider rejects an inline image with a deterministic
400 (unsupported media_type, undecodable data, limits jcode doesn't model),
replace stored images with text notes, reset provider/cache state, persist and
retry once, mirroring the 413 recovery. Shares the reset logic with it.

#1632 layer 3: session saves hold a shared guard; the daemon's SIGTERM handler
waits (bounded to 5s) for it exclusively before process::exit, so a checkpoint
can no longer be cut between the snapshot write and the journal delete.

* fix(update): patch the Termux glibc ELF interpreter after in-app updates (fixes #1630)

* fix(palette): apply configured roles on 256-color terminals (fixes #1663)

Indexed cells are now matched to a role in xterm index space, so a role
default that does not round-trip through quantization still picks up its
override. Based on the diagnosis and patch in the issue by @danflory.

* test(openrouter): pin tool-call markup in structured args as inert (refs #1702)

* fix(copilot): honor catalog-advertised reasoning effort (fixes #1643)

* fix(gmail): keep the action description under the tool-schema token cap

* fix(openrouter): use env-applied profile's default model instead of OpenRouter default (fixes #1625)

* chore(startup): log launched binary version and path (refs #1626)

* test(openrouter): keep the zai cached-context regression on a 200K GLM model

* fix: make env files the source of truth for API keys

Secret saves no longer write to the process environment. A shared
file-only save_named_api_key in jcode-provider-env replaces both
poisoned copies (CLI provider_init and TUI auth); save_env_value_to_env_file
keeps set_var only for non-secret config values. All secret write
paths route through the file-only helper: /login compat paste, TUI key
saves, Gemini, the jcode subscription key, and the inline
set_var(&key_name, &key).

The openrouter runtime resolves ProviderAuth through a per-instance
Arc<dyn Fn> resolver at every use instead of capturing it at
construction, so key edits take effect without a restart. Named-profile
config variants (Bearer/Header/None, inline api_key) are preserved by
resolving the captured profile inside the closure; constructor-failure
timing stays eager via auth()? at each constructor.

Raw readers of persisted keys switch to the env-then-file loader
(pricing mode detection, the ZHIPU legacy ZAI_API_KEY fallback).

Closes #1386

* fix: invoke auth resolver before applying ?

Review follow-up (greptile P1s):
- (self.auth)?() applied ? to the resolver Arc instead of the
  Result; call first, then propagate at all 5 request sites.
- openrouter_tests fixtures still assigned ProviderAuth directly to
  the AuthResolver field; wrap in Arc::new(|| Ok(...)) so the test
  target compiles.
- rustfmt on touched files.

* fix(auth): keep every saved API key out of the process env (fixes #1386)

Builds on @zipadoodlez's PR #1387 (cherry-picked above), adapted to current
master:
- The Grok Build provider added after the PR now uses the call-time auth
  resolver.
- Six more secret writes were still copied into the process env and now go
  through the file-only save_named_api_key: local-endpoint login keys,
  'jcode provider add --api-key', OpenAI-compatible key migration, Azure
  (CLI and TUI) and Cursor.
- Tests that asserted the old env export now assert the opposite, plus a
  regression test for the exact report: save a key, correct the env file,
  and the corrected value wins without a restart (fails on the old code).

* compile_remote: keep cached access state on transient check failure to stop prompt-cache invalidation

* Revert "compile_remote: keep cached access state on transient check failure to stop prompt-cache invalidation"

This reverts commit 27345e7f2f98859fa14672d4eb37ef35321f6718.

* compile_remote: make tool description static, report account state only in results

The description changed with account state and was re-checked every turn,
so a transient /v1/me failure flipped it and invalidated the prompt cache
for every session in the process. Tool definitions are part of the cached
prefix and must never change mid-session.

* fix(provider): retry every 5xx from OpenAI-compatible providers, including 529 (fixes #1596)

A 529 "heavy usage" answer (and other non-standard 5xx like 520) was not
classified as retryable, so the turn failed on the first attempt with a
hint to check the network. Every 5xx is now retried within the existing
retry budget, and a final 5xx hint points at provider overload.

* fix(usage): query Z.ai quota on the profile's region host (follow-up to #1699)

International api.z.ai keys are rejected by open.bigmodel.cn, so the
Coding Plan quota fetch silently fell back to the key probe for
non-mainland users. Derive the quota host from the profile api_base.

* fix(pricing): keep local profiles out of the cross-provider fallback (follow-up to #1658)

Ollama, LM Studio and localhost/private-network profiles serve vendor
model ids for free, so borrowing a hosted listing's rate invented spend
(e.g. ollama gpt-oss:20b picked up ollama-cloud pricing). Cross-provider
matches are now also reported at Medium confidence instead of High.

* chore(ci): restore Quality Guardrails (clippy redundant_closure, split oversized files, swallowed-error baseline)

* chore(ci): shrink oversized files and fix clippy redundant_closure for Quality Guardrails

* fix(anthropic): advertise registry tool schemas on Claude OAuth, renamed only

The OAuth route swapped in hand-curated Claude-Code schemas for Edit, Write,
Read, Grep, Glob, Agent and Skill. They drifted from the real tools and
dropped options such as intent, so OAuth models never sent intent for edits.
Every route now forwards the registry definition verbatim; OAuth only maps
names (edit -> Edit, ...).

* fix(tui): edit rows show intent, expand badge in every diff mode

- The edit tool row no longer repeats the file path that the inline diff
  header directly below already shows. It reads like other tool rows.
- The Alt+Shift+E expand badge stays on edit rows in Off and File diff modes,
  where it opens the hidden diff in full inline.

* chore(ci): accept size growth from #1711, #1714 and the edit-row intent fix

* release: v0.90.1

* docs: update weekly stars chart

* fix(server): release swarm member guard before reading connections in comm status

handle_comm_status held swarm_members.read while awaiting
client_connections.read. Disconnect cleanup holds client_connections.write
while awaiting swarm_members.write, so the two deadlocked and wedged every
later resume, swarm tool call, new connection, and `jcode server reload`
(clients stuck on "loading session…").

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(session): refuse snapshot checkpoints from transcript-less remote stubs

Remote clients keep a startup stub or stripped session as app.session.
`/restart` and `/reload` save it with a status change, which forces a
snapshot; the empty-checkpoint guard only fired when the in-memory copy
once held messages, so the stub replaced the server-owned transcript with
an empty one and deleted its journal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(server): release swarm member guard before awaits in plan handlers

Propose, approve, and reject held swarm_members.read across
queue_soft_interrupt_for_session (sessions/queue locks), and the direct
update and approve paths also across persist_swarm_state_for and
broadcast_swarm_plan, which re-read swarm_members. With tokio's fair
RwLock, a writer queued between the two reads deadlocks the server.
Send notifications under a short guard and do the awaits after it drops.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(swarm): let a per-call spawn_mode of auto defer to the configured mode

Models often pass spawn_mode="auto" on swarm spawns. Auto tries a
visible terminal window first, so it silently overrode the configured
agents.swarm_spawn_mode (inline by default). From terminals jcode cannot
target, such as the VS Code integrated terminal, every worker then opened
in a separate terminal app instead of the inline gallery.

A per-call auto now means no preference and resolves to the configured
mode. Explicit visible, headless and inline still win, and a configured
auto keeps its visible-then-headless behavior. The parameter description
now tells models to omit spawn_mode unless the user asks for one.

* chore(ci): accept size growth from swarm spawn-mode fix

* fix(swarm): stop spawned workers when their coordinator is interrupted

Cancelling a session's turn (Esc, Ctrl+C) only fired that session's own
cancel signal. Swarm workers run their own turns on the server, so every
worker the session had spawned kept running and spending tokens. In one
log the coordinator was interrupted at 16:59 and its four workers kept
streaming until 17:21.

A cancel now also fires the active-turn cancel signal of every member
the session spawned, directly or through other spawned members, marks
them stopped and tells attached clients their turn stopped. It runs on
every cancel path, including a coordinator that is idle in
await_members while its workers run. Idle workers and unrelated sessions
are left alone.

* chore(ci): accept size growth from the cascade cancel fix

* fix(server): reload when an install repoints the link the server started from

On macOS current_exe() returns the launch path with symlinks intact. The
shared server is started through builds/stable/jcode, and an install
repoints that link, so afterwards current_exe() resolved to the new
binary. Every reload check then concluded the server already ran the
newest build: `jcode server reload` and install_release.sh's reload
logged "no strictly-newer binary" and the daemon kept running the old
build indefinitely.

Resolve the running binary once, at server start, and use that pinned
path for the newer-binary check and the reload target.

* chore(ci): accept size growth from the server reload fix

* mcp: list tool names only and rank, clip, and cap mcp_search results

The mcp list action printed every tool's full description, which cost tens of
thousands of tokens with a few vendor servers connected. It now lists callable
names per server and points to mcp_search for details.

mcp_search now prefers name matches over description-only matches, requires
every query term to match, clips descriptions to 400 chars, emits compact JSON,
and returns full schemas for at most 12 matches, naming the rest.

* fix(telemetry): drop unused events indexes to cut D1 billed row writes

Each events insert/delete wrote one row per index. 13 indexes made every
telemetry event cost ~14 billed D1 row writes (~93M/month, ~$43 overage).
No query in the worker, dashboard, or report SQL used the dropped indexes.
Applied to production 2026-10-06.

* tui: pack todo quality gates onto shared rows instead of one per line

* fix(browser): target the right browser's bridge host when several run (fixes #1720)

Each browser running the bridge extension spawns its own native host. With
bridge PR 1jehuang/firefox-agent-bridge#12 each host takes its own port and
the bridge CLI picks one by FAB_BROWSER, so jcode now passes the target
browser:

- status/setup/ping/capability probes and browser tool actions set
  FAB_BROWSER for the resolved target (a user-set FAB_BROWSER wins, e.g.
  helium for a fork jcode does not know).
- Per-agent session daemons are keyed by browser, so switching browsers
  starts a daemon bound to the other browser's host. Session code moves to
  browser_session.rs.
- JCODE_BROWSER_NATIVE_HOST_DIRS lists extra NativeMessagingHosts dirs that
  setup also installs the Chromium host manifest into (Helium, Vivaldi, ...).
- Safari relay detection checks the relay port instead of 8766, which may now
  belong to another browser's host.

* docs: plan guided bring-your-own Google OAuth setup

* chore(ci): accept session.rs size growth from the stub-wipe guard

* mcp: fit search and call results to adaptive token budgets

Results under budget pass through untouched. Larger ones are squeezed just
enough to fit rather than cut at fixed caps:

- MCP tool results (direct mcp__ tools and mcp_call) get an 8k-token budget.
  JSON keeps its shape: the loosest string and array caps that fit are found
  by binary search, shortening long strings before sampling arrays. Text keeps
  its head and tail on line boundaries. A trailing note states the original
  and kept token counts.
- mcp_search fits a 6k-token budget: full results when they fit, then
  progressively shorter descriptions with every schema kept, then full detail
  for as many leading matches as fit with the rest named. Replaces the fixed
  12-result and 400-char caps.
- accept_large_output (top level or inside mcp_call arguments) returns the
  full result, and is no longer forwarded to MCP servers.

* google: selectable services in Google login and a built-in calendar tool

Generalize `jcode login google` beyond Gmail. A new --google-services
flag (gmail, calendar, all) plus an interactive prompt choose which Google
APIs to authorize, and the saved token records the services Google actually
granted. Older token files and pending logins default to Gmail only.

Add a Google Calendar v3 client and a `calendar` tool (calendars, list,
get, create, quick_add, update, delete). Local times resolve against the
calendar's own time zone. Deleting events or emailing guests requires
confirmed: true, and guests are not emailed by default.

* calendar: add opt-in live read-only test against the saved Google login

* calendar: add opt-in live create/update/delete round-trip test

* google: guided OAuth app setup like gog, plus auto-import and publish guidance

`jcode login google` now walks first-time users through their own Google
Cloud OAuth app instead of a wall of press-Enter prompts:

- Uses gcloud when installed and signed in to create a project and enable
  every selected API in one step. Without gcloud it opens one enable link
  for all APIs, and every console page opens with the project preselected.
- Watches Downloads for the client_secret*.json the user downloads and
  imports it automatically. It also offers a previously downloaded file and
  rejects Web application clients (jcode needs a Desktop app client).
- Tells users to publish the app, since Testing mode expires logins after 7
  days, and refresh failures with invalid_grant now explain that fix.
- New flags: --setup to redo the wizard, --google-client-json <path|auto>
  for agent-driven setup. Google login flags are grouped in one struct.
- docs/GOOGLE_GUIDED_SETUP.md becomes the agent playbook, and gmail and
  calendar point at it when not configured.

The Google login flow moves to src/cli/login/google.rs and the reusable
helpers live in jcode-base auth::google::setup.

* google setup: detect gcloud credentials correctly and keep its error headline

Validated against the real Google Cloud SDK (587.0.0):

- `gcloud config get-value account` reports a configured account even when
  it has no credentials, so the wizard offered gcloud automation that could
  only fail. Detect signed-in accounts with `gcloud auth list
  --filter=status:ACTIVE` instead.
- gcloud's error output puts the ERROR: headline first and remedies after.
  The summary kept the last 6 lines and dropped the headline. Keep it from
  the headline on. A test uses the real gcloud text.

* google setup: test generated project ids against gcloud's real create validator

* fix(cli): report the local/direct profile, not openrouter, in run --json/--ndjson (#804)

* docs: update weekly stars chart

* Add /desktop command to open the current session in Jcode Desktop

* tui: Alt+Up/Down cycle speed tier (Standard, Fast, Ultrafast)

- Add OpenAI ultrafast service tier (GPT-6 Astra, GPT-5.6 Sol) with pricing
- New speed_increase/speed_decrease keybindings, default alt+up/alt+down
- Shared speed tier ladder in provider-core used by local and remote TUI
- /fast ultra, status labels and info widget understand Ultrafast

* chore(release): prepare v0.91.0

* test: validate ultrafast payload and Alt+Up/Down speed cycling (local + remote wire)

* feat(browser): check for bridge updates and install them automatically

Setup only downloaded the browser bridge when a file was missing, so fixes in
newer bridge releases (multi-browser hosts for #1720) never reached existing
installs.

jcode now records the installed bridge release tag. Before browser actions it
checks the latest release at most every 6 hours (8s timeout, opt out with
JCODE_BROWSER_AUTO_UPDATE=0), and `jcode browser setup` always checks. A
newer release, or an install with no recorded version, is downloaded in place.
jcode then asks the extension to reload and stops the old native hosts, so
every browser reconnects to the new host. The agent gets a one-line note.

Verified on a real v0.9.7-era install: setup reported "Updated the browser
bridge to v0.10.1", Firefox respawned the new host, and ping answered.

* fix(browser): after a bridge update, keep hosts already running the new binary

The extension reload can respawn a host from the new file before jcode stops
the old ones. Stop only hosts whose executable is the replaced (deleted)
binary, so the fresh host is not killed and reconnected a second time.

* feat(tools): opt-in codemode, an embedded QuickJS sandbox that composes tool calls

Adds a `codemode` tool (off by default, enable with [tools] codemode = true
or JCODE_CODEMODE=1). The model writes the body of an async JS function that
calls any session tool, including MCP tools, via `await tools.<name>(args)`.
Intermediate results stay in the sandbox; only the return value and console
output reach the transcript.

- New jcode-codemode crate wraps rquickjs 0.14 (native QuickJS, ~1 MB).
  Each run uses a fresh runtime on a dedicated thread with a 64 MB heap,
  300 s deadline (interrupt handler + wall clock), 2000-call cap, and
  bounded console capture. No fs/network/timers/modules are exposed.
- Calls route through Registry::execute, so session allow/deny policy,
  pre_tool hooks, MCP routing, and telemetry all apply. codemode and batch
  are not callable from scripts.
- store()/load() persist JSON per session under ~/.jcode/codemode/.
- listTools()/describeTool() give in-script discovery of schemas.

* models: default every provider to its newest flagship

Copilot hardcoded claude-opus-4.6 as its tier default and overwrote the
active model on every catalog refresh. Route it through the shared
flagship-first ranking with new-release auto-promotion, and only replace
the placeholder default or a model the catalog no longer serves.

Picker recommendations (TUI and Desktop) now follow DEFAULT_OPENAI_MODEL
and DEFAULT_CLAUDE_MODEL instead of stale gpt-5.5 / claude-opus-4-8.

* test(copilot): regression test that a realistic catalog no longer defaults to Opus 4.6

* tui: copy rendered math as LaTeX source and hint when TeX is missing

- Unicode display-math frames now expose a math copy target whose content
  is the original $$...$$ LaTeX, instead of the text approximation.
- Inline math rendered as Unicode is recorded per line, and text selection
  substitutes any touched formula with its $...$ source.
- Image mode detects a missing TeX toolchain (latex+dvipng or
  pdflatex+pdftocairo), skips queuing doomed renders, and shows a one-time
  install hint under the Unicode fallback.
- Render \top and \bot.

* tui: math-aware copy on the wrapped fallback path + end-to-end tests

Selections that start on unmapped chrome (select-all from the session
header) fell back to a display-line path that ignored math, copying the
Unicode approximation. Route that path through the same math substitution.
Adds app-level tests for select-all, partial mouse drag over inline math,
and the Alt badge shortcut writing LaTeX to the clipboard.

* tui: move background tasks from pinned todo band into the background widget

The background info widget was fed only by the process-local task manager,
so in client/server mode (tasks run in the server) it never appeared. Feed
it from the session-scoped task rows the client already tracks from task
events, render each as a status glyph + label + progress bar, and stop
drawing task rows under the pinned todos.

* tui: rank the background widget above stat widgets while tasks need attention

It is now the only place task progress shows, so running or failed tasks
must not lose placement to model/kv-cache/usage. Debug widget summary
counts session task rows too.

* feat(gmail): support Cc and Bcc on drafts and sends

Add cc/bcc parameters to the gmail tool for draft, send, and update_draft.
Recipient headers are written into the raw MIME (Gmail strips Bcc from
delivered copies), CR/LF in address values is rejected, update_draft keeps
existing Cc/Bcc unless overridden (empty string clears), and read and
list_drafts now show To/Cc/Bcc so recipients can be verified.

* tui: size compact background rows to the overview width

The compact form assumed 40 columns, so in a narrow Overview the progress
bar and percent were clipped off.

* tui: Ctrl+wheel and trackpad pinch over inline images step their size

* models: rank OpenRouter and Grok Build flagships, expose preferred_model_for_provider

OpenRouter and Grok Build had no flagship ranking, so post-login selection
fell back to catalog order (OpenRouter's stale default is claude-sonnet-4).
Dotted Claude ids (claude-opus-4.6, anthropic/claude-opus-4.8) also failed
to match the hyphenated curated order. Normalize dots for Claude ids, add
OpenRouter to the Claude+OpenAI tiers and a Grok family with new-release
auto-promotion, and expose preferred_model_for_provider so clients that
already scoped candidates to one provider (Desktop's provider switcher) can
use the same ranking.

* fix(openai): isolate OAuth and API-key model catalogs

The ChatGPT/Codex OAuth catalog and the platform API-key catalog shared one
per-account cache scope, so whichever refresh landed last overwrote the
other. Selecting an API-only model (e.g. openai-api:gpt-6.1-sol) right after
an OAuth catalog refresh failed with 'Unsupported OpenAI model'.

Scope catalogs, availability, refresh throttling, and runtime unavailability
markers by the credential actually in use (API keys fingerprinted), build
picker routes from each credential's own catalog, and seed the API-key scope
from the openai-api profile listing before the first native refresh.

* sdk: shared auto-retry policy for transiently failed turns

TurnRetry is an I/O-free state machine SDK clients feed with session
events. It classifies a failed turn (network, timeout, 5xx/overloaded,
short rate limits are retried; credentials, billing, quota, invalid
requests, guardrails and cancels are not), schedules capped exponential
backoff, and tells the client when to resume with a hidden continuation
reminder. The failed prompt is already in the transcript, so resending it
would duplicate the request.

Desktop uses this so its sessions recover the way the TUI does.

* models: replace st…
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.

Composer undo stops at arbitrary Korean IME event boundaries

2 participants