@zhin.js/adapter-sandbox 1.1.20 → 1.1.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +64 -0
- package/README.md +55 -7
- package/adapters/sandbox/index.js +3 -12
- package/adapters/sandbox/index.ts +2 -12
- package/lib/adapter.d.ts +17 -0
- package/lib/adapter.js +17 -0
- package/lib/client.d.ts +7 -14
- package/lib/client.js +12 -11
- package/lib/endpoint.d.ts +16 -13
- package/lib/endpoint.js +171 -138
- package/lib/index.d.ts +2 -1
- package/lib/index.js +2 -1
- package/lib/protocol.d.ts +22 -1
- package/lib/protocol.js +34 -4
- package/package.json +17 -17
- package/pages/index/ConversationRecoveryPanel.js +131 -0
- package/pages/index/ConversationRecoveryPanel.tsx +134 -0
- package/pages/index/SandboxChat.js +319 -111
- package/pages/index/SandboxChat.tsx +356 -126
- package/pages/index/agentTrace.js +21 -10
- package/pages/index/agentTrace.ts +24 -10
- package/pages/index/conversationRecovery.js +40 -0
- package/pages/index/conversationRecovery.ts +68 -0
- package/pages/index/index.js +5 -5
- package/pages/index/index.tsx +5 -5
- package/pages/index/messages.js +24 -6
- package/pages/index/messages.ts +24 -6
- package/pages/index/playgroundState.js +51 -1
- package/pages/index/playgroundState.ts +61 -1
- package/pages/index/sandboxTransport.js +25 -0
- package/pages/index/sandboxTransport.ts +35 -0
- package/pages/index/useSandboxHistory.js +161 -0
- package/pages/index/useSandboxHistory.ts +164 -0
- package/pages/index/workspaceDirectory.js +49 -0
- package/pages/index/workspaceDirectory.ts +74 -0
- package/pages/index/workspaceDirectoryState.js +120 -0
- package/pages/index/workspaceDirectoryState.ts +124 -0
- package/src/adapter.ts +22 -0
- package/src/client.ts +16 -18
- package/src/endpoint.ts +179 -140
- package/src/index.ts +1 -1
- package/src/protocol.ts +59 -13
|
@@ -8,7 +8,9 @@ import {
|
|
|
8
8
|
pickMediaRawUrl,
|
|
9
9
|
type MessageSegment,
|
|
10
10
|
} from '@zhin.js/client';
|
|
11
|
-
import { buildSandboxWebSocketUrl } from './sandboxTransport';
|
|
11
|
+
import { buildSandboxWebSocketUrl, captureSandboxRequestContext, createSandboxMessageId, submitSandboxFrame, SANDBOX_SCOPED_PROTOCOL, type SandboxRequestContext } from './sandboxTransport';
|
|
12
|
+
import { createWorkspaceDirectoryController, type DirectoryStatus } from './workspaceDirectoryState.js';
|
|
13
|
+
import type { SandboxWorkspaceScope } from './workspaceDirectory.js';
|
|
12
14
|
import {
|
|
13
15
|
User, Bot, Users, Trash2, Send, Hash, MessageSquare,
|
|
14
16
|
Wifi, WifiOff, Smile, Image, X, Check, Info, Search,
|
|
@@ -20,8 +22,10 @@ import {
|
|
|
20
22
|
} from 'lucide-react';
|
|
21
23
|
import RichTextEditor, { type RichTextEditorRef } from './RichTextEditor';
|
|
22
24
|
import HtmlMessage from './HtmlMessage.js';
|
|
25
|
+
import ConversationRecoveryPanel from './ConversationRecoveryPanel.js';
|
|
26
|
+
import { useSandboxHistory } from './useSandboxHistory.js';
|
|
23
27
|
import {
|
|
24
|
-
|
|
28
|
+
agentSessionsPath,
|
|
25
29
|
buildAgentRunReport,
|
|
26
30
|
buildSandboxSessionKey,
|
|
27
31
|
cancelAgentTask,
|
|
@@ -41,6 +45,8 @@ import {
|
|
|
41
45
|
createDefaultPlaygroundState,
|
|
42
46
|
loadPlaygroundState,
|
|
43
47
|
savePlaygroundState,
|
|
48
|
+
mergePlaygroundMessage,
|
|
49
|
+
retirePlaygroundInteractions,
|
|
44
50
|
type PlaygroundMessage,
|
|
45
51
|
type PlaygroundSession,
|
|
46
52
|
} from './playgroundState.js';
|
|
@@ -50,10 +56,14 @@ type Message = PlaygroundMessage
|
|
|
50
56
|
type Channel = PlaygroundSession
|
|
51
57
|
interface Face { id: number; emojiId: number; stickerId: number; emojiType: string; name: string; describe: string; png: boolean; apng: boolean; lottie: boolean; }
|
|
52
58
|
|
|
53
|
-
export
|
|
59
|
+
export interface SandboxPageProps {
|
|
60
|
+
readonly renderConversationDetails?: (context: { readonly sessionKey: string; readonly canExecute: boolean; readonly connectionId?: string }) => React.ReactNode
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export default function Sandbox(props: SandboxPageProps = {}) {
|
|
54
64
|
const [locale, setLocale] = useState<SandboxLocale>('zh-CN')
|
|
55
65
|
const localeRef = useRef<SandboxLocale>('zh-CN')
|
|
56
|
-
const [initialState] = useState(() =>
|
|
66
|
+
const [initialState] = useState(() => createDefaultPlaygroundState())
|
|
57
67
|
const [messages, setMessages] = useState<Message[]>(() => [...initialState.messages])
|
|
58
68
|
const [channels, setChannels] = useState<Channel[]>(() => [...initialState.sessions])
|
|
59
69
|
const [faceList, setFaceList] = useState<Face[]>([])
|
|
@@ -67,8 +77,10 @@ export default function Sandbox() {
|
|
|
67
77
|
const [inputText, setInputText] = useState('')
|
|
68
78
|
const [endpointId, setBotName] = useState('sandbox-bot')
|
|
69
79
|
const [connected, setConnected] = useState(false)
|
|
70
|
-
const [canExecute, setCanExecute] = useState(
|
|
80
|
+
const [canExecute, setCanExecute] = useState(false)
|
|
71
81
|
const [persistenceStatus, setPersistenceStatus] = useState<'saved' | 'error'>('saved')
|
|
82
|
+
const [directoryStatus, setDirectoryStatus] = useState<DirectoryStatus>({ mode: 'loading', error: null })
|
|
83
|
+
const [workspaceScope, setWorkspaceScope] = useState<SandboxWorkspaceScope | null>(null)
|
|
72
84
|
const [transportNotice, setTransportNotice] = useState<string | null>(null)
|
|
73
85
|
const [shellIsolation, setShellIsolation] = useState<{ available: boolean; provider: string; message: string } | null>(null)
|
|
74
86
|
const [inspectorView, setInspectorView] = useState<'runs' | 'artifacts'>('runs')
|
|
@@ -90,6 +102,8 @@ export default function Sandbox() {
|
|
|
90
102
|
const [composerMode, setComposerMode] = useState<'write' | 'preview'>('write')
|
|
91
103
|
const [showChannelList, setShowChannelList] = useState(false)
|
|
92
104
|
const [showInspector, setShowInspector] = useState(false)
|
|
105
|
+
const [showConversationDetails, setShowConversationDetails] = useState(false)
|
|
106
|
+
const [pendingRefreshEpoch, setPendingRefreshEpoch] = useState(0)
|
|
93
107
|
const [showRunSettings, setShowRunSettings] = useState(false)
|
|
94
108
|
const [showNewSession, setShowNewSession] = useState(false)
|
|
95
109
|
const [newSessionName, setNewSessionName] = useState('')
|
|
@@ -98,16 +112,87 @@ export default function Sandbox() {
|
|
|
98
112
|
const [trace, setTrace] = useState<AgentTraceSnapshot | null>(null)
|
|
99
113
|
const [traceLoading, setTraceLoading] = useState(true)
|
|
100
114
|
const [traceNotice, setTraceNotice] = useState<string | null>(null)
|
|
115
|
+
const [cancellationFeedback, setCancellationFeedback] = useState<{ kind: 'error' | 'status'; message: string } | null>(null)
|
|
101
116
|
const messagesEndRef = useRef<HTMLDivElement>(null)
|
|
102
117
|
const wsRef = useRef<WebSocket | null>(null)
|
|
118
|
+
const connectionRef = useRef<{ protocol?: string; connectionId?: string; ownerId?: string; canExecute: boolean }>({ canExecute: false })
|
|
103
119
|
const editorRef = useRef<RichTextEditorRef>(null)
|
|
104
120
|
const traceRef = useRef<AgentTraceSnapshot | null>(null)
|
|
121
|
+
const traceReadOwnerRef = useRef<{
|
|
122
|
+
sessionKey: string; socket: WebSocket | null; controller: AbortController;
|
|
123
|
+
pending?: Promise<void>; cancelRefresh?: ReturnType<typeof window.setTimeout>;
|
|
124
|
+
} | null>(null)
|
|
105
125
|
const activeChannelRef = useRef(activeChannel)
|
|
106
126
|
const endpointIdRef = useRef(endpointId)
|
|
127
|
+
const directoryModeRef = useRef(directoryStatus.mode)
|
|
128
|
+
const directoryHostRef = useRef<string | null>(null)
|
|
129
|
+
const readyWorkingDirectoryRef = useRef('')
|
|
130
|
+
const readyIdentityRef = useRef<{ host: string; ownerId: string } | null>(null)
|
|
131
|
+
const socketRequestContextRef = useRef<SandboxRequestContext | null>(null)
|
|
132
|
+
const directoryControllerRef = useRef<ReturnType<typeof createWorkspaceDirectoryController> | null>(null)
|
|
133
|
+
if (!directoryControllerRef.current) directoryControllerRef.current = createWorkspaceDirectoryController({
|
|
134
|
+
loaded: (directory, sameScope) => {
|
|
135
|
+
const fallback = directory ? createDefaultPlaygroundState(readyWorkingDirectoryRef.current) : loadPlaygroundState()
|
|
136
|
+
const sessions: Channel[] = directory?.items.length
|
|
137
|
+
? directory.items.map((item) => ({ id: item.id, type: item.type, name: item.name, runConfig: item.runConfig, unread: 0 }))
|
|
138
|
+
: [...fallback.sessions]
|
|
139
|
+
const previous = activeChannelRef.current
|
|
140
|
+
if (sameScope && !sessions.some((session) => session.id === previous.id && session.type === previous.type)) sessions.push(previous)
|
|
141
|
+
const selected = sameScope
|
|
142
|
+
? sessions.find((session) => session.id === previous.id && session.type === previous.type)!
|
|
143
|
+
: sessions.find((session) => session.id === fallback.activeSessionId && session.type === fallback.activeSessionType) ?? sessions[0]!
|
|
144
|
+
activeChannelRef.current = selected
|
|
145
|
+
setActiveChannel(selected)
|
|
146
|
+
if (!sameScope) setMessages(directory ? [] : [...fallback.messages])
|
|
147
|
+
setChannels(sessions)
|
|
148
|
+
setWorkspaceScope(directory?.scope ?? null)
|
|
149
|
+
subscribeToScene(selected)
|
|
150
|
+
},
|
|
151
|
+
status: (status) => {
|
|
152
|
+
directoryModeRef.current = status.mode
|
|
153
|
+
setDirectoryStatus(status)
|
|
154
|
+
if (status.error) setPersistenceStatus('error')
|
|
155
|
+
else if (status.mode === 'server') setPersistenceStatus('saved')
|
|
156
|
+
},
|
|
157
|
+
})
|
|
107
158
|
const sessionKey = useMemo(
|
|
108
159
|
() => buildSandboxSessionKey(endpointId, activeChannel.type, activeChannel.id),
|
|
109
160
|
[activeChannel.id, activeChannel.type, endpointId],
|
|
110
161
|
)
|
|
162
|
+
const history = useSandboxHistory(canExecute && directoryStatus.mode === 'server' && workspaceScope
|
|
163
|
+
&& workspaceScope.connectionId === connectionRef.current.connectionId ? {
|
|
164
|
+
connectionId: workspaceScope.connectionId, sessionKey, scope: workspaceScope.endpoint,
|
|
165
|
+
scene: { id: activeChannel.id, type: activeChannel.type, name: activeChannel.name },
|
|
166
|
+
ownerId: workspaceScope.ownerId, requestContext: socketRequestContextRef.current ?? undefined,
|
|
167
|
+
} : undefined, setMessages, locale)
|
|
168
|
+
const retireTraceReads = () => {
|
|
169
|
+
const owner = traceReadOwnerRef.current
|
|
170
|
+
traceReadOwnerRef.current = null
|
|
171
|
+
owner?.controller.abort()
|
|
172
|
+
if (owner?.cancelRefresh !== undefined) window.clearTimeout(owner.cancelRefresh)
|
|
173
|
+
traceRef.current = null
|
|
174
|
+
}
|
|
175
|
+
const currentTraceOwner = () => {
|
|
176
|
+
const scene = activeChannelRef.current
|
|
177
|
+
const key = buildSandboxSessionKey(endpointIdRef.current, scene.type, scene.id)
|
|
178
|
+
let owner = traceReadOwnerRef.current
|
|
179
|
+
if (!owner || owner.sessionKey !== key || owner.socket !== wsRef.current) {
|
|
180
|
+
retireTraceReads()
|
|
181
|
+
owner = { sessionKey: key, socket: wsRef.current, controller: new AbortController() }
|
|
182
|
+
traceReadOwnerRef.current = owner
|
|
183
|
+
setTrace(null)
|
|
184
|
+
setTraceNotice(null)
|
|
185
|
+
setCancellationFeedback(null)
|
|
186
|
+
setStoppingTask(false)
|
|
187
|
+
}
|
|
188
|
+
return owner
|
|
189
|
+
}
|
|
190
|
+
const ownsCurrentTrace = (owner: NonNullable<typeof traceReadOwnerRef.current>) => {
|
|
191
|
+
const scene = activeChannelRef.current
|
|
192
|
+
return traceReadOwnerRef.current === owner && !owner.controller.signal.aborted
|
|
193
|
+
&& owner.socket === wsRef.current
|
|
194
|
+
&& owner.sessionKey === buildSandboxSessionKey(endpointIdRef.current, scene.type, scene.id)
|
|
195
|
+
}
|
|
111
196
|
const traceSummary = useMemo(() => summarizeTrace(trace), [trace])
|
|
112
197
|
const taskRuns = useMemo(() => deriveTaskRuns(trace), [trace])
|
|
113
198
|
const workbenchArtifacts = useMemo(() => deriveWorkbenchArtifacts(trace, locale), [trace, locale])
|
|
@@ -125,13 +210,14 @@ export default function Sandbox() {
|
|
|
125
210
|
useEffect(() => { setInlineRunExpanded(currentTask?.status === 'running') }, [currentTask?.id])
|
|
126
211
|
useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }) }, [currentTask?.id])
|
|
127
212
|
useEffect(() => {
|
|
213
|
+
if (directoryModeRef.current !== 'browser') return
|
|
128
214
|
setPersistenceStatus(savePlaygroundState({
|
|
129
215
|
activeSessionId: activeChannel.id,
|
|
130
216
|
activeSessionType: activeChannel.type,
|
|
131
217
|
sessions: channels,
|
|
132
218
|
messages,
|
|
133
219
|
}) ? 'saved' : 'error')
|
|
134
|
-
}, [activeChannel.id, channels, messages])
|
|
220
|
+
}, [activeChannel.id, channels, messages, directoryStatus.mode])
|
|
135
221
|
|
|
136
222
|
const fetchFaceList = async () => {
|
|
137
223
|
try { const res = await fetch('https://face.viki.moe/metadata.json'); setFaceList(await res.json()) }
|
|
@@ -140,16 +226,38 @@ export default function Sandbox() {
|
|
|
140
226
|
|
|
141
227
|
useEffect(() => { fetchFaceList() }, [])
|
|
142
228
|
|
|
229
|
+
const subscribeToScene = (scene: Pick<Channel, 'id' | 'type'>) => {
|
|
230
|
+
// Old Hosts parse unknown JSON as chat, so control frames require this explicit handshake.
|
|
231
|
+
if (connectionRef.current.protocol !== SANDBOX_SCOPED_PROTOCOL || !connectionRef.current.canExecute) return
|
|
232
|
+
if (!submitSandboxFrame(wsRef.current, { op: 'subscribe', conversation: { type: scene.type, id: scene.id } })) {
|
|
233
|
+
setTransportNotice(sandboxText(localeRef.current, "Sandbox 连接尚未就绪,会话切换未发送。"))
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
143
237
|
const handleInboundPayload = (data: {
|
|
144
238
|
type: string; id: string; locale?: unknown; content?: unknown; endpoint?: string; workingDirectory?: string; canExecute?: boolean;
|
|
145
239
|
shellIsolation?: { available?: boolean; provider?: string; message?: string }; timestamp: number;
|
|
146
|
-
messageId?: string; bot?: string;
|
|
240
|
+
messageId?: string; bot?: string; protocol?: string; connectionId?: string; direction?: string; senderId?: string;
|
|
241
|
+
conversation?: { type: Channel['type']; id: string };
|
|
147
242
|
}) => {
|
|
148
243
|
const locale = data.type === 'ready' && data.locale === 'en' ? 'en' : data.type === 'ready' ? 'zh-CN' : localeRef.current
|
|
149
244
|
if (data.type === 'ready') {
|
|
150
245
|
localeRef.current = locale
|
|
151
246
|
setLocale(locale)
|
|
152
|
-
|
|
247
|
+
const requestContext = socketRequestContextRef.current ?? captureSandboxRequestContext()
|
|
248
|
+
const host = requestContext.apiBase || window.location.origin
|
|
249
|
+
const previousIdentity = readyIdentityRef.current
|
|
250
|
+
if (previousIdentity && (previousIdentity.host !== host || previousIdentity.ownerId !== data.id)) {
|
|
251
|
+
const fresh = createDefaultPlaygroundState(data.workingDirectory?.trim())
|
|
252
|
+
activeChannelRef.current = fresh.sessions[0]!
|
|
253
|
+
setActiveChannel(fresh.sessions[0]!)
|
|
254
|
+
setChannels([...fresh.sessions])
|
|
255
|
+
setMessages([])
|
|
256
|
+
}
|
|
257
|
+
readyIdentityRef.current = { host, ownerId: data.id }
|
|
258
|
+
endpointIdRef.current = data.endpoint || data.bot || 'sandbox-bot'
|
|
259
|
+
setBotName(endpointIdRef.current)
|
|
260
|
+
connectionRef.current = { protocol: data.protocol, connectionId: data.connectionId, ownerId: data.id, canExecute: data.canExecute !== false }
|
|
153
261
|
setCanExecute(data.canExecute !== false)
|
|
154
262
|
setTransportNotice(data.canExecute === false ? sandboxText(locale, "当前 Token 只有演示权限,任务运行已禁用。") : null)
|
|
155
263
|
if (data.shellIsolation) {
|
|
@@ -159,18 +267,14 @@ export default function Sandbox() {
|
|
|
159
267
|
message: data.shellIsolation.message || sandboxText(locale, "未检测到隔离执行环境"),
|
|
160
268
|
})
|
|
161
269
|
}
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
? session
|
|
166
|
-
: { ...session, runConfig: { ...session.runConfig, workingDirectory } }))
|
|
167
|
-
setActiveChannel((current) => current.runConfig.workingDirectory
|
|
168
|
-
? current
|
|
169
|
-
: { ...current, runConfig: { ...current.runConfig, workingDirectory } })
|
|
170
|
-
}
|
|
270
|
+
readyWorkingDirectoryRef.current = data.workingDirectory?.trim() ?? ''
|
|
271
|
+
void directoryControllerRef.current!.begin({ host,
|
|
272
|
+
connectionId: data.connectionId, canExecute: data.canExecute !== false, requestContext })
|
|
171
273
|
return
|
|
172
274
|
}
|
|
275
|
+
if (data.type === 'subscribed') return
|
|
173
276
|
if (data.type === 'error') {
|
|
277
|
+
setPendingRefreshEpoch((epoch) => epoch + 1)
|
|
174
278
|
const notice = Array.isArray(data.content)
|
|
175
279
|
? String((data.content[0] as { data?: { text?: unknown } } | undefined)?.data?.text ?? sandboxText(locale, "Sandbox 拒绝了本次操作"))
|
|
176
280
|
: String(data.content ?? sandboxText(locale, "Sandbox 拒绝了本次操作"))
|
|
@@ -181,62 +285,67 @@ export default function Sandbox() {
|
|
|
181
285
|
const content: MessageSegment[] = Array.isArray(data.content)
|
|
182
286
|
? data.content as MessageSegment[]
|
|
183
287
|
: parseTextToSegments(String(data.content ?? ''))
|
|
184
|
-
|
|
288
|
+
const scene = data.conversation ?? activeChannelRef.current
|
|
289
|
+
if (!data.conversation && data.id && data.id !== scene.id) return
|
|
290
|
+
setMessages((prev) => prev.map((message) => message.id === data.messageId
|
|
291
|
+
&& message.channelType === scene.type && message.channelId === scene.id && message.type === 'received'
|
|
292
|
+
? { ...message, content } : message))
|
|
185
293
|
return
|
|
186
294
|
}
|
|
187
295
|
|
|
296
|
+
// A received message invalidates the projection; only Core decides whether a claim remains live.
|
|
297
|
+
setPendingRefreshEpoch((epoch) => epoch + 1)
|
|
188
298
|
const content: MessageSegment[] = typeof data.content === 'string'
|
|
189
299
|
? parseTextToSegments(data.content)
|
|
190
300
|
: Array.isArray(data.content) ? data.content as MessageSegment[] : parseTextToSegments(String(data.content ?? ''))
|
|
191
301
|
|
|
192
|
-
const channelType: Channel['type'] = data.type === 'group' || data.type === 'channel' ? data.type : 'private'
|
|
302
|
+
const channelType: Channel['type'] = data.conversation?.type ?? (data.type === 'group' || data.type === 'channel' ? data.type : 'private')
|
|
303
|
+
const sceneId = data.conversation?.id ?? data.id
|
|
304
|
+
const isInput = data.direction === 'inbound'
|
|
305
|
+
// Interactive choices are transport inputs, not another chat turn or an approval result.
|
|
306
|
+
if (isInput && content.every((segment) => segment.type === 'action')) return
|
|
193
307
|
const channelName = channelType === 'private'
|
|
194
|
-
? sandboxText(locale, "会话 {0}", [
|
|
308
|
+
? sandboxText(locale, "会话 {0}", [sceneId])
|
|
195
309
|
: channelType === 'group'
|
|
196
|
-
? sandboxText(locale, "群组场景 {0}", [
|
|
197
|
-
: sandboxText(locale, "频道场景 {0}", [
|
|
310
|
+
? sandboxText(locale, "群组场景 {0}", [sceneId])
|
|
311
|
+
: sandboxText(locale, "频道场景 {0}", [sceneId])
|
|
198
312
|
|
|
199
313
|
setChannels((prev) => {
|
|
200
|
-
if (prev.some((c) => c.id ===
|
|
314
|
+
if (prev.some((c) => c.id === sceneId && c.type === channelType)) return prev
|
|
201
315
|
const created: Channel = {
|
|
202
|
-
id:
|
|
316
|
+
id: sceneId, name: channelName, type: channelType, unread: 0,
|
|
203
317
|
runConfig: { ...activeChannelRef.current.runConfig },
|
|
204
318
|
}
|
|
319
|
+
activeChannelRef.current = created
|
|
205
320
|
setActiveChannel(created)
|
|
206
321
|
return [...prev, created]
|
|
207
322
|
})
|
|
208
323
|
|
|
209
|
-
setMessages((prev) =>
|
|
210
|
-
id: data.messageId ??
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
324
|
+
setMessages((prev) => mergePlaygroundMessage(prev, {
|
|
325
|
+
id: data.messageId ?? createSandboxMessageId(), type: isInput ? 'sent' : 'received', channelType,
|
|
326
|
+
interactionReadOnly: false,
|
|
327
|
+
channelId: sceneId, channelName, senderId: isInput ? data.senderId || connectionRef.current.ownerId || 'owner' : 'endpoint',
|
|
328
|
+
senderName: isInput ? sandboxText(locale, "当前用户") : data.bot || endpointIdRef.current, content, timestamp: data.timestamp,
|
|
329
|
+
}))
|
|
214
330
|
}
|
|
215
331
|
|
|
216
332
|
const sendInteractiveAction = (payload: string, messageId?: string) => {
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
setTransportNotice(sandboxText(locale, "Sandbox 连接尚未就绪,审批选择未发送。"))
|
|
220
|
-
return
|
|
221
|
-
}
|
|
333
|
+
if (!connectionRef.current.canExecute) return false
|
|
334
|
+
const scene = activeChannelRef.current
|
|
222
335
|
const segments: MessageSegment[] = [{ type: 'action', data: { id: payload, payload } }]
|
|
223
|
-
|
|
224
|
-
type:
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
})
|
|
230
|
-
try {
|
|
231
|
-
ws.send(payloadJson)
|
|
232
|
-
if (messageId) {
|
|
233
|
-
setMessages((current) => current.map((message) => message.id === messageId
|
|
234
|
-
? { ...message, interactionResolved: true }
|
|
235
|
-
: message))
|
|
236
|
-
}
|
|
237
|
-
} catch {
|
|
238
|
-
setTransportNotice(sandboxText(locale, "审批选择发送失败,请等待连接恢复后重试。"))
|
|
336
|
+
if (!submitSandboxFrame(wsRef.current, {
|
|
337
|
+
type: scene.type, id: scene.id, messageId: createSandboxMessageId(), content: segments,
|
|
338
|
+
agentRun: scene.runConfig, timestamp: Date.now(),
|
|
339
|
+
})) {
|
|
340
|
+
setTransportNotice(sandboxText(localeRef.current, "Sandbox 连接尚未就绪,审批选择未发送。"))
|
|
341
|
+
return false
|
|
239
342
|
}
|
|
343
|
+
if (messageId) {
|
|
344
|
+
setMessages((current) => current.map((message) => message.id === messageId
|
|
345
|
+
&& message.channelType === scene.type && message.channelId === scene.id && message.type === 'received'
|
|
346
|
+
? { ...message, interactionResolved: true } : message))
|
|
347
|
+
}
|
|
348
|
+
return true
|
|
240
349
|
}
|
|
241
350
|
|
|
242
351
|
useEffect(() => {
|
|
@@ -248,13 +357,30 @@ export default function Sandbox() {
|
|
|
248
357
|
|
|
249
358
|
const connect = () => {
|
|
250
359
|
if (closed) return
|
|
360
|
+
retireTraceReads()
|
|
361
|
+
directoryControllerRef.current?.retire()
|
|
362
|
+
directoryModeRef.current = 'loading'
|
|
363
|
+
setDirectoryStatus({ mode: 'loading', error: null })
|
|
364
|
+
setWorkspaceScope(null)
|
|
365
|
+
const requestContext = captureSandboxRequestContext()
|
|
366
|
+
const nextHost = requestContext.apiBase || window.location.origin
|
|
367
|
+
if (directoryHostRef.current !== nextHost) {
|
|
368
|
+
const fresh = createDefaultPlaygroundState()
|
|
369
|
+
activeChannelRef.current = fresh.sessions[0]!
|
|
370
|
+
setActiveChannel(fresh.sessions[0]!)
|
|
371
|
+
setChannels([...fresh.sessions])
|
|
372
|
+
setMessages([])
|
|
373
|
+
}
|
|
374
|
+
directoryHostRef.current = nextHost
|
|
251
375
|
if (retryTimer) {
|
|
252
376
|
clearTimeout(retryTimer)
|
|
253
377
|
retryTimer = undefined
|
|
254
378
|
}
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
379
|
+
connectionRef.current = { canExecute: false }
|
|
380
|
+
setCanExecute(false)
|
|
381
|
+
setConnected(false)
|
|
382
|
+
const wsUrl = buildSandboxWebSocketUrl(nextHost)
|
|
383
|
+
// This page owns one connection; replacing its credentials must retire only that socket.
|
|
258
384
|
const previous = wsRef.current
|
|
259
385
|
if (previous) {
|
|
260
386
|
replaceInFlight = true
|
|
@@ -266,18 +392,29 @@ export default function Sandbox() {
|
|
|
266
392
|
replaceInFlight = false
|
|
267
393
|
}
|
|
268
394
|
const ws = new WebSocket(wsUrl)
|
|
395
|
+
socketRequestContextRef.current = requestContext
|
|
269
396
|
wsRef.current = ws
|
|
397
|
+
void loadTrace()
|
|
270
398
|
ws.onopen = () => {
|
|
399
|
+
if (wsRef.current !== ws) return
|
|
271
400
|
attempt = 0
|
|
272
401
|
setConnected(true)
|
|
273
402
|
}
|
|
274
403
|
ws.onmessage = (event) => {
|
|
404
|
+
if (wsRef.current !== ws) return
|
|
275
405
|
try { handleInboundPayload(JSON.parse(String(event.data))) }
|
|
276
406
|
catch (err) { console.error('[Sandbox] Failed to parse message:', err) }
|
|
277
407
|
}
|
|
278
408
|
ws.onclose = () => {
|
|
279
409
|
if (wsRef.current !== ws) return
|
|
410
|
+
retireTraceReads()
|
|
411
|
+
directoryControllerRef.current?.retire()
|
|
412
|
+
directoryModeRef.current = 'loading'
|
|
413
|
+
setDirectoryStatus({ mode: 'loading', error: null })
|
|
414
|
+
setWorkspaceScope(null)
|
|
280
415
|
setConnected(false)
|
|
416
|
+
setCanExecute(false)
|
|
417
|
+
connectionRef.current = { canExecute: false }
|
|
281
418
|
wsRef.current = null
|
|
282
419
|
if (closed || replaceInFlight) return
|
|
283
420
|
const delay = Math.min(8_000, 500 * 2 ** attempt)
|
|
@@ -318,6 +455,8 @@ export default function Sandbox() {
|
|
|
318
455
|
}
|
|
319
456
|
return () => {
|
|
320
457
|
closed = true
|
|
458
|
+
retireTraceReads()
|
|
459
|
+
directoryControllerRef.current?.retire()
|
|
321
460
|
if (retryTimer) clearTimeout(retryTimer)
|
|
322
461
|
if (typeof window !== 'undefined') {
|
|
323
462
|
window.removeEventListener('storage', onAuthOrStorage)
|
|
@@ -327,6 +466,8 @@ export default function Sandbox() {
|
|
|
327
466
|
}
|
|
328
467
|
wsRef.current?.close()
|
|
329
468
|
wsRef.current = null
|
|
469
|
+
connectionRef.current = { canExecute: false }
|
|
470
|
+
setCanExecute(false)
|
|
330
471
|
setConnected(false)
|
|
331
472
|
}
|
|
332
473
|
}, [])
|
|
@@ -335,37 +476,50 @@ export default function Sandbox() {
|
|
|
335
476
|
useEffect(() => { setPreviewSegments(inputText.trim() ? parseTextToSegments(inputText) : []) }, [inputText])
|
|
336
477
|
|
|
337
478
|
const loadTrace = useCallback(async (quiet = false) => {
|
|
479
|
+
const owner = currentTraceOwner()
|
|
338
480
|
const locale = localeRef.current
|
|
339
481
|
if (!quiet) setTraceLoading(true)
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
incoming = await fetchAgentTrace(sessionKey, 0, locale)
|
|
482
|
+
if (owner.pending) return owner.pending
|
|
483
|
+
owner.pending = (async () => {
|
|
484
|
+
try {
|
|
485
|
+
const current = traceRef.current?.sessionKey === owner.sessionKey ? traceRef.current : null
|
|
486
|
+
let incoming = await fetchAgentTrace(owner.sessionKey, quiet ? current?.latestSequence ?? 0 : 0, locale, owner.controller.signal)
|
|
487
|
+
if (!ownsCurrentTrace(owner)) return
|
|
488
|
+
if (quiet && current?.runtimeId && incoming.runtimeId && current.runtimeId !== incoming.runtimeId) {
|
|
489
|
+
incoming = await fetchAgentTrace(owner.sessionKey, 0, locale, owner.controller.signal)
|
|
490
|
+
if (!ownsCurrentTrace(owner)) return
|
|
491
|
+
}
|
|
492
|
+
const baseline = traceRef.current?.sessionKey === owner.sessionKey ? traceRef.current : null
|
|
493
|
+
const merged = mergeTraceSnapshot(baseline, incoming)
|
|
494
|
+
traceRef.current = merged
|
|
495
|
+
setTrace(merged)
|
|
496
|
+
saveCachedAgentTrace(merged)
|
|
497
|
+
setTraceNotice(null)
|
|
498
|
+
} catch (error) {
|
|
499
|
+
if (ownsCurrentTrace(owner)) setTraceNotice(error instanceof Error ? error.message : sandboxText(locale, "Agent Trace 暂不可用"))
|
|
500
|
+
} finally {
|
|
501
|
+
owner.pending = undefined
|
|
502
|
+
if (ownsCurrentTrace(owner)) setTraceLoading(false)
|
|
345
503
|
}
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
saveCachedAgentTrace(merged)
|
|
350
|
-
setTraceNotice(null)
|
|
351
|
-
} catch (error) {
|
|
352
|
-
setTraceNotice(error instanceof Error ? error.message : sandboxText(locale, "Agent Trace 暂不可用"))
|
|
353
|
-
} finally {
|
|
354
|
-
if (!quiet) setTraceLoading(false)
|
|
355
|
-
}
|
|
356
|
-
}, [sessionKey])
|
|
504
|
+
})()
|
|
505
|
+
return owner.pending
|
|
506
|
+
}, [])
|
|
357
507
|
|
|
358
508
|
useEffect(() => {
|
|
509
|
+
const owner = currentTraceOwner()
|
|
359
510
|
const cached = loadCachedAgentTrace(sessionKey)
|
|
360
|
-
|
|
511
|
+
// Cached display is not an incremental baseline for this connection.
|
|
361
512
|
setTrace(cached)
|
|
362
513
|
setTraceNotice(null)
|
|
363
514
|
void loadTrace()
|
|
364
515
|
const timer = window.setInterval(() => {
|
|
365
516
|
if (document.visibilityState === 'visible') void loadTrace(true)
|
|
366
517
|
}, 2_000)
|
|
367
|
-
return () =>
|
|
368
|
-
|
|
518
|
+
return () => {
|
|
519
|
+
window.clearInterval(timer)
|
|
520
|
+
if (traceReadOwnerRef.current === owner) retireTraceReads()
|
|
521
|
+
}
|
|
522
|
+
}, [sessionKey, loadTrace])
|
|
369
523
|
|
|
370
524
|
const parseTextToSegments = (text: string): MessageSegment[] => {
|
|
371
525
|
const segments: MessageSegment[] = []
|
|
@@ -405,6 +559,8 @@ export default function Sandbox() {
|
|
|
405
559
|
isSent: boolean,
|
|
406
560
|
messageId?: string,
|
|
407
561
|
interactionResolved = false,
|
|
562
|
+
onInteractionSubmitted?: () => void,
|
|
563
|
+
allowInteraction = true,
|
|
408
564
|
) => {
|
|
409
565
|
const ring = isSent ? 'ring-1 ring-primary-foreground/25' : 'ring-1 ring-border/60'
|
|
410
566
|
return segments.map((segment, index) => {
|
|
@@ -519,8 +675,8 @@ export default function Sandbox() {
|
|
|
519
675
|
<button
|
|
520
676
|
key={btn.payload}
|
|
521
677
|
type="button"
|
|
522
|
-
disabled={btn.disabled || isSent || resolved}
|
|
523
|
-
onClick={() => sendInteractiveAction(btn.payload, messageId)}
|
|
678
|
+
disabled={btn.disabled || isSent || resolved || !canExecute || !allowInteraction}
|
|
679
|
+
onClick={() => { if (sendInteractiveAction(btn.payload, messageId)) onInteractionSubmitted?.() }}
|
|
524
680
|
className={cn(
|
|
525
681
|
(btn.style === 'primary' || /^允许/u.test(btn.label)) && 'is-primary',
|
|
526
682
|
(btn.style === 'danger' || /拒绝|取消/u.test(btn.label)) && 'is-danger',
|
|
@@ -541,21 +697,26 @@ export default function Sandbox() {
|
|
|
541
697
|
})
|
|
542
698
|
}
|
|
543
699
|
|
|
544
|
-
const handleSendMessage = (
|
|
545
|
-
if (!canExecute || !hasRenderableSegments(segments)) return
|
|
546
|
-
const
|
|
547
|
-
|
|
700
|
+
const handleSendMessage = (_text: string, segments: MessageSegment[]) => {
|
|
701
|
+
if (!connectionRef.current.canExecute || directoryModeRef.current === 'loading' || !hasRenderableSegments(segments)) return
|
|
702
|
+
const scene = activeChannelRef.current
|
|
703
|
+
const newMessage: Message = {
|
|
704
|
+
id: createSandboxMessageId(), type: 'sent', channelType: scene.type, channelId: scene.id,
|
|
705
|
+
channelName: scene.name, senderId: connectionRef.current.ownerId || 'test_user',
|
|
706
|
+
senderName: sandboxText(localeRef.current, "测试用户"), content: segments, timestamp: Date.now(),
|
|
707
|
+
}
|
|
708
|
+
if (!submitSandboxFrame(wsRef.current, {
|
|
709
|
+
type: scene.type, id: scene.id, messageId: newMessage.id, content: segments,
|
|
710
|
+
agentRun: scene.runConfig, timestamp: newMessage.timestamp,
|
|
711
|
+
})) {
|
|
712
|
+
setTransportNotice(sandboxText(localeRef.current, "Sandbox 连接尚未就绪,消息未发送。"))
|
|
713
|
+
return
|
|
714
|
+
}
|
|
715
|
+
void directoryControllerRef.current?.save(scene, true)
|
|
716
|
+
setPendingRefreshEpoch((epoch) => epoch + 1)
|
|
717
|
+
setMessages((prev) => mergePlaygroundMessage(prev, newMessage))
|
|
718
|
+
setInputText(''); setPreviewSegments([]); setComposerMode('write')
|
|
548
719
|
editorRef.current?.clear()
|
|
549
|
-
// Stamp type+id so Host sandbox endpoint preserves channel context for outbound replies.
|
|
550
|
-
const payload = JSON.stringify({
|
|
551
|
-
type: activeChannel.type,
|
|
552
|
-
id: activeChannel.id,
|
|
553
|
-
messageId: newMessage.id,
|
|
554
|
-
content: segments,
|
|
555
|
-
agentRun: activeChannel.runConfig,
|
|
556
|
-
timestamp: Date.now(),
|
|
557
|
-
})
|
|
558
|
-
wsRef.current?.send(payload)
|
|
559
720
|
}
|
|
560
721
|
|
|
561
722
|
|
|
@@ -565,21 +726,35 @@ export default function Sandbox() {
|
|
|
565
726
|
)))
|
|
566
727
|
setConfirmClear(false)
|
|
567
728
|
}
|
|
568
|
-
const switchChannel = (channel: Channel) => {
|
|
729
|
+
const switchChannel = (channel: Channel) => {
|
|
730
|
+
activeChannelRef.current = channel
|
|
731
|
+
subscribeToScene(channel)
|
|
732
|
+
setActiveChannel(channel)
|
|
733
|
+
setChannels((prev) => prev.map((c) => c.id === channel.id && c.type === channel.type ? { ...c, unread: 0 } : c))
|
|
734
|
+
if (window.innerWidth < 900) setShowChannelList(false)
|
|
735
|
+
}
|
|
569
736
|
const updateRunConfig = (patch: Partial<SandboxAgentRunConfig>) => {
|
|
570
|
-
|
|
737
|
+
if (directoryModeRef.current === 'loading') return
|
|
738
|
+
const current = activeChannelRef.current
|
|
739
|
+
const next = { ...current, runConfig: { ...current.runConfig, ...patch } }
|
|
740
|
+
activeChannelRef.current = next
|
|
571
741
|
setActiveChannel(next)
|
|
572
|
-
setChannels((sessions) => sessions.map((session) => session.id ===
|
|
742
|
+
setChannels((sessions) => sessions.map((session) => session.id === current.id && session.type === current.type ? next : session))
|
|
743
|
+
void directoryControllerRef.current?.save(next)
|
|
573
744
|
}
|
|
574
745
|
const addSession = () => {
|
|
746
|
+
if (directoryModeRef.current === 'loading') return
|
|
575
747
|
const label = newSessionName.trim() || sandboxText(locale, "未命名试验")
|
|
576
|
-
const id = `${newSessionScope}-${
|
|
748
|
+
const id = `${newSessionScope}-${createSandboxMessageId()}`
|
|
577
749
|
const session: Channel = {
|
|
578
750
|
id, name: label, type: newSessionScope, unread: 0,
|
|
579
751
|
runConfig: { ...activeChannel.runConfig },
|
|
580
752
|
}
|
|
581
753
|
setChannels((current) => [...current, session])
|
|
754
|
+
activeChannelRef.current = session
|
|
755
|
+
subscribeToScene(session)
|
|
582
756
|
setActiveChannel(session)
|
|
757
|
+
void directoryControllerRef.current?.save(session)
|
|
583
758
|
setNewSessionName('')
|
|
584
759
|
setShowNewSession(false)
|
|
585
760
|
}
|
|
@@ -611,16 +786,24 @@ export default function Sandbox() {
|
|
|
611
786
|
const runPrompt = (prompt: string) => handleSendMessage(prompt, [{ type: 'text', data: { text: prompt } }])
|
|
612
787
|
const recentTraceEvents = trace?.events.slice(-8).reverse() ?? []
|
|
613
788
|
const stopActiveTask = async () => {
|
|
789
|
+
const owner = currentTraceOwner()
|
|
790
|
+
setCancellationFeedback(null)
|
|
614
791
|
setStoppingTask(true)
|
|
615
792
|
try {
|
|
616
|
-
const cancelled = await cancelAgentTask(sessionKey, locale)
|
|
617
|
-
|
|
618
|
-
|
|
793
|
+
const cancelled = await cancelAgentTask(owner.sessionKey, locale)
|
|
794
|
+
if (!ownsCurrentTrace(owner)) return
|
|
795
|
+
setCancellationFeedback({ kind: 'status', message: cancelled ? sandboxText(locale, "停止请求已提交。") : sandboxText(locale, "当前会话没有运行中的任务。") })
|
|
796
|
+
if (owner.cancelRefresh !== undefined) window.clearTimeout(owner.cancelRefresh)
|
|
797
|
+
owner.cancelRefresh = window.setTimeout(() => {
|
|
798
|
+
owner.cancelRefresh = undefined
|
|
799
|
+
if (ownsCurrentTrace(owner)) void loadTrace(true)
|
|
800
|
+
}, 240)
|
|
619
801
|
} catch (error) {
|
|
620
|
-
|
|
802
|
+
if (!ownsCurrentTrace(owner)) return
|
|
803
|
+
setCancellationFeedback({ kind: 'error', message: error instanceof Error ? error.message : sandboxText(locale, "无法停止任务") })
|
|
621
804
|
setShowInspector(true)
|
|
622
805
|
} finally {
|
|
623
|
-
setStoppingTask(false)
|
|
806
|
+
if (ownsCurrentTrace(owner)) setStoppingTask(false)
|
|
624
807
|
}
|
|
625
808
|
}
|
|
626
809
|
const retryLastTask = () => {
|
|
@@ -701,20 +884,21 @@ export default function Sandbox() {
|
|
|
701
884
|
</article>
|
|
702
885
|
) : null
|
|
703
886
|
|
|
887
|
+
const recoveryConnectionId = connectionRef.current.connectionId
|
|
704
888
|
return (
|
|
705
|
-
<section className="agent-playground-shell">
|
|
889
|
+
<section className={cn("agent-playground-shell", showInspector && "has-inspector")}>
|
|
706
890
|
<div className="agent-playground-mobilebar">
|
|
707
|
-
<button type="button" aria-expanded={showChannelList} onClick={() => setShowChannelList(!showChannelList)}><MessageSquare size={17} />{sandboxText(locale, "
|
|
708
|
-
<strong>{sandboxText(locale, "
|
|
709
|
-
<button type="button" aria-expanded={showInspector} onClick={() => setShowInspector(!showInspector)}><PanelRight size={17} />{sandboxText(locale, "检查器")}</button>
|
|
891
|
+
<button type="button" aria-expanded={showChannelList} onClick={() => setShowChannelList(!showChannelList)}><MessageSquare size={17} />{sandboxText(locale, "会话列表")}</button>
|
|
892
|
+
<strong>{sandboxText(locale, "会话")}</strong>
|
|
893
|
+
<button type="button" aria-expanded={showInspector} aria-controls="sandbox-run-inspector" onClick={() => setShowInspector(!showInspector)}><PanelRight size={17} />{sandboxText(locale, "检查器")}</button>
|
|
710
894
|
</div>
|
|
711
895
|
|
|
712
|
-
<nav className={cn("channel-sidebar agent-playground-sessions", showChannelList && "show")} aria-label={sandboxText(locale, "
|
|
896
|
+
<nav className={cn("channel-sidebar agent-playground-sessions", showChannelList && "show")} aria-label={sandboxText(locale, "会话列表")}>
|
|
713
897
|
<div className="agent-playground-brand">
|
|
714
898
|
<div className="flex justify-between items-center">
|
|
715
899
|
<div className="flex items-center gap-2">
|
|
716
900
|
<span className="agent-playground-mark"><Sparkles size={16} /></span>
|
|
717
|
-
<div><h2>{sandboxText(locale, "
|
|
901
|
+
<div><h2>{sandboxText(locale, "会话")}</h2><small>Conversations</small></div>
|
|
718
902
|
</div>
|
|
719
903
|
<span className={cn("agent-playground-connection", connected && "is-online")} title={connected ? sandboxText(locale, "Sandbox WebSocket 已连接") : sandboxText(locale, "正在重连 Sandbox WebSocket")}>
|
|
720
904
|
{connected ? <Wifi size={12} /> : <WifiOff size={12} />}
|
|
@@ -722,12 +906,12 @@ export default function Sandbox() {
|
|
|
722
906
|
</div>
|
|
723
907
|
</div>
|
|
724
908
|
|
|
725
|
-
<div className="agent-playground-section-label"><span>{sandboxText(locale, "
|
|
909
|
+
<div className="agent-playground-section-label"><span>{sandboxText(locale, "会话列表")}</span><span>{channels.length}</span><button type="button" disabled={directoryStatus.mode === 'loading'} aria-label={sandboxText(locale, "刷新会话目录")} onClick={() => void directoryControllerRef.current?.refresh()}><RefreshCw size={13} /></button></div>
|
|
726
910
|
<div className="agent-playground-session-list">
|
|
727
911
|
{channels.map((channel) => {
|
|
728
912
|
const isActive = activeChannel.id === channel.id && activeChannel.type === channel.type
|
|
729
913
|
return (
|
|
730
|
-
<button type="button" key={`${channel.type}:${channel.id}`} aria-current={isActive ? 'page' : undefined} className={cn("agent-playground-session", isActive && "active")} onClick={() => switchChannel(channel)}>
|
|
914
|
+
<button type="button" key={`${channel.type}:${channel.id}`} disabled={directoryStatus.mode === 'loading'} aria-current={isActive ? 'page' : undefined} className={cn("agent-playground-session", isActive && "active")} onClick={() => switchChannel(channel)}>
|
|
731
915
|
<span className="agent-playground-session-icon">{getChannelIcon(channel.type)}</span>
|
|
732
916
|
<div className="flex-1 min-w-0">
|
|
733
917
|
<div className="text-sm font-medium truncate">{channel.name}</div>
|
|
@@ -756,11 +940,11 @@ export default function Sandbox() {
|
|
|
756
940
|
</div>
|
|
757
941
|
</div>
|
|
758
942
|
) : (
|
|
759
|
-
<button type="button" className="agent-playground-add" onClick={() => setShowNewSession(true)}><Plus size={15} />{sandboxText(locale, "
|
|
943
|
+
<button type="button" disabled={directoryStatus.mode === 'loading'} className="agent-playground-add" onClick={() => setShowNewSession(true)}><Plus size={15} />{sandboxText(locale, "新建会话")}</button>
|
|
760
944
|
)}
|
|
761
945
|
</div>
|
|
762
946
|
<div className="agent-playground-endpoint">
|
|
763
|
-
<span>{persistenceStatus === 'saved' ? sandboxText(locale, "会话已持久化") : sandboxText(locale, "会话保存失败")}</span>
|
|
947
|
+
<span>{directoryStatus.mode === 'loading' ? sandboxText(locale, "正在读取会话目录") : directoryStatus.mode === 'server' && !directoryStatus.error ? sandboxText(locale, "Host 会话目录") : persistenceStatus === 'saved' ? sandboxText(locale, "会话已持久化") : sandboxText(locale, "会话保存失败")}</span>
|
|
764
948
|
<strong>{endpointId}</strong>
|
|
765
949
|
</div>
|
|
766
950
|
</nav>
|
|
@@ -771,9 +955,8 @@ export default function Sandbox() {
|
|
|
771
955
|
<header className="agent-playground-runbar">
|
|
772
956
|
<div className="agent-playground-run-identity">
|
|
773
957
|
<span className="agent-playground-run-icon">{getChannelIcon(activeChannel.type)}</span>
|
|
774
|
-
<div>
|
|
775
|
-
<div className="agent-playground-run-title"><h1>{activeChannel.name}</h1><span>{scopeLabel}</span></div>
|
|
776
|
-
<code>{sessionKey}</code>
|
|
958
|
+
<div title={sessionKey}>
|
|
959
|
+
<div className="agent-playground-run-title"><h1 title={activeChannel.name}>{activeChannel.name}</h1><span>{scopeLabel}</span></div>
|
|
777
960
|
</div>
|
|
778
961
|
</div>
|
|
779
962
|
<div className="agent-playground-run-actions">
|
|
@@ -786,13 +969,20 @@ export default function Sandbox() {
|
|
|
786
969
|
) : lastUserMessage ? (
|
|
787
970
|
<button type="button" onClick={retryLastTask} aria-label={sandboxText(locale, "重新运行上一个任务")}><RotateCcw size={14} />{sandboxText(locale, "重试")}</button>
|
|
788
971
|
) : null}
|
|
789
|
-
|
|
972
|
+
{props.renderConversationDetails
|
|
973
|
+
? <button type="button" disabled={!canExecute} aria-expanded={showConversationDetails} aria-controls="sandbox-conversation-details" onClick={() => setShowConversationDetails((visible) => !visible)}><ListChecks size={14} />{sandboxText(locale, "对话与轨迹")}</button>
|
|
974
|
+
: <a href={agentSessionsPath(sessionKey)}><ExternalLink size={14} />{sandboxText(locale, "对话与轨迹")}</a>}
|
|
790
975
|
<button type="button" className={cn(showRunSettings && 'active')} aria-expanded={showRunSettings} onClick={() => setShowRunSettings((visible) => !visible)} aria-label={sandboxText(locale, "配置运行环境")}><SlidersHorizontal size={16} /></button>
|
|
791
|
-
<button type="button" aria-expanded={showInspector} onClick={() => setShowInspector(!showInspector)} aria-label={sandboxText(locale, "切换运行检查器")}><PanelRight size={16} /></button>
|
|
976
|
+
<button type="button" aria-expanded={showInspector} aria-controls="sandbox-run-inspector" onClick={() => setShowInspector(!showInspector)} aria-label={sandboxText(locale, "切换运行检查器")}><PanelRight size={16} /></button>
|
|
792
977
|
<button type="button" onClick={() => setConfirmClear(true)} aria-label={sandboxText(locale, "清空当前会话")}><Trash2 size={15} /></button>
|
|
793
978
|
</div>
|
|
794
979
|
</header>
|
|
795
980
|
|
|
981
|
+
{cancellationFeedback && <div className="agent-playground-confirm" role={cancellationFeedback.kind === 'error' ? 'alert' : 'status'}>
|
|
982
|
+
<div><span>{cancellationFeedback.message}</span></div>
|
|
983
|
+
<button type="button" onClick={() => setCancellationFeedback(null)}>{sandboxText(locale, "知道了")}</button>
|
|
984
|
+
</div>}
|
|
985
|
+
|
|
796
986
|
{confirmClear && (
|
|
797
987
|
<div className="agent-playground-confirm" role="alert">
|
|
798
988
|
<div><strong>{sandboxText(locale, "清空当前测试记录?")}</strong><span>{sandboxText(locale, "只移除“")}{activeChannel.name}{sandboxText(locale, "”在浏览器中的消息,不影响 Agent 会话存储。")}</span></div>
|
|
@@ -808,11 +998,17 @@ export default function Sandbox() {
|
|
|
808
998
|
</div>
|
|
809
999
|
)}
|
|
810
1000
|
|
|
1001
|
+
{directoryStatus.error && <div className="agent-playground-confirm" role="alert">
|
|
1002
|
+
<div><strong>{sandboxText(locale, "会话目录")}</strong><span>{directoryStatus.error}</span></div>
|
|
1003
|
+
<button type="button" onClick={() => void directoryControllerRef.current?.refresh()}>{sandboxText(locale, "重新读取")}</button>
|
|
1004
|
+
</div>}
|
|
1005
|
+
|
|
811
1006
|
{showRunSettings && (
|
|
812
1007
|
<section className="agent-playground-run-settings" aria-label={sandboxText(locale, "运行配置")}>
|
|
813
1008
|
<label className="agent-playground-directory-field">
|
|
814
1009
|
<span><FolderOpen size={14} />{sandboxText(locale, "工作目录")}</span>
|
|
815
1010
|
<input
|
|
1011
|
+
disabled={directoryStatus.mode === 'loading'}
|
|
816
1012
|
value={activeChannel.runConfig.workingDirectory}
|
|
817
1013
|
onChange={(event) => updateRunConfig({ workingDirectory: event.target.value })}
|
|
818
1014
|
placeholder={sandboxText(locale, "使用 Host 项目目录")}
|
|
@@ -821,7 +1017,7 @@ export default function Sandbox() {
|
|
|
821
1017
|
</label>
|
|
822
1018
|
<label>
|
|
823
1019
|
<span><ShieldCheck size={14} />{sandboxText(locale, "安全策略")}</span>
|
|
824
|
-
<select value={activeChannel.runConfig.safetyMode} onChange={(event) => {
|
|
1020
|
+
<select disabled={directoryStatus.mode === 'loading'} value={activeChannel.runConfig.safetyMode} onChange={(event) => {
|
|
825
1021
|
const safetyMode = event.target.value as SandboxAgentRunConfig['safetyMode']
|
|
826
1022
|
updateRunConfig({ safetyMode, ...(safetyMode === 'danger-full-access' ? { networkAccess: true } : {}) })
|
|
827
1023
|
}}>
|
|
@@ -861,9 +1057,37 @@ export default function Sandbox() {
|
|
|
861
1057
|
</section>
|
|
862
1058
|
)}
|
|
863
1059
|
|
|
864
|
-
{
|
|
865
|
-
|
|
866
|
-
|
|
1060
|
+
{canExecute && recoveryConnectionId && (
|
|
1061
|
+
<ConversationRecoveryPanel key={JSON.stringify([recoveryConnectionId, sessionKey])}
|
|
1062
|
+
connectionId={recoveryConnectionId} sessionKey={sessionKey} locale={locale} hidden={showConversationDetails}
|
|
1063
|
+
pendingRefreshEpoch={pendingRefreshEpoch}
|
|
1064
|
+
onRetiredInteractions={(retired) => {
|
|
1065
|
+
const segments = retired.flatMap(interaction => interaction.segments)
|
|
1066
|
+
setMessages(previous => {
|
|
1067
|
+
const current = activeChannelRef.current
|
|
1068
|
+
if (connectionRef.current.connectionId !== recoveryConnectionId
|
|
1069
|
+
|| buildSandboxSessionKey(endpointIdRef.current, current.type, current.id) !== sessionKey) return previous
|
|
1070
|
+
return retirePlaygroundInteractions(previous, activeChannel, segments)
|
|
1071
|
+
})
|
|
1072
|
+
}}
|
|
1073
|
+
requestContext={socketRequestContextRef.current ?? undefined}
|
|
1074
|
+
renderInteraction={(segments, id, submitted, onSubmitted) => renderMessageSegments(segments, false, id, submitted, onSubmitted)} />
|
|
1075
|
+
)}
|
|
1076
|
+
|
|
1077
|
+
{showConversationDetails && props.renderConversationDetails && (
|
|
1078
|
+
<section id="sandbox-conversation-details" className="agent-playground-conversation-details" aria-label={sandboxText(locale, "对话与轨迹")}>
|
|
1079
|
+
<button type="button" className="agent-playground-details-back" onClick={() => setShowConversationDetails(false)}><MessageSquare size={14} />{sandboxText(locale, "返回会话")}</button>
|
|
1080
|
+
{props.renderConversationDetails({ sessionKey, canExecute, connectionId: connectionRef.current.connectionId })}
|
|
1081
|
+
</section>
|
|
1082
|
+
)}
|
|
1083
|
+
|
|
1084
|
+
{/* Keep the live editor mounted while reading details so its draft survives. */}
|
|
1085
|
+
<section className="agent-playground-conversation" hidden={showConversationDetails} aria-label={sandboxText(locale, "Agent 对话")}>
|
|
1086
|
+
<div className="agent-playground-message-scroll" aria-busy={history.loading}>
|
|
1087
|
+
{history.hasMore || history.error ? <div className="agent-playground-history-navigation">
|
|
1088
|
+
{history.error ? <p role="alert">{history.error} <button type="button" disabled={history.loading} onClick={() => void history.refresh()}>{sandboxText(locale, '重试')}</button></p> : null}
|
|
1089
|
+
{history.hasMore ? <button type="button" disabled={history.loading} onClick={() => void history.loadEarlier()}>{sandboxText(locale, '加载更早记录')}</button> : null}
|
|
1090
|
+
</div> : null}
|
|
867
1091
|
{channelMessages.length === 0 ? (
|
|
868
1092
|
<div className="agent-playground-empty">
|
|
869
1093
|
<span className="agent-playground-empty-mark"><Sparkles size={24} /></span>
|
|
@@ -877,18 +1101,20 @@ export default function Sandbox() {
|
|
|
877
1101
|
) : (
|
|
878
1102
|
<div className="agent-playground-message-list">
|
|
879
1103
|
{channelMessages.map((msg) => {
|
|
880
|
-
|
|
1104
|
+
if (msg.recalledMessageId) return <p key={msg.id} className="agent-playground-history-notice">{sandboxText(locale, '消息已撤回')}</p>
|
|
1105
|
+
const isApproval = msg.type === 'received' && msg.interactionReadOnly !== true && msg.content.some((segment) => segment.type === 'keyboard')
|
|
881
1106
|
return (
|
|
882
|
-
<React.Fragment key={msg.id}>
|
|
1107
|
+
<React.Fragment key={JSON.stringify([msg.channelType, msg.channelId, msg.type, msg.id])}>
|
|
883
1108
|
<article className={cn("agent-playground-message", msg.type === 'sent' ? "is-user" : "is-agent", isApproval && "is-approval")}>
|
|
884
1109
|
<span className="agent-playground-message-avatar">{msg.type === 'received' ? <Bot size={16} /> : <User size={16} />}</span>
|
|
885
1110
|
<div className="agent-playground-message-main">
|
|
886
1111
|
<div className="agent-playground-message-meta">
|
|
887
|
-
<strong>{isApproval ? sandboxText(locale, "需要你的确认") : msg.type === 'received' ? endpointId : sandboxText(locale, "你")}</strong>
|
|
1112
|
+
<strong>{isApproval ? sandboxText(locale, "需要你的确认") : msg.type === 'received' ? endpointId : msg.senderId === connectionRef.current.ownerId ? sandboxText(locale, "你") : msg.senderName || msg.senderId}</strong>
|
|
888
1113
|
{isApproval && <span>approval required</span>}
|
|
1114
|
+
{msg.recalled && <span>{sandboxText(locale, '已撤回')}</span>}
|
|
889
1115
|
<time>{new Date(msg.timestamp).toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' })}</time>
|
|
890
1116
|
</div>
|
|
891
|
-
<div className="agent-playground-message-content">{renderMessageSegments(msg.content, msg.type === 'sent', msg.id, msg.interactionResolved === true)}</div>
|
|
1117
|
+
<div className="agent-playground-message-content">{renderMessageSegments(msg.content, msg.type === 'sent', msg.id, msg.interactionResolved === true, undefined, msg.interactionReadOnly !== true)}</div>
|
|
892
1118
|
</div>
|
|
893
1119
|
</article>
|
|
894
1120
|
{currentTaskMessage?.id === msg.id && inlineRunCard}
|
|
@@ -903,7 +1129,7 @@ export default function Sandbox() {
|
|
|
903
1129
|
</section>
|
|
904
1130
|
|
|
905
1131
|
{/* Input area */}
|
|
906
|
-
<section className="agent-playground-composer" aria-label={sandboxText(locale, "任务输入")}>
|
|
1132
|
+
<section className="agent-playground-composer" hidden={showConversationDetails} aria-label={sandboxText(locale, "任务输入")}>
|
|
907
1133
|
{/* Toolbar */}
|
|
908
1134
|
<div className="flex gap-2 items-center flex-wrap">
|
|
909
1135
|
<button type="button" className={cn("h-8 w-8 rounded-md flex items-center justify-center border transition-colors", showFacePicker ? "bg-primary text-primary-foreground" : "hover:bg-accent")}
|
|
@@ -1017,7 +1243,7 @@ export default function Sandbox() {
|
|
|
1017
1243
|
<button
|
|
1018
1244
|
className="inline-flex items-center gap-1.5 h-10 px-4 rounded-md bg-primary text-primary-foreground text-sm font-medium disabled:opacity-50 transition-colors hover:bg-primary/90"
|
|
1019
1245
|
onClick={() => { const c = editorRef.current?.getContent(); if (c) handleSendMessage(c.text, c.segments) }}
|
|
1020
|
-
disabled={!canExecute || !hasRenderableSegments(previewSegments)}>
|
|
1246
|
+
disabled={!canExecute || directoryStatus.mode === 'loading' || !hasRenderableSegments(previewSegments)}>
|
|
1021
1247
|
<Send size={16} /> {sandboxText(locale, "发送")}</button>
|
|
1022
1248
|
</div>
|
|
1023
1249
|
|
|
@@ -1029,7 +1255,7 @@ export default function Sandbox() {
|
|
|
1029
1255
|
</section>
|
|
1030
1256
|
</main>
|
|
1031
1257
|
|
|
1032
|
-
<aside className={cn("agent-playground-inspector", showInspector && "show")} aria-label={sandboxText(locale, "运行检查器")}>
|
|
1258
|
+
<aside id="sandbox-run-inspector" className={cn("agent-playground-inspector", showInspector && "show")} hidden={!showInspector} aria-hidden={!showInspector} aria-label={sandboxText(locale, "运行检查器")}>
|
|
1033
1259
|
<div className="agent-playground-inspector-head">
|
|
1034
1260
|
<div><span>Run inspector</span><h2>{sandboxText(locale, "运行检查器")}</h2></div>
|
|
1035
1261
|
<div>
|
|
@@ -1091,10 +1317,9 @@ export default function Sandbox() {
|
|
|
1091
1317
|
|
|
1092
1318
|
<section className="agent-playground-inspector-section agent-playground-trace-section">
|
|
1093
1319
|
<div className="agent-playground-inspector-title"><span>{sandboxText(locale, "最近执行")}</span><small>2s sync</small></div>
|
|
1320
|
+
{traceNotice && <div className="agent-playground-trace-notice" role="alert"><CircleAlert size={16} /><span>{traceNotice}</span></div>}
|
|
1094
1321
|
{traceLoading && !trace ? (
|
|
1095
1322
|
<div className="agent-playground-trace-loading"><i /><i /><i /></div>
|
|
1096
|
-
) : traceNotice && !trace?.events.length ? (
|
|
1097
|
-
<div className="agent-playground-trace-notice"><CircleAlert size={16} /><span>{traceNotice}</span></div>
|
|
1098
1323
|
) : recentTraceEvents.length ? (
|
|
1099
1324
|
<div className="agent-playground-trace-list">
|
|
1100
1325
|
{recentTraceEvents.map((event) => {
|
|
@@ -1133,6 +1358,11 @@ export default function Sandbox() {
|
|
|
1133
1358
|
{expanded && (
|
|
1134
1359
|
<div className="agent-playground-artifact-detail">
|
|
1135
1360
|
{artifact.path && <code>{artifact.path}</code>}
|
|
1361
|
+
{canExecute && artifact.projectFilePath && (
|
|
1362
|
+
<a href={`/files?${new URLSearchParams({ path: artifact.projectFilePath })}`} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-primary hover:underline">
|
|
1363
|
+
<ExternalLink size={13} />{sandboxText(locale, "打开当前文件")}
|
|
1364
|
+
</a>
|
|
1365
|
+
)}
|
|
1136
1366
|
{artifact.diff ? <pre>{artifact.diff}</pre> : <pre>{artifact.detail || sandboxText(locale, "暂无输出")}</pre>}
|
|
1137
1367
|
<footer><span>{artifact.durationMs === undefined ? sandboxText(locale, "等待结果") : `${artifact.durationMs.toLocaleString(locale)} ms`}</span><code>{artifact.turnId.slice(0, 12)}</code></footer>
|
|
1138
1368
|
</div>
|
|
@@ -1145,7 +1375,7 @@ export default function Sandbox() {
|
|
|
1145
1375
|
</section>
|
|
1146
1376
|
</div>
|
|
1147
1377
|
|
|
1148
|
-
<a className="agent-playground-studio-link" href={
|
|
1378
|
+
<a className="agent-playground-studio-link" href={agentSessionsPath(sessionKey)}><span><ExternalLink size={15} />{sandboxText(locale, "对话与轨迹")}</span><code>{sessionKey}</code></a>
|
|
1149
1379
|
</aside>
|
|
1150
1380
|
{showInspector && <div className="agent-playground-inspector-overlay" onClick={() => setShowInspector(false)} />}
|
|
1151
1381
|
</section>
|