Skip to content

feat(sandbox): activate T3 Connect relay on Docker Sandbox registration - #1

Closed
mdelapenya wants to merge 0 commit into
feat/docker-sandbox-connectionsfrom
feat/sandbox-relay-activation
Closed

mdelapenya wants to merge 0 commit into
feat/docker-sandbox-connectionsfrom
feat/sandbox-relay-activation

Conversation

@mdelapenya

Copy link
Copy Markdown
Owner

Summary

  • packages/client-runtime — registerSshConnection now returns SshRegistrationResult (adds httpBaseUrl, wsBaseUrl, bearerToken) instead of just EnvironmentId, so callers can make authenticated API calls to the sandbox server immediately after registration.
  • apps/web/cloud — new linkSandboxEnvironmentToCloud function: a trimmed-down relay activation path that uses the SSH provisioning bearer token per-request (no desktop auth middleware), skips the cloudflared WS readiness check (sandbox kit pre-installs it), and always uses managed tunnel mode.
  • apps/web/connection — new connectAndLinkSandboxEnvironment runtime command: registers SSH → fires relay activation as a non-fatal side-effect (failure is logged as a warning, registration is not rolled back).
  • apps/web/settings — DockerSandboxModeBody now uses handleConnectSandboxHost, which fetches the Clerk token and calls the new command. Toast describes relay outcome ("with T3 Connect relay" vs "over SSH").

Design decisions

  • Fire-and-forget relay: relay activation failure must not block the SSH connection. The user can retry via the T3 Connect toggle in environment settings.
  • Plain fetch layer: remoteHttpClientLayer(globalThis.fetch) is used instead of the primary environment HTTP layer to avoid injecting the desktop bearer token into sandbox requests.
  • No ensureRelayClientAvailable: the sandbox kit is expected to pre-install cloudflared, so no WS check is needed before pushing relay config.
  • satisfies SshRegistrationResult on the return literal (not an explicit Effect.Effect<…> annotation) to preserve correct type inference inside Effect.fn.

Test plan

  • Connect a Docker Sandbox while signed in to T3 Connect → toast should say "with T3 Connect relay"; mobile client should be able to reach the sandbox agent.
  • Connect a Docker Sandbox while not signed in → toast should say "over SSH"; SSH connection should still succeed.
  • Simulate relay activation failure (e.g. wrong relay URL) → SSH connection should succeed, warning logged, no error shown to user.
  • Reconnect an existing sandbox alias → toast title should say "Sandbox reconnected".

@mdelapenya

Copy link
Copy Markdown
Owner Author

Plan: Sandbox Inspect UI Surface

This comment persists the design plan for the next feature: exposing sbx inspect as a UI surface. Filed here because issues are disabled on the fork.


Plan: Sandbox Inspect UI Surface

Goal

Expose the output of sbx inspect <name> as a read-only info panel inside
T3 Code's Settings → Connections view. The panel shows live state of a running
sandbox: exposed ports, mounted secrets, network policies, installed kits,
workspace mounts, and image/resource info.

Why this matters

Today SbxSandboxRow shows name · agent · status · workspace[0] — three
truncated metadata fragments from sbx ls. sbx inspect provides the full
runtime picture: which ports are forwarded into the container, which secrets
are injected (SSH agent socket, env vars), and what network isolation policy is
active. Without this, operators have to drop into a terminal to debug
connectivity or credential issues in a running sandbox.


Architecture layers

The change follows the existing probe → DesktopSbxEnvironment → IPC bridge → component pattern used for sbx ls, with the difference that inspect state
is component-local rather than a shared atom (see Step 5).

sbx inspect <name>  (CLI, desktop side)
    │
    ▼
DesktopSbxCli.ts           buildSbxInspectArgs / parseSbxInspectOutput
    │
    ▼
packages/contracts/src/ipc.ts   DesktopSbxInspectResult schema + type
    │
    ▼
DesktopSbxEnvironment.ts   inspect: (name) => Effect<DesktopSbxInspectResult, DesktopSbxCommandError>
    │
    ▼
apps/desktop/src/ipc/      inspectSbxSandbox exposed on DesktopBridge + IPC handler
    │
    ▼
apps/web/src/state/        no shared atom — inspect state is component-local (see Step 5)
    │
    ▼
apps/web/src/components/   SandboxInspectDrawer — triggered from SbxSandboxRow "Details" button

Step 1 — CLI command shape (apps/desktop/src/sbx/DesktopSbxCli.ts)

Add two pure functions (same pattern as existing buildSbxListArgs /
parseSbxListOutput):

export const buildSbxInspectArgs = (name: string): ReadonlyArray<string> => [
  "inspect",
  "--json",
  name,
];

parseSbxInspectOutput takes the raw JSON string from stdout and returns a
DesktopSbxInspectResult | null. Unknown fields are ignored (forward-compat).
Parsing errors return null rather than throwing.


Step 2 — Contract schema (packages/contracts/src/ipc.ts)

New exported schema and type, placed after DesktopSbxCreateInputSchema:

export const DesktopSbxPortMappingSchema = Schema.Struct({
  /** Host-side port number. */
  hostPort: Schema.Number,
  /** Container-side port number. */
  containerPort: Schema.Number,
  /**
   * Transport protocol. Open string for forward-compat; currently "tcp",
   * "udp", or "sctp". The UI shows the value verbatim in the ports table.
   */
  protocol: Schema.String,
});
export type DesktopSbxPortMapping = typeof DesktopSbxPortMappingSchema.Type;

export const DesktopSbxSecretSchema = Schema.Struct({
  /** Display name for the injected secret, e.g. "SSH_AUTH_SOCK". */
  name: Schema.String,
  /**
   * Type hint for rendering. Open string for forward-compat; known values
   * include "socket", "env", "file". Derived from the sbx inspect payload;
   * never the secret value itself.
   */
  kind: Schema.String,
});
export type DesktopSbxSecret = typeof DesktopSbxSecretSchema.Type;

export const DesktopSbxNetworkPolicySchema = Schema.Struct({
  /**
   * Coarse network isolation level reported by sbx.
   * Open string for forward-compat; known values include "full", "egress-only",
   * "isolated". The UI maps known values to badge colours; unknown values are
   * shown verbatim.
   */
  isolation: Schema.String,
  /** List of allowed egress domains or CIDR blocks, if the policy exposes them. */
  allowedEgress: Schema.Array(Schema.String),
});
export type DesktopSbxNetworkPolicy = typeof DesktopSbxNetworkPolicySchema.Type;

export const DesktopSbxInspectResultSchema = Schema.Struct({
  /** Sandbox name (same as the CLI argument). */
  name: Schema.String,
  /** OCI image reference, e.g. "docker.io/sbx/claude:latest". */
  image: Schema.NullOr(Schema.String),
  /** ISO-8601 creation timestamp. */
  createdAt: Schema.NullOr(Schema.String),
  /** Container runtime status, e.g. "running", "stopped". */
  status: Schema.NullOr(Schema.String),
  /** Agent identifier, e.g. "claude". */
  agent: Schema.NullOr(Schema.String),
  /** Kits applied at creation time. */
  kits: Schema.Array(Schema.String),
  /** Workspace paths mounted into the sandbox. */
  workspaces: Schema.Array(Schema.String),
  /** Host→container port mappings currently active. */
  ports: Schema.Array(DesktopSbxPortMappingSchema),
  /** Injected secrets (name + kind only — never values). */
  secrets: Schema.Array(DesktopSbxSecretSchema),
  /**
   * Network isolation policy, or null when sbx does not report it (e.g. for
   * stopped sandboxes or older sbx versions). The UI omits the section when
   * null.
   */
  networkPolicy: Schema.NullOr(DesktopSbxNetworkPolicySchema),
  /** CPU limit (e.g. "2.0") or null if not set / not reported. */
  cpuLimit: Schema.NullOr(Schema.String),
  /** Memory limit (e.g. "4GiB") or null if not set / not reported. */
  memoryLimit: Schema.NullOr(Schema.String),
});
export type DesktopSbxInspectResult = typeof DesktopSbxInspectResultSchema.Type;

Design note — secrets: The schema carries name + kind only. The parser
must never copy secret values into the result, even if sbx inspect --json
includes them. The UI renders names such as SSH_AUTH_SOCK (socket) in a
read-only list.


Step 3 — Desktop service (apps/desktop/src/sbx/DesktopSbxEnvironment.ts)

Add inspect to the DesktopSbxEnvironment context service:

readonly inspect: (name: string) => Effect.Effect<DesktopSbxInspectResult, DesktopSbxCommandError>;

Implementation in make:

const inspect = (name: string) =>
  Effect.gen(function* () {
    const result = yield* provideSpawner(
      runSbx(buildSbxInspectArgs(name), PROBE_TIMEOUT),
    );
    if (result.transportFailure !== null || result.exitCode !== 0) {
      return yield* failedCommandReason(`Inspecting sandbox "${name}"`, result);
    }
    const parsed = parseSbxInspectOutput(result.stdout);
    if (parsed === null) {
      return yield* new DesktopSbxCommandError({
        reason: `Could not parse \`sbx inspect ${name}\` output. Update sbx or T3 Code to resolve the mismatch.`,
      });
    }
    return parsed;
  }).pipe(Effect.withSpan("desktop.sbx.inspect"));

Timeout: reuses PROBE_TIMEOUT (15 s) since inspect is a lightweight read.


Step 4 — IPC bridge

4a. packages/contracts/src/ipc.ts — DesktopBridge interface

Add to the bridge interface (alongside probeSbx, installSbx):

inspectSbxSandbox?: (name: string) => Promise<DesktopSbxInspectResult>;

4b. apps/desktop/src/preload.ts

Wire inspectSbxSandbox via contextBridge using the same ipc-invocation
pattern as probeSbx.

4c. apps/desktop/src/ipc/DesktopIpcHandlers.ts

Register inspectSbxSandbox handler:

yield* ipc.handle(inspectSbxSandbox);

4d. New file apps/desktop/src/ipc/methods/sbxEnvironment.ts

SSH IPC methods live in sshEnvironment.ts; sbx IPC methods are distinct
enough to warrant their own file. Inspect, and any future sbx IPC methods
(e.g. startSbxSandbox, stopSbxSandbox), belong here.

export const inspectSbxSandbox = DesktopIpc.makeIpcMethod({
  name: "inspectSbxSandbox",
  execute: (name: string) =>
    DesktopSbxEnvironment.pipe(
      Effect.flatMap((sbx) => sbx.inspect(name)),
    ),
});

Step 5 — Web state (apps/web/src/state/desktopSbx.ts)

Inspect is on-demand only — not part of the background probe poll, which
runs on every focus and already costs one sbx ls call. Adding sbx inspect
to the poll would cost one subprocess per sandbox per focus event.

Because @effect/atom-react does not expose a keyed atomFamily API,
per-sandbox inspect state is managed directly in the component using standard
React state (useState + useEffect) rather than a shared atom. This is the
correct choice for ephemeral, component-local data that is not shared across
the tree.

No additions to desktopSbx.ts are needed for this feature. The
SandboxInspectDrawer component owns its own fetch lifecycle:

// Inside SandboxInspectDrawer (component-local, not a shared atom)
const [inspect, setInspect] = useState<DesktopSbxInspectResult | null>(null);
const [error, setError] = useState<string | null>(null);
const [isPending, setIsPending] = useState(false);

const refresh = useCallback(async () => {
  const bridge = window.desktopBridge;
  if (!bridge?.inspectSbxSandbox) return;
  setIsPending(true);
  setError(null);
  try {
    setInspect(await bridge.inspectSbxSandbox(name));
  } catch (e) {
    setError(e instanceof Error ? e.message : String(e));
  } finally {
    setIsPending(false);
  }
}, [name]);

// Fetch on first open.
useEffect(() => { if (open) void refresh(); }, [open, refresh]);

Step 6 — UI component

SandboxInspectDrawer (inline in apps/web/src/components/settings/ConnectionsSettings.tsx)

SbxSandboxRow is currently defined inline in ConnectionsSettings.tsx.
SandboxInspectDrawer is a local sub-component of the same file — extracted
into a separate file would require moving SbxSandboxRow too, which is
unnecessary churn. If the file grows beyond 4 000 lines after this change,
a follow-up issue should extract the sandbox section.

SandboxInspectDrawer is a <Sheet> (slide-over panel, same chrome as the
PR detail panel) triggered by a Details button on SbxSandboxRow. The
button is rendered for any sandbox the desktop bridge can inspect (i.e.
desktopBridge?.inspectSbxSandbox is defined). Restricting to
status === "running" is too conservative — sbx inspect works on stopped
containers and the config is still useful.

Panel sections (collapsible <Accordion> items, open by default):

Section Data source Fields shown
Overview DesktopSbxInspectResult name, agent, image, status badge, createdAt (relative), cpu/memory limits
Ports ports[] Table: Host port → Container port · protocol. Empty state: "No ports exposed."
Secrets secrets[] Badge list: name (kind). Empty state: "No secrets mounted."
Network policy networkPolicy Isolation level badge + allowed egress list (truncated to 10, "+ N more" disclosure). Section hidden when networkPolicy is null. Empty state when networkPolicy.allowedEgress is empty.
Kits kits[] Badge list of kit references. Resolves against SBX_OPTIONAL_KITS for human-readable labels when matched.
Workspaces workspaces[] Monospace path list. Empty state: "No workspace mounted."

Loading & error states:

  • While isPending: skeleton rows inside each section (same ghost pattern as
    PullRequestGhosts).
  • On error: inline AlertDestructive with the error message + a Retry button
    that calls refresh().
  • The Details button itself is hidden in SbxSandboxRow when the bridge is
    unavailable; the drawer assumes bridge.inspectSbxSandbox is defined when
    open.

Refresh: A refresh icon button in the drawer header calls the component-local
refresh callback (see Step 5). No auto-refresh — inspect is a point-in-time
snapshot.

SbxSandboxRow — add Details trigger

desktopBridge is not currently in scope inside SbxSandboxRow. Two
options; the plan chooses option B to avoid prop-drilling:

  • A: Pass showDetails: boolean as a prop from DockerSandboxModeBody
    (where desktopBridge is already accessed). Caller computes
    showDetails={!!desktopBridge?.inspectSbxSandbox}.
  • B: Read window.desktopBridge directly inside the component. This is
    already done elsewhere in ConnectionsSettings.tsx (e.g. handleInstall
    accesses desktopBridge?.installSbx). Because SbxSandboxRow is a memo
    component, the bridge check is O(1) and stable across renders.
// Inside SbxSandboxRow
const desktopBridge = window.desktopBridge;
const [inspectOpen, setInspectOpen] = useState(false);

// In the button row:
{desktopBridge?.inspectSbxSandbox ? (
  <Button size="xs" variant="ghost" onClick={() => setInspectOpen(true)}>
    Details
  </Button>
) : null}
<SandboxInspectDrawer
  name={sandbox.name}
  open={inspectOpen}
  onOpenChange={setInspectOpen}
/>

Step 7 — Tests

DesktopSbxCli.test.ts — parser tests

Add describe("parseSbxInspectOutput") cases:

  • Full valid JSON → all fields populated
  • Missing optional fields → null defaults applied, no throw
  • Port with unknown protocol → passed through as-is
  • Secret with value field present → value field not included in result
  • Unknown top-level key → silently ignored
  • Malformed JSON → returns null

DesktopSbxEnvironment.ts — layerTest stub

When inspect is added to the DesktopSbxEnvironment service interface,
layerTest must include an inspect stub to keep the existing test helper
valid:

export interface DesktopSbxEnvironmentTestStub {
  // ... existing fields ...
  readonly inspectResult?: DesktopSbxInspectResult | DesktopSbxCommandError;
}

// In layerTest:
inspect: (name) =>
  stub.inspectResult !== undefined && isDesktopSbxCommandError(stub.inspectResult)
    ? Effect.fail(stub.inspectResult)
    : stub.inspectResult !== undefined
      ? Effect.succeed(stub.inspectResult)
      : Effect.fail(new DesktopSbxCommandError({ reason: `No inspect stub for "${name}"` })),

SbxSandboxRow — component tests

  • desktopBridge.inspectSbxSandbox defined → Details button rendered
  • desktopBridge.inspectSbxSandbox absent → Details button not rendered
  • Clicking Details button → drawer opens

SandboxInspectDrawer — component tests

Test the drawer in isolation with vi.stubGlobal("desktopBridge", ...):

  • open=true, bridge returns result → all sections render populated data
  • open=true, bridge throws → error message + Retry button rendered
  • Retry button triggers a second inspectSbxSandbox call
  • open transitions from false → true → fetch is triggered exactly once

Rollout / feature gating

No feature flag needed. The Details button is conditionally rendered only
when window.desktopBridge?.inspectSbxSandbox is defined (desktop-app
context). Users on older desktop versions where inspectSbxSandbox is absent
see the existing SbxSandboxRow unchanged — perfect backward compatibility.


Out of scope for this issue

  • Live tail / auto-refresh of inspect data (future: polling atom variant)
  • Port-forward shortcut ("open in browser" for exposed HTTP ports) — needs
    separate user intent model
  • Writing to sandbox config (secrets, network policy changes) — read-only surface only
  • Mobile / React Native surface — desktop-only bridge method, irrelevant on mobile

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The provisioning token lacks relay-write access, and the managed tunnel uses the desktop-side forwarded port rather than the sandbox server port.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

Adds automatic T3 Connect relay activation when registering Docker Sandbox environments over SSH.

Changes:

  • Returns sandbox endpoint credentials after SSH registration.
  • Adds bearer-authenticated sandbox relay linking.
  • Integrates relay activation and outcome messaging into sandbox settings.
File summaries
File Description
packages/client-runtime/src/connection/onboarding.ts Returns SSH endpoint and bearer details.
packages/client-runtime/src/connection/onboarding.test.ts Tests prepared SSH endpoint details.
packages/client-runtime/src/connection/index.ts Exports the registration result type.
apps/web/src/connection/onboarding.ts Adds sandbox registration and relay linking command.
apps/web/src/components/settings/ConnectionsSettings.tsx Uses the new sandbox flow and updates toasts.
apps/web/src/cloud/linkEnvironment.ts Implements sandbox-specific managed relay activation.
Review details
  • Files reviewed: 6/6 changed files
  • Comments generated: 6
  • Review effort level: Balanced

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread apps/web/src/cloud/linkEnvironment.ts Resolved
wsBaseUrl: input.target.wsBaseUrl,
providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,
},
origin: endpointOrigin(input.target.httpBaseUrl),
Comment thread apps/web/src/connection/onboarding.ts Outdated
Comment on lines +84 to +88
yield* linkSandboxEnvironmentToCloud({
target,
clerkToken: input.clerkToken,
bearerToken: registration.bearerToken,
}).pipe(
* - Uses a plain fetch HTTP layer (no desktop bearer middleware) since auth is
* embedded in the `authorization` header per request.
*/
export function linkSandboxEnvironmentToCloud(input: {
@mdelapenya
mdelapenya force-pushed the feat/docker-sandbox-connections branch from f058a3e to ecd584e Compare September 7, 2026 11:10
@mdelapenya
mdelapenya force-pushed the feat/sandbox-relay-activation branch from 6256850 to e401c10 Compare September 7, 2026 11:29
@github-actions github-actions Bot added vouch:trusted PR author is trusted by repo permissions or the VOUCHED list. size:L size:XL and removed size:L labels Sep 7, 2026
@mdelapenya
mdelapenya force-pushed the feat/sandbox-relay-activation branch 2 times, most recently from f26f8e9 to 0133ed1 Compare September 7, 2026 14:33
@mdelapenya
mdelapenya force-pushed the feat/docker-sandbox-connections branch from ce65bea to b826a2c Compare September 8, 2026 09:27
@mdelapenya
mdelapenya force-pushed the feat/sandbox-relay-activation branch from 0133ed1 to 78ff59a Compare September 8, 2026 09:27
@github-actions

github-actions Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Thread transfer impact

⚠️ The latest CI run did not produce a thread transfer result for bf1af6b.

This comment will update automatically after the next completed run.

@mdelapenya
mdelapenya force-pushed the feat/docker-sandbox-connections branch from b826a2c to 6a613b0 Compare September 24, 2026 11:50
@mdelapenya
mdelapenya force-pushed the feat/sandbox-relay-activation branch from 78ff59a to d00428b Compare September 24, 2026 12:32
@mdelapenya
mdelapenya force-pushed the feat/docker-sandbox-connections branch from 6a613b0 to 0528fd1 Compare October 14, 2026 14:12
@mdelapenya

Copy link
Copy Markdown
Owner Author

Merged into feat/docker-sandbox-connections: the base branch was fast-forwarded to this branch's tip and then rebased onto upstream main, so the whole stack now lives on that single branch (pingdotgg/t3code@main...mdelapenya:t3code:feat/docker-sandbox-connections). Closing this PR as superseded and removing the stale head branch.

@mdelapenya mdelapenya closed this Oct 14, 2026
@mdelapenya
mdelapenya deleted the feat/sandbox-relay-activation branch October 14, 2026 14:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:XL vouch:trusted PR author is trusted by repo permissions or the VOUCHED list.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants