feat(sandbox): unify the interactive PTY prompt and reconnect running sandboxes (#3128)
* feat(sandbox): use a classic colored user@host prompt in the PTY Cube, Docker, and E2B now share user@host:last-dir with WeKnora brand green, overriding E2B's default `\w $ ` prompt. * fix(sandbox): redraw the PTY prompt after connect instead of waiting for Enter Reattach does not replay bash's already-printed prompt, and FitAddon can clear the first paint. Fit before flushing output, then Ctrl-L if the screen is still empty. * feat(sandbox): add Debian-style ll/la/l aliases in the interactive PTY Interactive bash now gets colored ls/grep shortcuts; non-interactive skill scripts still see the real commands. * fix(sandbox): restore conventional ls colors so directories stay blue Map ANSI blue/cyan back to Tango colors so directories and executables are distinguishable; keep brand green only for user@host. * fix(sandbox): correct runtime env-var hint to this config and create time The copy claimed workspace-wide injection. Scope it to sandboxes created from this config, point per-run secrets to the Sandbox secrets page, and keep the hint off the add-button row so Chinese no longer wraps mid-word. * feat(sandbox): attach a running session sandbox when the terminal opens Opening the panel used to always show the start overlay. Lookup first so a running sandbox reconnects, while paused or missing sandboxes still wait for an explicit click and Connect cannot silently resume. * fix(sandbox): do not inject PTY input or auto-connect a non-running sandbox Empty-screen reconnect now SIGWINCHes so a reattached busy PTY is not fed Ctrl-L. Lookup-only opens require a click unless List confirms running, and closing the panel drops the terminal mount so a Files-tab reopen cannot attach. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>main
parent
fbaff900a0
commit
3ab6d3940d
|
|
@ -68,6 +68,14 @@ RUN groupadd -g 1000 user && \
|
|||
RUN mkdir -p /workspace/input /workspace/output && \
|
||||
chown -R user:user /workspace
|
||||
|
||||
# Classic user@host:path prompt (colored). E2B's provisioner later appends
|
||||
# `PS1='\w $ '`; the script reapplies this prompt via PROMPT_COMMAND so
|
||||
# Cube, Docker, and E2B all show the same Debian-style line.
|
||||
COPY docker/sandbox-pty-prompt.sh /etc/weknora/pty-prompt.sh
|
||||
RUN echo '. /etc/weknora/pty-prompt.sh' > /etc/profile.d/zz-weknora-prompt.sh && \
|
||||
echo '. /etc/weknora/pty-prompt.sh' >> /root/.bashrc && \
|
||||
echo '. /etc/weknora/pty-prompt.sh' >> /home/user/.bashrc
|
||||
|
||||
WORKDIR /workspace
|
||||
USER root
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,54 @@
|
|||
# WeKnora interactive PTY prompt: classic \u@\h:\W\$
|
||||
# (user@host:last-path-segment, # for root / $ otherwise).
|
||||
#
|
||||
# \W is the last directory only (e.g. /opt/weknora/skills → skills),
|
||||
# so deep cwd does not blow the prompt width.
|
||||
#
|
||||
# Bold green (01;32) is user@host; bold blue (01;34) is the path — the
|
||||
# usual Debian colors, so ls --color can keep directories blue and
|
||||
# executables green. Root uses the same green as a normal user.
|
||||
#
|
||||
# Also enables Debian-style interactive aliases (ll, la, l, colored ls/grep).
|
||||
#
|
||||
# Sourced from profile.d and bashrc. E2B's template provisioner later
|
||||
# appends PS1='\w $ '; PROMPT_COMMAND reapplies this prompt so that cannot
|
||||
# stick. No-op for non-bash (Debian /etc/profile is also read by dash).
|
||||
|
||||
[ -n "${BASH_VERSION-}" ] || return 0
|
||||
|
||||
weknora_set_pty_prompt() {
|
||||
PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\W\[\033[00m\]\$ '
|
||||
}
|
||||
|
||||
weknora_set_pty_prompt
|
||||
|
||||
# Debian/Ubuntu interactive shortcuts. Aliases only apply in interactive
|
||||
# shells, so skill scripts still see the real ls/grep.
|
||||
case "$-" in
|
||||
*i*)
|
||||
if command -v dircolors >/dev/null 2>&1; then
|
||||
eval "$(dircolors -b)"
|
||||
fi
|
||||
alias ls='ls --color=auto'
|
||||
alias grep='grep --color=auto'
|
||||
alias fgrep='fgrep --color=auto'
|
||||
alias egrep='egrep --color=auto'
|
||||
alias ll='ls -alF'
|
||||
alias la='ls -A'
|
||||
alias l='ls -CF'
|
||||
;;
|
||||
esac
|
||||
|
||||
case ";${PROMPT_COMMAND-};" in
|
||||
*weknora_set_pty_prompt*) ;;
|
||||
*)
|
||||
if [ -n "${PROMPT_COMMAND-}" ]; then
|
||||
PROMPT_COMMAND="weknora_set_pty_prompt; ${PROMPT_COMMAND}"
|
||||
else
|
||||
PROMPT_COMMAND="weknora_set_pty_prompt"
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
# PS1 and PROMPT_COMMAND stay shell-local. Exporting PS1 makes child
|
||||
# processes look interactive (`[ -z "$PS1" ]`); exporting PROMPT_COMMAND
|
||||
# without `export -f weknora_set_pty_prompt` breaks nested bash.
|
||||
|
|
@ -677,15 +677,13 @@
|
|||
|
||||
<section v-if="currentStepKey === 'runtime'" class="setting-drawer__section">
|
||||
<div class="section-title-row">
|
||||
<div>
|
||||
<h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.sectionEnvironment') }}</h4>
|
||||
<p class="section-help section-help--under-title">{{ $t('settings.sandbox.envVarsHint') }}</p>
|
||||
</div>
|
||||
<h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.sectionEnvironment') }}</h4>
|
||||
<t-button variant="text" size="small" @click="envRows.push({ key: '', value: '' })">
|
||||
<template #icon><t-icon name="add" /></template>
|
||||
{{ $t('settings.sandbox.addRow') }}
|
||||
</t-button>
|
||||
</div>
|
||||
<p class="section-help section-help--under-title">{{ $t('settings.sandbox.envVarsHint') }}</p>
|
||||
<div v-if="envRows.length" class="env-rows">
|
||||
<div v-for="(row, index) in envRows" :key="index" class="env-row">
|
||||
<t-input v-model="row.key" :placeholder="$t('settings.sandbox.envKey')" class="env-key" />
|
||||
|
|
@ -2360,6 +2358,7 @@ onUnmounted(stopTemplatePolling)
|
|||
&--under-title {
|
||||
margin-top: 5px;
|
||||
max-width: 540px;
|
||||
white-space: pre-line;
|
||||
}
|
||||
|
||||
/* Sits under an input inside the same form item. */
|
||||
|
|
|
|||
|
|
@ -15,3 +15,9 @@ test('artifacts is the first sandbox panel tab', () => {
|
|||
assert.doesNotMatch(panel, /chat-sandbox-panel__title/)
|
||||
assert.doesNotMatch(panel, /<h3/)
|
||||
})
|
||||
|
||||
test('closing the panel drops the terminal mount flag so Files reopen does not reconnect', () => {
|
||||
assert.match(panel, /if\s*\(!visible\)/)
|
||||
assert.match(panel, /terminalMounted\.value = false/)
|
||||
assert.match(panel, /tab === 'terminal'/)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -130,7 +130,13 @@ const terminalRef = ref<{ focus?: () => void } | null>(null)
|
|||
watch(
|
||||
() => [panel?.visible.value, panel?.activeTab.value] as const,
|
||||
([visible, tab]) => {
|
||||
if (visible && tab === 'terminal') {
|
||||
if (!visible) {
|
||||
// Drop the lazy-mount flag so reopening on Files does not remount
|
||||
// SandboxTerminal (which would lookup-connect a PTY and refresh TTL).
|
||||
terminalMounted.value = false
|
||||
return
|
||||
}
|
||||
if (tab === 'terminal') {
|
||||
terminalMounted.value = true
|
||||
void nextTick(() => terminalRef.value?.focus?.())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,8 +3,8 @@ import { post } from '@/utils/request'
|
|||
import { readStoredPtyId, writeStoredPtyId } from '@/utils/sandboxPtyId'
|
||||
|
||||
export type SandboxTerminalStatus =
|
||||
/** 尚未连接:打开面板不会碰后端,等用户显式启动。 */
|
||||
| 'not_started'
|
||||
/** 查询到会话沙箱已暂停;唤醒需要用户确认。 */
|
||||
| 'paused'
|
||||
| 'connecting'
|
||||
| 'ready'
|
||||
/** 查到会话没有运行中的沙箱;创建需要用户确认。 */
|
||||
|
|
@ -66,6 +66,7 @@ function statusFromErrorCode(
|
|||
if (code === 'SANDBOX_NOT_BOUND') {
|
||||
return provisionAttempted ? 'no_sandbox' : 'needs_provision'
|
||||
}
|
||||
if (code === 'SANDBOX_PAUSED') return 'paused'
|
||||
if (code === 'TERMINAL_UNSUPPORTED') return 'unsupported'
|
||||
if (code === 'IDLE_DISCONNECTED') return 'idle'
|
||||
if (code === 'AUTH_REVOKED') return 'unauthorized'
|
||||
|
|
@ -83,11 +84,11 @@ export type SandboxTerminalSession = {
|
|||
/**
|
||||
* 连接并打开终端;已在连接中时幂等。
|
||||
*
|
||||
* provision 表示"这是用户的显式动作,允许后端创建或重建沙箱"。只有点击
|
||||
* 按钮才应该传 true:创建沙箱是要计费的真实基础设施,不能是打开面板的副
|
||||
* 作用。自动重连一律不带,查不到沙箱就退回让用户确认。
|
||||
* provision 表示"这是用户的显式动作,允许后端创建或唤醒沙箱"。只有点击
|
||||
* 按钮才应该传 true:创建/唤醒沙箱是要计费的真实基础设施。打开面板时的
|
||||
* 自动连接一律不带:运行中的沙箱直接挂上,暂停或尚未创建则退回让用户确认。
|
||||
*/
|
||||
connect: (options?: { provision?: boolean }) => void
|
||||
connect: (options?: { provision?: boolean; cols?: number; rows?: number }) => void
|
||||
/** 发送键盘输入(xterm onData 的原始字符串)。 */
|
||||
sendInput: (data: string) => void
|
||||
/** 同步终端尺寸;ready 后调用。 */
|
||||
|
|
@ -106,7 +107,7 @@ export function useSandboxTerminal(
|
|||
agentId: Ref<string | undefined>,
|
||||
agentSourceTenantId: Ref<string | number | null | undefined> = ref(undefined),
|
||||
): SandboxTerminalSession {
|
||||
const status = ref<SandboxTerminalStatus>('not_started')
|
||||
const status = ref<SandboxTerminalStatus>('connecting')
|
||||
|
||||
let ws: WebSocket | null = null
|
||||
let opening = false
|
||||
|
|
@ -118,6 +119,7 @@ export function useSandboxTerminal(
|
|||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let pingTimer: ReturnType<typeof setInterval> | null = null
|
||||
let pendingResize: { cols: number; rows: number } | null = null
|
||||
let pendingGeometry: { cols: number; rows: number } | null = null
|
||||
// 刷新 / 关面板会拆掉这个闭包;PID 写在 sessionStorage,重挂时才能带 pty_id。
|
||||
let lastPid: number | null = readStoredPtyId(sessionId.value)
|
||||
// 当前这次连接是否带创建意图。只由 connect({ provision: true }) 置真。
|
||||
|
|
@ -187,6 +189,10 @@ export function useSandboxTerminal(
|
|||
if (lastPid && lastPid > 0) {
|
||||
query.set('pty_id', String(lastPid))
|
||||
}
|
||||
if (pendingGeometry) {
|
||||
query.set('cols', String(pendingGeometry.cols))
|
||||
query.set('rows', String(pendingGeometry.rows))
|
||||
}
|
||||
const socket = new WebSocket(
|
||||
`${resolveWsBase()}/api/v1/sessions/${encodeURIComponent(sid)}/sandbox/terminal?${query.toString()}`,
|
||||
)
|
||||
|
|
@ -234,6 +240,7 @@ export function useSandboxTerminal(
|
|||
if (
|
||||
event.code === 1008
|
||||
|| reason === 'SANDBOX_NOT_BOUND'
|
||||
|| reason === 'SANDBOX_PAUSED'
|
||||
|| reason === 'TERMINAL_UNSUPPORTED'
|
||||
|| reason === 'IDLE_DISCONNECTED'
|
||||
|| reason === 'AUTH_REVOKED'
|
||||
|
|
@ -243,15 +250,16 @@ export function useSandboxTerminal(
|
|||
} else if (status.value === 'ready' || status.value === 'connecting') {
|
||||
status.value = 'error'
|
||||
}
|
||||
// idle / unauthorized:shell 还在沙箱里,PID 必须留下才能重挂。
|
||||
// idle / unauthorized / paused:shell 还在沙箱里,PID 必须留下才能重挂。
|
||||
// 沙箱没了或后端不支持:PID 已无效,清掉以免下次 Create 撞上死进程。
|
||||
if (status.value !== 'idle' && status.value !== 'unauthorized') {
|
||||
if (status.value !== 'idle' && status.value !== 'unauthorized' && status.value !== 'paused') {
|
||||
rememberPid(null)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (
|
||||
status.value !== 'needs_provision'
|
||||
&& status.value !== 'paused'
|
||||
&& status.value !== 'no_sandbox'
|
||||
&& status.value !== 'unsupported'
|
||||
&& status.value !== 'exited'
|
||||
|
|
@ -296,7 +304,7 @@ export function useSandboxTerminal(
|
|||
}
|
||||
case 'error': {
|
||||
status.value = statusFromErrorCode(frame.code, allowProvision)
|
||||
if (status.value !== 'idle' && status.value !== 'unauthorized') {
|
||||
if (status.value !== 'idle' && status.value !== 'unauthorized' && status.value !== 'paused') {
|
||||
rememberPid(null)
|
||||
}
|
||||
break
|
||||
|
|
@ -351,6 +359,10 @@ export function useSandboxTerminal(
|
|||
clearReconnectTimer()
|
||||
allowProvision = options?.provision === true
|
||||
reconnectAttempt = 0
|
||||
const cols = options?.cols
|
||||
const rows = options?.rows
|
||||
pendingGeometry =
|
||||
cols && rows && cols > 0 && rows > 0 ? { cols, rows } : null
|
||||
void openSocket()
|
||||
},
|
||||
sendInput(data) {
|
||||
|
|
|
|||
|
|
@ -1272,7 +1272,7 @@ export default {
|
|||
allowPrivateEndpoints: 'Allow private cluster endpoints',
|
||||
allowPrivateEndpointsHint: 'Use for self-hosted private control planes. Link-local and cloud metadata addresses remain blocked.',
|
||||
howToBuildTemplate: 'Sandbox cluster setup and template guide',
|
||||
noEnvVars: 'No additional environment variables. Add only values required by skills.',
|
||||
noEnvVars: 'No additional environment variables.',
|
||||
fieldRequired: 'Required',
|
||||
cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox',
|
||||
cubeApiKeyWhere: 'How to enable auth on a self-hosted cluster',
|
||||
|
|
@ -1327,7 +1327,7 @@ export default {
|
|||
envVars: 'Environment variables',
|
||||
envKey: 'Name',
|
||||
envValue: 'Value',
|
||||
envVarsHint: 'Injected into every sandbox for this workspace. Values are encrypted at rest but visible to scripts running inside the sandbox.',
|
||||
envVarsHint: 'Injected into every sandbox created from this config. Values are encrypted at rest but visible to scripts inside the sandbox.\nInjected only when a sandbox is created; to inject on each run, add them on the Sandbox secrets page.',
|
||||
addRow: 'Add variable',
|
||||
removeRow: 'Remove',
|
||||
save: 'Save',
|
||||
|
|
@ -3412,6 +3412,7 @@ export default {
|
|||
artifactsEmpty: 'No generated files in this conversation yet.',
|
||||
desktopPlaceholder: 'Desktop visualization coming soon',
|
||||
notStarted: 'The terminal is not running yet. Starting it connects to this conversation\'s sandbox, creating or resuming one if none is available.',
|
||||
paused: 'This conversation\'s sandbox is paused. Starting the terminal resumes it.',
|
||||
start: 'Start terminal',
|
||||
connecting: 'Connecting to sandbox…',
|
||||
needsProvision: 'This conversation has no running sandbox. Creating one starts a new sandbox, billed according to your workspace configuration.',
|
||||
|
|
|
|||
|
|
@ -1272,7 +1272,7 @@ export default {
|
|||
allowPrivateEndpoints: 'プライベートクラスタエンドポイントを許可',
|
||||
allowPrivateEndpointsHint: 'セルフホストのプライベートコントロールプレーン向けです。リンクローカルアドレスとクラウドメタデータアドレスは引き続きブロックされます。',
|
||||
howToBuildTemplate: 'サンドボックスクラスタの構築とテンプレートのガイド',
|
||||
noEnvVars: '追加の環境変数はありません。スキルが必要とする値のみを追加してください。',
|
||||
noEnvVars: '追加の環境変数はありません。',
|
||||
fieldRequired: '必須',
|
||||
cubeApiKeyOptional: '任意。認証なしのセルフホストCubeSandboxでは空欄のままにしてください',
|
||||
cubeApiKeyWhere: 'セルフホストクラスタで認証を有効にする方法',
|
||||
|
|
@ -1327,7 +1327,7 @@ export default {
|
|||
envVars: '環境変数',
|
||||
envKey: '名前',
|
||||
envValue: '値',
|
||||
envVarsHint: 'このワークスペースのすべてのサンドボックスに注入されます。値は保存時に暗号化されますが、サンドボックス内で実行されるスクリプトからは参照できます。',
|
||||
envVarsHint: 'この設定から作成されるサンドボックスに注入されます。値は保存時に暗号化されますが、サンドボックス内のスクリプトからは参照できます。\n注入はサンドボックス作成時のみです。実行のたびに注入する場合は「サンドボックスのシークレット」ページで追加してください。',
|
||||
addRow: '変数を追加',
|
||||
removeRow: '削除',
|
||||
save: '保存',
|
||||
|
|
@ -3412,6 +3412,7 @@ export default {
|
|||
artifactsEmpty: 'この会話で生成されたファイルはまだありません',
|
||||
desktopPlaceholder: 'デスクトップの可視化は近日対応予定です',
|
||||
notStarted: 'ターミナルはまだ起動していません。起動するとこの会話のサンドボックスに接続し、存在しないか一時停止中の場合は作成または再開します。',
|
||||
paused: 'この会話のサンドボックスは一時停止中です。ターミナルを起動すると再開します。',
|
||||
start: 'ターミナルを起動',
|
||||
connecting: 'サンドボックスに接続中…',
|
||||
needsProvision: 'この会話には実行中のサンドボックスがありません。作成すると新しいサンドボックスが起動し、ワークスペースの設定に従って課金されます。',
|
||||
|
|
|
|||
|
|
@ -3463,6 +3463,7 @@ export default {
|
|||
artifactsEmpty: '이 대화에서 생성된 파일이 없습니다',
|
||||
desktopPlaceholder: '데스크톱 시각화는 곧 지원될 예정입니다',
|
||||
notStarted: '터미널이 아직 실행되지 않았습니다. 시작하면 이 대화의 샌드박스에 연결하며, 샌드박스가 없거나 일시 중지된 경우 생성하거나 다시 시작합니다.',
|
||||
paused: '이 대화의 샌드박스가 일시 중지되었습니다. 터미널을 시작하면 다시 시작됩니다.',
|
||||
start: '터미널 시작',
|
||||
connecting: '샌드박스에 연결하는 중…',
|
||||
needsProvision: '이 대화에는 실행 중인 샌드박스가 없습니다. 생성하고 시작하면 새 샌드박스가 만들어지며 워크스페이스 설정에 따라 요금이 부과됩니다.',
|
||||
|
|
@ -5397,7 +5398,7 @@ export default {
|
|||
allowPrivateEndpoints: 'Allow private cluster endpoints',
|
||||
allowPrivateEndpointsHint: 'Use for self-hosted private control planes. Link-local and cloud metadata addresses remain blocked.',
|
||||
howToBuildTemplate: 'Sandbox cluster setup and template guide',
|
||||
noEnvVars: 'No additional environment variables. Add only values required by skills.',
|
||||
noEnvVars: 'No additional environment variables.',
|
||||
fieldRequired: 'Required',
|
||||
cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox',
|
||||
cubeApiKeyWhere: '자체 호스팅 클러스터에서 인증을 켜는 방법',
|
||||
|
|
@ -5452,7 +5453,7 @@ export default {
|
|||
envVars: 'Environment variables',
|
||||
envKey: 'Name',
|
||||
envValue: 'Value',
|
||||
envVarsHint: 'Injected into every sandbox for this workspace. Values are encrypted at rest but visible to scripts running inside the sandbox.',
|
||||
envVarsHint: 'Injected into every sandbox created from this config. Values are encrypted at rest but visible to scripts inside the sandbox.\nInjected only when a sandbox is created; to inject on each run, add them on the Sandbox secrets page.',
|
||||
addRow: 'Add variable',
|
||||
removeRow: 'Remove',
|
||||
save: 'Save',
|
||||
|
|
|
|||
|
|
@ -3463,6 +3463,7 @@ export default {
|
|||
artifactsEmpty: 'В этом диалоге пока нет созданных файлов',
|
||||
desktopPlaceholder: 'Визуализация рабочего стола скоро появится',
|
||||
notStarted: 'Терминал ещё не запущен. Запуск подключит его к песочнице этого диалога, создав или возобновив её при необходимости.',
|
||||
paused: 'Песочница этого диалога приостановлена. Запуск терминала возобновит её.',
|
||||
start: 'Запустить терминал',
|
||||
connecting: 'Подключение к песочнице…',
|
||||
needsProvision: 'В этом диалоге нет работающей песочницы. Создание запустит новую песочницу — она тарифицируется согласно настройкам рабочего пространства.',
|
||||
|
|
@ -5397,7 +5398,7 @@ export default {
|
|||
allowPrivateEndpoints: 'Allow private cluster endpoints',
|
||||
allowPrivateEndpointsHint: 'Use for self-hosted private control planes. Link-local and cloud metadata addresses remain blocked.',
|
||||
howToBuildTemplate: 'Sandbox cluster setup and template guide',
|
||||
noEnvVars: 'No additional environment variables. Add only values required by skills.',
|
||||
noEnvVars: 'No additional environment variables.',
|
||||
fieldRequired: 'Required',
|
||||
cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox',
|
||||
cubeApiKeyWhere: 'Как включить аутентификацию в собственном кластере',
|
||||
|
|
@ -5452,7 +5453,7 @@ export default {
|
|||
envVars: 'Environment variables',
|
||||
envKey: 'Name',
|
||||
envValue: 'Value',
|
||||
envVarsHint: 'Injected into every sandbox for this workspace. Values are encrypted at rest but visible to scripts running inside the sandbox.',
|
||||
envVarsHint: 'Injected into every sandbox created from this config. Values are encrypted at rest but visible to scripts inside the sandbox.\nInjected only when a sandbox is created; to inject on each run, add them on the Sandbox secrets page.',
|
||||
addRow: 'Add variable',
|
||||
removeRow: 'Remove',
|
||||
save: 'Save',
|
||||
|
|
|
|||
|
|
@ -3465,6 +3465,7 @@ export default {
|
|||
artifactsEmpty: '本会话尚未生成可下载的文件',
|
||||
desktopPlaceholder: '桌面可视化即将支持',
|
||||
notStarted: '终端尚未启动。启动后会连接本会话的沙箱环境;若沙箱不存在或已暂停,将为你创建或唤醒它。',
|
||||
paused: '本会话的沙箱已暂停。启动终端会唤醒它。',
|
||||
start: '启动终端',
|
||||
connecting: '正在连接沙箱…',
|
||||
needsProvision: '本会话当前没有运行中的沙箱环境。创建并启动会新建一个沙箱,并按工作区配置计费。',
|
||||
|
|
@ -5399,7 +5400,7 @@ export default {
|
|||
allowPrivateEndpoints: '允许访问私网集群地址',
|
||||
allowPrivateEndpointsHint: '仅用于自建 Cube 等私网控制面;云元数据等链路本地地址始终禁止访问。',
|
||||
howToBuildTemplate: '沙箱集群搭建与模板说明',
|
||||
noEnvVars: '暂无额外环境变量,仅添加技能确实需要的值。',
|
||||
noEnvVars: '暂无额外环境变量。',
|
||||
fieldRequired: '必填',
|
||||
cubeApiKeyOptional: '可留空 —— 自建 CubeSandbox 通常无鉴权',
|
||||
cubeApiKeyWhere: '自建集群如何开启鉴权',
|
||||
|
|
@ -5454,7 +5455,7 @@ export default {
|
|||
envVars: '环境变量',
|
||||
envKey: '变量名',
|
||||
envValue: '变量值',
|
||||
envVarsHint: '注入到该空间所有沙箱;值加密存储,但对沙箱内脚本可见,请勿放入脚本不应读取的密钥。',
|
||||
envVarsHint: '注入到该配置下所有沙箱;值加密存储,但对沙箱内脚本可见。\n只会在沙箱创建时注入,如果要实时注入请在「沙箱密钥」页面添加。',
|
||||
addRow: '添加变量',
|
||||
removeRow: '删除',
|
||||
save: '保存',
|
||||
|
|
|
|||
|
|
@ -0,0 +1,13 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { xtermBufferLooksEmpty } from './ptyPromptNudge'
|
||||
|
||||
test('xtermBufferLooksEmpty is true when every visible row is blank', () => {
|
||||
const rows = ['', ' ', '\t']
|
||||
assert.equal(xtermBufferLooksEmpty((i) => rows[i], rows.length), true)
|
||||
})
|
||||
|
||||
test('xtermBufferLooksEmpty is false when any row has text', () => {
|
||||
const rows = ['', 'root@host:workspace#']
|
||||
assert.equal(xtermBufferLooksEmpty((i) => rows[i], rows.length), false)
|
||||
})
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
/** Wait for in-flight PTY bytes before deciding the screen is empty. */
|
||||
export const PTY_PROMPT_NUDGE_DELAY_MS = 120
|
||||
|
||||
export function xtermBufferLooksEmpty(
|
||||
getLine: (row: number) => string | undefined,
|
||||
rows: number,
|
||||
): boolean {
|
||||
for (let i = 0; i < rows; i++) {
|
||||
if ((getLine(i) ?? '').trim() !== '') return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const terminal = readFileSync(new URL('./SandboxTerminal.vue', import.meta.url), 'utf8')
|
||||
const theme = readFileSync(new URL('../../../assets/theme/theme.css', import.meta.url), 'utf8')
|
||||
const promptUrl = new URL('../../../../../docker/sandbox-pty-prompt.sh', import.meta.url)
|
||||
const prompt = readFileSync(promptUrl, 'utf8')
|
||||
const promptPath = fileURLToPath(promptUrl)
|
||||
|
||||
test('xterm palette keeps prompt green but ls directories blue', () => {
|
||||
assert.match(theme, /--td-brand-color-4: #07c05f/)
|
||||
assert.match(terminal, /brightGreen: '#07c05f'/)
|
||||
assert.match(terminal, /brightBlue: '#729fcf'/)
|
||||
assert.doesNotMatch(terminal, /brightBlue: '#07c05f'/)
|
||||
assert.match(terminal, /brightCyan: '#34e2e2'/)
|
||||
assert.doesNotMatch(terminal, /brightCyan: '#08dd6e'/)
|
||||
assert.match(prompt, /\\033\[01;32m/)
|
||||
assert.match(prompt, /\\033\[01;34m/)
|
||||
assert.doesNotMatch(prompt, /\\033\[01;31m/)
|
||||
assert.match(prompt, /\]\\W\\\[/)
|
||||
assert.doesNotMatch(prompt, /\]\\w\\\[/)
|
||||
})
|
||||
|
||||
test('PTY output attaches after the first fit so FitAddon cannot wipe the prompt', () => {
|
||||
const start = terminal.indexOf('function mountTerminal')
|
||||
const end = terminal.indexOf('function unmountTerminal')
|
||||
assert.ok(start >= 0 && end > start)
|
||||
const mount = terminal.slice(start, end)
|
||||
const fitAt = mount.indexOf('applyFit()')
|
||||
const outputAt = mount.indexOf('terminal.onOutput')
|
||||
assert.ok(fitAt >= 0, 'mountTerminal must fit xterm')
|
||||
assert.ok(outputAt >= 0, 'mountTerminal must attach PTY output')
|
||||
assert.ok(
|
||||
fitAt < outputAt,
|
||||
'FitAddon.fit() clears the renderer when cols/rows change; flushing the buffered prompt before that fit leaves an empty cursor until the next keystroke',
|
||||
)
|
||||
assert.match(terminal, /xterm\.refresh\(0,\s*xterm\.rows\s*-\s*1\)/)
|
||||
})
|
||||
|
||||
test('empty PTY screen is nudged with SIGWINCH, not keystrokes', () => {
|
||||
assert.match(terminal, /schedulePromptNudge/)
|
||||
assert.match(terminal, /estimatePtySize/)
|
||||
assert.match(terminal, /resize\(cols,\s*rows\s*-\s*1\)/)
|
||||
assert.doesNotMatch(terminal, /sendInput\(PTY_PROMPT_NUDGE\)/)
|
||||
assert.doesNotMatch(terminal, /sendInput\('\\x0c'\)/)
|
||||
assert.doesNotMatch(terminal, /sendInput\('\\r'\)/)
|
||||
})
|
||||
|
||||
test('panel open looks up a running sandbox and only provisions on an explicit click', () => {
|
||||
assert.match(terminal, /connectLookup/)
|
||||
assert.match(terminal, /onMounted\(\(\) => \{\s*connectLookup\(\)/)
|
||||
assert.match(terminal, /connect\(\{ provision: false/)
|
||||
assert.match(terminal, /connect\(\{ provision: true/)
|
||||
assert.match(terminal, /status === 'paused'/)
|
||||
assert.match(terminal, /chat\.sandbox\.paused/)
|
||||
assert.doesNotMatch(terminal, /not_started/)
|
||||
})
|
||||
|
||||
test('interactive bash defines Debian-style ls aliases', () => {
|
||||
const out = execFileSync('bash', [
|
||||
'--norc',
|
||||
'--noprofile',
|
||||
'-ic',
|
||||
`. '${promptPath}'; alias ll; alias la; alias l; alias ls; alias grep`,
|
||||
], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
|
||||
assert.match(out, /alias ll='ls -alF'/)
|
||||
assert.match(out, /alias la='ls -A'/)
|
||||
assert.match(out, /alias l='ls -CF'/)
|
||||
assert.match(out, /alias ls='ls --color=auto'/)
|
||||
assert.match(out, /alias grep='grep --color=auto'/)
|
||||
})
|
||||
|
||||
test('interactive prompt script does not export PS1 or PROMPT_COMMAND', () => {
|
||||
assert.doesNotMatch(prompt, /export PS1/)
|
||||
assert.doesNotMatch(prompt, /export PROMPT_COMMAND/)
|
||||
})
|
||||
|
|
@ -6,7 +6,7 @@
|
|||
<t-icon v-if="status === 'connecting'" name="loading" size="24px"
|
||||
class="sandbox-terminal__spinner" />
|
||||
<t-icon
|
||||
v-else-if="status === 'not_started' || status === 'needs_provision' || status === 'no_sandbox'"
|
||||
v-else-if="status === 'paused' || status === 'needs_provision' || status === 'no_sandbox'"
|
||||
name="terminal" size="28px" />
|
||||
<t-icon v-else-if="status === 'unsupported'" name="error-circle" size="28px" />
|
||||
<t-icon v-else-if="status === 'idle'" name="time" size="28px" />
|
||||
|
|
@ -24,7 +24,7 @@
|
|||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, ref, toRef, watch } from 'vue';
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, toRef, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Terminal } from '@xterm/xterm';
|
||||
import { FitAddon } from '@xterm/addon-fit';
|
||||
|
|
@ -32,6 +32,10 @@ import '@xterm/xterm/css/xterm.css';
|
|||
import { useSandboxTerminal, type SandboxTerminalStatus } from '@/composables/useSandboxTerminal';
|
||||
import { useTheme } from '@/composables/useTheme';
|
||||
import { createPtyEchoPredictor } from '@/utils/ptyEchoPredictor';
|
||||
import {
|
||||
PTY_PROMPT_NUDGE_DELAY_MS,
|
||||
xtermBufferLooksEmpty,
|
||||
} from '@/utils/ptyPromptNudge';
|
||||
|
||||
const props = defineProps<{
|
||||
sessionId: string;
|
||||
|
|
@ -68,6 +72,10 @@ const onSystemThemeChange = (event: MediaQueryListEvent) => {
|
|||
};
|
||||
prefersDark?.addEventListener('change', onSystemThemeChange);
|
||||
|
||||
// ANSI palette: ls --color uses the usual dircolors mapping (dir=blue,
|
||||
// exec=green, link=cyan). Only the green slots stay WeKnora brand so
|
||||
// user@host (01;32) matches the product color; path (01;34) stays blue
|
||||
// like directories.
|
||||
function xtermTheme(dark: boolean) {
|
||||
return dark
|
||||
? {
|
||||
|
|
@ -76,6 +84,18 @@ function xtermTheme(dark: boolean) {
|
|||
cursor: '#e6e6e6',
|
||||
cursorAccent: '#1a1a1a',
|
||||
selectionBackground: '#3a3a3a',
|
||||
red: '#c64751',
|
||||
brightRed: '#de6670',
|
||||
green: '#06b04d',
|
||||
brightGreen: '#07c05f',
|
||||
yellow: '#c4a000',
|
||||
brightYellow: '#fce94f',
|
||||
blue: '#3465a4',
|
||||
brightBlue: '#729fcf',
|
||||
magenta: '#75507b',
|
||||
brightMagenta: '#ad7fa8',
|
||||
cyan: '#06989a',
|
||||
brightCyan: '#34e2e2',
|
||||
}
|
||||
: {
|
||||
background: '#ffffff',
|
||||
|
|
@ -83,6 +103,18 @@ function xtermTheme(dark: boolean) {
|
|||
cursor: '#242424',
|
||||
cursorAccent: '#ffffff',
|
||||
selectionBackground: '#d0d7de',
|
||||
red: '#e34d59',
|
||||
brightRed: '#f36d78',
|
||||
green: '#06b04d',
|
||||
brightGreen: '#07c05f',
|
||||
yellow: '#c4a000',
|
||||
brightYellow: '#c4a000',
|
||||
blue: '#3465a4',
|
||||
brightBlue: '#729fcf',
|
||||
magenta: '#75507b',
|
||||
brightMagenta: '#ad7fa8',
|
||||
cyan: '#06989a',
|
||||
brightCyan: '#34e2e2',
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -97,8 +129,8 @@ const { status } = terminal;
|
|||
|
||||
const statusText = computed(() => {
|
||||
switch (status.value as SandboxTerminalStatus) {
|
||||
case 'not_started':
|
||||
return t('chat.sandbox.notStarted');
|
||||
case 'paused':
|
||||
return t('chat.sandbox.paused');
|
||||
case 'connecting':
|
||||
return t('chat.sandbox.connecting');
|
||||
case 'needs_provision':
|
||||
|
|
@ -118,11 +150,11 @@ const statusText = computed(() => {
|
|||
}
|
||||
});
|
||||
|
||||
// 覆盖层上那颗按钮的文案;空串表示这个状态没有可执行的动作。
|
||||
// 每次点击都视为"用户确认",因此允许后端创建或唤醒沙箱——面板本身永远不会。
|
||||
// 覆盖层按钮:暂停用「启动终端」,尚未创建用「创建并启动」。点击才允许
|
||||
// 创建或唤醒;打开面板时的 lookup 不会做这两件事。
|
||||
const actionLabel = computed(() => {
|
||||
switch (status.value as SandboxTerminalStatus) {
|
||||
case 'not_started':
|
||||
case 'paused':
|
||||
return t('chat.sandbox.start');
|
||||
case 'needs_provision':
|
||||
return t('chat.sandbox.createAndStart');
|
||||
|
|
@ -145,6 +177,7 @@ let fitAddon: FitAddon | null = null;
|
|||
let echo: ReturnType<typeof createPtyEchoPredictor> | null = null;
|
||||
let resizeObserver: ResizeObserver | null = null;
|
||||
let resizeDebounce: ReturnType<typeof setTimeout> | null = null;
|
||||
let promptNudgeTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let unmounted = false;
|
||||
|
||||
function writeToXterm(chunk: string | Uint8Array) {
|
||||
|
|
@ -175,28 +208,19 @@ function mountTerminal() {
|
|||
echo?.onLocal(data);
|
||||
terminal.sendInput(data);
|
||||
});
|
||||
// 必须在 connect 之后、但在有输出要展示时注册;composable 会先冲出缓冲的提示符。
|
||||
terminal.onOutput((data) => echo?.onRemote(data));
|
||||
|
||||
resizeObserver = new ResizeObserver(() => {
|
||||
if (resizeDebounce) clearTimeout(resizeDebounce);
|
||||
resizeDebounce = setTimeout(() => {
|
||||
if (!fitAddon || !xterm) return;
|
||||
try {
|
||||
fitAddon.fit();
|
||||
terminal.resize(xterm.cols, xterm.rows);
|
||||
} catch {
|
||||
// fit 在容器尺寸为 0 时会抛错,忽略即可。
|
||||
}
|
||||
}, 100);
|
||||
resizeDebounce = setTimeout(() => applyFit(), 100);
|
||||
});
|
||||
resizeObserver.observe(containerRef.value || terminalHost.value);
|
||||
try {
|
||||
fitAddon.fit();
|
||||
} catch {
|
||||
// 首帧布局未就绪时忽略。
|
||||
}
|
||||
terminal.resize(xterm.cols, xterm.rows);
|
||||
// Fit BEFORE flushing buffered PTY bytes. FitAddon.fit() calls
|
||||
// _renderService.clear() when the default 80x24 becomes the panel size,
|
||||
// which would wipe a prompt painted a moment earlier and leave only the
|
||||
// cursor until the next keystroke.
|
||||
applyFit();
|
||||
terminal.onOutput((data) => echo?.onRemote(data));
|
||||
schedulePromptNudge();
|
||||
void nextTick(() => {
|
||||
requestAnimationFrame(() => fitAndFocus());
|
||||
});
|
||||
|
|
@ -209,18 +233,31 @@ function unmountTerminal() {
|
|||
resizeObserver = null;
|
||||
if (resizeDebounce) clearTimeout(resizeDebounce);
|
||||
resizeDebounce = null;
|
||||
if (promptNudgeTimer) clearTimeout(promptNudgeTimer);
|
||||
promptNudgeTimer = null;
|
||||
xterm?.dispose();
|
||||
xterm = null;
|
||||
fitAddon = null;
|
||||
}
|
||||
|
||||
// 覆盖层上唯一的连接入口。provision: true 表示这是用户的显式确认,允许后端
|
||||
// 创建或唤醒沙箱;组件挂载本身不连接,所以打开面板不会产生任何计费副作用。
|
||||
// 覆盖层上唯一会创建或唤醒沙箱的入口。provision: true 表示这是用户的显式
|
||||
// 确认。组件挂载只做 lookup:运行中的沙箱直接连上,暂停或尚未创建才停在
|
||||
// 覆盖层等点击。
|
||||
function start() {
|
||||
unmountTerminal();
|
||||
terminal.connect({ provision: true });
|
||||
const { cols, rows } = estimatePtySize();
|
||||
terminal.connect({ provision: true, cols, rows });
|
||||
}
|
||||
|
||||
function connectLookup() {
|
||||
const { cols, rows } = estimatePtySize();
|
||||
terminal.connect({ provision: false, cols, rows });
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
connectLookup();
|
||||
});
|
||||
|
||||
watch(isDarkTheme, (dark) => {
|
||||
if (xterm) xterm.options.theme = xtermTheme(dark);
|
||||
});
|
||||
|
|
@ -250,13 +287,56 @@ onBeforeUnmount(() => {
|
|||
unmountTerminal();
|
||||
});
|
||||
|
||||
function fitAndFocus() {
|
||||
function estimatePtySize() {
|
||||
const el = containerRef.value;
|
||||
const width = Math.max(0, (el?.clientWidth ?? 0) - 16);
|
||||
const height = Math.max(0, (el?.clientHeight ?? 0) - 16);
|
||||
return {
|
||||
cols: Math.max(20, Math.floor(width / 8) || 80),
|
||||
rows: Math.max(8, Math.floor(height / 17) || 24),
|
||||
};
|
||||
}
|
||||
|
||||
function xtermVisibleBufferEmpty(): boolean {
|
||||
if (!xterm) return true;
|
||||
const buf = xterm.buffer.active;
|
||||
const origin = buf.viewportY;
|
||||
return xtermBufferLooksEmpty(
|
||||
(row) => buf.getLine(origin + row)?.translateToString(true),
|
||||
xterm.rows,
|
||||
);
|
||||
}
|
||||
|
||||
// Pty.Connect does not replay a prompt bash already printed. A same-size
|
||||
// resize is a no-op; flipping rows by 1 sends SIGWINCH so readline (and
|
||||
// TUIs) redraw. Do not inject Ctrl-L or Enter: that would go to whatever
|
||||
// is running in a reattached PTY.
|
||||
function schedulePromptNudge() {
|
||||
if (promptNudgeTimer) clearTimeout(promptNudgeTimer);
|
||||
promptNudgeTimer = setTimeout(() => {
|
||||
promptNudgeTimer = null;
|
||||
if (unmounted || !xterm || status.value !== 'ready') return;
|
||||
if (!xtermVisibleBufferEmpty()) return;
|
||||
const cols = Math.max(2, xterm.cols);
|
||||
const rows = Math.max(2, xterm.rows);
|
||||
terminal.resize(cols, rows - 1);
|
||||
terminal.resize(cols, rows);
|
||||
}, PTY_PROMPT_NUDGE_DELAY_MS);
|
||||
}
|
||||
|
||||
function applyFit() {
|
||||
if (!xterm) return;
|
||||
try {
|
||||
fitAddon?.fit();
|
||||
} catch {
|
||||
// 容器尚未完成布局时忽略。
|
||||
// fit 在容器尺寸为 0 时会抛错,忽略即可。
|
||||
}
|
||||
if (xterm) terminal.resize(xterm.cols, xterm.rows);
|
||||
terminal.resize(xterm.cols, xterm.rows);
|
||||
xterm.refresh(0, xterm.rows - 1);
|
||||
}
|
||||
|
||||
function fitAndFocus() {
|
||||
applyFit();
|
||||
xterm?.focus();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -54,17 +54,21 @@ func NewSandboxTerminalService(
|
|||
}
|
||||
|
||||
// OpenSessionTerminal attaches to the session's currently bound sandbox
|
||||
// without ever creating or rebuilding one. This is the path a page load and
|
||||
// an automatic reconnect take: opening a panel must not conjure a microVM.
|
||||
// without ever creating or resuming one. This is the path a panel open and
|
||||
// an automatic reconnect take: a running sandbox is attached, a bound
|
||||
// sandbox that is not confirmed running reports ErrSandboxPaused, and a
|
||||
// missing one reports ErrNoLiveSessionSandbox. Opening a panel must not
|
||||
// conjure or wake a microVM.
|
||||
//
|
||||
// When the session has no live sandbox it reports
|
||||
// sandbox.ErrNoLiveSessionSandbox, which the WebSocket handler turns into
|
||||
// the SANDBOX_NOT_BOUND frame the UI answers with an explicit "create and
|
||||
// start" button. That confirmed click is what calls EnsureSessionTerminal.
|
||||
// The WebSocket handler turns those errors into SANDBOX_PAUSED /
|
||||
// SANDBOX_NOT_BOUND frames the UI answers with an explicit button. That
|
||||
// confirmed click is what calls EnsureSessionTerminal.
|
||||
//
|
||||
// Error contract (the WebSocket handler maps these onto protocol error
|
||||
// frames):
|
||||
// - sandbox.ErrNoLiveSessionSandbox — the session has no bound sandbox.
|
||||
// - sandbox.ErrSandboxPaused — the bound sandbox is paused; resume needs
|
||||
// an explicit click (EnsureSessionTerminal with AllowResume).
|
||||
// - ErrTerminalUnsupported — the resolved backend cannot stream PTYs
|
||||
// (Docker, disabled manager).
|
||||
// - any other error — resolution or provider failure.
|
||||
|
|
@ -73,6 +77,7 @@ func (s *SandboxTerminalService) OpenSessionTerminal(
|
|||
sessionID string,
|
||||
opts sandbox.RemoteTerminalOptions,
|
||||
) (*SessionTerminal, error) {
|
||||
opts.AllowResume = false
|
||||
mgr, _, err := s.resolveSessionManager(ctx, sessionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
@ -134,6 +139,7 @@ func (s *SandboxTerminalService) EnsureSessionTerminal(
|
|||
sandboxConfigID string,
|
||||
opts sandbox.RemoteTerminalOptions,
|
||||
) (*SessionTerminal, error) {
|
||||
opts.AllowResume = true
|
||||
mgr, _, err := s.resolveSessionManager(ctx, sessionID)
|
||||
if err == nil {
|
||||
terminal, terr := s.openOnManager(ctx, mgr, sessionID, opts)
|
||||
|
|
@ -141,9 +147,9 @@ func (s *SandboxTerminalService) EnsureSessionTerminal(
|
|||
return terminal, nil
|
||||
}
|
||||
// The pin names the config but the sandbox itself is gone
|
||||
// (reclaimed or paused out of band). The config context is right
|
||||
// here, so rebuild on it instead of treating the session as
|
||||
// sandbox-less and asking the caller for an agent.
|
||||
// (reclaimed out of band). Resume of a paused instance already
|
||||
// happened above via AllowResume. Rebuild only when there is
|
||||
// nothing left to connect to.
|
||||
if errors.Is(terr, sandbox.ErrNoLiveSessionSandbox) {
|
||||
if perr := s.provisionOnManager(ctx, mgr, sessionID); perr == nil {
|
||||
if terminal, retryErr := s.openOnManager(ctx, mgr, sessionID, opts); retryErr == nil {
|
||||
|
|
|
|||
|
|
@ -5,6 +5,9 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
"github.com/Tencent/WeKnora/internal/sandbox"
|
||||
)
|
||||
|
||||
func TestTerminalIdleExpired(t *testing.T) {
|
||||
|
|
@ -48,3 +51,16 @@ func TestTerminalAuthRecheckInterval(t *testing.T) {
|
|||
require.LessOrEqual(t, terminalAuthRecheckInterval, 2*time.Minute)
|
||||
require.Equal(t, "AUTH_REVOKED", terminalErrAuth)
|
||||
}
|
||||
|
||||
func TestTerminalErrorFrame(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
code, _ := terminalErrorFrame(sandbox.ErrNoLiveSessionSandbox)
|
||||
require.Equal(t, terminalErrNotBound, code)
|
||||
|
||||
code, _ = terminalErrorFrame(sandbox.ErrSandboxPaused)
|
||||
require.Equal(t, terminalErrPaused, code)
|
||||
|
||||
code, _ = terminalErrorFrame(service.ErrTerminalUnsupported)
|
||||
require.Equal(t, terminalErrUnsupported, code)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -70,6 +70,7 @@ var terminalAuthRecheckInterval = time.Minute
|
|||
// Protocol error codes sent as HTTP close reasons and on error frames.
|
||||
const (
|
||||
terminalErrNotBound = "SANDBOX_NOT_BOUND"
|
||||
terminalErrPaused = "SANDBOX_PAUSED"
|
||||
terminalErrUnsupported = "TERMINAL_UNSUPPORTED"
|
||||
terminalErrInternal = "INTERNAL"
|
||||
terminalErrIdle = "IDLE_DISCONNECTED"
|
||||
|
|
@ -196,9 +197,10 @@ func (h *Handler) SandboxTerminalWS(c *gin.Context) {
|
|||
|
||||
// Provisioning is opt-in per connect, because it creates (or resumes and
|
||||
// re-bills) a microVM and this is a GET. A bare handshake — panel opened,
|
||||
// tab restored, background reconnect — stays lookup-only and reports
|
||||
// SANDBOX_NOT_BOUND, which the UI turns into an explicit "create and
|
||||
// start" button. Only that confirmed click sets provision=1.
|
||||
// tab restored, background reconnect — stays lookup-only: a running
|
||||
// sandbox is attached, a paused one reports SANDBOX_PAUSED, and a
|
||||
// missing one reports SANDBOX_NOT_BOUND. Only a confirmed click sets
|
||||
// provision=1, which may create or resume.
|
||||
allowProvision := terminalFlagParam(c.Query("provision"))
|
||||
sandboxConfigID := h.terminalProvisionConfigID(ctx, c, allowProvision)
|
||||
|
||||
|
|
@ -383,6 +385,8 @@ func terminalErrorFrame(err error) (code, message string) {
|
|||
switch {
|
||||
case stderrors.Is(err, sandbox.ErrNoLiveSessionSandbox):
|
||||
return terminalErrNotBound, "session has no live sandbox"
|
||||
case stderrors.Is(err, sandbox.ErrSandboxPaused):
|
||||
return terminalErrPaused, "session sandbox is paused"
|
||||
case stderrors.Is(err, service.ErrTerminalUnsupported):
|
||||
return terminalErrUnsupported, "sandbox backend does not support terminals"
|
||||
default:
|
||||
|
|
|
|||
|
|
@ -135,8 +135,11 @@ type SessionTerminalManager interface {
|
|||
// and opens a PTY. It is lookup-only: when no live sandbox is bound it
|
||||
// returns ErrNoLiveSessionSandbox instead of provisioning one, because
|
||||
// the terminal entry point lacks the agent's config-pin context and
|
||||
// must not create microVMs as a side effect. A backend that cannot
|
||||
// stream PTYs returns ErrTerminalUnsupported, not "no sandbox".
|
||||
// must not create microVMs as a side effect. A bound sandbox that is
|
||||
// not confirmed running returns ErrSandboxPaused unless opts.AllowResume
|
||||
// is set, so a panel open cannot silently resume (and re-bill) a paused
|
||||
// instance. A backend that cannot stream PTYs returns
|
||||
// ErrTerminalUnsupported, not "no sandbox".
|
||||
OpenSessionTerminal(ctx context.Context, sessionID string, opts RemoteTerminalOptions) (RemoteTerminalSession, error)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -396,8 +396,17 @@ func (c *E2BRemoteClient) DeleteSupersededStandardTemplates(ctx context.Context,
|
|||
return nil
|
||||
}
|
||||
|
||||
// e2bPtyPromptOverrideCmd re-sources the image prompt after E2B's
|
||||
// template provisioner appends `PS1='\w $ '` to bashrc. Harmless if the
|
||||
// image already sources /etc/weknora/pty-prompt.sh (PROMPT_COMMAND wins
|
||||
// either way); required when rebuilding from an older image that does not.
|
||||
const e2bPtyPromptOverrideCmd = `. /etc/weknora/pty-prompt.sh 2>/dev/null; ` +
|
||||
`for f in /root/.bashrc /home/user/.bashrc /etc/profile.d/zz-weknora-prompt.sh; do ` +
|
||||
`grep -q /etc/weknora/pty-prompt.sh "$f" 2>/dev/null || echo '. /etc/weknora/pty-prompt.sh' >> "$f"; ` +
|
||||
`done`
|
||||
|
||||
func (c *E2BRemoteClient) buildStandardTemplate(ctx context.Context) (*RemoteTemplate, error) {
|
||||
builder := e2b.NewTemplate().FromImage(DefaultDockerImage)
|
||||
builder := e2b.NewTemplate().FromImage(DefaultDockerImage).RunCmd(e2bPtyPromptOverrideCmd)
|
||||
build, err := builder.BuildInBackground(ctx, c.client, e2b.BuildConfig{
|
||||
Name: StandardTemplateName,
|
||||
// Creating a sandbox from a plain template name or ID resolves the
|
||||
|
|
|
|||
|
|
@ -755,6 +755,49 @@ func TestE2BRemoteClientListTemplatesIgnoresSpawnCount(t *testing.T) {
|
|||
require.Equal(t, "waiting", templates[0].Status)
|
||||
}
|
||||
|
||||
func TestE2BBuildStandardTemplateOverridesPtyPrompt(t *testing.T) {
|
||||
var startBody struct {
|
||||
FromImage string `json:"fromImage"`
|
||||
Steps []struct {
|
||||
Type string `json:"type"`
|
||||
Args []string `json:"args"`
|
||||
} `json:"steps"`
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/templates":
|
||||
writeJSON(w, http.StatusOK, []map[string]any{})
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/v3/templates":
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{
|
||||
"templateID": "tpl-new",
|
||||
"buildID": "build-new",
|
||||
"names": []string{StandardTemplateName},
|
||||
})
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/v2/templates/tpl-new/builds/build-new":
|
||||
require.NoError(t, json.NewDecoder(r.Body).Decode(&startBody))
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
client, err := NewE2BRemoteClient(&Config{
|
||||
E2BAPIKey: "key-test",
|
||||
E2BAPIURL: server.URL,
|
||||
E2BSandboxTTL: time.Minute,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
got, err := client.EnsureStandardTemplate(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "tpl-new", got.ID)
|
||||
require.Equal(t, DefaultDockerImage, startBody.FromImage)
|
||||
require.NotEmpty(t, startBody.Steps)
|
||||
require.Equal(t, "run", startBody.Steps[0].Type)
|
||||
require.Equal(t, e2bPtyPromptOverrideCmd, startBody.Steps[0].Args[0])
|
||||
}
|
||||
|
||||
func TestNormalizeE2BTemplateBuildStatus(t *testing.T) {
|
||||
tests := map[string]string{
|
||||
"READY": "ready",
|
||||
|
|
|
|||
|
|
@ -111,6 +111,13 @@ var (
|
|||
// Unlike Execute, these entry points never provision: creating a sandbox
|
||||
// needs the agent's config-pin context, which they do not carry.
|
||||
ErrNoLiveSessionSandbox = errors.New("session has no live sandbox")
|
||||
// ErrSandboxPaused is returned by lookup-only terminal opens when the
|
||||
// session has a bound sandbox that is not confirmed running (paused,
|
||||
// transitioning, or missing from the provider list). Connect would
|
||||
// resume a paused instance and start billing again; the UI must get
|
||||
// an explicit click first. Distinct from ErrNoLiveSessionSandbox,
|
||||
// which means there is no binding to resume.
|
||||
ErrSandboxPaused = errors.New("session sandbox is paused")
|
||||
// ErrTerminalUnsupported is returned when the active backend cannot
|
||||
// stream PTYs (Docker, a disabled manager). Distinct from
|
||||
// ErrNoLiveSessionSandbox: the session may well have a live sandbox,
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ import (
|
|||
"fmt"
|
||||
"log"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
|
@ -837,7 +838,9 @@ func (m *SessionBoundManager) SessionTerminalManager() SessionTerminalManager {
|
|||
// session. It is strictly lookup-only: with no live binding it returns
|
||||
// ErrNoLiveSessionSandbox instead of provisioning, because the terminal
|
||||
// entry point lacks the config-pin context that agent-driven creation
|
||||
// relies on. A backend that cannot stream PTYs (Docker) returns
|
||||
// relies on. A bound sandbox that is not confirmed running returns
|
||||
// ErrSandboxPaused unless opts.AllowResume is set — Connect would wake a
|
||||
// paused instance. A backend that cannot stream PTYs (Docker) returns
|
||||
// ErrTerminalUnsupported, not "no sandbox".
|
||||
func (m *SessionBoundManager) OpenSessionTerminal(
|
||||
ctx context.Context,
|
||||
|
|
@ -848,6 +851,21 @@ func (m *SessionBoundManager) OpenSessionTerminal(
|
|||
if !ok {
|
||||
return nil, ErrTerminalUnsupported
|
||||
}
|
||||
if !opts.AllowResume {
|
||||
state, bound, err := m.peekBoundSandboxState(ctx, sessionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !bound {
|
||||
return nil, ErrNoLiveSessionSandbox
|
||||
}
|
||||
// Only a List-confirmed running sandbox is safe to Connect:
|
||||
// paused/transitioning Connect resumes (and re-bills), and a
|
||||
// list miss with a stale binding is not "no sandbox".
|
||||
if state != RemoteStateRunning {
|
||||
return nil, ErrSandboxPaused
|
||||
}
|
||||
}
|
||||
handle, found, err := m.lookupSessionHandle(ctx, sessionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
@ -930,6 +948,54 @@ func (m *SessionBoundManager) resolveSession(
|
|||
return m.lifecycle.Resolve(ctx, key)
|
||||
}
|
||||
|
||||
// peekBoundSandboxState reads provider listing for the bound sandbox without
|
||||
// Connect. The bool is "a binding exists for this provider", not "List
|
||||
// returned a row": a list miss still reports bound so lookup cannot pretend
|
||||
// the session has no sandbox. E2B/Cube Connect resumes a paused instance,
|
||||
// so the lookup-only terminal path must List first.
|
||||
func (m *SessionBoundManager) peekBoundSandboxState(
|
||||
ctx context.Context,
|
||||
sessionID string,
|
||||
) (RemoteSandboxState, bool, error) {
|
||||
if m.remoteDisabled() || strings.TrimSpace(sessionID) == "" {
|
||||
return "", false, nil
|
||||
}
|
||||
key, err := m.sessionKey(ctx, sessionID)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
binding, err := m.bindings.Get(ctx, key)
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("sandbox: read session binding: %w", err)
|
||||
}
|
||||
if binding == nil || binding.Provider != m.client.Provider() {
|
||||
return "", false, nil
|
||||
}
|
||||
summaries, err := m.client.List(ctx, RemoteListFilter{
|
||||
Metadata: map[string]string{
|
||||
remoteMetadataTenantID: strconv.FormatUint(key.TenantID, 10),
|
||||
remoteMetadataSessionID: key.SessionID,
|
||||
},
|
||||
States: []RemoteSandboxState{
|
||||
RemoteStateRunning,
|
||||
RemoteStatePaused,
|
||||
RemoteStateTransitioning,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("sandbox: list session sandbox: %w", err)
|
||||
}
|
||||
for _, summary := range summaries {
|
||||
if summary.ID == binding.SandboxID {
|
||||
return summary.State, true, nil
|
||||
}
|
||||
}
|
||||
// Binding exists but the provider list did not return it (lag, metadata
|
||||
// mismatch, or a state outside the filter). That is not "no sandbox":
|
||||
// the UI should ask before Connect, which would resume a paused VM.
|
||||
return RemoteStateUnknown, true, nil
|
||||
}
|
||||
|
||||
// lookupSessionHandle reads the authoritative binding and, when one exists
|
||||
// with the current provider, connects to the remote sandbox without
|
||||
// allocating. Used by artifact / staging paths that must never provision.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,163 @@
|
|||
package sandbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
func newSessionManagerTerminalTestHarness(t *testing.T) (*SessionBoundManager, *terminalFakeClient) {
|
||||
t.Helper()
|
||||
|
||||
client := &terminalFakeClient{fakeRemoteClient: newFakeRemoteClient(SandboxTypeCube)}
|
||||
client.capabilities.SupportsTerminals = true
|
||||
cfg := DefaultConfig()
|
||||
cfg.CubeTemplate = "tpl-test"
|
||||
mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
|
||||
Config: cfg,
|
||||
Client: client,
|
||||
Store: NewMemorySessionSandboxBindingStore(),
|
||||
Checker: &fakeSessionExistenceChecker{exists: true},
|
||||
SkipHealthProbe: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return mgr, client
|
||||
}
|
||||
|
||||
func terminalTestContext() context.Context {
|
||||
return context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
|
||||
}
|
||||
|
||||
func pauseAllFakeSandboxes(t *testing.T, client *fakeRemoteClient) {
|
||||
t.Helper()
|
||||
client.mu.Lock()
|
||||
defer client.mu.Unlock()
|
||||
require.NotEmpty(t, client.sandboxes)
|
||||
for _, rec := range client.sandboxes {
|
||||
rec.state = RemoteStatePaused
|
||||
}
|
||||
}
|
||||
|
||||
func fakeConnectCount(t *testing.T, client *fakeRemoteClient) int {
|
||||
t.Helper()
|
||||
client.mu.Lock()
|
||||
defer client.mu.Unlock()
|
||||
return len(client.connectIDs)
|
||||
}
|
||||
|
||||
func fakeCreateCount(t *testing.T, client *fakeRemoteClient) int {
|
||||
t.Helper()
|
||||
client.mu.Lock()
|
||||
defer client.mu.Unlock()
|
||||
return client.createCount
|
||||
}
|
||||
|
||||
func setAllFakeSandboxState(t *testing.T, client *fakeRemoteClient, state RemoteSandboxState) {
|
||||
t.Helper()
|
||||
client.mu.Lock()
|
||||
defer client.mu.Unlock()
|
||||
require.NotEmpty(t, client.sandboxes)
|
||||
for _, rec := range client.sandboxes {
|
||||
rec.state = state
|
||||
rec.rawState = string(state)
|
||||
}
|
||||
}
|
||||
|
||||
func clearAllFakeSandboxMetadata(t *testing.T, client *fakeRemoteClient) {
|
||||
t.Helper()
|
||||
client.mu.Lock()
|
||||
defer client.mu.Unlock()
|
||||
require.NotEmpty(t, client.sandboxes)
|
||||
for _, rec := range client.sandboxes {
|
||||
rec.metadata = map[string]string{}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenSessionTerminalRefusesPausedSandboxWithoutResume(t *testing.T) {
|
||||
ctx := terminalTestContext()
|
||||
mgr, client := newSessionManagerTerminalTestHarness(t)
|
||||
|
||||
_, err := mgr.ExecShellCommand(ctx, "sess-1", "true", "", time.Second, nil)
|
||||
require.NoError(t, err)
|
||||
pauseAllFakeSandboxes(t, client.fakeRemoteClient)
|
||||
connectsBefore := fakeConnectCount(t, client.fakeRemoteClient)
|
||||
|
||||
_, err = mgr.OpenSessionTerminal(ctx, "sess-1", RemoteTerminalOptions{})
|
||||
require.ErrorIs(t, err, ErrSandboxPaused)
|
||||
require.Equal(t, connectsBefore, fakeConnectCount(t, client.fakeRemoteClient),
|
||||
"lookup-only open must List a paused sandbox instead of Connect, which would resume it")
|
||||
}
|
||||
|
||||
func TestOpenSessionTerminalResumesPausedSandboxWhenAllowed(t *testing.T) {
|
||||
ctx := terminalTestContext()
|
||||
mgr, client := newSessionManagerTerminalTestHarness(t)
|
||||
|
||||
_, err := mgr.ExecShellCommand(ctx, "sess-1", "true", "", time.Second, nil)
|
||||
require.NoError(t, err)
|
||||
pauseAllFakeSandboxes(t, client.fakeRemoteClient)
|
||||
connectsBefore := fakeConnectCount(t, client.fakeRemoteClient)
|
||||
|
||||
createsBefore := fakeCreateCount(t, client.fakeRemoteClient)
|
||||
session, err := mgr.OpenSessionTerminal(ctx, "sess-1", RemoteTerminalOptions{AllowResume: true})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, session)
|
||||
require.Greater(t, fakeConnectCount(t, client.fakeRemoteClient), connectsBefore)
|
||||
require.Equal(t, createsBefore, fakeCreateCount(t, client.fakeRemoteClient),
|
||||
"resuming a paused sandbox must Connect, not provision a replacement")
|
||||
}
|
||||
|
||||
func TestOpenSessionTerminalConnectsRunningSandbox(t *testing.T) {
|
||||
ctx := terminalTestContext()
|
||||
mgr, _ := newSessionManagerTerminalTestHarness(t)
|
||||
|
||||
_, err := mgr.ExecShellCommand(ctx, "sess-1", "true", "", time.Second, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
session, err := mgr.OpenSessionTerminal(ctx, "sess-1", RemoteTerminalOptions{})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, session)
|
||||
}
|
||||
|
||||
func TestOpenSessionTerminalNoBindingIsNotPaused(t *testing.T) {
|
||||
ctx := terminalTestContext()
|
||||
mgr, _ := newSessionManagerTerminalTestHarness(t)
|
||||
|
||||
_, err := mgr.OpenSessionTerminal(ctx, "sess-missing", RemoteTerminalOptions{})
|
||||
require.ErrorIs(t, err, ErrNoLiveSessionSandbox)
|
||||
require.NotErrorIs(t, err, ErrSandboxPaused)
|
||||
}
|
||||
|
||||
func TestOpenSessionTerminalRefusesTransitioningSandboxWithoutResume(t *testing.T) {
|
||||
ctx := terminalTestContext()
|
||||
mgr, client := newSessionManagerTerminalTestHarness(t)
|
||||
|
||||
_, err := mgr.ExecShellCommand(ctx, "sess-1", "true", "", time.Second, nil)
|
||||
require.NoError(t, err)
|
||||
setAllFakeSandboxState(t, client.fakeRemoteClient, RemoteStateTransitioning)
|
||||
connectsBefore := fakeConnectCount(t, client.fakeRemoteClient)
|
||||
|
||||
_, err = mgr.OpenSessionTerminal(ctx, "sess-1", RemoteTerminalOptions{})
|
||||
require.ErrorIs(t, err, ErrSandboxPaused)
|
||||
require.Equal(t, connectsBefore, fakeConnectCount(t, client.fakeRemoteClient),
|
||||
"pausing/resuming is Transitioning; lookup-only Connect would still resume")
|
||||
}
|
||||
|
||||
func TestOpenSessionTerminalListMissWithBindingIsPausedNotUnbound(t *testing.T) {
|
||||
ctx := terminalTestContext()
|
||||
mgr, client := newSessionManagerTerminalTestHarness(t)
|
||||
|
||||
_, err := mgr.ExecShellCommand(ctx, "sess-1", "true", "", time.Second, nil)
|
||||
require.NoError(t, err)
|
||||
clearAllFakeSandboxMetadata(t, client.fakeRemoteClient)
|
||||
connectsBefore := fakeConnectCount(t, client.fakeRemoteClient)
|
||||
|
||||
_, err = mgr.OpenSessionTerminal(ctx, "sess-1", RemoteTerminalOptions{})
|
||||
require.ErrorIs(t, err, ErrSandboxPaused)
|
||||
require.NotErrorIs(t, err, ErrNoLiveSessionSandbox)
|
||||
require.Equal(t, connectsBefore, fakeConnectCount(t, client.fakeRemoteClient),
|
||||
"a bound sandbox missing from List must not be reported as unbound")
|
||||
}
|
||||
|
|
@ -35,6 +35,12 @@ type RemoteTerminalOptions struct {
|
|||
// already-running PTY instead of creating a new shell. A failed
|
||||
// reattach falls back to Create.
|
||||
AttachPID uint32
|
||||
|
||||
// AllowResume lets OpenSessionTerminal Connect (and therefore wake) a
|
||||
// paused sandbox. Lookup-only opens leave this false so opening a
|
||||
// panel cannot resume a paused microVM; the confirmed-create path
|
||||
// sets it.
|
||||
AllowResume bool
|
||||
}
|
||||
|
||||
// RemoteTerminalEvent is one event on a terminal's output stream. The
|
||||
|
|
|
|||
Loading…
Reference in New Issue