Skip to content

Wip/sandbox no claude - #3139

Merged
pedrofrxncx merged 218 commits into
mainfrom
wip/sandbox-no-claude
Apr 23, 2026
Merged

pedrofrxncx merged 218 commits into
mainfrom
wip/sandbox-no-claude

Conversation

@pedrofrxncx

@pedrofrxncx pedrofrxncx commented Apr 22, 2026 •

Copy link
Copy Markdown
Collaborator

What is this contribution about?

Describe your changes and why they're needed.

Screenshots/Demonstration

Add screenshots or a Loom video if your changes affect the UI.

How to Test

Provide step-by-step instructions for reviewers to test your changes:

  1. Step one
  2. Step two
  3. Expected outcome

Migration Notes

Only one new migration lands in this PR:

  • apps/mesh/migrations/069-sandbox-runner-state.ts — creates sandbox_runner_state (runner state keyed on user_id, project_ref, runner_kind).

068-threads-branch.ts (nullable threads.branch column) is already on the base branch (tlgimenes/github-pr-panel) and is not part of this diff, even though the cubic auto-summary below lists both.

Deploy steps (in order):

  1. bun run --cwd apps/mesh migrate
  2. docker build -t mesh-sandbox:local packages/mesh-plugin-user-sandbox/image
  3. Set MESH_SANDBOX_RUNNER=docker (the resolver throws in production when unset).

Review Checklist

  • PR title is clear and descriptive
  • Changes are tested and working
  • Documentation is updated (if needed)
  • No breaking changes

Summary by cubic

Adds per-user, per-branch sandboxes behind a runner-agnostic SandboxRunner via mesh-plugin-user-sandbox (Docker + Freestyle), with a secure app-proxied daemon and a branch-aware GitHub PR workflow. Threads persist a branch, VMs are keyed by user+branch in vmMap, and the UI auto-picks/starts a branch with a Git PR panel (actions + sub‑tabs).

  • New Features

    • Runner-agnostic sandboxes + state: unified API for Docker/Freestyle; VMs stored as vmMap[userId][branch] -> { vmId, previewUrl, runnerKind }. VM_DELETE dispatches by stored runnerKind. Persistent sandbox_runner_state resumes/cleans sandboxes across restarts.
    • Secure daemon + ingress: app route /api/sandbox/:handle/_daemon with strict ownership and per‑VM bearer; local Docker ingress on *.sandboxes.localhost:7070 with boot‑time orphan sweep and graceful shutdown.
    • VM tools: runner-agnostic read/write/edit/grep/glob/bash over SandboxRunner.proxyDaemonRequest using canonical /_daemon/* paths (translated for Freestyle). Lazy handle resolver; large outputs previewed via read_tool_output. Single SSE fanout for daemon events.
    • GitHub UX: sticky deco/* branch picker, Git tab (Description/Changes/Checks) with header actions, auto‑start on mount, improved booting state, and per‑turn context ring. Stream requests tag threadId for tracing.
  • Migration

    • Run DB migrations (adds threads.branch and sandbox_runner_state).
    • Build the Docker sandbox image: docker build -t mesh-sandbox:local packages/mesh-plugin-user-sandbox/image (dev auto‑kicks a background build; set MESH_SANDBOX_IMAGE to skip).
    • Choose a runner with MESH_SANDBOX_RUNNER (docker or freestyle). Optional local ingress: set MESH_LOCAL_SANDBOX_INGRESS=1 and use http://<handle>.sandboxes.localhost:7070.

Written for commit 1a763d9. Summary will update on new commits.

@github-actions

Copy link
Copy Markdown
Contributor

🧪 Benchmark

Should we run the Virtual MCP strategy benchmark for this PR?

React with 👍 to run the benchmark.

Reaction Action
👍 Run quick benchmark (10 & 128 tools)

Benchmark will run on the next push after you react.

@github-actions

github-actions Bot commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor

Release Options

Suggested: Patch (2.272.3) — default (no conventional commit prefix detected)

React with an emoji to override the release type:

Reaction Type Next Version
👍 Prerelease 2.272.3-alpha.1
🎉 Patch 2.272.3
❤️ Minor 2.273.0
🚀 Major 3.0.0

Current version: 2.272.2

Note: If multiple reactions exist, the smallest bump wins. If no reactions, the suggested bump is used (default: patch).

tlgimenes and others added 28 commits April 22, 2026 11:47
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- Adds optional branch input to VM_START
- Daemon receives injectedBranch, attaches to origin/<branch> if it exists
  on the remote; otherwise creates a new local branch
- Domain key includes branch (when provided) so different branches for the
  same user get distinct preview domains
- After vm creation, writes vmMap[userId][branch] = vmId
- Lookup prefers vmMap[userId][branch] when branch is injected, falling back
  to activeVms for branch-unaware callers

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
StreamRequestSchema accepts optional branch. Routes pass it to streamCore.
createMemory persists it on the thread when the thread is created for the
first time; existing threads keep their branch.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Reads available branches from vmMap (yours) + github-mcp-server.list_branches
(others). "+ New branch" sub-form invokes create_branch synchronously.
Selected branch is stored in ?branch=... URL param, injected into message
metadata on sendMessage so the server persists it on first-message thread
creation and forwards to VM_START.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
github-mcp-server returns branches as a stringified JSON in content[0].text
rather than structuredContent. Accept both shapes.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- New "git" tab with git-branch icon when metadata.githubRepo is set
- GitTab renders 3 states: no branch, no PR yet, PR open, PR merged/closed
- Primary actions (Create PR / Squash & merge / Rebase / Close) call
  sendMessage with natural-language templates; LLM executes via its
  github tools
- PR data fetched via useMCPToolCallQuery (list_pull_requests, 60s poll)
- Parses both structuredContent and content[0].text tool-result shapes
- Instructions tab preserved for non-github vms — zero regression

Scoped MVP: single view, no sub-tabs (Changes/Checks/Comments deferred),
no header action buttons (buttons render inside the tab for now).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ntext)

MainPanelContent renders as a SIBLING of ActiveTaskProvider inside
ChatMainPanelGroup, so useChatStream/useOptionalChatStream return null
there. Switch GitTab to useChatBridge and extend ChatBridgeValue to
expose isStreaming so action buttons still disable during a turn.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Agent was asking clarifying questions because prompts didn't specify the
repo. Each template now leads with "On repo `owner/repo`, …" so the
agent can act immediately.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ates

GitHub MCP tools like update_pull_request_branch perform merge-of-base
rather than true rebase, so rebase/resolve-conflicts/create-PR templates
now instruct the agent to use the BASH tool with git in the vm's working
tree. PR-level ops (close, reopen, merge) keep using GitHub MCP tools.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Creating a new task from the tasks panel previously dropped ?branch and
?main URL params, forcing the user to re-select the branch and re-open
the git tab. Preserve both so the new thread inherits the prior state.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
useChatBridge previously returned bridgeRef.current captured at
ChatContextProvider's first render — always BRIDGE_NOOP when a consumer
rendered before ActiveTaskProvider registered the real sendMessage.

Now the context holds the RefObject and useChatBridge returns wrappers
that read .current at call time. Consumers get the latest sendMessage /
isStreaming even when the bridge is registered later.

Fixes GitTab buttons silently no-op'ing on a fresh task page load.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
tlgimenes and others added 12 commits April 22, 2026 23:05
GitHub-linked vMCPs: Connections → Automations → Layout → Terminal →
Preview → git. Previously git led the list.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…el top

Three coordinated moves to make the git context feel minimal:

1. The git tab's label is now the current branch name (falls back to
   "git" when no branch is selected). Clicking the tab was already the
   user's way to see branch detail; making the label the branch makes
   the breadcrumb self-evident.

2. The main header center drops the branch chip and the PR# chip. Only
   the vMCP icon+title remain there. The center column gets its
   breathing room back.

3. Inside the git panel, a new PrHeader row (h-12, border-b) renders
   "PR #N ↗" prominently above the sub-tabs / merged summary. Single
   link — click to open the PR on GitHub. The older "Open PR #N on
   GitHub" button in the merged state is removed (the new header
   supersedes it).

No PR → no PrHeader; the existing "No pull request yet" body stands on
its own.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Previously preview.tsx, env.tsx, and use-branch-status.ts each opened
their own EventSource to /_decopilot_vm/events. On reloads the old
connections didn't always release before new ones opened, backing up
against the daemon's MAX_SSE_CLIENTS cap and leaving branchStatus stuck
at null — which made the selector hide the Publish button until a
manual VM restart.

Now:
- VmEventsProvider (added in a prior commit) owns exactly one
  EventSource per previewUrl and fans out to all consumers via React
  context. Chunk subscribers register through a Set-backed registry.
- useVmEvents() is argless and just reads the context.
- useVmChunkHandler(handler) registers per-consumer PTY chunk
  subscriptions with stale-closure safety via a ref.
- useBranchStatus() collapses to `useVmEvents().branchStatus`.
- HeaderActions drops its direct session/userId plumbing (the provider
  does the vmMap → previewUrl derivation once, at the layout level).

The provider mounts inside Chat.Provider in agent-shell-layout for
both desktop and mobile, so all VM-event consumers are always inside
one shared scope.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- Introduced per-kind `SandboxRunner` singletons to manage state and lifecycle for Docker and Freestyle runners.
- Implemented boot and shutdown sweeps specific to Docker, ensuring proper cleanup of orphaned containers.
- Refactored sandbox daemon interactions to support both Docker and Freestyle runners, streamlining the codebase and improving modularity.
- Removed outdated Docker-specific transport files, consolidating VM tool functionality into a unified structure.
- Introduced focused tests for the translateDaemonPath function in freestyle-runner, ensuring accurate mapping from Docker's daemon paths to Freestyle's format.
- Covered various scenarios including valid mappings, null returns for unrecognized paths, and preservation of query strings.
- Exported translateDaemonPath for unit testing to maintain coverage as new runners are added.
…wip/sandbox-no-claude

Conflicts in apps/mesh/src/web/components/vm/hooks/use-vm-events.ts,
preview.tsx, and env.tsx resolved by adopting the incoming single-SSE
VmEventsProvider architecture while preserving notFound (404-probe
reprovision), connection-based suspension, and iframe-reload support
from wip/sandbox-no-claude. VmEventsProvider now takes a daemonBaseUrl
so agent-shell-layout can route docker runners through the mesh proxy.
Splits refreshAccessToken into its own file so mock.module can intercept
calls made from inside refreshAndStore, and adds proactive refresh to
buildCloneInfo so the daemon's git clone no longer fails when the stored
token has expired between VM_START calls.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Without this scope the MCP SDK's authorize request omits both `scope` and
`prompt=consent`, and downstream OAuth servers (e.g. sites-github-mcp)
don't issue a refresh_token. The resulting token row in downstream_tokens
has null refresh_token / null expires_at and can never be proactively
refreshed — forcing users to reconnect whenever the token goes stale.

Applied at every authenticateMcp call site in apps/mesh/src/web.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- Introduced `useVmStart` hook to centralize VM_START logic, improving error handling and state management across different components.
- Updated `start.test.ts` to validate the `createdAt` timestamp for VM entries, ensuring it reflects server-side provisioning time.
- Refactored `preview.tsx` to utilize the new mutation hook for auto-start and self-heal scenarios, enhancing the user experience by reducing redundant calls.
- Added `callVmTool` utility to standardize error handling for VM-related tool calls, ensuring consistent error reporting.
- Enhanced `VmMapEntry` schema to include `createdAt` for better tracking of VM lifecycle events.
@pedrofrxncx

Copy link
Copy Markdown
Collaborator Author

@cubic-ai

@cubic-dev-ai

cubic-dev-ai Bot commented Apr 23, 2026

Copy link
Copy Markdown
Contributor

@cubic-ai

@pedrofrxncx I have started the AI code review. It will take a few minutes to complete.

…ion tests

- Added new optional dependencies for freestyle integration in package.json.
- Introduced comprehensive tests for sandbox daemon authorization, ensuring proper access control and error handling for different user scenarios.
- Refactored sandbox daemon route handling to improve authorization checks and response behaviors.
- Enhanced the Docker and Freestyle runner implementations to support concurrent operations with state management.
- Improved error handling and logging in Docker runner operations to ensure better observability during failures.
…s files

- Simplified and clarified comments in migration, API routes, and sandbox runner files to improve readability and maintainability.
- Removed redundant explanations and consolidated information to focus on key functionalities and behaviors.
- Enhanced documentation for VM tools and lifecycle management, ensuring consistency and better understanding of the codebase.
- Updated test descriptions to reflect the purpose and scope of tests more accurately.
…r operations

- Introduced `RunnerStateStoreOps` interface for scoped database operations, improving transaction handling during concurrent state management.
- Updated `DockerSandboxRunner` and `FreestyleSandboxRunner` to utilize scoped store connections, preventing main pool starvation during long provisioning.
- Refactored state persistence methods to accept scoped store, ensuring consistent access to database connections.
- Improved comments and documentation for clarity on state management and locking mechanisms across sandbox runners.
- Enhanced `useVmStart` hook to centralize VM_START logic, reducing redundant calls and improving error handling across components.
- Added a `daemonToken` field to the `DaemonConfig` interface, ensuring a secure token is generated and validated for each VM.
- Enhanced the `FreestyleSandboxRunner` and `DockerSandboxRunner` to utilize the bearer token for authorization on `/_decopilot_vm/*` requests.
- Updated the `freestyle-daemon-script` to include bearer token checks, improving security for VM interactions.
- Refactored tests to include regression checks for the new authorization mechanism, ensuring proper handling of runner kinds during VM operations.
- Streamlined comments and documentation to clarify the new authentication flow and its implications for VM management.
Base automatically changed from tlgimenes/github-pr-panel to main April 23, 2026 20:42
… for sandbox runners

- Refactored `FreestyleSandboxRunner` to centralize VM disposal logic in `disposeVm`, improving error handling and logging during VM deletion.
- Implemented new tests for `KyselySandboxRunnerStateStore` to validate state persistence and retrieval, ensuring robust state management across different runner types.
- Added lifecycle tests for Docker and Freestyle runners, verifying correct behavior during VM provisioning and teardown scenarios.
- Updated `VM_START` handler to manage stale VMs when runner types change, ensuring efficient resource utilization and preventing orphaned VMs.
- Enhanced comments and documentation for clarity on VM lifecycle operations and state management.
- Updated the `PreviewContent` component to include a check for the `branch` variable before determining if the VM should auto-start. This prevents issues with deduplication keys and ensures the correct sandbox is used during VM operations.
…ing logic

- Merged `ChatContextProvider` and `ActiveTaskProvider` into a single `Chat.Provider`, streamlining the context management for chat components.
- Updated `ChatMainPanelGroup` to directly render `ChatCenterPanel`, removing unnecessary indirection and improving performance.
- Enhanced the handling of chat content with a new `chatContent` prop, allowing for more flexible rendering options.
- Removed unused exports and cleaned up the codebase for better maintainability.
- Added `kickoffSandboxImageBuild` function to initiate background image checks and builds for Docker when running in development mode.
- Updated CLI commands to call this function with appropriate options based on the `noTui` flag, ensuring that the image build process is triggered seamlessly during development server startup.
- Introduced a new `sandbox-image.ts` file to encapsulate the image build logic, improving code organization and maintainability.
- Enhanced Docker runner to ensure the sandbox image is present before starting the development server, preventing potential runtime issues.
@pedrofrxncx
pedrofrxncx marked this pull request as ready for review April 23, 2026 22:28
@pedrofrxncx
pedrofrxncx merged commit 8aa970a into main Apr 23, 2026
15 checks passed
@pedrofrxncx
pedrofrxncx deleted the wip/sandbox-no-claude branch April 23, 2026 22:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants