-
Notifications
You must be signed in to change notification settings - Fork 52.5k
feat(gateway): add /workspace command for multi-workspace sessions #62075
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
joymadhu49
wants to merge
1
commit into
NousResearch:main
Choose a base branch
from
joymadhu49:feat/workspaces
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -102,6 +102,112 @@ def _typed_command_prefix_for(self, platform) -> str: | |
| adapter = self.adapters.get(platform) if getattr(self, "adapters", None) else None | ||
| return getattr(adapter, "typed_command_prefix", "/") if adapter is not None else "/" | ||
|
|
||
| async def _handle_workspace_command(self, event: MessageEvent) -> str: | ||
| """List and manage registered gateway working directories.""" | ||
| try: | ||
| parts = shlex.split((event.text or "").strip()) | ||
| except ValueError as exc: | ||
| return f"Invalid /workspace arguments: {exc}" | ||
| args = parts[1:] | ||
| action = args[0].lower() if args else "list" | ||
| if action not in {"list", "new", "switch", "remove"}: | ||
| args = ["switch", *args] | ||
| action = "switch" | ||
|
|
||
| source = event.source | ||
| entry = await self.async_session_store.get_or_create_session(source) | ||
| session_key = entry.session_key | ||
|
|
||
| def _operate() -> tuple[str, Optional[tuple[str, str]]]: | ||
| from hermes_cli.config import load_config, save_config | ||
| from hermes_constants import get_hermes_home | ||
|
|
||
| cfg = load_config() | ||
| gateway_cfg = cfg.setdefault("gateway", {}) | ||
| raw_registry = gateway_cfg.setdefault("workspaces", {}) | ||
| registry = raw_registry if isinstance(raw_registry, dict) else {} | ||
| if raw_registry is not registry: | ||
| gateway_cfg["workspaces"] = registry | ||
|
|
||
| if action == "list": | ||
| current_name = entry.workspace_name or "default" | ||
| current_cwd = entry.workspace_cwd or os.environ.get( | ||
| "TERMINAL_CWD", str(Path.home()) | ||
| ) | ||
| lines = [f"Current: {current_name} ({current_cwd})", "Workspaces:"] | ||
| if not registry: | ||
| lines.append(" (none registered)") | ||
| for name, raw_path in sorted(registry.items()): | ||
| marker = "*" if name == entry.workspace_name else " " | ||
| lines.append(f"{marker} {name}: {raw_path}") | ||
| if entry.workspace_name and entry.workspace_name not in registry: | ||
| lines.append(f"* {entry.workspace_name}: {entry.workspace_cwd} (unregistered)") | ||
| if entry.workspace_name: | ||
| lines.append("* = current") | ||
| return "\n".join(lines), None | ||
|
|
||
| if action == "new": | ||
| if len(args) not in {2, 3}: | ||
| return "Usage: /workspace new <name> [path]", None | ||
| name = args[1] | ||
| if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}", name) or name in {".", ".."}: | ||
| return "Workspace names may contain letters, numbers, '.', '_', and '-' (max 64).", None | ||
| if name in registry: | ||
| return f"Workspace '{name}' is already registered at {registry[name]}", None | ||
| path = Path(args[2]).expanduser() if len(args) == 3 else get_hermes_home() / "workspaces" / name | ||
| try: | ||
| path = path.resolve(strict=False) | ||
| path.mkdir(parents=True, exist_ok=True) | ||
| except OSError as exc: | ||
| return f"Could not create workspace '{name}': {exc}", None | ||
| registry[name] = str(path) | ||
| save_config(cfg) | ||
| return f"Registered workspace '{name}' at {path}", None | ||
|
|
||
| if len(args) != 2: | ||
| return f"Usage: /workspace {action} <name>", None | ||
| name = args[1] | ||
| if name not in registry: | ||
| return f"Unknown workspace '{name}'. Use /workspace list to see registered workspaces.", None | ||
|
|
||
| path = Path(str(registry[name])).expanduser().resolve(strict=False) | ||
| if action == "remove": | ||
| del registry[name] | ||
| save_config(cfg) | ||
| if entry.workspace_name == name: | ||
| fallback = os.environ.get("TERMINAL_CWD", str(Path.home())) | ||
| return f"Unregistered workspace '{name}'. Files were not deleted.", ("", fallback) | ||
| return f"Unregistered workspace '{name}'. Files were not deleted.", None | ||
|
|
||
| if not path.is_dir(): | ||
| return f"Workspace '{name}' path does not exist or is not a directory: {path}", None | ||
| return f"Switched workspace to '{name}' ({path})", (name, str(path)) | ||
|
|
||
| if getattr(getattr(self, "config", None), "multiplex_profiles", False): | ||
| from gateway.run import _profile_runtime_scope | ||
| with _profile_runtime_scope(self._resolve_profile_home_for_source(source)): | ||
| message, selection = await asyncio.to_thread(_operate) | ||
| else: | ||
| message, selection = await asyncio.to_thread(_operate) | ||
|
|
||
| if selection is not None: | ||
| name, cwd = selection | ||
| updated = await self.async_session_store.set_workspace( | ||
| session_key, name or None, cwd if name else None, | ||
| ) | ||
| if updated is not None: | ||
| from tools.terminal_tool import register_task_env_overrides | ||
| register_task_env_overrides(updated.session_id, { | ||
| "cwd": cwd, | ||
| # Gateway workspaces may run concurrently. Mark this task | ||
| # as isolated so two sessions never share a mutable env.cwd. | ||
| "env_type": os.environ.get("TERMINAL_ENV", "local"), | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| }) | ||
| db = getattr(self.session_store, "_db", None) | ||
| if db is not None: | ||
| await asyncio.to_thread(db.update_session_cwd, updated.session_id, cwd) | ||
| return message | ||
|
|
||
| async def _handle_reset_command(self, event: MessageEvent) -> Union[str, EphemeralReply]: | ||
| """Handle /new or /reset command.""" | ||
| source = event.source | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| """Behavior contracts for gateway /workspace management.""" | ||
|
|
||
| from types import SimpleNamespace | ||
|
|
||
| import pytest | ||
|
|
||
| from gateway.config import GatewayConfig, Platform, PlatformConfig | ||
| from gateway.platforms.base import MessageEvent | ||
| from gateway.session import SessionSource, SessionStore | ||
| from hermes_constants import reset_hermes_home_override, set_hermes_home_override | ||
|
|
||
|
|
||
| def _source() -> SessionSource: | ||
| return SessionSource( | ||
| platform=Platform.TELEGRAM, | ||
| user_id="workspace-user", | ||
| chat_id="workspace-chat", | ||
| chat_type="dm", | ||
| ) | ||
|
|
||
|
|
||
| def _event(text: str) -> MessageEvent: | ||
| return MessageEvent(text=text, source=_source(), message_id="m1") | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def workspace_runner(tmp_path): | ||
| from gateway.run import GatewayRunner | ||
|
|
||
| home = tmp_path / ".hermes" | ||
| home.mkdir() | ||
| token = set_hermes_home_override(home) | ||
| config = GatewayConfig( | ||
| platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token="test")} | ||
| ) | ||
| runner = object.__new__(GatewayRunner) | ||
| runner.config = config | ||
| runner.adapters = {} | ||
| runner.session_store = SessionStore(home / "gateway-sessions", config) | ||
| runner._async_session_store = None | ||
| runner._session_db = SimpleNamespace(_db=runner.session_store._db) | ||
| runner._agent_cache = {"unchanged": object()} | ||
|
|
||
| try: | ||
| yield runner, home | ||
| finally: | ||
| from tools.terminal_tool import clear_task_env_overrides | ||
|
|
||
| for entry in runner.session_store._entries.values(): | ||
| clear_task_env_overrides(entry.session_id) | ||
| reset_hermes_home_override(token) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_workspace_switch_updates_tools_without_rebuilding_agent(workspace_runner): | ||
| runner, home = workspace_runner | ||
| target = home / "projects" / "alpha" | ||
| cached_agent = runner._agent_cache["unchanged"] | ||
|
|
||
| created = await runner._handle_workspace_command( | ||
| _event(f'/workspace new alpha "{target}"') | ||
| ) | ||
| switched = await runner._handle_workspace_command(_event("/workspace alpha")) | ||
|
|
||
| entry = await runner.async_session_store.get_or_create_session(_source()) | ||
| from tools.terminal_tool import resolve_task_overrides | ||
|
|
||
| assert "Registered workspace 'alpha'" in created | ||
| assert "Switched workspace to 'alpha'" in switched | ||
| assert target.is_dir() | ||
| assert entry.workspace_name == "alpha" | ||
| assert entry.workspace_cwd == str(target.resolve()) | ||
| overrides = resolve_task_overrides(entry.session_id) | ||
| assert overrides["cwd"] == str(target.resolve()) | ||
| assert overrides["env_type"] == "local" | ||
| assert runner._agent_cache["unchanged"] is cached_agent | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_workspace_registry_persists_and_remove_never_deletes_files(workspace_runner): | ||
| runner, home = workspace_runner | ||
|
|
||
| await runner._handle_workspace_command(_event("/workspace new beta")) | ||
| await runner._handle_workspace_command(_event("/workspace switch beta")) | ||
| listed = await runner._handle_workspace_command(_event("/workspace list")) | ||
| target = home / "workspaces" / "beta" | ||
| sentinel = target / "keep.txt" | ||
| sentinel.write_text("keep", encoding="utf-8") | ||
| removed = await runner._handle_workspace_command(_event("/workspace remove beta")) | ||
|
|
||
| from hermes_cli.config import load_config | ||
|
|
||
| entry = await runner.async_session_store.get_or_create_session(_source()) | ||
| assert f"Current: beta ({target.resolve()})" in listed | ||
| assert f"* beta: {target.resolve()}" in listed | ||
| assert "Files were not deleted" in removed | ||
| assert sentinel.read_text(encoding="utf-8") == "keep" | ||
| assert "beta" not in load_config().get("gateway", {}).get("workspaces", {}) | ||
| assert entry.workspace_name is None | ||
| assert entry.workspace_cwd is None | ||
|
|
||
|
|
||
| def test_workspace_selection_survives_session_routing_round_trip(): | ||
| from datetime import datetime | ||
| from gateway.session import SessionEntry | ||
|
|
||
| entry = SessionEntry( | ||
| session_key="agent:main:telegram:dm:u:c", | ||
| session_id="session-1", | ||
| created_at=datetime.now(), | ||
| updated_at=datetime.now(), | ||
| workspace_name="alpha", | ||
| workspace_cwd="/tmp/alpha", | ||
| ) | ||
|
|
||
| restored = SessionEntry.from_dict(entry.to_dict()) | ||
| assert (restored.workspace_name, restored.workspace_cwd) == ( | ||
| entry.workspace_name, | ||
| entry.workspace_cwd, | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is a host path, but container backends reject host-path CWD overrides and fall back to their configured sandbox CWD (
tools/terminal_tool.py:2096-2115). Please map only mounted paths to valid in-container paths, or return a clear unsupported/mount-required result.