Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 19 additions & 7 deletions src/app/sbx/new/route.ts

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

you are breaking the sbx.new here since it does not create a sandbox anymore.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

still works but making it so we only use new terminal if we have a template or a command then

Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import { normalizeTerminalTemplate } from '@/features/dashboard/terminal/templat
export const GET = async (req: NextRequest) => {
try {
const requestUrl = new URL(req.url)
const shouldUseTerminalCreateFlow =
requestUrl.searchParams.has('template') ||
requestUrl.searchParams.has('command')
const template = normalizeTerminalTemplate(
requestUrl.searchParams.get('template') ?? undefined
)
Expand Down Expand Up @@ -39,6 +42,22 @@ export const GET = async (req: NextRequest) => {
return NextResponse.redirect(new URL(req.url).origin)
}

const terminalParams = new URLSearchParams({ template })
const command = requestUrl.searchParams.get('command')?.trim()

if (command) {
terminalParams.set('command', command)
}

if (shouldUseTerminalCreateFlow) {
return NextResponse.redirect(
new URL(
`${PROTECTED_URLS.TERMINAL(team.slug)}?${terminalParams.toString()}`,
req.url
)
)
}

const sbx = await Sandbox.create(template, {
apiUrl: process.env.NEXT_PUBLIC_INFRA_API_URL,
domain: process.env.NEXT_PUBLIC_E2B_DOMAIN,
Expand All @@ -47,13 +66,6 @@ export const GET = async (req: NextRequest) => {
},
})

const terminalParams = new URLSearchParams({ template })
const command = requestUrl.searchParams.get('command')?.trim()

if (command) {
terminalParams.set('command', command)
}

const terminalUrl = PROTECTED_URLS.SANDBOX_TERMINAL(
team.slug,
sbx.sandboxId
Expand Down
10 changes: 10 additions & 0 deletions src/core/modules/feature-flags/definitions.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { z } from 'zod'
import type { FeatureFlagDefinition } from '@/core/modules/feature-flags/types'

export const FEATURE_FLAGS = {
Expand Down Expand Up @@ -31,6 +32,15 @@ export const FEATURE_FLAGS = {
'Disables provisioning of e2b access tokens via generateE2BUserAccessToken. When enabled, the legacy CLI flow shows an upgrade prompt and the createAccessToken tRPC mutation returns an error.',
exposure: 'server',
},
trustedTemplateProviders: {
kind: 'payload',
key: 'trusted_template_providers',
defaultValue: [],
schema: z.array(z.string()),
description:
'Template providers whose namespaced templates can auto-start dashboard terminals.',
exposure: 'both',
},
} as const satisfies Record<string, FeatureFlagDefinition>

export type FeatureFlagId = keyof typeof FEATURE_FLAGS
Expand Down
18 changes: 16 additions & 2 deletions src/core/modules/feature-flags/feature-flags.client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ import {
import {
type BooleanFeatureFlagId,
FEATURE_FLAGS,
type PayloadFeatureFlagId,
} from '@/core/modules/feature-flags/definitions'
import type { EvaluatedFeatureFlag } from '@/core/modules/feature-flags/types'

type FeatureFlagsContextValue = {
flags: EvaluatedFeatureFlag[]
getPayload(flagId: PayloadFeatureFlagId): unknown
isEnabled(flagId: BooleanFeatureFlagId): boolean
}

Expand Down Expand Up @@ -47,9 +49,17 @@ export function FeatureFlagsProvider({
[flagsById]
)

const getPayload = useCallback(
(flagId: PayloadFeatureFlagId) => {
const evaluatedFlag = flagsById.get(flagId)
return evaluatedFlag?.value ?? FEATURE_FLAGS[flagId].defaultValue
},
[flagsById]
)

const value = useMemo(
() => ({ flags: initialFlags, isEnabled }),
[initialFlags, isEnabled]
() => ({ flags: initialFlags, getPayload, isEnabled }),
[initialFlags, getPayload, isEnabled]
)

return (
Expand All @@ -72,3 +82,7 @@ export function useFeatureFlags() {
export function useFeatureFlag(flagId: BooleanFeatureFlagId) {
return useFeatureFlags().isEnabled(flagId)
}

export function useFeatureFlagPayload(flagId: PayloadFeatureFlagId) {
return useFeatureFlags().getPayload(flagId)
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import type { PendingTerminalLaunch } from './types'
interface DashboardTerminalCommandDialogProps {
launch: PendingTerminalLaunch | null
onCancel: () => void
onConfirm: (command: string) => void
onConfirm: (command?: string) => void
}

export default function DashboardTerminalCommandDialog({
Expand All @@ -28,6 +28,8 @@ export default function DashboardTerminalCommandDialog({
const commandInputId = useId()
const [command, setCommand] = useState('')
const normalizedCommand = command.trim()
const hasCommand = launch?.command !== undefined
const untrustedTemplateProvider = launch?.untrustedTemplateProvider

useEffect(() => {
setCommand(launch?.command ?? '')
Expand All @@ -40,10 +42,15 @@ export default function DashboardTerminalCommandDialog({
<div className="mb-1 flex size-9 items-center justify-center border bg-bg">
<WarningIcon className="size-5 text-icon-tertiary" />
</div>
<DialogTitle>Review terminal command</DialogTitle>
<DialogTitle>
{hasCommand
? 'Review terminal command'
: 'Review terminal template'}
</DialogTitle>
<DialogDescription>
This command will run inside a persistent E2B sandbox after the
terminal opens.
{hasCommand
? 'This command will run inside a persistent E2B sandbox after the terminal opens.'
: 'This terminal will start from a template published by an untrusted provider.'}
</DialogDescription>
</DialogHeader>

Expand All @@ -63,21 +70,33 @@ export default function DashboardTerminalCommandDialog({
{launch.target?.template ?? 'base'}
</code>
</div>
<div className="space-y-1">
<label
className="prose-label text-fg-tertiary"
htmlFor={commandInputId}
>
Command
</label>
<Textarea
className="max-h-48 min-h-24 font-mono text-xs"
id={commandInputId}
onChange={(event) => setCommand(event.target.value)}
spellCheck={false}
value={command}
/>
</div>
{untrustedTemplateProvider ? (
<div className="space-y-1">
<p className="prose-label text-fg-tertiary">
Template provider
</p>
<code className="block border bg-bg px-3 py-2 font-mono text-xs text-fg">
{untrustedTemplateProvider}
</code>
</div>
) : null}
{hasCommand ? (
<div className="space-y-1">
<label
className="prose-label text-fg-tertiary"
htmlFor={commandInputId}
>
Command
</label>
<Textarea
className="max-h-48 min-h-24 font-mono text-xs"
id={commandInputId}
onChange={(event) => setCommand(event.target.value)}
spellCheck={false}
value={command}
/>
</div>
) : null}
</div>
) : null}

Expand All @@ -87,10 +106,12 @@ export default function DashboardTerminalCommandDialog({
</Button>
<Button
type="button"
disabled={!normalizedCommand}
onClick={() => onConfirm(normalizedCommand)}
disabled={hasCommand && !normalizedCommand}
onClick={() =>
onConfirm(hasCommand ? normalizedCommand : undefined)
}
>
Run command
{hasCommand ? 'Run command' : 'Start terminal'}
</Button>
</DialogFooter>
</DialogContent>
Expand Down
81 changes: 69 additions & 12 deletions src/features/dashboard/terminal/dashboard-terminal.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
'use client'

import type { CommandHandle, Sandbox } from 'e2b'
import { useCallback, useEffect, useEffectEvent, useRef, useState } from 'react'
import {
useCallback,
useEffect,
useEffectEvent,
useMemo,
useRef,
useState,
} from 'react'
import { useFeatureFlagPayload } from '@/core/modules/feature-flags/feature-flags.client'
import { useTRPCClient } from '@/trpc/client'
import {
DEFAULT_CWD,
Expand All @@ -11,6 +19,7 @@ import {
import DashboardTerminalCommandDialog from './dashboard-terminal-command-dialog'
import { openTerminalSandbox } from './sandbox-session'
import {
getUntrustedTerminalTemplateProvider,
normalizeTerminalTemplate,
resolveTerminalTemplateOverride,
} from './template'
Expand Down Expand Up @@ -52,6 +61,18 @@ export default function DashboardTerminal({
userId,
}: DashboardTerminalProps) {
const trpcClient = useTRPCClient()
const trustedTemplateProvidersPayload = useFeatureFlagPayload(
'trustedTemplateProviders'
)
const trustedTemplateProviders = useMemo(
() =>
Array.isArray(trustedTemplateProvidersPayload)
? trustedTemplateProvidersPayload.filter(
(provider): provider is string => typeof provider === 'string'
)
: [],
[trustedTemplateProvidersPayload]
)

const [status, setStatus] = useState<TerminalStatus>('idle')
const [activeSandboxId, setActiveSandboxId] = useState<string>()
Expand Down Expand Up @@ -443,15 +464,24 @@ export default function DashboardTerminal({
return
}

if (command.trim()) {
// Commands can come from links, so require an explicit click before
// sending anything into the PTY.
const normalizedCommand = command.trim()
const untrustedTemplateProvider = !options.target?.sandboxId
? getUntrustedTerminalTemplateProvider(
nextTemplate,
trustedTemplateProviders
)
: undefined

if (normalizedCommand || untrustedTemplateProvider) {
// Commands and third-party template starts can come from links, so
// require an explicit click before creating a sandbox or writing PTY input.
setPendingLaunch({
Comment thread
matthewlouisbrockman marked this conversation as resolved.
command: command.trim(),
command: normalizedCommand || undefined,
target: {
...options.target,
template: nextTemplate,
},
untrustedTemplateProvider,
})
return
}
Comment thread
matthewlouisbrockman marked this conversation as resolved.
Expand All @@ -466,21 +496,22 @@ export default function DashboardTerminal({
})
}
},
[appendOutput, startTerminal, status, template]
[appendOutput, startTerminal, status, template, trustedTemplateProviders]
)

const confirmPendingLaunch = useCallback(
(command: string) => {
(command?: string) => {
if (!pendingLaunch) return

const normalizedCommand = command.trim()
if (!normalizedCommand) return
const normalizedCommand = command?.trim() ?? ''
if (pendingLaunch.command !== undefined && !normalizedCommand) return

const { target: launchTarget } = pendingLaunch
const launchTemplate = launchTarget?.template ?? 'base'
const launchSandboxId = launchTarget?.sandboxId

if (
normalizedCommand &&
status === 'ready' &&
template === launchTemplate &&
(!launchSandboxId || activeSandboxId === launchSandboxId)
Expand All @@ -501,9 +532,11 @@ export default function DashboardTerminal({
}

setPendingLaunch(null)
pendingCommandsRef.current = [normalizedCommand]
pendingCommandsRef.current = normalizedCommand ? [normalizedCommand] : []
Comment thread
cursor[bot] marked this conversation as resolved.
Comment thread
cursor[bot] marked this conversation as resolved.
void startTerminal({
forceNewSandbox: !launchSandboxId && template !== launchTemplate,
forceNewSandbox:
pendingLaunch.forceNewSandbox ??
(!launchSandboxId && template !== launchTemplate),
target: launchTarget,
})
},
Expand All @@ -518,6 +551,14 @@ export default function DashboardTerminal({
]
)

const cancelPendingLaunch = useCallback(() => {
if (pendingLaunch?.untrustedTemplateProvider && !activeSandboxId) {
setTemplate('base')
}

setPendingLaunch(null)
}, [activeSandboxId, pendingLaunch])

const reconnectTarget = sandboxScoped
? launchTarget
: activeSandboxId
Expand All @@ -543,13 +584,29 @@ export default function DashboardTerminal({
return
}

const untrustedTemplateProvider = getUntrustedTerminalTemplateProvider(
template,
trustedTemplateProviders
)

if (untrustedTemplateProvider) {
setPendingLaunch({
forceNewSandbox: true,
target: { template },
untrustedTemplateProvider,
})
return
}

void startTerminal({ forceNewSandbox: true })
}, [
getSandbox,
reconnectTarget,
reconnectSandboxId,
sandboxScoped,
startTerminal,
template,
trustedTemplateProviders,
])

useEffect(() => {
Expand Down Expand Up @@ -615,7 +672,7 @@ export default function DashboardTerminal({

<DashboardTerminalCommandDialog
launch={pendingLaunch}
onCancel={() => setPendingLaunch(null)}
onCancel={cancelPendingLaunch}
onConfirm={confirmPendingLaunch}
/>
</>
Expand Down
Loading
Loading