diff --git a/cptr/routers/state.py b/cptr/routers/state.py index e944a64..58ee142 100644 --- a/cptr/routers/state.py +++ b/cptr/routers/state.py @@ -174,7 +174,15 @@ async def put_workspace(request: Request, path: str = Query(...)): return {"status": "skipped"} workspace_path = _resolve_workspace_path(path) workspace_data = await request.json() - name = workspace_data.pop("name", _workspace_display_name(workspace_path)) + existing_workspace = _newest_workspace(await _workspaces_at_path(user_id, workspace_path)) + if "name" in workspace_data: + name = workspace_data.pop("name") + else: + name = ( + existing_workspace.name + if existing_workspace + else _workspace_display_name(workspace_path) + ) workspace_data.pop("path", None) # Everything else is workspace data (groups, tabs, etc.) await Workspace.upsert(user_id, workspace_path, name, workspace_data) @@ -351,7 +359,7 @@ def _collect_system_info() -> dict: # Load average try: load = os.getloadavg() - system["load_avg"] = [round(l, 2) for l in load] + system["load_avg"] = [round(value, 2) for value in load] except Exception: pass diff --git a/cptr/utils/agents/claude_code.py b/cptr/utils/agents/claude_code.py index d868dbf..7ded387 100644 --- a/cptr/utils/agents/claude_code.py +++ b/cptr/utils/agents/claude_code.py @@ -20,6 +20,9 @@ from cptr.utils.agents.events import ( from cptr.utils.agents.prompts import latest_user_text +_claude_clients: dict[str, tuple[Any, tuple[Any, ...]]] = {} + + def _claude_query_input( prompt: str, attachments: PreparedAgentAttachments ) -> str | AsyncIterator[dict[str, Any]]: @@ -66,6 +69,19 @@ def _permission_mode(chat_approval_mode: str) -> str: return "default" +async def _disconnect_cached_claude_client(session_id: str) -> None: + cached = _claude_clients.pop(session_id, None) + if cached: + await cached[0].disconnect() + + +async def _clear_claude_client_cache() -> None: + cached_clients = list(_claude_clients.values()) + _claude_clients.clear() + for client, _ in cached_clients: + await client.disconnect() + + def _tool_update_from_claude_start( event: dict[str, Any], ) -> tuple[int | None, AgentToolUpdate | None]: @@ -111,15 +127,19 @@ async def run_claude_code_agent( prompt = latest_user_text(messages) env = os.environ.copy() - if profile.get("home"): - env["HOME"] = os.path.expanduser(str(profile["home"])) + home = os.path.expanduser(str(profile["home"])) if profile.get("home") else None + if home: + env["HOME"] = home permission_mode = _permission_mode(_chat_approval_mode(chat_params)) launch_args = str(profile.get("launch_args") or "").strip() - extra_args = shlex.split(launch_args) if launch_args else [] + extra_args = tuple(shlex.split(launch_args)) if launch_args else () + command = str(profile["command"]) + cache_key = (workspace, command, home, extra_args, model, permission_mode) + session_id = None + client = None try: - session_id = None if resume_state: value = resume_state.get("session_id") session_id = value if isinstance(value, str) and value else None @@ -139,12 +159,22 @@ async def run_claude_code_agent( options_kwargs["extra_args"] = {arg: None for arg in extra_args} options = sdk.ClaudeAgentOptions(**options_kwargs) - options.cli_path = str(profile["command"]) + options.cli_path = command if model != "default": options.model = model - client = sdk.ClaudeSDKClient(options) - await client.connect() + cached = None + if session_id: + cached = _claude_clients.get(session_id) + if cached and cached[1] != cache_key: + await _disconnect_cached_claude_client(session_id) + cached = None + + if cached: + client = cached[0] + else: + client = sdk.ClaudeSDKClient(options) + await client.connect() try: query_input = _claude_query_input(prompt, attachments) @@ -229,6 +259,15 @@ async def run_claude_code_agent( } break + if observed_session_id: + old_client = _claude_clients.pop(session_id, (None,))[0] if session_id else None + if old_client is not None and old_client is not client: + await old_client.disconnect() + _claude_clients[observed_session_id] = (client, cache_key) + session_id = observed_session_id + else: + await client.disconnect() + yield AgentDone( usage=usage, resume_state={ @@ -238,9 +277,17 @@ async def run_claude_code_agent( "model": model, }, ) - finally: - await client.disconnect() + except Exception: + if session_id: + await _disconnect_cached_claude_client(session_id) + else: + await client.disconnect() + raise except asyncio.CancelledError: + if session_id: + await _disconnect_cached_claude_client(session_id) + elif client is not None: + await client.disconnect() raise except Exception as exc: # noqa: BLE001 - surfaced in the chat. yield AgentError(str(exc)) diff --git a/cptr/utils/agents/detection.py b/cptr/utils/agents/detection.py index 7d2be09..cbdd0c9 100644 --- a/cptr/utils/agents/detection.py +++ b/cptr/utils/agents/detection.py @@ -23,7 +23,7 @@ from cptr.utils.agents.models import ( ) DETECTION_TTL_SECONDS = 30 -CLAUDE_MODELS = [ +CLAUDE_MODEL_FALLBACKS = [ "claude-fable-5", "claude-opus-4-8", "claude-opus-4-7", @@ -290,7 +290,7 @@ def _version_at_least(version: tuple[int, int, int] | None, minimum: tuple[int, def _claude_models_for_version(version: str | None) -> list[str]: parsed = _parse_version_tuple(version) models = [] - for model in CLAUDE_MODELS: + for model in CLAUDE_MODEL_FALLBACKS: if model == "claude-fable-5" and not _version_at_least(parsed, MIN_CLAUDE_FABLE_5): continue if model == "claude-opus-4-8" and not _version_at_least(parsed, MIN_CLAUDE_OPUS_4_8): @@ -611,12 +611,8 @@ async def get_agent_status(app_state=None, refresh: bool = False) -> dict[str, A if implicit_defaults and detected.status in {"not_found", "error"}: continue mode = profile.get("mode", "auto") - models = detected.models or profile.get("models") or [] - available = ( - mode != "disabled" - and bool(models) - and (mode != "auto" or detected.status == "ready") - ) + models = list(dict.fromkeys([*(detected.models or []), *(profile.get("models") or [])])) + available = mode != "disabled" and (mode != "auto" or detected.status == "ready") effective_profile = dict(profile) resolved_profile_command = _resolve_command(str(profile.get("command") or "")) if ( diff --git a/cptr/utils/model_targets.py b/cptr/utils/model_targets.py index 0769531..26b2854 100644 --- a/cptr/utils/model_targets.py +++ b/cptr/utils/model_targets.py @@ -45,9 +45,6 @@ async def resolve_agent_model_target(model_id: str, app_state=None) -> AgentMode raise HTTPException(400, f"agent profile not found: {profile_id}") profile = entry["config"] - if model not in (profile.get("models") or []): - raise HTTPException(400, f"model '{model}' is not configured for agent profile {profile_id}") - if not entry["available"]: detection = entry.get("detected") or {} raise HTTPException(