refactor(sessions)!: retire the global shared session (#6621)

Co-authored-by: chengyongru <chengyongru.ai@gmail.com>
This commit is contained in:
Xubin Renandchengyongru authored and GitHub committed 2026-11-12 09:55:55 +08:00
1 parent 28d73b6942
commit e6b0aec2a8
77 files changed
+311 -1255

No files matched your search

+1 -1
View File
@@ -183,7 +183,7 @@ Session history is the near-term conversation replay. Memory is the longer-term
`SessionState` owns both logical histories. `history_entries` stores transport-neutral inputs, completed answer/reasoning segments, activity, historical file diffs, response sources, and completion statistics/outcomes; `history_turns` and `history_heads` provide bounded paging and revision/sidebar projections. WebUI converts these facts into its existing transcript protocol inside an owner-managed read snapshot. Delta frames remain transient. A turn may commit facts as it progresses; this is not a transaction held across a model request or network delivery.
Every append carries the generation admitted before execution, including a distinct display destination under unified-session routing. A missing or replaced session rejects the append instead of creating a new row. Delete/reset cascades through both logical histories; fork copies its canonical and display prefixes in one SQLite transaction. Future in-place history replacement should use that same owner transaction rather than file journals or replay-cache writes.
Every append carries the generation admitted before execution, including the display destination when an internal turn reports to a different chat. A missing or replaced session rejects the append instead of creating a new row. Delete/reset cascades through both logical histories; fork copies its canonical and display prefixes in one SQLite transaction. Future in-place history replacement should use that same owner transaction rather than file journals or replay-cache writes.
`nanobot/webui/history.py` resolves legacy `<stem>.jsonl` files and numbered JSONL files inside `<stem>.segments/` directories, then imports them through `SessionState` before recovery or transport admission. Recorded chat identities determine the target session; histories without a recorded identity require an unambiguous existing canonical session. Display-only histories with a recorded identity are imported into the starting workspace namespace. Histories owned by exactly one other namespace are deferred to that namespace; duplicate owners and malformed records fail startup.
+1 -1
View File
@@ -166,7 +166,7 @@ Future runs use the new chat's history and reply there by default. Previous mess
You can discuss each new result in that same chat. Background task results also return there. If you delete that chat, nanobot asks you to confirm deletion of its scheduled tasks as well. Cancelling the deletion keeps the chat and tasks.
The list shows chats available on this gateway that use the same workspace and access permissions. A chat-app destination appears only after its channel is running and nanobot has received a message there. If the chat you want is missing, first send nanobot a message in that chat, then confirm its channel is running. You cannot choose a raw recipient ID, a chat on another host, a unified session, a system job, or a local trigger. Older gateway versions show this list as read-only.
The list shows chats available on this gateway that use the same workspace and access permissions. A chat-app destination appears only after its channel is running and nanobot has received a message there. If the chat you want is missing, first send nanobot a message in that chat, then confirm its channel is running. You cannot choose a raw recipient ID, a chat on another host, a system job, or a local trigger. Older gateway versions show this list as read-only.
If a scheduled turn is running or queued, wait for it to finish before changing the chat. The current scheduler also rejects a change while another scheduled turn is active. If another editor changes the task, reopen the task and review the latest instructions. A rejected save leaves the draft visible.
+1 -3
View File
@@ -117,9 +117,7 @@ See [`providers.md`](./providers.md) for practical examples and [`configuration.
## Channels and Sessions
Each channel maps inbound messages to a session key. That lets independent conversations keep separate history. The WebUI also supports multiple chats and workspace-scoped metadata for project workspaces.
`agents.defaults.unifiedSession` can intentionally share one session across channels for a single-user multi-device setup. Leave it off if you expect separate people, groups, channels, or projects to keep separate context.
By default, each channel and chat has its own session and conversation history. The WebUI also supports multiple chats and workspace-scoped metadata for project workspaces.
## Memory, Sessions, and Dream
+1 -34
View File
@@ -47,7 +47,7 @@ This page is the complete configuration reference. For task-oriented setup, use
| Add MCP servers | [MCP](#mcp-model-context-protocol) |
| Review shell, workspace, and SSRF controls | [Security](#security) |
| Control access and pairing | [Pairing](#pairing) |
| Tune gateway jobs, sessions, and tools | [Gateway Heartbeat](#gateway-heartbeat), [Auto Compact](#auto-compact), [Unified Session](#unified-session), [Tool Hint Max Length](#tool-hint-max-length) |
| Tune gateway jobs, sessions, and tools | [Gateway Heartbeat](#gateway-heartbeat), [Auto Compact](#auto-compact), [Tool Hint Max Length](#tool-hint-max-length) |
## Where a Setting Lives
@@ -2595,39 +2595,6 @@ Common examples: `UTC`, `America/New_York`, `America/Los_Angeles`, `Europe/Londo
> Need another timezone? Browse the full [IANA Time Zone Database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).
## Unified Session
Open **Settings → System** and change **Shared sessions**. Enable it only for a single-user setup where conversations should share context. Follow any restart prompt.
By default, each channel × chat ID combination gets its own session. If you use nanobot across multiple channels (e.g. Telegram + Discord + CLI) and want them to share the same conversation, enable `unifiedSession`:
<details>
<summary>Manual configuration</summary>
```json
{
"agents": {
"defaults": {
"unifiedSession": true
}
}
}
```
</details>
When enabled, all incoming messages — regardless of which channel they arrive on — are routed into a single shared session. Switching from Telegram to Discord (or any other channel) continues the same conversation seamlessly.
| Behavior | `false` (default) | `true` |
|----------|-------------------|--------|
| Conversation scope | Separate for each channel and chat | Shared across channels and chats |
| Cross-channel continuity | No | Yes |
| `/new` clears | Current channel session | Shared session |
| `/stop` finds tasks | By channel session | By shared session |
| Separate conversations explicitly assigned by a channel (e.g. Telegram threads) | Kept separate | Still kept separate |
> Use this only for single-user, multi-device setups: messages from different chats can share conversation context. It is **off by default**.
## Disabled Skills
Open **Skills** in the sidebar, find the installed skill, and turn its switch off or on. This controls whether the agent can load it without deleting its files.
-1
View File
@@ -330,7 +330,6 @@ See [`chat-apps.md`](./chat-apps.md) for channel-specific setup.
| Memory does not update immediately | Dream consolidation is periodic; recent turns still live in session history. |
| Sessions disappear after changing `--config` | Sessions follow the config directory at `<config-dir>/sessions/<workspace-id>/`; use the original config path or copy that `sessions/` directory into the new config directory while nanobot is stopped. |
| Sessions disappear after moving a workspace | Keep the workspace's `.nanobot/workspace-id` file with the move or backup. If it was lost, restore that marker from backup before starting nanobot. |
| You want one shared session across devices | Set `agents.defaults.unifiedSession` intentionally; otherwise keep separate sessions. |
## Collect Useful Evidence
+4
View File
@@ -62,6 +62,10 @@ Back up the configuration and data before updating. The old top-level `api` bloc
To read old API conversations after updating, open the same configuration and workspace with [the Python SDK](./python-sdk.md#botsessions). Use `await bot.sessions.list()` to find keys such as `api:default` and `api:<session_id>`, then use `await bot.sessions.get(key)` to read their messages. If the old launcher used a separate API workspace, pass that workspace to `Nanobot.from_config(config_path, workspace=workspace)` instead of using the Gateway's workspace.
## Shared sessions removal
The shared sessions feature has been removed. The old `agents.defaults.unifiedSession` or `unified_session` setting is ignored.
## Recover an interrupted update
Refreshing restores saved progress, **not installation consent**. A staged update may ask you to review and confirm it again. A disconnected page cannot tell whether the worker stopped: do not start another installation while it reconnects. Closing the browser does not stop the managed update or its recovery.
+1 -1
View File
@@ -167,7 +167,7 @@ Temporary does not mean consequence-free. Requests still go to the configured mo
Project selection and Full Access controls require an owner-authenticated WebUI connection. Ordinary WebSocket clients stay within the workspace and access mode configured by the operator; an owner's saved topic scope or WebUI preference does not grant a client additional access. Existing topics remain available to the owner, while clients attempting to resume a topic outside their configured authority receive an error instead of silently changing its scope. Legacy plain-text clients use the same permission boundary. Keep the configured `tokenIssueSecret` (or fallback `token`) private: it can issue owner credentials. Share short-lived client connection tokens, not that owner secret.
With unified sessions, inputs with different workspace permissions wait for the active turn to finish, then run with their own permissions. Inputs with the same scope can still join the active turn.
Inputs to the same session with different workspace permissions wait for the active turn to finish, then run with their own permissions. Inputs with the same scope can still join the active turn.
Use the workspace picker to browse folders on the connected nanobot host, enter an absolute path, or return to recent and starred projects; favorites persist across gateway restarts. The host name appears above saved locations. Project paths refer to that machine, not the browser's filesystem.
-6
View File
@@ -17,7 +17,6 @@ from nanobot.runtime_context import (
append_runtime_context,
)
from nanobot.security.workspace_access import WorkspaceScopeResolver
from nanobot.session.keys import last_channel_from_metadata
from nanobot.session.manager import Session
from nanobot.session.summary import SessionSummary
from nanobot.utils.helpers import detect_image_mime, image_placeholder_text, load_bundled_template
@@ -38,14 +37,9 @@ class PersistedPromptContextResolver:
"""Restore prompt routing context when no inbound message is available."""
workspace_scopes: WorkspaceScopeResolver
unified_session: bool = False
def __call__(self, session: Session) -> tuple[str | None, Path]:
channel = session.key.split(":", 1)[0] if ":" in session.key else None
if self.unified_session:
route = last_channel_from_metadata(session.metadata)
if route is not None:
channel = route[0]
scope = self.workspace_scopes.for_turn(
channel=channel,
message_metadata=None,
+24 -52
View File
@@ -81,7 +81,6 @@ from nanobot.security.workspace_access import (
from nanobot.session import turn_continuation
from nanobot.session.automation_turns import automation_history_overrides
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
from nanobot.session.keys import UNIFIED_SESSION_KEY, remember_last_channel
from nanobot.session.manager import SESSION_CACHE_MAX_SIZE, Session, SessionManager, SessionPolicy
from nanobot.session.message_metadata import input_history_metadata, persisted_message
from nanobot.session.model_selection import (
@@ -291,7 +290,6 @@ class AgentLoop:
session_ttl_minutes: int = 0,
hooks: list[AgentHook] | None = None,
hook_factories: list[AgentTurnHookFactory] | None = None,
unified_session: bool = False,
disabled_skills: list[str] | None = None,
tools_config: ToolsConfig | None = None,
network_config: NetworkConfig | None = None,
@@ -392,7 +390,6 @@ class AgentLoop:
get_tool_definitions=self.tools.get_definitions,
resolve_prompt_context=PersistedPromptContextResolver(
workspace_scopes=self.workspace_scopes,
unified_session=unified_session,
),
)
self.subagents = SubagentManager(
@@ -408,7 +405,6 @@ class AgentLoop:
consolidator=self.consolidator,
session_manager=self.sessions,
)
self._unified_session = unified_session
self._running = False
self._runtime_context_providers: list[RuntimeContextProvider] = []
self._active_tasks: dict[str, set[asyncio.Task[Any]]] = {}
@@ -510,7 +506,6 @@ class AgentLoop:
restrict_to_workspace=config.tools.restrict_to_workspace,
channels_config=config.channels,
timezone=defaults.timezone,
unified_session=defaults.unified_session,
disabled_skills=defaults.disabled_skills,
session_ttl_minutes=defaults.session_ttl_minutes,
idle_compact_check_interval_seconds=defaults.idle_compact_check_interval_seconds,
@@ -854,7 +849,6 @@ class AgentLoop:
async def _dispatch_command_inline(
self,
msg: InboundMessage,
key: str,
raw: str,
dispatch_fn: Callable[
[CommandContext], Awaitable[CommandExpansion | InboundMessage | OutboundMessage | None],
@@ -867,7 +861,7 @@ class AgentLoop:
async def dispatch_and_publish() -> None:
_, automation_metadata = automation_history_overrides(msg.metadata)
ctx = CommandContext(
msg=msg, session=None, key=key, raw=raw, loop=self,
msg=msg, session=None, key=msg.session_key, raw=raw, loop=self,
is_user_turn=(
msg.is_user_input and msg.channel != "system"
and msg.sender_id != "subagent" and not automation_metadata
@@ -964,11 +958,6 @@ class AgentLoop:
"""Forget ephemeral file-read state for a reset or removed session."""
self._file_state_store.discard(key)
def _effective_session_key(self, msg: InboundMessage) -> str:
if self._unified_session and not msg.session_key_override:
return UNIFIED_SESSION_KEY
return msg.session_key
def _can_inject_message(self, msg: InboundMessage) -> bool:
if turn_continuation.internal_continuation_inbound(msg.metadata) or any(
coordinator.owns_turn(msg) for coordinator in self._automation_turn_coordinators
@@ -1007,8 +996,6 @@ class AgentLoop:
if automation_metadata:
return
delivery.remember_session_route(session.metadata)
if self._unified_session and session.key == UNIFIED_SESSION_KEY:
remember_last_channel(session.metadata, msg.channel, msg.chat_id)
async def _run_agent_loop(
self,
@@ -1439,7 +1426,7 @@ class AgentLoop:
try:
await self._dispatch_inbound(msg)
except (SessionOperationQueueFullError, SessionConflictError, ExecutionControlError) as exc:
key = self._effective_session_key(msg)
key = msg.session_key
logger.warning("Session input rejected for {}: {}", key, exc)
if msg.is_user_input:
delivery = self.turn_delivery_factory.unrouted(msg, key)
@@ -1449,48 +1436,36 @@ class AgentLoop:
async def _dispatch_inbound(self, msg: InboundMessage) -> None:
raw = command_text(msg)
effective_key = self._effective_session_key(msg)
key = msg.session_key
if msg.metadata.get(INBOUND_META_RUNTIME_CONTROL) == RUNTIME_CONTROL_SESSION_DISCARD:
await self.discard_session(msg.session_key)
await self.discard_session(key)
return
if (
msg.require_existing_session
and await self.sessions.state.read_metadata(effective_key) is None
and await self.sessions.state.read_metadata(key) is None
):
return
if msg.is_user_input:
await self.runtime_event_publisher.user_input_accepted(msg, effective_key)
await self.runtime_event_publisher.user_input_accepted(msg, key)
if msg.channel != "system" and self.commands.is_priority(raw):
await self._dispatch_command_inline(
msg, effective_key, raw,
self.commands.dispatch_priority,
)
await self._dispatch_command_inline(msg, raw, self.commands.dispatch_priority)
return
routed_msg = msg
if effective_key != msg.session_key:
routed_msg = dataclasses.replace(
msg,
session_key_override=effective_key,
)
# Mid-turn injection bypasses _dispatch_one, so admit before joining
# an active queue. Admission may cancel its worker and release the queue.
# Mid-turn injection bypasses _dispatch_one. Admit before joining an
# active queue; admission may cancel its worker and release the queue.
if (
effective_key in self._pending_queues
key in self._pending_queues
and self._recovery_admission is not None
and not await self._recovery_admission.admit(routed_msg)
and not await self._recovery_admission.admit(msg)
):
return
# If this session already has an active pending queue (i.e. a task
# is processing this session), route the message there for mid-turn
# injection instead of creating a competing task.
if effective_key in self._pending_queues:
if msg.channel != "system" and self.commands.is_dispatchable_command(raw):
await self._dispatch_command_inline(
msg, effective_key, raw,
self.commands.dispatch,
)
return
await self._enqueue_session_message(routed_msg)
if (
key in self._pending_queues
and msg.channel != "system"
and self.commands.is_dispatchable_command(raw)
):
await self._dispatch_command_inline(msg, raw, self.commands.dispatch)
return
await self._enqueue_session_message(msg)
def maintenance(self) -> AbstractContextManager[None]:
"""Close task intake only when this runtime's accepted work is finished.
@@ -1540,11 +1515,9 @@ class AgentLoop:
async def _enqueue_session_message(self, msg: InboundMessage) -> None:
self.bus.admission.check()
session_key = self._effective_session_key(msg)
session_key = msg.session_key
if not self.subagents.accepts_result(msg, session_key):
return
if session_key != msg.session_key:
msg = dataclasses.replace(msg, session_key_override=session_key)
for coordinator in self._automation_turn_coordinators:
if coordinator.defer_if_active(
@@ -1629,7 +1602,7 @@ class AgentLoop:
msg: InboundMessage,
pending: asyncio.Queue[InboundMessage],
) -> None:
session_key = self._effective_session_key(msg)
session_key = msg.session_key
# The request context is reset before errors reach this boundary, and
# discard may evict the session while a turn is still unwinding.
session = self.sessions.state.peek_header(session_key)
@@ -1699,19 +1672,18 @@ class AgentLoop:
or self._preserve_inflight_turns_on_shutdown
):
raise exc
key = self._effective_session_key(msg)
generation = delivery.delivery_message.session_generation
try:
session = await self.sessions.state.read(key)
session = await self.sessions.state.read(session_key)
if session is None or (generation is not None and session.generation != generation):
self.runtime_event_publisher.clear_turn(session_key, run_id=delivery.run_id)
skip_idle = True
raise exc
restore_runtime_checkpoint(session)
await self.sessions.state.finish_turn(session)
logger.info("Saved cancelled turn for session {}", key)
logger.info("Saved cancelled turn for session {}", session_key)
except SessionConflictError:
current = await self.sessions.state.read_header(key)
current = await self.sessions.state.read_header(session_key)
if current is None or (generation is not None and current.generation != generation):
self.runtime_event_publisher.clear_turn(session_key, run_id=delivery.run_id)
skip_idle = True
+1 -1
View File
@@ -908,7 +908,7 @@ class SubagentManager:
# Inject as system message to trigger main agent.
# Use session_key_override to align with the main agent's effective
# session key (which accounts for unified sessions) so the result is
# session key (including any explicit override) so the result is
# routed to the correct pending queue (mid-turn injection) instead of
# being dispatched as a competing independent task.
override = origin.get("session_key") or f"{origin['channel']}:{origin['chat_id']}"
+1 -6
View File
@@ -17,7 +17,6 @@ from nanobot.agent.tools.schema import (
from nanobot.cron.service import CronService
from nanobot.cron.session_turns import is_bound_cron_job, is_cron_turn
from nanobot.cron.types import CronJob, CronJobState, CronSchedule
from nanobot.session.keys import UNIFIED_SESSION_KEY
_CRON_PARAMETERS = tool_parameters_schema(
action=StringSchema(
@@ -81,11 +80,7 @@ class CronTool(Tool):
ctx = current_request_context()
if ctx is None:
return "", "", "", {}
raw_key = f"{ctx.channel}:{ctx.chat_id}" if ctx.channel and ctx.chat_id else ""
session_key = (
raw_key if ctx.session_key == UNIFIED_SESSION_KEY else (ctx.session_key or "")
)
return session_key, ctx.channel or "", ctx.chat_id or "", dict(ctx.metadata or {})
return ctx.session_key or "", ctx.channel or "", ctx.chat_id or "", dict(ctx.metadata or {})
@staticmethod
def _validate_timezone(tz: str) -> str | None:
+1 -1
View File
@@ -62,7 +62,7 @@ class MyTool(Tool):
"_session_locks", "_active_tasks", "_background_tasks",
# Security boundaries (inspect + modify both blocked)
"restrict_to_workspace", "channels_config",
"_concurrency_gate", "_unified_session", "_extra_hooks", "_hook_factories",
"_concurrency_gate", "_extra_hooks", "_hook_factories",
})
READ_ONLY = frozenset({
+3 -11
View File
@@ -30,11 +30,7 @@ from nanobot.events import (
)
from nanobot.providers.base import LLMUsage
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
from nanobot.session.keys import (
UNIFIED_SESSION_KEY,
is_internal_session,
last_channel_from_metadata,
)
from nanobot.session.keys import is_internal_session
from nanobot.session.message_metadata import input_history_metadata
from nanobot.utils.cancellation import shield_and_drain
from nanobot.utils.helpers import strip_think
@@ -165,12 +161,8 @@ class TurnDeliveryFactory:
else:
# Older sessions have no route snapshot. Only direct clients have a
# session key that is also an unambiguous delivery address.
route = (
last_channel_from_metadata(session_metadata)
if session_key == UNIFIED_SESSION_KEY
else tuple(session_key.split(":", 1))
)
if not route or len(route) != 2 or route[0] not in {"websocket", "cli"}:
route = session_key.split(":", 1)
if len(route) != 2 or route[0] not in {"websocket", "cli"}:
return EventSink()
channel, chat_id = route
metadata = {}
-1
View File
@@ -216,7 +216,6 @@ class ChannelManager:
static_dist_path=static_path,
workspace_path=workspace,
default_restrict_to_workspace=self.config.tools.restrict_to_workspace,
unified_session=self.config.agents.defaults.unified_session,
config_path=self._config_path,
disabled_skills=set(self.config.agents.defaults.disabled_skills),
runtime_model_name=self._webui_runtime_model_name,
-2
View File
@@ -426,7 +426,6 @@ class WebSocketChannel(BaseChannel):
media: list[str] | None,
metadata: dict[str, Any],
is_dm: bool,
session_key: str | None,
require_existing_session: bool,
session_generation: str | None,
) -> None:
@@ -437,7 +436,6 @@ class WebSocketChannel(BaseChannel):
media=media,
metadata=metadata,
is_dm=is_dm,
session_key=session_key,
require_existing_session=require_existing_session,
session_generation=session_generation,
)
@@ -510,7 +510,6 @@ async def test_temporary_chat_is_transient_and_discarded(history, bus, tmp_path)
inbound = bus.publish_inbound.await_args_list[0].args[0]
assert inbound.session_key == f"websocket:{chat_id}"
assert inbound.session_key_override == f"websocket:{chat_id}"
assert inbound.require_existing_session is True
assert inbound.metadata["cli_apps"] == [{"name": "drawio"}]
assert inbound.metadata[WORKSPACE_SCOPE_METADATA_KEY] == {
@@ -5948,7 +5947,6 @@ def test_sessions_list_includes_active_run_started_at(monkeypatch) -> None:
("abc", True),
("a1b2_c:d-e", True),
("x" * 64, True),
("unified:default", True),
("", False),
("x" * 65, False),
("has space", False),
@@ -21,7 +21,6 @@ from nanobot.cron.service import CronService
from nanobot.cron.types import CronJob, CronPayload, CronRunResult, CronSchedule
from nanobot.optional_features import InstallResult
from nanobot.security.workspace_access import WORKSPACE_SCOPE_METADATA_KEY
from nanobot.session.keys import UNIFIED_SESSION_KEY
from nanobot.session.manager import Session, SessionManager
from nanobot.session.session_handles import SessionHandleResolver
from nanobot.triggers.local_store import LocalTriggerStore
@@ -429,7 +428,7 @@ async def test_session_automations_route_ignores_unified_owner(
name="Unified check",
schedule=hourly,
message="Check the shared session",
session_key=UNIFIED_SESSION_KEY,
session_key="unified:default",
origin_channel="websocket",
origin_chat_id="abc",
)
@@ -17,7 +17,6 @@ from nanobot.channels.websocket.runtime import WebSocketChannel
from nanobot.config.schema import Config
from nanobot.providers.base import LLMProvider, LLMResponse
from nanobot.runtime_context import public_history_message
from nanobot.session.keys import UNIFIED_SESSION_KEY, session_key_for_channel
from nanobot.session.manager import SessionManager
from nanobot.session.webui_turns import clear_websocket_turns
@@ -64,24 +63,23 @@ class _Runtime:
async def execute(self, message: InboundMessage) -> None:
await self.loop._enqueue_session_message(message)
tasks = self.loop._active_tasks[self.loop._effective_session_key(message)]
tasks = self.loop._active_tasks[message.session_key]
await asyncio.gather(*tuple(tasks))
@pytest.fixture(params=[False, True], ids=["separate", "shared"])
async def runtime(request: pytest.FixtureRequest, tmp_path: Path) -> AsyncIterator[_Runtime]:
unified = request.param
@pytest.fixture
async def runtime(tmp_path: Path) -> AsyncIterator[_Runtime]:
workspace = tmp_path / "workspace"
workspace.mkdir()
config = Config.model_validate({"agents": {"defaults": {
"workspace": str(workspace), "unifiedSession": unified,
"workspace": str(workspace), "unifiedSession": True,
}}})
bus = MessageBus()
sessions = SessionManager(workspace)
provider = _Provider()
loop = AgentLoop(
bus=bus, provider=provider, workspace=workspace,
session_manager=sessions, unified_session=unified,
session_manager=sessions,
)
manager = ChannelManager(
config, bus, session_manager=sessions, webui_static_dist=False,
@@ -107,18 +105,12 @@ async def test_webui_admission_executes_with_the_routed_session(runtime: _Runtim
message = await runtime.message(chat_id)
await runtime.execute(message)
key = session_key_for_channel(
"websocket", chat_id, unified_session=runtime.channel.gateway.unified_session,
)
key = f"websocket:{chat_id}"
session = await runtime.sessions.state.read(key)
assert session is not None
assert [public_history_message(record)["content"] for record in session.messages
if record["role"] == "user"] == (
["hello", "hello"] if key == UNIFIED_SESSION_KEY and chat_id == "chat-b"
else ["hello"]
)
display = await runtime.sessions.state.read_metadata(f"websocket:{chat_id}")
assert display is not None and display["metadata"]["webui"] is True
if record["role"] == "user"] == ["hello"]
assert session.metadata["webui"] is True
assert runtime.provider.calls == 2
@@ -127,7 +119,7 @@ async def test_replaced_execution_session_rejects_accepted_input(
runtime: _Runtime, operation: str,
) -> None:
message = await runtime.message("chat-stale")
key = runtime.loop._effective_session_key(message)
key = message.session_key
if operation == "reset":
await runtime.sessions.state.reset(key)
else:
@@ -153,6 +145,11 @@ async def test_failed_transport_admission_removes_new_sessions(
async def test_temporary_chat_retains_its_own_generation(history, runtime: _Runtime) -> None:
state = runtime.sessions.state
retired = await state.get("unified:default")
retired.add_message("user", "Old shared history")
await state.finish_turn(retired)
await runtime.channel._dispatch_envelope(
runtime.connection, "webui-client", {"type": "new_temporary_chat"},
)
@@ -161,8 +158,8 @@ async def test_temporary_chat_retains_its_own_generation(history, runtime: _Runt
first = await runtime.message(chat_id)
await runtime.execute(first)
assert runtime.provider.calls == 1
assert runtime.loop._effective_session_key(first) == f"websocket:{chat_id}"
assert await runtime.sessions.state.list_sessions() == []
assert first.session_key == f"websocket:{chat_id}"
assert {row["key"] for row in await state.list_sessions()} == {retired.key}
assert history.read(f"websocket:{chat_id}") == []
queued = await runtime.message(chat_id, "discarded input")
@@ -170,5 +167,7 @@ async def test_temporary_chat_retains_its_own_generation(history, runtime: _Runt
await runtime.execute(queued)
assert runtime.provider.calls == 1
assert await runtime.sessions.state.read(first.session_key) is None
assert await runtime.sessions.state.list_sessions() == []
assert await state.read(first.session_key) is None
assert {row["key"] for row in await state.list_sessions()} == {retired.key}
saved = runtime.sessions.read_session_snapshot(retired.key)
assert saved is not None and saved.messages == retired.messages
+3 -34
View File
@@ -44,12 +44,7 @@ from nanobot.config.schema import Config
from nanobot.gateway.runtime import GatewayHealthIdentity, GatewayInstance, GatewayRuntime
from nanobot.installation_lock import installation_access
from nanobot.security.network import is_loopback_host
from nanobot.session.keys import (
HEARTBEAT_SESSION_KEY,
UNIFIED_SESSION_KEY,
last_channel_from_metadata,
session_key_for_channel,
)
from nanobot.session.keys import HEARTBEAT_SESSION_KEY
from nanobot.session.manager import SessionManager
from nanobot.utils.evaluator import evaluate_response, resolve_evaluator_prompt
from nanobot.utils.helpers import sync_workspace_templates
@@ -73,7 +68,6 @@ async def _deliver_to_channel(
*,
bus: MessageBus,
session_manager: SessionManager,
unified_session: bool = False,
record: bool = False,
session_key: str | None = None,
session_generation: str | None = None,
@@ -89,9 +83,7 @@ async def _deliver_to_channel(
)
key = session_key or (raw_key if isinstance(raw_key, str) else None)
if key is None:
key = session_key_for_channel(
msg.channel, msg.chat_id, unified_session=unified_session,
)
key = f"{msg.channel}:{msg.chat_id}"
if msg.channel == "websocket":
from nanobot.agent.turn_delivery import TurnRoute
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
@@ -274,7 +266,6 @@ def _pick_heartbeat_target_from_sessions(
enabled_channels: Iterable[str],
sessions: Iterable[dict[str, Any]],
archived_keys: Iterable[str],
unified_session_metadata: dict[str, Any] | None = None,
) -> tuple[str, str]:
enabled = set(enabled_channels)
archived = set(archived_keys)
@@ -282,13 +273,6 @@ def _pick_heartbeat_target_from_sessions(
key = item.get("key") or ""
if key in archived:
continue
if key == UNIFIED_SESSION_KEY:
route = last_channel_from_metadata(unified_session_metadata)
if route is not None:
channel, chat_id = route
if channel not in {"cli", "system"} and channel in enabled:
return channel, chat_id
continue
if ":" not in key:
continue
channel, chat_id = key.split(":", 1)
@@ -591,7 +575,6 @@ def _run_claimed_gateway(
recovery = RecoveryCoordinator(
sessions=session_manager,
bus=bus,
unified_session=config.agents.defaults.unified_session,
)
from nanobot.goal.assembly import install_goal
@@ -624,18 +607,10 @@ def _run_claimed_gateway(
schedule_background=_schedule_webui_background,
recovery=recovery,
)
def _channel_session_key(channel: str, chat_id: str) -> str:
return session_key_for_channel(
channel,
chat_id,
unified_session=config.agents.defaults.unified_session,
)
deliver_to_channel = partial(
_deliver_to_channel,
bus=bus,
session_manager=session_manager,
unified_session=config.agents.defaults.unified_session,
)
message_tool = agent.tools.get("message")
@@ -719,7 +694,7 @@ def _run_claimed_gateway(
channel, chat_id = await _pick_heartbeat_target()
if channel == "cli":
return None
delivery_key = _channel_session_key(channel, chat_id)
delivery_key = f"{channel}:{chat_id}"
delivery_session = await session_manager.state.read(delivery_key)
if delivery_session is None:
return None
@@ -835,16 +810,10 @@ def _run_claimed_gateway(
async def _pick_heartbeat_target() -> tuple[str, str]:
archived_keys = await ensure_webui_session_archives(session_manager.state)
unified_metadata = None
if config.agents.defaults.unified_session:
record = await session_manager.state.read_metadata(UNIFIED_SESSION_KEY)
if isinstance(record, dict) and isinstance(record.get("metadata"), dict):
unified_metadata = record["metadata"]
return _pick_heartbeat_target_from_sessions(
enabled_channels=channels.enabled_channels,
sessions=await session_manager.state.list_sessions(),
archived_keys=archived_keys,
unified_session_metadata=unified_metadata,
)
if channels.enabled_channels:
+1 -8
View File
@@ -888,18 +888,11 @@ async def cmd_trigger(ctx: CommandContext) -> OutboundMessage:
if store is None:
store = LocalTriggerStore(loop.workspace)
from nanobot.session.keys import UNIFIED_SESSION_KEY
session_key = (
ctx.msg.session_key
if ctx.key == UNIFIED_SESSION_KEY
else ctx.key
)
trigger = store.create(
name=name,
channel=ctx.msg.channel,
chat_id=ctx.msg.chat_id,
session_key=session_key,
session_key=ctx.key,
sender_id="trigger",
origin_metadata=dict(ctx.msg.metadata or {}),
)
-1
View File
@@ -193,7 +193,6 @@ class AgentDefaults(Base):
timezone_mode: Literal["auto", "manual"] = "auto"
bot_name: str = "nanobot"
bot_icon: str = "🐈" # Short icon (emoji or text) shown next to the bot name in CLI; "" to omit
unified_session: bool = False # Share one session across all channels (single-user multi-device)
disabled_skills: list[str] = Field(default_factory=list) # Skill names to exclude from loading (e.g. ["summarize", "skill-creator"])
session_ttl_minutes: int = Field(
default=15,
-38
View File
@@ -1,11 +1,6 @@
from __future__ import annotations
from collections.abc import Mapping, MutableMapping
from typing import Any
UNIFIED_SESSION_KEY = "unified:default"
HEARTBEAT_SESSION_KEY = "heartbeat"
LAST_CHANNEL_METADATA_KEY = "last_channel"
def is_dream_session(key: str) -> bool:
@@ -16,36 +11,3 @@ def is_dream_session(key: str) -> bool:
def is_internal_session(key: str) -> bool:
"""Identify maintenance sessions whose context is not a user conversation."""
return key == HEARTBEAT_SESSION_KEY or is_dream_session(key)
def session_key_for_channel(channel: str, chat_id: str, *, unified_session: bool = False) -> str:
"""Return the session key for a channel/chat pair."""
if unified_session:
return UNIFIED_SESSION_KEY
return f"{channel}:{chat_id}"
def remember_last_channel(
metadata: MutableMapping[str, Any],
channel: str,
chat_id: str,
) -> None:
"""Persist the latest concrete delivery route in session metadata."""
if not channel or not chat_id:
return
metadata[LAST_CHANNEL_METADATA_KEY] = f"{channel}:{chat_id}"
def last_channel_from_metadata(
metadata: Mapping[str, Any] | None,
) -> tuple[str, str] | None:
"""Return a concrete delivery route from persisted session metadata."""
if not isinstance(metadata, Mapping):
return None
route = metadata.get(LAST_CHANNEL_METADATA_KEY)
if not isinstance(route, str) or ":" not in route:
return None
channel, chat_id = route.split(":", 1)
if not channel or not chat_id:
return None
return channel, chat_id
+22 -100
View File
@@ -85,10 +85,6 @@ class _WebsocketTurn:
_WEBSOCKET_ACTIVE_TURNS: dict[str, dict[str, _WebsocketTurn]] = {}
def _validated_llm_runtime(value: object) -> LLMRuntime | None:
return value if isinstance(value, LLMRuntime) else None
def _sync_websocket_turn_projection(chat_id: str) -> None:
turns = _WEBSOCKET_ACTIVE_TURNS.get(chat_id)
if not turns:
@@ -155,62 +151,20 @@ def _title_inputs(session: Session) -> tuple[str, str]:
return user_text, assistant_text
def _latest_title_inputs(session: Session) -> tuple[str, str]:
user_text = ""
assistant_text = ""
for message in reversed(session.messages):
if message.get("_command") is True:
continue
if is_hidden_history_message(message):
continue
message = public_history_message(message)
role = message.get("role")
content = message.get("content")
if not isinstance(content, str) or not content.strip():
continue
content = strip_think(content)
if not content:
continue
if role == "user" and not user_text:
user_text = content.strip()
elif role == "assistant" and not assistant_text:
assistant_text = content.strip()
if user_text and assistant_text:
break
return user_text, assistant_text
async def maybe_generate_webui_title(
*,
sessions: SessionManager,
session_key: str,
provider: LLMProvider,
model: str,
target_session_key: str | None = None,
) -> bool:
"""Generate and persist a short title for WebUI-owned sessions.
``session_key`` owns the conversation content. Under unified-session
routing this is the shared session while WebUI renders per-chat sessions,
so pass ``target_session_key`` to project the title onto that per-chat
session instead of storing it on the shared one.
"""
routed_session = await sessions.state.read(session_key)
if routed_session is None:
"""Generate and persist a short title for a WebUI-owned session."""
session = await sessions.state.read(session_key)
if session is None or session.metadata.get(WEBUI_SESSION_METADATA_KEY) is not True:
return False
target_is_routed = target_session_key is None or target_session_key == session_key
if target_is_routed or target_session_key is None:
target_session = routed_session
else:
target_session = await sessions.state.get(target_session_key)
if (
routed_session.metadata.get(WEBUI_SESSION_METADATA_KEY) is not True
and target_session.metadata.get(WEBUI_SESSION_METADATA_KEY) is not True
):
if session.metadata.get(WEBUI_TITLE_USER_EDITED_METADATA_KEY) is True:
return False
if target_session.metadata.get(WEBUI_TITLE_USER_EDITED_METADATA_KEY) is True:
return False
current_title = target_session.metadata.get(WEBUI_TITLE_METADATA_KEY)
current_title = session.metadata.get(WEBUI_TITLE_METADATA_KEY)
if isinstance(current_title, str) and current_title.strip():
cleaned_current_title = clean_generated_title(current_title)
if cleaned_current_title:
@@ -220,17 +174,12 @@ async def maybe_generate_webui_title(
and metadata.get(WEBUI_TITLE_USER_EDITED_METADATA_KEY) is not True):
metadata[WEBUI_TITLE_METADATA_KEY] = cleaned_current_title
await sessions.state.mutate_metadata(
target_session.key, clean_title, expected_generation=target_session.generation,
session.key, clean_title, expected_generation=session.generation,
)
return False
target_session.metadata.pop(WEBUI_TITLE_METADATA_KEY, None)
session.metadata.pop(WEBUI_TITLE_METADATA_KEY, None)
if target_is_routed:
user_text, assistant_text = _title_inputs(routed_session)
else:
# Shared-session content mixes every channel; generation runs right
# after this turn, so its exchange is the latest pair.
user_text, assistant_text = _latest_title_inputs(routed_session)
user_text, assistant_text = _title_inputs(session)
if not user_text:
return False
@@ -250,7 +199,7 @@ async def maybe_generate_webui_title(
try:
with (
llm_usage_source("system"),
logger.contextualize(purpose="webui_title", session_key=target_session.key),
logger.contextualize(purpose="webui_title", session_key=session.key),
):
response = await provider.chat_stream_with_retry(
[
@@ -293,37 +242,13 @@ async def maybe_generate_webui_title(
return True
try:
changed, _ = await sessions.state.mutate_metadata(
target_session.key, set_title, expected_generation=target_session.generation,
session.key, set_title, expected_generation=session.generation,
)
except SessionConflictError:
return False
return changed
async def maybe_generate_webui_title_after_turn(
*,
channel: str,
chat_id: str,
metadata: dict[str, Any],
sessions: SessionManager,
session_key: str,
provider: LLMProvider,
model: str,
) -> bool:
if channel != "websocket" or metadata.get(WEBUI_SESSION_METADATA_KEY) is not True:
return False
origin_session_key = f"{channel}:{chat_id}"
return await maybe_generate_webui_title(
sessions=sessions,
session_key=session_key,
provider=provider,
model=model,
target_session_key=(
origin_session_key if origin_session_key != session_key else None
),
)
def websocket_turn_wall_started_at(chat_id: str) -> float | None:
"""Return ``time.time()`` when the active user turn began, if still running."""
return _WEBSOCKET_TURN_WALL_STARTED_AT.get(chat_id)
@@ -528,7 +453,7 @@ class WebuiTurnRoutePolicy:
if revision is None:
raise SessionConflictError("display destination is no longer active")
admitted = metadata.get(HISTORY_GENERATION_METADATA_KEY)
# A distinct alias admitted by the WebSocket edge must still be current.
# An admitted display destination must still be current.
if admitted not in (None, generation, revision[0]):
raise SessionConflictError("display destination generation was replaced")
metadata[HISTORY_GENERATION_METADATA_KEY] = revision[0]
@@ -831,30 +756,27 @@ class WebuiTurnCoordinator:
)
def _schedule_title_update_from_event(self, event: TurnCompleted) -> None:
title_context = _validated_llm_runtime(event.runtime)
ctx = event.context
title_llm = event.runtime
if (
event.context.metadata.get("webui") is not True
or title_context is None
ctx.metadata.get(WEBUI_SESSION_METADATA_KEY) is not True
or ctx.session_key != webui_session_key(ctx.chat_id)
or not isinstance(title_llm, LLMRuntime)
):
return
async def _generate_title_and_notify(
title_llm: LLMRuntime = title_context,
) -> None:
generated = await maybe_generate_webui_title_after_turn(
channel=event.context.channel,
chat_id=event.context.chat_id,
metadata=event.context.metadata,
async def _generate_title_and_notify() -> None:
generated = await maybe_generate_webui_title(
sessions=self.sessions,
session_key=event.context.session_key,
session_key=ctx.session_key,
provider=title_llm.provider,
model=title_llm.model,
)
if generated:
await self._publish_session_metadata_updated(
channel=event.context.channel,
chat_id=event.context.chat_id,
metadata=event.context.metadata,
channel=ctx.channel,
chat_id=ctx.chat_id,
metadata=ctx.metadata,
)
self.schedule_background(_generate_title_and_notify())
-3
View File
@@ -51,7 +51,6 @@ class GatewayServices:
local_trigger_store: LocalTriggerStore | None
cron_pending_job_ids: Callable[[str], set[str]] | None
local_trigger_pending_ids: Callable[[str], set[str]] | None
unified_session: bool = False
def build_gateway_services(
@@ -62,7 +61,6 @@ def build_gateway_services(
static_dist_path: Path | None,
workspace_path: Path,
default_restrict_to_workspace: bool,
unified_session: bool = False,
config_path: Path | None = None,
runtime_model_name: Callable[[], str | None] | None,
refresh_runtime_config: Callable[[], None] | None = None,
@@ -171,5 +169,4 @@ def build_gateway_services(
local_trigger_store=local_trigger_store,
cron_pending_job_ids=cron_pending_job_ids,
local_trigger_pending_ids=local_trigger_pending_ids,
unified_session=unified_session,
)
+5 -50
View File
@@ -29,7 +29,6 @@ from nanobot.security.workspace_access import (
WorkspaceScopeError,
)
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
from nanobot.session.keys import session_key_for_channel
from nanobot.session.webui_turns import (
clear_websocket_turn_if_current,
clear_websocket_turns,
@@ -125,7 +124,6 @@ class WebUICommandTransport(Protocol):
media: list[str] | None,
metadata: dict[str, Any],
is_dm: bool,
session_key: str | None,
require_existing_session: bool,
session_generation: str | None,
) -> None: ...
@@ -313,7 +311,6 @@ class WebUICommandRouter:
WORKSPACE_SCOPE_METADATA_KEY: scope.metadata(),
},
is_dm=False,
session_key=None,
require_existing_session=False,
session_generation=None,
)
@@ -651,7 +648,7 @@ class WebUICommandRouter:
)
return
self._transport.webui_attach(connection, chat_id)
if temporary_policy is None or temporary_policy.hydrate_transcript:
if temporary_policy is None:
await self._outbound.hydrate(chat_id)
scope = temporary_policy.workspace_scope if temporary_policy is not None else (
@@ -766,22 +763,8 @@ class WebUICommandRouter:
metadata[WEBSOCKET_TURN_OWNER_METADATA_KEY] = queued_owner
accepted = False
admission_session_key = (
temporary_policy.session_key
if temporary_policy is not None
else webui_session_key(chat_id)
)
execution_session_key = (
temporary_policy.session_key
if temporary_policy is not None
else session_key_for_channel(
"websocket", chat_id, unified_session=self.gateway.unified_session,
)
)
session_generation: str | None = None
session_created = False
execution_generation: str | None = None
execution_created = False
try:
if not restart_control:
admission = await self.workspace_scope_or_error(
@@ -789,7 +772,6 @@ class WebUICommandRouter:
lambda: self._workspaces.persist_scope(
chat_id,
scope,
session_key=admission_session_key,
expected_generation=(
temporary_policy.session_generation
if temporary_policy is not None
@@ -802,21 +784,9 @@ class WebUICommandRouter:
if admission is None:
return
session_generation, session_created = admission
execution_generation = session_generation
if (
execution_session_key != admission_session_key
and self.gateway.session_manager is not None
):
execution_generation, execution_created = (
await self.gateway.session_manager.state.open_with_metadata(
execution_session_key, {},
)
)
if session_generation is not None:
metadata[HISTORY_GENERATION_METADATA_KEY] = session_generation
if is_webui and not restart_control and (
temporary_policy is None or temporary_policy.persist_transcript
):
if is_webui and not restart_control and temporary_policy is None:
await self._transcripts.append_user_message(
chat_id,
content,
@@ -850,18 +820,8 @@ class WebUICommandRouter:
media=media_paths or None,
metadata=metadata,
is_dm=False,
session_key=(
execution_session_key
if temporary_policy is not None
or execution_session_key != admission_session_key
else None
),
require_existing_session=(
temporary_policy.require_existing_session
if temporary_policy is not None
else False
),
session_generation=execution_generation,
require_existing_session=temporary_policy is not None,
session_generation=session_generation,
)
accepted = True
if turn_id:
@@ -870,12 +830,7 @@ class WebUICommandRouter:
del self._accepted_messages[next(iter(self._accepted_messages))]
except BaseException:
await self._workspaces.rollback_scope_admission(
execution_session_key,
execution_generation,
created=execution_created,
)
await self._workspaces.rollback_scope_admission(
admission_session_key,
chat_id,
session_generation,
created=session_created,
)
+13 -38
View File
@@ -18,7 +18,6 @@ from nanobot.bus.outbound_events import (
from nanobot.bus.queue import MessageBus
from nanobot.session import turn_continuation
from nanobot.session.display_history import HistoryFact, HistoryKind, HistoryReader
from nanobot.session.keys import UNIFIED_SESSION_KEY, last_channel_from_metadata
from nanobot.session.manager import Session, SessionManager
from nanobot.session.recovery import (
KNOWN_CHECKPOINT_PHASES,
@@ -56,7 +55,6 @@ class RecoveryCoordinator:
sessions: SessionManager
bus: MessageBus
unified_session: bool = False
_active_recovery_tasks: dict[str, asyncio.Task[Any]] = dataclasses.field(
default_factory=dict,
init=False,
@@ -87,19 +85,20 @@ class RecoveryCoordinator:
from nanobot.webui.history import initialize_history
await initialize_history(self.sessions)
for key in await self._recovery_candidates():
for item in await self.sessions.state.list_sessions():
key = item["key"]
chat_id = webui_chat_id(key)
if chat_id is None:
continue
metadata_payload = await self.sessions.state.read_metadata(key)
raw_metadata = metadata_payload.get("metadata") if metadata_payload else None
metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}
route = self._websocket_route_for(key, metadata)
if route is None:
continue
unfinished = await self._has_unfinished_webui_transcript(key)
if not self._needs_recovery(metadata) and not unfinished:
continue
session = await self.sessions.state.get(key)
try:
await self._recover_session(session, route[1])
await self._recover_session(session, chat_id)
await self._close_interrupted_turns(session)
await self._requeue_pending_followups(session)
except Exception:
@@ -114,10 +113,7 @@ class RecoveryCoordinator:
can_continue=False,
)
await self.sessions.state.restore_interruption(session)
await self._publish(route[1], failed)
async def _recovery_candidates(self) -> list[str]:
return [item["key"] for item in await self.sessions.state.list_sessions()]
await self._publish(chat_id, failed)
@staticmethod
def _needs_recovery(metadata: Mapping[str, Any]) -> bool:
@@ -179,11 +175,11 @@ class RecoveryCoordinator:
failure_error_kind: str | None = None,
) -> None:
"""Offer explicit continuation of committed model failures or resolve recovery."""
chat_id = webui_chat_id(session_key)
if chat_id is None:
return
session = await self.sessions.state.get(session_key)
state = recovery_state_from_metadata(session.metadata)
route = self._websocket_route(session)
if route is None:
return
if failure_kind == "model":
# The turn has already saved its transcript and tool results. Use
# that context, never resend the user's message or replay tools.
@@ -199,7 +195,7 @@ class RecoveryCoordinator:
if session.messages and session.messages[-1].get("_interrupted") is True:
waiting["reply_preserved"] = True
await self.sessions.state.restore_interruption(session)
await self._publish(route[1], waiting)
await self._publish(chat_id, waiting)
return
if not state or state["status"] != "resuming":
return
@@ -211,7 +207,7 @@ class RecoveryCoordinator:
reason="continued",
)
await self.sessions.state.restore_interruption(session)
await self._publish(route[1], recovered)
await self._publish(chat_id, recovered)
async def handle_action(self, action: str, payload: dict[str, Any]) -> dict[str, Any]:
"""Apply an authenticated continue/dismiss operation."""
@@ -221,7 +217,7 @@ class RecoveryCoordinator:
raise RecoveryActionError("missing chat_id")
if not isinstance(recovery_id, str) or not recovery_id:
raise RecoveryActionError("missing recovery_id")
session = await self.sessions.state.get(self._session_key(chat_id))
session = await self.sessions.state.get(webui_session_key(chat_id))
state = recovery_state_from_metadata(session.metadata)
if not state or state["recovery_id"] != recovery_id:
raise RecoveryActionError("recovery state is stale", status=409)
@@ -521,9 +517,6 @@ class RecoveryCoordinator:
session.updated_at = datetime.now()
return state
def _session_key(self, chat_id: str) -> str:
return UNIFIED_SESSION_KEY if self.unified_session else webui_session_key(chat_id)
async def _has_unfinished_webui_transcript(self, session_key: str) -> bool:
from nanobot.webui.transcript import has_unfinished_transcript_tail
@@ -553,21 +546,3 @@ class RecoveryCoordinator:
for message in tail
)
)
@staticmethod
def _websocket_route(session: Session) -> tuple[str, str] | None:
return RecoveryCoordinator._websocket_route_for(session.key, session.metadata)
@staticmethod
def _websocket_route_for(
session_key: str,
metadata: Mapping[str, Any],
) -> tuple[str, str] | None:
chat_id = webui_chat_id(session_key)
if chat_id is not None:
return ("websocket", chat_id)
if session_key == UNIFIED_SESSION_KEY:
route = last_channel_from_metadata(metadata)
if route and route[0] == "websocket":
return route
return None
-1
View File
@@ -18,7 +18,6 @@ from nanobot.webui.settings_contracts import WebUISettingsError
RUNTIME_CONFIG_PATHS = (
"agents.defaults.timezone",
"agents.defaults.timezone_mode",
"agents.defaults.unified_session",
"agents.defaults.session_ttl_minutes",
"agents.defaults.max_tool_iterations",
"agents.defaults.max_concurrent_subagents",
-1
View File
@@ -158,7 +158,6 @@ def system_settings_payload(
"dream": {
"schedule": defaults.dream.describe_schedule(),
},
"unified_session": defaults.unified_session,
},
"advanced": {
"restrict_to_workspace": config.tools.restrict_to_workspace,
+7 -17
View File
@@ -15,6 +15,7 @@ from nanobot.command.application import register_builtin_commands
from nanobot.command.router import CommandRouter
from nanobot.security.workspace_access import WorkspaceScope
from nanobot.session.manager import SessionManager
from nanobot.webui.session_identity import webui_session_key
from nanobot.webui.workspaces import WebUIWorkspaceController
_TEMPORARY_CHAT_DISABLED_TOOLS = frozenset({
@@ -38,12 +39,8 @@ class TemporaryChatError(ValueError):
class TemporaryChatMessagePolicy:
"""Server-owned message rules for one active Temporary Chat."""
session_key: str
session_generation: str
workspace_scope: WorkspaceScope
require_existing_session: bool = True
hydrate_transcript: bool = False
persist_transcript: bool = False
class WebUITemporaryChats:
@@ -56,13 +53,11 @@ class WebUITemporaryChats:
session_manager: SessionManager | None,
workspaces: WebUIWorkspaceController,
logger: Any,
channel_name: str = "websocket",
) -> None:
self._bus = bus
self._sessions = session_manager
self._workspaces = workspaces
self._logger = logger
self._channel_name = channel_name
self._commands = CommandRouter()
register_builtin_commands(self._commands)
self._owners: dict[str, object] = {}
@@ -72,13 +67,10 @@ class WebUITemporaryChats:
self._known_transient_chat_ids: set[str] = set()
self._media_paths: dict[str, set[str]] = {}
def _session_key(self, chat_id: str) -> str:
return f"{self._channel_name}:{chat_id}"
def _cached_session_is_transient(self, chat_id: str) -> bool:
if self._sessions is None:
return False
identity = self._sessions.state.peek_identity(self._session_key(chat_id))
identity = self._sessions.state.peek_identity(webui_session_key(chat_id))
return identity is not None and not identity.policy.persist
async def create(self, owner: object, *, trusted_webui: bool) -> str:
@@ -90,7 +82,7 @@ class WebUITemporaryChats:
chat_id = str(uuid.uuid4())
session = await self._sessions.state.register_transient(
self._session_key(chat_id),
webui_session_key(chat_id),
disabled_tools=_TEMPORARY_CHAT_DISABLED_TOOLS,
)
if session.policy.persist:
@@ -114,7 +106,7 @@ class WebUITemporaryChats:
if self._owners.get(chat_id) is not owner or self._sessions is None:
raise TemporaryChatError("temporary_chat_unavailable")
identity = self._sessions.state.peek_identity(self._session_key(chat_id))
identity = self._sessions.state.peek_identity(webui_session_key(chat_id))
if identity is None:
raise TemporaryChatError("temporary_chat_unavailable")
@@ -123,7 +115,6 @@ class WebUITemporaryChats:
raise TemporaryChatError("temporary_chat_command_rejected")
return TemporaryChatMessagePolicy(
session_key=self._session_key(chat_id),
session_generation=identity.generation,
workspace_scope=self._workspaces.restricted_default_scope(),
)
@@ -187,21 +178,20 @@ class WebUITemporaryChats:
):
raise TemporaryChatError("temporary_chat_unavailable")
session_key = self._session_key(chat_id)
session_key = webui_session_key(chat_id)
self._forget_owner(owner, chat_id)
self._discard_media(chat_id)
if self._sessions is not None:
await self._sessions.state.discard(session_key)
await self._bus.publish_inbound(
InboundMessage(
channel=self._channel_name,
channel="websocket",
sender_id="webui",
chat_id=chat_id,
content="",
metadata={
INBOUND_META_RUNTIME_CONTROL: RUNTIME_CONTROL_SESSION_DISCARD,
},
session_key_override=session_key,
)
)
@@ -210,7 +200,7 @@ class WebUITemporaryChats:
for chat_id in tuple(self._owners):
self._discard_media(chat_id)
if self._sessions is not None:
self._sessions.state.forget_transient(self._session_key(chat_id))
self._sessions.state.forget_transient(webui_session_key(chat_id))
self._owners.clear()
self._owner_chat_ids.clear()
self._known_transient_chat_ids.clear()
+3 -4
View File
@@ -491,12 +491,11 @@ class WebUIWorkspaceController:
chat_id: str,
scope: WorkspaceScope,
*,
session_key: str | None = None,
expected_generation: str | None = None,
) -> tuple[str | None, bool]:
async with self._scope_lock(chat_id):
return await self._persist_scope(
session_key or webui_session_key(chat_id), scope, expected_generation,
webui_session_key(chat_id), scope, expected_generation,
)
async def _persist_scope(
@@ -517,7 +516,7 @@ class WebUIWorkspaceController:
async def rollback_scope_admission(
self,
session_key: str,
chat_id: str,
generation: str | None,
*,
created: bool,
@@ -526,7 +525,7 @@ class WebUIWorkspaceController:
if not created or generation is None or self._sessions is None:
return
await self._sessions.state.delete(
session_key,
webui_session_key(chat_id),
expected_generation=generation,
)
-2
View File
@@ -43,7 +43,6 @@ def make_loop(
model: str = "test-model",
context_window_tokens: int = 128_000,
session_ttl_minutes: int = 0,
unified_session: bool = False,
tools_config=None,
model_presets: dict | None = None,
hooks: list | None = None,
@@ -67,7 +66,6 @@ def make_loop(
model=model,
context_window_tokens=context_window_tokens,
session_ttl_minutes=session_ttl_minutes,
unified_session=unified_session,
)
if tools_config is not None:
kwargs["tools_config"] = tools_config
+2 -2
View File
@@ -33,8 +33,8 @@ async def save_completed_subagent(loop: AgentLoop, task_id: str, owner: str) ->
async def run_session(loop: AgentLoop, msg: InboundMessage) -> None:
"""Submit input and wait for its session worker to finish."""
(await loop._enqueue_session_message(msg))
await asyncio.gather(*loop._active_tasks[loop._effective_session_key(msg)])
await loop._enqueue_session_message(msg)
await asyncio.gather(*loop._active_tasks[msg.session_key])
async def stop_loop(loop: AgentLoop, worker: asyncio.Task[None], *, timeout: float) -> None:
+1 -30
View File
@@ -19,13 +19,12 @@ from nanobot.events import NO_EVENTS, ContextCompactionEvent
from nanobot.providers.base import LLMResponse
from nanobot.runtime_context import public_history_message
from nanobot.sdk.clients import RuntimeClient
from nanobot.session.keys import HEARTBEAT_SESSION_KEY, UNIFIED_SESSION_KEY
from nanobot.session.keys import HEARTBEAT_SESSION_KEY
def _make_loop(
tmp_path: Path,
session_ttl_minutes: int = 15,
unified_session: bool = False,
) -> AgentLoop:
"""Create a minimal AgentLoop for testing."""
bus = MessageBus()
@@ -41,7 +40,6 @@ def _make_loop(
model="test-model",
context_window_tokens=128_000,
session_ttl_minutes=session_ttl_minutes,
unified_session=unified_session,
)
loop.tools.get_definitions = MagicMock(return_value=[])
return loop
@@ -230,33 +228,6 @@ async def test_idle_compaction_skips_subagent_sessions(tmp_path, monkeypatch, re
await loop.aclose()
async def test_expired_unified_turn_keeps_latest_delivery_route(tmp_path, monkeypatch):
monkeypatch.setattr("nanobot.config.home._home_path", tmp_path / "home")
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json")
loop = _make_loop(tmp_path / "workspace", unified_session=True)
session = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
session.metadata["last_channel"] = "telegram:old"
session.metadata["_compaction_route"] = {
"channel": "telegram", "chat_id": "old", "metadata": {},
}
session.updated_at = datetime.now() - timedelta(minutes=20)
loop.sessions.save(session)
try:
response = await loop.process_direct(
"hello", session_key=UNIFIED_SESSION_KEY, channel="discord", chat_id="new",
)
assert response is not None and response.content == "ok"
saved = await loop.sessions.state.get(UNIFIED_SESSION_KEY)
assert saved.generation == session.generation
assert saved.metadata["last_channel"] == "discord:new"
assert saved.metadata["_compaction_route"] == {
"channel": "discord", "chat_id": "new", "metadata": {},
}
finally:
await loop.aclose()
@pytest.mark.parametrize("compaction", ["idle", "compact_session", "compact_idle_session"])
async def test_turn_resuming_during_archive_commits_reply(tmp_path, monkeypatch, compaction):
monkeypatch.setattr("nanobot.config.home._home_path", tmp_path / "home")
+2 -2
View File
@@ -492,14 +492,14 @@ class TestPrepareSession:
ac = _make_autocompact(ttl=15)
session = _make_session(
updated_at=datetime.now() - timedelta(minutes=20),
metadata={"last_channel": "discord:new"},
metadata={"title": "Project notes"},
)
if archiving:
ac._archiving.add(session.key)
prepared, _ = await ac.prepare_session(session, session.key)
assert prepared.metadata["last_channel"] == "discord:new"
assert prepared.metadata["title"] == "Project notes"
async def test_hot_path_summary_from_summaries(self):
ac = _make_autocompact()
+3 -5
View File
@@ -21,7 +21,6 @@ from nanobot.runtime_context import (
RuntimeContextBlock,
append_runtime_context,
)
from nanobot.session.keys import UNIFIED_SESSION_KEY, remember_last_channel
from nanobot.session.manager import Session
from nanobot.utils.llm_runtime import LLMRuntime
from nanobot.utils.prompt_templates import render_template
@@ -1481,7 +1480,7 @@ class TestCompactIdleSession:
assert sent[-1]["content"] == _ARCHIVE_PROMPT
@pytest.mark.asyncio
async def test_reuses_real_prefix_for_unified_session_workspace(
async def test_reuses_real_prefix_for_webui_session_workspace(
self,
loop_factory,
mock_provider,
@@ -1491,14 +1490,13 @@ class TestCompactIdleSession:
project.mkdir()
(tmp_path / "AGENTS.md").write_text("GLOBAL_WORKSPACE_MARKER", encoding="utf-8")
(project / "AGENTS.md").write_text("PROJECT_WORKSPACE_MARKER", encoding="utf-8")
loop = loop_factory(provider=mock_provider, unified_session=True)
loop = loop_factory(provider=mock_provider)
runtime = loop.llm_runtime()
runtime.provider.chat_stream_with_retry.return_value = LLMResponse(
content="Summary.",
finish_reason="stop",
)
session = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
remember_last_channel(session.metadata, "websocket", "scope")
session = loop.sessions.get_or_create("websocket:scope")
session.metadata["workspace_scope"] = {
"project_path": str(project),
"access_mode": "restricted",
+3 -44
View File
@@ -1115,13 +1115,13 @@ class TestToolEventProgress:
captured: dict[str, object] = {}
async def fake_title_after_turn(**kwargs: object) -> bool:
async def fake_generate_title(**kwargs: object) -> bool:
captured.update(kwargs)
return False
monkeypatch.setattr(
"nanobot.session.webui_turns.maybe_generate_webui_title_after_turn",
fake_title_after_turn,
"nanobot.session.webui_turns.maybe_generate_webui_title",
fake_generate_title,
)
scheduled_title: list[object] = []
@@ -1157,39 +1157,6 @@ class TestToolEventProgress:
assert captured["provider"] is provider
assert captured["model"] == "test-model"
@pytest.mark.asyncio
@pytest.mark.parametrize("metadata", [{}, {"webui": False}])
async def test_webui_title_requires_inbound_opt_in(
self,
tmp_path: Path,
metadata: dict[str, object],
) -> None:
from nanobot.session.manager import SessionManager
from nanobot.session.webui_turns import maybe_generate_webui_title_after_turn
sessions = SessionManager(tmp_path)
session = sessions.get_or_create("websocket:chat1")
session.metadata["webui"] = True
session.add_message("user", "say hello")
session.add_message("assistant", "Hello")
sessions.save(session)
provider = MagicMock()
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Greeting"))
generated = await maybe_generate_webui_title_after_turn(
channel="websocket",
chat_id="chat1",
metadata=metadata,
sessions=sessions,
session_key=session.key,
provider=provider,
model="test-model",
)
assert generated is False
provider.chat_stream_with_retry.assert_not_awaited()
assert "title" not in session.metadata
@pytest.mark.asyncio
@pytest.mark.parametrize("metadata", [{}, {"webui": False}])
async def test_webui_turn_without_opt_in_does_not_schedule_title(
@@ -1232,7 +1199,6 @@ class TestToolEventProgress:
async def test_webui_command_turn_does_not_schedule_title_generation(
self,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
bus = MessageBus()
provider = MagicMock()
@@ -1241,13 +1207,6 @@ class TestToolEventProgress:
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path, model="test-model")
_attach_webui_runtime_events(loop, bus)
async def fake_title_after_turn(**_kwargs: object) -> bool:
raise AssertionError("command-only turns should not generate titles")
monkeypatch.setattr(
"nanobot.session.webui_turns.maybe_generate_webui_title_after_turn",
fake_title_after_turn,
)
scheduled: list[object] = []
loop.schedule_background = scheduled.append # type: ignore[method-assign]
-1
View File
@@ -127,7 +127,6 @@ async def test_recovery_continuation_runs_without_a_sustained_goal(
loop = AgentLoop.__new__(AgentLoop)
loop.sessions = sessions
loop._unified_session = False
loop._recovery_admission = recovery
loop._session_locks = {}
loop._concurrency_gate = None
+3 -134
View File
@@ -44,10 +44,6 @@ from nanobot.runtime_context import (
)
from nanobot.session.automation_turns import AUTOMATION_HISTORY_META
from nanobot.session.goal_state import GOAL_STATE_KEY
from nanobot.session.keys import (
LAST_CHANNEL_METADATA_KEY,
UNIFIED_SESSION_KEY,
)
from nanobot.session.manager import Session
from nanobot.session.recovery import (
PENDING_FOLLOWUP_ID_KEY,
@@ -71,7 +67,6 @@ from nanobot.session.webui_turns import (
WebuiTurnCoordinator,
clean_generated_title,
maybe_generate_webui_title,
maybe_generate_webui_title_after_turn,
)
from nanobot.triggers.local_session_turns import LOCAL_TRIGGER_META
@@ -466,69 +461,6 @@ async def test_generate_webui_title_ignores_cron_internal_turns(tmp_path: Path)
loop.provider.chat_stream_with_retry.assert_not_awaited()
@pytest.mark.asyncio
async def test_generate_webui_title_projects_onto_chat_session_under_unified_routing(
tmp_path: Path,
) -> None:
loop = _make_full_loop(tmp_path)
loop.provider.chat_stream_with_retry = AsyncMock(
return_value=LLMResponse(content='"查询临期 IP"', finish_reason="stop")
)
unified = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
unified.metadata[WEBUI_SESSION_METADATA_KEY] = True
unified.metadata[WEBUI_TITLE_METADATA_KEY] = "开启私聊Topic功能"
unified.add_message("user", "很早以前的问题")
unified.add_message("assistant", "很久以前的回答。")
unified.add_message("user", "帮我查一下临期IP有哪些")
unified.add_message("assistant", "以下是临期 IP 列表。")
loop.sessions.save(unified)
generated = await maybe_generate_webui_title_after_turn(
channel="websocket",
chat_id="chat-projection",
metadata={WEBUI_SESSION_METADATA_KEY: True},
sessions=loop.sessions,
session_key=UNIFIED_SESSION_KEY,
provider=loop.provider,
model=loop.model,
)
assert generated is True
chat = loop.sessions.get_or_create("websocket:chat-projection")
assert chat.metadata[WEBUI_TITLE_METADATA_KEY] == "查询临期 IP"
assert unified.metadata[WEBUI_TITLE_METADATA_KEY] == "开启私聊Topic功能"
prompt = loop.provider.chat_stream_with_retry.await_args.args[0][1]["content"]
assert "帮我查一下临期IP有哪些" in prompt
assert "很早以前的问题" not in prompt
@pytest.mark.asyncio
async def test_projected_title_generation_skips_existing_chat_title(tmp_path: Path) -> None:
loop = _make_full_loop(tmp_path)
unified = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
unified.metadata[WEBUI_SESSION_METADATA_KEY] = True
unified.add_message("user", "帮我查一下临期IP有哪些")
unified.add_message("assistant", "以下是临期 IP 列表。")
chat = loop.sessions.get_or_create("websocket:chat-existing")
chat.metadata[WEBUI_TITLE_METADATA_KEY] = "Existing title"
loop.sessions.save(chat)
loop.sessions.save(unified)
generated = await maybe_generate_webui_title_after_turn(
channel="websocket",
chat_id="chat-existing",
metadata={WEBUI_SESSION_METADATA_KEY: True},
sessions=loop.sessions,
session_key=UNIFIED_SESSION_KEY,
provider=loop.provider,
model=loop.model,
)
assert generated is False
assert chat.metadata[WEBUI_TITLE_METADATA_KEY] == "Existing title"
loop.provider.chat_stream_with_retry.assert_not_awaited()
def test_save_turn_keeps_multimodal_runtime_context_for_model_replay() -> None:
loop = _mk_loop()
session = Session(key="test:runtime-only")
@@ -1203,9 +1135,8 @@ async def test_subagent_followup_clears_state_before_compatibility_failure(
@pytest.mark.asyncio
async def test_process_message_persists_unified_session_delivery_route(tmp_path: Path) -> None:
async def test_process_message_persists_delivery_route_on_failure(tmp_path: Path) -> None:
loop = _make_full_loop(tmp_path)
loop._unified_session = True
loop._run_agent_loop = AsyncMock(side_effect=RuntimeError("boom")) # type: ignore[method-assign]
msg = InboundMessage(
@@ -1213,79 +1144,17 @@ async def test_process_message_persists_unified_session_delivery_route(tmp_path:
sender_id="u1",
chat_id="oc_123",
content="persist my route",
session_key_override=UNIFIED_SESSION_KEY,
)
with pytest.raises(RuntimeError, match="boom"):
await loop._process_message(msg)
loop.sessions.invalidate(UNIFIED_SESSION_KEY)
persisted = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
assert persisted.metadata[LAST_CHANNEL_METADATA_KEY] == "feishu:oc_123"
loop.sessions.invalidate("feishu:oc_123")
persisted = loop.sessions.get_or_create("feishu:oc_123")
assert persisted.metadata["_compaction_route"] == {
"channel": "feishu", "chat_id": "oc_123", "metadata": {},
}
@pytest.mark.parametrize(
("msg", "is_user_turn"),
[
(
InboundMessage(
channel="cli",
sender_id="u1",
chat_id="direct",
content="cli input",
),
True,
),
(
InboundMessage(
channel="system",
sender_id="system",
chat_id="discord:automation",
content="system event",
),
False,
),
(
InboundMessage(
channel="discord",
sender_id="subagent",
chat_id="subagent-result",
content="subagent result",
),
True,
),
(
InboundMessage(
channel="discord",
sender_id="u1",
chat_id="automation",
content="scheduled turn",
metadata={CRON_TRIGGER_META: {"job_id": "job-1"}},
),
True,
),
],
)
def test_unified_session_route_ignores_non_user_destinations(
tmp_path: Path,
msg: InboundMessage,
is_user_turn: bool,
) -> None:
loop = _make_full_loop(tmp_path)
loop._unified_session = True
session = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
session.metadata[LAST_CHANNEL_METADATA_KEY] = "telegram:existing"
loop._remember_session_route(
session, msg, is_user_turn=is_user_turn,
delivery=loop.turn_delivery_factory.unrouted(msg, session.key),
)
assert session.metadata[LAST_CHANNEL_METADATA_KEY] == "telegram:existing"
# 1x1 PNG used by the media-persistence tests. Attachment preparation filters
# ``msg.media`` down to paths that magic-byte-sniff as images, so the test
# fixture needs real bytes on disk (not just placeholder paths).
+1 -22
View File
@@ -18,8 +18,7 @@ from nanobot.bus.events import (
)
from nanobot.bus.queue import MessageBus
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
from nanobot.runtime_context import RuntimeContextBlock, public_history_message
from nanobot.session.keys import UNIFIED_SESSION_KEY
from nanobot.runtime_context import RuntimeContextBlock
from nanobot.session.manager import SessionPolicy
from nanobot.webui.temporary_chats import WebUITemporaryChats
from nanobot.webui.workspaces import WebUIWorkspaceController
@@ -269,26 +268,6 @@ async def test_session_worker_errors_keep_private_content_out_of_logs(
assert secret not in str([r["message"] for r in records])
@pytest.mark.asyncio
async def test_transient_session_stays_outside_unified_session(tmp_path) -> None:
loop = _loop(tmp_path, ["private answer"], unified_session=True)
durable = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
durable.add_message("user", "durable question")
loop.sessions.save(durable)
key = "websocket:transient-unified"
await loop.sessions.state.register_transient(key)
await run_session(loop, _message(key, "private question"))
transient = await loop.sessions.state.get(key)
assert [public_history_message(message)["content"] for message in transient.messages] == [
"private question",
"private answer",
]
assert [message["content"] for message in durable.messages] == ["durable question"]
assert loop.sessions.read_session_file(key) is None
@pytest.mark.asyncio
async def test_missing_required_session_cannot_fall_back_to_disk(tmp_path) -> None:
loop = _loop(tmp_path, [])
+4 -4
View File
@@ -111,7 +111,7 @@ async def test_scheduled_goal_command_cannot_generate_internal_input(tmp_path):
)
loop = _assembled_loop(bus=MessageBus(), provider=MagicMock(aclose=AsyncMock()), workspace=tmp_path, model="test-model")
try:
await loop._dispatch_command_inline(msg, msg.session_key, msg.content, loop.commands.dispatch)
await loop._dispatch_command_inline(msg, msg.content, loop.commands.dispatch)
response = loop.bus.outbound.get_nowait()
assert "only be started by a user" in response.content
assert loop._pending_queues == {}
@@ -142,7 +142,7 @@ async def test_goal_at_iteration_limit_stays_queued_for_a_tool_capable_turn(tmp_
calls.append(str(kwargs["messages"]))
if len(calls) == 1:
await loop._dispatch_command_inline(
goal, goal.session_key, goal.content, loop.commands.dispatch,
goal, goal.content, loop.commands.dispatch,
)
if boundary == "tool":
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
@@ -454,7 +454,7 @@ async def test_replaced_goal_uses_current_objective_for_same_run_prompt(tmp_path
calls.append(kwargs)
if len(calls) == 1:
await loop._dispatch_command_inline(
replacement, replacement.session_key, replacement.content, loop.commands.dispatch,
replacement, replacement.content, loop.commands.dispatch,
)
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="list", name="list_dir", arguments={"path": "."},
@@ -554,7 +554,7 @@ async def test_queued_goal_command_does_not_write_to_an_obsolete_generation(tmp_
else:
assert await loop.sessions.state.delete(key)
with pytest.raises(SessionConflictError):
await loop._dispatch_command_inline(message, key, message.content, loop.commands.dispatch)
await loop._dispatch_command_inline(message, message.content, loop.commands.dispatch)
current = await loop.sessions.state.read(key)
if operation == "delete":
assert current is None
+2 -42
View File
@@ -1081,13 +1081,11 @@ async def test_no_injections_flag_is_false_by_default():
@pytest.mark.asyncio
async def test_followup_routed_to_pending_queue(tmp_path):
from nanobot.bus.events import InboundMessage
from nanobot.session.keys import UNIFIED_SESSION_KEY
loop = _make_loop(tmp_path)
loop._unified_session = True
pending = asyncio.Queue(maxsize=20)
loop._pending_queues[UNIFIED_SESSION_KEY] = pending
loop._pending_queues["discord:c"] = pending
run_task = asyncio.create_task(loop.run())
msg = InboundMessage(channel="discord", sender_id="u", chat_id="c", content="follow-up")
@@ -1100,7 +1098,7 @@ async def test_followup_routed_to_pending_queue(tmp_path):
assert loop._active_tasks == {}
assert queued_msg.content == "follow-up"
assert queued_msg.session_key == UNIFIED_SESSION_KEY
assert queued_msg.session_key == "discord:c"
@pytest.mark.asyncio
@@ -1133,44 +1131,6 @@ async def test_websocket_followup_is_admitted_before_recovery_queue(tmp_path):
await asyncio.wait_for(run_task, timeout=2)
@pytest.mark.asyncio
@pytest.mark.parametrize("channel", ["websocket", "discord"])
async def test_unified_followup_admits_effective_session(tmp_path, channel):
from nanobot.bus.events import InboundMessage
from nanobot.session.keys import UNIFIED_SESSION_KEY
admission = MagicMock()
admission.admit = AsyncMock(return_value=True)
loop = _make_loop(tmp_path, recovery_admission=admission)
loop._unified_session = True
pending = asyncio.Queue(maxsize=20)
loop._pending_queues[UNIFIED_SESSION_KEY] = pending
msg = InboundMessage(
channel=channel,
sender_id="u",
chat_id="chat",
content="new request",
)
try:
# Exercise the real routing/journaling boundary to completion. This is
# a session-key contract, not a two-second SQLite fsync benchmark.
await loop._dispatch_inbound(msg)
queued_msg = pending.get_nowait()
admission.admit.assert_awaited_once()
admitted_msg = admission.admit.await_args.args[0]
assert admitted_msg.session_key == UNIFIED_SESSION_KEY
assert queued_msg.session_key == UNIFIED_SESSION_KEY
assert queued_msg.content == msg.content
if channel == "websocket":
assert queued_msg.metadata["_recovery_followup_id"]
else:
assert queued_msg.metadata == msg.metadata
finally:
await loop.aclose()
@pytest.mark.asyncio
async def test_mid_turn_subagent_result_does_not_resolve_a_new_turn_route(tmp_path):
from nanobot.bus.events import InboundMessage
+17 -19
View File
@@ -163,8 +163,7 @@ async def test_new_during_active_turn_stops_it_and_resets_session(loop):
@pytest.mark.parametrize("followup_scope", ["same", "restricted", "other-project"])
async def test_unified_followup_keeps_its_workspace_authority(loop, tmp_path, followup_scope):
loop._unified_session = True
async def test_followup_keeps_its_workspace_authority(loop, tmp_path, followup_scope):
project = tmp_path / "other-project"
project.mkdir()
initial_scope = {"project_path": str(tmp_path), "access_mode": "full"}
@@ -179,11 +178,11 @@ async def test_unified_followup_keeps_its_workspace_authority(loop, tmp_path, fo
observed.append(scope.metadata())
if len(observed) == 1:
await loop.bus.publish_inbound(InboundMessage(
channel="websocket", sender_id="client", chat_id="followup", content="second",
channel="websocket", sender_id="client", chat_id="initial", content="second",
metadata={"workspace_scope": next_scope},
))
async with asyncio.timeout(3):
while loop._pending_queues["unified:default"].empty():
while loop._pending_queues["websocket:initial"].empty():
await asyncio.sleep(0)
return LLMResponse(content="done")
@@ -196,7 +195,7 @@ async def test_unified_followup_keeps_its_workspace_authority(loop, tmp_path, fo
metadata={"workspace_scope": initial_scope},
))
async with asyncio.timeout(5):
while not observed or "unified:default" in loop._pending_queues:
while not observed or "websocket:initial" in loop._pending_queues:
await asyncio.sleep(0.01)
assert observed == [initial_scope, next_scope]
assert loop.runner.run.await_count == (1 if followup_scope == "same" else 2)
@@ -525,7 +524,7 @@ async def test_stopped_followups_are_not_recovered_but_shutdown_preserves_them(
stop = InboundMessage(
channel="websocket", sender_id="u", chat_id="test", content="/stop",
)
await loop._dispatch_command_inline(stop, key, "/stop", loop.commands.dispatch_priority)
await loop._dispatch_command_inline(stop, stop.content, loop.commands.dispatch_priority)
# Use fresh managers and the real startup scan: a cache-only assertion can
# miss the canceled journal being replayed from disk on the next restart.
@@ -684,7 +683,7 @@ async def test_ingress_sources_share_one_session_worker(loop, bus_running):
else:
(await loop._enqueue_session_message(second))
compact = InboundMessage(channel="websocket", sender_id="u", chat_id="test", content="/compact")
await loop._dispatch_command_inline(compact, key, compact.content, loop.commands.dispatch)
await loop._dispatch_command_inline(compact, compact.content, loop.commands.dispatch)
assert len(loop._active_tasks[key]) == 1
release.set()
results = await asyncio.wait_for(asyncio.gather(cron, trigger), timeout=3)
@@ -809,11 +808,10 @@ async def test_active_goal_prioritizes_real_followup_before_internal_prompt(loop
async def test_active_goal_keeps_origin_until_queued_independent_command_runs(loop):
loop._unified_session = True
loop.max_iterations = 1
loop.tools.prepare_call = MagicMock(return_value=(None, {}, None))
loop.tools.execute = AsyncMock(return_value="ok")
key = "unified:default"
key = "feishu:chat-a"
session = loop.sessions.get_or_create(key)
session.metadata[GOAL_STATE_KEY] = {"status": "active", "objective": "Finish the goal"}
loop.sessions.save(session)
@@ -832,7 +830,7 @@ async def test_active_goal_keeps_origin_until_queued_independent_command_runs(lo
usage = LLMUsage(input_tokens=tokens, output_tokens=0, total_tokens=tokens, reported_tokens=tokens)
if len(requests) == 1:
await loop.bus.publish_inbound(InboundMessage(
channel="feishu", sender_id="user", chat_id="chat-b", content="/compact",
channel="feishu", sender_id="user", chat_id="chat-a", content="/compact",
metadata={"message_id": "message-b"},
))
async with asyncio.timeout(3):
@@ -866,16 +864,16 @@ async def test_active_goal_keeps_origin_until_queued_independent_command_runs(lo
loop.runner.run.assert_awaited_once()
loop.consolidator.compact_idle_session.assert_awaited_once()
assert persisted_origin == {"message_id": "message-a", "turn_id": requests[0][2]}
by_chat = {event.context.chat_id: event for event in completed}
assert set(by_chat) == {"chat-a", "chat-b"}
assert by_chat["chat-a"].outcome == "completed"
by_message = {event.context.metadata.get("message_id"): event for event in completed}
assert set(by_message) == {"message-a", "message-b"}
assert by_message["message-a"].outcome == "completed"
assert len(completed) == 2
assert by_chat["chat-a"].usage.total_tokens == 60
assert [usage.total_tokens for usage in by_chat["chat-a"].round_usages] == [10, 20, 30]
assert by_chat["chat-b"].outcome == "completed"
assert by_chat["chat-b"].context.metadata["message_id"] == "message-b"
assert by_chat["chat-b"].usage is None
assert by_chat["chat-b"].round_usages == ()
assert by_message["message-a"].usage.total_tokens == 60
assert [usage.total_tokens for usage in by_message["message-a"].round_usages] == [10, 20, 30]
assert by_message["message-b"].outcome == "completed"
assert by_message["message-b"].context.metadata["message_id"] == "message-b"
assert by_message["message-b"].usage is None
assert by_message["message-b"].round_usages == ()
replies = []
while not loop.bus.outbound.empty():
reply = loop.bus.outbound.get_nowait()
+6 -20
View File
@@ -11,7 +11,6 @@ from nanobot.agent.memory import Consolidator
from nanobot.bus.outbound_events import StreamDeltaEvent, StreamEndEvent
from nanobot.config.schema import AgentDefaults
from nanobot.providers.base import GenerationSettings
from nanobot.session.keys import UNIFIED_SESSION_KEY
from nanobot.utils.llm_runtime import LLMRuntime
_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars
@@ -740,28 +739,15 @@ class TestSubagentAnnounceSessionKey:
return mgr, bus
@pytest.mark.asyncio
async def test_announce_uses_effective_key_in_unified_mode(self):
"""In unified session mode, session_key_override must be 'unified:default'
so the result matches the pending queue key."""
async def test_announce_uses_explicit_topic_session_key(self):
mgr, bus = self._make_mgr()
origin = {"channel": "telegram", "chat_id": "111", "session_key": UNIFIED_SESSION_KEY}
origin = {"channel": "telegram", "chat_id": "111", "session_key": "telegram:111:topic:5"}
await mgr._announce_result("sub-1", "label", "task", "result", origin, "ok")
msg = await bus.consume_inbound()
assert msg.session_key_override == UNIFIED_SESSION_KEY
assert msg.session_key == UNIFIED_SESSION_KEY
@pytest.mark.asyncio
async def test_announce_uses_raw_key_in_normal_mode(self):
mgr, bus = self._make_mgr()
origin = {"channel": "telegram", "chat_id": "222", "session_key": "telegram:222"}
await mgr._announce_result("sub-2", "label", "task", "result", origin, "ok")
msg = await bus.consume_inbound()
assert msg.session_key_override == "telegram:222"
assert msg.session_key == "telegram:222"
assert msg.session_key_override == "telegram:111:topic:5"
assert msg.session_key == "telegram:111:topic:5"
@pytest.mark.asyncio
async def test_announce_falls_back_to_origin_when_no_session_key(self):
@@ -796,9 +782,9 @@ class TestSubagentAnnounceSessionKey:
origin_channel="telegram",
origin_chat_id="444",
runtime=_runtime(),
session_key=UNIFIED_SESSION_KEY,
session_key="telegram:444:topic:5",
)
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
msg = await bus.consume_inbound()
assert msg.session_key_override == UNIFIED_SESSION_KEY
assert msg.session_key_override == "telegram:444:topic:5"
+10 -18
View File
@@ -45,7 +45,6 @@ async def test_internal_compaction_never_reaches_its_result_destination(channel,
)
@pytest.mark.parametrize("unified", [False, True])
@pytest.mark.parametrize(("key", "channel", "chat_id", "metadata"), [
("slack:C123:1700000000.000100", "slack", "C123",
{"slack": {"thread_ts": "1700000000.000100"}}),
@@ -59,14 +58,13 @@ async def test_internal_compaction_never_reaches_its_result_destination(channel,
("dingtalk:group:conversation:user", "dingtalk", "group:conversation", {}),
])
async def test_session_route_delivers_automatic_and_manual_compaction(
key, channel, chat_id, metadata, unified,
key, channel, chat_id, metadata,
) -> None:
factory = TurnDeliveryFactory(MessageBus())
automatic = ContextCompactionEvent(compaction_id="auto-1", phase="started")
notified = ContextCompactionEvent(
compaction_id="notified-1", phase="started", notify=True,
)
key = "unified:default" if unified else key
msg = InboundMessage(
channel=channel, sender_id="user", chat_id=chat_id, content="hello",
metadata={
@@ -90,9 +88,9 @@ async def test_session_route_delivers_automatic_and_manual_compaction(
assert [outbound.event for outbound in outbounds] == [automatic, notified]
async def test_idle_compaction_keeps_its_route_when_a_unified_session_moves() -> None:
async def test_idle_compaction_keeps_its_route_when_the_saved_route_changes() -> None:
factory = TurnDeliveryFactory(MessageBus())
key = "unified:default"
key = "sdk:workflow"
session_metadata = {}
original = InboundMessage(
channel="slack", sender_id="user", chat_id="C123", content="hello",
@@ -476,29 +474,23 @@ async def test_late_subagent_route_requires_webui_owned_session(tmp_path: Path)
@pytest.mark.asyncio
async def test_unified_display_route_admits_alias_generation_and_rejects_stale_lifetime(tmp_path):
async def test_cross_session_display_route_rejects_stale_lifetime(tmp_path):
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
from nanobot.session.sqlite_store import SessionConflictError
sessions = SessionManager(tmp_path)
alias = await sessions.state.get_header("websocket:chat")
source = await sessions.state.get_header("unified:default")
target = await sessions.state.get_header("websocket:chat")
source = await sessions.state.get_header("heartbeat")
policy = WebuiTurnRoutePolicy(sessions)
factory = TurnDeliveryFactory(MessageBus(), route_policy=policy, route_admission=policy.admit)
message = InboundMessage(channel="system", sender_id="cron", chat_id="websocket:chat", content="notice")
delivery = factory.create(message, source.key)
await delivery.bind_session_generation(source.generation)
assert delivery.route.metadata[HISTORY_GENERATION_METADATA_KEY] == alias.generation
assert delivery.route.metadata[HISTORY_GENERATION_METADATA_KEY] == target.generation
assert delivery.delivery_message.session_generation == source.generation
response = delivery.background_response("done", stop_reason="end_turn", streamed=False, latency_ms=1)
assert response.metadata[HISTORY_GENERATION_METADATA_KEY] == alias.generation
await sessions.state.delete(alias.key)
replacement = await sessions.state.get_header(alias.key)
stale = factory.create(InboundMessage(
channel="websocket", sender_id="user", chat_id="chat", content="old queued input",
metadata={HISTORY_GENERATION_METADATA_KEY: alias.generation},
), source.key)
assert response.metadata[HISTORY_GENERATION_METADATA_KEY] == target.generation
await sessions.state.reset(target.key)
with pytest.raises(SessionConflictError):
await stale.bind_session_generation(source.generation)
assert replacement.generation != alias.generation
await policy.admit(delivery.route, source.key, source.generation)
await sessions.state.aclose()
-372
View File
@@ -1,372 +0,0 @@
import asyncio
import json
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from agent.session_helpers import mock_session_manager, run_session
from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.file_state import FileStateStore
from nanobot.agent.tools.filesystem import ReadFileTool
from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.command.application import register_builtin_commands
from nanobot.command.builtin import cmd_new
from nanobot.command.router import CommandContext, CommandRouter
from nanobot.config.schema import AgentDefaults, Config
from nanobot.session.keys import UNIFIED_SESSION_KEY
from nanobot.session.manager import SessionManager
def _make_loop(tmp_path: Path, unified_session: bool = False) -> AgentLoop:
"""Create a minimal AgentLoop for dispatch-level tests."""
bus = MessageBus()
provider = MagicMock()
provider.get_default_model.return_value = "test-model"
with patch("nanobot.agent.loop.SessionManager", side_effect=mock_session_manager), \
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr:
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
loop = AgentLoop(
bus=bus,
provider=provider,
workspace=tmp_path,
unified_session=unified_session,
)
return loop
def _make_msg(channel: str = "telegram", chat_id: str = "111",
session_key_override: str | None = None) -> InboundMessage:
return InboundMessage(
channel=channel,
chat_id=chat_id,
sender_id="user1",
content="hello",
session_key_override=session_key_override,
)
class TestUnifiedSessionDispatch:
@pytest.mark.asyncio
async def test_unified_session_rewrites_key_to_unified_default(self, tmp_path: Path):
loop = _make_loop(tmp_path, unified_session=True)
captured: list[str] = []
async def fake_process(msg, **kwargs):
captured.append(msg.session_key)
return None
loop._process_message = fake_process # type: ignore[method-assign]
msg = _make_msg(channel="telegram", chat_id="111")
await run_session(loop, msg)
assert captured == ["unified:default"]
@pytest.mark.asyncio
async def test_unified_session_different_channels_share_same_key(self, tmp_path: Path):
loop = _make_loop(tmp_path, unified_session=True)
captured: list[str] = []
async def fake_process(msg, **kwargs):
captured.append(msg.session_key)
return None
loop._process_message = fake_process # type: ignore[method-assign]
await run_session(loop, _make_msg(channel="telegram", chat_id="111"))
await run_session(loop, _make_msg(channel="discord", chat_id="222"))
await run_session(loop, _make_msg(channel="cli", chat_id="direct"))
assert captured == ["unified:default", "unified:default", "unified:default"]
@pytest.mark.asyncio
async def test_unified_session_disabled_preserves_original_key(self, tmp_path: Path):
loop = _make_loop(tmp_path, unified_session=False)
captured: list[str] = []
async def fake_process(msg, **kwargs):
captured.append(msg.session_key)
return None
loop._process_message = fake_process # type: ignore[method-assign]
msg = _make_msg(channel="telegram", chat_id="999")
await run_session(loop, msg)
assert captured == ["telegram:999"]
@pytest.mark.asyncio
async def test_unified_session_respects_existing_override(self, tmp_path: Path):
loop = _make_loop(tmp_path, unified_session=True)
captured: list[str] = []
async def fake_process(msg, **kwargs):
captured.append(msg.session_key)
return None
loop._process_message = fake_process # type: ignore[method-assign]
msg = _make_msg(channel="telegram", chat_id="111", session_key_override="telegram:thread:42")
await run_session(loop, msg)
assert captured == ["telegram:thread:42"]
def test_unified_session_default_is_false(self, tmp_path: Path):
loop = _make_loop(tmp_path)
assert loop._unified_session is False
class TestUnifiedSessionConfig:
def test_agent_defaults_unified_session_default_is_false(self):
defaults = AgentDefaults()
assert defaults.unified_session is False
def test_agent_defaults_unified_session_can_be_enabled(self):
defaults = AgentDefaults(unified_session=True)
assert defaults.unified_session is True
def test_config_serialises_unified_session_as_camel_case(self):
config = Config()
data = config.model_dump(mode="json", by_alias=True)
agents_defaults = data["agents"]["defaults"]
assert "unifiedSession" in agents_defaults
assert agents_defaults["unifiedSession"] is False
def test_config_parses_unified_session_from_camel_case(self):
raw = {"agents": {"defaults": {"unifiedSession": True}}}
config = Config.model_validate(raw)
assert config.agents.defaults.unified_session is True
def test_config_parses_unified_session_from_snake_case(self):
raw = {"agents": {"defaults": {"unified_session": True}}}
config = Config.model_validate(raw)
assert config.agents.defaults.unified_session is True
def test_onboard_generated_config_contains_unified_session(self, tmp_path: Path):
from nanobot.config.loader import save_config
config = Config()
config_path = tmp_path / "config.json"
save_config(config, config_path)
with open(config_path, encoding="utf-8") as f:
data = json.load(f)
agents_defaults = data["agents"]["defaults"]
assert "unifiedSession" in agents_defaults, (
"onboard-generated config.json must contain 'unifiedSession' key"
)
assert agents_defaults["unifiedSession"] is False
class TestCmdNewUnifiedSession:
def test_new_is_not_a_priority_command(self):
router = CommandRouter()
register_builtin_commands(router)
assert router.is_priority("/new") is False
def test_new_is_an_exact_command(self):
router = CommandRouter()
register_builtin_commands(router)
assert "/new" in router._exact
@pytest.mark.asyncio
async def test_cmd_new_clears_unified_session(self, tmp_path: Path):
sessions = SessionManager(tmp_path)
shared = sessions.get_or_create("unified:default")
shared.add_message("user", "hello from telegram")
shared.add_message("assistant", "hi there")
sessions.save(shared)
assert len(sessions.get_or_create("unified:default").messages) == 2
expected_snapshot = list(shared.messages)
# schedule_background is a *sync* method that schedules a coroutine via
# asyncio.create_task(). Mirror that exactly so the coroutine is consumed
# and no RuntimeWarning is emitted.
admitted_runtime = MagicMock(name="admitted_runtime")
file_state_store = FileStateStore()
previous_file_state = file_state_store.for_session("unified:default")
tracked_file = tmp_path / "tracked.txt"
tracked_file.write_text("tracked", encoding="utf-8")
await ReadFileTool(workspace=tmp_path, file_states=previous_file_state).execute(
path=str(tracked_file),
)
assert previous_file_state.get(tracked_file) is not None
loop = SimpleNamespace(
sessions=sessions,
consolidator=SimpleNamespace(archive_session=AsyncMock(return_value=True)),
_cancel_active_tasks=AsyncMock(return_value=0),
discard_session_file_state=file_state_store.discard,
llm_runtime=MagicMock(return_value=MagicMock()),
schedule_background=lambda coro: asyncio.ensure_future(coro),
)
msg = InboundMessage(
channel="telegram", sender_id="user1", chat_id="111", content="/new",
session_key_override="unified:default",
)
ctx = CommandContext(
msg=msg,
session=None,
key="unified:default",
raw="/new",
loop=loop,
runtime=admitted_runtime,
)
result = await cmd_new(ctx)
assert "New session started" in result.content
sessions.invalidate("unified:default")
reloaded = sessions.get_or_create("unified:default")
assert reloaded.messages == []
reset_file_state = file_state_store.for_session("unified:default")
assert reset_file_state is not previous_file_state
assert reset_file_state.get(tracked_file) is None
archived = loop.consolidator.archive_session.call_args.args[0]
assert archived.key == "unified:default"
assert archived.messages == expected_snapshot
assert archived.last_archived == 0
loop.consolidator.archive_session.assert_called_once_with(
archived,
archive_end=len(expected_snapshot),
runtime=admitted_runtime,
)
loop.llm_runtime.assert_not_called()
@pytest.mark.asyncio
async def test_cmd_new_in_unified_mode_does_not_affect_other_sessions(self, tmp_path: Path):
sessions = SessionManager(tmp_path)
other = sessions.get_or_create("discord:999")
other.add_message("user", "discord message")
sessions.save(other)
shared = sessions.get_or_create("unified:default")
shared.add_message("user", "shared message")
sessions.save(shared)
loop = SimpleNamespace(
sessions=sessions,
consolidator=SimpleNamespace(archive_session=AsyncMock(return_value=True)),
_cancel_active_tasks=AsyncMock(return_value=0),
discard_session_file_state=MagicMock(),
runtime_for_session=AsyncMock(return_value=MagicMock()),
schedule_background=lambda coro: asyncio.ensure_future(coro),
)
msg = InboundMessage(
channel="telegram", sender_id="user1", chat_id="111", content="/new",
session_key_override="unified:default",
)
ctx = CommandContext(msg=msg, session=None, key="unified:default", raw="/new", loop=loop)
await cmd_new(ctx)
sessions.invalidate("unified:default")
sessions.invalidate("discord:999")
assert sessions.get_or_create("unified:default").messages == []
assert len(sessions.get_or_create("discord:999").messages) == 1
class TestStopCommandWithUnifiedSession:
@pytest.mark.asyncio
async def test_active_tasks_use_effective_key_in_unified_mode(self, tmp_path: Path):
loop = _make_loop(tmp_path, unified_session=True)
msg = _make_msg(channel="telegram", chat_id="123456")
loop._process_message = AsyncMock(return_value=None)
(await loop._enqueue_session_message(msg))
assert set(loop._active_tasks) == {UNIFIED_SESSION_KEY}
await asyncio.gather(*loop._active_tasks[UNIFIED_SESSION_KEY])
@pytest.mark.asyncio
async def test_stop_command_finds_task_in_unified_mode(self, tmp_path: Path):
from nanobot.command.builtin import cmd_stop
loop = _make_loop(tmp_path, unified_session=True)
async def long_running():
await asyncio.sleep(10)
task = asyncio.create_task(long_running())
loop._active_tasks[UNIFIED_SESSION_KEY] = {task}
msg = InboundMessage(
channel="telegram",
chat_id="123456",
sender_id="user1",
content="/stop",
session_key_override=UNIFIED_SESSION_KEY,
)
ctx = CommandContext(msg=msg, session=None, key=UNIFIED_SESSION_KEY, raw="/stop", loop=loop)
result = await cmd_stop(ctx)
assert task.cancelled() or task.done()
assert "Stopped 1 task" in result.content
@pytest.mark.asyncio
async def test_stop_command_uses_effective_key_without_session_override(self, tmp_path: Path):
from nanobot.command.builtin import cmd_stop
loop = _make_loop(tmp_path, unified_session=True)
async def long_running():
await asyncio.sleep(10)
task = asyncio.create_task(long_running())
loop._active_tasks[UNIFIED_SESSION_KEY] = {task}
msg = InboundMessage(
channel="telegram",
chat_id="123456",
sender_id="user1",
content="/stop",
)
ctx = CommandContext(msg=msg, session=None, key=UNIFIED_SESSION_KEY, raw="/stop", loop=loop)
result = await cmd_stop(ctx)
assert task.cancelled() or task.done()
assert "Stopped 1 task" in result.content
@pytest.mark.asyncio
async def test_stop_command_cross_channel_in_unified_mode(self, tmp_path: Path):
from nanobot.command.builtin import cmd_stop
loop = _make_loop(tmp_path, unified_session=True)
async def long_running():
await asyncio.sleep(10)
task1 = asyncio.create_task(long_running())
task2 = asyncio.create_task(long_running())
loop._active_tasks[UNIFIED_SESSION_KEY] = {task1, task2}
msg = InboundMessage(
channel="discord",
chat_id="789012",
sender_id="user2",
content="/stop",
session_key_override=UNIFIED_SESSION_KEY,
)
ctx = CommandContext(msg=msg, session=None, key=UNIFIED_SESSION_KEY, raw="/stop", loop=loop)
result = await cmd_stop(ctx)
assert "Stopped 2 task" in result.content
+2 -5
View File
@@ -28,13 +28,11 @@ from nanobot.security.workspace_access import (
build_workspace_scope,
reset_workspace_scope,
)
from nanobot.session.keys import UNIFIED_SESSION_KEY
from nanobot.utils.llm_runtime import LLMRuntime
def _make_loop(
tmp_path: Path, *, allow_set: bool = False, restricted: bool = False, sandbox: str = "",
unified_session: bool = False,
) -> AgentLoop:
provider = MagicMock()
provider.get_default_model.return_value = "test-model"
@@ -49,7 +47,6 @@ def _make_loop(
model="test-model",
tools_config=tools_config,
restrict_to_workspace=restricted,
unified_session=unified_session,
)
@@ -505,7 +502,7 @@ async def test_followup_only_joins_matching_tool_scope(tmp_path: Path, same_scop
project = tmp_path / "project"
project.mkdir()
(project / "marker.txt").write_text("active project", encoding="utf-8")
loop = _make_loop(tmp_path / "agent", unified_session=True)
loop = _make_loop(tmp_path / "agent")
loop.provider.generation = GenerationSettings()
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content=None, tool_calls=[
@@ -513,7 +510,7 @@ async def test_followup_only_joins_matching_tool_scope(tmp_path: Path, same_scop
]),
LLMResponse(content="done"),
])
session = await loop.sessions.state.get(UNIFIED_SESSION_KEY)
session = await loop.sessions.state.get("websocket:chat")
session.metadata["workspace_scope"] = {"project_path": str(project), "access_mode": "restricted"}
session.add_message("user", "Start")
await loop.sessions.state.prepare_input(session)
-1
View File
@@ -32,7 +32,6 @@ def _make_mock_loop(**overrides):
loop.model_preset = None
loop.model_presets = {}
loop._concurrency_gate = None
loop._unified_session = False
loop._extra_hooks = []
loop.set_runtime_model.side_effect = lambda value: setattr(loop, "model", value)
loop.set_runtime_max_iterations.side_effect = lambda value: setattr(loop, "max_iterations", value)
+1 -1
View File
@@ -91,7 +91,7 @@ async def test_scope_snapshots_route_and_queues_events_in_order():
factory = TurnDeliveryFactory(bus)
delivery = factory.create(InboundMessage(
channel="slack", sender_id="u", chat_id="chat", content="", metadata=metadata,
), "unified:default")
), "slack:chat")
metadata["slack"]["thread_ts"] = "moved"
for phase in ("started", "succeeded"):
await delivery.events.emit(ContextCompactionEvent("c1", phase))
@@ -165,5 +165,5 @@ def test_persisted_webui_session_prefix_has_one_production_owner() -> None:
def test_runtime_exports_compatibility_protocol_helpers() -> None:
assert runtime._is_valid_chat_id("unified:default") # pyright: ignore[reportPrivateUsage]
assert runtime._is_valid_chat_id("chat:branch-2") # pyright: ignore[reportPrivateUsage]
assert not runtime._is_valid_chat_id("../escape") # pyright: ignore[reportPrivateUsage]
+3 -8
View File
@@ -8,7 +8,6 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
from nanobot.cli.gateway_runtime import _deliver_to_channel
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
from nanobot.session.keys import UNIFIED_SESSION_KEY
from nanobot.session.manager import SessionManager
from nanobot.webui.gateway_services import build_gateway_services
@@ -125,16 +124,12 @@ async def webui_delivery(delivery, tmp_path, monkeypatch):
@pytest.mark.parametrize("caption", ["caption", ""])
async def test_unified_webui_media_keeps_its_display_generation(webui_delivery, caption):
async def test_webui_media_keeps_its_display_generation(webui_delivery, caption):
sessions, bus, tool, channel = webui_delivery
alias = await sessions.state.get_header("websocket:chat")
canonical = await sessions.state.get_header(UNIFIED_SESSION_KEY)
tool.set_send_callback(partial(
_deliver_to_channel, bus=bus, session_manager=sessions, unified_session=True,
))
with request_context(RequestContext(
"websocket", "chat", session_key=canonical.key,
session_generation=canonical.generation,
"websocket", "chat", session_key=alias.key,
session_generation=alias.generation,
metadata={HISTORY_GENERATION_METADATA_KEY: alias.generation},
)):
result = await tool.execute(content=caption, media=["attachment.txt"])
-36
View File
@@ -1998,42 +1998,6 @@ def test_heartbeat_target_skips_archived_webui_sessions():
assert target == ("websocket", "active")
def test_heartbeat_target_uses_last_channel_for_unified_session():
from nanobot.cli.gateway_runtime import _pick_heartbeat_target_from_sessions
from nanobot.session.keys import LAST_CHANNEL_METADATA_KEY, UNIFIED_SESSION_KEY
target = _pick_heartbeat_target_from_sessions(
enabled_channels=["telegram", "discord"],
archived_keys=[],
sessions=[{"key": UNIFIED_SESSION_KEY}],
unified_session_metadata={LAST_CHANNEL_METADATA_KEY: "discord:chat-42"},
)
assert target == ("discord", "chat-42")
@pytest.mark.parametrize(
"metadata",
[
{"last_channel": "telegram:chat-42"},
{"last_channel": "cli:direct"},
{"last_channel": "invalid"},
],
)
def test_heartbeat_target_rejects_unroutable_unified_metadata(metadata):
from nanobot.cli.gateway_runtime import _pick_heartbeat_target_from_sessions
from nanobot.session.keys import UNIFIED_SESSION_KEY
target = _pick_heartbeat_target_from_sessions(
enabled_channels=["discord"],
archived_keys=[],
sessions=[{"key": UNIFIED_SESSION_KEY}],
unified_session_metadata=metadata,
)
assert target == ("cli", "direct")
def _write_instance_config(tmp_path: Path) -> Path:
config_file = tmp_path / "instance" / "config.json"
config_file.parent.mkdir(parents=True)
+4 -4
View File
@@ -257,7 +257,7 @@ async def test_compact_during_active_turn_waits_for_the_session_lock(loop, comma
)
lock = loop._get_session_lock(key)
async with lock:
await loop._dispatch_command_inline(msg, key, msg.content, loop.commands.dispatch)
await loop._dispatch_command_inline(msg, msg.content, loop.commands.dispatch)
tasks = list(loop._active_tasks[key])
assert len(tasks) == 1
await asyncio.sleep(0)
@@ -285,7 +285,7 @@ async def test_stop_completes_a_compact_command_waiting_for_the_session_lock(loo
completions = []
loop.bus.subscribe(completions.append, TurnCompleted)
async with loop._get_session_lock(key):
await loop._dispatch_command_inline(msg, key, msg.content, loop.commands.dispatch)
await loop._dispatch_command_inline(msg, msg.content, loop.commands.dispatch)
reply = await cmd_stop(CommandContext(
msg=msg, session=None, key=key, raw="/stop", loop=loop,
))
@@ -330,7 +330,7 @@ async def test_compact_is_a_fifo_barrier_during_an_active_turn(loop, command_tex
channel="cli", sender_id="u", chat_id="test", content="before compaction",
)))
command = InboundMessage(channel="cli", sender_id="u", chat_id="test", content=command_text)
await loop._dispatch_command_inline(command, key, command.content, loop.commands.dispatch)
await loop._dispatch_command_inline(command, command.content, loop.commands.dispatch)
(await loop._enqueue_session_message(InboundMessage(
channel="cli", sender_id="u", chat_id="test", content="after compaction",
)))
@@ -375,7 +375,7 @@ async def test_stop_completes_compact_queued_behind_an_active_turn(loop, command
channel="websocket", sender_id="u", chat_id="test", content=command_text,
metadata={"webui_turn_id": "queued-compact"},
)
await loop._dispatch_command_inline(command, key, command.content, loop.commands.dispatch)
await loop._dispatch_command_inline(command, command.content, loop.commands.dispatch)
await cmd_stop(CommandContext(msg=command, session=None, key=key, raw="/stop", loop=loop))
assert task.cancelled()
+7 -8
View File
@@ -8,7 +8,6 @@ import pytest
from nanobot.bus.events import InboundMessage
from nanobot.command.application import build_help_text, register_builtin_commands
from nanobot.command.router import CommandContext, CommandRouter
from nanobot.session.keys import UNIFIED_SESSION_KEY
from nanobot.triggers.local_store import LocalTriggerStore
@@ -47,7 +46,7 @@ async def test_trigger_command_creates_session_bound_local_trigger(tmp_path: Pat
@pytest.mark.asyncio
async def test_trigger_command_binds_inbound_session_when_unified_session_is_active(
async def test_trigger_command_binds_explicit_topic_session(
tmp_path: Path,
) -> None:
router = CommandRouter()
@@ -55,16 +54,16 @@ async def test_trigger_command_binds_inbound_session_when_unified_session_is_act
store = LocalTriggerStore(tmp_path)
loop = SimpleNamespace(workspace=tmp_path, local_trigger_store=store)
msg = InboundMessage(
channel="websocket",
channel="telegram",
sender_id="user",
chat_id="chat-1",
content="/trigger PR review",
session_key_override="websocket:chat-1:thread-a",
session_key_override="telegram:chat-1:topic:5",
)
ctx = CommandContext(
msg=msg,
session=None,
key=UNIFIED_SESSION_KEY,
key=msg.session_key,
raw="/trigger PR review",
loop=loop,
)
@@ -72,9 +71,9 @@ async def test_trigger_command_binds_inbound_session_when_unified_session_is_act
response = await router.dispatch(ctx)
assert response is not None
trigger = store.list_for_session("websocket:chat-1:thread-a")[0]
assert trigger.session_key == "websocket:chat-1:thread-a"
assert store.list_for_session(UNIFIED_SESSION_KEY) == []
trigger = store.list_for_session("telegram:chat-1:topic:5")[0]
assert trigger.session_key == "telegram:chat-1:topic:5"
assert store.list_for_session("telegram:chat-1") == []
@pytest.mark.asyncio
+15
View File
@@ -17,6 +17,21 @@ from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequ
from nanobot.session.manager import SessionManager
@pytest.mark.asyncio
async def test_bound_job_runs_with_its_saved_session_key(tmp_path):
cron = CronService(tmp_path / "jobs.json")
job = cron.add_job(
"Reminder", CronSchedule(kind="every", every_ms=86_400_000), "Take a break",
session_key="unified:default", origin_channel="telegram", origin_chat_id="old",
)
agent = MagicMock(submit_cron_turn=AsyncMock(return_value=None))
await run_bound_cron_job(job, agent=agent, cron=cron)
message = agent.submit_cron_turn.await_args.args[0]
assert message.session_key == "unified:default"
assert (message.channel, message.chat_id) == ("telegram", "old")
@pytest.mark.asyncio
@pytest.mark.parametrize("delivery", ["reply", "legacy_message", "broadcast"])
async def test_moved_cron_keeps_reply_send_and_prompt_prefix_contract(tmp_path, monkeypatch, delivery):
+18 -3
View File
@@ -10,7 +10,6 @@ from nanobot.bus.outbound_events import RecoveryStateEvent, SessionUpdatedEvent
from nanobot.bus.queue import MessageBus
from nanobot.providers.base import ProviderConversationState
from nanobot.session.display_history import HistoryFact, HistoryKind
from nanobot.session.keys import UNIFIED_SESSION_KEY
from nanobot.session.manager import Session, SessionManager
from nanobot.session.recovery import (
PENDING_FOLLOWUPS_KEY,
@@ -45,6 +44,23 @@ def _coordinator(workspace: Path) -> tuple[RecoveryCoordinator, MessageBus, Sess
return RecoveryCoordinator(sessions, bus), bus, sessions
@pytest.mark.asyncio
async def test_startup_preserves_interrupted_retired_session_without_resuming(tmp_path: Path):
coordinator, bus, sessions = _coordinator(tmp_path)
shared = sessions.get_or_create("unified:default")
shared.add_message("user", "Old shared request")
shared.metadata.update(last_channel="websocket:chat", **{PENDING_USER_TURN_KEY: True})
_persist(sessions, shared)
await coordinator.scan()
retained = await sessions.state.read(shared.key)
assert retained is not None
assert retained.messages == shared.messages
assert retained.metadata == shared.metadata
assert bus.inbound.empty() and bus.outbound.empty()
@pytest.mark.asyncio
async def test_restart_before_model_call_waits_for_confirmation(tmp_path: Path) -> None:
sessions = SessionManager(tmp_path)
@@ -681,8 +697,7 @@ async def test_new_user_message_supersedes_waiting_recovery(tmp_path: Path) -> N
@pytest.mark.parametrize("channel", ["websocket", "discord"])
async def test_new_input_only_supersedes_recovery_for_websocket(tmp_path: Path, channel: str) -> None:
coordinator, bus, sessions = _coordinator(tmp_path)
coordinator.unified_session = True
session = sessions.get_or_create(UNIFIED_SESSION_KEY)
session = sessions.get_or_create("websocket:chat")
session.metadata[RECOVERY_METADATA_KEY] = {
"status": "resuming",
"recovery_id": "active",
+59
View File
@@ -103,6 +103,65 @@ def test_from_config_creates_instance(tmp_path):
assert bot._loop.sessions.sessions_dir.parent == config_path.parent / "sessions"
@pytest.mark.asyncio
async def test_shared_history_remains_readable_after_retirement(tmp_path):
from nanobot.session.manager import SessionManager
config_path = _write_config(tmp_path, {
"agents": {"defaults": {"model": "openai/gpt-4.1", "unifiedSession": True}},
})
workspace = tmp_path / "workspace"
before = SessionManager(workspace, sessions_root=config_path.parent / "sessions")
shared = before.get_or_create("unified:default")
shared.metadata["last_channel"] = "telegram:legacy-chat"
shared.add_message("user", "Old shared question")
shared.add_message("assistant", "Old shared answer")
before.save(shared)
await before.state.aclose()
config_bytes = config_path.read_bytes()
for _ in range(2):
async with Nanobot.from_config(config_path, workspace=workspace) as bot:
assert {row.key for row in await bot.sessions.list()} >= {"unified:default"}
snapshot = await bot.sessions.get("unified:default")
assert snapshot is not None
assert [row["content"] for row in snapshot.messages] == [
"Old shared question", "Old shared answer",
]
assert config_path.read_bytes() == config_bytes
@pytest.mark.asyncio
@pytest.mark.parametrize("legacy_key", ["unifiedSession", "unified_session"])
async def test_legacy_unified_config_keeps_runs_isolated(tmp_path, monkeypatch, legacy_key):
from nanobot.providers.base import LLMResponse
config_path = _write_config(tmp_path, {
"agents": {"defaults": {"model": "openai/gpt-4.1", legacy_key: True}},
})
original_config = config_path.read_bytes()
provider = _fake_provider("test-model")
provider.aclose = AsyncMock()
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="reply"))
monkeypatch.setattr("nanobot.providers.factory.make_provider", lambda *_args: provider)
async with Nanobot.from_config(config_path, workspace=tmp_path / "workspace") as bot:
await bot.run("alice secret", session_key="sdk:alice")
await bot.run("bob secret", session_key="sdk:bob")
await bot.run("alice followup", session_key="sdk:alice")
alice = await bot.sessions.get("sdk:alice")
bob = await bot.sessions.get("sdk:bob")
assert [m["content"] for m in alice.messages] == [
"alice secret", "reply", "alice followup", "reply",
]
assert [m["content"] for m in bob.messages] == ["bob secret", "reply"]
prompts = [str(call.kwargs["messages"]) for call in provider.chat_stream_with_retry.await_args_list]
assert "alice secret" not in prompts[1]
assert "alice secret" in prompts[2]
assert "bob secret" not in prompts[2]
assert config_path.read_bytes() == original_config
def test_from_config_composes_configured_mcp_outside_agent_loop(tmp_path):
config_path = _write_config(
tmp_path,
+3 -4
View File
@@ -13,7 +13,6 @@ from nanobot.agent.tools.subagent import SubagentTool
from nanobot.cron.service import CronService
from nanobot.providers.base import GenerationSettings, LLMProvider
from nanobot.runtime_context import RUNTIME_CONTEXT_INPUT_META, RuntimeContextBlock
from nanobot.session.keys import UNIFIED_SESSION_KEY
from nanobot.utils.llm_runtime import LLMRuntime
@@ -281,7 +280,7 @@ async def test_cron_tool_basic_request_context_and_execute(tmp_path) -> None:
@pytest.mark.asyncio
async def test_webui_cron_tool_uses_origin_session_when_unified_enabled(tmp_path) -> None:
async def test_webui_cron_tool_binds_origin_chat(tmp_path) -> None:
tool = CronTool(CronService(tmp_path / "jobs.json"))
with request_context(
@@ -289,7 +288,7 @@ async def test_webui_cron_tool_uses_origin_session_when_unified_enabled(tmp_path
channel="websocket",
chat_id="chat-123",
metadata={"webui": True},
session_key=UNIFIED_SESSION_KEY,
session_key="websocket:chat-123",
)
):
result = await tool.execute(action="add", message="standup", every_seconds=300)
@@ -321,7 +320,7 @@ async def test_cron_tool_snapshots_only_persistable_request_metadata(tmp_path) -
],
"opaque": object(),
},
session_key=UNIFIED_SESSION_KEY,
session_key="websocket:chat-123",
)
):
result = await tool.execute(action="add", message="standup", every_seconds=300)
+27
View File
@@ -6,6 +6,7 @@ import json
import os
from contextlib import suppress
from pathlib import Path
from unittest.mock import AsyncMock
import pytest
@@ -275,6 +276,32 @@ def test_recover_processing_deliveries_requeues_claimed_delivery(tmp_path: Path)
assert reclaimed[0].last_error == "delivery was recovered from interrupted processing"
@pytest.mark.asyncio
async def test_trigger_delivers_to_its_saved_session(tmp_path: Path) -> None:
store = LocalTriggerStore(tmp_path)
trigger = store.create(
name="Old trigger", channel="websocket", chat_id="chat-1",
session_key="unified:default",
)
store.enqueue(trigger.id, "Process this delivery")
submit_turn = AsyncMock()
task = asyncio.create_task(run_local_trigger_queue(
store=store, submit_turn=submit_turn, is_channel_enabled=_channel_is_enabled,
))
try:
async with asyncio.timeout(3):
while not (current := store.get(trigger.id)) or current.last_status != "ok":
await asyncio.sleep(0.01)
message = submit_turn.await_args.args[0]
assert message.session_key == "unified:default"
assert (message.channel, message.chat_id) == ("websocket", "chat-1")
finally:
task.cancel()
with suppress(asyncio.CancelledError):
await task
@pytest.mark.asyncio
async def test_local_trigger_queue_submits_bound_inbound_message(tmp_path: Path) -> None:
store = LocalTriggerStore(tmp_path)
@@ -1,7 +1,6 @@
[
"agents.defaults.timezone",
"agents.defaults.timezone_mode",
"agents.defaults.unified_session",
"agents.defaults.session_ttl_minutes",
"agents.defaults.max_tool_iterations",
"agents.defaults.max_concurrent_subagents",
+1 -1
View File
@@ -18,7 +18,7 @@ def test_webui_session_identity_preserves_persisted_wire_compatibility() -> None
def test_webui_chat_id_validation_is_protocol_scoped() -> None:
assert is_valid_webui_chat_id("unified:default")
assert is_valid_webui_chat_id("chat:branch-2")
assert is_valid_webui_chat_id("x" * 64)
assert not is_valid_webui_chat_id("x" * 65)
assert not is_valid_webui_chat_id("../escape")
@@ -38,7 +38,6 @@ export const RUNTIME_CONFIG_FIELDS: RuntimeConfigField[] = [
{ group: "execution", path: "agents.defaults.max_tool_result_chars", kind: "number", min: 1 },
{ group: "execution", path: "agents.defaults.tool_hint_max_length", kind: "number", min: 20, max: 500 },
{ group: "execution", path: "tools.max_session_messages_per_minute", kind: "number", min: 1 },
{ group: "sessions", path: "agents.defaults.unified_session", kind: "boolean" },
{ group: "sessions", path: "agents.defaults.session_ttl_minutes", kind: "idle-compaction", manual: true },
{ group: "tools", path: "tools.exec.enable", kind: "boolean" },
{ group: "tools", path: "tools.file.enable", kind: "boolean" },
+1 -1
View File
@@ -63,7 +63,7 @@ export const settings: SettingsPayload = {
transcription: { enabled: true, provider: "groq", provider_configured: true, model: "whisper-large-v3", language: null,
max_duration_sec: 120, max_upload_mb: 25, providers: [{ name: "groq", label: "Groq", configured: true }] },
runtime: { config_path: "config.json", workspace_path: "workspace", gateway_host: "127.0.0.1", gateway_port: 8765,
heartbeat: { enabled: true, interval_s: 1800 }, dream: { schedule: "0 3 * * *" }, unified_session: false },
heartbeat: { enabled: true, interval_s: 1800 }, dream: { schedule: "0 3 * * *" } },
advanced: { restrict_to_workspace: true, ssrf_whitelist_count: 0, webui_allow_local_service_access: true,
webui_default_access_mode: "default", private_service_protection_enabled: true, mcp_server_count: 0,
exec_enabled: true, exec_path_prepend_set: false, exec_path_append_set: false },
-4
View File
@@ -589,10 +589,6 @@
"label": "Message rate",
"help": "Maximum tool messages to one session per minute.\n\nMaximum number of messages tools can send to the same session each minute."
},
"agents_defaults_unified_session": {
"label": "Shared sessions",
"help": "Share one user's chat history across platforms.\n\nShare conversation history across chat channels for a single user."
},
"tools_exec_enable": {
"label": "Shell tool",
"help": "Allow the agent to run Shell commands.\n\nAllow the agent to run shell commands."
-1
View File
@@ -556,7 +556,6 @@
"agents_defaults_provider_retry_mode": {"label": "Seguir reintentando", "help": "Reintenta errores recuperables; desactívalo para usar reintentos estándar.\n\nVuelve a intentar las solicitudes al modelo tras un error temporal. Desactiva esta opción para limitar el número de reintentos."},
"agents_defaults_tool_hint_max_length": {"label": "Longitud del resumen", "help": "Límite de caracteres de los resúmenes de herramientas.\n\nLongitud máxima de las indicaciones breves de actividad."},
"tools_max_session_messages_per_minute": {"label": "Frecuencia de mensajes", "help": "Máximo de mensajes de herramientas a una sesión por minuto.\n\nLimita la frecuencia de los mensajes que envían las herramientas a una conversación."},
"agents_defaults_unified_session": {"label": "Sesiones compartidas", "help": "Comparte el historial de un usuario entre plataformas.\n\nUsa la misma conversación para un usuario en varias plataformas de chat."},
"tools_exec_enable": {"label": "Herramienta de shell", "help": "Permite al agente ejecutar comandos Shell.\n\nPermite al agente ejecutar comandos de shell."},
"tools_file_enable": {"label": "Herramientas de archivos", "help": "Permite las herramientas integradas de lectura y edición de archivos."},
"tools_web_enable": {"label": "Acceso web", "help": "Permite buscar y leer páginas web.\n\nPermite buscar en la web y obtener páginas."},
-1
View File
@@ -556,7 +556,6 @@
"agents_defaults_provider_retry_mode": {"label": "Réessayer en continu", "help": "Réessayez les erreurs récupérables ; désactivez pour les tentatives standard.\n\nRelance les requêtes après une erreur temporaire du modèle. Désactivez cette option pour limiter le nombre de tentatives."},
"agents_defaults_tool_hint_max_length": {"label": "Longueur du résumé", "help": "Limite de caractères des résumés d’activité des outils.\n\nLongueur maximale des brèves indications d’activité."},
"tools_max_session_messages_per_minute": {"label": "Fréquence des messages", "help": "Nombre maximal de messages d’outils vers une session par minute.\n\nLimite la fréquence des messages envoyés par les outils dans une conversation."},
"agents_defaults_unified_session": {"label": "Sessions partagées", "help": "Partagez l’historique d’un utilisateur entre plateformes.\n\nUtilise une même conversation pour un utilisateur sur plusieurs plateformes."},
"tools_exec_enable": {"label": "Outil shell", "help": "Autorisez l’agent à exécuter des commandes Shell.\n\nAutorise l’agent à exécuter des commandes shell."},
"tools_file_enable": {"label": "Outils de fichiers", "help": "Autorisez les outils intégrés de lecture et d’édition de fichiers.\n\nAutorise les outils intégrés de lecture et de modification de fichiers."},
"tools_web_enable": {"label": "Accès web", "help": "Autorisez la recherche et la lecture de pages web.\n\nAutorise la recherche et la récupération de pages web."},
-1
View File
@@ -556,7 +556,6 @@
"agents_defaults_provider_retry_mode": {"label": "Terus mencoba", "help": "Ulangi setelah kesalahan yang dapat dipulihkan; nonaktifkan untuk percobaan standar.\n\nMencoba kembali permintaan ke model saat terjadi kesalahan sementara. Nonaktifkan untuk membatasi jumlah percobaan ulang."},
"agents_defaults_tool_hint_max_length": {"label": "Panjang ringkasan", "help": "Batas karakter ringkasan aktivitas alat.\n\nPanjang maksimum petunjuk singkat aktivitas alat."},
"tools_max_session_messages_per_minute": {"label": "Frekuensi pesan", "help": "Batas pesan alat ke satu sesi per menit.\n\nMembatasi frekuensi alat mengirim pesan ke percakapan."},
"agents_defaults_unified_session": {"label": "Sesi bersama", "help": "Bagikan riwayat chat satu pengguna di berbagai platform.\n\nMenggunakan satu percakapan untuk satu pengguna di beberapa platform chat."},
"tools_exec_enable": {"label": "Alat shell", "help": "Izinkan agen menjalankan perintah Shell.\n\nMengizinkan agen menjalankan perintah shell."},
"tools_file_enable": {"label": "Alat file", "help": "Izinkan alat bawaan untuk membaca dan mengedit berkas.\n\nMengizinkan alat bawaan untuk membaca dan mengedit file."},
"tools_web_enable": {"label": "Akses web", "help": "Izinkan pencarian dan pembacaan halaman web.\n\nMengizinkan pencarian web dan pengambilan halaman."},
-1
View File
@@ -556,7 +556,6 @@
"agents_defaults_provider_retry_mode": {"label": "再試行を継続", "help": "回復可能なエラーで再試行します。オフでは標準の再試行を使います。\n\nモデルへのリクエストが一時的なエラーで失敗した場合、成功するまで再試行します。オフにすると再試行回数を制限します。"},
"agents_defaults_tool_hint_max_length": {"label": "概要の長さ", "help": "ツールの実行概要に表示する文字数上限です。\n\nツールの動作を簡潔に表示する説明文の最大文字数です。"},
"tools_max_session_messages_per_minute": {"label": "メッセージ頻度", "help": "同じセッションにツールが送る毎分のメッセージ上限です。\n\nツールが会話にメッセージを送信する頻度を制限します。"},
"agents_defaults_unified_session": {"label": "セッション共有", "help": "同じユーザーのチャット履歴を複数のプラットフォームで共有します。\n\n1 人のユーザーが複数のチャットプラットフォームで同じ会話を使用します。"},
"tools_exec_enable": {"label": "シェルツール", "help": "エージェントによる Shell コマンドの実行を許可します。\n\nエージェントによるシェルコマンドの実行を許可します。"},
"tools_file_enable": {"label": "ファイルツール", "help": "組み込みのファイル読み取り・編集ツールを許可します。"},
"tools_web_enable": {"label": "ウェブアクセス", "help": "ウェブ検索とページの読み取りを許可します。\n\nウェブ検索とページ取得を許可します。"},
-1
View File
@@ -556,7 +556,6 @@
"agents_defaults_provider_retry_mode": {"label": "계속 재시도", "help": "복구 가능한 오류는 계속 재시도합니다. 끄면 기본 재시도를 사용합니다.\n\n일시적인 오류로 모델 요청이 실패하면 계속 재시도합니다. 끄면 재시도 횟수를 제한합니다."},
"agents_defaults_tool_hint_max_length": {"label": "요약 길이", "help": "도구 실행 요약의 글자 수 상한입니다.\n\n도구 활동을 나타내는 짧은 안내의 최대 길이입니다."},
"tools_max_session_messages_per_minute": {"label": "메시지 빈도", "help": "도구가 한 세션에 보내는 분당 메시지 수 상한입니다.\n\n도구가 대화에 메시지를 보내는 빈도를 제한합니다."},
"agents_defaults_unified_session": {"label": "세션 공유", "help": "동일 사용자의 채팅 기록을 여러 플랫폼에서 공유합니다.\n\n한 사용자가 여러 채팅 플랫폼에서 같은 대화를 사용합니다."},
"tools_exec_enable": {"label": "셸 도구", "help": "에이전트의 Shell 명령 실행을 허용합니다.\n\n에이전트의 셸 명령 실행을 허용합니다."},
"tools_file_enable": {"label": "파일 도구", "help": "내장 파일 읽기와 편집 도구를 허용합니다.\n\n기본 파일 읽기 및 편집 도구를 허용합니다."},
"tools_web_enable": {"label": "웹 접근", "help": "웹 검색과 페이지 읽기를 허용합니다.\n\n웹 검색과 페이지 가져오기를 허용합니다."},
-1
View File
@@ -556,7 +556,6 @@
"agents_defaults_provider_retry_mode": {"label": "Continuar tentando", "help": "Tente novamente após erros recuperáveis; desative para tentativas padrão.\n\nTenta novamente quando uma solicitação ao modelo falha por um erro temporário. Desative para limitar o número de tentativas."},
"agents_defaults_tool_hint_max_length": {"label": "Tamanho do resumo", "help": "Limite de caracteres dos resumos de atividade das ferramentas.\n\nTamanho máximo das indicações breves de atividade."},
"tools_max_session_messages_per_minute": {"label": "Frequência de mensagens", "help": "Máximo de mensagens de ferramentas para uma sessão por minuto.\n\nLimita a frequência das mensagens enviadas pelas ferramentas à conversa."},
"agents_defaults_unified_session": {"label": "Sessões compartilhadas", "help": "Compartilhe o histórico de um usuário entre plataformas.\n\nUsa a mesma conversa para um usuário em diferentes plataformas de chat."},
"tools_exec_enable": {"label": "Ferramenta de shell", "help": "Permita que o agente execute comandos Shell.\n\nPermite que o agente execute comandos de shell."},
"tools_file_enable": {"label": "Ferramentas de arquivos", "help": "Permita ferramentas integradas de leitura e edição de arquivos.\n\nPermite as ferramentas integradas de leitura e edição de arquivos."},
"tools_web_enable": {"label": "Acesso à web", "help": "Permita pesquisar e ler páginas web.\n\nPermite pesquisar na web e obter páginas."},
-1
View File
@@ -556,7 +556,6 @@
"agents_defaults_provider_retry_mode": {"label": "Tiếp tục thử lại", "help": "Thử lại khi lỗi có thể khắc phục; tắt để dùng cách thử lại tiêu chuẩn.\n\nTự động thử lại khi yêu cầu gửi đến mô hình gặp lỗi tạm thời. Tắt tùy chọn này để giới hạn số lần thử lại."},
"agents_defaults_tool_hint_max_length": {"label": "Độ dài tóm tắt", "help": "Giới hạn ký tự tóm tắt hoạt động công cụ.\n\nĐộ dài tối đa của gợi ý ngắn về hoạt động công cụ."},
"tools_max_session_messages_per_minute": {"label": "Tần suất tin nhắn", "help": "Số tin nhắn công cụ gửi đến một phiên mỗi phút tối đa.\n\nGiới hạn tần suất công cụ gửi tin nhắn vào cuộc trò chuyện."},
"agents_defaults_unified_session": {"label": "Phiên dùng chung", "help": "Chia sẻ lịch sử trò chuyện của một người dùng giữa các nền tảng.\n\nDùng chung một cuộc trò chuyện cho một người dùng trên nhiều nền tảng."},
"tools_exec_enable": {"label": "Công cụ shell", "help": "Cho phép agent chạy lệnh Shell.\n\nCho phép tác nhân chạy lệnh shell."},
"tools_file_enable": {"label": "Công cụ tệp", "help": "Cho phép công cụ đọc và chỉnh sửa tệp tích hợp.\n\nCho phép dùng công cụ đọc và chỉnh sửa tệp tích hợp."},
"tools_web_enable": {"label": "Truy cập web", "help": "Cho phép tìm kiếm web và đọc trang.\n\nCho phép tìm kiếm và tải nội dung trang web."},
-4
View File
@@ -589,10 +589,6 @@
"label": "消息频率",
"help": "工具每分钟向同一会话发消息的上限"
},
"agents_defaults_unified_session": {
"label": "共享会话",
"help": "同一用户的跨平台对话共用记录\n\n让同一用户在不同聊天平台的对话共用会话记录。"
},
"tools_exec_enable": {
"label": "执行命令",
"help": "允许智能体执行 Shell 命令"
-1
View File
@@ -556,7 +556,6 @@
"agents_defaults_provider_retry_mode": {"label": "持續重試", "help": "可恢復錯誤持續重試;關閉用標準策略\n\n遇到可恢復的請求錯誤時持續重試。關閉後使用標準重試策略。"},
"agents_defaults_tool_hint_max_length": {"label": "提示長度", "help": "工具執行提示的字元數上限\n\n工具執行時顯示的簡短提示最多包含多少個字元。"},
"tools_max_session_messages_per_minute": {"label": "訊息頻率", "help": "工具每分鐘向同一會話發訊息的上限"},
"agents_defaults_unified_session": {"label": "共享會話", "help": "同一使用者的跨平臺對話共用記錄\n\n讓同一使用者在不同聊天平臺的對話共用會話記錄。"},
"tools_exec_enable": {"label": "Shell 工具", "help": "允許智慧體執行 Shell 命令"},
"tools_file_enable": {"label": "檔案工具", "help": "允許使用內建檔案讀取和編輯工具"},
"tools_web_enable": {"label": "網頁訪問", "help": "允許搜尋網頁和讀取網頁內容"},
-1
View File
@@ -908,7 +908,6 @@ export interface SettingsPayload {
dream: {
schedule: string;
};
unified_session: boolean;
};
usage?: {
days: Array<{
-2
View File
@@ -156,7 +156,6 @@ function baseSettingsPayload() {
dream: {
schedule: "every 2h",
},
unified_session: false,
},
advanced: {
restrict_to_workspace: false,
@@ -3657,7 +3656,6 @@ describe("App layout", () => {
dream: {
schedule: "every 2h",
},
unified_session: false,
},
advanced: {
restrict_to_workspace: false,
@@ -11,7 +11,7 @@ const path = "agents.defaults.session_ttl_minutes";
function setup(minutes = 720) {
let persisted = {
...settingsPayload(),
runtime_config: { [path]: minutes, "agents.defaults.unified_session": false },
runtime_config: { [path]: minutes },
};
requestMutationMock.mockImplementation(async (_action, { values }) => {
persisted = { ...persisted, requires_restart: true,
-1
View File
@@ -92,7 +92,6 @@ export function settingsPayload(): SettingsPayload {
dream: {
schedule: "every 2h",
},
unified_session: false,
},
advanced: {
restrict_to_workspace: false,
-1
View File
@@ -438,7 +438,6 @@ function modelSettings(model: string, provider: string): SettingsPayload {
dream: {
schedule: "every 2h",
},
unified_session: false,
},
advanced: {
restrict_to_workspace: false,