mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-23 16:42:19 +00:00
03cd9bc968cbda17533938571ef476ca3684ca85
28
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
1fec5925eb | Refactor large modules and fix runtime errors (#1136) | ||
|
|
53d3e05bb4 |
Per-agent provider switcher chip in the Catty Agent chat input (#1107)
* 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> |
||
|
|
51a6b7efaa |
Preload compact history on first turn after app restart (#753 hedge) (#769)
* 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> |
||
|
|
4574f1e2b2 |
fix: stabilize scoped AI draft/session transitions (#724)
* 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
|
||
|
|
363f03a92d | fix ai draft scope state updates | ||
|
|
75dc3dd72b |
feat: scope AI draft and session resume state
- 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> |
||
|
|
c771979178 |
Add Skills + CLI mode for external agents (#599)
* Add Skills + CLI external agent workflow * feat: add Skills + CLI transport for ACP agents * chore: remove branch-local compatibility shims |
||
|
|
7639191c50 |
fix: preserve AI chat history across reconnects (#541)
* 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>
|
||
|
|
c74b78a49d | Reconcile AI session state with live sessions | ||
|
|
a7f42ec93e | Avoid dropping unflushed AI sessions during cleanup | ||
|
|
d6fea6c328 | Preserve AI session state and cleanup across panel unmounts | ||
|
|
3d4fbf8763 |
fix: keep workspace MCP scope in sync (#385)
* fix: keep workspace MCP scope in sync * fix: refresh catty workspace tool context * fix: preserve AI stream state across tab switches * fix: align ACP stop and resume with 1code semantics * fix: harden ACP resume fallback for unsupported agents |
||
|
|
9387590696 |
Fix ACP stop cleanup and cancel state (#384)
* Fix ACP stop cleanup and cancel state * Block ACP tool writes after stop * Kill ACP child processes on cleanup * Cleanup ACP sessions when tabs disappear |
||
|
|
6727248924 |
feat: add web search & URL fetch tools for AI agent (#365)
* 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> |
||
|
|
eeb300295d |
refactor: improve security, accessibility, performance, and code organization
- 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> |
||
|
|
be36ccd167 |
fix: address security, correctness, and performance issues from code review
Security: add validateSender to agent IPC handlers, remove CODEX_API_KEY and NODE_PATH from SAFE_ENV_KEYS, validate URL scheme before openExternal, add backtick substitution to command blocklist, add 10MB buffer limits. Bugs: fix runExternalAgentTurn timeout hang, fix limitConcurrency undefined entries on error, treat null exitCode as failure, enforce maxBytes for SFTP reads. Performance: debounce addMessageToSession persistence, cache compiled blocklist regexes, add QuotaExceededError handling for localStorage writes. UI: use local onKeyDown for PermissionDialog, move CRITICAL_PATHS to module level. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
71b13a77a3 |
fix: address security, correctness, and performance issues from code review
Security: validate agent spawn commands against allowlist, replace execSync with execFileSync in agent discovery, restrict localhost SSRF to known ports, add observer mode enforcement at IPC layer, add IPC sender validation, expand dangerous env key blocklist, add pending approval timeout. Correctness: replace updateLastMessage with ID-based updateMessageById to fix race condition during streaming, include tool-call/tool-result messages in SDK context, flush debounced persist on unmount, fix ACP client break placement, use proper AI SDK message types. Performance: pre-compile command blocklist regexps, extract shared tool executors to deduplicate executor.ts and tools.ts (~50% reduction each). Also: i18n for hardcoded English strings, remove dead detectDoomLoop code, add bypass-resistant blocklist patterns, include permissionMode in ACP provider reuse fingerprint. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
0b9cb86c4e |
fix: address security and correctness issues from code review
- Add command blocklist check to terminal_send_input (executor + SDK tools) - Add session scope validation to all tools in executor.ts - Fix abort handler to call aiChatCancel instead of aiChatStream - Enforce URL allowlist in fetch proxy to prevent SSRF - Wrap event.sender.send with safeSend for destroyed window check - Filter dangerous env vars (LD_PRELOAD, NODE_OPTIONS, etc.) from agent spawn - Fix stale debouncedPersistSessions closure using sessionsRef - Fix cleanupOrphanedSessions race when sessions load before workspaces - Fix limitConcurrency implementation using Set + finally pattern - Improve command blocklist regex patterns with word boundaries - Add regex validation with error feedback in SafetySettings - Add confirmation dialog for provider removal - Fix React key warning for tool-role messages in ChatMessageList - Remove debug console.warn in TerminalLayer - Remove unused nanoid dependency - Remove redundant platform-specific codex-acp binary from dependencies Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
d8d29d1709 |
fix: address code review findings for AI chat panel
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> |
||
|
|
a55da77471 |
refactor: fix security issues, remove dead code, and split monolithic files
Security: - Fix command injection in 15+ shell interpolation sites with shellQuote() - Add token-based authentication to MCP TCP server - Fix heredoc delimiter collision in SFTP write fallbacks - Add case-insensitive flag to mcpServerBridge command blocklist - Add exhaustive default case to createModelFromConfig Architecture: - Split aiBridge.cjs (1971→1483 lines) into 4 modules: shellUtils, codexHelpers, claudeHelpers, ptyExec - Split SettingsAITab.tsx (1480→520 lines) into 10 sub-components - Extract shared processCattyStream from AIChatSidePanel.tsx (-168 lines) - Consolidate duplicate PTY execution logic into shared ptyExec.cjs - Consolidate duplicate stripAnsi/toUnpackedAsarPath utilities Code quality: - Remove ~33 debug console.log statements from production code - Remove dead code: terminal_read_output stub, checkToolPermission, isCommandAllowed, READ_ONLY_TOOLS - Unify bridge type accessor in useAIState.ts (eliminate 15 unsafe casts) - Add localStorage session pruning (50 sessions / 200 messages cap) - Fix ModelSelector onBlur race condition (setTimeout → preventDefault) - Fix duplicate getShellEnv() calls in Codex helpers - Remove unused _config param from claudeAgentAdapter - Type claudeAgentAdapter bridge parameter directly as ClaudeBridge Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
d1a59ed40c |
fix: add missing cross-window sync for host permissions and agent model map
The StorageEvent handler was missing cases for STORAGE_KEY_AI_HOST_PERMISSIONS and STORAGE_KEY_AI_AGENT_MODEL_MAP, so changes made in the settings window were not picked up by the main window. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
f90aa81b2c |
feat: enforce safety settings, blocklist UI, provider UX improvements, and full i18n
Safety enforcement: - Command Timeout: use user setting in MCP Server (execViaPty/execViaChannel) and Catty Agent path (aiBridge execViaPtyForCatty/execViaChannel fallback) - Max Iterations: read user setting for Catty (stepCountIs) and ACP (via IPC) - Permission Mode: observer mode hard-blocks write ops in MCP Server dispatch; Catty SDK tools wired to checkToolPermission(); all synced via IPC on change Command Blocklist UI: - Add editable regex pattern list in Settings AI Safety section - Reset to defaults button, add/remove patterns - IPC sync to MCP Server on change and on mount Provider UX: - ModelSelector rewritten as combobox: type-to-filter with suggestions dropdown - All providers use unified ModelSelector (modelsEndpoint optional) - API key passed as auth header for model fetching (Bearer / x-api-key) - Skip model fetch when no API key (except Ollama) - Provider toggle is now mutually exclusive (activating one disables others) - New providers default to disabled (switch off) - Custom provider supports editable display name - No-provider error: friendly message shown in chat i18n: - Full i18n coverage for Settings AI tab (~55 keys) - Full i18n for AI chat panel (placeholder, empty state, time, sessions) - en.ts and zh-CN.ts locale files updated Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
950819746e |
fix: per-agent model memory and correct Claude ACP model presets
- Replace single selectedAgentModel state with per-agent agentModelMap persisted to localStorage, so each agent remembers its last selected model - Default to first preset when no prior selection exists - Fix Claude model presets: use 'default' instead of 'opus' to match what claude-code-acp actually exposes (default=Opus 4.6) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
b2447b06d2 |
fix: per-scope AI chat isolation and workspace host discovery
- Fix workspace host discovery: use `activeWorkspace.root` instead of
non-existent `.tree` property, which caused `collectSessionIds` to
always return empty for workspaces
- Isolate AI chat state per-scope (tab/workspace): activeSessionId,
isStreaming, abortController, and inputValue are now keyed by
`${scopeType}:${scopeTargetId}` so different tabs don't interfere
- Add per-chatSession MCP scope metadata to prevent host list mixing
across workspaces, with chatSessionId passed through the full IPC chain
- Store hostname/username in SSH session objects as fallback for MCP
host info when renderer metadata is unavailable
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
|
||
|
|
f53bc05cb3 |
feat: overhaul AI settings, fix Catty Agent streaming and tool execution
AI Settings: - Remove External Agents section, add dedicated Codex/Claude Code sections with auto-detection and manual path override - Add OpenRouter model list auto-fetch with searchable dropdown - Remove standalone Default Model section, integrate into provider cards - Provider toggle now acts as mutual-exclusive active selector - Add cross-window state sync via storage events - Add ErrorBoundary around AI tab for graceful error handling Catty Agent fixes: - Fix streaming: use .chat() instead of default Responses API, use getReader() pattern instead of for-await, handle text-delta/text chunk types correctly per SDK v6 - Fix API key: decrypt encrypted key before passing to SDK - Fix terminal_execute: use PTY stream (visible in terminal) with MCP markers instead of invisible SSH exec channel - Fix multi-turn: only pass user/assistant text history, skip tool messages to avoid SDK schema validation errors - Fix tool result display: create new assistant message after tool results so follow-up text renders correctly Other: - Add netcatty:ai:resolve-cli IPC handler for CLI path validation - Remove Gemini from agent discovery (only Codex + Claude Code) - Fix lint errors across ChatInput, TerminalLayer, SettingsAITab - Strip MCP markers from tool execution stdout Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
847df7a023 |
feat: add MCP server for remote host access, model selector, and PTY execution
- Create netcatty-remote-hosts MCP server (TCP bridge + stdio child process) exposing terminal_execute, sftp_*, get_environment tools to ACP agents - Execute commands via PTY stream with self-erasing markers for terminal visibility; disable pagers automatically; 60s timeout fallback - Inject MCP server into both Codex (ACP) and Claude Code (ACP) sessions - Add model selector popover with hardcoded presets for Claude (Opus/Sonnet/ Haiku) and Codex (GPT 5.4, Codex 5.3/5.2/5.1, o3/o4-mini) with thinking level sub-menus - Fix multi-step tool call message flow (mutable flag instead of stale closure) - Remove CLAUDE_CONFIG_DIR isolation to fix Claude auth; switch Claude to ACP - Add startup cleanup for orphaned AI sessions - Guard collectSessionIds against undefined workspace tree - Remove permission mode chip from chat input Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
150724fc7c |
fix: enforce session-agent binding and scope-based lifecycle management
- Switching agent deactivates current session, next message creates a new one - Filter history sessions by both scopeType and targetId - Restore agent selector when resuming a historical session - Auto-cleanup AI sessions when terminal/workspace instances are destroyed Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
72887c35b5 |
feat: add AI chat panel with Vercel AI SDK integration
Add a comprehensive AI assistant feature to netcatty, enabling AI-powered terminal automation and multi-host orchestration. Core features: - AI chat side panel (Zed-style) with agent selector, session history, conversation export (Markdown/JSON/TXT), and streaming responses - Catty Agent: built-in terminal assistant with 9 tools (terminal exec, SFTP read/write, multi-host orchestration) using zod schemas - BYOK provider support: OpenAI, Anthropic, Google, Ollama, OpenRouter, and custom OpenAI-compatible endpoints - Three-tier permission model: Observer / Confirm / Autonomous - Command safety: blocklist patterns, doom loop detection, abort support - External agent support: ACP protocol (JSON-RPC over stdio) for Claude Agent, Codex CLI, Gemini CLI, and custom agents Tech stack: - Vercel AI SDK (ai, @ai-sdk/openai, @ai-sdk/anthropic, @ai-sdk/google) with streamText + fullStream for streaming tool-call loops - AI Elements: adapted conversation (use-stick-to-bottom), message (streamdown markdown), prompt-input (InputGroup) components - Custom bridge fetch adapter routing all API calls through Electron main process IPC to avoid CORS - zod for tool parameter schemas UI components: - AIChatSidePanel, AgentSelector, ChatInput, ChatMessageList - PermissionDialog, ExecutionPlan, ConversationExport - AI Elements: conversation, message, tool-call, prompt-input - New UI primitives: InputGroup, Spinner - Settings AI tab for BYOK configuration and safety settings Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |