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 1/8] 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 2/8] 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 3/8] 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 4/8] 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({
);
diff --git a/dashboard/src/pages/Agent/Workspace/components/htmlPreviewDoc.test.ts b/dashboard/src/pages/Agent/Workspace/components/htmlPreviewDoc.test.ts
new file mode 100644
index 0000000000..270182893c
--- /dev/null
+++ b/dashboard/src/pages/Agent/Workspace/components/htmlPreviewDoc.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+import { isolateHtmlPreview } from "./htmlPreviewDoc";
+
+describe("isolateHtmlPreview", () => {
+ it("injects the anchor guard into an existing head", () => {
+ const doc = isolateHtmlPreview(
+ "x",
+ );
+ expect(doc).toContain('data-octop-preview-guard="1"');
+ expect(doc).toContain('');
+ expect(doc.indexOf("data-octop-preview-guard")).toBeLessThan(
+ doc.indexOf(""),
+ );
+ });
+
+ it("wraps a fragment and does not inject twice", () => {
+ const once = isolateHtmlPreview('top');
+ expect(once.startsWith("")).toBe(true);
+ expect(isolateHtmlPreview(once)).toBe(once);
+ });
+});
diff --git a/dashboard/src/pages/Agent/Workspace/components/htmlPreviewDoc.ts b/dashboard/src/pages/Agent/Workspace/components/htmlPreviewDoc.ts
new file mode 100644
index 0000000000..110683e0a4
--- /dev/null
+++ b/dashboard/src/pages/Agent/Workspace/components/htmlPreviewDoc.ts
@@ -0,0 +1,19 @@
+const GUARD_MARKER = 'data-octop-preview-guard="1"';
+
+const GUARD = ``;
+
+/** Keep in-page anchors inside the sandboxed preview document. */
+export function isolateHtmlPreview(content: string): string {
+ if (content.includes(GUARD_MARKER)) return content;
+ const head = content.match(/]*>/i);
+ if (head && head.index != null) {
+ const at = head.index + head[0].length;
+ return content.slice(0, at) + GUARD + content.slice(at);
+ }
+ const html = content.match(/]*>/i);
+ if (html && html.index != null) {
+ const at = html.index + html[0].length;
+ return content.slice(0, at) + `${GUARD}` + content.slice(at);
+ }
+ return `${GUARD}${content}`;
+}
diff --git a/dashboard/src/pages/Chat/chatAgentCard.partial.less b/dashboard/src/pages/Chat/chatAgentCard.partial.less
index 305124db2b..af1e689c2e 100644
--- a/dashboard/src/pages/Chat/chatAgentCard.partial.less
+++ b/dashboard/src/pages/Chat/chatAgentCard.partial.less
@@ -269,6 +269,12 @@
display: inline-flex;
align-items: center;
justify-content: center;
+
+ &:is(button) {
+ border: none;
+ cursor: pointer;
+ font-family: inherit;
+ }
}
.sessionRowUnread {
diff --git a/dashboard/src/pages/Chat/chatThemeOverrides.partial.less b/dashboard/src/pages/Chat/chatThemeOverrides.partial.less
index 2d97eef324..0a40f2f2fa 100644
--- a/dashboard/src/pages/Chat/chatThemeOverrides.partial.less
+++ b/dashboard/src/pages/Chat/chatThemeOverrides.partial.less
@@ -31,6 +31,13 @@
right: -8px;
}
+/* The open rail is click-through so the resize handle stays reachable.
+ Reveal the collapse button from the sidebar hover instead. */
+.sidebarWrapper:hover .chatRailEdgeOpen button {
+ opacity: 1;
+ pointer-events: auto;
+}
+
.chatRailEdgeClosed {
/* Align with MainLayout nav RailEdgeControl (edgeEnd: right -8px / width 16px). */
left: -8px !important;
diff --git a/dashboard/src/pages/Chat/components/AgentUnreadBadge.tsx b/dashboard/src/pages/Chat/components/AgentUnreadBadge.tsx
new file mode 100644
index 0000000000..92729104df
--- /dev/null
+++ b/dashboard/src/pages/Chat/components/AgentUnreadBadge.tsx
@@ -0,0 +1,28 @@
+import { useTranslation } from "react-i18next";
+import styles from "../index.module.less";
+
+/** Clickable unread count. Opens that expert's unread thread. */
+export default function AgentUnreadBadge({
+ count,
+ onOpen,
+}: {
+ count: number;
+ onOpen: () => void;
+}) {
+ const { t } = useTranslation();
+ if (!count || count <= 0) return null;
+ const text = count > 99 ? "99+" : count;
+ return (
+
+ );
+}
diff --git a/dashboard/src/pages/Chat/components/ChatSidebarPanel.tsx b/dashboard/src/pages/Chat/components/ChatSidebarPanel.tsx
index 25fd4a629f..b3452f0963 100644
--- a/dashboard/src/pages/Chat/components/ChatSidebarPanel.tsx
+++ b/dashboard/src/pages/Chat/components/ChatSidebarPanel.tsx
@@ -187,6 +187,7 @@ export default function ChatSidebarPanel({
/* Collapsed: share the nav rail divider — avoid a second gapped line. */
showLine={sidebarOpen}
placement={sidebarOpen ? "center" : "after"}
+ passThrough={sidebarOpen}
className={
sidebarOpen ? styles.chatRailEdgeOpen : styles.chatRailEdgeClosed
}
diff --git a/dashboard/src/pages/Chat/components/MinimalAgentSessionNav.tsx b/dashboard/src/pages/Chat/components/MinimalAgentSessionNav.tsx
index 11721bc100..c59befbe3a 100644
--- a/dashboard/src/pages/Chat/components/MinimalAgentSessionNav.tsx
+++ b/dashboard/src/pages/Chat/components/MinimalAgentSessionNav.tsx
@@ -24,6 +24,7 @@ import {
import { isAgentChatReady } from "../../../utils/agentError";
import { isImeComposing } from "../../../utils/ime";
import { sortSessions, toSession, type Session } from "../hooks/useSessions";
+import { openAgentUnread } from "../utils/openUnreadSession";
import { formatThreadTitle } from "../utils/threadTitle";
import { onSessionEvent } from "../hooks/chatStore";
import { useExpertSessionCatalog } from "../hooks/useExpertSessionCatalog";
@@ -37,6 +38,7 @@ import {
matchesChatNavScope,
type ChatNavScope,
} from "../utils/chatNavScope";
+import AgentUnreadBadge from "./AgentUnreadBadge";
import ChatNavScopeTabs, { ChatNavScopeEmpty } from "./ChatNavScopeTabs";
import {
expertVisibleInNavSearch,
@@ -121,19 +123,6 @@ interface MinimalAgentSessionNavProps {
activeForkDisabledHint?: string;
}
-function AgentUnreadBadge({ count }: { count: number }) {
- const { t } = useTranslation();
- if (!count || count <= 0) return null;
- return (
-
- {count > 99 ? "99+" : count}
-
- );
-}
-
const PreviewSessionRow = memo(function PreviewSessionRow({
session,
isActive,
@@ -794,8 +783,13 @@ export default function MinimalAgentSessionNav({
-
+ {
+ void openAgentUnread(agent.agent_id, list, onSelect);
+ }}
+ />
- {count > 99 ? "99+" : count}
-
- );
-}
+import { openAgentUnread } from "../utils/openUnreadSession";
interface SessionItemProps {
session: Session;
@@ -356,7 +345,12 @@ function ActiveAgentCard({
-
+ {
+ void openAgentUnread(agent.agent_id, sessions, onSelect);
+ }}
+ />
{onTogglePin ? (
void;
pinned?: boolean;
onTogglePin?: () => void;
+ onOpenUnread: () => void;
}
function InactiveAgentRow({
@@ -449,6 +444,7 @@ function InactiveAgentRow({
onUnhide,
pinned = false,
onTogglePin,
+ onOpenUnread,
}: AgentRowProps) {
const accent = agent.color || "#6366f1";
@@ -488,7 +484,10 @@ function InactiveAgentRow({
-
+
{onNewChat && onTogglePin ? (
unhide(agent.agent_id) : undefined}
pinned={isPinned(agent.agent_id)}
onTogglePin={() => togglePin(agent.agent_id)}
+ onOpenUnread={() => {
+ void openAgentUnread(
+ agent.agent_id,
+ sessionsFor(agent.agent_id),
+ onSelect,
+ );
+ }}
/>
);
};
diff --git a/dashboard/src/pages/Chat/hooks/useSessions.ts b/dashboard/src/pages/Chat/hooks/useSessions.ts
index e429da121c..e2586961bb 100644
--- a/dashboard/src/pages/Chat/hooks/useSessions.ts
+++ b/dashboard/src/pages/Chat/hooks/useSessions.ts
@@ -30,6 +30,7 @@ export interface Session {
artifacts?: ThreadArtifact[];
turnActive?: boolean;
awaitingUser?: boolean;
+ unreadCount?: number;
}
/** Result of probing whether a thread exists for the current agent. */
@@ -55,6 +56,7 @@ export function toSession(row: {
agent_id?: string | null;
turn_active?: boolean;
awaiting_user?: boolean;
+ unread_count?: number;
}): Session {
const hasActivity =
Boolean(row.has_messages) || Boolean(row.title) || row.last_active > 0;
@@ -89,6 +91,7 @@ export function toSession(row: {
),
turnActive: Boolean(row.turn_active),
awaitingUser: Boolean(row.awaiting_user),
+ unreadCount: row.unread_count ?? 0,
};
}
diff --git a/dashboard/src/pages/Chat/utils/openUnreadSession.test.ts b/dashboard/src/pages/Chat/utils/openUnreadSession.test.ts
new file mode 100644
index 0000000000..07aa0d47bb
--- /dev/null
+++ b/dashboard/src/pages/Chat/utils/openUnreadSession.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from "vitest";
+import { sortSessions, type Session } from "../hooks/useSessions";
+import { pickUnreadSession } from "./openUnreadSession";
+
+function session(
+ partial: Pick &
+ Partial>,
+): Session {
+ return {
+ name: partial.id,
+ threadId: partial.id,
+ channelType: "dashboard",
+ updatedAt: null,
+ ...partial,
+ };
+}
+
+describe("pickUnreadSession", () => {
+ it("follows list order, so a pinned unread comes before a newer one", () => {
+ const sessions = sortSessions([
+ session({
+ id: "new",
+ unreadCount: 2,
+ pinned: false,
+ updatedAt: "2026-11-06T12:00:00.000Z",
+ }),
+ session({
+ id: "pinned",
+ unreadCount: 1,
+ pinned: true,
+ updatedAt: "2026-11-01T12:00:00.000Z",
+ }),
+ session({ id: "read", unreadCount: 0, pinned: false }),
+ ]);
+
+ expect(pickUnreadSession(sessions)?.id).toBe("pinned");
+ });
+
+ it("returns null when nothing is unread", () => {
+ expect(pickUnreadSession([session({ id: "read", unreadCount: 0 })])).toBe(
+ null,
+ );
+ });
+});
diff --git a/dashboard/src/pages/Chat/utils/openUnreadSession.ts b/dashboard/src/pages/Chat/utils/openUnreadSession.ts
new file mode 100644
index 0000000000..1154d6db13
--- /dev/null
+++ b/dashboard/src/pages/Chat/utils/openUnreadSession.ts
@@ -0,0 +1,29 @@
+import { octopThreadsApi } from "../../../api/modules/octopThreads";
+import { sortSessions, toSession, type Session } from "../hooks/useSessions";
+
+/** First unread row in list order. Callers that sort with ``sortSessions`` put pinned threads first. */
+export function pickUnreadSession(
+ sessions: readonly Session[],
+): Session | null {
+ return sessions.find((session) => (session.unreadCount ?? 0) > 0) ?? null;
+}
+
+/** Open the first unread thread in list order, fetching the list if needed. */
+export async function openAgentUnread(
+ agentId: string,
+ sessions: readonly Session[],
+ onSelect: (sessionId: string, agentId: string) => void,
+): Promise {
+ const local = pickUnreadSession(sessions);
+ if (local) {
+ onSelect(local.id, agentId);
+ return;
+ }
+ try {
+ const rows = await octopThreadsApi.list(agentId, 50);
+ const fetched = pickUnreadSession(sortSessions(rows.map(toSession)));
+ if (fetched) onSelect(fetched.id, agentId);
+ } catch {
+ // Leave the current selection when the thread list cannot be loaded.
+ }
+}
diff --git a/dashboard/src/pages/Experts/components/ExpertMarketTab.tsx b/dashboard/src/pages/Experts/components/ExpertMarketTab.tsx
index 9dec449aa2..052dbd5e0e 100644
--- a/dashboard/src/pages/Experts/components/ExpertMarketTab.tsx
+++ b/dashboard/src/pages/Experts/components/ExpertMarketTab.tsx
@@ -1,9 +1,10 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { CSSProperties } from "react";
-import { Button, Drawer, Input, Result, Spin, Tag } from "antd";
+import { Button, Drawer, Input, Result, Spin, Tag, Tooltip } from "antd";
import { message } from "@/utils/antdMessage";
import {
+ Bookmark,
CheckCircle,
Download,
Layers,
@@ -35,6 +36,7 @@ import {
splitMarkdownFrontmatter,
} from "../../../utils/markdown";
import { iconForName } from "./iconForName";
+import { MARKET_SCENE_FEATURED, visibleMarketExperts } from "./marketFeatured";
import styles from "../index.module.less";
interface ExpertMarketTabProps {
@@ -93,7 +95,7 @@ export default function ExpertMarketTab({
const { t } = useTranslation();
const [items, setItems] = useState([]);
const [scenes, setScenes] = useState([]);
- const [activeScene, setActiveScene] = useState(SCENE_ALL);
+ const [activeScene, setActiveScene] = useState(MARKET_SCENE_FEATURED);
const [source, setSource] = useState<
typeof SOURCE_REMOTE | typeof SOURCE_PUBLISHED
>(SOURCE_REMOTE);
@@ -194,13 +196,16 @@ export default function ExpertMarketTab({
const visibleItems = useMemo(() => {
const queryText = keyword.trim();
- if ((queryText && listQuery === queryText) || !activeScene) return items;
- const scene = activeScene.toLowerCase();
- return items.filter((item) => (item.scene || "").toLowerCase() === scene);
+ const searching = Boolean(queryText) && listQuery === queryText;
+ return visibleMarketExperts(items, activeScene, searching);
}, [activeScene, items, keyword, listQuery]);
const sceneOptions = useMemo(
() => [
+ {
+ value: MARKET_SCENE_FEATURED,
+ label: t("experts.sceneFeatured", "精选"),
+ },
{ value: SCENE_ALL, label: sceneLabel(SCENE_ALL, t) },
...scenes.map((scene) => ({
value: scene,
@@ -407,6 +412,7 @@ export default function ExpertMarketTab({
const label = labelOf(expert, lang);
const desc = descOf(expert, lang);
const accent = expert.color || "#6366f1";
+ const featured = expert.featured === true;
return (
-
+ {featured ? (
+
+
+
+
+
+ ) : null}
+
{
+ it("defaults the featured pill to shipped templates", () => {
+ expect(
+ visibleMarketExperts(items, MARKET_SCENE_FEATURED, false).map(
+ (item) => item.id,
+ ),
+ ).toEqual(["ops"]);
+ });
+
+ it("keeps every card on All and while searching", () => {
+ expect(visibleMarketExperts(items, "", false)).toHaveLength(3);
+ expect(
+ visibleMarketExperts(items, MARKET_SCENE_FEATURED, true),
+ ).toHaveLength(3);
+ });
+
+ it("still filters a normal scene", () => {
+ expect(
+ visibleMarketExperts(items, "ecommerce", false).map((item) => item.id),
+ ).toEqual(["shop"]);
+ });
+});
diff --git a/dashboard/src/pages/Experts/components/marketFeatured.ts b/dashboard/src/pages/Experts/components/marketFeatured.ts
new file mode 100644
index 0000000000..e311c310d0
--- /dev/null
+++ b/dashboard/src/pages/Experts/components/marketFeatured.ts
@@ -0,0 +1,13 @@
+/** Scene pill for the templates that used to ship as built-in experts. */
+export const MARKET_SCENE_FEATURED = "__featured__";
+
+export function visibleMarketExperts<
+ T extends { scene?: string; featured?: boolean },
+>(items: readonly T[], activeScene: string, searching: boolean): T[] {
+ if (searching || !activeScene) return [...items];
+ if (activeScene === MARKET_SCENE_FEATURED) {
+ return items.filter((item) => item.featured === true);
+ }
+ const scene = activeScene.toLowerCase();
+ return items.filter((item) => (item.scene || "").toLowerCase() === scene);
+}
diff --git a/dashboard/src/pages/Experts/index.module.less b/dashboard/src/pages/Experts/index.module.less
index 0fedca501e..e5ee2838c3 100644
--- a/dashboard/src/pages/Experts/index.module.less
+++ b/dashboard/src/pages/Experts/index.module.less
@@ -1173,6 +1173,21 @@
min-width: 0;
}
+.marketCardHeaderFeatured {
+ padding-right: 22px;
+}
+
+.marketFeaturedMark {
+ position: absolute;
+ top: 10px;
+ right: 14px;
+ z-index: 1;
+ display: inline-flex;
+ color: var(--expert-accent, var(--fn-color-brand));
+ line-height: 0;
+ cursor: default;
+}
+
.marketCardTitleRow {
display: flex;
align-items: center;
diff --git a/dashboard/src/styles/appearanceStorage.test.ts b/dashboard/src/styles/appearanceStorage.test.ts
index c46a87adc1..f392404c91 100644
--- a/dashboard/src/styles/appearanceStorage.test.ts
+++ b/dashboard/src/styles/appearanceStorage.test.ts
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it } from "vitest";
import {
loadAppearanceOnBoot,
readStoredAppearance,
+ userAppearanceStorageKey,
writeStoredAppearance,
} from "./appearanceStorage";
import {
@@ -14,6 +15,9 @@ import {
afterEach(() => {
localStorage.removeItem(THEME_STORAGE_KEY);
localStorage.removeItem(LEGACY_PALETTE_STORAGE_KEY);
+ localStorage.removeItem(userAppearanceStorageKey(1));
+ localStorage.removeItem(userAppearanceStorageKey(2));
+ localStorage.removeItem(userAppearanceStorageKey(3));
});
describe("appearanceStorage", () => {
@@ -115,4 +119,32 @@ describe("appearanceStorage", () => {
expect(readStoredAppearance().preference).toBe("system");
expect(readStoredAppearance().palette).toBe(DEFAULT_PALETTE);
});
+
+ it("keeps each user's palette separate from the shared boot key", () => {
+ writeStoredAppearance(
+ {
+ preference: "dark",
+ palette: "violet",
+ customColor: DEFAULT_CUSTOM_COLOR,
+ },
+ 1,
+ );
+ writeStoredAppearance(
+ {
+ preference: "light",
+ palette: "indigo",
+ customColor: DEFAULT_CUSTOM_COLOR,
+ },
+ 2,
+ );
+ localStorage.setItem(
+ THEME_STORAGE_KEY,
+ JSON.stringify({ preference: "dark", palette: "tech" }),
+ );
+
+ expect(readStoredAppearance(1).palette).toBe("violet");
+ expect(readStoredAppearance(2).palette).toBe("indigo");
+ expect(readStoredAppearance(3).palette).toBe(DEFAULT_PALETTE);
+ expect(readStoredAppearance().palette).toBe("tech");
+ });
});
diff --git a/dashboard/src/styles/appearanceStorage.ts b/dashboard/src/styles/appearanceStorage.ts
index 3aebc7659c..d8fd85b05b 100644
--- a/dashboard/src/styles/appearanceStorage.ts
+++ b/dashboard/src/styles/appearanceStorage.ts
@@ -42,7 +42,12 @@ function readLegacyPalette(): ThemePalette {
* Read light/dark preference + brand palette from the shared `theme` key.
* Migrates legacy plain-string `theme` and `octop:ui-palette` values.
*/
-export function readStoredAppearance(): StoredAppearance {
+export function readStoredAppearance(userId?: number | null): StoredAppearance {
+ if (typeof userId === "number") {
+ const own = localStorage.getItem(userAppearanceStorageKey(userId));
+ if (!own) return defaultAppearance();
+ return parseUserAppearance(own);
+ }
const raw = localStorage.getItem(THEME_STORAGE_KEY);
if (!raw) {
return {
@@ -86,10 +91,50 @@ export function readStoredAppearance(): StoredAppearance {
};
}
-/** Persist both fields under the same `theme` key; drop legacy palette key. */
-export function writeStoredAppearance(appearance: StoredAppearance): void {
+function parseUserAppearance(raw: string): StoredAppearance {
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (parsed && typeof parsed === "object") {
+ const obj = parsed as Record
;
+ return {
+ preference: isPreference(obj.preference) ? obj.preference : "system",
+ palette: isPalette(obj.palette) ? obj.palette : DEFAULT_PALETTE,
+ customColor:
+ normalizeHexColor(obj.customColor as string) ?? DEFAULT_CUSTOM_COLOR,
+ };
+ }
+ } catch {
+ // fall through
+ }
+ return defaultAppearance();
+}
+
+export function defaultAppearance(): StoredAppearance {
+ return {
+ preference: "system",
+ palette: DEFAULT_PALETTE,
+ customColor: DEFAULT_CUSTOM_COLOR,
+ };
+}
+
+/** Per-user key so two accounts on one browser do not share a palette. */
+export function userAppearanceStorageKey(userId: number): string {
+ return `${THEME_STORAGE_KEY}:user:${userId}`;
+}
+
+function appearanceStorageKey(userId?: number | null): string {
+ return typeof userId === "number"
+ ? userAppearanceStorageKey(userId)
+ : THEME_STORAGE_KEY;
+}
+
+/** Persist both fields. A user id writes that account's key, not the shared boot key. */
+export function writeStoredAppearance(
+ appearance: StoredAppearance,
+ userId?: number | null,
+): void {
localStorage.setItem(
- THEME_STORAGE_KEY,
+ appearanceStorageKey(userId),
JSON.stringify({
preference: appearance.preference,
palette: appearance.palette,
@@ -97,7 +142,9 @@ export function writeStoredAppearance(appearance: StoredAppearance): void {
normalizeHexColor(appearance.customColor ?? "") ?? DEFAULT_CUSTOM_COLOR,
}),
);
- localStorage.removeItem(LEGACY_PALETTE_STORAGE_KEY);
+ if (typeof userId !== "number") {
+ localStorage.removeItem(LEGACY_PALETTE_STORAGE_KEY);
+ }
}
/** One-shot boot read + migrate for ThemeProvider initial state. */
diff --git a/src/octop/api/middleware/bridge_proxy.py b/src/octop/api/middleware/bridge_proxy.py
index 9927dc9426..772cfd5acf 100644
--- a/src/octop/api/middleware/bridge_proxy.py
+++ b/src/octop/api/middleware/bridge_proxy.py
@@ -203,6 +203,21 @@ def _forward_headers(request: Request, remote_agent_id: str) -> dict[str, str]:
return headers
+def _is_websocket_upgrade(headers: Any) -> bool:
+ """True only for a real WebSocket handshake.
+
+ A reverse proxy often sets ``Connection: upgrade`` on every request
+ (``proxy_set_header Connection "upgrade"``) and leaves ``Upgrade`` empty.
+ Those requests must still be tunneled. ``Connection`` may also be a list.
+ """
+ connection = headers.get("connection") or ""
+ tokens = {part.strip().lower() for part in str(connection).split(",") if part.strip()}
+ if "upgrade" not in tokens:
+ return False
+ upgrade = headers.get("upgrade") or ""
+ return "websocket" in {part.strip().lower() for part in str(upgrade).split(",") if part.strip()}
+
+
def install(app: Any, server: Any) -> None:
if getattr(app, _INSTALL_ATTR, False):
return
@@ -220,8 +235,8 @@ async def _bridge_proxy(
)
if target is None:
return await call_next(request)
- # WebSocket upgrades are handled by the chat/bridge routers.
- if (request.headers.get("connection") or "").lower() == "upgrade":
+ # Real WebSocket upgrades are handled by the chat/bridge routers.
+ if _is_websocket_upgrade(request.headers):
return await call_next(request)
user = getattr(request.state, "octop_user", None)
diff --git a/src/octop/api/routers/chat/history.py b/src/octop/api/routers/chat/history.py
index 764cdd7441..f872b7de38 100644
--- a/src/octop/api/routers/chat/history.py
+++ b/src/octop/api/routers/chat/history.py
@@ -128,6 +128,7 @@ async def list_threads(
# 有些 thread 有标题但从未落过消息,点开就是空白。这里补一次真实计数。
message_repo = server.services.thread_message_repo
ids_with_messages = message_repo.threads_with_messages([r.thread_id for r in rows])
+ unread = thread_registry.unread_counts_for_threads([r.thread_id for r in rows])
def _has_messages(row: Any) -> bool:
if not thread_row_has_messages(row):
@@ -148,6 +149,7 @@ def _has_messages(row: Any) -> bool:
"is_active": r.thread_id == bound,
"has_messages": _has_messages(r),
"pinned": r.pinned,
+ "unread_count": int(unread.get(r.thread_id, 0)),
"model_ref": r.model_ref,
"reasoning_mode": r.reasoning_mode,
"reasoning_effort": r.reasoning_effort,
diff --git a/src/octop/api/routers/experts.py b/src/octop/api/routers/experts.py
index 65390f1eb0..46902a36c5 100644
--- a/src/octop/api/routers/experts.py
+++ b/src/octop/api/routers/experts.py
@@ -34,6 +34,7 @@
apply_workspace_quick_prompts,
build_create_spec_from_expert,
discover_seed_paths,
+ featured_expert_template_ids,
preview_file_paths,
preview_paths_from_expert_dir,
read_text_file_contents,
@@ -311,7 +312,12 @@ def _portal_prompts(value: Any) -> list[dict[str, Any]]:
return prompts
-def _portal_hub_item(item: dict[str, Any], *, include_content: bool) -> dict[str, Any]:
+def _portal_hub_item(
+ item: dict[str, Any],
+ *,
+ include_content: bool,
+ featured_ids: frozenset[str] | None = None,
+) -> dict[str, Any]:
raw_slugs = item.get("skill_slugs")
slugs = (
[slug for slug in raw_slugs if isinstance(slug, str)] if isinstance(raw_slugs, list) else []
@@ -329,6 +335,7 @@ def _portal_hub_item(item: dict[str, Any], *, include_content: bool) -> dict[str
"skill_slugs": slugs,
"skill_count": int(item.get("skill_count") or 0),
"source": str(item.get("source") or "portal"),
+ "featured": str(item.get("slug") or item.get("id") or "") in (featured_ids or frozenset()),
"task_examples": _portal_task_examples(item.get("task_examples")),
}
if include_content:
@@ -390,6 +397,7 @@ class ExpertHubItemResponse(BaseModel):
skill_slugs: list[str] = Field(default_factory=list)
skill_count: int = 0
source: str = "portal"
+ featured: bool = False
content: LocalizedTextResponse | None = None
quick_prompts: list[QuickPromptResponse] | None = None
task_examples: dict[str, list[str]] | None = None
@@ -820,6 +828,7 @@ async def list_expert_hub(
"""List experts published on the octop.cloud market."""
try:
portal_items, portal_scenes = await asyncio.to_thread(list_market_experts, q, scene)
+ featured_ids = featured_expert_template_ids()
except PortalMarketError as exc:
logger.warning("remote expert market unavailable: %s", exc)
network_error = local_network_error(exc)
@@ -831,7 +840,10 @@ async def list_expert_hub(
details={"reason": "upstream request failed"},
) from exc
return {
- "items": [_portal_hub_item(item, include_content=False) for item in portal_items],
+ "items": [
+ _portal_hub_item(item, include_content=False, featured_ids=featured_ids)
+ for item in portal_items
+ ],
"scenes": portal_scenes,
}
@@ -848,6 +860,7 @@ async def get_expert_hub_item(
"""Expert detail from the octop.cloud market."""
try:
portal_item = await asyncio.to_thread(get_market_expert, slug)
+ featured_ids = featured_expert_template_ids()
except PortalMarketError as exc:
logger.warning("remote expert market unavailable: %s", exc)
network_error = local_network_error(exc)
@@ -860,7 +873,7 @@ async def get_expert_hub_item(
) from exc
if portal_item is None:
raise OctopError(ErrorCode.NOT_FOUND, "expert not found")
- return _portal_hub_item(portal_item, include_content=True)
+ return _portal_hub_item(portal_item, include_content=True, featured_ids=featured_ids)
@router.post(
diff --git a/src/octop/api/routers/providers.py b/src/octop/api/routers/providers.py
index aec8d645b9..e80767e931 100644
--- a/src/octop/api/routers/providers.py
+++ b/src/octop/api/routers/providers.py
@@ -380,6 +380,11 @@ async def admin_create_provider(
models_json = _json.dumps(models) if models is not None else None
extra_json = merge_stream_usage_extra(body.extra_json, body.stream_usage)
extra_json = merge_provider_purpose_extra(extra_json, body.purpose)
+ if server.services.provider_repo.get_by_name(body.name) is not None:
+ raise OctopError(
+ ErrorCode.PROVIDER_NAME_TAKEN,
+ f"provider {body.name!r} already exists",
+ )
pid = server.services.provider_repo.create(
name=body.name,
kind=body.kind,
diff --git a/src/octop/cli/commands/backup.py b/src/octop/cli/commands/backup.py
index b90ddb4034..a0496b888d 100644
--- a/src/octop/cli/commands/backup.py
+++ b/src/octop/cli/commands/backup.py
@@ -9,7 +9,7 @@
from octop.config import load_config
from octop.infra.backup.auto import create_and_store_auto_backup
-from octop.infra.backup.store import place_backup_file
+from octop.infra.backup.store import move_file_replace, place_backup_file
from octop.infra.backup.system_archive import create_system_backup, restore_system_backup
from octop.infra.db.factory import open_database
from octop.infra.db.migrate import run_migrations
@@ -78,8 +78,7 @@ def create(
size = entry.size
else:
dest = output
- dest.parent.mkdir(parents=True, exist_ok=True)
- tmp_path.replace(dest)
+ move_file_replace(tmp_path, dest)
size = dest.stat().st_size
finally:
db.close()
diff --git a/src/octop/infra/agents/experts/catalog.py b/src/octop/infra/agents/experts/catalog.py
index a760e84aae..660cc26f01 100644
--- a/src/octop/infra/agents/experts/catalog.py
+++ b/src/octop/infra/agents/experts/catalog.py
@@ -883,6 +883,42 @@ def default_library_root() -> Path:
return Path(__file__).parent / "library"
+# Templates listed in the built-in library before the expert market replaced
+# that tab (22 cards; the blank ``default`` seed was never shown). Matching is
+# by id, not by whatever still happens to live under ``library/``.
+FEATURED_EXPERT_TEMPLATE_IDS = frozenset(
+ {
+ "ai-coding-coach",
+ "ai-safety-guardian",
+ "business-operations",
+ "clinical-learning-subscription",
+ "cowork-plugin-management",
+ "cvm-ai-doctor",
+ "cvm-cluster-doctor",
+ "design",
+ "engineering",
+ "general-assistant",
+ "karpathy-knowledge-base",
+ "meituan-living-assistant",
+ "multi-agent-orchestrator",
+ "news-trend",
+ "office-automation",
+ "ops-engineer",
+ "parenting-companion",
+ "productivity",
+ "stock-assistant",
+ "superpowers-methodology",
+ "tencentcloud-api",
+ "wechat-ops",
+ }
+)
+
+
+def featured_expert_template_ids() -> frozenset[str]:
+ """Ids of the expert templates that shipped before the remote market."""
+ return FEATURED_EXPERT_TEMPLATE_IDS
+
+
def resolve_expert_agent_name(
expert: Expert,
expert_id: str,
diff --git a/src/octop/infra/agents/manager.py b/src/octop/infra/agents/manager.py
index e1feeb8333..ae944e4e39 100644
--- a/src/octop/infra/agents/manager.py
+++ b/src/octop/infra/agents/manager.py
@@ -732,6 +732,13 @@ async def shutdown(self) -> None:
except Exception:
logger.warning("idle reclaim sweep failed during shutdown", exc_info=True)
self._reclaim_pending.clear()
+ # The idle sweep runs list_all on a worker thread. Cancelling that
+ # task does not stop the thread, so wait until the scan returns before
+ # the caller closes the control-plane connection.
+ sweep_task = self._reclaim_sweep_task
+ self._reclaim_sweep_task = None
+ if sweep_task is not None and not sweep_task.done():
+ await sweep_task
reclaim_task = self._reclaim_task
self._reclaim_task = None
if reclaim_task is not None and not reclaim_task.done():
@@ -1841,9 +1848,14 @@ def _ensure_reclaim_task(self) -> None:
self._reclaim_task = loop.create_task(self._reclaim_pending_loop(), name="store-reclaim")
async def _sweep_bloated_stores(self) -> None:
- queued = await asyncio.to_thread(self._queue_bloated_sqlite_stores)
- if queued:
- self._ensure_reclaim_task()
+ try:
+ queued = await asyncio.to_thread(self._queue_bloated_sqlite_stores)
+ if queued:
+ self._ensure_reclaim_task()
+ finally:
+ current = asyncio.current_task()
+ if self._reclaim_sweep_task is current:
+ self._reclaim_sweep_task = None
def _queue_bloated_sqlite_stores(self) -> int:
from octop.infra.agents.memory.thread_cleanup import ( # noqa: PLC0415
@@ -3006,7 +3018,11 @@ def _backend_supports_host_skill_packages(
root_dir = str(spec.get("root_dir") or "").strip()
if not root_dir:
return False
- if root_dir == "/":
+ from octop.infra.agents.workspace.dir import is_explicit_host_root # noqa: PLC0415
+
+ # ``/`` on POSIX, or a drive root (``C:/``) on Windows. Both can see the
+ # host path of a global skill package.
+ if is_explicit_host_root(root_dir):
return True
if workspace_dir is None:
return False
diff --git a/src/octop/infra/agents/workspace/dir.py b/src/octop/infra/agents/workspace/dir.py
index c80448fa13..b1600b1b17 100644
--- a/src/octop/infra/agents/workspace/dir.py
+++ b/src/octop/infra/agents/workspace/dir.py
@@ -45,6 +45,18 @@ def _running_on_windows() -> bool:
return os.name == "nt"
+def is_explicit_host_root(root: str) -> bool:
+ """True for POSIX ``/`` and a Windows drive root such as ``C:/``.
+
+ Empty strings are not a host root. A path below the drive (``C:/data``)
+ is a scoped jail.
+ """
+ text = root.strip()
+ if text in {"/", "\\"}:
+ return True
+ return bool(_WINDOWS_DRIVE_ROOT_RE.match(text))
+
+
def _is_host_root_sentinel(root: str | Path | None) -> bool:
"""True when *root* means the whole host filesystem (not a jail).
diff --git a/src/octop/infra/backup/store.py b/src/octop/infra/backup/store.py
index 556251816c..9deff127c4 100644
--- a/src/octop/infra/backup/store.py
+++ b/src/octop/infra/backup/store.py
@@ -184,6 +184,21 @@ def write_backup_file(paths: PathLayout, filename: str, data: bytes) -> BackupFi
return backup_file_info(dest)
+def move_file_replace(src: Path, dest: Path) -> None:
+ """Move *src* onto *dest*.
+
+ ``Path.replace`` raises ``EXDEV`` when the paths are on different filesystems.
+ Copy and then delete so a backup written under the system temp dir can land
+ on another disk.
+ """
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ src.replace(dest)
+ except OSError:
+ shutil.copy2(src, dest)
+ src.unlink(missing_ok=True)
+
+
def place_backup_file(paths: PathLayout, filename: str, src: Path) -> BackupFileInfo:
"""Move *src* into ``backups_dir`` under *filename* (atomic replace when possible)."""
paths.ensure_backups_dir()
@@ -192,12 +207,7 @@ def place_backup_file(paths: PathLayout, filename: str, src: Path) -> BackupFile
src = Path(src)
if src.resolve() == dest.resolve():
return backup_file_info(dest)
- dest.parent.mkdir(parents=True, exist_ok=True)
- try:
- src.replace(dest)
- except OSError:
- shutil.copy2(src, dest)
- src.unlink(missing_ok=True)
+ move_file_replace(src, dest)
return backup_file_info(dest)
diff --git a/src/octop/infra/gateway/hitl/store.py b/src/octop/infra/gateway/hitl/store.py
index 5102070230..aec7ef84e3 100644
--- a/src/octop/infra/gateway/hitl/store.py
+++ b/src/octop/infra/gateway/hitl/store.py
@@ -17,10 +17,19 @@ def _same_pause_slot(
existing: HitlPendingRecord,
*,
session_key: str,
+ thread_id: str,
resume_agent_id: str | None,
) -> bool:
+ """True when *existing* occupies the slot a new pause would replace.
+
+ Dashboard chats for one user and agent share a ``session_key``. The slot
+ is that key plus the thread, so a pause in chat B does not expire chat A.
+ Team members that share a room thread stay distinct via ``resume_agent_id``.
+ """
if existing.session_key != session_key or existing.status != "pending":
return False
+ if (existing.thread_id or "") != (thread_id or ""):
+ return False
if resume_agent_id:
return existing.resume_agent_id == resume_agent_id
return not existing.resume_agent_id
@@ -77,12 +86,14 @@ def register(
self._gc()
# A new pause replaces only the same slot. Two team members share the
# room session, so one member's card must not expire the other's.
+ # Dashboard threads also share a session key; thread_id keeps them apart.
# The same interrupt is often projected twice; reuse that pending id
# so an automatic resume of the first frame is not already expired.
for existing in list(self._records.values()):
if not _same_pause_slot(
existing,
session_key=session_key,
+ thread_id=thread_id,
resume_agent_id=resume_agent_id,
):
continue
@@ -92,6 +103,7 @@ def register(
if not _same_pause_slot(
existing,
session_key=session_key,
+ thread_id=thread_id,
resume_agent_id=resume_agent_id,
):
continue
diff --git a/src/octop/infra/knowledge/retrieve.py b/src/octop/infra/knowledge/retrieve.py
index 8421ef6bad..81b1286f6a 100644
--- a/src/octop/infra/knowledge/retrieve.py
+++ b/src/octop/infra/knowledge/retrieve.py
@@ -110,6 +110,7 @@ def _format_context(
ranked: Sequence[tuple[Any, Hit, Any]], *, char_budget: int, locale: str
) -> str:
sections: list[str] = []
+ included: list[tuple[Any, Hit, Any]] = []
remaining = char_budget
for base, hit, document in ranked:
citation = tr(
@@ -126,8 +127,9 @@ def _format_context(
continue
section = f"{citation}{text}"
sections.append(section)
+ included.append((base, hit, document))
remaining -= len(section)
if not sections:
return ""
body = tr("knowledge.retrieval.preamble", locale) + "\n\n" + "\n\n".join(sections)
- return append_citations_marker(body, citations_from_ranked(ranked))
+ return append_citations_marker(body, citations_from_ranked(included))
diff --git a/src/octop/infra/utils/env_file.py b/src/octop/infra/utils/env_file.py
index 2eea3451b5..740f059664 100644
--- a/src/octop/infra/utils/env_file.py
+++ b/src/octop/infra/utils/env_file.py
@@ -38,6 +38,19 @@ def env_file_path(root: Path) -> Path:
return root / "env"
+def _looks_like_assignment(line: str) -> bool:
+ """True when *line* is a new ``KEY=`` entry, not a quoted continuation."""
+ raw = line.strip()
+ if not raw or raw.startswith("#"):
+ return False
+ if raw.startswith("export "):
+ raw = raw[7:].strip()
+ if "=" not in raw:
+ return False
+ key, _, _ = raw.partition("=")
+ return bool(_KEY_RE.match(key.strip()))
+
+
def parse_env_text(text: str) -> dict[str, str]:
out: dict[str, str] = {}
lines = text.splitlines()
@@ -59,11 +72,13 @@ def parse_env_text(text: str) -> dict[str, str]:
# ``format_env_file`` quotes any value containing whitespace and leaves embedded line
# breaks raw, so a multi-line value has to be read back across lines. Only a value with
# an *unterminated* quote continues onto the next line; a value that already contains a
- # closing quote (or no quote at all) is left alone, so a malformed entry cannot swallow
- # the rest of the file.
+ # closing quote (or no quote at all) is left alone. A later ``KEY=`` line ends the
+ # continuation, so a missing closing quote cannot swallow the rest of the file.
if value[:1] in {'"', "'"} and value[0] not in value[1:]:
quote = value[0]
while index < len(lines) and quote not in value[1:]:
+ if _looks_like_assignment(lines[index]):
+ break
value = f"{value}\n{lines[index]}"
index += 1
value = value.strip()
diff --git a/tests/integration/test_providers_api.py b/tests/integration/test_providers_api.py
index f2f9cc1229..d8a4e3a989 100644
--- a/tests/integration/test_providers_api.py
+++ b/tests/integration/test_providers_api.py
@@ -32,6 +32,18 @@ async def test_admin_creates_provider(env):
assert "user_id" not in body
+async def test_duplicate_provider_name_is_conflict(env):
+ """POST /admin/providers with a taken name is 409, not an unhandled 500."""
+ c, _, auth = env
+ body = {"name": "taken-name", "kind": "openai", "api_key": "k"}
+ created = await c.post("/api/admin/providers", headers=auth, json=body)
+ assert created.status_code == 201
+
+ again = await c.post("/api/admin/providers", headers=auth, json=body)
+ assert again.status_code == 409
+ assert again.json()["error"]["code"] == "PROVIDER_NAME_TAKEN"
+
+
async def test_regular_user_cannot_create_provider(env):
"""POST /admin/providers is admin-only."""
c, _, admin_auth = env
diff --git a/tests/unit/agents/test_agent_manager.py b/tests/unit/agents/test_agent_manager.py
index 5f3031f384..10a4c5d6ec 100644
--- a/tests/unit/agents/test_agent_manager.py
+++ b/tests/unit/agents/test_agent_manager.py
@@ -1013,6 +1013,34 @@ def pending_operation() -> None:
await asyncio.to_thread(conn._thread.join, 5)
+@pytest.mark.asyncio
+async def test_shutdown_waits_for_idle_reclaim_sweep(manager: AgentManager) -> None:
+ """The freelist scan uses the control-plane connection from a worker thread."""
+ entered, release = threading.Event(), threading.Event()
+
+ def slow_scan() -> int:
+ entered.set()
+ assert release.wait(5)
+ return 0
+
+ manager._queue_bloated_sqlite_stores = slow_scan # type: ignore[method-assign]
+ manager.schedule_idle_reclaim_sweep()
+ closing = None
+ try:
+ assert await asyncio.to_thread(entered.wait, 5)
+ closing = asyncio.create_task(manager.shutdown())
+ await asyncio.sleep(0.05)
+ assert not closing.done()
+ release.set()
+ await asyncio.wait_for(closing, timeout=5)
+ finally:
+ release.set()
+ if closing is not None:
+ await closing
+ else:
+ await manager.shutdown()
+
+
def test_build_harness_config_enables_bootstrap_for_expert_template(manager: AgentManager) -> None:
from dataclasses import replace
diff --git a/tests/unit/agents/test_agent_skill_packages.py b/tests/unit/agents/test_agent_skill_packages.py
index a984115318..9210cf7e92 100644
--- a/tests/unit/agents/test_agent_skill_packages.py
+++ b/tests/unit/agents/test_agent_skill_packages.py
@@ -105,6 +105,17 @@ def test_assert_backend_supports_skill_packages_accepts_host_root(
)
+def test_assert_backend_supports_skill_packages_accepts_windows_drive_root(
+ manager: AgentManager,
+) -> None:
+ manager.assert_backend_supports_skill_packages(
+ {"type": "local_shell", "root_dir": "C:/", "virtual_mode": True}
+ )
+ manager.assert_backend_supports_skill_packages(
+ {"type": "filesystem", "root_dir": "D:\\", "virtual_mode": True}
+ )
+
+
def test_assert_backend_supports_skill_packages_accepts_workspace_scoped_default(
manager: AgentManager,
tmp_path: Path,
diff --git a/tests/unit/agents/test_expert_catalog.py b/tests/unit/agents/test_expert_catalog.py
index a913f59200..7d030c020a 100644
--- a/tests/unit/agents/test_expert_catalog.py
+++ b/tests/unit/agents/test_expert_catalog.py
@@ -387,3 +387,16 @@ async def test_apply_workspace_quick_prompts_refuses_invalid_json() -> None:
with pytest.raises(OctopError) as exc:
await apply_workspace_quick_prompts(workspace, [])
assert exc.value.code is ErrorCode.SLASH_BAD_ARGS
+
+
+def test_featured_expert_template_ids_are_the_pre_market_library() -> None:
+ from octop.infra.agents.experts.catalog import featured_expert_template_ids
+
+ ids = featured_expert_template_ids()
+
+ assert len(ids) == 22
+ assert "general-assistant" in ids
+ assert "ops-engineer" in ids
+ assert "wechat-ops" in ids
+ assert "default" not in ids
+ assert "tencent-cvm-ops" not in ids
diff --git a/tests/unit/api/test_chat_history.py b/tests/unit/api/test_chat_history.py
index 83bac3f2e2..1faf4f0bc2 100644
--- a/tests/unit/api/test_chat_history.py
+++ b/tests/unit/api/test_chat_history.py
@@ -211,6 +211,7 @@ async def test_list_threads_derives_has_messages_from_db() -> None:
thread_registry = MagicMock()
thread_registry.list_threads.return_value = rows
thread_registry.get_bound_thread_id.return_value = None
+ thread_registry.unread_counts_for_threads.return_value = {"thr_used": 3}
server = MagicMock()
agent_row = MagicMock(user_id=1)
@@ -235,6 +236,8 @@ async def test_list_threads_derives_has_messages_from_db() -> None:
assert out[1]["has_messages"] is True
assert out[1]["turn_active"] is True
assert out[1]["awaiting_user"] is False
+ assert out[0]["unread_count"] == 0
+ assert out[1]["unread_count"] == 3
@pytest.mark.asyncio
diff --git a/tests/unit/backup/test_move_file_replace.py b/tests/unit/backup/test_move_file_replace.py
new file mode 100644
index 0000000000..b3e2ad3e04
--- /dev/null
+++ b/tests/unit/backup/test_move_file_replace.py
@@ -0,0 +1,24 @@
+"""Cross-device backup moves fall back to copy."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from octop.infra.backup.store import move_file_replace
+
+
+def test_move_file_replace_copies_when_rename_fails(tmp_path: Path, monkeypatch) -> None:
+ src = tmp_path / "tmp" / "backup.tar.gz"
+ src.parent.mkdir()
+ src.write_bytes(b"archive")
+ dest = tmp_path / "other" / "backup.tar.gz"
+
+ def _explode(self: Path, _target: Path) -> Path:
+ raise OSError(18, "Invalid cross-device link")
+
+ monkeypatch.setattr(Path, "replace", _explode)
+
+ move_file_replace(src, dest)
+
+ assert dest.read_bytes() == b"archive"
+ assert not src.exists()
diff --git a/tests/unit/bridge/test_bridge_proxy_local.py b/tests/unit/bridge/test_bridge_proxy_local.py
index f22d67097d..3a65da4d55 100644
--- a/tests/unit/bridge/test_bridge_proxy_local.py
+++ b/tests/unit/bridge/test_bridge_proxy_local.py
@@ -7,6 +7,7 @@
import pytest
from octop.api.middleware.bridge_proxy import (
+ _is_websocket_upgrade,
_local_bridge_shadow_response,
resolve_tunnel_target,
)
@@ -54,6 +55,16 @@ def test_other_paths_pass_through() -> None:
)
+def test_constant_connection_upgrade_is_not_a_websocket() -> None:
+ """nginx ``Connection "upgrade"`` without ``Upgrade: websocket`` must still tunnel."""
+ assert _is_websocket_upgrade({"connection": "upgrade"}) is False
+ assert _is_websocket_upgrade({"connection": "keep-alive, upgrade"}) is False
+ assert _is_websocket_upgrade({"connection": "Upgrade", "upgrade": "websocket"}) is True
+ assert (
+ _is_websocket_upgrade({"connection": "keep-alive, Upgrade", "upgrade": "WebSocket"}) is True
+ )
+
+
def test_resolve_upload_path() -> None:
target = resolve_tunnel_target("/api/agents/bridge:cid1:aid1/upload")
assert target is not None
@@ -117,3 +128,60 @@ def test_resolve_ignores_local_header_and_unscoped_paths() -> None:
assert resolve_tunnel_target("/api/mbti/current", "01LOCAL") is None
assert resolve_tunnel_target("/api/users", "bridge:cid1:aid1") is None
assert resolve_tunnel_target("/api/plugins/install", "bridge:cid1:aid1") is None
+
+
+@pytest.mark.asyncio
+async def test_proxy_still_tunnels_when_connection_upgrade_is_not_websocket() -> None:
+ import httpx
+ from fastapi import FastAPI
+ from fastapi.responses import JSONResponse
+
+ from octop.api.middleware.bridge_proxy import install
+
+ app = FastAPI()
+ seen: dict[str, object] = {}
+
+ class _User:
+ id = 7
+
+ class _Mgr:
+ async def tunnel_http(self, **kwargs: object) -> httpx.Response:
+ seen.update(kwargs)
+ return httpx.Response(200, json={"ok": True})
+
+ class _Server:
+ class _Runtime:
+ bridge_manager = _Mgr()
+
+ app_runtime = _Runtime()
+
+ install(app, _Server())
+
+ @app.middleware("http")
+ async def _user(request, call_next): # type: ignore[no-untyped-def]
+ request.state.octop_user = _User()
+ return await call_next(request)
+
+ @app.get("/api/agents/{agent_id}/threads")
+ async def _local(agent_id: str) -> JSONResponse:
+ return JSONResponse(
+ {"error": {"code": "AGENT_NOT_FOUND", "message": agent_id}},
+ status_code=404,
+ )
+
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ proxied = await client.get(
+ "/api/agents/bridge:cid1:aid1/threads",
+ headers={"connection": "upgrade"},
+ )
+ skipped = await client.get(
+ "/api/agents/bridge:cid1:aid1/threads",
+ headers={"connection": "upgrade", "upgrade": "websocket"},
+ )
+
+ assert proxied.status_code == 200
+ assert proxied.json()["ok"] is True
+ assert seen["path"] == "/api/agents/aid1/threads"
+ assert skipped.status_code == 404
+ assert skipped.json()["error"]["code"] == "AGENT_NOT_FOUND"
diff --git a/tests/unit/db/test_db_pool.py b/tests/unit/db/test_db_pool.py
index e23a7e9e38..adf1ebf605 100644
--- a/tests/unit/db/test_db_pool.py
+++ b/tests/unit/db/test_db_pool.py
@@ -57,6 +57,31 @@ def test_db_pool_file_is_0600(tmp_path: Path):
assert mode == 0o600
+def test_close_waits_for_in_flight_connection(db: SqlitePool) -> None:
+ """Closing must not free the connection while another thread is inside it."""
+ started = threading.Event()
+ release = threading.Event()
+
+ def hold() -> None:
+ with db.connect() as conn:
+ started.set()
+ assert release.wait(timeout=5)
+ conn.execute("SELECT 1").fetchone()
+
+ holder = threading.Thread(target=hold)
+ holder.start()
+ assert started.wait(timeout=5)
+ closer = threading.Thread(target=db.close)
+ closer.start()
+ closer.join(timeout=0.2)
+ assert closer.is_alive()
+ release.set()
+ closer.join(timeout=5)
+ holder.join(timeout=5)
+ assert not closer.is_alive()
+ assert not holder.is_alive()
+
+
def test_run_migrations_creates_tables(db: SqlitePool):
with db.connect() as conn:
rows = conn.execute(
diff --git a/tests/unit/gateway/test_hitl_channel.py b/tests/unit/gateway/test_hitl_channel.py
index 7dc00cba9c..692bd2cb4b 100644
--- a/tests/unit/gateway/test_hitl_channel.py
+++ b/tests/unit/gateway/test_hitl_channel.py
@@ -405,6 +405,33 @@ def test_hitl_store_resolve_pending_for_thread() -> None:
assert store.pending_thread_ids(agent_id="agent1", user_id=2) == frozenset()
+def test_hitl_store_other_thread_does_not_expire_pending() -> None:
+ """Same dashboard session_key, different threads, stay pending together."""
+ store = HitlPendingStore()
+ ask_a = [{"name": "ask_user_question", "args": {"questions": [{"question": "A?"}]}}]
+ ask_b = [{"name": "ask_user_question", "args": {"questions": [{"question": "B?"}]}}]
+ first = store.register(
+ thread_id="thr-a",
+ agent_id="agent1",
+ user_id=1,
+ session_key="dash:1:agent1",
+ channel_type="dashboard",
+ action_requests=ask_a,
+ review_configs=None,
+ )
+ second = store.register(
+ thread_id="thr-b",
+ agent_id="agent1",
+ user_id=1,
+ session_key="dash:1:agent1",
+ channel_type="dashboard",
+ action_requests=ask_b,
+ review_configs=None,
+ )
+ assert store.get(first.pending_id).status == "pending" # type: ignore[union-attr]
+ assert store.get(second.pending_id).status == "pending" # type: ignore[union-attr]
+
+
def test_hitl_store_reuses_equivalent_pending() -> None:
store = HitlPendingStore()
actions = [{"name": "execute", "args": {"command": "df"}}]
diff --git a/tests/unit/knowledge/test_retrieve.py b/tests/unit/knowledge/test_retrieve.py
index 8102ab3258..d2f7299381 100644
--- a/tests/unit/knowledge/test_retrieve.py
+++ b/tests/unit/knowledge/test_retrieve.py
@@ -79,3 +79,21 @@ def test_retrieve_context_skips_empty_non_text_turn() -> None:
)
assert context == ""
+
+
+def test_format_context_cites_only_documents_inside_the_budget() -> None:
+ base = SimpleNamespace(id="kb", name="KB")
+ doc_a = SimpleNamespace(id="a", filename="a.md", path="a.md")
+ doc_b = SimpleNamespace(id="b", filename="b.md", path="b.md")
+ hit_a = SimpleNamespace(text="alpha " * 40, ordinal=0)
+ hit_b = SimpleNamespace(text="beta " * 40, ordinal=0)
+
+ text = retrieve_module._format_context(
+ [(base, hit_a, doc_a), (base, hit_b, doc_b)],
+ char_budget=80,
+ locale="en",
+ )
+
+ marker = text.split(CITATIONS_MARKER_PREFIX, 1)[1]
+ assert "a.md" in marker
+ assert "b.md" not in marker
diff --git a/tests/unit/test_env_file.py b/tests/unit/test_env_file.py
index cfcfbf53c2..de3792c15a 100644
--- a/tests/unit/test_env_file.py
+++ b/tests/unit/test_env_file.py
@@ -124,6 +124,16 @@ def test_multiline_value_survives_roundtrip() -> None:
}
+def test_unclosed_quote_does_not_swallow_following_assignments() -> None:
+ text = 'BROKEN="no-close\nNEXT=1\nOK=2\n'
+
+ parsed = parse_env_text(text)
+
+ assert parsed["NEXT"] == "1"
+ assert parsed["OK"] == "2"
+ assert "NEXT" not in parsed["BROKEN"]
+
+
def test_quoted_value_with_inner_quote_does_not_swallow_following_lines() -> None:
"""Only an unterminated quote continues onto the next line."""
text = 'MALFORMED="abc"def\nNEXT=1\n'
From 70f2bb7e0073eab340341e97c2a5098bab1e730d Mon Sep 17 00:00:00 2001
From: Jubaoliang
Date: Sat, 7 Nov 2026 16:39:34 +0800
Subject: [PATCH 5/8] feat(chat): share conversations on a shared expert
(#2877)
* feat(chat): share conversations on a shared expert
Owners can mark a thread as shared so anyone who can open that expert can read it, follow up, and handle pending approvals. Composer settings stay with the owner, and the chat expert menu can open the existing edit drawer.
Co-authored-by: Cursor
* fix(chat): satisfy mypy on shared-thread author and HITL lookup
Author ids from message JSON are narrowed before the profile map lookup, and a shared thread may resolve a pending approval without a user filter.
Co-authored-by: Cursor
* fix(chat): keep private threads private when the share flag is absent
Visibility checks treat a missing contributed flag as not shared, and dashboard tests read the author-stamped HumanMessage instead of a plain dict.
Co-authored-by: Cursor
* docs: describe projects alongside experts and teams
Record the agreed project shape: group visibility, owner-backed default context, and tasks that everyone who can open the project can see.
Co-authored-by: Cursor
---------
Co-authored-by: jubaoliang
Co-authored-by: Cursor
---
dashboard/src/api/modules/octopThreads.ts | 7 +
dashboard/src/locales/en.json | 7 +
dashboard/src/locales/zh.json | 7 +
.../Chat/components/ChatEditExpertDrawer.tsx | 30 +++
.../src/pages/Chat/components/ChatInput.tsx | 4 +
.../Chat/components/ChatInputActionsRow.tsx | 37 +++-
.../Chat/components/ExpertNavActions.tsx | 14 ++
.../Chat/components/HitlPolicyPicker.tsx | 13 +-
.../pages/Chat/components/MessageBubble.tsx | 43 ++--
.../MessageBubble.userAvatar.test.tsx | 74 +++++++
.../components/MinimalAgentSessionNav.tsx | 188 +++++++++++------
.../src/pages/Chat/components/SessionList.tsx | 197 ++++++++++++------
dashboard/src/pages/Chat/hooks/chatStore.ts | 60 ++++++
dashboard/src/pages/Chat/hooks/sseHelpers.ts | 10 +
dashboard/src/pages/Chat/hooks/useChat.ts | 42 +++-
.../Chat/hooks/useChatComposerResources.ts | 19 +-
dashboard/src/pages/Chat/hooks/useSessions.ts | 16 ++
dashboard/src/pages/Chat/index.module.less | 10 +
dashboard/src/pages/Chat/index.tsx | 98 +++++----
.../Chat/utils/inflightTranscriptCache.ts | 15 ++
.../src/pages/Chat/utils/shareSession.ts | 21 ++
docs/projects.md | 103 +++++++++
src/octop/api/routers/chat/history.py | 131 ++++++++++--
src/octop/api/routers/chat/models.py | 4 +
src/octop/api/routers/chat/routes.py | 8 +-
src/octop/api/routers/chat/serialize.py | 15 ++
src/octop/api/routers/chat/turn.py | 11 +-
src/octop/api/routers/chat/ws.py | 11 +-
src/octop/api/routers/users.py | 6 +-
src/octop/i18n/en.json | 1 +
src/octop/i18n/zh.json | 1 +
src/octop/infra/db/migrate.py | 10 +
.../infra/db/migrations/025_user_mfa.pg.sql | 2 +
.../infra/db/migrations/025_user_mfa.sql | 2 +
src/octop/infra/db/repos/sessions.py | 7 +
src/octop/infra/db/repos/threads.py | 26 +++
src/octop/infra/errors.py | 2 +
src/octop/infra/gateway/hitl/coordinator.py | 2 +-
src/octop/infra/gateway/hitl/store.py | 16 +-
.../infra/gateway/process/harness_request.py | 4 +
.../infra/gateway/process/message_keys.py | 2 +
src/octop/infra/gateway/process/processor.py | 11 +-
src/octop/infra/gateway/threads.py | 36 +++-
src/octop/infra/gateway/ws/ws_channel.py | 51 ++++-
tests/unit/api/test_chat_history.py | 96 ++++++++-
tests/unit/db/test_repo_sessions_threads.py | 33 +++
tests/unit/gateway/test_dashboard_ws.py | 27 ++-
tests/unit/gateway/test_hitl_channel.py | 4 +
tests/unit/gateway/test_message_build.py | 1 +
.../test_processor_conversation_mode.py | 4 +-
.../gateway/test_processor_default_open.py | 2 +-
51 files changed, 1312 insertions(+), 229 deletions(-)
create mode 100644 dashboard/src/pages/Chat/components/ChatEditExpertDrawer.tsx
create mode 100644 dashboard/src/pages/Chat/utils/shareSession.ts
create mode 100644 docs/projects.md
diff --git a/dashboard/src/api/modules/octopThreads.ts b/dashboard/src/api/modules/octopThreads.ts
index 75fa014ec7..7f5d39ff0b 100644
--- a/dashboard/src/api/modules/octopThreads.ts
+++ b/dashboard/src/api/modules/octopThreads.ts
@@ -67,6 +67,10 @@ export interface OctopThread {
turn_active?: boolean;
/** True when this thread is paused on a HITL approval or question. */
awaiting_user?: boolean;
+ /** Shared with other users who can open this expert. */
+ contributed?: boolean;
+ /** False when the thread was contributed by someone else. */
+ owned?: boolean;
}
export interface OctopThreadHistory {
@@ -117,6 +121,7 @@ export interface ThreadDeleteResult {
export interface OctopThreadPatch {
title?: string;
pinned?: boolean;
+ contributed?: boolean;
model_ref?: string | null;
reasoning_mode?: "auto" | "enabled" | "disabled" | null;
reasoning_effort?: string | null;
@@ -240,6 +245,8 @@ export const octopThreadsApi = {
thread_id: string;
title: string | null;
pinned?: boolean;
+ contributed?: boolean;
+ owned?: boolean;
model_ref?: string | null;
reasoning_mode?: "auto" | "enabled" | "disabled" | null;
reasoning_effort?: string | null;
diff --git a/dashboard/src/locales/en.json b/dashboard/src/locales/en.json
index 95a31b167e..43068a0536 100644
--- a/dashboard/src/locales/en.json
+++ b/dashboard/src/locales/en.json
@@ -131,6 +131,7 @@
"AGENT_NOT_RUNNING": "This expert is not enabled.",
"CHECKPOINT_DELETE_FAILED": "Conversation data was not deleted. The thread is still here; try again.",
"THREAD_TURN_ACTIVE": "A reply is still in progress. Stop it, then delete this conversation.",
+ "THREAD_CONTRIBUTE_REQUIRES_SHARE": "Only a shared expert can share a conversation with other users.",
"AGENT_FAILED": "Agent failed to start.",
"AGENT_BUSY": "Agent is busy.",
"AGENT_NAME_TAKEN": "This name is already in use. Please choose another.",
@@ -1596,6 +1597,12 @@
"expandMore": "Show more",
"pin": "Pin",
"unpin": "Unpin",
+ "contribute": "Share conversation",
+ "uncontribute": "Stop sharing",
+ "sharedSession": "Shared",
+ "sharedSessionBanner": "This conversation is shared. Anyone who can open this expert can read it and continue.",
+ "threadSettingsOwnerOnly": "Only the conversation owner can change the model and approval settings",
+ "shareFailed": "Couldn't change sharing. Try again.",
"deleteSessionConfirm": "Delete this conversation? This cannot be undone.",
"deleteSessionTitle": "Delete this conversation?",
"deleteSessionBody": "This cannot be undone. The conversation leaves the list immediately. The database file does not get smaller until it is compacted.",
diff --git a/dashboard/src/locales/zh.json b/dashboard/src/locales/zh.json
index 622a434a0f..5b3bb7b452 100644
--- a/dashboard/src/locales/zh.json
+++ b/dashboard/src/locales/zh.json
@@ -131,6 +131,7 @@
"AGENT_NOT_RUNNING": "此专家未启用。",
"CHECKPOINT_DELETE_FAILED": "对话数据没有删除,会话已保留,请重试。",
"THREAD_TURN_ACTIVE": "回复进行中,请先停止再删除。",
+ "THREAD_CONTRIBUTE_REQUIRES_SHARE": "只有共享专家上的会话可以共享给其他用户。",
"AGENT_FAILED": "专家启动失败。",
"AGENT_BUSY": "专家正忙。",
"AGENT_NAME_TAKEN": "该名称已被使用,请换一个名称。",
@@ -1596,6 +1597,12 @@
"expandMore": "展开更多",
"pin": "置顶",
"unpin": "取消置顶",
+ "contribute": "共享会话",
+ "uncontribute": "取消共享",
+ "sharedSession": "已共享",
+ "sharedSessionBanner": "这条会话已共享。能打开这个专家的人都能看到,并可以继续问。",
+ "threadSettingsOwnerOnly": "只有会话创建人可以改模型和审批设置",
+ "shareFailed": "没能改共享状态,请再试一次",
"deleteSessionConfirm": "确定删除这段会话吗?删除后无法恢复。",
"deleteSessionTitle": "删除这段会话?",
"deleteSessionBody": "删除后无法恢复。会话会马上从列表里消失。数据库文件要等整理之后才会变小。",
diff --git a/dashboard/src/pages/Chat/components/ChatEditExpertDrawer.tsx b/dashboard/src/pages/Chat/components/ChatEditExpertDrawer.tsx
new file mode 100644
index 0000000000..8c78894eed
--- /dev/null
+++ b/dashboard/src/pages/Chat/components/ChatEditExpertDrawer.tsx
@@ -0,0 +1,30 @@
+import { useAgent, type OctopAgent } from "../../../context/AgentContext";
+import { isOwnedExpert } from "../../../utils/sharedExpert";
+import { isTeamAgent } from "../../../utils/teamAgent";
+import EditAgentDrawer from "../../Experts/components/EditAgentDrawer";
+
+/** Local experts the current user can edit. Teams and remote experts use other screens. */
+export function canEditExpertFromChat(agent: OctopAgent): boolean {
+ return isOwnedExpert(agent) && !agent.bridge && !isTeamAgent(agent);
+}
+
+export default function ChatEditExpertDrawer({
+ agent,
+ onClose,
+}: {
+ agent: OctopAgent | null;
+ onClose: () => void;
+}) {
+ const { refresh } = useAgent();
+ return (
+ {
+ onClose();
+ void refresh({ silent: true });
+ }}
+ />
+ );
+}
diff --git a/dashboard/src/pages/Chat/components/ChatInput.tsx b/dashboard/src/pages/Chat/components/ChatInput.tsx
index d3a1d7d522..369b99e4a8 100644
--- a/dashboard/src/pages/Chat/components/ChatInput.tsx
+++ b/dashboard/src/pages/Chat/components/ChatInput.tsx
@@ -114,6 +114,8 @@ interface ChatInputProps {
onConversationModeChange?: (mode: "ask" | "plan" | "craft") => void;
hitlPolicy?: HitlSessionPolicy;
onHitlPolicyChange?: (policy: HitlSessionPolicy) => void;
+ /** Shared conversation: model, reasoning, mode, and approval stay with the owner. */
+ lockThreadSettings?: boolean;
availableConnectors?: {
mcp_server_name: string;
label: string;
@@ -176,6 +178,7 @@ const ChatInput = forwardRef(
onConversationModeChange,
hitlPolicy,
onHitlPolicyChange,
+ lockThreadSettings = false,
availableConnectors,
selectedConnectors = [],
onConnectorsChange,
@@ -1029,6 +1032,7 @@ const ChatInput = forwardRef(
onConversationModeChange={onConversationModeChange}
hitlPolicy={hitlPolicy}
onHitlPolicyChange={onHitlPolicyChange}
+ lockThreadSettings={lockThreadSettings}
defaultModel={defaultModel}
availableConnectors={availableConnectors}
selectedConnectors={selectedConnectors}
diff --git a/dashboard/src/pages/Chat/components/ChatInputActionsRow.tsx b/dashboard/src/pages/Chat/components/ChatInputActionsRow.tsx
index 85d878d34d..0792ea16a1 100644
--- a/dashboard/src/pages/Chat/components/ChatInputActionsRow.tsx
+++ b/dashboard/src/pages/Chat/components/ChatInputActionsRow.tsx
@@ -158,6 +158,7 @@ interface ChatInputActionsRowProps {
onConversationModeChange?: (mode: "ask" | "plan" | "craft") => void;
hitlPolicy?: HitlSessionPolicy;
onHitlPolicyChange?: (policy: HitlSessionPolicy) => void;
+ lockThreadSettings?: boolean;
availableConnectors?: {
mcp_server_name: string;
label: string;
@@ -221,6 +222,7 @@ export default function ChatInputActionsRow({
onConversationModeChange,
hitlPolicy,
onHitlPolicyChange,
+ lockThreadSettings = false,
availableConnectors,
selectedConnectors = [],
onConnectorsChange,
@@ -245,6 +247,13 @@ export default function ChatInputActionsRow({
onSubmit,
}: ChatInputActionsRowProps) {
const { t } = useTranslation();
+ const settingsLockedHint = lockThreadSettings
+ ? t("chat.threadSettingsOwnerOnly", "只有会话创建人可以改模型和审批设置")
+ : undefined;
+ const modelChange = lockThreadSettings ? undefined : onModelChange;
+ const reasoningChange = lockThreadSettings ? undefined : onReasoningChange;
+ const modeChange = lockThreadSettings ? undefined : onConversationModeChange;
+ const hitlChange = lockThreadSettings ? undefined : onHitlPolicyChange;
const navigate = useNavigate();
const remoteManaged = Boolean(agentId?.startsWith("bridge:"));
const skillDisplayName = useSkillDisplayName();
@@ -481,7 +490,7 @@ export default function ChatInputActionsRow({
};
const openModelReasoning = (modelRef: string) => {
- if (selectedModel !== modelRef) onModelChange?.(modelRef);
+ if (selectedModel !== modelRef) modelChange?.(modelRef);
setReasoningModelRef(modelRef);
};
@@ -525,7 +534,7 @@ export default function ChatInputActionsRow({
styles.reasoningMenuChoice,
reasoningMode === mode && styles.reasoningMenuChoiceActive,
)}
- onClick={() => onReasoningChange?.(mode, reasoningEffort)}
+ onClick={() => reasoningChange?.(mode, reasoningEffort)}
>
{reasoningModeLabel(mode)}
{reasoningMode === mode && }
@@ -547,7 +556,7 @@ export default function ChatInputActionsRow({
styles.reasoningMenuChoiceActive,
)}
onClick={() =>
- onReasoningChange?.(
+ reasoningChange?.(
reasoningMode === "disabled" ? "enabled" : reasoningMode,
effort,
)
@@ -591,7 +600,7 @@ export default function ChatInputActionsRow({
!selectedModel && styles.modelMenuItemActive,
)}
onClick={() => {
- onModelChange?.(null);
+ modelChange?.(null);
closePlusMenu();
}}
>
@@ -619,7 +628,7 @@ export default function ChatInputActionsRow({
type="button"
className={styles.modelMenuSelect}
onClick={() => {
- onModelChange?.(active ? null : value);
+ modelChange?.(active ? null : value);
closePlusMenu();
}}
>
@@ -740,7 +749,11 @@ export default function ChatInputActionsRow({
styles.mobileOverflowItem,
compactPicker === "mode" && styles.mobileOverflowItemActive,
)}
- onClick={() => openCompactPicker("mode")}
+ title={settingsLockedHint}
+ onClick={() => {
+ if (lockThreadSettings) return;
+ openCompactPicker("mode");
+ }}
>
@@ -761,7 +774,11 @@ export default function ChatInputActionsRow({
styles.mobileOverflowItem,
compactPicker === "model" && styles.mobileOverflowItemActive,
)}
- onClick={() => openCompactPicker("model")}
+ title={settingsLockedHint}
+ onClick={() => {
+ if (lockThreadSettings) return;
+ openCompactPicker("model");
+ }}
>
@@ -888,7 +905,7 @@ export default function ChatInputActionsRow({
{
- onConversationModeChange?.(mode);
+ modeChange?.(mode);
closePlusMenu();
}}
/>
@@ -1037,7 +1054,9 @@ export default function ChatInputActionsRow({
{onHitlPolicyChange && (
)}
void;
onNewChat: () => void;
+ onEdit?: () => void;
onHide?: () => void;
onUnhide?: () => void;
}) {
@@ -56,6 +59,17 @@ export default function ExpertNavActions({
},
},
];
+ if (onEdit) {
+ items.push({
+ key: "edit",
+ icon: ,
+ label: t("experts.editExpert", "编辑专家"),
+ onClick: ({ domEvent }) => {
+ domEvent.stopPropagation();
+ onEdit();
+ },
+ });
+ }
if (onHide) {
items.push({
key: "hide",
diff --git a/dashboard/src/pages/Chat/components/HitlPolicyPicker.tsx b/dashboard/src/pages/Chat/components/HitlPolicyPicker.tsx
index bfddbfcf26..8a0af688bd 100644
--- a/dashboard/src/pages/Chat/components/HitlPolicyPicker.tsx
+++ b/dashboard/src/pages/Chat/components/HitlPolicyPicker.tsx
@@ -14,11 +14,15 @@ import styles from "../index.module.less";
interface HitlPolicyPickerProps {
policy: HitlSessionPolicy;
onChange: (policy: HitlSessionPolicy) => void;
+ disabled?: boolean;
+ disabledHint?: string;
}
export default function HitlPolicyPicker({
policy,
onChange,
+ disabled = false,
+ disabledHint,
}: HitlPolicyPickerProps) {
const { t } = useTranslation();
const toolLabelOf = useToolDisplayNames();
@@ -36,8 +40,8 @@ export default function HitlPolicyPicker({
@@ -107,7 +111,10 @@ export default function HitlPolicyPicker({
}
>
-
+
- }
- />
+
+
+ }
+ />
+
) : expert || avatarProfileId ? (
= {
+ id: 1,
username: "ada",
display_name: "Ada",
avatar_icon: "business",
@@ -92,4 +93,77 @@ describe("MessageBubble user avatar", () => {
);
expect(sender.querySelector("svg")).toBeNull();
});
+
+ it("uses the other person's portrait and name on a shared conversation", () => {
+ currentUser.avatar_icon = "business";
+ currentUser.avatar_url = "/api/users/1/avatar";
+ render(
+ ,
+ );
+
+ const sender = screen.getByLabelText("Bob");
+ expect(sender.querySelector("img")).toHaveAttribute(
+ "src",
+ "/api/users/2/avatar",
+ );
+ });
+
+ it("does not paint the current account photo onto someone without one", () => {
+ currentUser.avatar_icon = "doctor";
+ currentUser.avatar_url = "/api/users/1/avatar?v=2";
+ render(
+ ,
+ );
+
+ const sender = screen.getByLabelText("Bob");
+ expect(sender.querySelector("img")).toBeNull();
+ expect(sender.querySelector("svg")).toBeTruthy();
+ });
+
+ it("uses the live account photo for the current user's own turns", () => {
+ currentUser.avatar_icon = "doctor";
+ currentUser.avatar_url = "/api/users/1/avatar?v=2";
+ render(
+ ,
+ );
+
+ const sender = screen.getByLabelText("Ada");
+ expect(sender.querySelector("img")).toHaveAttribute(
+ "src",
+ "/api/users/1/avatar?v=2",
+ );
+ });
});
diff --git a/dashboard/src/pages/Chat/components/MinimalAgentSessionNav.tsx b/dashboard/src/pages/Chat/components/MinimalAgentSessionNav.tsx
index c59befbe3a..5b408423d4 100644
--- a/dashboard/src/pages/Chat/components/MinimalAgentSessionNav.tsx
+++ b/dashboard/src/pages/Chat/components/MinimalAgentSessionNav.tsx
@@ -11,6 +11,7 @@ import {
Pin,
PinOff,
Search,
+ Share2,
Trash2,
} from "lucide-react";
import cx from "classnames";
@@ -25,6 +26,7 @@ import { isAgentChatReady } from "../../../utils/agentError";
import { isImeComposing } from "../../../utils/ime";
import { sortSessions, toSession, type Session } from "../hooks/useSessions";
import { openAgentUnread } from "../utils/openUnreadSession";
+import { saveSessionShared } from "../utils/shareSession";
import { formatThreadTitle } from "../utils/threadTitle";
import { onSessionEvent } from "../hooks/chatStore";
import { useExpertSessionCatalog } from "../hooks/useExpertSessionCatalog";
@@ -54,6 +56,9 @@ import SessionWorkStatusIcon from "./SessionWorkStatusIcon";
import TeamChatBadge from "./TeamChatBadge";
import ExpertNameLabel from "./ExpertNameLabel";
import ExpertNavActions, { ExpertPinMark } from "./ExpertNavActions";
+import ChatEditExpertDrawer, {
+ canEditExpertFromChat,
+} from "./ChatEditExpertDrawer";
import styles from "../index.module.less";
/** Default preview size per expert in minimal nav (matches session page size). */
@@ -132,6 +137,8 @@ const PreviewSessionRow = memo(function PreviewSessionRow({
onRename,
onPin,
onFork,
+ onContribute,
+ shareable,
forkDisabled,
forkDisabledHint,
}: {
@@ -146,6 +153,8 @@ const PreviewSessionRow = memo(function PreviewSessionRow({
onRename: (id: string, name: string) => void;
onPin: (id: string, pinned: boolean) => void;
onFork: (id: string) => void;
+ onContribute: (id: string, contributed: boolean) => void;
+ shareable: boolean;
forkDisabled?: boolean;
forkDisabledHint?: string;
}) {
@@ -179,52 +188,70 @@ const PreviewSessionRow = memo(function PreviewSessionRow({
const itemForkHint = !session.hasActivity
? t("chat.forkNoAssistant")
: forkDisabledHint;
-
- const menuItems: MenuProps["items"] = [
- {
- key: "pin",
- label: session.pinned
- ? t("chat.unpin", "取消置顶")
- : t("chat.pin", "置顶"),
- icon: session.pinned ? : ,
- onClick: ({ domEvent }) => {
- domEvent.stopPropagation();
- onPin(session.id, !session.pinned);
- },
- },
- {
- key: "fork",
- label: t("chat.fork", "分叉"),
- icon: ,
- disabled: itemForkDisabled,
- title: itemForkDisabled && itemForkHint ? itemForkHint : undefined,
- onClick: ({ domEvent }) => {
- domEvent.stopPropagation();
- onFork(session.id);
- },
- },
- {
- key: "rename",
- label: t("common.rename"),
- icon: ,
- onClick: ({ domEvent }) => {
- domEvent.stopPropagation();
- setIsEditing(true);
- },
- },
- {
- key: "delete",
- label: t("common.delete", "Delete"),
- icon: ,
- danger: true,
- onClick: ({ domEvent }) => {
- domEvent.stopPropagation();
- confirmDeleteConversation(t, (compact) =>
- onDelete(session.id, compact),
- );
- },
- },
- ];
+ const owned = session.owned !== false;
+
+ const menuItems: MenuProps["items"] = owned
+ ? [
+ ...(shareable
+ ? [
+ {
+ key: "contribute",
+ label: session.contributed
+ ? t("chat.uncontribute", "取消共享")
+ : t("chat.contribute", "共享会话"),
+ icon: ,
+ onClick: (event: { domEvent: { stopPropagation(): void } }) => {
+ event.domEvent.stopPropagation();
+ onContribute(session.id, !session.contributed);
+ },
+ },
+ ]
+ : []),
+ {
+ key: "pin",
+ label: session.pinned
+ ? t("chat.unpin", "取消置顶")
+ : t("chat.pin", "置顶"),
+ icon: session.pinned ? : ,
+ onClick: ({ domEvent }) => {
+ domEvent.stopPropagation();
+ onPin(session.id, !session.pinned);
+ },
+ },
+ {
+ key: "fork",
+ label: t("chat.fork", "分叉"),
+ icon: ,
+ disabled: itemForkDisabled,
+ title: itemForkDisabled && itemForkHint ? itemForkHint : undefined,
+ onClick: ({ domEvent }) => {
+ domEvent.stopPropagation();
+ onFork(session.id);
+ },
+ },
+ {
+ key: "rename",
+ label: t("common.rename"),
+ icon: ,
+ onClick: ({ domEvent }) => {
+ domEvent.stopPropagation();
+ setIsEditing(true);
+ },
+ },
+ {
+ key: "delete",
+ label: t("common.delete", "Delete"),
+ icon: ,
+ danger: true,
+ onClick: ({ domEvent }) => {
+ domEvent.stopPropagation();
+ confirmDeleteConversation(t, (compact) =>
+ onDelete(session.id, compact),
+ );
+ },
+ },
+ ]
+ : [];
return (
{session.name}
+ {session.contributed ? (
+
+
+
+ ) : null}
{session.pinned ? (
) : null}
-
-
-
+
+
+ ) : null}
>
)}
@@ -338,6 +375,7 @@ export default function MinimalAgentSessionNav({
);
const [searchQuery, setSearchQuery] = useState("");
+ const [editAgent, setEditAgent] = useState
(null);
const [showingHidden, setShowingHidden] = useState(false);
const [navScope, setNavScope] = useState(() =>
initialChatNavScope(
@@ -644,6 +682,25 @@ export default function MinimalAgentSessionNav({
[activeAgentId, onPinActive, patchLocal],
);
+ const handleContribute = useCallback(
+ (agentId: string, sessionId: string, contributed: boolean) => {
+ void saveSessionShared(
+ agentId,
+ sessionId,
+ contributed,
+ () => {
+ patchLocal(agentId, (prev) =>
+ prev.map((session) =>
+ session.id === sessionId ? { ...session, contributed } : session,
+ ),
+ );
+ },
+ t("chat.shareFailed", "没能改共享状态,请再试一次"),
+ );
+ },
+ [patchLocal, t],
+ );
+
if (agents.length === 0) {
return (
@@ -663,6 +720,10 @@ export default function MinimalAgentSessionNav({
return (
+
setEditAgent(null)}
+ />
togglePin(agent.agent_id)}
onNewChat={() => onNewChat(agent.agent_id)}
+ onEdit={
+ canEditExpertFromChat(agent)
+ ? () => setEditAgent(agent)
+ : undefined
+ }
onHide={
canHide(agent) &&
!hiddenAgents.some((row) => row.agent_id === agent.agent_id)
@@ -844,6 +910,10 @@ export default function MinimalAgentSessionNav({
onPin={(id, pinned) =>
handlePin(agent.agent_id, id, pinned)
}
+ onContribute={(id, contributed) =>
+ handleContribute(agent.agent_id, id, contributed)
+ }
+ shareable={Boolean(agent.is_shared)}
onFork={(id) => onFork(id, agent.agent_id)}
forkDisabled={
session.id === activeId
diff --git a/dashboard/src/pages/Chat/components/SessionList.tsx b/dashboard/src/pages/Chat/components/SessionList.tsx
index 9e056ceb6a..4b9240ca6b 100644
--- a/dashboard/src/pages/Chat/components/SessionList.tsx
+++ b/dashboard/src/pages/Chat/components/SessionList.tsx
@@ -10,10 +10,12 @@ import {
Pin,
PinOff,
Search,
+ Share2,
Trash2,
} from "lucide-react";
import cx from "classnames";
-import type { Session } from "../hooks/useSessions";
+import { type Session } from "../hooks/useSessions";
+import { saveSessionShared } from "../utils/shareSession";
import type { OctopAgent } from "../../../context/AgentContext";
import { isAgentChatReady } from "../../../utils/agentError";
import {
@@ -48,6 +50,9 @@ import ChatNavScopeTabs, { ChatNavScopeEmpty } from "./ChatNavScopeTabs";
import AgentUnreadBadge from "./AgentUnreadBadge";
import ExpertNameLabel from "./ExpertNameLabel";
import ExpertNavActions, { ExpertPinMark } from "./ExpertNavActions";
+import ChatEditExpertDrawer, {
+ canEditExpertFromChat,
+} from "./ChatEditExpertDrawer";
import {
resolveSessionWorkStatus,
type SessionWorkStatus,
@@ -67,6 +72,8 @@ interface SessionItemProps {
onRename: (id: string, name: string) => void;
onPin: (id: string, pinned: boolean) => void;
onFork: (id: string) => void;
+ onContribute: (id: string, contributed: boolean) => void;
+ shareable: boolean;
forkDisabled?: boolean;
forkDisabledHint?: string;
}
@@ -80,6 +87,8 @@ const SessionItem = memo(function SessionItem({
onRename,
onPin,
onFork,
+ onContribute,
+ shareable,
forkDisabled,
forkDisabledHint,
}: SessionItemProps) {
@@ -113,52 +122,70 @@ const SessionItem = memo(function SessionItem({
const itemForkHint = !session.hasActivity
? t("chat.forkNoAssistant")
: forkDisabledHint;
+ const owned = session.owned !== false;
- const menuItems: MenuProps["items"] = [
- {
- key: "pin",
- label: session.pinned
- ? t("chat.unpin", "取消置顶")
- : t("chat.pin", "置顶"),
- icon: session.pinned ? : ,
- onClick: ({ domEvent }) => {
- domEvent.stopPropagation();
- onPin(session.id, !session.pinned);
- },
- },
- {
- key: "fork",
- label: t("chat.fork", "分叉"),
- icon: ,
- disabled: itemForkDisabled,
- title: itemForkDisabled && itemForkHint ? itemForkHint : undefined,
- onClick: ({ domEvent }) => {
- domEvent.stopPropagation();
- onFork(session.id);
- },
- },
- {
- key: "rename",
- label: t("common.rename"),
- icon: ,
- onClick: ({ domEvent }) => {
- domEvent.stopPropagation();
- setIsEditing(true);
- },
- },
- {
- key: "delete",
- label: t("common.delete", "Delete"),
- icon: ,
- danger: true,
- onClick: ({ domEvent }) => {
- domEvent.stopPropagation();
- confirmDeleteConversation(t, (compact) =>
- onDelete(session.id, compact),
- );
- },
- },
- ];
+ const menuItems: MenuProps["items"] = owned
+ ? [
+ ...(shareable
+ ? [
+ {
+ key: "contribute",
+ label: session.contributed
+ ? t("chat.uncontribute", "取消共享")
+ : t("chat.contribute", "共享会话"),
+ icon: ,
+ onClick: (event: { domEvent: { stopPropagation(): void } }) => {
+ event.domEvent.stopPropagation();
+ onContribute(session.id, !session.contributed);
+ },
+ },
+ ]
+ : []),
+ {
+ key: "pin",
+ label: session.pinned
+ ? t("chat.unpin", "取消置顶")
+ : t("chat.pin", "置顶"),
+ icon: session.pinned ? : ,
+ onClick: ({ domEvent }) => {
+ domEvent.stopPropagation();
+ onPin(session.id, !session.pinned);
+ },
+ },
+ {
+ key: "fork",
+ label: t("chat.fork", "分叉"),
+ icon: ,
+ disabled: itemForkDisabled,
+ title: itemForkDisabled && itemForkHint ? itemForkHint : undefined,
+ onClick: ({ domEvent }) => {
+ domEvent.stopPropagation();
+ onFork(session.id);
+ },
+ },
+ {
+ key: "rename",
+ label: t("common.rename"),
+ icon: ,
+ onClick: ({ domEvent }) => {
+ domEvent.stopPropagation();
+ setIsEditing(true);
+ },
+ },
+ {
+ key: "delete",
+ label: t("common.delete", "Delete"),
+ icon: ,
+ danger: true,
+ onClick: ({ domEvent }) => {
+ domEvent.stopPropagation();
+ confirmDeleteConversation(t, (compact) =>
+ onDelete(session.id, compact),
+ );
+ },
+ },
+ ]
+ : [];
return (
{session.name}
+ {session.contributed ? (
+
+
+
+ ) : null}
{session.pinned ? (
) : null}
-
-
-
+
+
+ ) : null}
>
)}
@@ -253,12 +290,14 @@ interface AgentCardProps {
onRename: (id: string, name: string) => void;
onPin: (id: string, pinned: boolean) => void;
onFork: (id: string, agentId?: string | null) => void;
+ onContribute: (id: string, contributed: boolean) => void;
activeForkDisabled?: boolean;
activeForkDisabledHint?: string;
onHide?: () => void;
onUnhide?: () => void;
pinned?: boolean;
onTogglePin?: () => void;
+ onEdit?: () => void;
liveWorkingIds: ReadonlySet;
}
@@ -277,12 +316,14 @@ function ActiveAgentCard({
onRename,
onPin,
onFork,
+ onContribute,
activeForkDisabled,
activeForkDisabledHint,
onHide,
onUnhide,
pinned = false,
onTogglePin,
+ onEdit,
liveWorkingIds,
}: AgentCardProps) {
const { t } = useTranslation();
@@ -359,6 +400,7 @@ function ActiveAgentCard({
onNewChat={() => onNewChat(agent.agent_id)}
onHide={onHide}
onUnhide={onUnhide}
+ onEdit={onEdit}
/>
) : null}
@@ -397,6 +439,8 @@ function ActiveAgentCard({
onDelete={onDelete}
onRename={onRename}
onPin={onPin}
+ onContribute={onContribute}
+ shareable={Boolean(agent.is_shared)}
onFork={(id) => onFork(id, agent.agent_id)}
forkDisabled={
activeId === s.id ? activeForkDisabled : undefined
@@ -433,6 +477,7 @@ interface AgentRowProps {
onUnhide?: () => void;
pinned?: boolean;
onTogglePin?: () => void;
+ onEdit?: () => void;
onOpenUnread: () => void;
}
@@ -444,6 +489,7 @@ function InactiveAgentRow({
onUnhide,
pinned = false,
onTogglePin,
+ onEdit,
onOpenUnread,
}: AgentRowProps) {
const accent = agent.color || "#6366f1";
@@ -496,6 +542,7 @@ function InactiveAgentRow({
onNewChat={onNewChat}
onHide={onHide}
onUnhide={onUnhide}
+ onEdit={onEdit}
/>
) : null}
@@ -552,6 +599,7 @@ export default function SessionList({
const liveWorkingIds = useSessionWorkIds();
const [searchQuery, setSearchQuery] = useState("");
const [showingHidden, setShowingHidden] = useState(false);
+ const [editAgent, setEditAgent] = useState
(null);
const [navScope, setNavScope] = useState(() =>
initialChatNavScope(
agents.find((agent) => agent.agent_id === activeAgentId),
@@ -666,6 +714,24 @@ export default function SessionList({
},
[catalog],
);
+ const contributeSession = useCallback(
+ (agentId: string, id: string, contributed: boolean) => {
+ void saveSessionShared(
+ agentId,
+ id,
+ contributed,
+ () => {
+ catalog.patch(agentId, (prev) =>
+ prev.map((session) =>
+ session.id === id ? { ...session, contributed } : session,
+ ),
+ );
+ },
+ t("chat.shareFailed", "没能改共享状态,请再试一次"),
+ );
+ },
+ [catalog, t],
+ );
const renderAgentRow = (agent: OctopAgent, hiddenRow: boolean) => {
const isActive = agent.agent_id === activeAgentId;
@@ -708,6 +774,9 @@ export default function SessionList({
? onPin
: (id, pinned) => pinOther(agent.agent_id, id, pinned)
}
+ onContribute={(id, contributed) =>
+ contributeSession(agent.agent_id, id, contributed)
+ }
onFork={onFork}
activeForkDisabled={activeForkDisabled}
activeForkDisabledHint={activeForkDisabledHint}
@@ -719,6 +788,9 @@ export default function SessionList({
onUnhide={hiddenRow ? () => unhide(agent.agent_id) : undefined}
pinned={isPinned(agent.agent_id)}
onTogglePin={() => togglePin(agent.agent_id)}
+ onEdit={
+ canEditExpertFromChat(agent) ? () => setEditAgent(agent) : undefined
+ }
liveWorkingIds={liveWorkingIds}
/>
);
@@ -735,6 +807,9 @@ export default function SessionList({
onUnhide={hiddenRow ? () => unhide(agent.agent_id) : undefined}
pinned={isPinned(agent.agent_id)}
onTogglePin={() => togglePin(agent.agent_id)}
+ onEdit={
+ canEditExpertFromChat(agent) ? () => setEditAgent(agent) : undefined
+ }
onOpenUnread={() => {
void openAgentUnread(
agent.agent_id,
@@ -748,6 +823,10 @@ export default function SessionList({
return (
+
setEditAgent(null)}
+ />
{agents.length > 0 ? (
,
+ )
+ ) {
+ notify(state);
+ return;
+ }
handleHarnessChunk(state, data, sessionId);
if (
isHostTurnTerminal(
@@ -3869,6 +3882,53 @@ function dropOptimisticSteerMessages(
if (next.length !== state.messages.length) state.messages = next;
}
+function authorFromFrame(raw: unknown): ChatMessage["author"] {
+ if (!raw || typeof raw !== "object") return undefined;
+ const row = raw as {
+ user_id?: unknown;
+ display_name?: unknown;
+ username?: unknown;
+ avatar_url?: unknown;
+ avatar_icon?: unknown;
+ };
+ if (typeof row.user_id !== "number" || row.user_id <= 0) return undefined;
+ return {
+ userId: row.user_id,
+ displayName: typeof row.display_name === "string" ? row.display_name : "",
+ username: typeof row.username === "string" ? row.username : "",
+ avatarUrl: typeof row.avatar_url === "string" ? row.avatar_url : null,
+ avatarIcon: typeof row.avatar_icon === "string" ? row.avatar_icon : null,
+ };
+}
+
+/** Show someone else's question as soon as their turn starts. */
+function applyRemoteUserFrame(
+ state: SessionStreamState,
+ data: Record,
+): boolean {
+ if (String(data.type || "") !== "user") return false;
+ if ((data.meta as { steer?: boolean } | undefined)?.steer) return false;
+ const messageId = String(data.message_id || "").trim();
+ if (!messageId) return false;
+ if (state.messages.some((message) => message.id === messageId)) return true;
+ const content = String(data.content || "");
+ const attachments = attachmentsFromSteerFrame(data.attachments);
+ if (!content && (!attachments || attachments.length === 0)) return true;
+ state.messages = [
+ ...state.messages,
+ {
+ id: messageId,
+ role: "user",
+ content,
+ attachments,
+ author: authorFromFrame(data.author),
+ status: "done",
+ timestamp: Date.now(),
+ },
+ ];
+ return true;
+}
+
function applySteerProtocolFrame(
state: SessionStreamState,
data: Record,
diff --git a/dashboard/src/pages/Chat/hooks/sseHelpers.ts b/dashboard/src/pages/Chat/hooks/sseHelpers.ts
index 910fb59865..13b250a8ae 100644
--- a/dashboard/src/pages/Chat/hooks/sseHelpers.ts
+++ b/dashboard/src/pages/Chat/hooks/sseHelpers.ts
@@ -134,10 +134,20 @@ export function parseDecisionNotice(data: unknown): DecisionNotice | null {
};
}
+export interface MessageAuthor {
+ userId: number;
+ displayName: string;
+ username: string;
+ avatarUrl?: string | null;
+ avatarIcon?: string | null;
+}
+
export interface ChatMessage {
id: string;
role: "user" | "assistant" | "system" | "tool";
content: string;
+ /** Who asked this question. Shared conversations use it for the portrait. */
+ author?: MessageAuthor;
type?: string;
/** Structured content blocks for multi-part messages (thinking + text). */
contentBlocks?: ContentBlockItem[];
diff --git a/dashboard/src/pages/Chat/hooks/useChat.ts b/dashboard/src/pages/Chat/hooks/useChat.ts
index f2e1c96fe6..8532d0f95c 100644
--- a/dashboard/src/pages/Chat/hooks/useChat.ts
+++ b/dashboard/src/pages/Chat/hooks/useChat.ts
@@ -5,6 +5,7 @@ import {
useSyncExternalStore,
useEffect,
} from "react";
+import { useCurrentUser } from "../../../hooks/useCurrentUser";
import type {
MessageMetadata,
TokenUsage,
@@ -391,6 +392,25 @@ function enrichAttachmentPreviewUrls(
});
}
+function messageAuthor(raw: unknown): ChatMessage["author"] {
+ if (!raw || typeof raw !== "object") return undefined;
+ const row = raw as {
+ user_id?: unknown;
+ display_name?: unknown;
+ username?: unknown;
+ avatar_url?: unknown;
+ avatar_icon?: unknown;
+ };
+ if (typeof row.user_id !== "number" || row.user_id <= 0) return undefined;
+ return {
+ userId: row.user_id,
+ displayName: typeof row.display_name === "string" ? row.display_name : "",
+ username: typeof row.username === "string" ? row.username : "",
+ avatarUrl: typeof row.avatar_url === "string" ? row.avatar_url : null,
+ avatarIcon: typeof row.avatar_icon === "string" ? row.avatar_icon : null,
+ };
+}
+
function convertCallEntries(entries: CallEntry[]): ChatMessage[] {
const raw: InternalChatMessage[] = entries.map((entry, index) => {
const tool = extractToolData(entry.content);
@@ -495,6 +515,7 @@ function convertCallEntries(entries: CallEntry[]): ChatMessage[] {
? entry.speaker_agent_id.trim()
: undefined,
teamWrapup: Boolean(entry.team_wrapup),
+ author: messageAuthor(entry.author),
decision: parseDecisionNotice(entry.decision) ?? undefined,
editedFiles: Array.isArray(entry.edited_files)
? entry.edited_files
@@ -700,6 +721,13 @@ export function convertHistoryMessages(
team_wrapup?: boolean;
edited_files?: string[];
decision?: unknown;
+ author?: {
+ user_id?: number;
+ display_name?: string | null;
+ username?: string | null;
+ avatar_url?: string | null;
+ avatar_icon?: string | null;
+ };
}>,
agentId?: string,
): ChatMessage[] {
@@ -730,6 +758,7 @@ export function convertHistoryMessages(
typeof message.agent_id === "string" && message.agent_id.trim()
? message.agent_id.trim()
: undefined,
+ author: message.author,
team_wrapup: message.team_wrapup === true,
decision: message.decision,
edited_files: Array.isArray(message.edited_files)
@@ -874,6 +903,7 @@ export function useChat(
isTeamRoom = false,
) {
const stableSessionId = sessionId || "__empty__";
+ const currentUser = useCurrentUser();
useEffect(() => {
chatStore.setSessionTeamRoom(stableSessionId, isTeamRoom);
}, [stableSessionId, isTeamRoom]);
@@ -976,6 +1006,16 @@ export function useChat(
attachments:
attachments && attachments.length > 0 ? attachments : undefined,
composerContext,
+ author:
+ currentUser && currentUser.id > 0
+ ? {
+ userId: currentUser.id,
+ displayName: currentUser.display_name ?? "",
+ username: currentUser.username ?? "",
+ avatarUrl: currentUser.avatar_url,
+ avatarIcon: currentUser.avatar_icon,
+ }
+ : undefined,
status: "done",
timestamp: Date.now(),
};
@@ -1003,7 +1043,7 @@ export function useChat(
userMsg.id,
);
},
- [stableSessionId],
+ [currentUser, stableSessionId],
);
const cancelStream = useCallback(() => {
diff --git a/dashboard/src/pages/Chat/hooks/useChatComposerResources.ts b/dashboard/src/pages/Chat/hooks/useChatComposerResources.ts
index 1758a13a07..e3f2c2ce16 100644
--- a/dashboard/src/pages/Chat/hooks/useChatComposerResources.ts
+++ b/dashboard/src/pages/Chat/hooks/useChatComposerResources.ts
@@ -69,6 +69,7 @@ export function useChatComposerResources(
stickyReasoningEffort?: string | null,
stickyConversationMode?: ConversationMode | null,
stickyHitlPolicy?: HitlSessionPolicy | null,
+ persistThreadSettings = true,
) {
const user = useCurrentUser();
const currentUserId = user?.id ?? null;
@@ -543,6 +544,7 @@ export function useChatComposerResources(
}));
}
if (
+ persistThreadSettings &&
resolvedAgentId &&
activeThreadId &&
!isPendingThread(activeThreadId)
@@ -554,7 +556,13 @@ export function useChatComposerResources(
});
}
},
- [activeThreadId, availableModels, modelReasoning, resolvedAgentId],
+ [
+ activeThreadId,
+ availableModels,
+ modelReasoning,
+ persistThreadSettings,
+ resolvedAgentId,
+ ],
);
// Clear a saved thread override that this catalog no longer contains, and
@@ -601,6 +609,7 @@ export function useChatComposerResources(
}));
}
if (
+ persistThreadSettings &&
resolvedAgentId &&
activeThreadId &&
!isPendingThread(activeThreadId)
@@ -611,7 +620,7 @@ export function useChatComposerResources(
});
}
},
- [activeThreadId, resolvedAgentId, selectedModel],
+ [activeThreadId, persistThreadSettings, resolvedAgentId, selectedModel],
);
const handleConversationModeChange = useCallback(
@@ -625,6 +634,7 @@ export function useChatComposerResources(
);
}
if (
+ persistThreadSettings &&
(options?.persist ?? true) &&
resolvedAgentId &&
activeThreadId &&
@@ -635,7 +645,7 @@ export function useChatComposerResources(
});
}
},
- [activeThreadId, resolvedAgentId],
+ [activeThreadId, persistThreadSettings, resolvedAgentId],
);
const handleHitlPolicyChange = useCallback(
@@ -646,6 +656,7 @@ export function useChatComposerResources(
syncSessionHitlPolicy(activeThreadId, next);
}
if (
+ persistThreadSettings &&
(options?.persist ?? true) &&
resolvedAgentId &&
activeThreadId &&
@@ -656,7 +667,7 @@ export function useChatComposerResources(
});
}
},
- [activeThreadId, resolvedAgentId],
+ [activeThreadId, persistThreadSettings, resolvedAgentId],
);
return {
diff --git a/dashboard/src/pages/Chat/hooks/useSessions.ts b/dashboard/src/pages/Chat/hooks/useSessions.ts
index e2586961bb..1804af4d4b 100644
--- a/dashboard/src/pages/Chat/hooks/useSessions.ts
+++ b/dashboard/src/pages/Chat/hooks/useSessions.ts
@@ -31,6 +31,9 @@ export interface Session {
turnActive?: boolean;
awaitingUser?: boolean;
unreadCount?: number;
+ contributed?: boolean;
+ /** False when another user contributed this conversation. */
+ owned?: boolean;
}
/** Result of probing whether a thread exists for the current agent. */
@@ -57,6 +60,8 @@ export function toSession(row: {
turn_active?: boolean;
awaiting_user?: boolean;
unread_count?: number;
+ contributed?: boolean;
+ owned?: boolean;
}): Session {
const hasActivity =
Boolean(row.has_messages) || Boolean(row.title) || row.last_active > 0;
@@ -92,9 +97,20 @@ export function toSession(row: {
turnActive: Boolean(row.turn_active),
awaitingUser: Boolean(row.awaiting_user),
unreadCount: row.unread_count ?? 0,
+ contributed: Boolean(row.contributed),
+ owned: row.owned !== false,
};
}
+/** Update one thread already held in the chat session store. */
+export function patchStoredSession(id: string, patch: Partial) {
+ setModuleSessions((prev) =>
+ prev.map((session) =>
+ session.id === id ? { ...session, ...patch } : session,
+ ),
+ );
+}
+
/** Mirror server order: pinned first, then recency (empty chats use created_at). */
export function sortSessions(sessions: Session[]): Session[] {
return [...sessions].sort((a, b) => {
diff --git a/dashboard/src/pages/Chat/index.module.less b/dashboard/src/pages/Chat/index.module.less
index 2990b0f6d4..2dc5d0c334 100644
--- a/dashboard/src/pages/Chat/index.module.less
+++ b/dashboard/src/pages/Chat/index.module.less
@@ -335,6 +335,16 @@
background: var(--fn-bg-elevated, #fff);
}
+.sharedSessionBanner {
+ flex: none;
+ padding: 6px 16px;
+ font-size: 12px;
+ line-height: 18px;
+ color: var(--fn-text-tertiary);
+ background: var(--fn-bg-elevated, #fff);
+ border-bottom: 1px solid var(--fn-border-secondary);
+}
+
.agentNotReady {
flex: 1;
display: flex;
diff --git a/dashboard/src/pages/Chat/index.tsx b/dashboard/src/pages/Chat/index.tsx
index e51418c9ab..9cf1a7d44b 100644
--- a/dashboard/src/pages/Chat/index.tsx
+++ b/dashboard/src/pages/Chat/index.tsx
@@ -597,6 +597,7 @@ function ChatPageInner() {
composerSession?.reasoningEffort,
composerSession?.conversationMode,
composerSession?.hitlPolicy,
+ composerSession?.owned !== false,
);
const { contextMaxTokens, contextUsedTokens } = useChatContextWindow(
@@ -1539,48 +1540,60 @@ function ChatPageInner() {
isTeam={isTeamChat}
/>
) : (
- {
- setProfileAgentId(
- agentId && agentId !== resolvedAgentId ? agentId : null,
- );
- setAgentProfileOpen(true);
- }}
- isTeam={isTeamChat}
- >
- 0
- ? openFileList
- : undefined
- }
- />
-
+ <>
+ {composerSession?.contributed ? (
+
+ {t(
+ "chat.sharedSessionBanner",
+ "这条会话已共享。能打开这个专家的人都能看到,并可以继续问。",
+ )}
+
+ ) : null}
+ {
+ setProfileAgentId(
+ agentId && agentId !== resolvedAgentId ? agentId : null,
+ );
+ setAgentProfileOpen(true);
+ }}
+ isTeam={isTeamChat}
+ >
+ 0
+ ? openFileList
+ : undefined
+ }
+ />
+
+ >
)}
@@ -1861,6 +1874,7 @@ function ChatPageInner() {
onHitlPolicyChange={
hitlEnabled ? handleComposerHitlPolicyChange : undefined
}
+ lockThreadSettings={composerSession?.owned === false}
availableConnectors={isTeamChat ? undefined : chatConnectors}
selectedConnectors={isTeamChat ? [] : selectedConnectors}
onConnectorsChange={
diff --git a/dashboard/src/pages/Chat/utils/inflightTranscriptCache.ts b/dashboard/src/pages/Chat/utils/inflightTranscriptCache.ts
index f07692d484..6b288b42bd 100644
--- a/dashboard/src/pages/Chat/utils/inflightTranscriptCache.ts
+++ b/dashboard/src/pages/Chat/utils/inflightTranscriptCache.ts
@@ -38,6 +38,7 @@ function slimMessage(message: ChatMessage): ChatMessage {
? Math.round(message.durationMs)
: undefined,
speakerAgentId: message.speakerAgentId,
+ author: message.author,
teamWrapup: message.teamWrapup,
errorInfo: message.errorInfo,
toolData: message.toolData
@@ -52,6 +53,19 @@ function slimMessage(message: ChatMessage): ChatMessage {
};
}
+function parseCachedAuthor(raw: unknown): ChatMessage["author"] {
+ if (!raw || typeof raw !== "object") return undefined;
+ const row = raw as Partial>;
+ if (typeof row.userId !== "number" || row.userId <= 0) return undefined;
+ return {
+ userId: row.userId,
+ displayName: typeof row.displayName === "string" ? row.displayName : "",
+ username: typeof row.username === "string" ? row.username : "",
+ avatarUrl: typeof row.avatarUrl === "string" ? row.avatarUrl : null,
+ avatarIcon: typeof row.avatarIcon === "string" ? row.avatarIcon : null,
+ };
+}
+
function isRole(value: unknown): value is ChatMessage["role"] {
return (
value === "user" ||
@@ -107,6 +121,7 @@ function parseTail(raw: string): ChatMessage[] | null {
typeof row.speakerAgentId === "string"
? row.speakerAgentId
: undefined,
+ author: parseCachedAuthor(row.author),
teamWrapup: row.teamWrapup === true ? true : undefined,
toolData:
row.toolData && typeof row.toolData === "object"
diff --git a/dashboard/src/pages/Chat/utils/shareSession.ts b/dashboard/src/pages/Chat/utils/shareSession.ts
new file mode 100644
index 0000000000..7d0a9bc0cc
--- /dev/null
+++ b/dashboard/src/pages/Chat/utils/shareSession.ts
@@ -0,0 +1,21 @@
+import { message } from "../../../utils/antdMessage";
+import { octopThreadsApi } from "../../../api/modules/octopThreads";
+import { patchStoredSession } from "../hooks/useSessions";
+
+/** Persist the share flag and tell the user when it does not stick. */
+export async function saveSessionShared(
+ agentId: string,
+ sessionId: string,
+ contributed: boolean,
+ onSaved: () => void,
+ failedText: string,
+): Promise {
+ try {
+ await octopThreadsApi.patch(agentId, sessionId, { contributed });
+ } catch {
+ message.error(failedText);
+ return;
+ }
+ patchStoredSession(sessionId, { contributed });
+ onSaved();
+}
diff --git a/docs/projects.md b/docs/projects.md
new file mode 100644
index 0000000000..353b3345b3
--- /dev/null
+++ b/docs/projects.md
@@ -0,0 +1,103 @@
+# 项目模式设计
+
+项目是一种专家。它自己完成任务,需要时把别的专家当作工具调用。任务是这个项目下的对话。能打开项目的人看到全部任务,并可以继续问。
+
+本文是设计,尚未实现。专家上的「共享会话」已经单独落地:会话默认私有,主人可以再把某一条开放出去。那不是项目。
+
+## 区别和联系
+
+专家、团队、项目都是 `agents` 里的一行。工作区、记忆、对话都挂在这一行上。差别在谁干活、别人怎么进来、上下文怎么带。
+
+| | 专家 `kind=expert` | 团队 `kind=team` | 项目 `kind=project` |
+|---|---|---|---|
+| 是什么 | 一个人可用的专家 | 主持人加至少两名成员 | 一块共享的工作,本身也是专家 |
+| 谁干活 | 自己 | 主持人只调度,成员干活 | 自己做完;需要时再调用专家 |
+| 工具 | 干活的全套,含技能 | 只有 `agent_list`、异步 `ask_agent`、记忆、时间 | 和专家同一套 |
+| 调用专家 | 可以同步调用 | 异步派工,编制写在 `.octop/manifest.json` | 同步调用,名单写在项目配置里,可以为空 |
+| 谁能打开 | 仅自己、全部或指定分组 | 当前不能分享,只有创建者 | 和专家一样:仅自己、全部或指定分组 |
+| 对话谁能看 | 默认只有自己;主人可再共享某一条 | 只有创建者 | 能打开项目的人看到全部任务 |
+| 知识库、连接器 | 选进专家的,按当前发消息的人再滤一遍 | 主持人不挂 | 项目默认按主人调用;对话里另选的按当前用户的授权 |
+| 技能 | 挂在专家上,主人管理 | 主持人不挂技能 | 和专家一样,挂在项目上 |
+| 制品 | 专家工作区 | 各写各的工作区 | 项目工作区 |
+
+联系:
+
+- 项目和专家共用同一套技能、知识库、连接器、工作区和记忆。团队主持人是调度壳,这些能力在成员专家上。
+- 三者的准入都不是点名用户。专家和项目用「仅自己 / 全部 / 指定分组」。团队仍保持不分享。
+- 任务不另建表。专家的会话、团队房间、项目任务都是 `threads`。
+- 可调用的专家仍是普通专家。项目调用他们是一次工具返回,不是团队那种上墙派工。
+
+## 谁能用
+
+创建和编辑项目时选择可见范围,复用专家现在的「仅自己 / 全部 / 指定分组」。不单独点名用户。
+
+被选中的人可以打开项目、看到全部任务、继续追问、处理待审批。改名称、可见范围、默认知识库、默认连接器、技能和可调用专家,只有主人可以。
+
+## 知识库和连接器
+
+分成两层。
+
+项目上选中的默认知识库和默认连接器,每次任务都带上,按项目主人的身份调用。别人不用先拥有这些资源,也不会在自己的列表里看到它们,不能拿到别的专家上用。凭证仍是主人的,只在这个项目里生效。对话里不能拿掉这层默认。
+
+发消息时还可以再选。可选的只包括当前这个人自己的,以及别人已经共享给他的。这一层按该用户自己的授权调用,加在项目默认之上。
+
+因此一次任务里可以同时有两套:项目默认走主人,对话里勾上的走当前用户。
+
+今天的专家还不是这样。别人发消息时,专家上选的知识库和连接器会按这个人自己的可见范围再滤一遍。项目按上面的两层做。专家是否改成同样的默认层,不在这一版里。
+
+## 技能
+
+技能跟专家一样管理:挂在这个项目上,主人启用或停用。谁来聊都用这一份,不按用户再授权一次。
+
+## 任务
+
+一条任务就是这个项目下的一条对话。能打开项目的人默认都能看见,不必再逐条点共享。
+
+状态从这一轮运行情况读出来,不另做工单:
+
+- **进行中**:这一轮还在跑。有人追问后,从已完成回到进行中。
+- **待审批**:停在工具确认上。能看这条任务的人都可以处理。
+- **已完成**:这一轮正常结束。
+- **失败**:这一轮出错结束。现有接口若还没有失败标记,第一版先不画这个图标。
+
+创建人记在对话上。改名、置顶、删除、分叉,以及模型和审批设置,只有创建人可以。其他人可以发消息。调用专家产生的内部会话不出现在任务列表里。
+
+记忆是这个项目专家的一份,房间里的人共用。按人隔开放到后面。
+
+## 页面
+
+左侧导航增加「项目」,路径 `/projects`。
+
+列表是卡片:名称、简介、进行中和待审批的数量。主人可以新建、编辑、删除。
+
+详情列出当前绑定,主人可改,其他人只读:
+
+- 知识库
+- 连接器
+- 技能
+- 可调用的专家
+
+页头有「打开任务」,进入聊天里的这个项目。
+
+聊天侧栏的分页改为「专家 / 团队 / 项目」,用「项目」换掉「云端」。对端专家仍在「专家」里,对端团队仍在「团队」里,云端协同页面留在原入口。
+
+「项目」下展开的是任务。进行中和待审批排在前面,可筛「全部 / 进行中 / 待审批」。按钮写「新任务」。每一行有标题、状态、发起人头像,名字在悬停时出现。
+
+任务页仍是现在的聊天。顶栏标「项目」,下面一行只读摘要链到项目详情。制品在右侧文件栏,读这个项目的工作区。
+
+## 实现时沿用的结构
+
+不新建项目表,也不新建任务表。
+
+- `agents.kind` 增加 `project`。现在只接受 `expert` 和 `team`。
+- 可调用专家写在该专家配置里的一份 id 列表,不用团队清单。
+- 运行时走专家装配,不套主持人的工具白名单。`ask_agent` 用专家现有的同步调用,名单之外的专家调不到;名单为空就不提供这项工具。
+- 项目线程对能打开该项目的人全部可见。追问、作者和待审批走已经做好的共享会话路径。共享专家上的逐条共享保持不变。
+- `TEAM_NOT_SHAREABLE` 继续只拦团队。
+
+## 不做
+
+- 不把项目做成共享团队,不放开团队分享。
+- 不点名用户,不用第二张成员表。
+- 不做看板、项目动态、关闭后锁定的工单。
+- 不把项目默认的知识库和连接器复制进每个用户自己的库。
diff --git a/src/octop/api/routers/chat/history.py b/src/octop/api/routers/chat/history.py
index f872b7de38..1f76333f41 100644
--- a/src/octop/api/routers/chat/history.py
+++ b/src/octop/api/routers/chat/history.py
@@ -11,7 +11,7 @@
from fastapi import APIRouter, Depends, Query, Request
from fastapi.responses import JSONResponse, Response
-from octop.api.common.agent import require_agent_row
+from octop.api.common.agent import agent_is_shared, require_agent_row
from octop.api.common.agent_workspace import resolve_agent_workspace_dir
from octop.api.deps import current_user, get_server
from octop.api.routers.chat.models import ForkThreadBody, RebindSessionBody, RenameThreadBody
@@ -29,7 +29,7 @@
from octop.infra.agents.workspace.dir import agent_facing_workspace_dir_from_config
from octop.infra.errors import ErrorCode, OctopError
from octop.infra.gateway.hitl.coordinator import pending_hitl_payload
-from octop.infra.gateway.threads import ThreadRegistry, thread_row_has_messages
+from octop.infra.gateway.threads import ThreadRegistry, thread_row_has_messages, thread_visible_to
from octop.infra.history.service import HistoryArchive
from octop.infra.history.trajectory.service import TrajectoryService
from octop.infra.utils.locale import resolve_request_locale
@@ -47,6 +47,67 @@ def _hitl_policy_payload(row: Any) -> dict[str, Any]:
return parse_hitl_session_policy(getattr(row, "hitl_policy", None)).to_dict()
+def _message_author_profile(server: Any, user_id: int) -> dict[str, Any] | None:
+ """Name and portrait for one sender. Skips mocks and missing accounts."""
+ repo = getattr(getattr(server, "services", None), "user_repo", None)
+ get = getattr(repo, "get", None)
+ if not callable(get):
+ return None
+ row = get(user_id)
+ username = getattr(row, "username", None)
+ if not isinstance(username, str) or not username:
+ return None
+ from octop.infra.users.profile_avatar import profile_avatar_url # noqa: PLC0415
+
+ avatars = getattr(getattr(server, "services", None), "avatars", None)
+ avatar_url = None
+ if callable(avatars):
+ avatar_url = profile_avatar_url(
+ avatars("user"),
+ str(user_id),
+ f"/api/users/{user_id}/avatar",
+ )
+ display_name = getattr(row, "display_name", None)
+ icon = getattr(row, "avatar_icon", None)
+ return {
+ "user_id": user_id,
+ "display_name": display_name if isinstance(display_name, str) else "",
+ "username": username,
+ "avatar_icon": icon if isinstance(icon, str) and icon else None,
+ "avatar_url": avatar_url,
+ }
+
+
+def _attach_message_authors(
+ server: Any, messages: list[dict[str, Any]], *, owner_user_id: int
+) -> None:
+ """Fill each user turn with who asked it.
+
+ Turns written before this stamp belong to the thread owner. Later turns
+ keep the person who actually sent them, so a shared conversation can show
+ a different head for each person.
+ """
+ if not isinstance(owner_user_id, int) or owner_user_id <= 0:
+ return
+ needed: set[int] = set()
+ for item in messages:
+ if item.get("role") != "user":
+ continue
+ author_id = item.get("author_user_id")
+ if not isinstance(author_id, int) or author_id <= 0:
+ author_id = owner_user_id
+ item["author_user_id"] = author_id
+ needed.add(author_id)
+ profiles = {user_id: _message_author_profile(server, user_id) for user_id in needed}
+ for item in messages:
+ if item.get("role") != "user":
+ continue
+ raw_author = item.get("author_user_id")
+ profile = profiles.get(raw_author) if isinstance(raw_author, int) else None
+ if profile is not None:
+ item["author"] = profile
+
+
def _history_migration_payload(server: Any, *, agent_id: str, user_id: int) -> dict[str, Any]:
repo = server.services.thread_message_repo
summary = repo.migration_summary(
@@ -87,14 +148,28 @@ def _agent_facing_workspace_dir(server: Any, agent_id: str) -> Path:
def _require_thread(
- server: Any, agent_id: str, thread_id: str, user: Any, as_user: int | None
+ server: Any,
+ agent_id: str,
+ thread_id: str,
+ user: Any,
+ as_user: int | None,
+ *,
+ write: bool = False,
) -> Any:
+ """Load a thread the caller may open.
+
+ ``write`` is the owner's management actions (rename, delete, fork, contribute).
+ A contributed thread stays readable and continuable by anyone who can open the expert.
+ """
require_agent_row(agent_id, user=user, as_user=as_user, server=server)
row = server.app_runtime.gateway.thread_registry.get_thread(thread_id)
if row is None or row.agent_id != agent_id:
raise OctopError(ErrorCode.AGENT_NOT_FOUND, f"thread {thread_id!r} not found")
effective_uid = as_user if as_user is not None else user.id
- if row.user_id != effective_uid:
+ if write:
+ if row.user_id != effective_uid:
+ raise OctopError(ErrorCode.FORBIDDEN, "thread not owned by user")
+ elif not thread_visible_to(row, effective_uid):
raise OctopError(ErrorCode.FORBIDDEN, "thread not owned by user")
return row
@@ -115,14 +190,18 @@ async def list_threads(
require_agent_row(agent_id, user=user, as_user=as_user, server=server)
thread_registry = server.app_runtime.gateway.thread_registry
effective_uid = as_user if as_user is not None else user.id
- rows = thread_registry.list_threads(agent_id=agent_id, user_id=effective_uid, limit=limit)
+ rows = thread_registry.list_visible_threads(
+ agent_id=agent_id, user_id=effective_uid, limit=limit
+ )
bound = thread_registry.get_bound_thread_id(
ThreadRegistry.dashboard_key(agent_id=agent_id, user_id=effective_uid)
)
workspace_dir = _agent_facing_workspace_dir(server, agent_id)
hub = server.app_runtime.gateway.ws_hub
- awaiting_ids = server.app_runtime.gateway.processor.hitl_coordinator.store.pending_thread_ids(
- agent_id=agent_id, user_id=effective_uid
+ hitl_store = server.app_runtime.gateway.processor.hitl_coordinator.store
+ awaiting_ids = hitl_store.pending_thread_ids(agent_id=agent_id, user_id=effective_uid)
+ shared_awaiting_ids = hitl_store.pending_thread_ids(
+ agent_id=agent_id, user_id=effective_uid, any_user=True
)
# title / last_active 只能说明「建过会话」,不能说明「有内容」:
# 有些 thread 有标题但从未落过消息,点开就是空白。这里补一次真实计数。
@@ -150,6 +229,8 @@ def _has_messages(row: Any) -> bool:
"has_messages": _has_messages(r),
"pinned": r.pinned,
"unread_count": int(unread.get(r.thread_id, 0)),
+ "contributed": bool(r.contributed),
+ "owned": r.user_id == effective_uid,
"model_ref": r.model_ref,
"reasoning_mode": r.reasoning_mode,
"reasoning_effort": r.reasoning_effort,
@@ -157,7 +238,8 @@ def _has_messages(row: Any) -> bool:
"pending_plan_path": r.pending_plan_path,
"hitl_policy": _hitl_policy_payload(r),
"turn_active": hub.is_turn_active(r.thread_id),
- "awaiting_user": r.thread_id in awaiting_ids,
+ "awaiting_user": r.thread_id
+ in (shared_awaiting_ids if r.contributed else awaiting_ids),
**thread_artifacts_payload(
r.artifacts,
workspace_dir,
@@ -411,11 +493,12 @@ async def _work() -> None:
user=user,
)
effective_uid = as_user if as_user is not None else user.id
+ _attach_message_authors(server, messages, owner_user_id=row.user_id)
hitl_pending = pending_hitl_payload(
server.app_runtime.gateway.processor.hitl_coordinator.store,
thread_id=thread_id,
agent_id=agent_id,
- user_id=effective_uid,
+ user_id=None if row.contributed else effective_uid,
)
workspace_dir = _agent_facing_workspace_dir(server, agent_id)
return {
@@ -455,7 +538,8 @@ async def mark_thread_read(
) -> None:
"""Clear unread message count for a thread (e.g. when the user opens it in the dashboard)."""
_require_thread(server, agent_id, thread_id, user, as_user)
- server.app_runtime.gateway.thread_registry.mark_thread_read(thread_id)
+ effective_uid = as_user if as_user is not None else user.id
+ server.app_runtime.gateway.thread_registry.mark_thread_read_for_user(thread_id, effective_uid)
@router.post(
@@ -514,7 +598,7 @@ async def fork_thread(
ErrorCode.SLASH_BAD_ARGS,
"message_id or assistant_turns_from_end is required",
)
- row = _require_thread(server, agent_id, thread_id, user, as_user)
+ row = _require_thread(server, agent_id, thread_id, user, as_user, write=True)
effective_uid = as_user if as_user is not None else user.id
harness = server.app_runtime.agent_registry.get_agent(agent_id)
return await fork_dashboard_thread(
@@ -542,7 +626,10 @@ async def rebind_session(
_require_thread(server, agent_id, body.thread_id, user, as_user=None)
sk = ThreadRegistry.dashboard_key(agent_id=agent_id, user_id=user.id)
await server.app_runtime.gateway.thread_registry.rebind(
- session_key=sk, thread_id=body.thread_id, agent_id=agent_id
+ session_key=sk,
+ thread_id=body.thread_id,
+ agent_id=agent_id,
+ acting_user_id=user.id,
)
return {"session_key": sk, "thread_id": body.thread_id}
@@ -593,6 +680,7 @@ async def patch_thread(
) -> dict[str, Any]:
"""Update sidebar metadata or sticky composer settings for a thread."""
row = _require_thread(server, agent_id, thread_id, user, as_user)
+ effective_uid = as_user if as_user is not None else user.id
composer_fields = {
"model_ref",
"reasoning_mode",
@@ -600,15 +688,21 @@ async def patch_thread(
"conversation_mode",
"hitl_policy",
}
+ managing = bool(body.model_fields_set)
+ if managing and row.user_id != effective_uid:
+ raise OctopError(ErrorCode.FORBIDDEN, "thread not owned by user")
if (
body.title is None
and body.pinned is None
+ and "contributed" not in body.model_fields_set
and not body.model_fields_set.intersection(composer_fields)
):
return {
"thread_id": thread_id,
"title": row.title,
"pinned": row.pinned,
+ "contributed": bool(row.contributed),
+ "owned": row.user_id == effective_uid,
"model_ref": row.model_ref,
"reasoning_mode": row.reasoning_mode,
"reasoning_effort": row.reasoning_effort,
@@ -617,6 +711,15 @@ async def patch_thread(
"hitl_policy": _hitl_policy_payload(row),
}
registry = server.app_runtime.gateway.thread_registry
+ if "contributed" in body.model_fields_set:
+ if body.contributed:
+ agent_row = require_agent_row(agent_id, user=user, as_user=as_user, server=server)
+ if not agent_is_shared(agent_row):
+ raise OctopError(
+ ErrorCode.THREAD_CONTRIBUTE_REQUIRES_SHARE,
+ "only a shared expert can accept a contributed conversation",
+ )
+ registry.set_contributed(thread_id, bool(body.contributed))
if body.title is not None:
registry.update_title(thread_id, body.title)
if body.pinned is not None:
@@ -672,6 +775,8 @@ async def patch_thread(
"thread_id": thread_id,
"title": updated.title,
"pinned": updated.pinned,
+ "contributed": bool(updated.contributed),
+ "owned": updated.user_id == effective_uid,
"model_ref": updated.model_ref,
"reasoning_mode": updated.reasoning_mode,
"reasoning_effort": updated.reasoning_effort,
@@ -702,7 +807,7 @@ async def delete_thread(
maintenance reclaims the free space later, once the freelist is large
enough. Omitting ``compact`` keeps the previous empty 204.
"""
- _require_thread(server, agent_id, thread_id, user, as_user)
+ _require_thread(server, agent_id, thread_id, user, as_user, write=True)
if server.app_runtime.gateway.ws_hub.is_turn_active(thread_id):
raise OctopError(
ErrorCode.THREAD_TURN_ACTIVE,
diff --git a/src/octop/api/routers/chat/models.py b/src/octop/api/routers/chat/models.py
index d5b7482145..e221151c5f 100644
--- a/src/octop/api/routers/chat/models.py
+++ b/src/octop/api/routers/chat/models.py
@@ -194,6 +194,10 @@ class ForkThreadBody(BaseModel):
class RenameThreadBody(BaseModel):
title: str | None = None
pinned: bool | None = None
+ contributed: bool | None = Field(
+ default=None,
+ description="Share this conversation with other users of the expert.",
+ )
model_ref: str | None = None
reasoning_mode: Literal["auto", "enabled", "disabled"] | None = None
reasoning_effort: str | None = None
diff --git a/src/octop/api/routers/chat/routes.py b/src/octop/api/routers/chat/routes.py
index 4bf975af48..22a20a1657 100644
--- a/src/octop/api/routers/chat/routes.py
+++ b/src/octop/api/routers/chat/routes.py
@@ -233,14 +233,16 @@ async def resume_hitl(
server: Any = Depends(get_server),
) -> StreamingResponse:
"""Resume a paused human-in-the-loop tool approval and stream subsequent chunks."""
- assert_agent_access(server, agent_id, user)
+ from octop.api.routers.chat.history import _require_thread # noqa: PLC0415
+
+ thread_row = _require_thread(server, agent_id, body.thread_id, user, None)
processor = server.app_runtime.gateway.processor
hitl_coordinator = processor.hitl_coordinator
requested_id = (body.pending_id or "").strip()
pending = hitl_coordinator.store.resolve_pending_for_thread(
body.thread_id,
agent_id=agent_id,
- user_id=user.id,
+ user_id=None if thread_row.contributed else user.id,
pending_id=requested_id or None,
)
if requested_id and pending is None:
@@ -268,7 +270,7 @@ async def missing() -> AsyncIterator[str]:
if reason is not None:
raise HTTPException(status_code=400, detail=reason)
- if body.hitl_policy is not None:
+ if body.hitl_policy is not None and thread_row.user_id == user.id:
hitl_coordinator.session_policies.set(body.thread_id, body.hitl_policy.model_dump())
async def gen() -> AsyncIterator[str]:
diff --git a/src/octop/api/routers/chat/serialize.py b/src/octop/api/routers/chat/serialize.py
index d1b69a798e..ddfec14bc9 100644
--- a/src/octop/api/routers/chat/serialize.py
+++ b/src/octop/api/routers/chat/serialize.py
@@ -18,6 +18,7 @@
from octop.i18n.domains.attachment import attachment_empty_image
from octop.infra.agents.threads.context_breakdown import usage_dict_from_message
from octop.infra.gateway.process.message_keys import (
+ AUTHOR_USER_ID_KEY,
CHECKPOINT_TS_KEY,
COMPOSER_CTX_KEY,
INBOUND_ATTACHMENTS_KEY,
@@ -918,6 +919,17 @@ def _split_string_thinking(text: str) -> list[dict[str, Any]]:
return blocks
+def _author_user_id(raw: Any) -> int | None:
+ if isinstance(raw, bool):
+ return None
+ if isinstance(raw, int) and raw > 0:
+ return raw
+ if isinstance(raw, str) and raw.isdigit():
+ value = int(raw)
+ return value if value > 0 else None
+ return None
+
+
def _serialize_history_message(
msg: Any,
*,
@@ -1012,6 +1024,9 @@ def _serialize_history_message(
entry["composer_context"] = raw_ctx
if has_user_attachments:
entry["inbound_attachments"] = raw_att
+ author_id = _author_user_id(additional_kwargs.get(AUTHOR_USER_ID_KEY))
+ if author_id is not None:
+ entry["author_user_id"] = author_id
if additional_kwargs.get(STREAM_ERROR_FLAG):
entry["status"] = "error"
code = additional_kwargs.get(STREAM_ERROR_CODE_KEY)
diff --git a/src/octop/api/routers/chat/turn.py b/src/octop/api/routers/chat/turn.py
index d033f49d17..82d1fc74f8 100644
--- a/src/octop/api/routers/chat/turn.py
+++ b/src/octop/api/routers/chat/turn.py
@@ -31,7 +31,7 @@
build_composer_context,
)
from octop.infra.gateway.process.usage_record import extract_usage_from_chunk
-from octop.infra.gateway.threads import ThreadRegistry
+from octop.infra.gateway.threads import ThreadRegistry, thread_visible_to
from octop.infra.gateway.ws import WS_CHANNEL_ID
__all__ = [
@@ -71,9 +71,14 @@ async def resolve_thread_id(
row = thread_registry.get_thread(thread_id)
if row is None or row.agent_id != agent_id:
raise OctopError(ErrorCode.AGENT_NOT_FOUND, f"thread {thread_id!r} not found")
- if row.user_id != user_id:
+ if not thread_visible_to(row, user_id):
raise OctopError(ErrorCode.FORBIDDEN, "thread not owned by user")
- await thread_registry.rebind(session_key=sk, thread_id=thread_id, agent_id=agent_id)
+ await thread_registry.rebind(
+ session_key=sk,
+ thread_id=thread_id,
+ agent_id=agent_id,
+ acting_user_id=user_id,
+ )
return thread_id, sk
bound = thread_registry.get_bound_thread_id(sk)
if bound:
diff --git a/src/octop/api/routers/chat/ws.py b/src/octop/api/routers/chat/ws.py
index 410ac67e9e..0460a85ab5 100644
--- a/src/octop/api/routers/chat/ws.py
+++ b/src/octop/api/routers/chat/ws.py
@@ -27,6 +27,7 @@
from octop.infra.errors import OctopError
from octop.infra.gateway.steer import SteerAdmitOk, SteerAdmitReject, SteerCoordinator
from octop.infra.gateway.steer.types import preview_text
+from octop.infra.gateway.threads import thread_visible_to
from octop.infra.gateway.ws import WS_CHANNEL_ID
logger = logging.getLogger(__name__)
@@ -34,6 +35,10 @@
router = APIRouter()
+def _ws_thread_visible(row: Any, agent_id: str, user_id: int) -> bool:
+ return row is not None and row.agent_id == agent_id and thread_visible_to(row, user_id)
+
+
@router.websocket("/agents/{agent_id}/chat/ws")
async def dashboard_chat_ws(
websocket: WebSocket,
@@ -108,7 +113,7 @@ async def send_frame(frame: dict[str, Any]) -> None:
await send_frame({"type": "error", "message": "subscribe requires thread_id"})
continue
row = gateway.thread_registry.get_thread(thread_id)
- if row is None or row.agent_id != agent_id or row.user_id != user.id:
+ if not _ws_thread_visible(row, agent_id, user.id):
await send_frame(
{"type": "error", "message": f"thread {thread_id!r} not found"},
)
@@ -153,7 +158,7 @@ def _subscribe(tid: str = thread_id, cid: str = connection_id) -> None:
await send_frame({"type": "error", "message": "cancel requires thread_id"})
continue
row = gateway.thread_registry.get_thread(thread_id)
- if row is None or row.agent_id != agent_id or row.user_id != user.id:
+ if not _ws_thread_visible(row, agent_id, user.id):
await send_frame(
{"type": "error", "message": f"thread {thread_id!r} not found"},
)
@@ -754,7 +759,7 @@ async def _handle_steer_remove(
)
return
row = gateway.thread_registry.get_thread(thread_id)
- if row is None or row.agent_id != agent_id or row.user_id != user_id:
+ if not _ws_thread_visible(row, agent_id, user_id):
await send_frame(
{
"type": "steer.ack",
diff --git a/src/octop/api/routers/users.py b/src/octop/api/routers/users.py
index d7ec7a6f14..5ebf5aa149 100644
--- a/src/octop/api/routers/users.py
+++ b/src/octop/api/routers/users.py
@@ -16,7 +16,6 @@
from octop.infra.users.identity import Role, User
from octop.infra.users.permissions import (
PERMISSIONS,
- effective_permissions,
expand_permission_grants,
)
from octop.infra.users.resource_policy import (
@@ -688,11 +687,10 @@ async def upload_user_avatar(
@router.get("/{user_id}/avatar")
async def get_user_avatar(
user_id: int,
- actor: Any = Depends(current_user),
+ _: Any = Depends(current_user),
server: Any = Depends(get_server),
) -> Any:
- if actor.id != user_id and "users" not in effective_permissions(actor):
- raise OctopError(ErrorCode.FORBIDDEN, "not allowed to read this avatar")
+ """Portrait for any signed-in user. Shared conversations show each sender."""
from octop.infra.users.profile_avatar import avatar_response
if server.user_manager.get_row(user_id) is None:
diff --git a/src/octop/i18n/en.json b/src/octop/i18n/en.json
index 77ed010359..29118c89c4 100644
--- a/src/octop/i18n/en.json
+++ b/src/octop/i18n/en.json
@@ -420,6 +420,7 @@
"AGENT_NOT_RUNNING": "This expert is not enabled.",
"CHECKPOINT_DELETE_FAILED": "Conversation data was not deleted. The thread is still here; try again.",
"THREAD_TURN_ACTIVE": "A reply is still in progress. Stop it, then delete this conversation.",
+ "THREAD_CONTRIBUTE_REQUIRES_SHARE": "Only a shared expert can share a conversation with other users.",
"AGENT_FAILED": "Agent failed to start.",
"AGENT_BUSY": "Agent is busy.",
"AGENT_NAME_TAKEN": "This name is already in use. Please choose another.",
diff --git a/src/octop/i18n/zh.json b/src/octop/i18n/zh.json
index e00d92aee0..957f6ec995 100644
--- a/src/octop/i18n/zh.json
+++ b/src/octop/i18n/zh.json
@@ -420,6 +420,7 @@
"AGENT_NOT_RUNNING": "此专家未启用。",
"CHECKPOINT_DELETE_FAILED": "对话数据没有删除,会话已保留,请重试。",
"THREAD_TURN_ACTIVE": "回复进行中,请先停止再删除。",
+ "THREAD_CONTRIBUTE_REQUIRES_SHARE": "只有共享专家上的会话可以共享给其他用户。",
"AGENT_FAILED": "Agent 启动失败。",
"AGENT_BUSY": "Agent 正忙。",
"AGENT_NAME_TAKEN": "该名称已被使用,请换一个名称。",
diff --git a/src/octop/infra/db/migrate.py b/src/octop/infra/db/migrate.py
index 8a7e1087c4..f5b815bc0d 100644
--- a/src/octop/infra/db/migrate.py
+++ b/src/octop/infra/db/migrate.py
@@ -1676,6 +1676,13 @@ def _ensure_control_blobs_schema(db: DatabasePool) -> None:
)
+def _ensure_thread_contributed_schema(db: DatabasePool) -> None:
+ """``threads.contributed`` (v25). Idempotent for SQLite, which skips the SQL file."""
+ if not _table_exists(db, "threads"):
+ return
+ _ensure_column(db, "threads", "contributed", "INTEGER NOT NULL DEFAULT 0")
+
+
def _ensure_user_mfa_schema(db: DatabasePool) -> None:
"""MFA tables + users.mfa_* / password_version columns (v25). Idempotent."""
if not _table_exists(db, "users"):
@@ -1922,6 +1929,7 @@ def _repair_legacy_schema(db: DatabasePool) -> None:
_ensure_column(db, "threads", "reasoning_mode", "TEXT")
_ensure_column(db, "threads", "reasoning_effort", "TEXT")
_ensure_column(db, "threads", "artifacts", "TEXT NOT NULL DEFAULT '[]'")
+ _ensure_column(db, "threads", "contributed", "INTEGER NOT NULL DEFAULT 0")
_ensure_thread_conversation_mode_schema(db)
if _table_exists(db, "agents"):
_ensure_column(db, "agents", "is_shared", "INTEGER NOT NULL DEFAULT 0")
@@ -2225,6 +2233,7 @@ def _apply_sqlite_migration(db: DatabasePool, version: int, path: Path) -> None:
if version == 25:
_ensure_user_mfa_schema(db)
_ensure_instance_lease_schema(db)
+ _ensure_thread_contributed_schema(db)
with db.connect() as conn:
conn.execute("UPDATE _schema_version SET version = ?", (version,))
return
@@ -2483,6 +2492,7 @@ def run_migrations(db: DatabasePool) -> None:
_ensure_user_mfa_schema(db)
_ensure_instance_lease_schema(db)
_ensure_control_blobs_schema(db)
+ _ensure_thread_contributed_schema(db)
_grant_default_nav_permissions(db)
_grant_personalization_tab_permissions(db)
_grant_bridge_permission(db)
diff --git a/src/octop/infra/db/migrations/025_user_mfa.pg.sql b/src/octop/infra/db/migrations/025_user_mfa.pg.sql
index afd670e42f..23cea7d46e 100644
--- a/src/octop/infra/db/migrations/025_user_mfa.pg.sql
+++ b/src/octop/infra/db/migrations/025_user_mfa.pg.sql
@@ -72,6 +72,8 @@ ALTER TABLE channels ADD COLUMN IF NOT EXISTS runtime_lease_token TEXT;
ALTER TABLE channels ADD COLUMN IF NOT EXISTS runtime_lease_until BIGINT;
ALTER TABLE channels ADD COLUMN IF NOT EXISTS runtime_generation INTEGER NOT NULL DEFAULT 0;
+ALTER TABLE threads ADD COLUMN IF NOT EXISTS contributed INTEGER NOT NULL DEFAULT 0;
+
CREATE TABLE IF NOT EXISTS profile_avatars (
owner_kind TEXT NOT NULL,
owner_id TEXT NOT NULL,
diff --git a/src/octop/infra/db/migrations/025_user_mfa.sql b/src/octop/infra/db/migrations/025_user_mfa.sql
index 42647bc7fb..5707b10425 100644
--- a/src/octop/infra/db/migrations/025_user_mfa.sql
+++ b/src/octop/infra/db/migrations/025_user_mfa.sql
@@ -73,6 +73,8 @@ ALTER TABLE channels ADD COLUMN runtime_lease_token TEXT;
ALTER TABLE channels ADD COLUMN runtime_lease_until INTEGER;
ALTER TABLE channels ADD COLUMN runtime_generation INTEGER NOT NULL DEFAULT 0;
+ALTER TABLE threads ADD COLUMN contributed INTEGER NOT NULL DEFAULT 0;
+
CREATE TABLE IF NOT EXISTS profile_avatars (
owner_kind TEXT NOT NULL,
owner_id TEXT NOT NULL,
diff --git a/src/octop/infra/db/repos/sessions.py b/src/octop/infra/db/repos/sessions.py
index f2c28e46f1..0341d227e1 100644
--- a/src/octop/infra/db/repos/sessions.py
+++ b/src/octop/infra/db/repos/sessions.py
@@ -251,6 +251,13 @@ def clear_unread_for_thread(self, thread_id: str) -> None:
(thread_id,),
)
+ def clear_unread_for_user_thread(self, thread_id: str, user_id: int) -> None:
+ with self._db.transaction() as conn:
+ conn.execute(
+ "UPDATE sessions SET unread_count = 0 WHERE thread_id = ? AND user_id = ?",
+ (thread_id, user_id),
+ )
+
def clear_unread_for_agent(self, agent_id: str, user_id: int) -> None:
with self._db.transaction() as conn:
conn.execute(
diff --git a/src/octop/infra/db/repos/threads.py b/src/octop/infra/db/repos/threads.py
index 0f6649cf9b..d76aa31479 100644
--- a/src/octop/infra/db/repos/threads.py
+++ b/src/octop/infra/db/repos/threads.py
@@ -47,6 +47,7 @@ class ThreadRow:
conversation_mode: str | None = None
pending_plan_path: str | None = None
hitl_policy: str | None = None
+ contributed: bool = False
@classmethod
def from_row(cls, r: DbRow) -> ThreadRow:
@@ -66,6 +67,10 @@ def from_row(cls, r: DbRow) -> ThreadRow:
hitl_policy = r["hitl_policy"]
except (KeyError, IndexError):
hitl_policy = None
+ try:
+ contributed = bool(r["contributed"])
+ except (KeyError, IndexError):
+ contributed = False
return cls(
id=r["id"],
thread_id=r["thread_id"],
@@ -84,6 +89,7 @@ def from_row(cls, r: DbRow) -> ThreadRow:
conversation_mode=str(conversation_mode) if conversation_mode else None,
pending_plan_path=str(pending_plan_path) if pending_plan_path else None,
hitl_policy=str(hitl_policy) if hitl_policy else None,
+ contributed=contributed,
)
@@ -251,6 +257,26 @@ def list_by_agent_user(
).fetchall()
return map_rows(rows, ThreadRow)
+ def list_visible(self, *, agent_id: str, user_id: int, limit: int = 50) -> list[ThreadRow]:
+ """Own threads plus conversations contributed to this shared expert."""
+ with self._db.connect() as conn:
+ rows = conn.execute(
+ "SELECT * FROM threads WHERE agent_id = ? "
+ "AND (user_id = ? OR contributed = 1) "
+ "ORDER BY pinned DESC, "
+ "CASE WHEN last_active > 0 THEN last_active ELSE created_at END DESC, "
+ "thread_id DESC LIMIT ?",
+ (agent_id, user_id, limit),
+ ).fetchall()
+ return map_rows(rows, ThreadRow)
+
+ def set_contributed(self, thread_id: str, contributed: bool) -> None:
+ with self._db.transaction() as conn:
+ conn.execute(
+ "UPDATE threads SET contributed = ? WHERE thread_id = ?",
+ (bool_int(contributed), thread_id),
+ )
+
def list_by_session(self, *, session_key: str, limit: int = 50) -> list[ThreadRow]:
with self._db.connect() as conn:
rows = conn.execute(
diff --git a/src/octop/infra/errors.py b/src/octop/infra/errors.py
index 236da2ddc7..7478a2527c 100644
--- a/src/octop/infra/errors.py
+++ b/src/octop/infra/errors.py
@@ -38,6 +38,7 @@ class ErrorCode(StrEnum):
AGENT_NOT_RUNNING = "AGENT_NOT_RUNNING"
CHECKPOINT_DELETE_FAILED = "CHECKPOINT_DELETE_FAILED"
THREAD_TURN_ACTIVE = "THREAD_TURN_ACTIVE"
+ THREAD_CONTRIBUTE_REQUIRES_SHARE = "THREAD_CONTRIBUTE_REQUIRES_SHARE"
AGENT_FAILED = "AGENT_FAILED"
AGENT_BUSY = "AGENT_BUSY"
AGENT_NAME_TAKEN = "AGENT_NAME_TAKEN"
@@ -199,6 +200,7 @@ class ErrorCode(StrEnum):
ErrorCode.AGENT_NOT_RUNNING: 409,
ErrorCode.CHECKPOINT_DELETE_FAILED: 409,
ErrorCode.THREAD_TURN_ACTIVE: 409,
+ ErrorCode.THREAD_CONTRIBUTE_REQUIRES_SHARE: 400,
ErrorCode.AGENT_FAILED: 500,
ErrorCode.AGENT_BUSY: 409,
ErrorCode.AGENT_NAME_TAKEN: 409,
diff --git a/src/octop/infra/gateway/hitl/coordinator.py b/src/octop/infra/gateway/hitl/coordinator.py
index 1337709389..9f0d76c5b8 100644
--- a/src/octop/infra/gateway/hitl/coordinator.py
+++ b/src/octop/infra/gateway/hitl/coordinator.py
@@ -203,7 +203,7 @@ def pending_hitl_payload(
*,
thread_id: str,
agent_id: str,
- user_id: int,
+ user_id: int | None,
) -> dict[str, Any] | None:
record = store.resolve_pending_for_thread(
thread_id,
diff --git a/src/octop/infra/gateway/hitl/store.py b/src/octop/infra/gateway/hitl/store.py
index aec7ef84e3..671dfa3eeb 100644
--- a/src/octop/infra/gateway/hitl/store.py
+++ b/src/octop/infra/gateway/hitl/store.py
@@ -263,15 +263,25 @@ def list_pending_for_session(
rows.sort(key=lambda r: r.created_at, reverse=True)
return rows
- def pending_thread_ids(self, *, agent_id: str, user_id: int) -> frozenset[str]:
- """Thread ids with a still-pending HITL pause for this agent/user."""
+ def pending_thread_ids(
+ self,
+ *,
+ agent_id: str,
+ user_id: int,
+ any_user: bool = False,
+ ) -> frozenset[str]:
+ """Thread ids with a still-pending HITL pause for this agent.
+
+ ``any_user`` includes pauses opened by someone else. Callers use that
+ only for conversations that were shared with the current user.
+ """
self._gc()
now = time.time()
out: set[str] = set()
for record in self._records.values():
if record.status != "pending":
continue
- if record.user_id != user_id:
+ if not any_user and record.user_id != user_id:
continue
if now - record.created_at > self.ttl_seconds:
continue
diff --git a/src/octop/infra/gateway/process/harness_request.py b/src/octop/infra/gateway/process/harness_request.py
index abcbc512b0..6dcaec811f 100644
--- a/src/octop/infra/gateway/process/harness_request.py
+++ b/src/octop/infra/gateway/process/harness_request.py
@@ -331,7 +331,11 @@ def build_harness_request(
payload = content if content is not None else build_content(text=text, images=images)
stored_id = (message_id or "").strip() or None
+ from octop.infra.gateway.process.message_keys import AUTHOR_USER_ID_KEY # noqa: PLC0415
+
kwargs = dict(message_kwargs or {})
+ if user_id > 0:
+ kwargs[AUTHOR_USER_ID_KEY] = user_id
if isinstance(payload, list) or kwargs or stored_id:
from langchain_core.messages import HumanMessage # noqa: PLC0415
diff --git a/src/octop/infra/gateway/process/message_keys.py b/src/octop/infra/gateway/process/message_keys.py
index e039e42cf4..6a3bc5e68f 100644
--- a/src/octop/infra/gateway/process/message_keys.py
+++ b/src/octop/infra/gateway/process/message_keys.py
@@ -13,6 +13,8 @@
# Persisted on HumanMessage.additional_kwargs for dashboard history UI.
COMPOSER_CTX_KEY = "octop_composer_context"
INBOUND_ATTACHMENTS_KEY = "octop_inbound_attachments"
+# Who sent this user turn. Shared conversations render a different portrait per person.
+AUTHOR_USER_ID_KEY = "octop_author_user_id"
# Must match octop_harness.messages.CHECKPOINT_TS_KEY (epoch-ms).
CHECKPOINT_TS_KEY = "checkpoint_ts"
# Persisted on AIMessage.additional_kwargs when a stream fails mid-turn.
diff --git a/src/octop/infra/gateway/process/processor.py b/src/octop/infra/gateway/process/processor.py
index 1676b8678e..a2fa8c7d56 100644
--- a/src/octop/infra/gateway/process/processor.py
+++ b/src/octop/infra/gateway/process/processor.py
@@ -1410,6 +1410,7 @@ async def iter_turn_chunks(self, msg: InboundMessage) -> AsyncIterator[dict[str,
thread_id=thread_id,
command=msg.text,
response_lines=slash_lines,
+ user_id=user_id,
)
self._hitl.expire_pending_for_thread(thread_id, agent_id=agent_id, user_id=user_id)
self.teams.cancel_member_hitl(thread_id)
@@ -2227,12 +2228,20 @@ async def _append_slash_checkpoint(
thread_id: str,
command: str,
response_lines: list[str],
+ user_id: int = 0,
) -> None:
"""Save slash history, honoring the command's checkpoint persistence policy."""
+ from octop.infra.gateway.process.message_keys import AUTHOR_USER_ID_KEY # noqa: PLC0415
+
turn_id = new_ulid()
response = "\n".join(response_lines).strip()
+ kwargs = {AUTHOR_USER_ID_KEY: user_id} if user_id > 0 else {}
canonical: list[HumanMessage | AIMessage] = [
- HumanMessage(content=command, id=f"slash:{turn_id}:human"),
+ HumanMessage(
+ content=command,
+ id=f"slash:{turn_id}:human",
+ additional_kwargs=kwargs,
+ ),
]
if response:
canonical.append(AIMessage(content=response, id=f"slash:{turn_id}:assistant"))
diff --git a/src/octop/infra/gateway/threads.py b/src/octop/infra/gateway/threads.py
index c2991a4e60..cc70d46e35 100644
--- a/src/octop/infra/gateway/threads.py
+++ b/src/octop/infra/gateway/threads.py
@@ -270,7 +270,14 @@ def im_sessions_for_thread(self, thread_id: str) -> list[SessionRow]:
"""IM sessions bound to *thread_id* (excludes dashboard / CLI)."""
return [row for row in self.sessions_for_thread(thread_id) if self.is_im_session(row)]
- async def rebind(self, *, session_key: str, thread_id: str, agent_id: str) -> None:
+ async def rebind(
+ self,
+ *,
+ session_key: str,
+ thread_id: str,
+ agent_id: str,
+ acting_user_id: int | None = None,
+ ) -> None:
row = self._threads.get(thread_id)
if row is None:
msg = f"thread {thread_id!r} not found"
@@ -296,10 +303,14 @@ async def rebind(self, *, session_key: str, thread_id: str, agent_id: str) -> No
metadata = {"channel_type": row.channel_type, "user_id": row.user_id}
channel_id = None
if session is None:
+ session_user_id = acting_user_id if acting_user_id is not None else row.user_id
+ if acting_user_id is not None:
+ subject_id = str(acting_user_id)
+ metadata = {"channel_type": channel_type, "user_id": acting_user_id}
self._sessions.upsert(
session_key=session_key,
agent_id=agent_id,
- user_id=row.user_id,
+ user_id=session_user_id,
channel_type=channel_type,
chat_type=chat_type,
thread_id=thread_id,
@@ -436,6 +447,15 @@ def get_thread(self, thread_id: str) -> ThreadRow | None:
def list_threads(self, *, agent_id: str, user_id: int, limit: int = 50) -> list[ThreadRow]:
return self._threads.list_by_agent_user(agent_id=agent_id, user_id=user_id, limit=limit)
+ def list_visible_threads(
+ self, *, agent_id: str, user_id: int, limit: int = 50
+ ) -> list[ThreadRow]:
+ """Threads this user owns, plus ones contributed on the same expert."""
+ return self._threads.list_visible(agent_id=agent_id, user_id=user_id, limit=limit)
+
+ def set_contributed(self, thread_id: str, contributed: bool) -> None:
+ self._threads.set_contributed(thread_id, contributed)
+
def list_threads_for_session(self, *, session_key: str, limit: int = 50) -> list[ThreadRow]:
return self._threads.list_by_session(session_key=session_key, limit=limit)
@@ -495,6 +515,9 @@ def increment_unread(self, session_key: str, *, delta: int = 1) -> None:
def mark_thread_read(self, thread_id: str) -> None:
self._sessions.clear_unread_for_thread(thread_id)
+ def mark_thread_read_for_user(self, thread_id: str, user_id: int) -> None:
+ self._sessions.clear_unread_for_user_thread(thread_id, user_id)
+
def mark_agent_read(self, agent_id: str, user_id: int) -> None:
self._sessions.clear_unread_for_agent(agent_id, user_id)
@@ -509,6 +532,15 @@ def _new_thread_id() -> str:
return f"thr_{new_ulid()}"
+def thread_visible_to(row: ThreadRow, user_id: int) -> bool:
+ """Owner, or anyone who can open an expert that this thread was contributed to.
+
+ Rows that predate the column, and test fakes, have no ``contributed`` flag.
+ Those stay private to the owner.
+ """
+ return row.user_id == user_id or bool(getattr(row, "contributed", False))
+
+
def thread_row_has_messages(row: ThreadRow) -> bool:
"""Infer conversation activity from thread metadata (no checkpoint I/O).
diff --git a/src/octop/infra/gateway/ws/ws_channel.py b/src/octop/infra/gateway/ws/ws_channel.py
index e67c3c6752..91ce751f2a 100644
--- a/src/octop/infra/gateway/ws/ws_channel.py
+++ b/src/octop/infra/gateway/ws/ws_channel.py
@@ -25,7 +25,10 @@
inbound_attachments_from_parts,
is_vision_attachment,
)
-from octop.infra.gateway.process.message_keys import INBOUND_ATTACHMENTS_KEY
+from octop.infra.gateway.process.message_keys import (
+ INBOUND_ATTACHMENTS_KEY,
+ resolve_user_id_for_message,
+)
from octop.infra.gateway.steer import DiscardBundle, DrainBundle, SteerCoordinator
from octop.infra.gateway.threads import ThreadRegistry
from octop.infra.gateway.ws.ws_hub import WebSocketHub
@@ -176,6 +179,10 @@ async def handle_inbound(self, raw_payload: Any) -> None:
"thread_id": thread_id,
},
)
+ await self._hub.push_to_thread(
+ thread_id,
+ _turn_user_frame(message, thread_id, processor),
+ )
current = message
while True:
saw_tool_result = False
@@ -391,6 +398,48 @@ async def _send_media(self, subject: ChannelSubject, media: ContentPart) -> None
await self._hub.push(conn_id, frame)
+def _turn_user_frame(message: InboundMessage, thread_id: str, processor: Any) -> dict[str, Any]:
+ """Question bubble for every subscriber, including someone who did not send it."""
+ meta = message.metadata if isinstance(message.metadata, dict) else {}
+ frame: dict[str, Any] = {
+ "type": "user",
+ "content": message.text or "",
+ "thread_id": thread_id,
+ }
+ message_id = meta.get("client_message_id")
+ if isinstance(message_id, str) and message_id.strip():
+ frame["message_id"] = message_id.strip()
+ user_id = resolve_user_id_for_message(message, agent_owner_id=None)
+ if user_id > 0:
+ author: dict[str, Any] = {
+ "user_id": user_id,
+ "display_name": "",
+ "username": "",
+ "avatar_icon": None,
+ "avatar_url": f"/api/users/{user_id}/avatar",
+ }
+ repo = getattr(processor, "_user_repo", None)
+ get = getattr(repo, "get", None)
+ if callable(get):
+ row = get(user_id)
+ username = getattr(row, "username", None)
+ if isinstance(username, str):
+ author["username"] = username
+ display_name = getattr(row, "display_name", None)
+ if isinstance(display_name, str):
+ author["display_name"] = display_name
+ icon = getattr(row, "avatar_icon", None)
+ if isinstance(icon, str) and icon.strip():
+ author["avatar_icon"] = icon.strip()
+ frame["author"] = author
+ attachments = meta.get(INBOUND_ATTACHMENTS_KEY)
+ if not isinstance(attachments, list) or not attachments:
+ attachments = inbound_attachments_from_parts(message.content)
+ if attachments:
+ frame["attachments"] = attachments
+ return frame
+
+
def _push_discarded_frame(thread_id: str, bundle: DiscardBundle) -> dict[str, Any]:
return {
"type": "steer.discarded",
diff --git a/tests/unit/api/test_chat_history.py b/tests/unit/api/test_chat_history.py
index 1faf4f0bc2..079ccfe8c1 100644
--- a/tests/unit/api/test_chat_history.py
+++ b/tests/unit/api/test_chat_history.py
@@ -209,7 +209,7 @@ async def test_list_threads_derives_has_messages_from_db() -> None:
),
]
thread_registry = MagicMock()
- thread_registry.list_threads.return_value = rows
+ thread_registry.list_visible_threads.return_value = rows
thread_registry.get_bound_thread_id.return_value = None
thread_registry.unread_counts_for_threads.return_value = {"thr_used": 3}
@@ -537,3 +537,97 @@ async def _capture(_frame: dict[str, Any]) -> None:
server.app_runtime.agent_registry.delete_thread_checkpoint.assert_awaited_once_with(
"agt_1", "thr_1"
)
+
+
+@pytest.mark.asyncio
+async def test_non_owner_cannot_change_shared_thread_settings(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from octop.api.routers.chat.models import RenameThreadBody
+
+ monkeypatch.setattr(history_mod, "require_agent_row", lambda *_a, **_k: MagicMock())
+ server = MagicMock()
+ server.app_runtime.gateway.thread_registry.get_thread.return_value = MagicMock(
+ agent_id="agt_1",
+ user_id=1,
+ contributed=True,
+ )
+ body = RenameThreadBody(model_ref="prov/model")
+
+ with pytest.raises(OctopError) as exc:
+ await history_mod.patch_thread(
+ "agt_1",
+ "thr",
+ body,
+ user=MagicMock(id=2, is_admin=False),
+ server=server,
+ )
+
+ assert exc.value.code == ErrorCode.FORBIDDEN
+
+
+def test_history_authors_keep_the_sender() -> None:
+ class _User:
+ def __init__(self, username: str, display_name: str, avatar_icon: str | None) -> None:
+ self.username = username
+ self.display_name = display_name
+ self.avatar_icon = avatar_icon
+
+ users = {
+ 1: _User("ada", "Ada", None),
+ 2: _User("bob", "Bob", "doctor"),
+ }
+ server = MagicMock()
+ server.services.user_repo.get.side_effect = users.get
+ server.services.avatars.return_value.url.return_value = "/api/users/x/avatar?v=1"
+ messages: list[dict[str, Any]] = [
+ {"role": "user", "content": "old"},
+ {"role": "user", "content": "new", "author_user_id": 2},
+ {"role": "assistant", "content": "ok"},
+ ]
+
+ history_mod._attach_message_authors(server, messages, owner_user_id=1)
+
+ assert messages[0]["author"]["username"] == "ada"
+ assert messages[1]["author"]["username"] == "bob"
+ assert messages[1]["author"]["avatar_icon"] == "doctor"
+ assert "author" not in messages[2]
+
+
+@pytest.mark.asyncio
+async def test_shared_thread_hitl_resume_skips_user_filter(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from octop.api.routers.chat import routes as routes_mod
+ from octop.api.routers.chat.models import HitlResumeBody
+
+ row = MagicMock(contributed=True, user_id=1)
+ monkeypatch.setattr(history_mod, "_require_thread", lambda *_a, **_k: row)
+ server = MagicMock()
+ store = server.app_runtime.gateway.processor.hitl_coordinator.store
+ store.resolve_pending_for_thread.return_value = None
+ body = HitlResumeBody(
+ thread_id="thr",
+ decisions=[{"type": "approve"}],
+ pending_id="pend",
+ )
+
+ await routes_mod.resume_hitl(
+ "agt_1",
+ body,
+ MagicMock(),
+ user=MagicMock(id=2),
+ server=server,
+ )
+
+ assert store.resolve_pending_for_thread.call_args.kwargs["user_id"] is None
+
+ row.contributed = False
+ await routes_mod.resume_hitl(
+ "agt_1",
+ body,
+ MagicMock(),
+ user=MagicMock(id=2),
+ server=server,
+ )
+ assert store.resolve_pending_for_thread.call_args.kwargs["user_id"] == 2
diff --git a/tests/unit/db/test_repo_sessions_threads.py b/tests/unit/db/test_repo_sessions_threads.py
index fa5eba6294..949b91f869 100644
--- a/tests/unit/db/test_repo_sessions_threads.py
+++ b/tests/unit/db/test_repo_sessions_threads.py
@@ -305,3 +305,36 @@ def test_threads_hitl_policy_roundtrip(repos):
row = threads.get("thr_hitl")
assert row is not None
assert row.hitl_policy == '{"mode":"allow_all"}'
+
+
+def test_contributed_thread_is_listed_for_other_users(repos):
+ _sessions, threads = repos
+ UserRepo(threads._db).create(username="other", password_hash="h", role="user")
+ sk = ThreadRegistry.dashboard_key(agent_id="a1", user_id=1)
+ threads.insert(
+ thread_id="thr_private",
+ agent_id="a1",
+ user_id=1,
+ channel_type="dashboard",
+ session_key=sk,
+ title="mine",
+ last_active=10,
+ )
+ threads.insert(
+ thread_id="thr_shared",
+ agent_id="a1",
+ user_id=1,
+ channel_type="dashboard",
+ session_key=sk,
+ title="shared",
+ last_active=20,
+ )
+ threads.set_contributed("thr_shared", True)
+ visible = threads.list_visible(agent_id="a1", user_id=2, limit=10)
+ assert [row.thread_id for row in visible] == ["thr_shared"]
+ assert visible[0].contributed is True
+ assert threads.list_by_agent_user(agent_id="a1", user_id=2, limit=10) == []
+ owner_ids = {row.thread_id for row in threads.list_visible(agent_id="a1", user_id=1, limit=10)}
+ assert owner_ids == {"thr_private", "thr_shared"}
+ threads.set_contributed("thr_shared", False)
+ assert threads.list_visible(agent_id="a1", user_id=2, limit=10) == []
diff --git a/tests/unit/gateway/test_dashboard_ws.py b/tests/unit/gateway/test_dashboard_ws.py
index 12205df385..bc48b3a201 100644
--- a/tests/unit/gateway/test_dashboard_ws.py
+++ b/tests/unit/gateway/test_dashboard_ws.py
@@ -19,6 +19,21 @@ def _token(content: str, thread_id: str) -> dict[str, Any]:
return {"type": "token", "content": content, "thread_id": thread_id}
+def _user(content: str, thread_id: str, user_id: int = 7) -> dict[str, Any]:
+ return {
+ "type": "user",
+ "content": content,
+ "thread_id": thread_id,
+ "author": {
+ "user_id": user_id,
+ "display_name": "",
+ "username": "",
+ "avatar_icon": None,
+ "avatar_url": f"/api/users/{user_id}/avatar",
+ },
+ }
+
+
_STEER_PROTOCOL_TYPES = frozenset(
{
"turn.started",
@@ -240,6 +255,7 @@ async def iter_turn_chunks(self, msg: InboundMessage) -> AsyncIterator[dict[str,
)
await channel.handle_inbound(msg)
+ assert _user("hi", "thread-1") in frames
assert {"type": "token", "content": "hello", "thread_id": "thread-1"} in frames
assert {"type": "done", "thread_id": "thread-1"} in frames
assert frames[-1]["type"] == "turn.ended"
@@ -291,7 +307,10 @@ async def iter_turn_chunks(self, msg: InboundMessage) -> AsyncIterator[dict[str,
if a_frames:
break
await asyncio.sleep(0.01)
- assert _stream_frames(a_frames) == [_token("first", "thread-1")]
+ assert _stream_frames(a_frames) == [
+ _user("hi", "thread-1"),
+ _token("first", "thread-1"),
+ ]
assert hub.is_turn_active("thread-1") is True
hub.unsubscribe_connection("a")
@@ -350,13 +369,17 @@ async def iter_turn_chunks(self, msg: InboundMessage) -> AsyncIterator[dict[str,
if a_frames:
break
await asyncio.sleep(0.01)
- assert _stream_frames(a_frames) == [_token("first", "thread-1")]
+ assert _stream_frames(a_frames) == [
+ _user("hi", "thread-1"),
+ _token("first", "thread-1"),
+ ]
hub.subscribe("thread-1", "b")
gate.set()
await task
assert _stream_frames(a_frames) == [
+ _user("hi", "thread-1"),
_token("first", "thread-1"),
_token("second", "thread-1"),
{"type": "done", "thread_id": "thread-1"},
diff --git a/tests/unit/gateway/test_hitl_channel.py b/tests/unit/gateway/test_hitl_channel.py
index 692bd2cb4b..bb1e0a59d2 100644
--- a/tests/unit/gateway/test_hitl_channel.py
+++ b/tests/unit/gateway/test_hitl_channel.py
@@ -403,6 +403,10 @@ def test_hitl_store_resolve_pending_for_thread() -> None:
assert store.resolve_pending_for_thread("thr-a", agent_id="agent1", user_id=2) is None
assert store.pending_thread_ids(agent_id="agent1", user_id=1) == frozenset({"thr-a", "thr-b"})
assert store.pending_thread_ids(agent_id="agent1", user_id=2) == frozenset()
+ assert store.pending_thread_ids(agent_id="agent1", user_id=2, any_user=True) == frozenset(
+ {"thr-a", "thr-b"}
+ )
+ assert store.resolve_pending_for_thread("thr-a", agent_id="agent1", user_id=None) is pending
def test_hitl_store_other_thread_does_not_expire_pending() -> None:
diff --git a/tests/unit/gateway/test_message_build.py b/tests/unit/gateway/test_message_build.py
index 3ccd3ba793..45e1d27fec 100644
--- a/tests/unit/gateway/test_message_build.py
+++ b/tests/unit/gateway/test_message_build.py
@@ -103,6 +103,7 @@ def test_build_harness_request_stores_dashboard_message_id() -> None:
assert isinstance(message, HumanMessage)
assert message.id == "1710000000000-ab12cd"
assert message.content == "画一张图"
+ assert message.additional_kwargs["octop_author_user_id"] == 1
def test_overwrite_last_user_text_keeps_message_id() -> None:
diff --git a/tests/unit/gateway/test_processor_conversation_mode.py b/tests/unit/gateway/test_processor_conversation_mode.py
index 671974c419..0625044b39 100644
--- a/tests/unit/gateway/test_processor_conversation_mode.py
+++ b/tests/unit/gateway/test_processor_conversation_mode.py
@@ -80,7 +80,7 @@ async def test_dashboard_execute_overwrites_user_text() -> None:
thread_id="thr",
meta={},
)
- assert request["messages"][0]["content"] == "请按 plans/foo.md 执行"
+ assert request["messages"][0].content == "请按 plans/foo.md 执行"
assert request["conversation_mode"] == "craft"
processor._thread_registry.update_composer.assert_called_once_with(
"thr",
@@ -114,7 +114,7 @@ async def test_dashboard_mode_switch_keeps_pending_plan() -> None:
thread_id="thr",
meta={"conversation_mode": "ask"},
)
- assert request["messages"][0]["content"] == "先问一句"
+ assert request["messages"][0].content == "先问一句"
assert request["conversation_mode"] == "ask"
processor._thread_registry.update_composer.assert_called_once_with(
"thr",
diff --git a/tests/unit/gateway/test_processor_default_open.py b/tests/unit/gateway/test_processor_default_open.py
index f51c9cb400..7bda1b8fa1 100644
--- a/tests/unit/gateway/test_processor_default_open.py
+++ b/tests/unit/gateway/test_processor_default_open.py
@@ -291,7 +291,7 @@ async def test_dashboard_request_attaches_knowledge_base_ids_without_prepending(
meta=msg.metadata or {},
)
- content = request["messages"][0]["content"]
+ content = request["messages"][0].content
assert content == "question"
configurable = request.get("configurable") or {}
assert configurable["knowledge_base_ids"] == ["kb-1"]
From 1c07a27d6d5c56b00d3f478109e857af3570ca8b Mon Sep 17 00:00:00 2001
From: Jubaoliang
Date: Sat, 7 Nov 2026 20:53:16 +0800
Subject: [PATCH 6/8] fix: keep provider defaults, model names, and upgrade
prompts honest (#2880)
An empty default model was discarded, chat chips hid which vendor a model came from, and a waiting frontend never reached people without update permission. PostgreSQL backup now explains a missing client instead of failing as an internal error.
---
CHANGELOG.md | 3 ++
dashboard/src/App.tsx | 2 +
.../PwaUpdatePrompt/index.module.less | 3 +-
.../src/components/PwaUpdatePrompt/index.tsx | 37 ++++++++------
dashboard/src/layouts/MainLayout/index.tsx | 2 -
dashboard/src/locales/en.json | 1 +
dashboard/src/locales/zh.json | 45 ++++++++---------
.../src/pages/Admin/SharedModels/index.tsx | 2 +-
.../src/pages/Chat/components/ChatInput.tsx | 1 +
.../Chat/components/ChatInputPreviewBar.tsx | 9 +++-
.../components/UserMessageComposerTags.tsx | 8 +++-
dashboard/src/pages/Chat/index.tsx | 9 +++-
.../components/FileEditModal.module.less | 17 +++++++
.../Experts/components/FileEditModal.test.tsx | 23 +++++++++
.../Experts/components/FileEditModal.tsx | 48 ++++---------------
.../components/modals/ProviderConfigModal.tsx | 42 ++++++++++------
.../src/pages/Settings/Models/useProviders.ts | 2 +
dashboard/src/pwa.ts | 6 +++
dashboard/src/sw-register.test.ts | 12 +++++
dashboard/src/sw-register.ts | 5 ++
dashboard/src/utils/modelOptions.test.ts | 21 ++++++++
dashboard/src/utils/modelOptions.ts | 14 ++++++
docker/Dockerfile | 1 +
fnos/docker/Dockerfile | 1 +
src/octop/api/routers/providers.py | 27 +++++++++--
src/octop/i18n/en.json | 1 +
src/octop/i18n/zh.json | 1 +
src/octop/infra/agents/providers/store.py | 22 +++++++++
src/octop/infra/backup/pg_dump.py | 3 +-
src/octop/infra/errors.py | 2 +
.../unit/api/test_provider_patch_rehydrate.py | 38 +++++++++++++++
tests/unit/backup/test_pg_dump_helpers.py | 7 ++-
32 files changed, 310 insertions(+), 105 deletions(-)
create mode 100644 dashboard/src/pages/Experts/components/FileEditModal.module.less
create mode 100644 dashboard/src/pages/Experts/components/FileEditModal.test.tsx
create mode 100644 dashboard/src/utils/modelOptions.test.ts
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 52fbb1d050..b18f4d5dc1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,9 @@
- 重名的模型供应商返回冲突,不再报服务器错误。知识库引用只包含实际写进上下文的文档
- 备份落到另一块磁盘时不再丢文件。两个账号在同一浏览器里不再共用主题
- 未读数字可以打开对应会话。自定义 ACP 显示自己的名称,HTML 预览里的页内链接留在预览框内
+- 供应商的默认模型可以清空并保持为空。对话里的模型名与选择时一致,能区分不同厂家的同名模型
+- 服务端升级后,登录页和已登录页面都会提示刷新前端。PostgreSQL 备份缺少客户端工具时会说明原因,Docker 镜像带上该工具
+- 专家配置文件改为文本框编辑,打开时不再停在编辑器加载中
## [1.0.3b4] - 2026-11-06
diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsx
index d278fadbbf..3a0384607a 100644
--- a/dashboard/src/App.tsx
+++ b/dashboard/src/App.tsx
@@ -19,6 +19,7 @@ import OidcComplete from "./pages/Login/OidcComplete";
import SetupPage from "./pages/Setup";
import InvitePage from "./pages/Invite";
import AuthGuard from "./components/AuthGuard";
+import PwaUpdatePrompt from "./components/PwaUpdatePrompt";
import OctopSpinner from "./components/OctopSpinner";
import { AntdAppProvider } from "./components/AntdAppProvider";
import GlobalErrorBoundary from "./components/ErrorBoundary";
@@ -132,6 +133,7 @@ function ThemedApp() {
{desktopChrome ? (
) : null}
+
} />
} />
diff --git a/dashboard/src/components/PwaUpdatePrompt/index.module.less b/dashboard/src/components/PwaUpdatePrompt/index.module.less
index 6f7b02b0d2..c04136dd5b 100644
--- a/dashboard/src/components/PwaUpdatePrompt/index.module.less
+++ b/dashboard/src/components/PwaUpdatePrompt/index.module.less
@@ -12,7 +12,8 @@
border: 1px solid var(--fn-border-primary, rgba(255, 255, 255, 0.08));
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
z-index: 9999;
- white-space: nowrap;
+ max-width: calc(100vw - 24px);
+ flex-wrap: wrap;
animation: slideUp 0.25s ease;
}
diff --git a/dashboard/src/components/PwaUpdatePrompt/index.tsx b/dashboard/src/components/PwaUpdatePrompt/index.tsx
index 287267086b..d898833ff9 100644
--- a/dashboard/src/components/PwaUpdatePrompt/index.tsx
+++ b/dashboard/src/components/PwaUpdatePrompt/index.tsx
@@ -1,6 +1,6 @@
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
-import { applyUpdate } from "../../pwa";
+import { applyUpdate, hasPendingAppUpdate } from "../../pwa";
import { updateApi } from "../../api/modules/update";
import { useCurrentUser } from "../../hooks/useCurrentUser";
import { userCan } from "../../utils/permissions";
@@ -16,14 +16,16 @@ export const PWA_UPDATE_DISMISSED_KEY = "pwa:update-dismissed";
/**
* Listens for the "pwa:update-ready" event (dispatched by sw-register.ts) and
* renders a dismissible banner so the user can choose when to reload.
- * Designed to be mounted once in MainLayout.
+ * Mount once above the router so the login page sees it too. If the event
+ * fired before this component mounted, the waiting worker is checked directly.
*
- * Only users allowed to update see the banner: applying it restarts the backend
- * service, which requires the ``update`` permission. Non-admins are not prompted.
+ * The banner is shown on every page, including login. Reloading picks up the
+ * new frontend.
+ * Restarting the backend service still requires the ``update`` permission.
*
* When the process is running as a system service (OCTOP_SERVICE_MODE is
- * set), clicking the update-now action also triggers a backend service restart so that
- * the new Python package takes effect alongside the new frontend bundle.
+ * set) and the user may update, clicking the action also restarts the backend
+ * so the new Python package takes effect alongside the new frontend bundle.
*/
export default function PwaUpdatePrompt() {
const { t } = useTranslation();
@@ -34,16 +36,23 @@ export default function PwaUpdatePrompt() {
const canUpdate = userCan(user, "update");
useEffect(() => {
- const handler = () => {
+ let cancelled = false;
+ const show = () => {
try {
if (sessionStorage.getItem(PWA_UPDATE_DISMISSED_KEY)) return;
} catch {
// private mode / storage disabled — still allow the prompt
}
- setVisible(true);
+ if (!cancelled) setVisible(true);
+ };
+ window.addEventListener("pwa:update-ready", show);
+ void hasPendingAppUpdate().then((pending) => {
+ if (pending) show();
+ });
+ return () => {
+ cancelled = true;
+ window.removeEventListener("pwa:update-ready", show);
};
- window.addEventListener("pwa:update-ready", handler);
- return () => window.removeEventListener("pwa:update-ready", handler);
}, []);
// Fetch service mode once so we know whether to also restart the backend.
@@ -55,13 +64,13 @@ export default function PwaUpdatePrompt() {
.catch(() => {});
}, [canUpdate]);
- if (!canUpdate || !visible) return null;
+ if (!visible) return null;
const handleUpdate = async () => {
setVisible(false);
- // If running as a system service, trigger backend restart first.
- // applyUpdate() reloads once after posting SKIP_WAITING.
- if (serviceMode) {
+ // Frontend reload is enough for everyone. Only an operator may restart
+ // the backend service that is serving this page.
+ if (canUpdate && serviceMode) {
updateApi.restartService().catch(() => {});
}
await applyUpdate();
diff --git a/dashboard/src/layouts/MainLayout/index.tsx b/dashboard/src/layouts/MainLayout/index.tsx
index 6ade910924..b680a5b17b 100644
--- a/dashboard/src/layouts/MainLayout/index.tsx
+++ b/dashboard/src/layouts/MainLayout/index.tsx
@@ -7,7 +7,6 @@ import RailEdgeControl from "../../components/RailEdgeControl";
import PageLoading from "../../components/PageLoading";
import { ServiceRestartProvider } from "../../context/ServiceRestartContext";
import { BackupOperationProvider } from "../../context/BackupOperationContext";
-import PwaUpdatePrompt from "../../components/PwaUpdatePrompt";
import { PwaAutoPrompt } from "../../components/PwaInstallPrompt";
import {
routeConfigs,
@@ -303,7 +302,6 @@ export default function MainLayout() {
minHeight: 0,
}}
>
-
{workbenchMounted && (
diff --git a/dashboard/src/locales/en.json b/dashboard/src/locales/en.json
index 43068a0536..ea22be2fee 100644
--- a/dashboard/src/locales/en.json
+++ b/dashboard/src/locales/en.json
@@ -111,6 +111,7 @@
"BACKUP_DRIVER_MISMATCH": "This backup was made with a different database engine (SQLite vs PostgreSQL). Switch the runtime to match the backup, or create a new backup on the current engine. Cross-engine restore is not supported.",
"BACKUP_SCHEMA_INCOMPATIBLE": "This backup uses database schema version {{archive_schema_version}}, which cannot be restored by this Octop version (maximum supported: {{runtime_schema_version}}).",
"BACKUP_IN_PROGRESS": "A backup or restore is already in progress. Try again shortly.",
+ "BACKUP_CLIENT_MISSING": "PostgreSQL backup needs {{tool}}, which is not installed. Install the PostgreSQL client tools where Octop runs, then try again.",
"FORBIDDEN": "Permission denied.",
"UPDATE_TARGET_NOT_NEWER": "Target version {{target}} must be newer than installed version {{current}}. Reinstalling or downgrading is not supported.",
"NOT_FOUND": "Not found.",
diff --git a/dashboard/src/locales/zh.json b/dashboard/src/locales/zh.json
index 5b3bb7b452..ed091ca3b6 100644
--- a/dashboard/src/locales/zh.json
+++ b/dashboard/src/locales/zh.json
@@ -111,6 +111,7 @@
"BACKUP_DRIVER_MISMATCH": "该备份与当前数据库引擎不一致(SQLite 与 PostgreSQL 不能互恢)。请将运行时切回备份所用引擎后再恢复,或在当前引擎上重新备份。暂不支持跨引擎恢复。",
"BACKUP_SCHEMA_INCOMPATIBLE": "该备份使用数据库结构版本 {{archive_schema_version}},当前 Octop 版本无法恢复(最高支持版本:{{runtime_schema_version}})。",
"BACKUP_IN_PROGRESS": "已有备份或恢复任务正在进行,请稍后再试。",
+ "BACKUP_CLIENT_MISSING": "当前环境找不到 {{tool}},无法备份或恢复 PostgreSQL。请在运行 Octop 的环境中安装 PostgreSQL 客户端后再试。",
"FORBIDDEN": "没有权限。",
"UPDATE_TARGET_NOT_NEWER": "目标版本 {{target}} 必须高于已安装版本 {{current}},不支持重装同版本或降级。",
"NOT_FOUND": "未找到。",
@@ -274,7 +275,7 @@
"bridge": "云端协同",
"acp": "ACP 协作",
"agents": "专家",
- "providers": "Providers",
+ "providers": "供应商",
"models": "模型配置",
"channels": "通道",
"sessions": "会话",
@@ -705,7 +706,7 @@
"found": "检测到 OpenClaw 配置",
"foundHint": "请选择要迁移的内容,点击「立即迁移」自动同步:",
"selectAll": "全选",
- "itemModels": "大模型配置(providers + 活跃模型)",
+ "itemModels": "大模型配置(供应商 + 活跃模型)",
"itemChannels": "通道配置(Feishu / DingTalk / QQ / Discord)",
"itemModelsOnly": "大模型配置",
"itemChannelsOnly": "通道配置",
@@ -846,7 +847,7 @@
"ESFP": "表演者"
},
"experts": {
- "subtitle": "基于已配置的场景模板,一键创建预置身份/灵魂/心跳的智能体。每个专家自带 system prompt,新建后再绑定 provider 并启动即可。",
+ "subtitle": "基于已配置的场景模板,一键创建预置身份/灵魂/心跳的智能体。每个专家自带 system prompt,新建后再绑定供应商并启动即可。",
"loadFailed": "加载专家失败",
"loadDetailFailed": "加载详情失败",
"share": {
@@ -901,7 +902,7 @@
"createWithExpertTitle": "用 {{name}} 创建专家",
"agentNameLabel": "专家名称",
"pleaseEnterName": "请输入名称",
- "afterCreateHint": "创建后请前往专家页绑定 provider 并启动。",
+ "afterCreateHint": "创建后请前往专家页绑定供应商并启动。",
"agentCreated": "已创建专家:{{name}}",
"createFailed": "创建失败",
"fileLabel": {
@@ -1066,7 +1067,7 @@
"avatarUploadLater": "专家已创建,头像未能上传,可稍后在编辑专家中添加。",
"customColor": "自定义颜色",
"defaultModel": "默认模型",
- "defaultModelAuto": "Auto(使用 Provider 默认模型)",
+ "defaultModelAuto": "Auto(使用供应商默认模型)",
"editFile": "编辑 →",
"editFileTitle": "编辑 {{filename}}",
"fileSaved": "{{filename}} 已保存",
@@ -1159,7 +1160,7 @@
"shield-check": "安全盾牌",
"refresh-cw": "刷新"
},
- "noModelsWarning": "当前未配置任何模型,请前往管理员页面配置 Provider。",
+ "noModelsWarning": "当前未配置任何模型,请前往管理员页面配置供应商。",
"goToAdmin": "前往配置",
"backendLabel": "存储后端",
"backendRootDir": "存储根目录",
@@ -3329,10 +3330,10 @@
"authHeaderExtra": "将 Authorization: Bearer 作为额外的默认请求头注入",
"thinkingLabel": "思考模式",
"thinkingExtra": "启用深度思考(思维链)能力。关闭后,该服务商下所有模型将禁用思考模式。",
- "providerHeaders": "Provider Headers",
+ "providerHeaders": "供应商请求头",
"headersFormatHint": "每行一个请求头,格式:Key: Value",
"requestHeaders": "Request Headers",
- "requestHeadersExtra": "优先级高于 Provider Headers",
+ "requestHeadersExtra": "优先级高于供应商请求头",
"apiProtocolLabel": "协议类型",
"apiProtocolExtra": "选择与目标 API 兼容的协议类型",
"apiProtocolDefault": "默认(OpenAI 兼容)",
@@ -3678,7 +3679,7 @@
"decisionFallback": "分数不够、或服务没有返回结果时,这一轮仍使用原来的技能、工具和成员名单。",
"addCustomProvider": "自定义供应商",
"loadingProviders": "加载中...",
- "noProvidersHint": "还没有 provider,点击右上角新建",
+ "noProvidersHint": "还没有供应商,点击右上角新建",
"kindLabel": "类型",
"kindOpenaiCompat": "OpenAI 兼容",
"pleaseSelectKind": "请选择类型",
@@ -3701,27 +3702,27 @@
"testPingHint": "使用已保存配置发送一次 ping。",
"testDraftNeedModel": "请至少添加或选择一个模型后再测试。",
"codexOAuthLogin": "使用 ChatGPT 登录",
- "codexOAuthHint": "通过 ChatGPT 订阅 OAuth 登录,无需手动填写 API Key。登录成功后会自动创建 openai-codex provider。",
- "codexOAuthSuccess": "ChatGPT 登录成功,模型 provider 已配置。",
+ "codexOAuthHint": "通过 ChatGPT 订阅 OAuth 登录,无需手动填写 API Key。登录成功后会自动创建 openai-codex 供应商。",
+ "codexOAuthSuccess": "ChatGPT 登录成功,模型供应商已配置。",
"codexOAuthFailed": "ChatGPT 登录失败:{{error}}",
"codexOAuthStartFailed": "无法启动 ChatGPT OAuth",
"codexOAuthDisclaimer": "此方式使用 ChatGPT 内部 Codex API,非 OpenAI 官方 API Key 路径,可能受 OpenAI 服务条款与稳定性影响,请自行评估风险。",
"codexOAuthDeviceHint": "已在新标签页打开验证页面。如未自动打开,请点击下方按钮,输入下面的验证码完成登录,本页会自动更新。",
"codexOAuthOpenVerification": "打开验证页面",
"codexOAuthWaiting": "等待您完成授权…",
- "cannotDeleteSharedTitle": "无法删除共享 provider",
- "cannotDeleteSharedDesc": "此 provider 由管理员维护(user_id 为空),仅管理员可删除。",
- "deleteProviderTitle": "删除 provider",
+ "cannotDeleteSharedTitle": "无法删除共享供应商",
+ "cannotDeleteSharedDesc": "此供应商由管理员维护(user_id 为空),仅管理员可删除。",
+ "deleteProviderTitle": "删除供应商",
"deleteProviderConfirmSimple": "确认删除 “{{name}}”?该操作不可撤销。",
"providerDeletedSimple": "已删除 {{name}}",
"toggleStateFailed": "状态切换失败",
- "providerCreatedSimple": "已创建 provider “{{name}}”",
+ "providerCreatedSimple": "已创建供应商 “{{name}}”",
"createFailedSimple": "创建失败",
"revokeFailedSimple": "撤销失败",
"configureProviderTitle": "配置 {{name}}",
"providerConfigSaved": "{{name}} 配置已保存",
"revokeConfirmTitle": "撤销授权",
- "revokeConfirmContentSimple": "确认清除 {{name}} 的 API Key?清除后该 provider 将变为未授权状态。",
+ "revokeConfirmContentSimple": "确认清除 {{name}} 的 API Key?清除后该供应商将变为未授权状态。",
"authorizationRevokedSimpleAlt": "{{name}} 授权已撤销",
"testConnectionSuccess": "{{name}} 连接成功{{latency}}",
"testConnectionLatency": ",响应 {{time}}ms",
@@ -3735,7 +3736,7 @@
"chooseSiteFirst": "请先选择站点",
"addSiteVariant": "添加其他站点",
"configured": "已配置",
- "presetNameExists": "已有同名 provider,请直接编辑",
+ "presetNameExists": "已有同名供应商,请直接编辑",
"sharedProviders": "共享提供商(管理员)",
"pleaseEnterApiKey": "请输入 API Key",
"fetchModels": "获取模型列表",
@@ -5591,10 +5592,10 @@
},
"admin": {
"sharedModels": {
- "addProvider": "新增共享 Provider",
- "deleteConfirm": "确定要删除共享 Provider「{{name}}」?所有用户将无法再使用此 Provider。",
- "deleteSuccess": "已删除共享 Provider「{{name}}」",
- "createSuccess": "共享 Provider「{{name}}」已创建",
+ "addProvider": "新增共享供应商",
+ "deleteConfirm": "确定要删除共享供应商「{{name}}」?所有用户将无法再使用此供应商。",
+ "deleteSuccess": "已删除共享供应商「{{name}}」",
+ "createSuccess": "共享供应商「{{name}}」已创建",
"createFailed": "创建失败"
}
},
@@ -7358,7 +7359,7 @@
"WEBAUTHN_CONFIG_INVALID": "还不能使用通行密钥。请管理员在「应用设置 → 通行密钥」填写本站域名和完整网址。如果已经填过,请改用登记的那个网址打开。用 localhost 打开则不用填。"
},
"adminProviders": {
- "title": "Providers",
+ "title": "供应商",
"newProvider": "新建提供商",
"pageDescription": "所有提供商均由管理员统一管理,对每个专家全局可用。",
"colName": "名称",
diff --git a/dashboard/src/pages/Admin/SharedModels/index.tsx b/dashboard/src/pages/Admin/SharedModels/index.tsx
index a97ebffa17..c7f785eb61 100644
--- a/dashboard/src/pages/Admin/SharedModels/index.tsx
+++ b/dashboard/src/pages/Admin/SharedModels/index.tsx
@@ -26,7 +26,7 @@ export default function AdminSharedModelsPage() {
}
setProviders(rows);
} catch (err) {
- setError(err instanceof Error ? err.message : "加载共享 Provider 失败");
+ setError(err instanceof Error ? err.message : "加载共享供应商失败");
} finally {
setLoading(false);
}
diff --git a/dashboard/src/pages/Chat/components/ChatInput.tsx b/dashboard/src/pages/Chat/components/ChatInput.tsx
index 369b99e4a8..be7eb84167 100644
--- a/dashboard/src/pages/Chat/components/ChatInput.tsx
+++ b/dashboard/src/pages/Chat/components/ChatInput.tsx
@@ -887,6 +887,7 @@ const ChatInput = forwardRef(
uploading={uploading}
selectedConnectors={selectedConnectors}
selectedModel={selectedModel}
+ availableModels={availableModels}
availableConnectors={availableConnectors}
availableKnowledgeBases={availableKnowledgeBases}
onRemoveAttachment={removeAttachment}
diff --git a/dashboard/src/pages/Chat/components/ChatInputPreviewBar.tsx b/dashboard/src/pages/Chat/components/ChatInputPreviewBar.tsx
index 1cf6770372..4323261dc6 100644
--- a/dashboard/src/pages/Chat/components/ChatInputPreviewBar.tsx
+++ b/dashboard/src/pages/Chat/components/ChatInputPreviewBar.tsx
@@ -9,7 +9,10 @@ import { knowledgeIconForName } from "../../KnowledgeBases/knowledgeIcons";
import { inferKindFromNameAndMime } from "../utils/chatAttachments";
import { ChatMediaPlayer } from "./ChatMediaPlayer";
import ContextChip from "./ContextChip";
-import { modelShortLabel } from "../../../utils/modelOptions";
+import {
+ modelRefLabel,
+ type ModelPickerOption,
+} from "../../../utils/modelOptions";
import styles from "../index.module.less";
interface ChatInputPreviewBarProps {
@@ -18,6 +21,7 @@ interface ChatInputPreviewBarProps {
selectedConnectors: string[];
selectedKnowledgeBaseIds: string[];
selectedModel?: string | null;
+ availableModels?: readonly ModelPickerOption[];
availableConnectors?: {
mcp_server_name: string;
label: string;
@@ -98,6 +102,7 @@ export default function ChatInputPreviewBar({
onConnectorsChange,
onKnowledgeBaseIdsChange,
selectedModel,
+ availableModels,
onModelChange,
}: ChatInputPreviewBarProps) {
// Show the chip whenever a model is explicitly selected, mirroring how
@@ -260,7 +265,7 @@ export default function ChatInputPreviewBar({
}
- label={modelShortLabel(selectedModelValue)}
+ label={modelRefLabel(selectedModelValue, availableModels)}
onRemove={() => onModelChange?.(null)}
/>
)}
diff --git a/dashboard/src/pages/Chat/components/UserMessageComposerTags.tsx b/dashboard/src/pages/Chat/components/UserMessageComposerTags.tsx
index 4f50575baa..690470eed9 100644
--- a/dashboard/src/pages/Chat/components/UserMessageComposerTags.tsx
+++ b/dashboard/src/pages/Chat/components/UserMessageComposerTags.tsx
@@ -11,7 +11,10 @@ import { ConnectorLogo } from "../../Agent/Connectors/connectorDefs";
import { knowledgeIconForName } from "../../KnowledgeBases/knowledgeIcons";
import ContextChip, { type ContextChipVariant } from "./ContextChip";
import { skillChipIcon } from "../utils/skillChipIcon";
-import { modelShortLabel } from "../../../utils/modelOptions";
+import {
+ modelRefLabel,
+ type ModelPickerOption,
+} from "../../../utils/modelOptions";
import styles from "../index.module.less";
export interface ComposerTagLookups {
@@ -19,6 +22,7 @@ export interface ComposerTagLookups {
connectors?: { mcp_server_name: string; label: string; kind: string }[];
knowledgeBases?: KnowledgeBase[];
agents?: ChatAgentOption[];
+ models?: readonly ModelPickerOption[];
}
interface UserMessageComposerTagsProps {
@@ -120,7 +124,7 @@ export default function UserMessageComposerTags({
key: `model-${context.model}`,
variant: "model",
icon: ,
- label: modelShortLabel(context.model),
+ label: modelRefLabel(context.model, lookups?.models),
});
}
diff --git a/dashboard/src/pages/Chat/index.tsx b/dashboard/src/pages/Chat/index.tsx
index 9cf1a7d44b..10f4106561 100644
--- a/dashboard/src/pages/Chat/index.tsx
+++ b/dashboard/src/pages/Chat/index.tsx
@@ -712,8 +712,15 @@ function ChatPageInner() {
connectors: chatConnectors,
knowledgeBases: chatKnowledgeBases,
agents: chatAgentOptions,
+ models: availableModels,
}),
- [chatSkills, chatConnectors, chatKnowledgeBases, chatAgentOptions],
+ [
+ chatSkills,
+ chatConnectors,
+ chatKnowledgeBases,
+ chatAgentOptions,
+ availableModels,
+ ],
);
const { handleSend } = useChatSend({
diff --git a/dashboard/src/pages/Experts/components/FileEditModal.module.less b/dashboard/src/pages/Experts/components/FileEditModal.module.less
new file mode 100644
index 0000000000..73b57a46ac
--- /dev/null
+++ b/dashboard/src/pages/Experts/components/FileEditModal.module.less
@@ -0,0 +1,17 @@
+.editor {
+ flex: 1;
+ min-height: 240;
+ width: 100%;
+ margin: 0;
+ padding: 16px 18px;
+ border: none;
+ resize: none;
+ outline: none;
+ background: var(--fn-bg-primary, transparent);
+ color: var(--fn-text-primary, inherit);
+ font-family: ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono",
+ monospace;
+ font-size: 13px;
+ line-height: 1.6;
+ tab-size: 2;
+}
diff --git a/dashboard/src/pages/Experts/components/FileEditModal.test.tsx b/dashboard/src/pages/Experts/components/FileEditModal.test.tsx
new file mode 100644
index 0000000000..0b9cb554a8
--- /dev/null
+++ b/dashboard/src/pages/Experts/components/FileEditModal.test.tsx
@@ -0,0 +1,23 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+
+import FileEditModal from "./FileEditModal";
+
+describe("FileEditModal", () => {
+ it("edits a config file in a textarea", () => {
+ render(
+ {}}
+ onSaved={() => {}}
+ onLocalSave={() => {}}
+ />,
+ );
+
+ const box = screen.getByRole("textbox");
+ expect(box.tagName).toBe("TEXTAREA");
+ expect(box).toHaveValue("# Agents\nkeep this");
+ });
+});
diff --git a/dashboard/src/pages/Experts/components/FileEditModal.tsx b/dashboard/src/pages/Experts/components/FileEditModal.tsx
index ade8584382..7a9204fd12 100644
--- a/dashboard/src/pages/Experts/components/FileEditModal.tsx
+++ b/dashboard/src/pages/Experts/components/FileEditModal.tsx
@@ -1,14 +1,12 @@
// dashboard/src/pages/Experts/components/FileEditModal.tsx
-import { lazy, Suspense, useEffect, useState } from "react";
+import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button, Drawer, Spin } from "antd";
import { message } from "@/utils/antdMessage";
import { request } from "../../../api/request";
-import { useTheme } from "../../../context/ThemeContext";
import { withFromWorkspace } from "../../../utils/fromWorkspace";
-
-const MonacoEditor = lazy(() => import("@/components/monaco"));
+import styles from "./FileEditModal.module.less";
interface FileEditModalProps {
open: boolean;
@@ -37,7 +35,6 @@ export default function FileEditModal({
onLocalSave,
}: FileEditModalProps) {
const { t } = useTranslation();
- const { isDark } = useTheme();
const [value, setValue] = useState("");
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
@@ -163,39 +160,14 @@ export default function FileEditModal({
) : (
-
-
-
- }
- >
-
- setValue(v ?? "")}
- options={{
- minimap: { enabled: false },
- wordWrap: "on",
- fontSize: 13,
- lineNumbers: "on",
- scrollBeyondLastLine: false,
- }}
- />
-
-
+