@zhin.js/adapter-sandbox 1.1.34 → 1.1.36

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.
@@ -6,6 +6,7 @@ import { cn, CodeBlock, MarkdownContent, resolveMediaSrc, pickMediaRawUrl, } fro
6
6
  import { buildSandboxWebSocketUrl, captureSandboxRequestContext, createSandboxMessageId, submitSandboxFrame, SANDBOX_SCOPED_PROTOCOL } from './sandboxTransport.js';
7
7
  import { createWorkspaceDirectoryController } from './workspaceDirectoryState.js';
8
8
  import { isApprovalPrompt, readSandboxCommandHints } from './composerCommands.js';
9
+ import { ensureSandboxChatIdentity, readServerSpeaker, wantsAsMe } from './chatIdentity.js';
9
10
  import { isJsxNode, segmentFallbackText, segmentPreviewText } from './segmentFallback.js';
10
11
  import { User, Bot, Users, Trash2, Send, Hash, MessageSquare, Wifi, WifiOff, Smile, Image, X, Check, Search, Video, Music, Plus, PanelRight, ExternalLink, RefreshCw, Sparkles, Activity, Wrench, Coins, CircleAlert, Gauge, SlidersHorizontal, FolderOpen, ShieldCheck, Network, Square, RotateCcw, FileDiff, Terminal, FlaskConical, ChevronDown, FileDown, ListChecks, MoreHorizontal, Keyboard, AtSign, } from 'lucide-react';
11
12
  import RichTextEditor, {} from './RichTextEditor.js';
@@ -15,6 +16,12 @@ import ConversationRecoveryPanel from './ConversationRecoveryPanel.js';
15
16
  import { useSandboxHistory } from './useSandboxHistory.js';
16
17
  import { agentSessionsPath, buildAgentRunReport, buildSandboxSessionKey, cancelAgentTask, deriveAgentRunSteps, deriveTaskRuns, deriveWorkbenchArtifacts, fetchAgentTrace, loadCachedAgentTrace, mergeTraceSnapshot, presentTraceEvent, summarizeTrace, saveCachedAgentTrace, } from './agentTrace.js';
17
18
  import { createDefaultPlaygroundState, loadPlaygroundState, savePlaygroundState, mergePlaygroundMessage, retirePlaygroundInteractions, } from './playgroundState.js';
19
+ /** ADR 0060 §5.4: the simulated role is a platform standing (群主 / 管理员 / 成员), never a zhin role. */
20
+ function platformStandingLabel(role, locale) {
21
+ if (locale === 'en')
22
+ return role === 'master' ? 'group owner' : role === 'admin' ? 'group admin' : 'member';
23
+ return role === 'master' ? '群主' : role === 'admin' ? '群管理员' : '成员';
24
+ }
18
25
  export default function Sandbox(props = {}) {
19
26
  const [locale, setLocale] = useState('zh-CN');
20
27
  const localeRef = useRef('zh-CN');
@@ -59,6 +66,13 @@ export default function Sandbox(props = {}) {
59
66
  const [senderId, setSenderId] = useState('dev-user');
60
67
  const [senderName, setSenderName] = useState('Developer');
61
68
  const [senderRole, setSenderRole] = useState('master');
69
+ // ADR 0060 §5.4: what the server resolved for the last message sent (speaker, zhin role, Agent trust tier).
70
+ const [serverRole, setServerRole] = useState(null);
71
+ // 「以我的聊天身份发言」 (default) vs a simulated sender; only a signed-in Console user can speak as themselves.
72
+ const [speakerMode, setSpeakerMode] = useState('me');
73
+ const [consoleUser, setConsoleUser] = useState(false);
74
+ const [identitySetup, setIdentitySetup] = useState({ status: 'idle' });
75
+ const asMe = wantsAsMe(speakerMode, consoleUser);
62
76
  const [showSenderSettings, setShowSenderSettings] = useState(false);
63
77
  /** Runbar overflow: identity, run settings, inspector and clear live here (#1250). */
64
78
  const [showMoreActions, setShowMoreActions] = useState(false);
@@ -227,6 +241,7 @@ export default function Sandbox(props = {}) {
227
241
  connectionRef.current = { protocol: data.protocol, connectionId: data.connectionId, ownerId: data.id, canExecute: data.canExecute !== false };
228
242
  setReadyConnectionId(data.connectionId);
229
243
  setCanExecute(data.canExecute !== false);
244
+ setConsoleUser(data.consoleUser === true);
230
245
  setTransportNotice(data.canExecute === false ? sandboxText(locale, "当前 Token 只有演示权限,任务运行已禁用。") : null);
231
246
  if (data.shellIsolation) {
232
247
  setShellIsolation({
@@ -270,6 +285,9 @@ export default function Sandbox(props = {}) {
270
285
  const channelType = data.conversation?.type ?? (data.type === 'group' || data.type === 'channel' ? data.type : 'private');
271
286
  const sceneId = data.conversation?.id ?? data.id;
272
287
  const isInput = data.direction === 'inbound';
288
+ const speaker = isInput ? readServerSpeaker(data) : null;
289
+ if (speaker)
290
+ setServerRole(speaker);
273
291
  // Interactive choices are transport inputs, not another chat turn or an approval result.
274
292
  if (isInput && content.every((segment) => segment.type === 'action'))
275
293
  return;
@@ -292,7 +310,7 @@ export default function Sandbox(props = {}) {
292
310
  setMessages((prev) => mergePlaygroundMessage(prev, {
293
311
  id: data.messageId ?? createSandboxMessageId(), type: isInput ? 'sent' : 'received', channelType,
294
312
  interactionReadOnly: false,
295
- channelId: sceneId, channelName, senderId: isInput ? data.senderId || connectionRef.current.ownerId || 'owner' : 'endpoint',
313
+ channelId: sceneId, channelName, senderId: isInput ? data.displaySenderId || data.senderId || connectionRef.current.ownerId || 'owner' : 'endpoint',
296
314
  senderName: isInput ? (typeof data.senderName === 'string' && data.senderName.trim() ? data.senderName.trim() : sandboxText(locale, "当前用户")) : data.bot || endpointIdRef.current, content, timestamp: data.timestamp,
297
315
  ...(Number.isSafeInteger(data.revision) && data.revision > 0 ? { revision: data.revision } : {}),
298
316
  ...(typeof data.streaming === 'boolean' ? { streaming: data.streaming } : {}),
@@ -307,7 +325,7 @@ export default function Sandbox(props = {}) {
307
325
  const resolvedSenderName = senderName.trim() || sandboxText(localeRef.current, "测试用户");
308
326
  if (!submitSandboxFrame(wsRef.current, {
309
327
  type: scene.type, id: scene.id, messageId: createSandboxMessageId(), content: segments,
310
- senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole,
328
+ senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole, ...(asMe ? { asMe: true } : {}),
311
329
  agentRun: scene.runConfig, timestamp: Date.now(),
312
330
  })) {
313
331
  setTransportNotice(sandboxText(localeRef.current, "Sandbox 连接尚未就绪,审批选择未发送。"));
@@ -692,7 +710,7 @@ export default function Sandbox(props = {}) {
692
710
  };
693
711
  if (!submitSandboxFrame(wsRef.current, {
694
712
  type: scene.type, id: scene.id, messageId: newMessage.id, content: segments,
695
- senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole,
713
+ senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole, ...(asMe ? { asMe: true } : {}),
696
714
  agentRun: scene.runConfig, timestamp: newMessage.timestamp,
697
715
  })) {
698
716
  setTransportNotice(sandboxText(localeRef.current, "Sandbox 连接尚未就绪,消息未发送。"));
@@ -860,6 +878,7 @@ export default function Sandbox(props = {}) {
860
878
  .sandbox-role-badge.is-master { background: rgba(245,158,11,0.18); color: #d97706; }
861
879
  .sandbox-role-badge.is-admin { background: rgba(59,130,246,0.18); color: #2563eb; }
862
880
  .sandbox-role-badge.is-member { background: rgba(16,185,129,0.16); color: #059669; }
881
+ .sandbox-role-badge.is-zhin { text-transform: none; background: rgba(139,92,246,0.16); color: #7c3aed; }
863
882
  .sandbox-role-switcher { display: inline-flex; gap: 4px; }
864
883
  .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; }
865
884
  .sandbox-role-option.active { font-weight: 600; border-color: currentColor; background: rgba(59,130,246,0.12); }
@@ -893,7 +912,18 @@ export default function Sandbox(props = {}) {
893
912
  }) }), _jsx("div", { className: "agent-playground-new-session", children: showNewSession ? (_jsxs("div", { className: "agent-playground-new-form", children: [_jsx("input", { value: newSessionName, onChange: (event) => setNewSessionName(event.target.value), onKeyDown: (event) => { if (event.key === 'Enter')
894
913
  addSession(); }, placeholder: sandboxText(locale, "会话名称"), autoFocus: true }), _jsx("div", { className: "agent-playground-scope-picker", role: "group", "aria-label": sandboxText(locale, "消息作用域"), children: ['private', 'group', 'channel'].map((scope) => (_jsx("button", { type: "button", "aria-pressed": newSessionScope === scope, className: cn(newSessionScope === scope && 'active'), onClick: () => setNewSessionScope(scope), children: scope === 'private' ? sandboxText(locale, "单用户") : scope === 'group' ? sandboxText(locale, "群组") : sandboxText(locale, "频道") }, scope))) }), _jsxs("div", { className: "agent-playground-new-actions", children: [_jsx("button", { type: "button", onClick: () => setShowNewSession(false), children: sandboxText(locale, "取消") }), _jsx("button", { type: "button", className: "primary", onClick: addSession, children: sandboxText(locale, "创建") })] })] })) : (_jsxs("button", { type: "button", disabled: directoryStatus.mode === 'loading', className: "agent-playground-add", onClick: () => setShowNewSession(true), children: [_jsx(Plus, { size: 15 }), sandboxText(locale, "新建会话")] })) }), _jsxs("div", { className: "agent-playground-endpoint", children: [_jsx("span", { children: directoryStatus.mode === 'loading' ? sandboxText(locale, "正在读取会话目录") : directoryStatus.mode === 'server' && !directoryStatus.error ? sandboxText(locale, "Host 会话目录") : persistenceStatus === 'saved' ? sandboxText(locale, "会话已持久化") : sandboxText(locale, "会话保存失败") }), _jsx("strong", { children: endpointId })] })] }), showChannelList && _jsx("div", { className: "channel-overlay", onClick: () => setShowChannelList(false) }), _jsxs("main", { className: "chat-area agent-playground-main", children: [_jsxs("header", { className: "agent-playground-runbar", children: [_jsxs("div", { className: "agent-playground-run-identity", children: [_jsx("span", { className: "agent-playground-run-icon", children: getChannelIcon(activeChannel.type) }), _jsx("div", { title: sessionKey, children: _jsxs("div", { className: "agent-playground-run-title", children: [_jsx("h1", { title: activeChannel.name, children: activeChannel.name }), _jsx("span", { children: scopeLabel })] }) })] }), _jsxs("div", { className: "agent-playground-run-actions", children: [_jsxs("span", { className: cn("agent-playground-run-state", currentTask?.status === 'running' && "is-running", currentTask?.status === 'failed' && 'has-problem'), children: [currentTask?.status === 'running' ? _jsx(Activity, { size: 14 }) : _jsx(Gauge, { size: 14 }), currentTask ? taskStatusLabel(currentTask.status, locale) : sandboxText(locale, "{0} 条消息", [channelMessages.length])] }), currentTask?.status === 'running' ? (_jsxs("button", { type: "button", className: "agent-playground-stop", onClick: () => void stopActiveTask(), disabled: stoppingTask, "aria-label": sandboxText(locale, "停止当前任务"), children: [_jsx(Square, { size: 13 }), stoppingTask ? sandboxText(locale, "停止中") : sandboxText(locale, "停止")] })) : lastUserMessage ? (_jsxs("button", { type: "button", onClick: retryLastTask, "aria-label": sandboxText(locale, "重新运行上一个任务"), children: [_jsx(RotateCcw, { size: 14 }), sandboxText(locale, "重试")] })) : null, props.renderConversationDetails
895
914
  ? _jsxs("button", { type: "button", disabled: !canExecute, "aria-expanded": showConversationDetails, "aria-controls": "sandbox-conversation-details", onClick: () => setShowConversationDetails((visible) => !visible), children: [_jsx(ListChecks, { size: 14 }), sandboxText(locale, "对话与轨迹")] })
896
- : _jsxs("a", { href: agentSessionsPath(sessionKey), children: [_jsx(ExternalLink, { size: 14 }), sandboxText(locale, "对话与轨迹")] }), _jsxs("div", { className: "sandbox-more", children: [_jsx("button", { type: "button", className: cn("sandbox-more-trigger", (showMoreActions || showSenderSettings || showRunSettings) && 'active'), "aria-haspopup": "menu", "aria-expanded": showMoreActions, onClick: () => setShowMoreActions((visible) => !visible), "aria-label": sandboxText(locale, "更多操作"), title: sandboxText(locale, "更多操作"), children: _jsx(MoreHorizontal, { size: 16 }) }), showMoreActions && (_jsxs(_Fragment, { children: [_jsx("div", { className: "sandbox-more-backdrop", onClick: () => setShowMoreActions(false) }), _jsxs("div", { className: "sandbox-more-menu", role: "menu", "aria-label": sandboxText(locale, "更多操作"), children: [_jsxs("button", { type: "button", role: "menuitemcheckbox", "aria-checked": showSenderSettings, onClick: () => { setShowSenderSettings((visible) => !visible); setShowMoreActions(false); }, children: [_jsx(User, { size: 14 }), _jsx("span", { children: sandboxText(locale, "模拟发送者") }), _jsxs("em", { className: cn("sandbox-role-badge", `is-${senderRole}`), children: [senderName.trim() || senderId.trim() || 'dev-user', " \u00B7 ", senderRole] })] }), _jsxs("button", { type: "button", role: "menuitemcheckbox", "aria-checked": showRunSettings, onClick: () => { setShowRunSettings((visible) => !visible); setShowMoreActions(false); }, children: [_jsx(SlidersHorizontal, { size: 14 }), _jsx("span", { children: sandboxText(locale, "配置运行环境") })] }), _jsxs("button", { type: "button", role: "menuitemcheckbox", "aria-checked": showInspector, "aria-controls": "sandbox-run-inspector", onClick: () => { setShowInspector(!showInspector); setShowMoreActions(false); }, children: [_jsx(PanelRight, { size: 14 }), _jsx("span", { children: sandboxText(locale, "切换运行检查器") })] }), _jsxs("button", { type: "button", role: "menuitem", className: "is-danger", onClick: () => { setConfirmClear(true); setShowMoreActions(false); }, children: [_jsx(Trash2, { size: 14 }), _jsx("span", { children: sandboxText(locale, "清空当前会话") })] })] })] }))] })] })] }), showSenderSettings && (_jsxs("section", { className: "agent-playground-run-settings sandbox-sender-settings", "aria-label": locale === 'en' ? 'Simulated sender' : '模拟发送者配置', children: [_jsxs("label", { children: [_jsxs("span", { children: [_jsx(User, { size: 14 }), locale === 'en' ? 'Sender ID' : '发送者 ID'] }), _jsx("input", { value: senderId, onChange: (event) => setSenderId(event.target.value), placeholder: "dev-user", spellCheck: false })] }), _jsxs("label", { children: [_jsx("span", { children: locale === 'en' ? 'Sender Name' : '发送者昵称' }), _jsx("input", { value: senderName, onChange: (event) => setSenderName(event.target.value), placeholder: "Developer", spellCheck: false })] }), _jsxs("label", { children: [_jsxs("span", { children: [_jsx(ShieldCheck, { size: 14 }), locale === 'en' ? 'Sender Role' : '角色权限'] }), _jsx("div", { className: "sandbox-role-switcher", role: "group", "aria-label": locale === 'en' ? 'Sender role' : '角色权限', children: ['member', 'admin', 'master'].map((role) => (_jsx("button", { type: "button", "aria-pressed": senderRole === role, className: cn("sandbox-role-option", `is-${role}`, senderRole === role && "active"), onClick: () => setSenderRole(role), children: role }, role))) })] }), _jsxs("div", { className: "sandbox-sender-presets", children: [_jsx("button", { type: "button", onClick: () => { setSenderId('dev-user'); setSenderName('Developer'); setSenderRole('master'); }, children: "Master (dev-user)" }), _jsx("button", { type: "button", onClick: () => { setSenderId('admin-user'); setSenderName('Admin'); setSenderRole('admin'); }, children: "Admin (admin-user)" }), _jsx("button", { type: "button", onClick: () => { setSenderId('member-user'); setSenderName('Member'); setSenderRole('member'); }, children: "Member (member-user)" })] })] })), cancellationFeedback && _jsxs("div", { className: "agent-playground-confirm", role: cancellationFeedback.kind === 'error' ? 'alert' : 'status', children: [_jsx("div", { children: _jsx("span", { children: cancellationFeedback.message }) }), _jsx("button", { type: "button", onClick: () => setCancellationFeedback(null), children: sandboxText(locale, "知道了") })] }), confirmClear && (_jsxs("div", { className: "agent-playground-confirm", role: "alert", children: [_jsxs("div", { children: [_jsx("strong", { children: sandboxText(locale, "清空当前测试记录?") }), _jsxs("span", { children: [sandboxText(locale, "只移除“"), activeChannel.name, sandboxText(locale, "”在浏览器中的消息,不影响 Agent 会话存储。")] })] }), _jsx("button", { type: "button", onClick: () => setConfirmClear(false), children: sandboxText(locale, "取消") }), _jsx("button", { type: "button", className: "danger", onClick: clearMessages, children: sandboxText(locale, "确认清空") })] })), ['emoji', 'parse'].filter((kind) => inlineNotices[kind]).map((kind) => (_jsxs("div", { className: "sandbox-notice", role: "status", children: [_jsx(CircleAlert, { size: 14 }), _jsx("span", { children: kind === 'emoji' ? sandboxText(locale, "表情列表加载失败,表情选择器暂不可用。") : sandboxText(locale, "收到一条无法解析的消息,已忽略。") }), _jsx("button", { type: "button", onClick: () => setInlineNotices((n) => ({ ...n, [kind]: false })), children: sandboxText(locale, "知道了") })] }, kind))), transportNotice && (_jsxs("div", { className: "agent-playground-confirm", role: "status", children: [_jsxs("div", { children: [_jsx("strong", { children: sandboxText(locale, "运行暂不可用") }), _jsx("span", { children: transportNotice })] }), _jsx("button", { type: "button", onClick: () => setTransportNotice(null), children: sandboxText(locale, "知道了") })] })), directoryStatus.error && _jsxs("div", { className: "agent-playground-confirm", role: "alert", children: [_jsxs("div", { children: [_jsx("strong", { children: sandboxText(locale, "会话目录") }), _jsx("span", { children: directoryStatus.error })] }), _jsx("button", { type: "button", onClick: () => void directoryControllerRef.current?.refresh(), children: sandboxText(locale, "重新读取") })] }), showRunSettings && (_jsxs("section", { className: "agent-playground-run-settings", "aria-label": sandboxText(locale, "运行配置"), children: [_jsxs("label", { className: "agent-playground-directory-field", children: [_jsxs("span", { children: [_jsx(FolderOpen, { size: 14 }), sandboxText(locale, "工作目录")] }), _jsx("input", { disabled: directoryStatus.mode === 'loading', value: activeChannel.runConfig.workingDirectory, onChange: (event) => updateRunConfig({ workingDirectory: event.target.value }), placeholder: sandboxText(locale, "使用 Host 项目目录"), spellCheck: false })] }), _jsxs("label", { children: [_jsxs("span", { children: [_jsx(ShieldCheck, { size: 14 }), sandboxText(locale, "安全策略")] }), _jsxs("select", { disabled: directoryStatus.mode === 'loading', value: activeChannel.runConfig.safetyMode, onChange: (event) => {
915
+ : _jsxs("a", { href: agentSessionsPath(sessionKey), children: [_jsx(ExternalLink, { size: 14 }), sandboxText(locale, "对话与轨迹")] }), _jsxs("div", { className: "sandbox-more", children: [_jsx("button", { type: "button", className: cn("sandbox-more-trigger", (showMoreActions || showSenderSettings || showRunSettings) && 'active'), "aria-haspopup": "menu", "aria-expanded": showMoreActions, onClick: () => setShowMoreActions((visible) => !visible), "aria-label": sandboxText(locale, "更多操作"), title: sandboxText(locale, "更多操作"), children: _jsx(MoreHorizontal, { size: 16 }) }), showMoreActions && (_jsxs(_Fragment, { children: [_jsx("div", { className: "sandbox-more-backdrop", onClick: () => setShowMoreActions(false) }), _jsxs("div", { className: "sandbox-more-menu", role: "menu", "aria-label": sandboxText(locale, "更多操作"), children: [_jsxs("button", { type: "button", role: "menuitemcheckbox", "aria-checked": showSenderSettings, onClick: () => { setShowSenderSettings((visible) => !visible); setShowMoreActions(false); }, children: [_jsx(User, { size: 14 }), _jsx("span", { children: sandboxText(locale, "模拟发送者") }), _jsxs("em", { className: cn("sandbox-role-badge", `is-${senderRole}`), title: locale === 'en' ? 'Simulated platform standing (not a zhin role)' : '模拟的平台身份(不是 zhin 角色)', children: [asMe ? sandboxText(locale, "我的聊天身份") : (senderName.trim() || senderId.trim() || 'dev-user'), " \u00B7 ", platformStandingLabel(senderRole, locale)] }), serverRole && (serverRole.simulated
916
+ ? _jsx("em", { className: "sandbox-role-badge is-simulated", title: sandboxText(locale, "客户端自填的发送者不解析 zhin 角色"), children: sandboxText(locale, "模拟身份,无角色") })
917
+ : _jsx("em", { className: "sandbox-role-badge is-zhin", title: locale === 'en' ? 'Resolved by the server: zhin role · Agent trust tier' : '服务端解析:zhin 角色 · Agent 信任档位', children: `zhin: ${serverRole.chatRole ?? (locale === 'en' ? 'none' : '无')} · ${serverRole.trustLevel}` }))] }), _jsxs("button", { type: "button", role: "menuitemcheckbox", "aria-checked": showRunSettings, onClick: () => { setShowRunSettings((visible) => !visible); setShowMoreActions(false); }, children: [_jsx(SlidersHorizontal, { size: 14 }), _jsx("span", { children: sandboxText(locale, "配置运行环境") })] }), _jsxs("button", { type: "button", role: "menuitemcheckbox", "aria-checked": showInspector, "aria-controls": "sandbox-run-inspector", onClick: () => { setShowInspector(!showInspector); setShowMoreActions(false); }, children: [_jsx(PanelRight, { size: 14 }), _jsx("span", { children: sandboxText(locale, "切换运行检查器") })] }), _jsxs("button", { type: "button", role: "menuitem", className: "is-danger", onClick: () => { setConfirmClear(true); setShowMoreActions(false); }, children: [_jsx(Trash2, { size: 14 }), _jsx("span", { children: sandboxText(locale, "清空当前会话") })] })] })] }))] })] })] }), showSenderSettings && (_jsxs("section", { className: "agent-playground-run-settings sandbox-sender-settings", "aria-label": locale === 'en' ? 'Simulated sender' : '模拟发送者配置', children: [_jsxs("div", { className: "sandbox-speaker-mode", children: [_jsxs("label", { className: "sandbox-speaker-toggle", children: [_jsx("input", { type: "checkbox", checked: speakerMode === 'me', disabled: !consoleUser, onChange: (event) => setSpeakerMode(event.target.checked ? 'me' : 'simulated') }), _jsx("span", { children: sandboxText(locale, "以我的聊天身份发言") })] }), _jsx("p", { children: !consoleUser
918
+ ? sandboxText(locale, "当前连接没有 Console 用户(未登录或 --standalone),所有消息都按模拟身份处理,不解析 zhin 角色。")
919
+ : asMe
920
+ ? sandboxText(locale, "以链接到你 Console 账号的聊天身份发言,角色按你的聊天角色解析。")
921
+ : sandboxText(locale, "模拟身份,无角色:自填的发送者 ID 只用于模拟别人,不解析 zhin 角色。") }), asMe && serverRole?.asMeUnavailable === 'needs-global-iam' && (_jsx("div", { className: "sandbox-speaker-setup", role: "status", children: _jsx("span", { children: sandboxText(locale, "链接到你的聊天身份持有全局角色,以它发言需要全局 iam.manage 权限;上一条消息按模拟身份(无角色)发送。") }) })), asMe && serverRole?.asMeUnavailable === 'no-identity' && (_jsxs("div", { className: "sandbox-speaker-setup", role: "status", children: [_jsx("span", { children: sandboxText(locale, "你在 Sandbox 上还没有聊天身份,上一条消息按模拟身份发送。") }), _jsx("button", { type: "button", disabled: identitySetup.status === 'busy', onClick: () => {
922
+ setIdentitySetup({ status: 'busy' });
923
+ void ensureSandboxChatIdentity(socketRequestContextRef.current ?? undefined).then((result) => {
924
+ setIdentitySetup(result.status === 'ok' ? { status: 'done' } : result);
925
+ });
926
+ }, children: sandboxText(locale, "在 Sandbox 上创建我的聊天身份") }), identitySetup.status === 'done' && _jsx("em", { children: sandboxText(locale, "已创建,下一条消息生效。") }), identitySetup.status === 'unsupported' && _jsx("em", { children: sandboxText(locale, "当前 Host 不支持,请升级。") }), identitySetup.status === 'failed' && _jsx("em", { children: identitySetup.message })] }))] }), _jsxs("label", { children: [_jsxs("span", { children: [_jsx(User, { size: 14 }), locale === 'en' ? 'Sender ID (simulated, no role)' : '发送者 ID(模拟身份,无角色)'] }), _jsx("input", { value: senderId, disabled: asMe, onChange: (event) => setSenderId(event.target.value), placeholder: "dev-user", spellCheck: false })] }), _jsxs("label", { children: [_jsx("span", { children: locale === 'en' ? 'Sender Name' : '发送者昵称' }), _jsx("input", { value: senderName, disabled: asMe, onChange: (event) => setSenderName(event.target.value), placeholder: "Developer", spellCheck: false })] }), _jsxs("label", { children: [_jsxs("span", { children: [_jsx(ShieldCheck, { size: 14 }), locale === 'en' ? 'Platform standing (not a zhin role)' : '平台身份(不是 zhin 角色)'] }), _jsx("div", { className: "sandbox-role-switcher", role: "group", "aria-label": locale === 'en' ? 'Platform standing' : '平台身份', children: ['member', 'admin', 'master'].map((role) => (_jsx("button", { type: "button", "aria-pressed": senderRole === role, className: cn("sandbox-role-option", `is-${role}`, senderRole === role && "active"), onClick: () => setSenderRole(role), children: platformStandingLabel(role, locale) }, role))) })] }), _jsxs("div", { className: "sandbox-sender-presets", children: [_jsx("button", { type: "button", onClick: () => { setSenderId('dev-user'); setSenderName('Developer'); setSenderRole('master'); }, children: locale === 'en' ? 'Group owner (platform standing, dev-user)' : '群主(平台身份,dev-user)' }), _jsx("button", { type: "button", onClick: () => { setSenderId('admin-user'); setSenderName('Admin'); setSenderRole('admin'); }, children: "Admin (admin-user)" }), _jsx("button", { type: "button", onClick: () => { setSenderId('member-user'); setSenderName('Member'); setSenderRole('member'); }, children: "Member (member-user)" })] })] })), cancellationFeedback && _jsxs("div", { className: "agent-playground-confirm", role: cancellationFeedback.kind === 'error' ? 'alert' : 'status', children: [_jsx("div", { children: _jsx("span", { children: cancellationFeedback.message }) }), _jsx("button", { type: "button", onClick: () => setCancellationFeedback(null), children: sandboxText(locale, "知道了") })] }), confirmClear && (_jsxs("div", { className: "agent-playground-confirm", role: "alert", children: [_jsxs("div", { children: [_jsx("strong", { children: sandboxText(locale, "清空当前测试记录?") }), _jsxs("span", { children: [sandboxText(locale, "只移除“"), activeChannel.name, sandboxText(locale, "”在浏览器中的消息,不影响 Agent 会话存储。")] })] }), _jsx("button", { type: "button", onClick: () => setConfirmClear(false), children: sandboxText(locale, "取消") }), _jsx("button", { type: "button", className: "danger", onClick: clearMessages, children: sandboxText(locale, "确认清空") })] })), ['emoji', 'parse'].filter((kind) => inlineNotices[kind]).map((kind) => (_jsxs("div", { className: "sandbox-notice", role: "status", children: [_jsx(CircleAlert, { size: 14 }), _jsx("span", { children: kind === 'emoji' ? sandboxText(locale, "表情列表加载失败,表情选择器暂不可用。") : sandboxText(locale, "收到一条无法解析的消息,已忽略。") }), _jsx("button", { type: "button", onClick: () => setInlineNotices((n) => ({ ...n, [kind]: false })), children: sandboxText(locale, "知道了") })] }, kind))), transportNotice && (_jsxs("div", { className: "agent-playground-confirm", role: "status", children: [_jsxs("div", { children: [_jsx("strong", { children: sandboxText(locale, "运行暂不可用") }), _jsx("span", { children: transportNotice })] }), _jsx("button", { type: "button", onClick: () => setTransportNotice(null), children: sandboxText(locale, "知道了") })] })), directoryStatus.error && _jsxs("div", { className: "agent-playground-confirm", role: "alert", children: [_jsxs("div", { children: [_jsx("strong", { children: sandboxText(locale, "会话目录") }), _jsx("span", { children: directoryStatus.error })] }), _jsx("button", { type: "button", onClick: () => void directoryControllerRef.current?.refresh(), children: sandboxText(locale, "重新读取") })] }), showRunSettings && (_jsxs("section", { className: "agent-playground-run-settings", "aria-label": sandboxText(locale, "运行配置"), children: [_jsxs("label", { className: "agent-playground-directory-field", children: [_jsxs("span", { children: [_jsx(FolderOpen, { size: 14 }), sandboxText(locale, "工作目录")] }), _jsx("input", { disabled: directoryStatus.mode === 'loading', value: activeChannel.runConfig.workingDirectory, onChange: (event) => updateRunConfig({ workingDirectory: event.target.value }), placeholder: sandboxText(locale, "使用 Host 项目目录"), spellCheck: false })] }), _jsxs("label", { children: [_jsxs("span", { children: [_jsx(ShieldCheck, { size: 14 }), sandboxText(locale, "安全策略")] }), _jsxs("select", { disabled: directoryStatus.mode === 'loading', value: activeChannel.runConfig.safetyMode, onChange: (event) => {
897
927
  const safetyMode = event.target.value;
898
928
  updateRunConfig({ safetyMode, ...(safetyMode === 'danger-full-access' ? { networkAccess: true } : {}) });
899
929
  }, children: [_jsx("option", { value: "read-only", children: sandboxText(locale, "只读") }), _jsx("option", { value: "workspace-write", children: sandboxText(locale, "工作区写入") }), _jsx("option", { value: "danger-full-access", children: sandboxText(locale, "完全访问") })] })] }), _jsxs("label", { children: [_jsx("span", { children: sandboxText(locale, "审批策略") }), _jsxs("select", { value: activeChannel.runConfig.safetyMode === 'read-only' ? 'auto' : activeChannel.runConfig.safetyMode === 'danger-full-access' ? 'bypass' : activeChannel.runConfig.approvalMode, disabled: activeChannel.runConfig.safetyMode !== 'workspace-write', onChange: (event) => updateRunConfig({ approvalMode: event.target.value }), children: [_jsx("option", { value: "ask", children: sandboxText(locale, "按需确认") }), _jsx("option", { value: "auto", children: sandboxText(locale, "审核 Agent 自动判断") }), _jsx("option", { value: "bypass", children: sandboxText(locale, "绕过审批") })] })] }), _jsxs("label", { className: "agent-playground-network-toggle", children: [_jsxs("span", { children: [_jsx(Network, { size: 14 }), sandboxText(locale, "网络访问")] }), _jsx("input", { type: "checkbox", checked: activeChannel.runConfig.safetyMode === 'danger-full-access' || activeChannel.runConfig.networkAccess, disabled: activeChannel.runConfig.safetyMode === 'danger-full-access', onChange: (event) => updateRunConfig({ networkAccess: event.target.checked }) }), _jsx("i", { "aria-hidden": "true" })] }), activeChannel.runConfig.safetyMode === 'danger-full-access' && (_jsxs("p", { children: [_jsx(CircleAlert, { size: 14 }), sandboxText(locale, "完全访问允许 Agent 操作工作目录之外的文件并访问网络,请仅用于可信任务。")] })), activeChannel.runConfig.safetyMode !== 'danger-full-access' && shellIsolation?.available === false && (_jsxs("p", { children: [_jsx(CircleAlert, { size: 14 }), sandboxText(locale, "安全 Shell 需要可用的 Docker daemon;当前仅文件工具可运行。"), shellIsolation.message] }))] })), canExecute && recoveryConnectionId && (_jsx(ConversationRecoveryPanel, { connectionId: recoveryConnectionId, sessionKey: sessionKey, locale: locale, hidden: showConversationDetails, pendingRefreshEpoch: pendingRefreshEpoch, onRetiredInteractions: (retired) => {
@@ -12,6 +12,7 @@ import { buildSandboxWebSocketUrl, captureSandboxRequestContext, createSandboxMe
12
12
  import { createWorkspaceDirectoryController, type DirectoryStatus } from './workspaceDirectoryState.js';
13
13
  import type { SandboxWorkspaceScope } from './workspaceDirectory.js';
14
14
  import { isApprovalPrompt, readSandboxCommandHints, type SandboxCommandHints } from './composerCommands.js';
15
+ import { ensureSandboxChatIdentity, readServerSpeaker, wantsAsMe, type SandboxServerSpeaker, type SandboxSpeakerMode } from './chatIdentity.js';
15
16
  import { isJsxNode, segmentFallbackText, segmentPreviewText } from './segmentFallback.js';
16
17
  import {
17
18
  User, Bot, Users, Trash2, Send, Hash, MessageSquare,
@@ -63,6 +64,12 @@ export interface SandboxPageProps {
63
64
  readonly renderConversationDetails?: (context: { readonly sessionKey: string; readonly canExecute: boolean; readonly connectionId?: string }) => React.ReactNode
64
65
  }
65
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
+
66
73
  export default function Sandbox(props: SandboxPageProps = {}) {
67
74
  const [locale, setLocale] = useState<SandboxLocale>('zh-CN')
68
75
  const localeRef = useRef<SandboxLocale>('zh-CN')
@@ -111,6 +118,13 @@ export default function Sandbox(props: SandboxPageProps = {}) {
111
118
  const [senderId, setSenderId] = useState('dev-user')
112
119
  const [senderName, setSenderName] = useState('Developer')
113
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)
114
128
  const [showSenderSettings, setShowSenderSettings] = useState(false)
115
129
  /** Runbar overflow: identity, run settings, inspector and clear live here (#1250). */
116
130
  const [showMoreActions, setShowMoreActions] = useState(false)
@@ -265,6 +279,8 @@ export default function Sandbox(props: SandboxPageProps = {}) {
265
279
  shellIsolation?: { available?: boolean; provider?: string; message?: string }; timestamp: number;
266
280
  messageId?: string; bot?: string; protocol?: string; connectionId?: string; direction?: string; senderId?: string;
267
281
  senderName?: string; senderRole?: 'master' | 'admin' | 'member';
282
+ senderChatRole?: string; senderTrustLevel?: string; consoleUser?: boolean;
283
+ simulated?: boolean; displaySenderId?: string; asMeUnavailable?: string;
268
284
  revision?: number; streaming?: boolean;
269
285
  conversation?: { type: Channel['type']; id: string };
270
286
  }) => {
@@ -288,6 +304,7 @@ export default function Sandbox(props: SandboxPageProps = {}) {
288
304
  connectionRef.current = { protocol: data.protocol, connectionId: data.connectionId, ownerId: data.id, canExecute: data.canExecute !== false }
289
305
  setReadyConnectionId(data.connectionId)
290
306
  setCanExecute(data.canExecute !== false)
307
+ setConsoleUser(data.consoleUser === true)
291
308
  setTransportNotice(data.canExecute === false ? sandboxText(locale, "当前 Token 只有演示权限,任务运行已禁用。") : null)
292
309
  if (data.shellIsolation) {
293
310
  setShellIsolation({
@@ -331,6 +348,8 @@ export default function Sandbox(props: SandboxPageProps = {}) {
331
348
  const channelType: Channel['type'] = data.conversation?.type ?? (data.type === 'group' || data.type === 'channel' ? data.type : 'private')
332
349
  const sceneId = data.conversation?.id ?? data.id
333
350
  const isInput = data.direction === 'inbound'
351
+ const speaker = isInput ? readServerSpeaker(data as Record<string, unknown>) : null
352
+ if (speaker) setServerRole(speaker)
334
353
  // Interactive choices are transport inputs, not another chat turn or an approval result.
335
354
  if (isInput && content.every((segment) => segment.type === 'action')) return
336
355
  const channelName = channelType === 'private'
@@ -353,7 +372,7 @@ export default function Sandbox(props: SandboxPageProps = {}) {
353
372
  setMessages((prev) => mergePlaygroundMessage(prev, {
354
373
  id: data.messageId ?? createSandboxMessageId(), type: isInput ? 'sent' : 'received', channelType,
355
374
  interactionReadOnly: false,
356
- 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',
357
376
  senderName: isInput ? (typeof data.senderName === 'string' && data.senderName.trim() ? data.senderName.trim() : sandboxText(locale, "当前用户")) : data.bot || endpointIdRef.current, content, timestamp: data.timestamp,
358
377
  ...(Number.isSafeInteger(data.revision) && data.revision! > 0 ? { revision: data.revision } : {}),
359
378
  ...(typeof data.streaming === 'boolean' ? { streaming: data.streaming } : {}),
@@ -368,7 +387,7 @@ export default function Sandbox(props: SandboxPageProps = {}) {
368
387
  const resolvedSenderName = senderName.trim() || sandboxText(localeRef.current, "测试用户")
369
388
  if (!submitSandboxFrame(wsRef.current, {
370
389
  type: scene.type, id: scene.id, messageId: createSandboxMessageId(), content: segments,
371
- senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole,
390
+ senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole, ...(asMe ? { asMe: true } : {}),
372
391
  agentRun: scene.runConfig, timestamp: Date.now(),
373
392
  })) {
374
393
  setTransportNotice(sandboxText(localeRef.current, "Sandbox 连接尚未就绪,审批选择未发送。"))
@@ -881,7 +900,7 @@ export default function Sandbox(props: SandboxPageProps = {}) {
881
900
  }
882
901
  if (!submitSandboxFrame(wsRef.current, {
883
902
  type: scene.type, id: scene.id, messageId: newMessage.id, content: segments,
884
- senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole,
903
+ senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole, ...(asMe ? { asMe: true } : {}),
885
904
  agentRun: scene.runConfig, timestamp: newMessage.timestamp,
886
905
  })) {
887
906
  setTransportNotice(sandboxText(localeRef.current, "Sandbox 连接尚未就绪,消息未发送。"))
@@ -1068,6 +1087,7 @@ export default function Sandbox(props: SandboxPageProps = {}) {
1068
1087
  .sandbox-role-badge.is-master { background: rgba(245,158,11,0.18); color: #d97706; }
1069
1088
  .sandbox-role-badge.is-admin { background: rgba(59,130,246,0.18); color: #2563eb; }
1070
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; }
1071
1091
  .sandbox-role-switcher { display: inline-flex; gap: 4px; }
1072
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; }
1073
1093
  .sandbox-role-option.active { font-weight: 600; border-color: currentColor; background: rgba(59,130,246,0.12); }
@@ -1201,7 +1221,12 @@ export default function Sandbox(props: SandboxPageProps = {}) {
1201
1221
  onClick={() => { setShowSenderSettings((visible) => !visible); setShowMoreActions(false) }}>
1202
1222
  <User size={14} />
1203
1223
  <span>{sandboxText(locale, "模拟发送者")}</span>
1204
- <em className={cn("sandbox-role-badge", `is-${senderRole}`)}>{senderName.trim() || senderId.trim() || 'dev-user'} · {senderRole}</em>
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>)}
1205
1230
  </button>
1206
1231
  <button type="button" role="menuitemcheckbox" aria-checked={showRunSettings}
1207
1232
  onClick={() => { setShowRunSettings((visible) => !visible); setShowMoreActions(false) }}>
@@ -1224,10 +1249,44 @@ export default function Sandbox(props: SandboxPageProps = {}) {
1224
1249
 
1225
1250
  {showSenderSettings && (
1226
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>
1227
1285
  <label>
1228
- <span><User size={14} />{locale === 'en' ? 'Sender ID' : '发送者 ID'}</span>
1286
+ <span><User size={14} />{locale === 'en' ? 'Sender ID (simulated, no role)' : '发送者 ID(模拟身份,无角色)'}</span>
1229
1287
  <input
1230
1288
  value={senderId}
1289
+ disabled={asMe}
1231
1290
  onChange={(event) => setSenderId(event.target.value)}
1232
1291
  placeholder="dev-user"
1233
1292
  spellCheck={false}
@@ -1237,14 +1296,15 @@ export default function Sandbox(props: SandboxPageProps = {}) {
1237
1296
  <span>{locale === 'en' ? 'Sender Name' : '发送者昵称'}</span>
1238
1297
  <input
1239
1298
  value={senderName}
1299
+ disabled={asMe}
1240
1300
  onChange={(event) => setSenderName(event.target.value)}
1241
1301
  placeholder="Developer"
1242
1302
  spellCheck={false}
1243
1303
  />
1244
1304
  </label>
1245
1305
  <label>
1246
- <span><ShieldCheck size={14} />{locale === 'en' ? 'Sender Role' : '角色权限'}</span>
1247
- <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' : '平台身份'}>
1248
1308
  {(['member', 'admin', 'master'] as const).map((role) => (
1249
1309
  <button
1250
1310
  key={role}
@@ -1253,13 +1313,13 @@ export default function Sandbox(props: SandboxPageProps = {}) {
1253
1313
  className={cn("sandbox-role-option", `is-${role}`, senderRole === role && "active")}
1254
1314
  onClick={() => setSenderRole(role)}
1255
1315
  >
1256
- {role}
1316
+ {platformStandingLabel(role, locale)}
1257
1317
  </button>
1258
1318
  ))}
1259
1319
  </div>
1260
1320
  </label>
1261
1321
  <div className="sandbox-sender-presets">
1262
- <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>
1263
1323
  <button type="button" onClick={() => { setSenderId('admin-user'); setSenderName('Admin'); setSenderRole('admin') }}>Admin (admin-user)</button>
1264
1324
  <button type="button" onClick={() => { setSenderId('member-user'); setSenderName('Member'); setSenderRole('member') }}>Member (member-user)</button>
1265
1325
  </div>
@@ -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
+ }
@@ -2,6 +2,18 @@
2
2
  /** Authored interface copy only; unknown/user text is returned unchanged. */
3
3
  export const sandboxEnglish = {
4
4
  "刷新会话目录": "Refresh conversations",
5
+ "我的聊天身份": "My chat identity",
6
+ "客户端自填的发送者不解析 zhin 角色": "A sender id typed by the client never resolves a zhin role",
7
+ "模拟身份,无角色": "Simulated, no role",
8
+ "以我的聊天身份发言": "Speak as my chat identity",
9
+ "当前连接没有 Console 用户(未登录或 --standalone),所有消息都按模拟身份处理,不解析 zhin 角色。": "This connection has no Console user (not signed in, or --standalone): every message is simulated and resolves no zhin role.",
10
+ "以链接到你 Console 账号的聊天身份发言,角色按你的聊天角色解析。": "Messages use the chat identity linked to your Console account; roles resolve from your chat roles.",
11
+ "模拟身份,无角色:自填的发送者 ID 只用于模拟别人,不解析 zhin 角色。": "Simulated, no role: a typed sender id only simulates someone else and resolves no zhin role.",
12
+ "你在 Sandbox 上还没有聊天身份,上一条消息按模拟身份发送。": "You have no chat identity on the Sandbox yet; the last message was sent as a simulated sender.",
13
+ "链接到你的聊天身份持有全局角色,以它发言需要全局 iam.manage 权限;上一条消息按模拟身份(无角色)发送。": "The chat identity linked to you holds a global role; speaking as it needs global iam.manage, so the last message was sent as a simulated sender without roles.",
14
+ "在 Sandbox 上创建我的聊天身份": "Create my chat identity on the Sandbox",
15
+ "已创建,下一条消息生效。": "Created; it applies from the next message.",
16
+ "当前 Host 不支持,请升级。": "This Host does not support it; please upgrade.",
5
17
  "正在读取会话目录": "Loading conversations",
6
18
  "Host 会话目录": "Host conversations",
7
19
  "会话目录": "Conversations",
@@ -3,6 +3,18 @@ export type SandboxLocale = 'zh-CN' | 'en';
3
3
  /** Authored interface copy only; unknown/user text is returned unchanged. */
4
4
  export const sandboxEnglish: Readonly<Record<string, string>> = {
5
5
  "刷新会话目录": "Refresh conversations",
6
+ "我的聊天身份": "My chat identity",
7
+ "客户端自填的发送者不解析 zhin 角色": "A sender id typed by the client never resolves a zhin role",
8
+ "模拟身份,无角色": "Simulated, no role",
9
+ "以我的聊天身份发言": "Speak as my chat identity",
10
+ "当前连接没有 Console 用户(未登录或 --standalone),所有消息都按模拟身份处理,不解析 zhin 角色。": "This connection has no Console user (not signed in, or --standalone): every message is simulated and resolves no zhin role.",
11
+ "以链接到你 Console 账号的聊天身份发言,角色按你的聊天角色解析。": "Messages use the chat identity linked to your Console account; roles resolve from your chat roles.",
12
+ "模拟身份,无角色:自填的发送者 ID 只用于模拟别人,不解析 zhin 角色。": "Simulated, no role: a typed sender id only simulates someone else and resolves no zhin role.",
13
+ "你在 Sandbox 上还没有聊天身份,上一条消息按模拟身份发送。": "You have no chat identity on the Sandbox yet; the last message was sent as a simulated sender.",
14
+ "链接到你的聊天身份持有全局角色,以它发言需要全局 iam.manage 权限;上一条消息按模拟身份(无角色)发送。": "The chat identity linked to you holds a global role; speaking as it needs global iam.manage, so the last message was sent as a simulated sender without roles.",
15
+ "在 Sandbox 上创建我的聊天身份": "Create my chat identity on the Sandbox",
16
+ "已创建,下一条消息生效。": "Created; it applies from the next message.",
17
+ "当前 Host 不支持,请升级。": "This Host does not support it; please upgrade.",
6
18
  "正在读取会话目录": "Loading conversations",
7
19
  "Host 会话目录": "Host conversations",
8
20
  "会话目录": "Conversations",
@@ -362,6 +362,13 @@ export const sandboxStyles = `
362
362
  .zhin-sandbox .sandbox-more-menu > button[aria-checked="true"] { color: var(--sb-primary); }
363
363
  .zhin-sandbox .sandbox-more-menu > button.is-danger { color: var(--sb-danger); }
364
364
  .zhin-sandbox .sandbox-more-menu > button > em { margin-left: auto; font-style: normal; }
365
+ .zhin-sandbox .sandbox-more-menu > button > em + em { margin-left: 4px; }
366
+ .zhin-sandbox .sandbox-role-badge.is-simulated { color: var(--sb-muted-fg); }
367
+ .zhin-sandbox .sandbox-speaker-mode { display: grid; gap: 6px; grid-column: 1 / -1; }
368
+ .zhin-sandbox .sandbox-speaker-toggle { display: inline-flex; align-items: center; gap: 8px; font-weight: 600; }
369
+ .zhin-sandbox .sandbox-speaker-mode > p { margin: 0; color: var(--sb-muted-fg); font-size: 12px; }
370
+ .zhin-sandbox .sandbox-speaker-setup { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; font-size: 12px; }
371
+ .zhin-sandbox .sandbox-speaker-setup > em { font-style: normal; color: var(--sb-muted-fg); }
365
372
  .zhin-sandbox .sandbox-hint-key { padding: 1px 6px; border: 1px solid var(--sb-border); border-radius: var(--sb-radius-sm); background: var(--sb-muted); color: var(--sb-fg); font-family: var(--sb-mono); font-size: 12px; line-height: 1.4; }
366
373
  .zhin-sandbox .sandbox-hint-text { margin-right: 6px; }
367
374
 
@@ -361,6 +361,13 @@ export const sandboxStyles = `
361
361
  .zhin-sandbox .sandbox-more-menu > button[aria-checked="true"] { color: var(--sb-primary); }
362
362
  .zhin-sandbox .sandbox-more-menu > button.is-danger { color: var(--sb-danger); }
363
363
  .zhin-sandbox .sandbox-more-menu > button > em { margin-left: auto; font-style: normal; }
364
+ .zhin-sandbox .sandbox-more-menu > button > em + em { margin-left: 4px; }
365
+ .zhin-sandbox .sandbox-role-badge.is-simulated { color: var(--sb-muted-fg); }
366
+ .zhin-sandbox .sandbox-speaker-mode { display: grid; gap: 6px; grid-column: 1 / -1; }
367
+ .zhin-sandbox .sandbox-speaker-toggle { display: inline-flex; align-items: center; gap: 8px; font-weight: 600; }
368
+ .zhin-sandbox .sandbox-speaker-mode > p { margin: 0; color: var(--sb-muted-fg); font-size: 12px; }
369
+ .zhin-sandbox .sandbox-speaker-setup { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; font-size: 12px; }
370
+ .zhin-sandbox .sandbox-speaker-setup > em { font-style: normal; color: var(--sb-muted-fg); }
364
371
  .zhin-sandbox .sandbox-hint-key { padding: 1px 6px; border: 1px solid var(--sb-border); border-radius: var(--sb-radius-sm); background: var(--sb-muted); color: var(--sb-fg); font-family: var(--sb-mono); font-size: 12px; line-height: 1.4; }
365
372
  .zhin-sandbox .sandbox-hint-text { margin-right: 6px; }
366
373
 
package/plugin.js CHANGED
@@ -1,6 +1,13 @@
1
1
  // Generated by build-plugin-runtime-entries.mjs. Do not edit.
2
2
  import { definePlugin } from 'zhin.js';
3
+ import { createSandboxConsoleRpc } from "./lib/console.js";
3
4
  export default definePlugin({
4
5
  name: 'sandbox',
5
6
  configUpdate: { featurePaths: [['nickname'], ['profile'], ['endpoints']] },
7
+ setup(context) {
8
+ // Account management in the Console (status, add / start / stop / remove), as for other adapters.
9
+ return {
10
+ consoleRpc: createSandboxConsoleRpc(() => context.config.get()),
11
+ };
12
+ },
6
13
  });
package/src/adapter.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Adapter, type AdapterContext, type EndpointCreationContext } from 'zhin.js/adapter';
2
2
  import { httpHostToken } from '@zhin.js/host-http';
3
3
  import { projectLocaleToken, resolveLocale } from 'zhin.js/i18n';
4
+ import { chatRolesToken, type ChatRoleReader } from 'zhin.js';
4
5
  import { resolveSandboxEndpoint, type SandboxEndpointConfig } from './protocol.js';
5
6
  import { SandboxWsEndpoint } from './endpoint.js';
6
7
  import type { SandboxClientEventMap } from './client.js';
@@ -14,9 +15,14 @@ export class SandboxAdapter extends Adapter<SandboxWsEndpoint, SandboxEndpointCo
14
15
  protected override validateConfiguration(config: SandboxEndpointConfig): void { resolveSandboxEndpoint(config); }
15
16
  protected createEndpoint(input: SandboxEndpointConfig, execution: EndpointCreationContext): SandboxWsEndpoint {
16
17
  return new SandboxWsEndpoint({ id: execution.canonicalId, defaults: resolveSandboxEndpoint(input),
17
- http: this.#context.use(httpHostToken), locale: resolveLocale(this.#context.use(projectLocaleToken)) });
18
+ http: this.#context.use(httpHostToken), locale: resolveLocale(this.#context.use(projectLocaleToken)),
19
+ ...optionalChatRoles(() => this.#context.use(chatRolesToken)) });
18
20
  }
19
21
  }
22
+ /** The instance provides chat roles (ADR 0060 §6); hosts without them (tests, other roots) show no zhin role. */
23
+ function optionalChatRoles(read: () => ChatRoleReader): { chatRoles?: ChatRoleReader } {
24
+ try { return { chatRoles: read() }; } catch { return {}; }
25
+ }
20
26
  declare module '@zhin.js/feature-kit' {
21
27
  interface AdapterRegistry { readonly sandbox: SandboxAdapter; }
22
28
  }