Select default command-safety rules from the live session shell so legal
PowerShell subexpressions are allowed and PowerShell-native dangerous
commands are blocked. Untouched pre-shell-aware lists gain the new
defaults on read.
Closes#3256
Avoid rewriting thinking/provider maps when values are unchanged so
mounted AI panels do not re-render. Put permission title and short
description on one line and drop the Cursor CLI parenthetical.
Codex P2: missing agentThinkingMap was treated as Off, so GPT-5.1+
got reasoningEffort=none and Gemini 2.5 Flash got thinkingBudget=0
without a user choice. Store Off as an explicit value and leave an
absent preference unset so the provider default is used.
Give Catty a two-column provider/model menu in the composer, add search
plus recent/pinned models, and move thinking effort onto its own chip
so Claude, Codex, Grok, and Catty share the same compact controls.
Closes#2137Closes#2637Closes#1884
Every keystroke was re-rendering ChatInput and the first character
created a store draft that broadcast AI state, so the first 1-2 glyphs
painted and the rest dumped after a stall. IME composition hit the
parent on every pinyin letter, and Chromium spellcheck loaded on the
first word.
Keep the textarea uncontrolled, commit parent state on idle/blur/send,
and treat missing-to-composer-only drafts as text-only so store
listeners do not wake. Draft flush, send, and hide still persist the
current box text.
Opening the AI panel and typing a few characters hit a main-thread stall.
Streamdown warmup, panel remount, draft-store fan-out, and expand-time
IPC all raced the first keystrokes. import() cannot be cancelled, so the
heavy renderer must not start while the composer is busy.
Keep the composer mounted on hidden retained panels, ignore composer-text
store notifications, debounce draft flushes, and defer discovery/skills/
model IPC until the composer is idle. History stays plaintext until
Streamdown is warm, then hydrates a few rows at a time.
Merge seed only wrote activeSessionIdMap, so unsent draft demoted the panel
to draft mode and send created a new session while the old chat still showed.
Prefer persisted workspace active over hasDraft, and materialize panelView.
Mount AI maintenance even when no side-panel tools are open, and clear a departed pane's active-map entry when a live workspace retargets its chat.
Co-authored-by: Cursor <cursoragent@cursor.com>
Keep inherited terminal-scoped chats visible in a still-live multi-pane workspace by reminting the active chat onto a surviving pane.
Co-authored-by: Cursor <cursoragent@cursor.com>
Keep the surviving terminal on the dissolved workspace's active session view, and remint chats whose original pane is gone so history matching still resolves them.
Co-authored-by: Cursor <cursoragent@cursor.com>
Inherit the focused terminal's AI session when tabs merge, hand it back on dissolve, and remap side-panel open/layout/SFTP state so the panel does not look cleared.
Co-authored-by: Cursor <cursoragent@cursor.com>
Split vault/session/settings into publishers and store-backed Hosts so hot
fields no longer rebuild the whole shell, and harden Terminal boot / startup
effects for StrictMode double-mounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
Show manual compact for any Catty session with a configured model, not
only when enough history exists for a large head. External agents still
do not get the command.
Gate /compact behind canCompact so the composer is not cleared as a
silent no-op, hide the usage ring until a real context snapshot arrives,
and summarize only the UI head that the persisted compaction boundary
will drop. Drop unused clearSessionMessages surface and add slash-command
regression tests.
Fixes#1382
Deleting the active AI chat session left panelViewByScope pointing at a removed session, causing the side panel UI to blank. Sync panel view cleanup with session deletion, stop in-flight streams on delete, and return to draft with the deleted session's agent preserved.
* perf(terminal): smooth layout drags and faster tab switching
Defer xterm refit during split, sidebar, and host-tree drags while keeping pane containers in sync with live layout measurements. Refactor TerminalLayer into focused sections with TabBridge/memo optimizations and add the terminal host tree sidebar.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(terminal): keep side panels alive and guard session attach races
Prevent terminal boot unmount from leaking backend sessions, keep SFTP/scripts/theme/AI state when switching side tabs, and defer heavy SFTP UI mount so first entry stays responsive.
Co-authored-by: Cursor <cursoragent@cursor.com>
* perf(terminal): reduce tab switch jank
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(ai): provider switcher chip in the Catty Agent chat input
Catty Agent currently has no model chip in the chat input — modelPresets
is empty for the catty agentId so `hasModelPicker` is false. The
provider/model the chat ends up using comes from the global
`activeProviderId` / `activeModelId`, which means switching providers
requires opening Settings → AI → Providers. Closes the gap surfaced in
the original feedback on #1101 (problem 2) and partially addresses
#986 (per-context model switching) by going per-agent.
State layer adds an `agentProviderMap` (`Record<agentId, providerId>`)
alongside the existing `agentModelMap`. Both are written together when
the user picks from the new dropdown; together they form a per-agent
override that beats the global active provider/model when set. Cross-
window sync mirrors the agentModelMap pattern.
ChatInput grows a `providerSwitcher` prop carrying the enabled
ProviderConfigs, the selected (providerId, modelId), and an onSelect
callback. When supplied, the model chip switches from the Cpu glyph
to the provider's ProviderIconBadge + `providerName · modelId`, and
the popover renders a two-column layout — providers on the left
(icon + name + default model caption), that provider's known model(s)
on the right. ACP agents (Claude/Codex) are untouched because they
plumb their provider through the CLI, not the Vercel AI SDK.
AIChatSidePanel resolves `effectiveActiveProvider` /
`effectiveActiveModelId` for the catty agent from the per-agent map,
falling back to the global selection. handleSend now passes those
through to sendToCattyAgent so a provider picked in one Catty session
applies everywhere Catty runs.
For v1, each provider's right column shows just its configured
`defaultModel`. The two-level structure is in place to absorb richer
listings (cached /models, manual additions) later without UI
surgery — left a note in the popover code.
Refs #1101, #986.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* polish(ai): flatten provider picker to a single list
Two-level dropdown was theatre — each ProviderConfig exposes exactly
one model (its `defaultModel`), so the right column ended up showing
the same string already captioned on the left row. Picking a provider
implicitly picks its model; one click is enough.
Also drops the `p.enabled !== false` filter on the picker list. The
user's expectation, confirmed by feedback on the first cut, is that
the chat-input list mirrors what Settings → AI → Providers shows. The
per-provider `enabled` toggle is an "active-ish" flag, not a
visibility gate; hiding disabled providers in the picker silently
made everything but the one currently active disappear, which is what
the reviewer hit.
Pares the popover down to a vertical list — provider icon + name +
default-model caption (mono if set, italic "configure default model"
hint if not) + a Check on the bound row. Removes the `hoveredProviderId`
state along with the right-column rendering since it's no longer
driving anything.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* polish(ai): tune provider icon sizes in the chat input
Chip icon was sitting at sm (20px badge) and crowded the h-6 toolbar
chip alongside the truncated label; popover rows used the same sm, so
nothing differentiated the picker from the chip visually.
Adds an xs size to ProviderIconBadge (16px badge, 10px glyph, 9px
letter fallback) and uses it on the chip. Popover rows step up to md
(32px badge, 16px glyph) and the row padding grows accordingly so the
larger brand mark has room to breathe — the picker now reads like a
list of choices, the chip reads like a status line.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(ai): keep per-agent override honest in model fallback + chip label
Two codex P1/P2 findings on #1107:
P1 — When Catty has a per-agent provider override but no per-agent
model (agentModelMap['catty'] empty), cattyAgentModelId fell through
to the global `activeModelId`. That id belongs to whichever provider
was globally active, not the one Catty is now bound to, so e.g.
overriding to DeepSeek without a defaultModel happily sent gpt-4o
(global) to DeepSeek and produced a wrong-model error. The fallback
is now: stored agent model → override provider's defaultModel → empty.
Only the no-override path keeps the activeModelId tail; the
no-provider send guard catches the empty case for everyone else.
P2 — ChatInput's selectedSwitcherProvider used `?? providers[0]` so
the chip always displayed *some* provider even when none was actually
bound (selectedProviderId missing). The rest of the pipeline (send
guard, agentProviderMap) treats that as "no provider", so the chip
was lying. Dropped the fallback; when nothing is bound the chip now
shows a generic Cpu glyph + "Select provider" label until the user
picks one from the popover. Adds `ai.chat.selectProvider` in en /
zh-CN / ru.
Refs codex review on #1107.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(ai): purge per-agent binding when the bound provider is deleted
Codex local review (round 2) flagged that a saved Catty model id could
outlive its provider. The chain:
- catty bound to provider A (DeepSeek): agentProviderMap['catty']='A',
agentModelMap['catty']='deepseek-v4-flash'
- user deletes provider A
- cattyAgentProvider falls back to the global active provider (B, OpenAI)
- cattyAgentModelId still returned the saved 'deepseek-v4-flash'
- send dispatched the DeepSeek model id to OpenAI → wrong-model error
Two layers of fix:
1. **Defensive resolution** (AIChatSidePanel) — cattyAgentModelId now
looks at the override provider before trusting the stored model id.
If the override is stale (provider deleted), the stored model id is
treated as orphan and the resolution falls back to the global active
selection just like cattyAgentProvider already does.
2. **Cleanup on remove** (useAIState.removeProvider) — when a provider
is deleted, any agent whose agentProviderMap entry pointed at it
gets both maps cleared (provider override + saved model). Same
rationale: that model id is now meaningless against every other
provider. Mirrors the existing activeProviderId cleanup.
Adds a small agentProviderMapRef so removeProvider can snapshot which
agents to clean up without relying on the captured-at-callback-create
state (which would be stale).
Refs codex local review on #1107.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(ai): include agentProviderMap in settings sync + block empty-model send
Codex local review (round 3) found two issues:
P2 — `agentProviderMap` was missing from the cross-device sync surface.
Added it to the sync key list, the build path, the apply path, and the
SyncPayload type alongside the existing `agentModelMap`. Sync tests in
`syncPayload.test.ts` now cover the new field on both the build and
apply sides.
P2 — Provider rows with no `defaultModel` were still clickable in the
chat-input picker, so selecting one would save a binding with empty
model id; the send path then dispatched an empty model name and the
SDK would surface a vague backend error. Two changes:
1. ChatInput disables the row (\`disabled\`, \`aria-disabled\`, dimmed
styling, tooltip pointing the user to Settings) when the provider
has no \`defaultModel\`. Click is suppressed.
2. AIChatSidePanel \`handleSend\` adds a model-required guard mirroring
the existing no-provider guard — surfaces \`ai.chat.noProviderModel\`
as an assistant message. Catches stale bindings (e.g. user edited
the provider's \`defaultModel\` to empty after binding) before they
reach the SDK.
Refs codex local review on #1107.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(ai): trim whitespace-only model ids + reconcile orphan bindings on sync
Codex local review (round 4) found two more leaks:
P2 — Whitespace-only `defaultModel` passed the picker's `disabled` gate
(which trims) but every other layer (cattyAgentModelId resolution,
the send-guard `!sendActiveModelId` check, the SDK call) compared the
raw string. A provider whose default model was " " could still reach
the SDK and surface a vague backend error. Normalized: trim at the
resolution boundary (catty model fallback chain) and trim before the
send-guard's existence check.
P2 — Sync apply did not reconcile per-agent bindings against the
incoming provider set. A payload could change `providers` without
shipping a fresh `agentProviderMap`, leaving local overrides pointing
to provider ids the synced set no longer includes — the same ghost-
binding bug that `removeProvider` already handles for explicit user
deletes. Added `pruneOrphanPerAgentBindings()` that runs after every
AI settings apply: it walks `agentProviderMap`, drops any entry whose
provider id isn't in the current `providers` list, and clears the
saved model id for those agents alongside it (mirroring removeProvider
cleanup). A new test in `syncPayload.test.ts` exercises the ghost-
binding case end-to-end.
Refs codex local review on #1107.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(ai): notify open AI state of cross-device sync apply in the same window
Codex local review (round 4) flagged that `applySyncPayload` writes
straight to localStorage but `useAIState` only re-reads on browser
`storage` events. Those events only fire in *other* windows — the
window doing the apply (the one with the active chat panel) keeps
showing pre-sync providers and per-agent bindings until reload.
Concrete leak: cloud sync swaps in a new provider set, pruning runs,
localStorage is correct, but the open Catty chip still references the
ghost provider binding until the user reloads.
Extracts the existing `AI_STATE_CHANGED_EVENT` constant +
`emitAIStateChanged` helper out of `useAIState` and into a new
`application/state/aiStateEvents.ts` so non-React call sites (sync
apply, future IPC handlers) can fire it without pulling in the hook.
After AI settings apply, `syncPayload.ts` walks every AI key it
touched (including the agentProviderMap / agentModelMap that the
reconcile step may have mutated even when the payload didn't ship
them) and emits a same-window nudge. `useAIState`'s existing local
listener routes unknown keys back through its storage handler, so
each affected piece of React state rehydrates from localStorage.
Adds a regression test in `syncPayload.test.ts` that asserts the
expected `netcatty:ai-state-changed` keys are dispatched for the
providers + per-agent map keys.
Refs codex local review on #1107.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Preload compact history on first turn after app restart (#753 hedge)
Symptom (confirmed on Copilot CLI, originally reported on Codex in
#753): after closing and reopening Netcatty, the AI chat UI still
shows the prior conversation but the agent responds "this is the
beginning of our conversation, no previous records". Earlier context
is lost entirely.
Root cause: the bridge relied on session/load throwing "not found" to
trigger the catch-block fallback that replays compact history. Some
ACP agents (Copilot CLI, some Codex builds) silently spawn a new
session when handed a stale id instead of erroring. The catch-block
never fires → historyReplayFallback stays false → the first turn
sends only the latest prompt → agent sees zero context.
Fix: when we're creating a new provider process AND telling it to
resume an existing session id AND the renderer gave us compact
history, preload historyReplayFallback=true as a hedge. If the agent
really did reload the session, the replay is ~3KB of redundant
context (small waste). If the agent silently started fresh, the
replay restores durable constraints + last few raw turns so the
first response is coherent.
After the first successful streamed turn clears the flag (the round-2
post-stream hook), steady state is back to sending only the latest
prompt. Cost is bounded to one replay per app-restart-and-prompt.
Test: "replays compact history on the first turn after app restart
even when session/load 'succeeds'" — mocks createACPProvider to
behave like Copilot CLI (no error thrown, no real resume), asserts
the first streamText call carries history+latest (length 2) and the
second only latest (length 1).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Fix AI session resume and agent switching
* Preserve hidden draft when switching agents
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix: correct terminal AI history resume behavior
The previous implementation plan mistakenly treated reopening an old terminal AI session in a fresh or reconnected SSH tab as a scope-retargeting feature.
The intended rule is draft-first:
- a fresh or reconnected terminal opens on a blank draft
- older chats remain available in history for manual access
- selecting history does not imply automatic scope transfer into the new tab
This change is a rule correction, not a conflict between product rules.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* fix: harden ai draft transitions
* fix ai session continuation from history
* fix: clear stale activeSessionIdMap entry when view resolves to draft
Addresses the Codex P2 review on aiPanelViewState.ts:38. When a terminal
scope mounts with a persisted activeSessionIdMap entry but no explicit
panelView and no draft, resolveDisplayedPanelView now returns the
default draft view (terminal fresh-start behavior). The sync effect
that writes into activeSessionIdMap is guarded by `if (!activeSession)
return`, so the old entry stays put. That stale entry then leaks into
activeTerminalTargetIds in every other scope, and
getSessionScopeMatchRank uses it to suppress host-matched history that
is actually resumable — so valid sessions vanish from the history
drawer until another action rewrites the map.
Add a dedicated effect that clears the scope's activeSessionIdMap
entry whenever the resolved panel view is draft but a persisted
session id is still present. This keeps the map an accurate record of
"which session each scope is currently showing" instead of a lagging
snapshot.
Also extend sessionScopeMatch.test.ts to cover the rank=2 exact-match
branch and the scope-type mismatch short-circuit, which were missing
from the original suite.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: track cross-terminal session ownership by session id, not targetId
Addresses the Codex follow-up review on commit 345244b2. When a user
resumes a session from history into a different terminal, the session's
`scope.targetId` still points at the original terminal. The previous
ownership tracking — which checked whether `session.scope.targetId`
appeared in `activeTerminalTargetIds` (derived from the keys of
`activeSessionIdMap`) — therefore:
- could not prevent the same session from being resumed in multiple
terminals simultaneously, because the resumed session's targetId
never matches the current scope's targetId; and
- let `pruneInactiveScopedSessions` treat a session as orphaned and
clear its `externalSessionId` the moment the original terminal
closed, even though another terminal was actively using it.
Switch ownership to be keyed on session id:
- `getSessionScopeMatchRank` now takes `activeTerminalSessionIds`
(a Set of session ids currently displayed by other terminal scopes)
and returns rank 0 when `session.id` is in that set.
- `AIChatSidePanel` derives `activeTerminalSessionIds` from the
*values* of `activeSessionIdMap`, excluding the current scope's key.
- `pruneInactiveScopedSessions` gains an `activeSessionIds` parameter;
sessions whose id is in this set are never reported as orphaned and
never have their `externalSessionId` cleared, regardless of their
stored `scope.targetId`.
- `cleanupOrphanedAISessions` computes the in-use set from the
pre-cleanup `activeSessionIdMap`, filtered to live scopes, and
passes it through. The map is read once and reused.
Tests cover the new id-based ownership, the rank-2 exact-match path,
the scope-type-mismatch short-circuit, and the
"resumed-elsewhere session must not be cleaned" invariant.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- persist drafts, panel views, and active sessions per terminal/workspace scope
- restore scoped AI session selection on reconnect and cold mount
- prefer unsent drafts over implicit history fallback
- avoid redundant active session map rewrites during scoped cleanup
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* fix: preserve AI chat history across reconnects
* fix: retarget restored AI sessions on reconnect
* feat: format tool call results with proper line breaks
Extract stdout/stderr from structured results and unescape \n/\t
so command output displays with real line breaks like terminal output.
Supports both JSON object {stdout,stderr} and executor text formats.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: restrict unescape to stdout/stderr fields only
Plain strings may contain legitimate backslash sequences (file paths,
regex patterns) that should not be converted. Only apply unescape to
stdout/stderr fields extracted from command execution results.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address review findings for AI chat reconnect
1. Add explicit activeTerminalTargetIds guard in shouldRetargetActiveSession
to prevent retargeting sessions owned by other terminals, making the
invariant locally verifiable.
2. Only preserve orphaned terminal sessions with hostIds — workspace,
local, and serial sessions generate fresh IDs and would be permanently
unreachable, wasting MAX_STORED_SESSIONS quota.
3. Clear stale streaming state when restoring a session whose ACP handle
was already cleaned up (e.g., reconnect during mid-response), so the
user can send new messages.
4. Restore overflow-hidden on user message bubbles to prevent content
bleeding past rounded border corners.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address round 2 review findings
1. Fix streaming state clear: only clear for sessions whose targetId
doesn't match current scope (restored from different terminal),
not for built-in Catty chats that never set externalSessionId.
2. Exclude local/serial sessions from preservation: their synthetic
hostIds (local-*/serial-*) change on every open and can never be
matched back.
3. Preserve non-zero exitCode in formatted tool results so failed
commands show a visible failure signal.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: only clear streaming state during retarget, not for all restored sessions
The previous condition (targetId !== scopeTargetId) also fired for
built-in Catty sessions during normal operation, killing active streams.
Now streaming is only cleared when shouldRetargetActiveSession is true,
meaning the session came from a disconnected terminal where any
in-flight response is guaranteed to be dead.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address round 3 review findings
1. Clear externalSessionId during retarget to prevent stale ACP handle
from surviving if retarget runs before orphan cleanup.
2. Only retarget in visible AI panels — hidden/background panels should
not race to claim orphaned sessions.
3. Remove unescapeTerminalOutput — data flow trace confirms real newline
characters arrive at the component. The unescape was corrupting
legitimate backslash sequences in paths and patterns.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: only ACP-cleanup deleted sessions, not preserved ones
Preserved sessions may be reused on reconnect. Running aiAcpCleanup
on them asynchronously could race with a newly started ACP conversation
on the same session ID, tearing down the fresh provider.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: abort in-flight streams during retarget and restore ACP cleanup
1. Abort the active request's AbortController when retargeting a session
with stale streaming state. Prevents late chunks from the old run
appending into the restored chat.
2. Restore ACP cleanup for all orphaned sessions (not just deleted ones).
Preserved sessions get a new externalSessionId on next use, so
cleaning the old one prevents subprocess leaks without affecting
future conversations.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: guard hidden panels from session ownership and skip null map entries
1. Only assign restored sessions in visible panels — hidden panels
should not race to own sessions via setActiveSessionId, preventing
MCP/tool calls from being bound to the wrong terminal.
2. Skip null entries in activeSessionIdMap when building
activeTerminalTargetIds — deleted chats should not block same-host
history matching on other terminals.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: guard MCP sync behind visibility and cancel exec/approvals on retarget
1. Only sync MCP session metadata from visible panels to prevent
hidden panels from overwriting the scope mapping.
2. Cancel pending approvals and in-flight exec (Catty + ACP) during
retarget, matching handleStop behavior. Prevents stale tool results
and approval prompts from reappearing after session retarget.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: restore MCP sync for hidden panels
MCP scope is keyed by chatSessionId so hidden panels don't overwrite
visible panels' mappings. The isVisible guard was breaking background
chats that need updated terminal session metadata after reconnects
or workspace changes.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove unused deletedIds variable
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: add web search and URL fetch tools for AI agent
Add web_search and url_fetch tools to Catty Agent, allowing the AI to
search the internet for current information and fetch webpage content.
- Support 5 search providers: Tavily, Exa, Bocha, Zhipu, SearXNG
- Settings UI with provider selection, API key encryption, and config
- web_search is conditional on config; url_fetch is always available
- Both tools are read-only and work in all permission modes (incl. observer)
- aiFetch skipHostCheck for AI tool requests to arbitrary URLs
- System prompt guidelines for when to use search/fetch
- i18n support (en + zh-CN)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address code review findings (SSRF, key exposure, state race)
- P1: Restore SSRF protection when skipHostCheck is true — still block
localhost, RFC1918, link-local, and cloud metadata endpoints; only
skip the domain allowlist for public HTTPS hosts
- P2: Move web search API key decryption to main process via dedicated
IPC handler, matching the existing provider key security model
- P2: Use configRef to avoid stale closure in async settings callbacks
that could overwrite newer user changes
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address second review — DNS rebinding, url_fetch approval, maxResults
- P1: url_fetch now requires approval in confirm mode (outbound GET is
a side effect that could exfiltrate data via query strings)
- P1: Add DNS resolution check when skipHostCheck is set — resolve
hostname and reject if any IP is private/loopback/link-local, blocking
DNS rebinding attacks against internal services
- P2: Slice search results after provider call to enforce maxResults
consistently (Zhipu and SearXNG ignore the limit parameter)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address third review — localhost/IPv6 SSRF, API key blur race
- P1: Block localhost/loopback when skipHostCheck is enabled — restructure
isAllowedFetchUrl to check private hosts first in the skipHostCheck path,
preventing access to local services on allowlisted ports
- P1: Handle IPv6 private ranges (fc00::/7, fe80::/10, ::ffff: mapped),
strip brackets from URL.hostname, block [::1] and fd00:: addresses
- P2: Guard handleApiKeyBlur against provider change during async
encryption — skip stale write if provider switched while encrypting
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address fourth review — main-process key isolation, SearXNG compat
- P1: Replace aiWebSearchDecryptKey IPC with __WEB_SEARCH_KEY__ placeholder
pattern — renderer never sees plaintext keys; main process replaces
placeholder in headers before HTTP request, matching provider key flow
- P1: Search API requests use normal allowlist path (not skipHostCheck),
so SearXNG on localhost/HTTP/private networks works via aiSyncWebSearch;
only url_fetch uses skipHostCheck for arbitrary public HTTPS URLs
- P2: Remove needsApproval from url_fetch — treat as read-only like
sftp_read_file, consistent with observer mode allowlist
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address fifth review — private LAN providers, maxResults default
- P1: Allow private-IP hosts that are explicitly in the provider/search
allowlist (e.g. https://192.168.x.x model providers or SearXNG)
- P2: Remove .default(5) from web_search maxResults schema so the user's
configured maxResults setting is used when the model omits the param
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address sixth review — HTTPS scope, config gate, redirects
- P2: Scope HTTP exception to private/LAN IPs only — remote allowlisted
hosts still require HTTPS to protect API keys in transit
- P2: Gate web_search tool on complete config (API key for providers that
require it, apiHost for SearXNG) to avoid advertising a broken tool
- P2: Add redirect following (up to 5 hops) to aiFetch for url_fetch —
handles 301/302/307 for short links, www canonicalization, etc.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address seventh review — redirect SSRF, decrypt race, HTTPS-only
- P1: Revalidate each redirect hop against SSRF guards (allowlist check
+ DNS resolution) before following, preventing open-redirect SSRF
- P2: Add sequence counter to API key decryption effect — stale promise
results from a previous provider are discarded on provider switch
- P3: Restrict url_fetch to HTTPS-only URLs, matching the skipHostCheck
policy that already rejects HTTP in the bridge
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address eighth review — OS resolver, allowlisted HTTP hosts
- P1: Use dns.lookup (OS resolver) instead of dns.resolve4/6 for private
IP checks — matches what http.request actually connects to, respects
/etc/hosts, mDNS, and other local resolver sources
- P2: Allow HTTP for any explicitly allowlisted host (not just literal
private IPs), so self-hosted SearXNG at http://searxng.lan works
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address ninth review — HTTP scope, blur ordering, decrypt flag
- P1: Narrow HTTP exception to web search apiHost only — AI provider
endpoints remain HTTPS-only to protect credentials in transit
- P2: Add blur sequence counter to prevent out-of-order encryption
results from overwriting newer API key saves
- P2: Reset isDecrypting flag when cancelling decrypt on provider switch,
preventing permanently disabled API key input
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address tenth review — DNS pinning, prompt/tool alignment
- P1: Pin validated DNS result to the HTTP request via custom lookup
function, preventing TOCTOU/DNS-rebinding between validation and
actual connection
- P2: Extract isWebSearchReady() helper and use it consistently in
both tool registration and system prompt, so the model isn't told
web search is available when config is incomplete
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address eleventh review — single DNS lookup, redirect pinning, CGNAT
- P1: Combine DNS validation and pinning into a single lookup call,
eliminating the TOCTOU window between hasPrivateResolution and pinnedLookup
- P1: Pin DNS for redirect targets too — resolve/validate/pin in one step
before following each redirect hop
- P2: Add 100.64.0.0/10 (CGNAT) to private IP ranges for Tailscale and
similar CGNAT-addressed internal services
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address twelfth review — apiHost validation, sync on enable
- P2: Validate apiHost is a well-formed URL in isWebSearchReady(),
preventing tool exposure when user enters a malformed host
- P2: Add webSearchConfig.enabled to sync effect deps so the main
process gets updated immediately when the toggle changes
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: remove DNS-level SSRF checks that break fakedns/proxy environments
DNS resolution validation (dns.lookup + IP pinning) breaks in proxy
environments where fakedns resolves all domains to LAN addresses.
Revert to hostname-level checks only (blocking localhost, 127.0.0.1,
metadata endpoints, etc.) which are sufficient without false positives.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: resolve empty catch block lint warning
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Security: API keys no longer transit IPC as plaintext; renderer sends
providerId and main process decrypts via safeStorage. Add ReDoS
protection for user-supplied blocklist regex. Sanitize error messages
to strip file paths and sensitive URLs before displaying in chat.
- Bug fixes: approval timeout now notifies user in chat instead of
silently aborting. statusText cleared consistently across all 7 code
paths. useAIState persistence race condition fixed with mountedRef
guard, storage sync validated with type checks.
- Accessibility: InlineApprovalCard uses role="alertdialog" with focus
on approve button. ChatInput menus have proper ARIA roles, labels,
and aria-expanded. ThinkingBlock toggle has aria-expanded/controls.
Model selector submenu supports keyboard navigation.
- UX: switching agents preserves old session and creates new one.
Approval card buttons disabled immediately after click.
- Performance: text-delta streaming batched via requestAnimationFrame.
- Refactor: extract useAIChatStreaming, useToolApproval, and
useConversationExport hooks from AIChatSidePanel (1514 → 751 lines).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Security:
- Apply checkCommandSafety() in aiExec IPC handler to enforce command blocklist
- Add critical path validation in handleSftpRemove (normalize + blocklist)
- Change rm -rf to rm -r so permission errors surface
Stream lifecycle:
- Abort all active streams on component unmount (abortControllersRef cleanup)
- Wrap stream reader in try/finally with releaseLock() to prevent leaks
- Use refs for inputValue/images in handleSend to stabilize callback identity
State persistence:
- Clear debounce timer before synchronous persist in destructive operations
(clearSessionMessages, deleteSession, deleteSessionsByTarget)
- Add 10MB max buffer guard in ACP client and MCP server NDJSON parsing
i18n:
- Replace hardcoded English strings with t() calls in InlineApprovalCard,
PermissionDialog, ConversationExport, ThinkingBlock, AgentSelector
- Add 23 new i18n keys to en.ts and zh-CN.ts
Misc:
- Remove debug console.log statements in mcpServerBridge
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>