@zhin.js/adapter-sandbox 1.1.33 → 1.1.35

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.
@@ -11,14 +11,17 @@ import {
11
11
  import { buildSandboxWebSocketUrl, captureSandboxRequestContext, createSandboxMessageId, submitSandboxFrame, SANDBOX_SCOPED_PROTOCOL, type SandboxRequestContext } from './sandboxTransport.js';
12
12
  import { createWorkspaceDirectoryController, type DirectoryStatus } from './workspaceDirectoryState.js';
13
13
  import type { SandboxWorkspaceScope } from './workspaceDirectory.js';
14
+ import { isApprovalPrompt, readSandboxCommandHints, type SandboxCommandHints } from './composerCommands.js';
15
+ import { ensureSandboxChatIdentity, readServerSpeaker, wantsAsMe, type SandboxServerSpeaker, type SandboxSpeakerMode } from './chatIdentity.js';
16
+ import { isJsxNode, segmentFallbackText, segmentPreviewText } from './segmentFallback.js';
14
17
  import {
15
18
  User, Bot, Users, Trash2, Send, Hash, MessageSquare,
16
- Wifi, WifiOff, Smile, Image, X, Check, Info, Search,
19
+ Wifi, WifiOff, Smile, Image, X, Check, Search,
17
20
  Video, Music, Plus, PanelRight, ExternalLink, RefreshCw,
18
21
  Sparkles, Activity, Wrench, Coins, CircleAlert, Gauge,
19
22
  SlidersHorizontal, FolderOpen, ShieldCheck, Network,
20
23
  Square, RotateCcw, FileDiff, Terminal, FlaskConical, ChevronDown,
21
- FileDown, ListChecks,
24
+ FileDown, ListChecks, MoreHorizontal, Keyboard, AtSign,
22
25
  } from 'lucide-react';
23
26
  import RichTextEditor, { type RichTextEditorRef } from './RichTextEditor.js';
24
27
  import HtmlMessage from './HtmlMessage.js';
@@ -61,6 +64,12 @@ export interface SandboxPageProps {
61
64
  readonly renderConversationDetails?: (context: { readonly sessionKey: string; readonly canExecute: boolean; readonly connectionId?: string }) => React.ReactNode
62
65
  }
63
66
 
67
+ /** ADR 0060 §5.4: the simulated role is a platform standing (群主 / 管理员 / 成员), never a zhin role. */
68
+ function platformStandingLabel(role: 'master' | 'admin' | 'member', locale: string): string {
69
+ if (locale === 'en') return role === 'master' ? 'group owner' : role === 'admin' ? 'group admin' : 'member'
70
+ return role === 'master' ? '群主' : role === 'admin' ? '群管理员' : '成员'
71
+ }
72
+
64
73
  export default function Sandbox(props: SandboxPageProps = {}) {
65
74
  const [locale, setLocale] = useState<SandboxLocale>('zh-CN')
66
75
  const localeRef = useRef<SandboxLocale>('zh-CN')
@@ -97,7 +106,7 @@ export default function Sandbox(props: SandboxPageProps = {}) {
97
106
  const [faceSearchQuery, setFaceSearchQuery] = useState('')
98
107
  const atSuggestions = [
99
108
  { id: 'actor-owner', name: sandboxText(locale, "当前用户") }, { id: 'actor-reviewer', name: sandboxText(locale, "审阅者") },
100
- { id: 'actor-operator', name: sandboxText(locale, "协作者") }, { id: 'actor-bot', name: 'Sandbox Agent' }
109
+ { id: 'actor-operator', name: sandboxText(locale, "协作者") }, { id: endpointId, name: endpointId }
101
110
  ]
102
111
  const [previewSegments, setPreviewSegments] = useState<MessageSegment[]>([])
103
112
  const [composerMode, setComposerMode] = useState<'write' | 'preview'>('write')
@@ -109,7 +118,19 @@ export default function Sandbox(props: SandboxPageProps = {}) {
109
118
  const [senderId, setSenderId] = useState('dev-user')
110
119
  const [senderName, setSenderName] = useState('Developer')
111
120
  const [senderRole, setSenderRole] = useState<'master' | 'admin' | 'member'>('master')
121
+ // ADR 0060 §5.4: what the server resolved for the last message sent (speaker, zhin role, Agent trust tier).
122
+ const [serverRole, setServerRole] = useState<SandboxServerSpeaker | null>(null)
123
+ // 「以我的聊天身份发言」 (default) vs a simulated sender; only a signed-in Console user can speak as themselves.
124
+ const [speakerMode, setSpeakerMode] = useState<SandboxSpeakerMode>('me')
125
+ const [consoleUser, setConsoleUser] = useState(false)
126
+ const [identitySetup, setIdentitySetup] = useState<{ status: 'idle' | 'busy' | 'done' | 'unsupported' } | { status: 'failed'; message: string }>({ status: 'idle' })
127
+ const asMe = wantsAsMe(speakerMode, consoleUser)
112
128
  const [showSenderSettings, setShowSenderSettings] = useState(false)
129
+ /** Runbar overflow: identity, run settings, inspector and clear live here (#1250). */
130
+ const [showMoreActions, setShowMoreActions] = useState(false)
131
+ /** Live binding of the current socket; drives the Host-provided quick commands. */
132
+ const [readyConnectionId, setReadyConnectionId] = useState<string | undefined>(undefined)
133
+ const [commandHints, setCommandHints] = useState<SandboxCommandHints | null>(null)
113
134
  const [showNewSession, setShowNewSession] = useState(false)
114
135
  const [newSessionName, setNewSessionName] = useState('')
115
136
  const [newSessionScope, setNewSessionScope] = useState<SandboxScope>('private')
@@ -232,6 +253,19 @@ export default function Sandbox(props: SandboxPageProps = {}) {
232
253
 
233
254
  useEffect(() => { fetchFaceList() }, [])
234
255
 
256
+ // Quick commands come from the Host's command index and the endpoint's commandPrefix;
257
+ // without an answer the composer offers none rather than guessing.
258
+ useEffect(() => {
259
+ setCommandHints(null)
260
+ if (!readyConnectionId || !canExecute) return
261
+ const controller = new AbortController()
262
+ void readSandboxCommandHints(readyConnectionId, { type: activeChannel.type, id: activeChannel.id }, locale, controller.signal,
263
+ socketRequestContextRef.current ?? undefined).then((hints) => {
264
+ if (!controller.signal.aborted) setCommandHints(hints)
265
+ })
266
+ return () => controller.abort()
267
+ }, [readyConnectionId, canExecute, activeChannel.type, activeChannel.id, locale])
268
+
235
269
  const subscribeToScene = (scene: Pick<Channel, 'id' | 'type'>) => {
236
270
  // Old Hosts parse unknown JSON as chat, so control frames require this explicit handshake.
237
271
  if (connectionRef.current.protocol !== SANDBOX_SCOPED_PROTOCOL || !connectionRef.current.canExecute) return
@@ -245,6 +279,8 @@ export default function Sandbox(props: SandboxPageProps = {}) {
245
279
  shellIsolation?: { available?: boolean; provider?: string; message?: string }; timestamp: number;
246
280
  messageId?: string; bot?: string; protocol?: string; connectionId?: string; direction?: string; senderId?: string;
247
281
  senderName?: string; senderRole?: 'master' | 'admin' | 'member';
282
+ senderChatRole?: string; senderTrustLevel?: string; consoleUser?: boolean;
283
+ simulated?: boolean; displaySenderId?: string; asMeUnavailable?: string;
248
284
  revision?: number; streaming?: boolean;
249
285
  conversation?: { type: Channel['type']; id: string };
250
286
  }) => {
@@ -266,7 +302,9 @@ export default function Sandbox(props: SandboxPageProps = {}) {
266
302
  endpointIdRef.current = data.endpoint || data.bot || 'sandbox-bot'
267
303
  setBotName(endpointIdRef.current)
268
304
  connectionRef.current = { protocol: data.protocol, connectionId: data.connectionId, ownerId: data.id, canExecute: data.canExecute !== false }
305
+ setReadyConnectionId(data.connectionId)
269
306
  setCanExecute(data.canExecute !== false)
307
+ setConsoleUser(data.consoleUser === true)
270
308
  setTransportNotice(data.canExecute === false ? sandboxText(locale, "当前 Token 只有演示权限,任务运行已禁用。") : null)
271
309
  if (data.shellIsolation) {
272
310
  setShellIsolation({
@@ -310,6 +348,8 @@ export default function Sandbox(props: SandboxPageProps = {}) {
310
348
  const channelType: Channel['type'] = data.conversation?.type ?? (data.type === 'group' || data.type === 'channel' ? data.type : 'private')
311
349
  const sceneId = data.conversation?.id ?? data.id
312
350
  const isInput = data.direction === 'inbound'
351
+ const speaker = isInput ? readServerSpeaker(data as Record<string, unknown>) : null
352
+ if (speaker) setServerRole(speaker)
313
353
  // Interactive choices are transport inputs, not another chat turn or an approval result.
314
354
  if (isInput && content.every((segment) => segment.type === 'action')) return
315
355
  const channelName = channelType === 'private'
@@ -332,7 +372,7 @@ export default function Sandbox(props: SandboxPageProps = {}) {
332
372
  setMessages((prev) => mergePlaygroundMessage(prev, {
333
373
  id: data.messageId ?? createSandboxMessageId(), type: isInput ? 'sent' : 'received', channelType,
334
374
  interactionReadOnly: false,
335
- channelId: sceneId, channelName, senderId: isInput ? data.senderId || connectionRef.current.ownerId || 'owner' : 'endpoint',
375
+ channelId: sceneId, channelName, senderId: isInput ? data.displaySenderId || data.senderId || connectionRef.current.ownerId || 'owner' : 'endpoint',
336
376
  senderName: isInput ? (typeof data.senderName === 'string' && data.senderName.trim() ? data.senderName.trim() : sandboxText(locale, "当前用户")) : data.bot || endpointIdRef.current, content, timestamp: data.timestamp,
337
377
  ...(Number.isSafeInteger(data.revision) && data.revision! > 0 ? { revision: data.revision } : {}),
338
378
  ...(typeof data.streaming === 'boolean' ? { streaming: data.streaming } : {}),
@@ -347,7 +387,7 @@ export default function Sandbox(props: SandboxPageProps = {}) {
347
387
  const resolvedSenderName = senderName.trim() || sandboxText(localeRef.current, "测试用户")
348
388
  if (!submitSandboxFrame(wsRef.current, {
349
389
  type: scene.type, id: scene.id, messageId: createSandboxMessageId(), content: segments,
350
- senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole,
390
+ senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole, ...(asMe ? { asMe: true } : {}),
351
391
  agentRun: scene.runConfig, timestamp: Date.now(),
352
392
  })) {
353
393
  setTransportNotice(sandboxText(localeRef.current, "Sandbox 连接尚未就绪,审批选择未发送。"))
@@ -579,12 +619,19 @@ export default function Sandbox(props: SandboxPageProps = {}) {
579
619
  if (typeof segment === 'string') {
580
620
  return <MarkdownContent key={index} text={segment} className={isSent ? 'zhin-markdown--inverse' : undefined} />
581
621
  }
622
+ // Unrendered JSX (or a segment without data) is read as text with `[button]` labels, never as raw JSON.
623
+ if (isJsxNode(segment) || !segment.data || typeof segment.data !== 'object') {
624
+ const fallback = segmentFallbackText(segment)
625
+ return fallback
626
+ ? <MarkdownContent key={index} text={fallback} className={isSent ? 'zhin-markdown--inverse' : undefined} />
627
+ : <span key={index} className="sandbox-segment-note">[{String(segment.type)}]</span>
628
+ }
582
629
  const d = segment.data as Record<string, unknown>
583
630
  switch (segment.type) {
584
631
  case 'text':
585
632
  case 'markdown':
586
633
  case 'md':
587
- return <MarkdownContent key={index} text={String(d.text ?? d.content ?? '')} className={isSent ? 'zhin-markdown--inverse' : undefined} />
634
+ return <MarkdownContent key={index} text={typeof d.text === 'string' ? d.text : typeof d.content === 'string' ? d.content : segmentFallbackText(segment) ?? ''} className={isSent ? 'zhin-markdown--inverse' : undefined} />
588
635
  case 'html':
589
636
  return <HtmlMessage locale={locale} key={index} html={String(d.html ?? d.content ?? d.text ?? '')} />
590
637
  case 'code':
@@ -831,8 +878,12 @@ export default function Sandbox(props: SandboxPageProps = {}) {
831
878
  </div>
832
879
  )
833
880
  }
834
- default:
835
- return <span key={index} className="sandbox-segment-note">[{segment.type}]</span>
881
+ default: {
882
+ const fallback = segmentFallbackText(segment)
883
+ return fallback
884
+ ? <MarkdownContent key={index} text={fallback} className={isSent ? 'zhin-markdown--inverse' : undefined} />
885
+ : <span key={index} className="sandbox-segment-note">[{segment.type}]</span>
886
+ }
836
887
  }
837
888
  })
838
889
  }
@@ -849,7 +900,7 @@ export default function Sandbox(props: SandboxPageProps = {}) {
849
900
  }
850
901
  if (!submitSandboxFrame(wsRef.current, {
851
902
  type: scene.type, id: scene.id, messageId: newMessage.id, content: segments,
852
- senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole,
903
+ senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole, ...(asMe ? { asMe: true } : {}),
853
904
  agentRun: scene.runConfig, timestamp: newMessage.timestamp,
854
905
  })) {
855
906
  setTransportNotice(sandboxText(localeRef.current, "Sandbox 连接尚未就绪,消息未发送。"))
@@ -1036,6 +1087,7 @@ export default function Sandbox(props: SandboxPageProps = {}) {
1036
1087
  .sandbox-role-badge.is-master { background: rgba(245,158,11,0.18); color: #d97706; }
1037
1088
  .sandbox-role-badge.is-admin { background: rgba(59,130,246,0.18); color: #2563eb; }
1038
1089
  .sandbox-role-badge.is-member { background: rgba(16,185,129,0.16); color: #059669; }
1090
+ .sandbox-role-badge.is-zhin { text-transform: none; background: rgba(139,92,246,0.16); color: #7c3aed; }
1039
1091
  .sandbox-role-switcher { display: inline-flex; gap: 4px; }
1040
1092
  .sandbox-role-option { padding: 4px 10px; border-radius: 6px; border: 1px solid rgba(148,163,184,0.3); font-size: 12px; cursor: pointer; background: transparent; color: inherit; text-transform: capitalize; }
1041
1093
  .sandbox-role-option.active { font-weight: 600; border-color: currentColor; background: rgba(59,130,246,0.12); }
@@ -1149,29 +1201,92 @@ export default function Sandbox(props: SandboxPageProps = {}) {
1149
1201
  {props.renderConversationDetails
1150
1202
  ? <button type="button" disabled={!canExecute} aria-expanded={showConversationDetails} aria-controls="sandbox-conversation-details" onClick={() => setShowConversationDetails((visible) => !visible)}><ListChecks size={14} />{sandboxText(locale, "对话与轨迹")}</button>
1151
1203
  : <a href={agentSessionsPath(sessionKey)}><ExternalLink size={14} />{sandboxText(locale, "对话与轨迹")}</a>}
1152
- <button
1153
- type="button"
1154
- className={cn("sandbox-sender-trigger", showSenderSettings && "active")}
1155
- aria-expanded={showSenderSettings}
1156
- onClick={() => setShowSenderSettings((visible) => !visible)}
1157
- title={locale === 'en' ? 'Simulated sender identity & role' : '模拟发送者身份与角色'}
1158
- >
1159
- <User size={14} />
1160
- <span>{senderName.trim() || senderId.trim() || 'dev-user'}</span>
1161
- <em className={cn("sandbox-role-badge", `is-${senderRole}`)}>{senderRole}</em>
1162
- </button>
1163
- <button type="button" className={cn(showRunSettings && 'active')} aria-expanded={showRunSettings} onClick={() => setShowRunSettings((visible) => !visible)} aria-label={sandboxText(locale, "配置运行环境")}><SlidersHorizontal size={16} /></button>
1164
- <button type="button" aria-expanded={showInspector} aria-controls="sandbox-run-inspector" onClick={() => setShowInspector(!showInspector)} aria-label={sandboxText(locale, "切换运行检查器")}><PanelRight size={16} /></button>
1165
- <button type="button" onClick={() => setConfirmClear(true)} aria-label={sandboxText(locale, "清空当前会话")}><Trash2 size={15} /></button>
1204
+ <div className="sandbox-more">
1205
+ <button
1206
+ type="button"
1207
+ className={cn("sandbox-more-trigger", (showMoreActions || showSenderSettings || showRunSettings) && 'active')}
1208
+ aria-haspopup="menu"
1209
+ aria-expanded={showMoreActions}
1210
+ onClick={() => setShowMoreActions((visible) => !visible)}
1211
+ aria-label={sandboxText(locale, "更多操作")}
1212
+ title={sandboxText(locale, "更多操作")}
1213
+ >
1214
+ <MoreHorizontal size={16} />
1215
+ </button>
1216
+ {showMoreActions && (
1217
+ <>
1218
+ <div className="sandbox-more-backdrop" onClick={() => setShowMoreActions(false)} />
1219
+ <div className="sandbox-more-menu" role="menu" aria-label={sandboxText(locale, "更多操作")}>
1220
+ <button type="button" role="menuitemcheckbox" aria-checked={showSenderSettings}
1221
+ onClick={() => { setShowSenderSettings((visible) => !visible); setShowMoreActions(false) }}>
1222
+ <User size={14} />
1223
+ <span>{sandboxText(locale, "模拟发送者")}</span>
1224
+ <em className={cn("sandbox-role-badge", `is-${senderRole}`)} title={locale === 'en' ? 'Simulated platform standing (not a zhin role)' : '模拟的平台身份(不是 zhin 角色)'}>{asMe ? sandboxText(locale, "我的聊天身份") : (senderName.trim() || senderId.trim() || 'dev-user')} · {platformStandingLabel(senderRole, locale)}</em>
1225
+ {serverRole && (serverRole.simulated
1226
+ ? <em className="sandbox-role-badge is-simulated" title={sandboxText(locale, "客户端自填的发送者不解析 zhin 角色")}>{sandboxText(locale, "模拟身份,无角色")}</em>
1227
+ : <em className="sandbox-role-badge is-zhin" title={locale === 'en' ? 'Resolved by the server: zhin role · Agent trust tier' : '服务端解析:zhin 角色 · Agent 信任档位'}>
1228
+ {`zhin: ${serverRole.chatRole ?? (locale === 'en' ? 'none' : '无')} · ${serverRole.trustLevel}`}
1229
+ </em>)}
1230
+ </button>
1231
+ <button type="button" role="menuitemcheckbox" aria-checked={showRunSettings}
1232
+ onClick={() => { setShowRunSettings((visible) => !visible); setShowMoreActions(false) }}>
1233
+ <SlidersHorizontal size={14} /><span>{sandboxText(locale, "配置运行环境")}</span>
1234
+ </button>
1235
+ <button type="button" role="menuitemcheckbox" aria-checked={showInspector} aria-controls="sandbox-run-inspector"
1236
+ onClick={() => { setShowInspector(!showInspector); setShowMoreActions(false) }}>
1237
+ <PanelRight size={14} /><span>{sandboxText(locale, "切换运行检查器")}</span>
1238
+ </button>
1239
+ <button type="button" role="menuitem" className="is-danger"
1240
+ onClick={() => { setConfirmClear(true); setShowMoreActions(false) }}>
1241
+ <Trash2 size={14} /><span>{sandboxText(locale, "清空当前会话")}</span>
1242
+ </button>
1243
+ </div>
1244
+ </>
1245
+ )}
1246
+ </div>
1166
1247
  </div>
1167
1248
  </header>
1168
1249
 
1169
1250
  {showSenderSettings && (
1170
1251
  <section className="agent-playground-run-settings sandbox-sender-settings" aria-label={locale === 'en' ? 'Simulated sender' : '模拟发送者配置'}>
1252
+ <div className="sandbox-speaker-mode">
1253
+ <label className="sandbox-speaker-toggle">
1254
+ <input type="checkbox" checked={speakerMode === 'me'} disabled={!consoleUser}
1255
+ onChange={(event) => setSpeakerMode(event.target.checked ? 'me' : 'simulated')} />
1256
+ <span>{sandboxText(locale, "以我的聊天身份发言")}</span>
1257
+ </label>
1258
+ <p>
1259
+ {!consoleUser
1260
+ ? sandboxText(locale, "当前连接没有 Console 用户(未登录或 --standalone),所有消息都按模拟身份处理,不解析 zhin 角色。")
1261
+ : asMe
1262
+ ? sandboxText(locale, "以链接到你 Console 账号的聊天身份发言,角色按你的聊天角色解析。")
1263
+ : sandboxText(locale, "模拟身份,无角色:自填的发送者 ID 只用于模拟别人,不解析 zhin 角色。")}
1264
+ </p>
1265
+ {asMe && serverRole?.asMeUnavailable === 'needs-global-iam' && (
1266
+ <div className="sandbox-speaker-setup" role="status">
1267
+ <span>{sandboxText(locale, "链接到你的聊天身份持有全局角色,以它发言需要全局 iam.manage 权限;上一条消息按模拟身份(无角色)发送。")}</span>
1268
+ </div>
1269
+ )}
1270
+ {asMe && serverRole?.asMeUnavailable === 'no-identity' && (
1271
+ <div className="sandbox-speaker-setup" role="status">
1272
+ <span>{sandboxText(locale, "你在 Sandbox 上还没有聊天身份,上一条消息按模拟身份发送。")}</span>
1273
+ <button type="button" disabled={identitySetup.status === 'busy'} onClick={() => {
1274
+ setIdentitySetup({ status: 'busy' })
1275
+ void ensureSandboxChatIdentity(socketRequestContextRef.current ?? undefined).then((result) => {
1276
+ setIdentitySetup(result.status === 'ok' ? { status: 'done' } : result)
1277
+ })
1278
+ }}>{sandboxText(locale, "在 Sandbox 上创建我的聊天身份")}</button>
1279
+ {identitySetup.status === 'done' && <em>{sandboxText(locale, "已创建,下一条消息生效。")}</em>}
1280
+ {identitySetup.status === 'unsupported' && <em>{sandboxText(locale, "当前 Host 不支持,请升级。")}</em>}
1281
+ {identitySetup.status === 'failed' && <em>{identitySetup.message}</em>}
1282
+ </div>
1283
+ )}
1284
+ </div>
1171
1285
  <label>
1172
- <span><User size={14} />{locale === 'en' ? 'Sender ID' : '发送者 ID'}</span>
1286
+ <span><User size={14} />{locale === 'en' ? 'Sender ID (simulated, no role)' : '发送者 ID(模拟身份,无角色)'}</span>
1173
1287
  <input
1174
1288
  value={senderId}
1289
+ disabled={asMe}
1175
1290
  onChange={(event) => setSenderId(event.target.value)}
1176
1291
  placeholder="dev-user"
1177
1292
  spellCheck={false}
@@ -1181,14 +1296,15 @@ export default function Sandbox(props: SandboxPageProps = {}) {
1181
1296
  <span>{locale === 'en' ? 'Sender Name' : '发送者昵称'}</span>
1182
1297
  <input
1183
1298
  value={senderName}
1299
+ disabled={asMe}
1184
1300
  onChange={(event) => setSenderName(event.target.value)}
1185
1301
  placeholder="Developer"
1186
1302
  spellCheck={false}
1187
1303
  />
1188
1304
  </label>
1189
1305
  <label>
1190
- <span><ShieldCheck size={14} />{locale === 'en' ? 'Sender Role' : '角色权限'}</span>
1191
- <div className="sandbox-role-switcher" role="group" aria-label={locale === 'en' ? 'Sender role' : '角色权限'}>
1306
+ <span><ShieldCheck size={14} />{locale === 'en' ? 'Platform standing (not a zhin role)' : '平台身份(不是 zhin 角色)'}</span>
1307
+ <div className="sandbox-role-switcher" role="group" aria-label={locale === 'en' ? 'Platform standing' : '平台身份'}>
1192
1308
  {(['member', 'admin', 'master'] as const).map((role) => (
1193
1309
  <button
1194
1310
  key={role}
@@ -1197,13 +1313,13 @@ export default function Sandbox(props: SandboxPageProps = {}) {
1197
1313
  className={cn("sandbox-role-option", `is-${role}`, senderRole === role && "active")}
1198
1314
  onClick={() => setSenderRole(role)}
1199
1315
  >
1200
- {role}
1316
+ {platformStandingLabel(role, locale)}
1201
1317
  </button>
1202
1318
  ))}
1203
1319
  </div>
1204
1320
  </label>
1205
1321
  <div className="sandbox-sender-presets">
1206
- <button type="button" onClick={() => { setSenderId('dev-user'); setSenderName('Developer'); setSenderRole('master') }}>Master (dev-user)</button>
1322
+ <button type="button" onClick={() => { setSenderId('dev-user'); setSenderName('Developer'); setSenderRole('master') }}>{locale === 'en' ? 'Group owner (platform standing, dev-user)' : '群主(平台身份,dev-user)'}</button>
1207
1323
  <button type="button" onClick={() => { setSenderId('admin-user'); setSenderName('Admin'); setSenderRole('admin') }}>Admin (admin-user)</button>
1208
1324
  <button type="button" onClick={() => { setSenderId('member-user'); setSenderName('Member'); setSenderRole('member') }}>Member (member-user)</button>
1209
1325
  </div>
@@ -1328,7 +1444,12 @@ export default function Sandbox(props: SandboxPageProps = {}) {
1328
1444
  {history.error ? <p role="alert">{history.error} <button type="button" disabled={history.loading} onClick={() => void history.refresh()}>{sandboxText(locale, '重试')}</button></p> : null}
1329
1445
  {history.hasMore ? <button type="button" disabled={history.loading} onClick={() => void history.loadEarlier()}>{sandboxText(locale, '加载更早记录')}</button> : null}
1330
1446
  </div> : null}
1331
- {channelMessages.length === 0 ? (
1447
+ {channelMessages.length === 0 && history.loading ? (
1448
+ // Same full-height box as the empty state, so loaded history does not move the composer under the cursor.
1449
+ <div className="agent-playground-empty" role="status">
1450
+ <p>{sandboxText(locale, "正在加载会话记录…")}</p>
1451
+ </div>
1452
+ ) : channelMessages.length === 0 ? (
1332
1453
  <div className="agent-playground-empty">
1333
1454
  <span className="agent-playground-empty-mark"><Sparkles size={24} /></span>
1334
1455
  <div><h2>{sandboxText(locale, "开始一次可观察的 Agent 运行")}</h2><p>{sandboxText(locale, "发送任务后,回复、工具调用、Token 与异常会在同一会话上下文中关联。")}</p></div>
@@ -1342,7 +1463,7 @@ export default function Sandbox(props: SandboxPageProps = {}) {
1342
1463
  <div className="agent-playground-message-list">
1343
1464
  {channelMessages.map((msg) => {
1344
1465
  if (msg.recalledMessageId) return <p key={msg.id} className="agent-playground-history-notice">{sandboxText(locale, '消息已撤回')}</p>
1345
- const isApproval = msg.type === 'received' && msg.interactionReadOnly !== true && msg.content.some((segment) => segment.type === 'keyboard')
1466
+ const isApproval = isApprovalPrompt(msg)
1346
1467
  return (
1347
1468
  <React.Fragment key={JSON.stringify([msg.channelType, msg.channelId, msg.type, msg.id])}>
1348
1469
  <article className={cn("agent-playground-message", msg.type === 'sent' ? "is-user" : "is-agent", isApproval && "is-approval")}>
@@ -1388,14 +1509,24 @@ export default function Sandbox(props: SandboxPageProps = {}) {
1388
1509
  onClick={() => { setMediaPanel((p) => (p === 'audio' ? null : 'audio')); setShowFacePicker(false) }} title={sandboxText(locale, "插入音频 URL")}>
1389
1510
  <Music size={16} />
1390
1511
  </button>
1512
+ <button type="button" className="sandbox-tool-button"
1513
+ onClick={() => { editorRef.current?.insertAt(endpointId, endpointId); setShowFacePicker(false); setMediaPanel(null) }}
1514
+ title={sandboxText(locale, "@ 机器人(插入 [@{0}])", [endpointId])} aria-label={sandboxText(locale, "@ 机器人")}>
1515
+ <AtSign size={16} />
1516
+ </button>
1391
1517
  <div className="sandbox-quick-commands" role="toolbar" aria-label={locale === 'en' ? 'Quick commands' : '快捷命令'}>
1392
- {['/help', 'help', 'ping', '/status'].map((cmd) => (
1518
+ {(commandHints?.quick ?? []).map((cmd) => (
1393
1519
  <button
1394
1520
  key={cmd}
1395
1521
  type="button"
1396
1522
  className="sandbox-command-chip"
1397
1523
  disabled={!canExecute || directoryStatus.mode === 'loading'}
1398
- onClick={() => runPrompt(cmd)}
1524
+ // Keyboard-reachable (WCAG 2.1.1). A mouse click must not keep focus on the chip,
1525
+ // and the prefill moves focus into the composer, so Enter sends the draft
1526
+ // rather than re-activating the chip after a late layout shift (#1250).
1527
+ onMouseDown={(event) => event.preventDefault()}
1528
+ // Pre-fill the composer (never overwriting a draft); sending stays an explicit Enter / Send.
1529
+ onClick={() => editorRef.current?.setText(cmd)}
1399
1530
  >
1400
1531
  <Terminal size={11} />
1401
1532
  <span>{cmd}</span>
@@ -1512,11 +1643,22 @@ export default function Sandbox(props: SandboxPageProps = {}) {
1512
1643
  <Send size={16} /> {sandboxText(locale, "发送")}</button>
1513
1644
  </div>
1514
1645
 
1515
- {/* Hints */}
1516
- <div className="sandbox-hints">
1517
- <Info size={12} /> {sandboxText(locale, "快捷操作:")}<span className="sandbox-hint-key">Enter</span> {sandboxText(locale, "发送")}<span className="sandbox-hint-key">Shift+Enter</span> {sandboxText(locale, "换行")}<span className="sandbox-hint-key">```ts</span> {sandboxText(locale, "代码块")}<span className="sandbox-hint-key">{sandboxText(locale, "**文本**")}</span> {sandboxText(locale, "加粗")}<span className="sandbox-hint-key">{sandboxText(locale, "[@名称]")}</span> {sandboxText(locale, "@某人")}<span className="sandbox-hint-key">[video:URL]</span>
1518
- <span className="sandbox-hint-key">[audio:URL]</span>
1519
- </div>
1646
+ {/* Hints: collapsed by default so the composer stays one line tall (#1250). */}
1647
+ <details className="sandbox-hints">
1648
+ <summary><Keyboard size={12} /> {sandboxText(locale, "快捷操作与语法")}</summary>
1649
+ <ul>
1650
+ <li><span className="sandbox-hint-key">Enter</span> {sandboxText(locale, "发送")}</li>
1651
+ <li><span className="sandbox-hint-key">Shift+Enter</span> {sandboxText(locale, "换行")}</li>
1652
+ <li><span className="sandbox-hint-key">```ts</span> {sandboxText(locale, "代码块")}</li>
1653
+ <li><span className="sandbox-hint-key">{sandboxText(locale, "**文本**")}</span> {sandboxText(locale, "加粗")}</li>
1654
+ <li><span className="sandbox-hint-key">{sandboxText(locale, "[@名称]")}</span> {sandboxText(locale, "@某人")}</li>
1655
+ <li><span className="sandbox-hint-key">[@{endpointId}]</span> {sandboxText(locale, "@机器人(群聊里唤起机器人,也可点 @ 按钮插入)")}</li>
1656
+ <li><span className="sandbox-hint-key">[image:URL]</span> <span className="sandbox-hint-key">[video:URL]</span> <span className="sandbox-hint-key">[audio:URL]</span> {sandboxText(locale, "媒体")}</li>
1657
+ {commandHints && <li><Terminal size={11} /> {commandHints.prefix
1658
+ ? sandboxText(locale, "命令以 {0} 开头", [commandHints.prefix])
1659
+ : sandboxText(locale, "命令无需前缀")}</li>}
1660
+ </ul>
1661
+ </details>
1520
1662
  </section>
1521
1663
  </main>
1522
1664
 
@@ -1656,12 +1798,9 @@ function taskStatusLabel(status: 'running' | 'completed' | 'failed' | 'cancelled
1656
1798
 
1657
1799
  function messageText(segments: readonly MessageSegment[]): string {
1658
1800
  return segments.map((segment) => {
1659
- const data = segment.data as Record<string, unknown>
1660
- if (segment.type === 'text' || segment.type === 'markdown' || segment.type === 'md') {
1661
- return String(data.text ?? data.content ?? '')
1662
- }
1801
+ const data = (segment.data ?? {}) as Record<string, unknown>
1663
1802
  if (segment.type === 'mention' || segment.type === 'at') return `@${String(data.name ?? data.target ?? '')}`
1664
- return `[${segment.type}]`
1803
+ return segmentPreviewText(segment)
1665
1804
  }).join(' ').trim()
1666
1805
  }
1667
1806
 
@@ -0,0 +1,47 @@
1
+ // Generated by build-plugin-runtime-entries.mjs. Do not edit.
2
+ import { getSandboxApiBase, getSandboxAuthHeaders } from './sandboxTransport.js';
3
+ /** Reads the speaker fields of an inbound echo; null on frames from an older Host without them. */
4
+ export function readServerSpeaker(frame) {
5
+ if (typeof frame.senderId !== 'string' || typeof frame.senderTrustLevel !== 'string')
6
+ return null;
7
+ const simulated = frame.simulated === true;
8
+ const unavailable = frame.asMeUnavailable === 'no-console-user' || frame.asMeUnavailable === 'no-identity' || frame.asMeUnavailable === 'needs-global-iam'
9
+ ? frame.asMeUnavailable : undefined;
10
+ return Object.freeze({
11
+ senderId: frame.senderId,
12
+ displaySenderId: typeof frame.displaySenderId === 'string' && frame.displaySenderId ? frame.displaySenderId : frame.senderId,
13
+ simulated,
14
+ trustLevel: frame.senderTrustLevel,
15
+ ...(typeof frame.senderChatRole === 'string' && frame.senderChatRole ? { chatRole: frame.senderChatRole } : {}),
16
+ ...(unavailable ? { asMeUnavailable: unavailable } : {}),
17
+ });
18
+ }
19
+ /** Whether a send should ask to speak as the linked identity (only when the socket has a Console user). */
20
+ export function wantsAsMe(mode, consoleUser) {
21
+ return mode === 'me' && consoleUser;
22
+ }
23
+ /**
24
+ * `chat-identities.simulated.ensure`: gives the caller's person an identity on the Sandbox (and
25
+ * links a new person to the caller when there is none). `unsupported` on a Host without the RPC.
26
+ */
27
+ export async function ensureSandboxChatIdentity(context, signal) {
28
+ const url = new URL('/api/console/request', `${(context ? context.apiBase : getSandboxApiBase()) || window.location.origin}/`);
29
+ try {
30
+ const response = await fetch(url, {
31
+ method: 'POST',
32
+ headers: { ...(context?.headers ?? getSandboxAuthHeaders()), 'content-type': 'application/json' },
33
+ body: JSON.stringify({ type: 'chat-identities.simulated.ensure', data: {}, requestId: `sandbox-identity-${Date.now()}` }),
34
+ ...(signal ? { signal } : {}),
35
+ });
36
+ const body = await response.json().catch(() => null);
37
+ if (response.ok && body?.success)
38
+ return { status: 'ok' };
39
+ // Older Hosts refuse an RPC they do not list (`unmapped`) or answer 未知请求.
40
+ if (response.status === 404 || body?.code === 'unmapped' || body?.code === 'unknown_rpc' || body?.error === '未知请求')
41
+ return { status: 'unsupported' };
42
+ return { status: 'failed', message: typeof body?.error === 'string' && body.error ? body.error : `HTTP ${response.status}` };
43
+ }
44
+ catch (error) {
45
+ return { status: 'failed', message: error instanceof Error ? error.message : String(error) };
46
+ }
47
+ }
@@ -0,0 +1,66 @@
1
+ import { getSandboxApiBase, getSandboxAuthHeaders, type SandboxRequestContext } from './sandboxTransport.js';
2
+
3
+ /**
4
+ * ADR 0060 §5.4: who a Sandbox message speaks as. The server decides from the authenticated
5
+ * Console principal; the page only asks (`asMe`) and shows what the server answered.
6
+ */
7
+ export type SandboxSpeakerMode = 'me' | 'simulated';
8
+
9
+ /** Why 「以我的聊天身份发言」 could not be used for a message (`asMeUnavailable` on the echo). */
10
+ export type SandboxAsMeUnavailable = 'no-console-user' | 'no-identity' | 'needs-global-iam';
11
+
12
+ /** The server's answer for the last message this page sent. */
13
+ export interface SandboxServerSpeaker {
14
+ readonly senderId: string;
15
+ /** The id as typed (simulated) or the linked identity (me). */
16
+ readonly displaySenderId: string;
17
+ readonly simulated: boolean;
18
+ readonly chatRole?: string;
19
+ readonly trustLevel: string;
20
+ readonly asMeUnavailable?: SandboxAsMeUnavailable;
21
+ }
22
+
23
+ /** Reads the speaker fields of an inbound echo; null on frames from an older Host without them. */
24
+ export function readServerSpeaker(frame: Readonly<Record<string, unknown>>): SandboxServerSpeaker | null {
25
+ if (typeof frame.senderId !== 'string' || typeof frame.senderTrustLevel !== 'string') return null;
26
+ const simulated = frame.simulated === true;
27
+ const unavailable = frame.asMeUnavailable === 'no-console-user' || frame.asMeUnavailable === 'no-identity' || frame.asMeUnavailable === 'needs-global-iam'
28
+ ? frame.asMeUnavailable : undefined;
29
+ return Object.freeze({
30
+ senderId: frame.senderId,
31
+ displaySenderId: typeof frame.displaySenderId === 'string' && frame.displaySenderId ? frame.displaySenderId : frame.senderId,
32
+ simulated,
33
+ trustLevel: frame.senderTrustLevel,
34
+ ...(typeof frame.senderChatRole === 'string' && frame.senderChatRole ? { chatRole: frame.senderChatRole } : {}),
35
+ ...(unavailable ? { asMeUnavailable: unavailable } : {}),
36
+ });
37
+ }
38
+
39
+ /** Whether a send should ask to speak as the linked identity (only when the socket has a Console user). */
40
+ export function wantsAsMe(mode: SandboxSpeakerMode, consoleUser: boolean): boolean {
41
+ return mode === 'me' && consoleUser;
42
+ }
43
+
44
+ /**
45
+ * `chat-identities.simulated.ensure`: gives the caller's person an identity on the Sandbox (and
46
+ * links a new person to the caller when there is none). `unsupported` on a Host without the RPC.
47
+ */
48
+ export async function ensureSandboxChatIdentity(context?: SandboxRequestContext, signal?: AbortSignal):
49
+ Promise<{ readonly status: 'ok' } | { readonly status: 'unsupported' } | { readonly status: 'failed'; readonly message: string }> {
50
+ const url = new URL('/api/console/request', `${(context ? context.apiBase : getSandboxApiBase()) || window.location.origin}/`);
51
+ try {
52
+ const response = await fetch(url, {
53
+ method: 'POST',
54
+ headers: { ...(context?.headers ?? getSandboxAuthHeaders()), 'content-type': 'application/json' },
55
+ body: JSON.stringify({ type: 'chat-identities.simulated.ensure', data: {}, requestId: `sandbox-identity-${Date.now()}` }),
56
+ ...(signal ? { signal } : {}),
57
+ });
58
+ const body = await response.json().catch(() => null) as { success?: boolean; error?: unknown; code?: unknown } | null;
59
+ if (response.ok && body?.success) return { status: 'ok' };
60
+ // Older Hosts refuse an RPC they do not list (`unmapped`) or answer 未知请求.
61
+ if (response.status === 404 || body?.code === 'unmapped' || body?.code === 'unknown_rpc' || body?.error === '未知请求') return { status: 'unsupported' };
62
+ return { status: 'failed', message: typeof body?.error === 'string' && body.error ? body.error : `HTTP ${response.status}` };
63
+ } catch (error) {
64
+ return { status: 'failed', message: error instanceof Error ? error.message : String(error) };
65
+ }
66
+ }
@@ -0,0 +1,41 @@
1
+ // Generated by build-plugin-runtime-entries.mjs. Do not edit.
2
+ import { getSandboxApiBase, getSandboxAuthHeaders } from './sandboxTransport.js';
3
+ /**
4
+ * Host marker of a human approval prompt (#1250): `UserInteractionRequest.purpose = 'approval'`
5
+ * is rendered by Core as keyboard `data.purpose`. Any segment carrying it marks the message, so a
6
+ * text-only approval card that sets the same field on its body is recognised too.
7
+ */
8
+ export const APPROVAL_PURPOSE = 'approval';
9
+ /** Only real approval prompts get the "needs your confirmation" label, not game cards or menu pages. */
10
+ export function isApprovalPrompt(message) {
11
+ return message.type === 'received' && message.interactionReadOnly !== true
12
+ && message.content.some((segment) => {
13
+ const data = segment.data;
14
+ return data !== null && typeof data === 'object' && data.purpose === APPROVAL_PURPOSE;
15
+ });
16
+ }
17
+ /** Quick commands of the Host's command index; null when the Host cannot tell (older Host, no binding). */
18
+ export async function readSandboxCommandHints(connectionId, scene, locale, signal, context) {
19
+ const url = new URL('/api/conversations/workspaces/commands', `${(context ? context.apiBase : getSandboxApiBase()) || window.location.origin}/`);
20
+ url.searchParams.set('connectionId', connectionId);
21
+ url.searchParams.set('type', scene.type);
22
+ url.searchParams.set('id', scene.id);
23
+ url.searchParams.set('locale', locale);
24
+ try {
25
+ const response = await fetch(url, { headers: context?.headers ?? getSandboxAuthHeaders(), signal });
26
+ if (!response.ok)
27
+ return null;
28
+ const body = await response.json();
29
+ const data = body?.data;
30
+ if (!body?.success || !data || typeof data.prefix !== 'string' || !Array.isArray(data.quick))
31
+ return null;
32
+ return Object.freeze({
33
+ prefix: data.prefix,
34
+ ...(typeof data.menu === 'string' ? { menu: data.menu } : {}),
35
+ quick: Object.freeze(data.quick.filter((item) => typeof item === 'string' && item.trim().length > 0).slice(0, 6)),
36
+ });
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ }