Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
Merge remote-tracking branch 'origin/master' into feature/telegram-im
cyh36ad3784b9d8
diff --cc core/handlers/session_handler.pyindex 6807e012e,6041e6e75..ce9bde037--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@@ -49,22 -38,83 +38,103 @@@ class SessionHandler(BaseHandler)else:base_id = context.channel_id or context.user_idelse:- base_id = context.thread_id or context.message_id or context.channel_id+ base_id = context.thread_id+ if not base_id:+ use_message_id = True+ getter = getattr(self.controller, "get_im_client_for_context", None)+ if callable(getter):+ try:+ im_client = getter(context)+ except AttributeError:+ im_client = getattr(self.controller, "im_client", None)+ else:+ im_client = getattr(self.controller, "im_client", None)+ if im_client and hasattr(im_client, "should_use_message_id_for_channel_session"):+ use_message_id = bool(im_client.should_use_message_id_for_channel_session(context))+ base_id = context.message_id if use_message_id and context.message_id else context.channel_idreturn f"{platform}_{base_id}"+ def _get_context_platform(self, context: MessageContext) -> str:+ return (+ context.platform+ or (context.platform_specific or {}).get("platform")+ or getattr(self.config, "platform", "slack")+ )++ def should_allocate_scheduled_anchor(self, context: MessageContext, source: str = "human") -> bool:+ if source != "scheduled" or context.thread_id:+ return False+ is_dm = bool((context.platform_specific or {}).get("is_dm", False))- return self._supports_threaded_session(context, is_dm=is_dm)++ if not self._supports_threaded_session(context, is_dm=is_dm):++ return False++ if is_dm:++ return True++++ im_client = self._get_im_client(context)++ use_message_id = getattr(im_client, "should_use_message_id_for_channel_session", lambda _context=None: True)++ return bool(use_message_id(context))++ def build_message_anchor_base(self, context: MessageContext, message_id: str) -> str:+ return f"{self._get_context_platform(context)}_{message_id}"++ def alias_session_base(+ self,+ context: MessageContext,+ *,+ source_base_session_id: str,+ alias_base_session_id: str,+ clear_source: bool = False,+ ) -> bool:+ if not source_base_session_id or not alias_base_session_id:+ return False+ session_key = self._get_session_key(context)+ changed = self.sessions.alias_session_base(+ session_key,+ source_base_session_id,+ alias_base_session_id,+ )+ if changed and clear_source and source_base_session_id != alias_base_session_id:+ self.sessions.clear_session_base(session_key, source_base_session_id)+ return changed++ def finalize_scheduled_delivery(self, context: MessageContext, sent_message_id: Optional[str]) -> None:+ payload = context.platform_specific or {}+ if payload.get("turn_source") != "scheduled":+ return+ if context.thread_id or not payload.get("scheduled_anchor_required"):+ return+ if not sent_message_id:+ return++ source_base_session_id = payload.get("turn_base_session_id") or ""+ alias_base_session_id = self.build_message_anchor_base(context, sent_message_id)+ self.alias_session_base(+ context,+ source_base_session_id=source_base_session_id,+ alias_base_session_id=alias_base_session_id,+ clear_source=True,+ )++ platform = self._get_context_platform(context)+ if platform in {"slack", "lark"}:+ self.sessions.mark_thread_active("scheduled", context.channel_id, sent_message_id)++ def _supports_threaded_session(self, context: MessageContext, *, is_dm: bool) -> bool:+ getter = getattr(self.controller, "get_im_client_for_context", None)+ if callable(getter):+ try:+ im_client = getter(context)+ except AttributeError:+ im_client = getattr(self.controller, "im_client", None)+ else:+ im_client = getattr(self.controller, "im_client", None)++ if im_client is None:+ return False+ if is_dm:+ return bool(getattr(im_client, "should_use_thread_for_dm_session", lambda: False)())+ return bool(getattr(im_client, "should_use_thread_for_reply", lambda: False)())+def get_working_path(self, context: MessageContext) -> str:"""Get working directory - delegate to controller's get_cwd"""return self.controller.get_cwd(context)diff --cc modules/im/base.pyindex 87ce41e51,9d30bc138..2e374098b--- a/modules/im/base.py+++ b/modules/im/base.py@@@ -146,10 -146,14 +146,18 @@@ class BaseIMClient(ABC)"""return False+ def should_use_message_id_for_channel_session(self, context: Optional[MessageContext] = None) -> bool:+ """Whether non-thread channel messages should default to per-message sessions."""+ return True++ async def prepare_turn_context(self, context: MessageContext, source: str) -> MessageContext:+ """Allow IM adapters to adjust reply topology for a turn source.++ `source` is one of the higher-level inbound turn types such as+ ``human`` or ``scheduled``.+ """+ return context+@staticmethoddef extract_command_action(text: str, allow_plain_bind: bool = False) -> str:"""Extract command action name from slash command text.diff --cc tests/test_command_handler_user_names.pyindex 2f93029cd,648bb97ca..940450a65--- a/tests/test_command_handler_user_names.py+++ b/tests/test_command_handler_user_names.py@@@ -52,21 -52,25 +52,31 @@@ class _StubIMClientdef __init__(self, user_info):self.user_info = user_infoself.sent_messages = []+ self.sent_contexts = []+ self.sent_button_messages = []+ self.channel_info_calls = []self.formatter = None+ self.started_topic_context = Noneasync def get_user_info(self, user_id):return self.user_info+ async def get_channel_info(self, channel_id):+ self.channel_info_calls.append(channel_id)+ return {"id": channel_id, "name": channel_id}+async def send_message(self, context, text, parse_mode=None):+ self.sent_contexts.append(context)self.sent_messages.append((context.channel_id, text))return "T1"+ async def send_message_with_buttons(self, context, text, keyboard, parse_mode=None):+ self.sent_button_messages.append((context.channel_id, text, keyboard))+ return "T2"++ async def start_new_topic_session(self, context):+ return self.started_topic_context+class _StubSettingsManager:def __init__(self):@@@ -158,33 -162,23 +168,50 @@@ class CommandHandlerUserNameTests(unitt[("wx-chat", "🆕 已开启新的会话。你下一条消息会从全新对话开始。")],)+ async def test_telegram_new_command_creates_topic_session_when_supported(self):+ controller = _StubController({"display_name": "Alex"})+ setattr(controller.config, "platform", "telegram")+ controller.agent_service.clear_sessions = _clear_sessions # type: ignore[attr-defined]+ handler = CommandHandlers(controller)+ controller.im_client.started_topic_context = MessageContext(+ user_id="42",+ channel_id="-100123",+ thread_id="99",+ platform="telegram",+ )+ context = MessageContext(+ user_id="42",+ channel_id="-100123",+ thread_id="1",+ platform="telegram",+ platform_specific={"platform": "telegram"},+ )++ await handler.handle_new(context)++ self.assertEqual(+ controller.im_client.sent_messages,+ [("-100123", "🆕 已开启新的会话。你下一条消息会从全新对话开始。")],+ )+ self.assertEqual(controller.im_client.sent_contexts[0].thread_id, "99")++ async def test_slack_dm_start_skips_channel_info_lookup(self):+ controller = _StubController({"display_name": "Alex"})+ handler = CommandHandlers(controller)+ context = MessageContext(+ user_id="U0E0FM3QT",+ channel_id="D123",+ platform="slack",+ platform_specific={"is_dm": True, "platform": "slack"},+ )++ await handler.handle_start(context)++ self.assertEqual(controller.im_client.channel_info_calls, [])+ self.assertEqual(len(controller.im_client.sent_button_messages), 1)+ _, text, _ = controller.im_client.sent_button_messages[0]+ self.assertIn("私信", text)+async def _clear_sessions(_settings_key):return {}diff --cc tests/test_session_handler_base_id.pyindex 335227582,b33321d6b..5adb26f95--- a/tests/test_session_handler_base_id.py+++ b/tests/test_session_handler_base_id.py@@@ -15,23 -15,36 +15,43 @@@ class _Configplatform: str = "discord"+ class _FakeSessions:+ def __init__(self) -> None:+ self.alias_calls = []+ self.clear_calls = []+ self.thread_marks = []++ def alias_session_base(self, user_id, source_base_session_id, alias_base_session_id):+ self.alias_calls.append((user_id, source_base_session_id, alias_base_session_id))+ return True++ def clear_session_base(self, user_id, base_session_id):+ self.clear_calls.append((user_id, base_session_id))+ return 1++ def mark_thread_active(self, user_id, channel_id, thread_ts):+ self.thread_marks.append((user_id, channel_id, thread_ts))++class _Controller:- def __init__(self, *, platform: str = "discord", dm_threads: bool = False) -> None:+ def __init__(+ self,+ *,+ platform: str = "discord",+ dm_threads: bool = False,+ channel_message_sessions: bool = True,+ ) -> None:self.config = _Config()self.config.platform = platform+ self.sessions = _FakeSessions()self.im_client = type("IM",(),{"formatter": None,"should_use_thread_for_dm_session": lambda self: dm_threads,+ "should_use_message_id_for_channel_session": lambda self, context=None: channel_message_sessions,+ "should_use_thread_for_reply": lambda self: platform in {"discord", "slack", "lark"},},)()self.settings_manager = type("Settings", (), {"sessions": None})()@@@ -117,14 -130,51 +137,77 @@@ def test_channel_session_base_id_keeps_assert handler.get_base_session_id(context) == "discord_msg-999"+def test_telegram_plain_group_session_base_id_uses_stable_channel_id() -> None:+ handler = SessionHandler(_Controller(platform="telegram", channel_message_sessions=False))+ context = MessageContext(+ user_id="u-1",+ channel_id="-100123",+ message_id="42",+ platform="telegram",+ platform_specific={"is_dm": False, "chat_type": "supergroup"},+ )++ assert handler.get_base_session_id(context) == "telegram_-100123"+++++ def test_scheduled_channel_session_uses_provisional_anchor_on_threaded_surfaces() -> None:+ controller = _Controller(platform="slack", dm_threads=False)+ handler = SessionHandler(controller)+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform="slack",+ platform_specific={"is_dm": False, "turn_source": "scheduled"},+ )++ base_session_id = handler.get_base_session_id(context, source="scheduled")++ assert base_session_id.startswith("slack_scheduled-")++++def test_scheduled_telegram_group_session_reuses_channel_scope() -> None:++ controller = _Controller(platform="telegram", dm_threads=False, channel_message_sessions=False)++ handler = SessionHandler(controller)++ context = MessageContext(++ user_id="scheduled",++ channel_id="-100123",++ platform="telegram",++ platform_specific={"is_dm": False, "chat_type": "supergroup", "turn_source": "scheduled"},++ )++++ assert handler.get_base_session_id(context, source="scheduled") == "telegram_-100123"+++++ def test_scheduled_dm_session_reuses_flat_session_scope() -> None:+ controller = _Controller(platform="discord", dm_threads=False)+ handler = SessionHandler(controller)+ context = MessageContext(+ user_id="u-1",+ channel_id="dm-123",+ platform="discord",+ platform_specific={"is_dm": True, "turn_source": "scheduled"},+ )++ assert handler.get_base_session_id(context, source="scheduled") == "discord_dm-123"+++ def test_finalize_scheduled_delivery_aliases_provisional_base_and_marks_thread() -> None:+ controller = _Controller(platform="slack", dm_threads=False)+ handler = SessionHandler(controller)+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform="slack",+ platform_specific={+ "is_dm": False,+ "turn_source": "scheduled",+ "turn_base_session_id": "slack_scheduled-abc",+ "scheduled_anchor_required": True,+ },+ )++ handler.finalize_scheduled_delivery(context, "171717.123")++ assert controller.sessions.alias_calls == [("slack::C123", "slack_scheduled-abc", "slack_171717.123")]+ assert controller.sessions.clear_calls == [("slack::C123", "slack_scheduled-abc")]+ assert controller.sessions.thread_marks == [("scheduled", "C123", "171717.123")]diff --cc tests/test_ui_api.pyindex 147cef078,b7739bd07..c3b6f8ff7--- a/tests/test_ui_api.py+++ b/tests/test_ui_api.py@@@ -180,6 -178,133 +180,130 @@@ def test_install_codex_detects_binary_vassert calls[0][0] == [str(npm_path), "install", "-g", "@openai/codex"]assert calls[0][1]["PATH"].split(api.os.pathsep)[0] == str(npm_path.parent)-+ def test_claude_models_merge_builtin_cli_and_settings(monkeypatch, tmp_path):+ claude_dir = tmp_path / ".claude"+ claude_dir.mkdir(parents=True, exist_ok=True)+ (claude_dir / "settings.json").write_text(+ json.dumps(+ {+ "model": "opus[1m]",+ "env": {+ "ANTHROPIC_MODEL": "claude-sonnet-4-6",+ "ANTHROPIC_SMALL_FAST_MODEL": "claude-haiku-4-5-20251001",+ },+ }+ ),+ encoding="utf-8",+ )+ cli_bundle = tmp_path / "claude-cli.js"+ cli_bundle.write_text(+ '\n'.join(+ [+ 'const OPUS_ID = "claude-opus-4-6";',+ 'const SONNET_ID = "claude-sonnet-4-6";',+ 'const HAIKU_ID = "claude-haiku-4-5";',+ 'const PREV_SONNET_ID = "claude-sonnet-4-5";',+ ]+ ),+ encoding="utf-8",+ )++ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)+ monkeypatch.setattr(api, "resolve_cli_path", lambda binary: str(cli_bundle) if binary == "claude" else None)++ result = api.claude_models()++ assert result["ok"] is True+ assert result["models"][:4] == [+ "claude-opus-4-6",+ "claude-sonnet-4-6",+ "claude-haiku-4-5",+ "claude-opus-4-5",+ ]+ assert "opus" in result["models"]+ assert "sonnet" in result["models"]+ assert "haiku" in result["models"]+ assert "opus[1m]" in result["models"]+ assert "claude-haiku-4-5-20251001" in result["models"]+ assert result["models"].count("claude-sonnet-4-6") == 1+ assert [item["value"] for item in result["reasoning_options"]["opus"]] == [+ "__default__",+ "low",+ "medium",+ "high",+ "max",+ ]+++ def test_codex_models_prefers_cli_cache_and_filters_hidden_models(monkeypatch, tmp_path):+ codex_dir = tmp_path / ".codex"+ codex_dir.mkdir(parents=True, exist_ok=True)+ (codex_dir / "models_cache.json").write_text(+ json.dumps(+ {+ "models": [+ {"slug": "gpt-5.1", "visibility": "hide", "priority": 9},+ {"slug": "gpt-5.3-codex-spark", "visibility": "list", "priority": 6},+ {"slug": "gpt-5.4-mini", "visibility": "list", "priority": 3},+ {"slug": "gpt-5.4", "visibility": "list", "priority": 1},+ {"slug": "gpt-5.1-codex-mini", "visibility": "list", "priority": 19},+ ]+ }+ ),+ encoding="utf-8",+ )+ (codex_dir / "config.toml").write_text(+ '\n'.join(+ [+ 'model = "gpt-5.1"',+ "[notice.model_migrations]",+ '"gpt-5.2" = "gpt-5.4"',+ ]+ ),+ encoding="utf-8",+ )++ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)++ result = api.codex_models()++ assert result["ok"] is True+ assert result["models"][:3] == [+ "gpt-5.4",+ "gpt-5.4-mini",+ "gpt-5.4-nano",+ ]+ assert "gpt-5.3-codex-spark" in result["models"]+ assert "gpt-5.1-codex-mini" in result["models"]+ assert "gpt-5.1" in result["models"]+ assert "gpt-5.2" in result["models"]+ assert result["models"].count("gpt-5.4") == 1+++ def test_codex_models_falls_back_when_cli_cache_missing(monkeypatch, tmp_path):+ codex_dir = tmp_path / ".codex"+ codex_dir.mkdir(parents=True, exist_ok=True)+ (codex_dir / "config.toml").write_text(+ '\n'.join(+ [+ 'model = "custom-codex-model"',+ "[notice.model_migrations]",+ '"legacy-codex" = "gpt-5.4"',+ ]+ ),+ encoding="utf-8",+ )++ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)++ result = api.codex_models()++ assert result["ok"] is True+ assert result["models"][:3] == ["gpt-5.4", "gpt-5.4-mini", "gpt-5.4-nano"]+ assert "custom-codex-model" in result["models"]+ assert "legacy-codex" in result["models"]+ assert "gpt-5.1-codex-max" in result["models"]+ assert "gpt-5.1-codex-mini" in result["models"]--def test_setup_opencode_permission_preserves_existing_json_fields(monkeypatch, tmp_path):config_path = tmp_path / ".config" / "opencode" / "opencode.json"config_path.parent.mkdir(parents=True, exist_ok=True)