From 6cc7448e0ee53a8f5c356fab54200ad4d4026347 Mon Sep 17 00:00:00 2001 From: wxhking <186391338+wxhking@users.noreply.github.com> Date: Thu, 5 Nov 2026 17:17:03 +0800 Subject: [PATCH 01/20] fix(gateway): resolve reasoning overrides on IM turns like the dashboard path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit _build_dashboard_request resolves the turn's reasoning overrides and hands them to build_harness_request, so Dashboard turns send the configured reasoning_effort through the harness's reasoning middleware. The IM path inside __call__ skipped both steps: the request was built without reasoning_overrides, so a model whose reasoning_config.default_effort (e.g. high) was set sent no reasoning_effort at all on WeChat/QQ/Feishu turns — the same conversation proved it from the same provider when asked from the Dashboard. Resolve the overrides for IM turns with the same call (meta=None: IM metadata carries no per-turn reasoning overrides) and pass the result into build_harness_request. Fixes #2785 --- CHANGELOG.md | 1 + src/octop/infra/gateway/process/processor.py | 7 ++ .../gateway/test_processor_im_reasoning.py | 112 ++++++++++++++++++ 3 files changed, 120 insertions(+) create mode 100644 tests/unit/gateway/test_processor_im_reasoning.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 39332b7edd..21ae243850 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ - 超长图片先缩小再发送。失效的默认模型会自动换掉 - 升级记忆库:长会话分批提炼,重启后不重跑 - 安装清理不再删掉运行环境。PostgreSQL 上的知识库检索和关怀去重恢复正常 +- IM 通道的对话请求也会带上配置的推理强度,和 Dashboard 路径一致 ### 变更 - 升级 octop-harness 至 1.0.7 diff --git a/src/octop/infra/gateway/process/processor.py b/src/octop/infra/gateway/process/processor.py index 7a99fe5a6e..53ccbd6ee3 100644 --- a/src/octop/infra/gateway/process/processor.py +++ b/src/octop/infra/gateway/process/processor.py @@ -1064,6 +1064,12 @@ async def __call__(self, msg: InboundMessage) -> AsyncIterator[MessageEvent]: needs_multimodal=content_blocks_need_vision(content), ) model_ref = model_route.model_ref + reasoning_overrides = self._resolve_reasoning_overrides( + user_id=user_id, + thread_id=thread_id, + model_ref=model_ref, + meta=None, + ) mcp_servers = await self._resolve_turn_mcp_servers( agent_id=agent_id, user_id=user_id, @@ -1102,6 +1108,7 @@ async def __call__(self, msg: InboundMessage) -> AsyncIterator[MessageEvent]: model=model_ref, auto_route=model_route.automatic, message_kwargs=message_kwargs or None, + reasoning_overrides=reasoning_overrides, ) self.teams.stamp_host_runtime(request, agent_id) self._attach_turn_knowledge_config( diff --git a/tests/unit/gateway/test_processor_im_reasoning.py b/tests/unit/gateway/test_processor_im_reasoning.py new file mode 100644 index 0000000000..37bbb9131a --- /dev/null +++ b/tests/unit/gateway/test_processor_im_reasoning.py @@ -0,0 +1,112 @@ +"""IM turns resolve reasoning overrides like the Dashboard path (#2785).""" + +from __future__ import annotations + +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from octop_gateway.models import ChannelSubject, InboundMessage, TextContent + +from octop.infra.gateway.process.processor import GlobalProcessor +from octop.infra.gateway.slash.dispatcher import SlashDispatcher + + +def _processor(reasoning_parameters: dict | None) -> GlobalProcessor: + """A processor whose providers report an OpenAI-effort reasoning capability.""" + agent_manager = MagicMock() + agent_manager.merge_turn_mcp_servers = MagicMock(return_value=None) + agent_manager.default_mcp_servers = MagicMock(return_value=[]) + agent_manager.default_knowledge_base_ids = MagicMock(return_value=[]) + agent_manager.prepare_chat_mcp = AsyncMock(return_value=[]) + agent_manager.get_row = MagicMock(return_value=MagicMock(default_model=None)) + agent_manager.providers = MagicMock() + agent_manager.providers.is_model_ref_usable = MagicMock(return_value=False) + agent_manager.providers.resolve_explicit_default_model = MagicMock(return_value=None) + agent_manager.providers.resolve_model_for_multimodal_turn = MagicMock( + side_effect=lambda ref, **_k: ref + ) + agent_manager.providers.get_model_reasoning_capability = MagicMock( + return_value={"adapter": "openai_reasoning_effort"} + if reasoning_parameters is not None + else None + ) + agent_manager.get_thread_model = MagicMock(return_value=None) + agent_manager.resolve_fallback_model_ref = MagicMock(return_value="prov/m-1") + + agent_repo = MagicMock() + agent_repo.get = MagicMock(return_value=MagicMock(user_id=7, default_model=None)) + + thread_registry = MagicMock() + thread_registry.get_or_create_by_key = AsyncMock(return_value="thr-im") + thread_registry.touch_last_active = MagicMock() + thread_registry.set_title_if_null = MagicMock() + thread_registry.get_thread = MagicMock(return_value=None) + + return GlobalProcessor( + agent_manager=agent_manager, + thread_registry=thread_registry, + audit_repo=MagicMock(), + agent_repo=agent_repo, + user_repo=MagicMock(), + connector_repo=MagicMock(), + dispatcher=SlashDispatcher(), + usage_repo=None, + gateway=None, + ) + + +def _im_message() -> InboundMessage: + return InboundMessage( + channel_id="feishu", + channel_type="feishu", + tenant_id="agent-1", + channel_subject=ChannelSubject(subject_id="u1"), + content=[TextContent(text="hello")], + ) + + +@pytest.mark.asyncio +async def test_im_request_carries_reasoning_overrides() -> None: + captured: dict[str, object] = {} + overrides = {"model_fields": {"reasoning_effort": "high"}} + + async def fake_project_stream(_mgr, _aid, request, **_kwargs): + captured["request"] = request + yield MagicMock() + + processor = _processor(overrides) + + with ( + patch( + "octop.infra.gateway.process.processor.project_stream", + new=fake_project_stream, + ), + patch( + "octop.infra.gateway.process.processor.reasoning_request_parameters", + return_value=overrides, + ), + ): + events = [ev async for ev in processor(_im_message())] + + assert events + assert captured["request"]["configurable"]["octop_reasoning_overrides"] == overrides + + +@pytest.mark.asyncio +async def test_im_request_without_reasoning_capability_has_no_overrides() -> None: + captured: dict[str, object] = {} + + async def fake_project_stream(_mgr, _aid, request, **_kwargs): + captured["request"] = request + yield MagicMock() + + processor = _processor(None) + + with patch( + "octop.infra.gateway.process.processor.project_stream", + new=fake_project_stream, + ): + events = [ev async for ev in processor(_im_message())] + + assert events + assert not captured["request"].get("reasoning_overrides") From 5dad80c27af7dc572344425b8b31637fb405c27f Mon Sep 17 00:00:00 2001 From: wxhking <186391338+wxhking@users.noreply.github.com> Date: Fri, 6 Nov 2026 08:57:01 +0800 Subject: [PATCH 02/20] fix(gateway): remove duplicate MCP resolver after merge --- src/octop/infra/gateway/process/processor.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/octop/infra/gateway/process/processor.py b/src/octop/infra/gateway/process/processor.py index 6e19c5df88..4da377faf0 100644 --- a/src/octop/infra/gateway/process/processor.py +++ b/src/octop/infra/gateway/process/processor.py @@ -1077,7 +1077,6 @@ async def __call__(self, msg: InboundMessage) -> AsyncIterator[MessageEvent]: model_ref=model_ref, meta=None, ) - mcp_servers = await self._resolve_turn_mcp_servers( resolved_mcp = await self._resolve_turn_mcp_servers( agent_id=agent_id, user_id=user_id, From 1ee82eaf7f63a0f353309f3cf875ef769f0f7ef6 Mon Sep 17 00:00:00 2001 From: Wang Xinming <1353119036@qq.com> Date: Fri, 6 Nov 2026 10:07:05 +0800 Subject: [PATCH 03/20] fix(memory): preserve capture and recall runtime switches (#2296) --- CHANGELOG.md | 1 + docs/api.md | 8 ++++++ src/octop/api/routers/memory.py | 13 +++++++-- src/octop/infra/agents/manager.py | 7 +++-- tests/integration/test_memory_api.py | 36 +++++++++++++++++++++++++ tests/unit/agents/test_agent_manager.py | 33 +++++++++++++++++++++++ tests/unit/api/test_openapi_meta.py | 6 +++++ 7 files changed, 100 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e312b2f48..59e6b9f2b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -59,6 +59,7 @@ - 表单和对话可以让 AI 润色。搜索增加 DeepSeek 与元宝,模型支持 OpenAI Responses API ### 修复 +- 记忆配置 API 支持独立开关自动记录对话与自动注入召回结果,显式关闭时正确传递到运行时,避免配置被静默忽略(#2282)。 - 云端协同共享后可以直接对话。回复进行中不会被刷新冲掉,也不能删掉这场会话 - 手机截图写到专家自己的工作区。只改定时任务文案时,间隔任务不再重新计时 - 浏览器工作台恢复中文输入。主动关怀等对话安静后再发 diff --git a/docs/api.md b/docs/api.md index ad75d94bc2..131dd4fa7c 100644 --- a/docs/api.md +++ b/docs/api.md @@ -393,6 +393,7 @@ Bundled experts live in `src/octop/infra/agents/experts/library/` | `GET` | `/agents/{aid}/heartbeat-config` | owner | read heartbeat YAML | | `PUT` | `/agents/{aid}/heartbeat-config` | owner | write heartbeat YAML | | `GET` | `/agents/{aid}/memory/daily` | owner | list daily memory files | +| `GET`/`PUT` | `/agents/{aid}/memory/extract-config` | owner/admin | Read/update memory runtime and extraction options; omitted fields retain their stored values | | `GET`/`PUT` | `/agents/{aid}/memory/strong` | owner | read/edit user-maintained MEMORY.md, including for stopped agents; new sessions snapshot full content once, existing sessions keep their snapshot | | `GET`/`PUT` | `/agents/{aid}/memory/user` | owner | read/edit user-maintained USER.md with the same session snapshot policy; distinct from the derived profile | | `GET` | `/agents/{aid}/memory/manual-review` | owner | read persisted reconciliation status against current documents; no model call or memory mutation | @@ -401,6 +402,13 @@ Bundled experts live in `src/octop/infra/agents/experts/library/` | `DELETE` | `/agents/{aid}/memory/daily/{filename}` | owner | delete one daily memory | | `GET`/`POST` | `/memory/...` | user | memory API (dashboard memory tab) | +The extraction-config API accepts independent `memory_capture_enabled` and +`memory_recall_inject_enabled` booleans. Both default to `true`: set the first to +`false` to stop automatic conversation-event capture, or the second to `false` to +stop automatically injecting recalled memory into model context. These switches +do not disable explicit memory tools. Check `supported_call_options` before using +them with an older harness; unsupported options are not forwarded to its config. + ### Manual document reconciliation The manual editors save files first, then request reconciliation. The response reports diff --git a/src/octop/api/routers/memory.py b/src/octop/api/routers/memory.py index ddf345bcff..f44cae665a 100644 --- a/src/octop/api/routers/memory.py +++ b/src/octop/api/routers/memory.py @@ -57,6 +57,8 @@ # back when constructing the agent. _EXTRACT_DEFAULTS: dict[str, Any] = { "memory_enabled": True, + "memory_capture_enabled": True, + "memory_recall_inject_enabled": True, "extract_on_session_end": True, "extract_trigger_mode": "idle", "extract_idle_seconds": 300.0, @@ -193,6 +195,12 @@ class _ExtractConfigBody(BaseModel): """ memory_enabled: bool | None = None + memory_capture_enabled: bool | None = Field( + default=None, description="Automatically record conversation events in memory" + ) + memory_recall_inject_enabled: bool | None = Field( + default=None, description="Automatically inject recalled memory into the agent context" + ) extract_on_session_end: bool | None = None extract_trigger_mode: str | None = Field(default=None, description="idle / interval") extract_idle_seconds: float | None = Field( @@ -922,8 +930,9 @@ async def put_extract_config( merged = _read_extract_config(row) patch = body.model_dump(exclude_none=True) - if "memory_enabled" in patch: - merged["memory_enabled"] = bool(patch["memory_enabled"]) + for key in ("memory_enabled", "memory_capture_enabled", "memory_recall_inject_enabled"): + if key in patch: + merged[key] = bool(patch[key]) if "extract_on_session_end" in patch: merged["extract_on_session_end"] = bool(patch["extract_on_session_end"]) if "extract_trigger_mode" in patch: diff --git a/src/octop/infra/agents/manager.py b/src/octop/infra/agents/manager.py index aa4263cffa..17baaad8c7 100644 --- a/src/octop/infra/agents/manager.py +++ b/src/octop/infra/agents/manager.py @@ -224,6 +224,8 @@ def _memory_aux_model_settings( def memory_extract_supported_options() -> list[str]: """Call options supported by the installed harness, for the settings UI.""" fields = { + "memory_capture_enabled": "memory_capture_enabled", + "memory_recall_inject_enabled": "memory_recall_inject_enabled", "extract_max_tokens": "memory_extract_max_tokens", "extract_light_timeout_s": "memory_aux_light_timeout_s", "extract_heavy_timeout_s": "memory_aux_heavy_timeout_s", @@ -252,8 +254,9 @@ def _memory_extract_settings( if not isinstance(mem, dict): return {} out: dict[str, Any] = _memory_aux_model_settings(mem, supported_fields, is_ref_usable) - if "memory_enabled" in supported_fields and isinstance(mem.get("memory_enabled"), bool): - out["memory_enabled"] = mem["memory_enabled"] + for key in ("memory_enabled", "memory_capture_enabled", "memory_recall_inject_enabled"): + if key in supported_fields and isinstance(mem.get(key), bool): + out[key] = mem[key] if "memory_extract_on_session_end" in supported_fields and isinstance( mem.get("extract_on_session_end"), bool ): diff --git a/tests/integration/test_memory_api.py b/tests/integration/test_memory_api.py index 5789750582..33a8a4e7d3 100644 --- a/tests/integration/test_memory_api.py +++ b/tests/integration/test_memory_api.py @@ -384,6 +384,42 @@ async def test_extract_config_defaults_then_update(env_with_main_agent) -> None: assert r3.json()["memory_enabled"] is False +@pytest.mark.asyncio +@pytest.mark.parametrize("key", ["memory_capture_enabled", "memory_recall_inject_enabled"]) +async def test_extract_config_memory_switch_roundtrip(env_with_main_agent, key: str) -> None: + import json + + client, srv, auth, aid = env_with_main_agent + url = f"/api/agents/{aid}/memory/extract-config" + registry = srv.app_runtime.agent_registry + + initial = await client.get(url, headers=auth) + assert initial.status_code == 200, initial.text + assert initial.json()[key] is True + assert key in initial.json()["supported_call_options"] + + for enabled in (False, True): + updated = await client.put(url, headers=auth, json={key: enabled}) + assert updated.status_code == 200, updated.text + assert updated.json()[key] is enabled + row = registry.get_row(aid) + assert json.loads(row.config_json)["memory"][key] is enabled + assert getattr(registry._build_harness_config(row), key) is enabled + + # Updating extraction timing must preserve the independent runtime switch. + timing = await client.put(url, headers=auth, json={"extract_idle_seconds": 600}) + assert timing.status_code == 200, timing.text + reread = await client.get(url, headers=auth) + assert reread.json()[key] is enabled + assert reread.json()["memory_enabled"] is True + other = ( + "memory_recall_inject_enabled" + if key == "memory_capture_enabled" + else "memory_capture_enabled" + ) + assert reread.json()[other] is True + + @pytest.mark.asyncio async def test_extract_config_aux_model_roundtrip(env_with_main_agent) -> None: from tests.support.auth import create_provider diff --git a/tests/unit/agents/test_agent_manager.py b/tests/unit/agents/test_agent_manager.py index 3ff9950648..5f3031f384 100644 --- a/tests/unit/agents/test_agent_manager.py +++ b/tests/unit/agents/test_agent_manager.py @@ -628,6 +628,39 @@ def test_format_agent_start_error_unknown_passthrough() -> None: assert format_agent_start_error(exc) == "disk full" +@pytest.mark.parametrize("key", ["memory_capture_enabled", "memory_recall_inject_enabled"]) +@pytest.mark.parametrize("enabled", [False, True]) +def test_memory_runtime_switches_reach_harness_config( + manager: AgentManager, key: str, enabled: bool +) -> None: + memory = {key: enabled} + assert _memory_extract_settings({"memory": memory}) == memory + cfg = manager._build_harness_config(_row(config_json=json.dumps({"memory": memory}))) + assert getattr(cfg, key) is enabled + + +@pytest.mark.parametrize("key", ["memory_capture_enabled", "memory_recall_inject_enabled"]) +@pytest.mark.parametrize("value", [None, "false", 0, 1]) +def test_memory_runtime_switches_ignore_non_booleans(key: str, value: Any) -> None: + assert _memory_extract_settings({"memory": {key: value}}) == {} + + +def test_memory_runtime_switches_skip_unsupported_harness_fields() -> None: + memory = {"memory_capture_enabled": False, "memory_recall_inject_enabled": False} + assert _memory_extract_settings({"memory": memory}, supported_fields=frozenset()) == {} + + +def test_memory_runtime_switches_advertise_only_supported_options( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from octop.infra.agents import manager as module + + monkeypatch.setattr( + module, "_HARNESS_AGENT_CONFIG_FIELDS", frozenset({"memory_capture_enabled"}) + ) + assert module.memory_extract_supported_options() == ["memory_capture_enabled"] + + def test_memory_extract_settings_supports_legacy_harness(caplog: pytest.LogCaptureFixture) -> None: settings = _memory_extract_settings( { diff --git a/tests/unit/api/test_openapi_meta.py b/tests/unit/api/test_openapi_meta.py index 4b9a598d97..d409b2e281 100644 --- a/tests/unit/api/test_openapi_meta.py +++ b/tests/unit/api/test_openapi_meta.py @@ -27,5 +27,11 @@ async def test_openapi_has_bearer_security_and_descriptions(tmp_octop_home: Path me = spec["paths"]["/api/auth/me"]["get"] assert "BearerAuth" in me["security"][0] assert "security" not in spec["paths"]["/api/setup/status"]["get"] + extraction = spec["paths"]["/api/agents/{agent_id}/memory/extract-config"]["put"] + ref = extraction["requestBody"]["content"]["application/json"]["schema"]["$ref"] + properties = spec["components"]["schemas"][ref.rsplit("/", 1)[-1]]["properties"] + for key in ("memory_capture_enabled", "memory_recall_inject_enabled"): + assert {"type": "boolean"} in properties[key]["anyOf"] + assert properties[key]["description"] finally: await srv.stop() From fa02edc7114bbf13929d9cece44c546d0495f26f Mon Sep 17 00:00:00 2001 From: liukewia Date: Fri, 6 Nov 2026 13:55:36 +0800 Subject: [PATCH 04/20] fix(ci): build darwin-arm64 desktop packages on macos-15 (#2865) GitHub retired the macos-14 runner on 2026-11-02, so the v1.0.3b4 desktop job was cancelled before a runner was assigned. --- .github/workflows/octop-desktop.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/octop-desktop.yml b/.github/workflows/octop-desktop.yml index 78e866700c..52fb362fc9 100644 --- a/.github/workflows/octop-desktop.yml +++ b/.github/workflows/octop-desktop.yml @@ -101,7 +101,7 @@ jobs: all_plats = [ {"plat": "linux-amd64", "arch": "amd64", "os": "ubuntu-latest"}, {"plat": "linux-arm64", "arch": "arm64", "os": "ubuntu-24.04-arm"}, - {"plat": "darwin-arm64", "arch": "arm64", "os": "macos-14"}, + {"plat": "darwin-arm64", "arch": "arm64", "os": "macos-15"}, {"plat": "darwin-amd64", "arch": "amd64", "os": "macos-15-intel"}, {"plat": "windows-amd64", "arch": "amd64", "os": "windows-latest"}, {"plat": "windows-arm64", "arch": "arm64", "os": "windows-11-arm"}, From b9ee98735a80996f6fa6acf3388864bcd6996e1f Mon Sep 17 00:00:00 2001 From: Jubaoliang Date: Sat, 7 Nov 2026 14:48:39 +0800 Subject: [PATCH 05/20] fix(models,bridge): keep pool preference out of chat and explain collab failures (#2874) * fix(models,bridge): keep pool preference out of chat and explain collab failures The starred model is only a harness auto-route preference, so the chat picker shows an expert default or an explicit choice. Permanent cloud-collab rejections now fail immediately with a readable error instead of a raw close frame. * docs: record preferred-model and bridge error fixes * fix(db): close SQLite only after in-flight queries finish Windows aborted the process when server shutdown closed the shared connection while the idle reclaim sweep was still reading agents. * test(agents): initialize the reclaim sweep handle on stub managers * test(bridge): wait for both listen frames before cancelling --- CHANGELOG.md | 5 + dashboard/src/context/AgentContext.test.ts | 21 +++ dashboard/src/locales/en.json | 17 +- dashboard/src/locales/zh.json | 17 +- .../hooks/useChatComposerResources.test.tsx | 52 +++++- .../Chat/hooks/useChatComposerResources.ts | 32 ++-- dashboard/src/pages/Chat/index.tsx | 5 +- .../AdvancedSettings/BridgeSettings.tsx | 35 ++++- .../components/sections/ActiveModelPool.tsx | 38 +++-- .../pages/Settings/Models/index.module.less | 15 ++ .../src/pages/Settings/Models/useProviders.ts | 14 +- src/octop/i18n/en.json | 2 + src/octop/i18n/zh.json | 2 + src/octop/infra/agents/manager.py | 20 ++- src/octop/infra/bridge/manager.py | 148 ++++++++++++++++-- src/octop/infra/db/pool.py | 36 +++-- src/octop/infra/errors.py | 4 + tests/unit/agents/test_memory_slim.py | 1 + tests/unit/bridge/test_inbound_identity.py | 46 ++++++ tests/unit/bridge/test_list_remote_agents.py | 2 + tests/unit/bridge/test_peer_auth.py | 103 ++++++++++++ tests/unit/bridge/test_session_liveness.py | 5 +- tests/unit/db/test_db_pool.py | 22 +++ 23 files changed, 554 insertions(+), 88 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 810cc8cab9..bccb36a6d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ ## [Unreleased] +### 修复 +- 关机时会等正在进行的数据库查询结束再关闭连接,避免 Windows 上测试进程被访问冲突打断 +- 模型池里的优先模型可以取消,并且不再显示为聊天框里的选中模型。聊天框只显示专家默认模型或这场对话的手选模型 +- 添加云端协同时,权限不足、连接被占用、连到本机或达到条数上限会立刻显示可读错误,不再重试原始关闭帧 + ## [1.0.3b4] - 2026-11-06 ### 新增 diff --git a/dashboard/src/context/AgentContext.test.ts b/dashboard/src/context/AgentContext.test.ts index 7f16bff924..c5f2e4a95c 100644 --- a/dashboard/src/context/AgentContext.test.ts +++ b/dashboard/src/context/AgentContext.test.ts @@ -253,6 +253,27 @@ describe("mapBridgeAgent", () => { expect(mapped.owner_username).toBe("Alice"); }); + it("keeps a shared peer expert's default model for the chat picker", () => { + const mapped = mapBridgeAgent( + { + agent_id: "bridge:cid:01AGENT", + name: "Peer", + is_owner: false, + is_shared: true, + default_model: "prov/shared-default", + }, + { + ...conn, + is_owner: false, + owner_username: "alice", + owner_display_name: "Alice", + }, + ); + expect(mapped.is_shared).toBe(true); + expect(mapped.is_owner).toBe(false); + expect(mapped.default_model).toBe("prov/shared-default"); + }); + it("keeps management when this user owns the link and the peer owns the expert", () => { const mapped = mapBridgeAgent( { diff --git a/dashboard/src/locales/en.json b/dashboard/src/locales/en.json index 6e55a88754..cb17b51cfb 100644 --- a/dashboard/src/locales/en.json +++ b/dashboard/src/locales/en.json @@ -170,6 +170,8 @@ "BRIDGE_CONNECTION_LIMIT": "At most {{limit}} cloud collab connections per user. Delete one to add another.", "BRIDGE_SELF_CONNECT": "Cannot add this Octop instance as a peer of itself.", "BRIDGE_INBOUND_PASSIVE": "This link was opened by the peer. This side cannot change the address or dial out. After disconnect, the peer must reopen it.", + "BRIDGE_PEER_FORBIDDEN": "The account you signed in with on the peer does not have Cloud collab permission. This is not limited to admins — grant that account Cloud collab on the peer, or sign in with an account that already has it.", + "BRIDGE_PEER_CONNECTION_OWNED": "The peer already registered this cloud collab link to another user, so this account cannot take it over. Ask that user to delete it, or sign in with the same peer account. If the address actually points at this Octop, use the peer's real address instead.", "CRON_TRIGGER_INVALID": "Invalid cron trigger.", "CRON_ALREADY_RUNNING": "This task is already running on another instance.", "SLASH_UNKNOWN": "Unknown slash command.", @@ -3295,7 +3297,7 @@ "providersTitle": "Providers", "providersDescription": "Configure API keys and endpoints for each provider.", "llmTitle": "LLM", - "llmDescription": "The system intelligently selects the best model based on message content. You can also set a preferred model.", + "llmDescription": "The system intelligently selects the best model based on message content. You can also set a priority model.", "configureProvider": "Configure {{name}}", "baseURL": "Base URL", "docs": "Docs", @@ -3504,14 +3506,17 @@ "costOutput": "Output Cost (per 1M tokens)", "templateApplied": "✓ Pre-filled from preset template. You can edit these values.", "modelPool": "Available Model Pool", - "autoRouteTooltip": "Auto mode prioritizes your preferred model and switches when the input type is incompatible", - "autoRouteDesc": "These models are currently available. Auto mode prioritizes your preferred model; if a message contains images or other content the current model cannot handle, the system switches to a compatible model.", + "autoRouteTooltip": "Auto mode uses your priority model first and switches when the input type is incompatible", + "autoRouteDesc": "These models are currently available. Auto mode uses your priority model first; if a message contains images or other content the current model cannot handle, the system switches to a compatible model.", "modelCount": "{{count}} available", "modelUnit": "models", "noModelsAvailable": "No models available. Please authorize at least one provider and configure models.", - "preferredModelSet": "{{model}} set as preferred model", - "setAsPreferred": "Set as preferred", - "currentPreferred": "Current preferred model", + "preferredModelSet": "{{model}} set as the priority model", + "preferredModelCleared": "Priority model cleared", + "setAsPreferred": "Use this model first for auto routing", + "clearPreferred": "Clear priority model", + "preferredBadge": "Priority", + "currentPreferred": "Current priority model", "capReasoning": "Reasoning", "cap_text": "Text", "cap_image": "Image", diff --git a/dashboard/src/locales/zh.json b/dashboard/src/locales/zh.json index 74e95645b8..3632f17f4d 100644 --- a/dashboard/src/locales/zh.json +++ b/dashboard/src/locales/zh.json @@ -170,6 +170,8 @@ "BRIDGE_CONNECTION_LIMIT": "每用户最多 {{limit}} 条云端协同,请先删除不用的连接。", "BRIDGE_SELF_CONNECT": "不能把本机 Octop 添加为自己的对端。", "BRIDGE_INBOUND_PASSIVE": "这是对端主动接入的连接,本侧无法改地址或主动拨号。断开后需对端重新打开。", + "BRIDGE_PEER_FORBIDDEN": "对端登录账号没有「云端协同」权限。这项功能不限于管理员:请在对端为该账号打开云端协同权限,或改用已有该权限的账号。", + "BRIDGE_PEER_CONNECTION_OWNED": "对端已把这条云端协同登记在另一个用户名下,当前账号无法接管。请让原用户删除那条连接,或改用同一个对端账号。如果填写的地址其实指向本机,请改成对端的真实地址。", "CRON_TRIGGER_INVALID": "无效的定时触发器。", "CRON_ALREADY_RUNNING": "该任务已在其他实例上运行。", "SLASH_UNKNOWN": "未知的斜杠指令。", @@ -3295,7 +3297,7 @@ "providersTitle": "模型提供商", "providersDescription": "为每个模型提供商配置 API 密钥和接入端点。", "llmTitle": "大语言模型", - "llmDescription": "系统会根据消息内容智能选择最合适的模型,您也可以设置偏好模型。", + "llmDescription": "系统会根据消息内容智能选择最合适的模型,您也可以设置优先模型。", "configureProvider": "配置 {{name}}", "baseURL": "接入地址", "docs": "文档", @@ -3504,14 +3506,17 @@ "costOutput": "输出费用(每百万 Token)", "templateApplied": "✓ 已从预置模板预填充,您可以修改这些值。", "modelPool": "可用模型池", - "autoRouteTooltip": "自动模式优先使用你的偏好模型;当输入类型不兼容时,系统会切换到支持该输入的模型", - "autoRouteDesc": "以下为当前可用模型。自动模式会优先使用你的偏好模型;当消息包含图片等当前模型不支持的内容时,系统会自动切换到兼容模型。", + "autoRouteTooltip": "自动模式优先使用你的优先模型;当输入类型不兼容时,系统会切换到支持该输入的模型", + "autoRouteDesc": "以下为当前可用模型。自动模式会优先使用你的优先模型;当消息包含图片等当前模型不支持的内容时,系统会自动切换到兼容模型。", "modelCount": "{{count}} 个可用", "modelUnit": "个", "noModelsAvailable": "暂无可用模型,请先授权至少一个提供商并配置模型。", - "preferredModelSet": "已将 {{model}} 设为偏好模型", - "setAsPreferred": "设为偏好模型", - "currentPreferred": "当前偏好模型", + "preferredModelSet": "已将 {{model}} 设为优先模型", + "preferredModelCleared": "已取消优先模型", + "setAsPreferred": "设为自动调度的优先模型", + "clearPreferred": "取消优先模型", + "preferredBadge": "当前优先", + "currentPreferred": "当前优先模型", "capReasoning": "推理", "cap_text": "文本", "cap_image": "图像", diff --git a/dashboard/src/pages/Chat/hooks/useChatComposerResources.test.tsx b/dashboard/src/pages/Chat/hooks/useChatComposerResources.test.tsx index 4c4d95eeae..dfa6e63059 100644 --- a/dashboard/src/pages/Chat/hooks/useChatComposerResources.test.tsx +++ b/dashboard/src/pages/Chat/hooks/useChatComposerResources.test.tsx @@ -424,7 +424,7 @@ describe("useChatComposerResources — expert default model", () => { ); }); - it("uses the account preferred model when the expert default is Auto", async () => { + it("leaves Auto unset when the expert has no default, even if a preferred model is set", async () => { vi.mocked(preferencesApi.get).mockResolvedValue({ locale: "zh", remote_browser_bookmarks: [], @@ -437,8 +437,9 @@ describe("useChatComposerResources — expert default model", () => { ); await waitFor(() => - expect(result.current.selectedModel).toBe("prov/preferred"), + expect(result.current.preferredModel).toBe("prov/preferred"), ); + expect(result.current.selectedModel).toBeNull(); }); it("keeps an explicit thread model ahead of the expert default", async () => { @@ -485,6 +486,7 @@ describe("useChatComposerResources — peer expert defaults", () => { ); await waitFor(() => { + expect(result.current.modelsReady).toBe(true); expect(result.current.selectedModel).toBe("prov/peer"); expect(result.current.selectedConnectors).toEqual(["c2"]); expect(result.current.selectedKnowledgeBaseIds).toEqual(["k2"]); @@ -492,6 +494,52 @@ describe("useChatComposerResources — peer expert defaults", () => { }); }); + it("shows a shared peer expert default even when this catalog omits it", async () => { + agentState.agents = [ + { + agent_id: "bridge:cid:peer", + bridge: true, + bridge_connection_id: "cid", + is_owner: false, + is_shared: true, + default_model: "prov/shared-peer", + }, + ]; + vi.mocked(providerApi.listResolvedModels).mockResolvedValue([ + model("other"), + ]); + + const { result } = renderHook(() => + useChatComposerResources("bridge:cid:peer", null), + ); + + await waitFor(() => expect(result.current.modelsReady).toBe(true)); + expect(result.current.selectedModel).toBe("prov/shared-peer"); + expect(octopThreadsApi.patch).not.toHaveBeenCalled(); + }); + + it("shows a shared local expert default even when this catalog omits it", async () => { + agentState.agents = [ + { + agent_id: "expertA", + is_shared: true, + is_owner: false, + default_model: "prov/shared-local", + }, + ]; + vi.mocked(providerApi.listResolvedModels).mockResolvedValue([ + model("other"), + ]); + + const { result } = renderHook(() => + useChatComposerResources("expertA", null), + ); + + await waitFor(() => expect(result.current.modelsReady).toBe(true)); + expect(result.current.selectedModel).toBe("prov/shared-local"); + expect(octopThreadsApi.patch).not.toHaveBeenCalled(); + }); + it("leaves a remote Auto expert unset instead of the local preferred model", async () => { agentState.agents = [ { diff --git a/dashboard/src/pages/Chat/hooks/useChatComposerResources.ts b/dashboard/src/pages/Chat/hooks/useChatComposerResources.ts index e2cc158839..1758a13a07 100644 --- a/dashboard/src/pages/Chat/hooks/useChatComposerResources.ts +++ b/dashboard/src/pages/Chat/hooks/useChatComposerResources.ts @@ -166,26 +166,21 @@ export function useChatComposerResources( if (isNewSession) composerTouchedRef.current = false; }, [isNewSession]); - // No thread override: show the expert default. A local account preference - // fills Auto only for experts on this Octop. A remote Auto stays unset so - // the turn omits ``model`` and the peer resolves its own default. + // The chat picker shows an explicit choice only: this thread's override, or + // the expert's default model. Account preferred model is an auto-route + // priority on the server and stays unselected here (Auto). useEffect(() => { const local = activeThreadId ? conversationOverrides[activeThreadId] : undefined; - const autoFallback = remoteBridge ? null : preferredModel; setSelectedModel( - local - ? local.model - : stickyModel || expertDefaultModel || autoFallback || null, + local ? local.model : stickyModel || expertDefaultModel || null, ); }, [ resolvedAgentId, activeThreadId, stickyModel, expertDefaultModel, - preferredModel, - remoteBridge, conversationOverrides, ]); @@ -562,21 +557,21 @@ export function useChatComposerResources( [activeThreadId, availableModels, modelReasoning, resolvedAgentId], ); - // Clear a stale choice only after this expert's catalog loaded successfully. - // Persist Auto so reopening the thread cannot restore the disabled model. + // Clear a saved thread override that this catalog no longer contains, and + // persist Auto so reopening the thread cannot restore that disabled model. + // The expert's own default stays selected even when the viewer's catalog + // omits it — shared and peer experts must still show that default. useEffect(() => { if (!modelsReady) return; const local = activeThreadId ? conversationOverrides[activeThreadId] : undefined; - const autoFallback = remoteBridge ? null : preferredModel; - const model = local - ? local.model - : stickyModel || expertDefaultModel || autoFallback || null; + const override = local ? local.model : stickyModel || null; if ( - model && + override && + override !== expertDefaultModel && !availableModels.some( - (item) => `${item.provider_name}/${item.model}` === model, + (item) => `${item.provider_name}/${item.model}` === override, ) ) { handleModelChange(null); @@ -585,8 +580,6 @@ export function useChatComposerResources( activeThreadId, stickyModel, expertDefaultModel, - preferredModel, - remoteBridge, conversationOverrides, availableModels, modelsReady, @@ -683,6 +676,7 @@ export function useChatComposerResources( availableModels, modelsReady, activeModelRef, + preferredModel, handleConnectorsChange, handleKnowledgeBaseIdsChange, }; diff --git a/dashboard/src/pages/Chat/index.tsx b/dashboard/src/pages/Chat/index.tsx index a11fce0245..e51418c9ab 100644 --- a/dashboard/src/pages/Chat/index.tsx +++ b/dashboard/src/pages/Chat/index.tsx @@ -579,6 +579,7 @@ function ChatPageInner() { availableModels, modelsReady, activeModelRef, + preferredModel, reasoningMode, reasoningEffort, handleReasoningChange, @@ -604,7 +605,7 @@ function ChatPageInner() { selectedModel, availableModels, activeAgent?.default_model, - activeModelRef, + preferredModel || activeModelRef, activeAgent, ); @@ -1126,6 +1127,7 @@ function ChatPageInner() { lastUserModel, selectedModel, activeAgent?.default_model, + preferredModel, activeModelRef, ]); if (providerId == null) { @@ -1144,6 +1146,7 @@ function ChatPageInner() { availableModels, selectedModel, activeAgent?.default_model, + preferredModel, activeModelRef, messages, t, diff --git a/dashboard/src/pages/Settings/AdvancedSettings/BridgeSettings.tsx b/dashboard/src/pages/Settings/AdvancedSettings/BridgeSettings.tsx index ce91981899..314d6cbde1 100644 --- a/dashboard/src/pages/Settings/AdvancedSettings/BridgeSettings.tsx +++ b/dashboard/src/pages/Settings/AdvancedSettings/BridgeSettings.tsx @@ -7,6 +7,7 @@ import { type CSSProperties, type ReactNode, } from "react"; +import type { TFunction } from "i18next"; import { Button, Drawer, @@ -779,6 +780,36 @@ function AutoReconnectControl({ ); } +function formatBridgeLastError(error: string, t: TFunction): string { + const prefix = "octop:"; + if (error.startsWith(prefix)) { + const body = error.slice(prefix.length); + const queryAt = body.indexOf("?"); + const key = queryAt === -1 ? body : body.slice(0, queryAt); + const params: Record = {}; + if (queryAt !== -1) { + const search = new URLSearchParams(body.slice(queryAt + 1)); + search.forEach((value, name) => { + params[name] = + name === "limit" && /^\d+$/.test(value) ? Number(value) : value; + }); + } + const translated = t(key, { ...params, defaultValue: "" }); + if (translated && translated !== key) return String(translated); + } + const lower = error.toLowerCase(); + if (lower.includes("owned by another user")) { + return t("apiErrors.BRIDGE_PEER_CONNECTION_OWNED"); + } + if (lower.includes("permission required")) { + return t("apiErrors.BRIDGE_PEER_FORBIDDEN"); + } + if (lower.includes("self connect")) { + return t("apiErrors.BRIDGE_SELF_CONNECT"); + } + return error; +} + function BridgeConnectionCard({ row, agents, @@ -886,7 +917,9 @@ function BridgeConnectionCard({

) : null} {row.last_error ? ( -

{row.last_error}

+

+ {formatBridgeLastError(row.last_error, t)} +

) : null} diff --git a/dashboard/src/pages/Settings/Models/components/sections/ActiveModelPool.tsx b/dashboard/src/pages/Settings/Models/components/sections/ActiveModelPool.tsx index bdc329fc2c..5543627fcb 100644 --- a/dashboard/src/pages/Settings/Models/components/sections/ActiveModelPool.tsx +++ b/dashboard/src/pages/Settings/Models/components/sections/ActiveModelPool.tsx @@ -85,17 +85,20 @@ export function ActiveModelPool({ const isAlready = m.provider_name === activeModel.provider_name && m.model === activeModel.model; - if (isAlready) return; - const key = `${m.provider_name}/${m.model}`; setSetting(key); try { - await preferencesApi.patch({ preferred_model: key }); - message.success( - t("models.preferredModelSet", { - model: modelOptionLabel(m), - }), - ); + if (isAlready) { + await preferencesApi.patch({ preferred_model: null }); + message.success(t("models.preferredModelCleared")); + } else { + await preferencesApi.patch({ preferred_model: key }); + message.success( + t("models.preferredModelSet", { + model: modelOptionLabel(m), + }), + ); + } await onSaved(); } catch (err) { message.error( @@ -328,7 +331,7 @@ export function ActiveModelPool({ @@ -351,11 +354,18 @@ export function ActiveModelPool({
- - {modelOptionLabel(m)} + + + {modelOptionLabel(m)} + + {isPreferred ? ( + + {t("models.preferredBadge")} + + ) : null}
diff --git a/dashboard/src/pages/Settings/Models/index.module.less b/dashboard/src/pages/Settings/Models/index.module.less index c01daae272..cb07e6d453 100644 --- a/dashboard/src/pages/Settings/Models/index.module.less +++ b/dashboard/src/pages/Settings/Models/index.module.less @@ -1173,6 +1173,20 @@ white-space: nowrap; } +.poolModelNameRow { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; +} + +.preferredBadge { + flex: none; + margin-inline-end: 0; + font-size: 11px; + line-height: 18px; +} + .poolModelName { font-size: 14px; font-weight: 500; @@ -1180,6 +1194,7 @@ line-height: 1.4; word-break: break-word; overflow-wrap: anywhere; + min-width: 0; @media (max-width: 767px) { font-size: 14px; diff --git a/dashboard/src/pages/Settings/Models/useProviders.ts b/dashboard/src/pages/Settings/Models/useProviders.ts index ee42b656b6..98e2aac6a1 100644 --- a/dashboard/src/pages/Settings/Models/useProviders.ts +++ b/dashboard/src/pages/Settings/Models/useProviders.ts @@ -133,9 +133,6 @@ export function useProviders(): UseProvidersResult { request("/admin/providers"), request("/providers/presets"), providerApi.listResolvedModels(), - request<{ provider_name: string; model: string }>( - "/providers/active-model", - ), preferencesApi.get(), ]); const rows = @@ -150,10 +147,8 @@ export function useProviders(): UseProvidersResult { settled[2].status === "fulfilled" && Array.isArray(settled[2].value) ? settled[2].value : []; - const active = - settled[3].status === "fulfilled" ? settled[3].value : null; const preferences = - settled[4].status === "fulfilled" ? settled[4].value : null; + settled[3].status === "fulfilled" ? settled[3].value : null; if ( settled[0].status === "rejected" && @@ -171,6 +166,8 @@ export function useProviders(): UseProvidersResult { setProviders(normalized); setPresets(presetList); setResolvedModels(resolved); + // Only an explicit per-user preference is starred. The global active + // model is a separate fallback and must not look selected here. const preferredParts = (preferences?.preferred_model || "").split("/"); setActiveModel( preferredParts.length > 1 @@ -178,11 +175,6 @@ export function useProviders(): UseProvidersResult { provider_name: preferredParts[0], model: preferredParts.slice(1).join("/"), } - : active && typeof active === "object" - ? { - provider_name: active.provider_name ?? "", - model: active.model ?? "", - } : { provider_name: "", model: "" }, ); setModelReasoning(preferences?.model_reasoning || {}); diff --git a/src/octop/i18n/en.json b/src/octop/i18n/en.json index 58a34b0ef4..77ed010359 100644 --- a/src/octop/i18n/en.json +++ b/src/octop/i18n/en.json @@ -459,6 +459,8 @@ "BRIDGE_CONNECTION_LIMIT": "At most {limit} cloud collab connections per user. Delete one to add another.", "BRIDGE_SELF_CONNECT": "Cannot add this Octop instance as a peer of itself.", "BRIDGE_INBOUND_PASSIVE": "This link was opened by the peer. This side cannot change the address or dial out. After disconnect, the peer must reopen it.", + "BRIDGE_PEER_FORBIDDEN": "The account you signed in with on the peer does not have Cloud collab permission. This is not limited to admins — grant that account Cloud collab on the peer, or sign in with an account that already has it.", + "BRIDGE_PEER_CONNECTION_OWNED": "The peer already registered this cloud collab link to another user, so this account cannot take it over. Ask that user to delete it, or sign in with the same peer account. If the address actually points at this Octop, use the peer's real address instead.", "CRON_TRIGGER_INVALID": "Invalid cron trigger.", "CRON_ALREADY_RUNNING": "This task is already running on another instance.", "SLASH_UNKNOWN": "Unknown slash command.", diff --git a/src/octop/i18n/zh.json b/src/octop/i18n/zh.json index ccea23761f..e00d92aee0 100644 --- a/src/octop/i18n/zh.json +++ b/src/octop/i18n/zh.json @@ -459,6 +459,8 @@ "BRIDGE_CONNECTION_LIMIT": "每用户最多 {limit} 条云端协同,请先删除不用的连接。", "BRIDGE_SELF_CONNECT": "不能把本机 Octop 添加为自己的对端。", "BRIDGE_INBOUND_PASSIVE": "这是对端主动接入的连接,本侧无法改地址或主动拨号。断开后需对端重新打开。", + "BRIDGE_PEER_FORBIDDEN": "对端登录账号没有「云端协同」权限。这项功能不限于管理员:请在对端为该账号打开云端协同权限,或改用已有该权限的账号。", + "BRIDGE_PEER_CONNECTION_OWNED": "对端已把这条云端协同登记在另一个用户名下,当前账号无法接管。请让原用户删除那条连接,或改用同一个对端账号。如果填写的地址其实指向本机,请改成对端的真实地址。", "CRON_TRIGGER_INVALID": "无效的定时触发器。", "CRON_ALREADY_RUNNING": "该任务已在其他实例上运行。", "SLASH_UNKNOWN": "未知的斜杠指令。", diff --git a/src/octop/infra/agents/manager.py b/src/octop/infra/agents/manager.py index 17baaad8c7..e1feeb8333 100644 --- a/src/octop/infra/agents/manager.py +++ b/src/octop/infra/agents/manager.py @@ -562,6 +562,7 @@ def __init__( self._reclaim_pending: set[str] = set() self._reclaim_holds: dict[str, asyncio.Event] = {} self._reclaim_task: asyncio.Task[None] | None = None + self._reclaim_sweep_task: asyncio.Task[None] | None = None self._reclaim_wake: asyncio.Event | None = None self._reload_dirty: set[str] = set() self._reload_worker_running: dict[str, bool] = {} @@ -721,6 +722,15 @@ async def boot(self) -> None: ) async def shutdown(self) -> None: + # The idle sweep reads the control-plane DB on a worker thread. Wait for + # that read to finish before the caller closes the shared connection. + sweep = self._reclaim_sweep_task + self._reclaim_sweep_task = None + if sweep is not None and not sweep.done(): + try: + await sweep + except Exception: + logger.warning("idle reclaim sweep failed during shutdown", exc_info=True) self._reclaim_pending.clear() reclaim_task = self._reclaim_task self._reclaim_task = None @@ -1769,11 +1779,15 @@ def schedule_store_reclaim(self, agent_id: str) -> None: def schedule_idle_reclaim_sweep(self) -> None: """Queue loaded stores whose freelist is already large enough to compact.""" try: - asyncio.get_running_loop().create_task( - self._sweep_bloated_stores(), name="store-reclaim-sweep" - ) + loop = asyncio.get_running_loop() except RuntimeError: return + current = self._reclaim_sweep_task + if current is not None and not current.done(): + return + self._reclaim_sweep_task = loop.create_task( + self._sweep_bloated_stores(), name="store-reclaim-sweep" + ) async def compact_agent_database(self, agent_id: str, *, wait_s: float = 60) -> bool: """Rebuild the database now. False means it was deferred until idle.""" diff --git a/src/octop/infra/bridge/manager.py b/src/octop/infra/bridge/manager.py index 474d0d1ef4..d23d64a35d 100644 --- a/src/octop/infra/bridge/manager.py +++ b/src/octop/infra/bridge/manager.py @@ -7,8 +7,8 @@ import json import logging from contextlib import suppress -from typing import Any -from urllib.parse import urljoin, urlparse, urlsplit +from typing import Any, NoReturn +from urllib.parse import parse_qsl, urlencode, urljoin, urlparse, urlsplit import httpx import websockets @@ -62,12 +62,106 @@ def _handshake_http_status(exc: BaseException) -> int | None: return status if isinstance(status, int) else None +def _close_frame(exc: BaseException) -> Any: + return getattr(exc, "rcvd", None) or getattr(exc, "sent", None) + + def _close_code(exc: BaseException) -> int | None: - rcvd = getattr(exc, "rcvd", None) - code = getattr(rcvd, "code", None) + frame = _close_frame(exc) + code = getattr(frame, "code", None) return code if isinstance(code, int) else None +def _close_reason(exc: BaseException) -> str: + frame = _close_frame(exc) + reason = getattr(frame, "reason", None) + if isinstance(reason, bytes): + reason = reason.decode("utf-8", errors="replace") + return str(reason or "").strip() + + +_DIAL_ERROR_PREFIX = "octop:apiErrors." +# The peer will reject these the same way on every retry. Fail the dial at once +# and keep the readable error; do not spend the auto-reconnect budget on them. +_PERMANENT_DIAL_CODES = frozenset( + { + ErrorCode.BRIDGE_SELF_CONNECT, + ErrorCode.BRIDGE_PEER_FORBIDDEN, + ErrorCode.BRIDGE_PEER_CONNECTION_OWNED, + ErrorCode.BRIDGE_CONNECTION_LIMIT, + ErrorCode.BRIDGE_AUTH_FAILED, + } +) + + +def bridge_failure_from_dial(exc: BaseException) -> OctopError: + """Map a peer WebSocket close into a user-facing bridge error. + + The raw ``websockets`` text (``received 4003 (private use) ...``) is not + something to show in the dashboard. + """ + reason = _close_reason(exc).lower() + code = _close_code(exc) + if code == 4004 or "self connect" in reason: + return OctopError( + ErrorCode.BRIDGE_SELF_CONNECT, + "cannot link this Octop instance to itself", + ) + if code == 4003 and "permission" in reason: + return OctopError( + ErrorCode.BRIDGE_PEER_FORBIDDEN, + "peer account lacks cloud collab permission", + ) + if code == 4003 and "owned by another" in reason: + return OctopError( + ErrorCode.BRIDGE_PEER_CONNECTION_OWNED, + "connection owned by another user on the peer", + ) + if code == 4008 or "connection limit" in reason: + return OctopError( + ErrorCode.BRIDGE_CONNECTION_LIMIT, + f"at most {MAX_CONNECTIONS_PER_USER} cloud collab connections", + details={"limit": MAX_CONNECTIONS_PER_USER}, + ) + if code == 4001: + return OctopError(ErrorCode.BRIDGE_AUTH_FAILED, "peer rejected credentials") + return OctopError(ErrorCode.BRIDGE_PEER_UNREACHABLE, _annotate_bridge_dial_error(exc)) + + +def dial_error_note(exc: BaseException) -> str: + """Persist a bridge dial failure. Known cases use an ``octop:`` i18n key. + + Interpolation values (for example the connection ``limit``) ride in the + query so the dashboard and the API toast can format the same sentence. + """ + failure = bridge_failure_from_dial(exc) + if failure.code is not ErrorCode.BRIDGE_PEER_UNREACHABLE: + note = f"{_DIAL_ERROR_PREFIX}{failure.code.value}" + if failure.details: + note = f"{note}?{urlencode(failure.details)}" + return note + reason = _close_reason(exc) + if reason: + return reason + return _annotate_bridge_dial_error(exc) + + +def error_from_dial_note(note: str | None) -> OctopError | None: + text = (note or "").strip() + if not text.startswith(_DIAL_ERROR_PREFIX): + return None + body = text[len(_DIAL_ERROR_PREFIX) :] + name, _, query = body.partition("?") + try: + code = ErrorCode(name) + except ValueError: + return None + details: dict[str, Any] = {} + for key, value in parse_qsl(query, keep_blank_values=False): + details[key] = int(value) if key == "limit" and value.isdigit() else value + return OctopError(code, name, details=details) + + def _should_refresh_peer_token(exc: BaseException) -> bool: """True when the peer refused the socket before hello — usually a bad token. @@ -661,15 +755,26 @@ async def connect(self, connection_id: str, *, owner_user_id: int) -> BridgeConn self._reconnect_failures[connection_id] = 0 return self._repo.get(connection_id) or row if task.done(): - exc = task.exception() if not task.cancelled() else None - msg = str(exc) if exc else "bridge connect failed" - latest = self._repo.get(connection_id) - if latest is not None and latest.status != "error": - self._repo.update_status(connection_id, status="error", last_error=msg[:500]) - raise OctopError(ErrorCode.BRIDGE_PEER_UNREACHABLE, msg) + self._raise_dial_failure(connection_id) await asyncio.sleep(0.1) - self._repo.update_status(connection_id, status="error", last_error="bridge connect timeout") - raise OctopError(ErrorCode.BRIDGE_PEER_UNREACHABLE, "bridge connect timeout") + self._raise_dial_failure(connection_id, fallback="bridge connect timeout") + + def _raise_dial_failure( + self, connection_id: str, *, fallback: str = "bridge connect failed" + ) -> NoReturn: + latest = self._repo.get(connection_id) + note = latest.last_error if latest is not None else None + known = error_from_dial_note(note) + if known is not None: + if latest is not None and latest.status != "error": + self._repo.update_status( + connection_id, status="error", last_error=(note or "")[:500] + ) + raise known + detail = (note or fallback)[:500] + if latest is not None and latest.status != "error": + self._repo.update_status(connection_id, status="error", last_error=detail) + raise OctopError(ErrorCode.BRIDGE_PEER_UNREACHABLE, detail) async def disconnect(self, connection_id: str) -> None: self._user_stopped.add(connection_id) @@ -888,7 +993,17 @@ async def _outbound_supervisor(self, connection_id: str) -> None: ) continue retried_auth = False - detail = _annotate_bridge_dial_error(exc) + detail = dial_error_note(exc) + if bridge_failure_from_dial(exc).code in _PERMANENT_DIAL_CODES: + if self._repo.get(connection_id) is not None: + self._repo.update_status( + connection_id, status="error", last_error=detail[:500] + ) + # Leave auto-reconnect enabled, but stop this supervisor so a + # rejected login does not wait out the backoff or overwrite + # the readable error with the English disable line. + self._user_stopped.add(connection_id) + return failures = self._reconnect_failures.get(connection_id, 0) + 1 self._reconnect_failures[connection_id] = failures if self._repo.get(connection_id) is not None: @@ -1128,6 +1243,13 @@ async def close_transport() -> None: return existing = self._repo.get(connection_id) + # An outbound row (we stored the peer password) only exists on the + # instance that allocated this connection id. A hello for that id means + # the dial reached this same Octop — often because the typed URL does + # not match the advertised address, so the earlier self-check missed it. + if existing is not None and bool(existing.credential_blob): + await websocket.close(code=4004, reason="self connect") + return if existing is not None and int(existing.owner_user_id) != int(user.id): await websocket.close(code=4003, reason="connection owned by another user") return diff --git a/src/octop/infra/db/pool.py b/src/octop/infra/db/pool.py index 84f44cded9..aefb1c5cab 100644 --- a/src/octop/infra/db/pool.py +++ b/src/octop/infra/db/pool.py @@ -39,29 +39,36 @@ def __init__(self, path: Path): self.path = Path(path) self.path.parent.mkdir(parents=True, exist_ok=True) first_create = not self.path.exists() - self._conn = sqlite3.connect( + conn = sqlite3.connect( str(self.path), check_same_thread=False, isolation_level=None, ) - self._conn.row_factory = sqlite3.Row - self._conn.execute("PRAGMA foreign_keys = ON") - self._conn.execute("PRAGMA journal_mode = WAL") + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA foreign_keys = ON") + conn.execute("PRAGMA journal_mode = WAL") # WAL + FULL fsyncs every autocommit statement. On Windows that is # FlushFileBuffers and dominates pytest (and the app), so only Windows # drops to NORMAL (SQLite's recommended WAL setting): an OS crash can # drop the last transaction, an application crash cannot corrupt the # file. Other platforms keep the default FULL. if os.name == "nt": - self._conn.execute("PRAGMA synchronous = NORMAL") + conn.execute("PRAGMA synchronous = NORMAL") + self._conn: sqlite3.Connection | None = conn self._lock = threading.RLock() if first_create and os.name == "posix": os.chmod(self.path, 0o600) + def _live_connection(self) -> sqlite3.Connection: + conn = self._conn + if conn is None: + raise sqlite3.ProgrammingError("sqlite pool is closed") + return conn + @contextmanager def connect(self) -> Iterator[sqlite3.Connection]: with self._lock: - yield self._conn + yield self._live_connection() @contextmanager def transaction(self) -> Iterator[sqlite3.Connection]: @@ -73,16 +80,23 @@ def transaction(self) -> Iterator[sqlite3.Connection]: # SQLITE_BUSY_SNAPSHOT ("database is locked") *immediately*; the 5s busy timeout # cannot wait that out. Taking the write lock up front makes the competing writer # wait instead of aborting us. - self._conn.execute("BEGIN IMMEDIATE") + conn = self._live_connection() + conn.execute("BEGIN IMMEDIATE") try: - yield self._conn - self._conn.execute("COMMIT") + yield conn + conn.execute("COMMIT") except Exception: - self._conn.execute("ROLLBACK") + conn.execute("ROLLBACK") raise def close(self) -> None: - self._conn.close() + # Wait for an in-flight query. Closing the shared connection underneath + # another thread is an access violation on Windows. + with self._lock: + conn = self._conn + self._conn = None + if conn is not None: + conn.close() class _CompatRow(Mapping[str, Any]): diff --git a/src/octop/infra/errors.py b/src/octop/infra/errors.py index b8c74ce52a..236da2ddc7 100644 --- a/src/octop/infra/errors.py +++ b/src/octop/infra/errors.py @@ -77,6 +77,8 @@ class ErrorCode(StrEnum): BRIDGE_CONNECTION_LIMIT = "BRIDGE_CONNECTION_LIMIT" BRIDGE_SELF_CONNECT = "BRIDGE_SELF_CONNECT" BRIDGE_INBOUND_PASSIVE = "BRIDGE_INBOUND_PASSIVE" + BRIDGE_PEER_FORBIDDEN = "BRIDGE_PEER_FORBIDDEN" + BRIDGE_PEER_CONNECTION_OWNED = "BRIDGE_PEER_CONNECTION_OWNED" CRON_TRIGGER_INVALID = "CRON_TRIGGER_INVALID" CRON_ALREADY_RUNNING = "CRON_ALREADY_RUNNING" SLASH_UNKNOWN = "SLASH_UNKNOWN" @@ -238,6 +240,8 @@ class ErrorCode(StrEnum): ErrorCode.BRIDGE_CONNECTION_LIMIT: 400, ErrorCode.BRIDGE_SELF_CONNECT: 400, ErrorCode.BRIDGE_INBOUND_PASSIVE: 400, + ErrorCode.BRIDGE_PEER_FORBIDDEN: 403, + ErrorCode.BRIDGE_PEER_CONNECTION_OWNED: 409, ErrorCode.CRON_TRIGGER_INVALID: 400, ErrorCode.CRON_ALREADY_RUNNING: 409, ErrorCode.SLASH_UNKNOWN: 400, diff --git a/tests/unit/agents/test_memory_slim.py b/tests/unit/agents/test_memory_slim.py index a05e3dd5f4..4c7aada22e 100644 --- a/tests/unit/agents/test_memory_slim.py +++ b/tests/unit/agents/test_memory_slim.py @@ -37,6 +37,7 @@ def make_manager(tmp_path): registry._reclaim_pending = set() registry._reclaim_holds = {} registry._reclaim_task = None + registry._reclaim_sweep_task = None registry._reclaim_wake = None registry.get_agent = lambda _: agent registry.memory_slim = MemorySlimCoordinator(registry) diff --git a/tests/unit/bridge/test_inbound_identity.py b/tests/unit/bridge/test_inbound_identity.py index 8a8d3925ee..67d3f24d40 100644 --- a/tests/unit/bridge/test_inbound_identity.py +++ b/tests/unit/bridge/test_inbound_identity.py @@ -171,6 +171,52 @@ async def test_same_loopback_advertise_accepts_remote_peer(tmp_path: Path) -> No await task +@pytest.mark.asyncio +async def test_hello_for_local_outbound_row_is_self_connect(tmp_path: Path) -> None: + """A dial that lands on this instance is self-connect, even as another user. + + The typed URL often does not match the advertised address, so the outbound + row already exists when the hello arrives. That used to close with + "connection owned by another user". + """ + mgr, owner, uid = _manager(tmp_path, advertise_base_url="http://127.0.0.1:8088") + member_id = mgr._users.create(username="member", password_hash="x", role="user") + mgr._repo.create( + connection_id="CIDOUT", + owner_user_id=uid, + peer_base_url="https://peer.example", + peer_username="member", + display_name="peer", + credential_blob=b"secret", + ) + member = SimpleNamespace(id=member_id, username="member") + sock = _HoldSocket(_hello("CIDOUT", display_name="对端"), client_host="203.0.113.8") + await mgr.accept_inbound(websocket=sock, user=member) + assert sock.close_code == 4004 + assert mgr._sessions.get("CIDOUT") is None + + own = _HoldSocket(_hello("CIDOUT", display_name="自己"), client_host="203.0.113.9") + await mgr.accept_inbound(websocket=own, user=owner) + assert own.close_code == 4004 + + +@pytest.mark.asyncio +async def test_inbound_id_owned_by_another_user_stays_rejected(tmp_path: Path) -> None: + mgr, _owner, uid = _manager(tmp_path, advertise_base_url="http://127.0.0.1:8088") + member_id = mgr._users.create(username="member", password_hash="x", role="user") + mgr._repo.create( + connection_id="CIDIN", + owner_user_id=uid, + peer_base_url="http://203.0.113.8:8088", + peer_username="someone", + display_name="inbound", + ) + sock = _HoldSocket(_hello("CIDIN", display_name="对端"), client_host="203.0.113.8") + member = SimpleNamespace(id=member_id, username="member") + await mgr.accept_inbound(websocket=sock, user=member) + assert sock.close_code == 4003 + + @pytest.mark.asyncio async def test_matching_public_advertise_is_self_connect(tmp_path: Path) -> None: mgr, owner, _uid = _manager(tmp_path, advertise_base_url="http://203.0.113.10:8088") diff --git a/tests/unit/bridge/test_list_remote_agents.py b/tests/unit/bridge/test_list_remote_agents.py index a479ca8ede..cd11b447d2 100644 --- a/tests/unit/bridge/test_list_remote_agents.py +++ b/tests/unit/bridge/test_list_remote_agents.py @@ -103,6 +103,7 @@ def json(self) -> list[dict[str, Any]]: "name": "别人共享", "is_owner": False, "is_shared": True, + "default_model": "prov/shared-default", }, ] @@ -113,6 +114,7 @@ def json(self) -> list[dict[str, Any]]: assert by_remote["mine"]["is_shared"] is False assert by_remote["shared"]["is_owner"] is False assert by_remote["shared"]["is_shared"] is True + assert by_remote["shared"]["default_model"] == "prov/shared-default" assert by_remote["mine"]["state"] == "stopped" assert by_remote["shared"]["state"] == "stopped" diff --git a/tests/unit/bridge/test_peer_auth.py b/tests/unit/bridge/test_peer_auth.py index 29d5d68692..9f12139165 100644 --- a/tests/unit/bridge/test_peer_auth.py +++ b/tests/unit/bridge/test_peer_auth.py @@ -2,11 +2,18 @@ from __future__ import annotations +import asyncio +from unittest.mock import AsyncMock, MagicMock + import pytest +from octop.i18n import error_message from octop.infra.bridge.manager import ( _annotate_bridge_dial_error, _should_refresh_peer_token, + bridge_failure_from_dial, + dial_error_note, + error_from_dial_note, ) from octop.infra.bridge.peer_auth import ( is_self_peer_url, @@ -58,6 +65,102 @@ def __init__(self) -> None: assert "needs Octop with /api/bridge/ws" not in text +class _Close: + def __init__(self, code: int, reason: str) -> None: + self.code = code + self.reason = reason + + def __str__(self) -> str: + return f"{self.code} (private use) {self.reason}" + + +class _Closed(Exception): + def __init__(self, code: int, reason: str) -> None: + frame = _Close(code, reason) + self.rcvd = frame + self.sent = frame + super().__init__(f"received {frame}; then sent {frame}") + + +def test_dial_close_owned_by_another_user_is_readable() -> None: + exc = _Closed(4003, "connection owned by another user") + err = bridge_failure_from_dial(exc) + assert err.code == ErrorCode.BRIDGE_PEER_CONNECTION_OWNED + assert "4003" not in dial_error_note(exc) + assert dial_error_note(exc) == "octop:apiErrors.BRIDGE_PEER_CONNECTION_OWNED" + + +def test_dial_close_permission_required_is_not_admin_only() -> None: + exc = _Closed(4003, "permission required") + err = bridge_failure_from_dial(exc) + assert err.code == ErrorCode.BRIDGE_PEER_FORBIDDEN + text = error_message(err.code.value, "zh") + assert "权限" in text + assert "管理员" in text + + +def test_connection_limit_note_keeps_the_limit() -> None: + exc = _Closed(4008, "connection limit") + note = dial_error_note(exc) + err = error_from_dial_note(note) + assert err is not None + assert err.code == ErrorCode.BRIDGE_CONNECTION_LIMIT + assert err.details["limit"] == 10 + text = error_message(err.code.value, "zh", **err.details) + assert "10" in text + assert "{limit}" not in text + + +@pytest.mark.asyncio +async def test_permanent_dial_stops_without_reconnect_backoff() -> None: + from octop.infra.bridge.manager import BridgeManager + from octop.infra.db.repos.bridge_connections import BridgeConnectionRow + + row = BridgeConnectionRow( + pk=1, + connection_id="cid1", + owner_user_id=1, + peer_base_url="https://peer.example", + peer_username="alice", + display_name="云端", + notes=None, + icon_name=None, + credential_blob=b"enc", + access_token_blob=b"tok", + token_expires_at=None, + status="connecting", + last_error=None, + last_seen_at=None, + auto_reconnect=True, + created_at=1, + updated_at=1, + ) + repo = MagicMock() + repo.get.return_value = row + mgr = BridgeManager( + bridge_repo=repo, + secret_repo=MagicMock(), + user_repo=MagicMock(), + advertise_base_url="http://local.test", + ) + mgr._ensure_peer_token = AsyncMock(return_value="tok") # type: ignore[method-assign] + + async def reject(*_args: object, **_kwargs: object) -> None: + raise _Closed(4003, "permission required") + + mgr._run_outbound_client = reject # type: ignore[method-assign] + started = asyncio.get_running_loop().time() + await asyncio.wait_for(mgr._outbound_supervisor("cid1"), timeout=1.0) + assert asyncio.get_running_loop().time() - started < 0.5 + assert "cid1" in mgr._user_stopped + repo.set_auto_reconnect.assert_not_called() + repo.update_status.assert_any_call( + "cid1", + status="error", + last_error="octop:apiErrors.BRIDGE_PEER_FORBIDDEN", + ) + + def test_is_self_peer_url_matches_loopback_aliases() -> None: assert is_self_peer_url("http://localhost:8787", "http://127.0.0.1:8787") assert not is_self_peer_url("https://peer.example", "http://127.0.0.1:8787") diff --git a/tests/unit/bridge/test_session_liveness.py b/tests/unit/bridge/test_session_liveness.py index 021ca0d7fb..83d9ad4ab1 100644 --- a/tests/unit/bridge/test_session_liveness.py +++ b/tests/unit/bridge/test_session_liveness.py @@ -397,9 +397,12 @@ async def send_json(payload: dict[str, Any]) -> None: sess.send_json = send_json # type: ignore[method-assign] frames: list[dict[str, Any]] = [] + forwarded = asyncio.Event() async def on_frame(frame: dict[str, Any]) -> None: frames.append(frame) + if len(frames) >= 2: + forwarded.set() task = asyncio.create_task( mgr.relay_user_listen( @@ -411,7 +414,7 @@ async def on_frame(frame: dict[str, Any]) -> None: ) ) await asyncio.wait_for(started.wait(), timeout=1.0) - await asyncio.sleep(0.05) + await asyncio.wait_for(forwarded.wait(), timeout=1.0) task.cancel() with pytest.raises(asyncio.CancelledError): await task diff --git a/tests/unit/db/test_db_pool.py b/tests/unit/db/test_db_pool.py index 4a4e03c6f0..e23a7e9e38 100644 --- a/tests/unit/db/test_db_pool.py +++ b/tests/unit/db/test_db_pool.py @@ -21,6 +21,28 @@ def db(tmp_path: Path) -> SqlitePool: return pool +def test_close_waits_for_in_flight_query(tmp_path: Path) -> None: + pool = SqlitePool(tmp_path / "octop.db") + entered = threading.Event() + result: dict[str, int] = {} + + def query() -> None: + with pool.connect() as conn: + entered.set() + time.sleep(0.2) + result["row"] = int(conn.execute("SELECT 1").fetchone()[0]) + + worker = threading.Thread(target=query) + worker.start() + assert entered.wait(2) + pool.close() + worker.join(2) + assert not worker.is_alive() + assert result["row"] == 1 + with pytest.raises(sqlite3.ProgrammingError), pool.connect(): + pass + + def test_db_pool_creates_file(tmp_path: Path): db_path = tmp_path / "octop.db" SqlitePool(db_path) From e1962d49a0c753b717c9241aa3689585a556e294 Mon Sep 17 00:00:00 2001 From: Jubaoliang Date: Sat, 7 Nov 2026 15:59:29 +0800 Subject: [PATCH 06/20] fix: close the open bug batch and mark pre-market experts as featured (#2878) Keep pauses, themes, citations, backups, and chat chrome from colliding, and show the templates that shipped before the expert market as the default featured set. --- CHANGELOG.md | 7 ++ dashboard/src/api/modules/expertMarket.ts | 2 + dashboard/src/components/AuthGuard.tsx | 6 ++ .../components/RailEdgeControl.module.less | 6 ++ dashboard/src/components/RailEdgeControl.tsx | 7 ++ dashboard/src/context/ThemeContext.tsx | 33 ++++++++- dashboard/src/hooks/useAuthImageSrc.test.ts | 38 +++++++++++ dashboard/src/hooks/useAuthImageSrc.ts | 34 +++++++--- dashboard/src/locales/en.json | 2 + dashboard/src/locales/zh.json | 2 + .../pages/Agent/ACP/components/ACPCard.tsx | 17 +++-- .../Workspace/components/FilePreview.tsx | 3 +- .../components/htmlPreviewDoc.test.ts | 21 ++++++ .../Workspace/components/htmlPreviewDoc.ts | 19 ++++++ .../src/pages/Chat/chatAgentCard.partial.less | 6 ++ .../Chat/chatThemeOverrides.partial.less | 7 ++ .../Chat/components/AgentUnreadBadge.tsx | 28 ++++++++ .../Chat/components/ChatSidebarPanel.tsx | 1 + .../components/MinimalAgentSessionNav.tsx | 22 +++--- .../src/pages/Chat/components/SessionList.tsx | 36 ++++++---- dashboard/src/pages/Chat/hooks/useSessions.ts | 3 + .../Chat/utils/openUnreadSession.test.ts | 44 ++++++++++++ .../src/pages/Chat/utils/openUnreadSession.ts | 29 ++++++++ .../Experts/components/ExpertMarketTab.tsx | 38 +++++++++-- .../Experts/components/marketFeatured.test.ts | 31 +++++++++ .../Experts/components/marketFeatured.ts | 13 ++++ dashboard/src/pages/Experts/index.module.less | 15 ++++ .../src/styles/appearanceStorage.test.ts | 32 +++++++++ dashboard/src/styles/appearanceStorage.ts | 57 ++++++++++++++-- src/octop/api/middleware/bridge_proxy.py | 19 +++++- src/octop/api/routers/chat/history.py | 2 + src/octop/api/routers/experts.py | 19 +++++- src/octop/api/routers/providers.py | 5 ++ src/octop/cli/commands/backup.py | 5 +- src/octop/infra/agents/experts/catalog.py | 36 ++++++++++ src/octop/infra/agents/manager.py | 24 +++++-- src/octop/infra/agents/workspace/dir.py | 12 ++++ src/octop/infra/backup/store.py | 22 ++++-- src/octop/infra/gateway/hitl/store.py | 12 ++++ src/octop/infra/knowledge/retrieve.py | 4 +- src/octop/infra/utils/env_file.py | 19 +++++- tests/integration/test_providers_api.py | 12 ++++ tests/unit/agents/test_agent_manager.py | 28 ++++++++ .../unit/agents/test_agent_skill_packages.py | 11 +++ tests/unit/agents/test_expert_catalog.py | 13 ++++ tests/unit/api/test_chat_history.py | 3 + tests/unit/backup/test_move_file_replace.py | 24 +++++++ tests/unit/bridge/test_bridge_proxy_local.py | 68 +++++++++++++++++++ tests/unit/db/test_db_pool.py | 25 +++++++ tests/unit/gateway/test_hitl_channel.py | 27 ++++++++ tests/unit/knowledge/test_retrieve.py | 18 +++++ tests/unit/test_env_file.py | 10 +++ 52 files changed, 900 insertions(+), 77 deletions(-) create mode 100644 dashboard/src/hooks/useAuthImageSrc.test.ts create mode 100644 dashboard/src/pages/Agent/Workspace/components/htmlPreviewDoc.test.ts create mode 100644 dashboard/src/pages/Agent/Workspace/components/htmlPreviewDoc.ts create mode 100644 dashboard/src/pages/Chat/components/AgentUnreadBadge.tsx create mode 100644 dashboard/src/pages/Chat/utils/openUnreadSession.test.ts create mode 100644 dashboard/src/pages/Chat/utils/openUnreadSession.ts create mode 100644 dashboard/src/pages/Experts/components/marketFeatured.test.ts create mode 100644 dashboard/src/pages/Experts/components/marketFeatured.ts create mode 100644 tests/unit/backup/test_move_file_replace.py diff --git a/CHANGELOG.md b/CHANGELOG.md index bccb36a6d3..52fbb1d050 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,10 +6,17 @@ ## [Unreleased] +### 新增 +- 专家市场默认打开「精选」,用书签标出接入市场前随安装包提供的 22 个专家模板 + ### 修复 - 关机时会等正在进行的数据库查询结束再关闭连接,避免 Windows 上测试进程被访问冲突打断 - 模型池里的优先模型可以取消,并且不再显示为聊天框里的选中模型。聊天框只显示专家默认模型或这场对话的手选模型 - 添加云端协同时,权限不足、连接被占用、连到本机或达到条数上限会立刻显示可读错误,不再重试原始关闭帧 +- 同一专家的不同会话不再互相取消正在等待的提问。侧栏展开时可以拖右缘改宽度 +- 重名的模型供应商返回冲突,不再报服务器错误。知识库引用只包含实际写进上下文的文档 +- 备份落到另一块磁盘时不再丢文件。两个账号在同一浏览器里不再共用主题 +- 未读数字可以打开对应会话。自定义 ACP 显示自己的名称,HTML 预览里的页内链接留在预览框内 ## [1.0.3b4] - 2026-11-06 diff --git a/dashboard/src/api/modules/expertMarket.ts b/dashboard/src/api/modules/expertMarket.ts index 1e2b701129..44d73ace36 100644 --- a/dashboard/src/api/modules/expertMarket.ts +++ b/dashboard/src/api/modules/expertMarket.ts @@ -26,6 +26,8 @@ export interface MarketExpert { skill_slugs?: string[]; skill_count?: number; source?: string; + /** True when this card is a template that ships with Octop. */ + featured?: boolean; content?: LocalizedText; quick_prompts?: ExpertMarketQuickPrompt[]; task_examples?: { zh?: string[]; en?: string[] } | null; diff --git a/dashboard/src/components/AuthGuard.tsx b/dashboard/src/components/AuthGuard.tsx index 4a4c3af4d9..2d2e508cfe 100644 --- a/dashboard/src/components/AuthGuard.tsx +++ b/dashboard/src/components/AuthGuard.tsx @@ -6,6 +6,7 @@ import { authApi, type OctopUser } from "../api/modules/auth"; import { applyUserLocale } from "../utils/locale"; import { isNetworkFetchError } from "../utils/networkError"; import { CurrentUserProvider } from "../hooks/useCurrentUser"; +import { useTheme } from "../context/ThemeContext"; import BootOfflinePanel from "./BootOfflinePanel"; interface AuthGuardProps { @@ -42,6 +43,11 @@ export default function AuthGuard({ children }: AuthGuardProps) { const [checking, setChecking] = useState(true); const [authed, setAuthed] = useState(false); const [user, setUser] = useState(null); + const { bindUser } = useTheme(); + useEffect(() => { + bindUser(user?.id ?? null); + return () => bindUser(null); + }, [user?.id, bindUser]); const [offline, setOffline] = useState(false); const [retryKey, setRetryKey] = useState(0); diff --git a/dashboard/src/components/RailEdgeControl.module.less b/dashboard/src/components/RailEdgeControl.module.less index 2bc3d47587..cb00a1a8de 100644 --- a/dashboard/src/components/RailEdgeControl.module.less +++ b/dashboard/src/components/RailEdgeControl.module.less @@ -30,6 +30,12 @@ width: 12px; } +.edgePassThrough { + /* The rail itself must not cover a resize handle. The collapse button + stays pointer-events: none until a hover rule reveals it. */ + pointer-events: none; +} + .line { position: absolute; top: 0; diff --git a/dashboard/src/components/RailEdgeControl.tsx b/dashboard/src/components/RailEdgeControl.tsx index 652b326850..1cfea31021 100644 --- a/dashboard/src/components/RailEdgeControl.tsx +++ b/dashboard/src/components/RailEdgeControl.tsx @@ -25,6 +25,11 @@ interface RailEdgeControlProps { * ``before`` / ``after`` sit on either side when two rails share one line. */ placement?: "center" | "before" | "after"; + /** + * Let pointer events fall through the rail so a resize handle underneath + * stays usable. The collapse button itself still receives clicks. + */ + passThrough?: boolean; } /** @@ -39,6 +44,7 @@ export default function RailEdgeControl({ className, showLine = true, placement = "center", + passThrough = false, }: RailEdgeControlProps) { const { t } = useTranslation(); const ariaLabel = @@ -53,6 +59,7 @@ export default function RailEdgeControl({ styles.edge, side === "start" ? styles.edgeStart : styles.edgeEnd, !expanded && styles.edgeCollapsed, + passThrough && styles.edgePassThrough, className, )} > diff --git a/dashboard/src/context/ThemeContext.tsx b/dashboard/src/context/ThemeContext.tsx index 7d6c02ac15..a79c2d048f 100644 --- a/dashboard/src/context/ThemeContext.tsx +++ b/dashboard/src/context/ThemeContext.tsx @@ -4,10 +4,13 @@ import { useState, useEffect, useCallback, + useRef, type ReactNode, } from "react"; import { + defaultAppearance, loadAppearanceOnBoot, + readStoredAppearance, writeStoredAppearance, type ThemePreference, } from "../styles/appearanceStorage"; @@ -43,6 +46,8 @@ interface ThemeContextValue { toggle: () => void; /** Whether the current mode is considered "dark" for Ant Design */ isDark: boolean; + /** Load the signed-in user's palette. ``null`` restores the shared boot theme. */ + bindUser: (userId: number | null) => void; } const ThemeContext = createContext({ @@ -55,6 +60,7 @@ const ThemeContext = createContext({ setCustomColor: () => {}, toggle: () => {}, isDark: false, + bindUser: () => {}, }); function resolveMode(pref: ThemePreference): ThemeMode { @@ -91,6 +97,27 @@ export function ThemeProvider({ children }: { children: ReactNode }) { ); const [mode, setMode] = useState(() => resolveMode(preference)); + const userIdRef = useRef(null); + + const bindUser = useCallback((userId: number | null) => { + if (userIdRef.current === userId) return; + const previous = userIdRef.current; + userIdRef.current = userId; + if (userId == null) { + if (previous != null) { + const defaults = defaultAppearance(); + setPreferenceState(defaults.preference); + setPaletteState(defaults.palette); + setCustomColorState(defaults.customColor ?? ""); + writeStoredAppearance(defaults, null); + } + return; + } + const stored = readStoredAppearance(userId); + setPreferenceState(stored.preference); + setPaletteState(stored.palette); + setCustomColorState(stored.customColor ?? ""); + }, []); // Listen for system color scheme changes when preference is "system" useEffect(() => { @@ -111,7 +138,10 @@ export function ThemeProvider({ children }: { children: ReactNode }) { // Persist preference + palette together (mode is derived, not stored) useEffect(() => { - writeStoredAppearance({ preference, palette, customColor }); + writeStoredAppearance( + { preference, palette, customColor }, + userIdRef.current, + ); document.documentElement.setAttribute("data-palette", palette); }, [preference, palette, customColor]); @@ -185,6 +215,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) { setCustomColor, toggle, isDark: isDarkMode(mode), + bindUser, }} > {children} diff --git a/dashboard/src/hooks/useAuthImageSrc.test.ts b/dashboard/src/hooks/useAuthImageSrc.test.ts new file mode 100644 index 0000000000..95f0ed890a --- /dev/null +++ b/dashboard/src/hooks/useAuthImageSrc.test.ts @@ -0,0 +1,38 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +vi.mock("../api/request", () => ({ + requestBlob: vi.fn(async () => new Blob(["img"], { type: "image/png" })), +})); + +import { requestBlob } from "../api/request"; +import { acquireAuthImageSrc, releaseAuthImageSrc } from "./useAuthImageSrc"; + +afterEach(() => { + vi.mocked(requestBlob).mockClear(); +}); + +describe("auth image cache", () => { + it("keeps an idle object URL so the next mount does not refetch", async () => { + const created: string[] = []; + const revoked: string[] = []; + vi.stubGlobal("URL", { + createObjectURL: (blob: Blob) => { + const url = `blob:${created.length}:${blob.size}`; + created.push(url); + return url; + }, + revokeObjectURL: (url: string) => { + revoked.push(url); + }, + }); + + const first = await acquireAuthImageSrc("/api/avatar/keep"); + releaseAuthImageSrc("/api/avatar/keep"); + const second = await acquireAuthImageSrc("/api/avatar/keep"); + releaseAuthImageSrc("/api/avatar/keep"); + + expect(second).toBe(first); + expect(requestBlob).toHaveBeenCalledTimes(1); + expect(revoked).not.toContain(first); + }); +}); diff --git a/dashboard/src/hooks/useAuthImageSrc.ts b/dashboard/src/hooks/useAuthImageSrc.ts index 26a39224fe..27127987c5 100644 --- a/dashboard/src/hooks/useAuthImageSrc.ts +++ b/dashboard/src/hooks/useAuthImageSrc.ts @@ -16,8 +16,29 @@ type AuthImageCacheEntry = { inflight?: Promise; }; +const AUTH_IMAGE_CACHE_LIMIT = 32; const authImageCache = new Map(); +function touchAuthImage(key: string, entry: AuthImageCacheEntry): void { + authImageCache.delete(key); + authImageCache.set(key, entry); +} + +function evictIdleAuthImages(): void { + let idle = 0; + for (const entry of authImageCache.values()) { + if (entry.refs <= 0 && !entry.inflight) idle += 1; + } + if (idle <= AUTH_IMAGE_CACHE_LIMIT) return; + for (const [key, entry] of authImageCache) { + if (idle <= AUTH_IMAGE_CACHE_LIMIT) break; + if (entry.refs > 0 || entry.inflight) continue; + if (entry.objectUrl) URL.revokeObjectURL(entry.objectUrl); + authImageCache.delete(key); + idle -= 1; + } +} + function apiPathFromUrl(url: string): string { if (url.startsWith("http")) { const parsed = new URL(url); @@ -54,6 +75,7 @@ export function acquireAuthImageSrc( } entry.refs += 1; if (entry.objectUrl) { + touchAuthImage(key, entry); return Promise.resolve(entry.objectUrl); } if (!entry.inflight) { @@ -63,10 +85,8 @@ export function acquireAuthImageSrc( const objectUrl = URL.createObjectURL(blob); pending.objectUrl = objectUrl; pending.inflight = undefined; - if (pending.refs <= 0) { - URL.revokeObjectURL(objectUrl); - authImageCache.delete(key); - } + touchAuthImage(key, pending); + evictIdleAuthImages(); return objectUrl; }) .catch((err: unknown) => { @@ -89,10 +109,8 @@ export function releaseAuthImageSrc(url: string, filename?: string): void { if (!entry) return; entry.refs -= 1; if (entry.refs > 0 || entry.inflight) return; - if (entry.objectUrl) { - URL.revokeObjectURL(entry.objectUrl); - } - authImageCache.delete(key); + touchAuthImage(key, entry); + evictIdleAuthImages(); } function releaseHeld(held: HeldAuthImage | undefined): void { diff --git a/dashboard/src/locales/en.json b/dashboard/src/locales/en.json index cb17b51cfb..95a31b167e 100644 --- a/dashboard/src/locales/en.json +++ b/dashboard/src/locales/en.json @@ -1000,6 +1000,8 @@ "marketScenePrev": "Scroll left", "marketSceneNext": "Scroll right", "sceneAll": "All", + "sceneFeatured": "Featured", + "featuredHint": "Expert templates that shipped with Octop before the expert market", "scenes": { "academic": "Academic", "content-creation": "Content Creation", diff --git a/dashboard/src/locales/zh.json b/dashboard/src/locales/zh.json index 3632f17f4d..622a434a0f 100644 --- a/dashboard/src/locales/zh.json +++ b/dashboard/src/locales/zh.json @@ -1000,6 +1000,8 @@ "marketScenePrev": "向左滚动", "marketSceneNext": "向右滚动", "sceneAll": "全部", + "sceneFeatured": "精选", + "featuredHint": "接入专家市场之前,随 Octop 一起提供的专家模板", "scenes": { "academic": "学术", "content-creation": "内容创作", diff --git a/dashboard/src/pages/Agent/ACP/components/ACPCard.tsx b/dashboard/src/pages/Agent/ACP/components/ACPCard.tsx index 5fe2edddab..09665cdc94 100644 --- a/dashboard/src/pages/Agent/ACP/components/ACPCard.tsx +++ b/dashboard/src/pages/Agent/ACP/components/ACPCard.tsx @@ -3,7 +3,12 @@ import { CheckCircle, Plug } from "lucide-react"; import { useTranslation } from "react-i18next"; import cx from "classnames"; import type { ACPRunnerConfig } from "../../../../api/types/acp"; -import { runnerIcon, runnerIntroKey, runnerLabelKey } from "../constants"; +import { + isBuiltinRunner, + runnerIcon, + runnerIntroKey, + runnerLabelKey, +} from "../constants"; import styles from "../../Channels/index.module.less"; import acpStyles from "../index.module.less"; @@ -36,11 +41,11 @@ export function ACPCard({ onToggleEnabled, }: ACPCardProps) { const { t } = useTranslation(); - const labelKey = runnerLabelKey(runnerKey); - const label = labelKey ? t(labelKey) : runnerKey; - const introKey = runnerIntroKey(runnerKey); - const intro = introKey - ? t(introKey) + const label = isBuiltinRunner(runnerKey) + ? t(runnerLabelKey(runnerKey)) + : runnerKey; + const intro = isBuiltinRunner(runnerKey) + ? t(runnerIntroKey(runnerKey)) : t("acp.intro_custom", { command: config.command || t("acp.notSet"), }); diff --git a/dashboard/src/pages/Agent/Workspace/components/FilePreview.tsx b/dashboard/src/pages/Agent/Workspace/components/FilePreview.tsx index ba63303ca1..d6167f5d22 100644 --- a/dashboard/src/pages/Agent/Workspace/components/FilePreview.tsx +++ b/dashboard/src/pages/Agent/Workspace/components/FilePreview.tsx @@ -2,6 +2,7 @@ import type { RefObject } from "react"; import { useEffect, useRef, useState } from "react"; import Markdown from "../../../../components/Markdown/LazyMarkdown"; import styles from "../index.module.less"; +import { isolateHtmlPreview } from "./htmlPreviewDoc"; /** * Rich preview kinds — documents that benefit from rendered view. @@ -122,7 +123,7 @@ export default function FilePreview({