chatluna-plugin-onebot-sandbox 1.0.0

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.
Files changed (184) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -0
  3. package/client/app.tsx +306 -0
  4. package/client/chat/chat-pane.tsx +303 -0
  5. package/client/chat/composer.css +635 -0
  6. package/client/chat/composer.tsx +646 -0
  7. package/client/chat/details-panel.tsx +196 -0
  8. package/client/chat/emoji-picker.tsx +70 -0
  9. package/client/chat/extension-mark.tsx +16 -0
  10. package/client/chat/forward.tsx +257 -0
  11. package/client/chat/image-preview.tsx +93 -0
  12. package/client/chat/member-menu.tsx +64 -0
  13. package/client/chat/message-list.tsx +617 -0
  14. package/client/chat/messages.css +1018 -0
  15. package/client/chat/notifications.tsx +83 -0
  16. package/client/chat/reactions.tsx +52 -0
  17. package/client/chat/search-panel.tsx +231 -0
  18. package/client/chat/sidebar.tsx +424 -0
  19. package/client/chat/webqq-view.tsx +71 -0
  20. package/client/environment/avatar-picker.tsx +92 -0
  21. package/client/environment/create-popover.tsx +228 -0
  22. package/client/environment/directory-model.ts +63 -0
  23. package/client/environment/entity-dialog.css +383 -0
  24. package/client/environment/entity-dialog.tsx +442 -0
  25. package/client/environment/page.css +14 -0
  26. package/client/environment/page.tsx +280 -0
  27. package/client/i18n.ts +19 -0
  28. package/client/index.ts +17 -0
  29. package/client/locales/en.yml +617 -0
  30. package/client/locales/zh.yml +617 -0
  31. package/client/mcp/capability-catalog.tsx +277 -0
  32. package/client/mcp/credential-manager.tsx +257 -0
  33. package/client/onebot-debug/page.tsx +329 -0
  34. package/client/records/record-layout.tsx +429 -0
  35. package/client/records/records.css +259 -0
  36. package/client/settings/about.tsx +43 -0
  37. package/client/settings/draft.ts +47 -0
  38. package/client/settings/localize.ts +76 -0
  39. package/client/settings/page.tsx +210 -0
  40. package/client/settings/settings.css +47 -0
  41. package/client/shared/avatar.tsx +35 -0
  42. package/client/shared/confirm-dialog.tsx +44 -0
  43. package/client/shared/controls.css +17 -0
  44. package/client/shared/discard-confirm.tsx +45 -0
  45. package/client/shared/floating-panel.ts +40 -0
  46. package/client/shared/format-duration.ts +22 -0
  47. package/client/shared/format-time.ts +49 -0
  48. package/client/shared/glass.css +150 -0
  49. package/client/shared/implementation.ts +12 -0
  50. package/client/shared/overlay-scrollbar.css +45 -0
  51. package/client/shared/overlay-scrollbar.tsx +123 -0
  52. package/client/shared/use-element-width.ts +19 -0
  53. package/client/shared/use-retained.ts +12 -0
  54. package/client/test-call/page.tsx +260 -0
  55. package/client/test-space/agent-visuals.tsx +121 -0
  56. package/client/test-space/observe-overlay.tsx +42 -0
  57. package/client/test-space/overview.tsx +267 -0
  58. package/client/test-space/spaces.css +201 -0
  59. package/client/test-space/thumbnail-capture.ts +63 -0
  60. package/client/test-space/thumbnail-scale.ts +21 -0
  61. package/client/test-space/use-space-list.ts +35 -0
  62. package/client/test-space/zoom.ts +197 -0
  63. package/client/webqq/composer-draft-host.ts +578 -0
  64. package/client/webqq/composer-draft.ts +81 -0
  65. package/client/webqq/conversation-tree.ts +155 -0
  66. package/client/webqq/emoji-catalog.ts +78 -0
  67. package/client/webqq/fork-boundary.ts +28 -0
  68. package/client/webqq/forward-cluster.ts +20 -0
  69. package/client/webqq/forward-dialog-stack.ts +74 -0
  70. package/client/webqq/forward-preview.ts +40 -0
  71. package/client/webqq/friend-menu.ts +17 -0
  72. package/client/webqq/group-display.ts +18 -0
  73. package/client/webqq/group-menu.ts +25 -0
  74. package/client/webqq/mention.ts +4 -0
  75. package/client/webqq/message-capabilities.ts +37 -0
  76. package/client/webqq/message-cluster.ts +68 -0
  77. package/client/webqq/message-presentation.ts +197 -0
  78. package/client/webqq/message-reveal.ts +31 -0
  79. package/client/webqq/message-search-date.ts +40 -0
  80. package/client/webqq/message-selection.ts +85 -0
  81. package/client/webqq/notification-requests.ts +20 -0
  82. package/client/webqq/participant-presentation.ts +128 -0
  83. package/client/webqq/profile-card.ts +199 -0
  84. package/client/webqq/relationship-directory.ts +62 -0
  85. package/client/webqq/thinking-panel.ts +7 -0
  86. package/client/webqq/user-stack.ts +53 -0
  87. package/client/workspace/agent-overlay-effect.ts +238 -0
  88. package/client/workspace/context.tsx +117 -0
  89. package/client/workspace/overlay-host.tsx +299 -0
  90. package/client/workspace/profile-card.css +164 -0
  91. package/client/workspace/state.ts +28 -0
  92. package/client/workspace/store.ts +388 -0
  93. package/client/workspace/use-test-spaces.ts +21 -0
  94. package/dist/.vite/manifest.json +21 -0
  95. package/dist/app-63rfTh6w.js +85 -0
  96. package/dist/client.css +4 -0
  97. package/dist/client.js +1 -0
  98. package/lib/account-profile.d.ts +17 -0
  99. package/lib/account-profile.d.ts.map +1 -0
  100. package/lib/base-dir.d.ts +4 -0
  101. package/lib/base-dir.d.ts.map +1 -0
  102. package/lib/bot.d.ts +185 -0
  103. package/lib/bot.d.ts.map +1 -0
  104. package/lib/builtin-avatar-options.d.ts +11 -0
  105. package/lib/builtin-avatar-options.d.ts.map +1 -0
  106. package/lib/builtin-avatars.d.ts +6 -0
  107. package/lib/builtin-avatars.d.ts.map +1 -0
  108. package/lib/channel-assignee.d.ts +52 -0
  109. package/lib/channel-assignee.d.ts.map +1 -0
  110. package/lib/chatluna/conversation-lines.d.ts +46 -0
  111. package/lib/chatluna/conversation-lines.d.ts.map +1 -0
  112. package/lib/chatluna/runtime.d.ts +26 -0
  113. package/lib/chatluna/runtime.d.ts.map +1 -0
  114. package/lib/chatluna/state.d.ts +67 -0
  115. package/lib/chatluna/state.d.ts.map +1 -0
  116. package/lib/chatluna/thinking.d.ts +10 -0
  117. package/lib/chatluna/thinking.d.ts.map +1 -0
  118. package/lib/chatluna/tools.d.ts +36 -0
  119. package/lib/chatluna/tools.d.ts.map +1 -0
  120. package/lib/chatluna/wakeup.d.ts +143 -0
  121. package/lib/chatluna/wakeup.d.ts.map +1 -0
  122. package/lib/console-contract.d.ts +131 -0
  123. package/lib/console-contract.d.ts.map +1 -0
  124. package/lib/console.d.ts +31 -0
  125. package/lib/console.d.ts.map +1 -0
  126. package/lib/control-service.d.ts +425 -0
  127. package/lib/control-service.d.ts.map +1 -0
  128. package/lib/conversation-resolution.d.ts +157 -0
  129. package/lib/conversation-resolution.d.ts.map +1 -0
  130. package/lib/error-detail.d.ts +3 -0
  131. package/lib/error-detail.d.ts.map +1 -0
  132. package/lib/inbound-delivery.d.ts +156 -0
  133. package/lib/inbound-delivery.d.ts.map +1 -0
  134. package/lib/index.d.ts +76 -0
  135. package/lib/index.d.ts.map +1 -0
  136. package/lib/index.js +12834 -0
  137. package/lib/index.js.map +1 -0
  138. package/lib/lifecycle.d.ts +8 -0
  139. package/lib/lifecycle.d.ts.map +1 -0
  140. package/lib/mcp/arguments.d.ts +71 -0
  141. package/lib/mcp/arguments.d.ts.map +1 -0
  142. package/lib/mcp/call-records.d.ts +32 -0
  143. package/lib/mcp/call-records.d.ts.map +1 -0
  144. package/lib/mcp/http-api.d.ts +147 -0
  145. package/lib/mcp/http-api.d.ts.map +1 -0
  146. package/lib/mcp/page-cursor.d.ts +37 -0
  147. package/lib/mcp/page-cursor.d.ts.map +1 -0
  148. package/lib/mcp/server.d.ts +60 -0
  149. package/lib/mcp/server.d.ts.map +1 -0
  150. package/lib/mcp/service.d.ts +219 -0
  151. package/lib/mcp/service.d.ts.map +1 -0
  152. package/lib/mcp/tool-registry.d.ts +113 -0
  153. package/lib/mcp/tool-registry.d.ts.map +1 -0
  154. package/lib/mcp/types.d.ts +144 -0
  155. package/lib/mcp/types.d.ts.map +1 -0
  156. package/lib/media-storage.d.ts +33 -0
  157. package/lib/media-storage.d.ts.map +1 -0
  158. package/lib/message-capabilities.d.ts +78 -0
  159. package/lib/message-capabilities.d.ts.map +1 -0
  160. package/lib/onebot-debug.d.ts +115 -0
  161. package/lib/onebot-debug.d.ts.map +1 -0
  162. package/lib/onebot-message.d.ts +23 -0
  163. package/lib/onebot-message.d.ts.map +1 -0
  164. package/lib/onebot-profiles.d.ts +45 -0
  165. package/lib/onebot-profiles.d.ts.map +1 -0
  166. package/lib/persistence.d.ts +148 -0
  167. package/lib/persistence.d.ts.map +1 -0
  168. package/lib/random.d.ts +5 -0
  169. package/lib/random.d.ts.map +1 -0
  170. package/lib/record-store.d.ts +80 -0
  171. package/lib/record-store.d.ts.map +1 -0
  172. package/lib/relationship-actions.d.ts +157 -0
  173. package/lib/relationship-actions.d.ts.map +1 -0
  174. package/lib/scope-directory.d.ts +105 -0
  175. package/lib/scope-directory.d.ts.map +1 -0
  176. package/lib/settings.d.ts +33 -0
  177. package/lib/settings.d.ts.map +1 -0
  178. package/lib/test-spaces.d.ts +69 -0
  179. package/lib/test-spaces.d.ts.map +1 -0
  180. package/lib/types.d.ts +739 -0
  181. package/lib/types.d.ts.map +1 -0
  182. package/lib/webui.d.ts +26 -0
  183. package/lib/webui.d.ts.map +1 -0
  184. package/package.json +112 -0
@@ -0,0 +1,277 @@
1
+ import * as React from 'react'
2
+ import { ChevronRightIcon, SearchIcon } from 'lucide-react'
3
+ import {
4
+ Badge,
5
+ Button,
6
+ cn,
7
+ Collapsible,
8
+ CollapsibleContent,
9
+ CollapsibleTrigger,
10
+ Input,
11
+ Spinner,
12
+ } from '@chatluna/ui-kit'
13
+ import type { SandboxHttpApiCapabilityCatalog } from '../../src/mcp/http-api'
14
+ import type { SandboxMcpCapabilityCatalog, SandboxMcpScope } from '../../src/mcp/types'
15
+ import { useT } from '../i18n'
16
+ import { errorText } from '../workspace/store'
17
+
18
+ export const MCP_SCOPES: readonly SandboxMcpScope[] = ['read', 'interact', 'manage', 'debug']
19
+
20
+ /**
21
+ * 一次性目录读取:独立的加载与失败态,失败只落成一条消息。两种协议表述各调一次,
22
+ * 一页读失败不会把另一页拖成失败态,重试也只重试自己。
23
+ */
24
+ export function useCatalog<Catalog>(read: () => Promise<Catalog>, failure: string) {
25
+ const [catalog, setCatalog] = React.useState<Catalog>()
26
+ const [loading, setLoading] = React.useState(false)
27
+ const [error, setError] = React.useState('')
28
+ const latest = React.useRef(read)
29
+ latest.current = read
30
+ const load = React.useCallback(async () => {
31
+ setLoading(true)
32
+ setError('')
33
+ try {
34
+ setCatalog(await latest.current())
35
+ } catch (cause) {
36
+ setError(errorText(cause, failure))
37
+ } finally {
38
+ setLoading(false)
39
+ }
40
+ }, [failure])
41
+ return { catalog, loading, error, load }
42
+ }
43
+
44
+ function CatalogState({ loading, error, onRetry, unavailable }: { loading: boolean, error: string, onRetry(): void, unavailable: string }) {
45
+ const t = useT()
46
+ if (loading) return <div className="flex flex-1 items-center justify-center p-8"><Spinner /></div>
47
+ if (error) {
48
+ return (
49
+ <div className="flex flex-1 flex-col items-center justify-center gap-3 p-8 text-xs">
50
+ <p role="alert" className="text-destructive">{error}</p>
51
+ <Button size="sm" variant="outline" onClick={onRetry}>{t('sandbox.common.retry')}</Button>
52
+ </div>
53
+ )
54
+ }
55
+ return <p className="p-8 text-center text-xs text-muted-foreground">{unavailable}</p>
56
+ }
57
+
58
+ function Summary({ items }: { items: Array<{ value: React.ReactNode, label: string }> }) {
59
+ return (
60
+ <div className="grid grid-cols-3 gap-2">
61
+ {items.map((item) => (
62
+ <article key={item.label} className="flex flex-col gap-0.5 rounded-lg bg-muted/50 px-3 py-2.5">
63
+ <strong className="text-base font-semibold tabular-nums">{item.value}</strong>
64
+ <span className="text-[11px] text-muted-foreground">{item.label}</span>
65
+ </article>
66
+ ))}
67
+ </div>
68
+ )
69
+ }
70
+
71
+ function SearchInput({ value, onChange, placeholder }: { value: string, onChange(value: string): void, placeholder: string }) {
72
+ return (
73
+ <div className="relative flex-1">
74
+ <SearchIcon className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />
75
+ <Input type="search" className="sandbox-search-input h-8 pl-8!" value={value} placeholder={placeholder} aria-label={placeholder} onChange={(event) => onChange(event.target.value)} />
76
+ </div>
77
+ )
78
+ }
79
+
80
+ function Pill({ active, onClick, children }: { active: boolean, onClick(): void, children: React.ReactNode }) {
81
+ return <Button size="sm" variant={active ? 'secondary' : 'ghost'} aria-pressed={active} onClick={onClick}>{children}</Button>
82
+ }
83
+
84
+ export function McpCapabilityCatalog({ catalog, loading, error, onRetry }: {
85
+ catalog?: SandboxMcpCapabilityCatalog
86
+ loading: boolean
87
+ error: string
88
+ onRetry(): void
89
+ }) {
90
+ const t = useT()
91
+ const [query, setQuery] = React.useState('')
92
+ const [kind, setKind] = React.useState<'tools' | 'resources'>('tools')
93
+ const [scope, setScope] = React.useState<'all' | SandboxMcpScope>('all')
94
+ if (!catalog || loading || error) return <CatalogState loading={loading} error={error} onRetry={onRetry} unavailable={t('sandbox.env.mcpUnavailable')} />
95
+
96
+ const needle = query.trim().toLocaleLowerCase()
97
+ const scopeLabel = (value: SandboxMcpScope) => t(`sandbox.scope.${value}`)
98
+ const tools = catalog.tools.filter((tool) => (scope === 'all' || tool.scope === scope)
99
+ && (!needle || [tool.name, tool.description, scopeLabel(tool.scope)].some((value) => value.toLocaleLowerCase().includes(needle))))
100
+ const resources = catalog.resources.filter((resource) => !needle || [resource.name, resource.uri, resource.mimeType].some((value) => value.toLocaleLowerCase().includes(needle)))
101
+ const flags = catalog.serverCapabilities
102
+ const endpoint = catalog.endpoint
103
+ // 与 HTTP 能力页的 curl 示例对应:给出能直接粘进 MCP 客户端配置的 Streamable HTTP 条目。
104
+ const clientConfig = endpoint && JSON.stringify({
105
+ mcpServers: {
106
+ 'onebot-sandbox': {
107
+ type: 'streamable-http',
108
+ url: endpoint.url,
109
+ headers: { Authorization: `Bearer <${t('sandbox.env.http.tokenPlaceholder')}>` },
110
+ },
111
+ },
112
+ }, null, 2)
113
+ const code = (text: string) => <code className="rounded bg-muted px-1 py-0.5 font-mono text-[11px]">{text}</code>
114
+
115
+ return (
116
+ <div className="flex flex-col gap-4 p-4">
117
+ {endpoint && !endpoint.enabled && (
118
+ <p className="rounded-lg bg-amber-500/10 p-3 text-xs leading-5 text-amber-800 dark:text-amber-300">{t('sandbox.env.mcp.disabledNotice')}</p>
119
+ )}
120
+ {endpoint && (
121
+ <section className="flex flex-col gap-2">
122
+ <h3 className="text-xs font-medium">{t('sandbox.env.mcp.connect')}</h3>
123
+ <p className="text-xs leading-5 text-muted-foreground">
124
+ {t('sandbox.env.mcp.connectBefore')}{code(endpoint.url)}{t('sandbox.env.mcp.connectAfter')}
125
+ </p>
126
+ <pre className="overflow-auto rounded-lg bg-muted/50 p-3 font-mono text-[11px] leading-5">{clientConfig}</pre>
127
+ </section>
128
+ )}
129
+ <Summary items={[
130
+ { value: catalog.tools.length, label: t('sandbox.env.mcp.tools') },
131
+ { value: catalog.resources.length, label: t('sandbox.env.mcp.resources') },
132
+ { value: catalog.scopes.length, label: t('sandbox.env.mcp.scopes') },
133
+ ]} />
134
+ <div className="flex flex-wrap items-center gap-1.5 text-xs">
135
+ <span className="mr-1 text-muted-foreground">{t('sandbox.env.mcp.serverCapabilities')}</span>
136
+ <Badge variant={flags.tools ? 'secondary' : 'outline'}>{t('sandbox.env.mcp.capability.tools')}</Badge>
137
+ <Badge variant={flags.resources ? 'secondary' : 'outline'}>{t('sandbox.env.mcp.capability.resources')}</Badge>
138
+ <Badge variant={flags.prompts ? 'secondary' : 'outline'}>{flags.prompts ? t('sandbox.env.mcp.capability.prompts') : t('sandbox.env.mcp.promptsMissing')}</Badge>
139
+ </div>
140
+ <div className="flex flex-wrap items-center gap-2">
141
+ <SearchInput value={query} onChange={setQuery} placeholder={t('sandbox.env.mcp.search')} />
142
+ <div className="flex gap-0.5">
143
+ <Pill active={kind === 'tools'} onClick={() => setKind('tools')}>{t('sandbox.env.mcp.tools')}</Pill>
144
+ <Pill active={kind === 'resources'} onClick={() => setKind('resources')}>{t('sandbox.env.mcp.resources')}</Pill>
145
+ </div>
146
+ </div>
147
+ {kind === 'tools' ? (
148
+ <>
149
+ <div className="flex flex-wrap gap-0.5" aria-label={t('sandbox.env.mcp.scopeFilter')}>
150
+ <Pill active={scope === 'all'} onClick={() => setScope('all')}>{t('sandbox.env.mcp.allScopes')}</Pill>
151
+ {MCP_SCOPES.map((value) => <Pill key={value} active={scope === value} onClick={() => setScope(value)}>{scopeLabel(value)}</Pill>)}
152
+ </div>
153
+ <div className="flex flex-col gap-1.5">
154
+ {tools.map((tool) => (
155
+ <Collapsible key={tool.name} className="rounded-lg ring-1 ring-border">
156
+ <CollapsibleTrigger className="group flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left hover:bg-accent/60">
157
+ <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground transition-transform group-data-[panel-open]:rotate-90" />
158
+ <span className="flex min-w-0 flex-1 flex-col">
159
+ <strong className="truncate font-mono text-xs font-medium">{tool.name}</strong>
160
+ <small className="line-clamp-2 text-[11px] text-muted-foreground">{tool.description}</small>
161
+ </span>
162
+ <Badge variant="outline">{scopeLabel(tool.scope)}</Badge>
163
+ </CollapsibleTrigger>
164
+ <CollapsibleContent className="flex flex-col gap-1.5 px-3 pb-3">
165
+ <span className="text-[11px] text-muted-foreground">{t('sandbox.env.mcp.inputSchema')}</span>
166
+ <pre className="max-h-80 overflow-auto rounded-md bg-muted/50 p-2.5 font-mono text-[11px] leading-5">{JSON.stringify(tool.inputSchema, null, 2)}</pre>
167
+ </CollapsibleContent>
168
+ </Collapsible>
169
+ ))}
170
+ {!tools.length && <p className="py-6 text-center text-xs text-muted-foreground">{t('sandbox.env.mcp.noTool')}</p>}
171
+ </div>
172
+ </>
173
+ ) : (
174
+ <div className="flex flex-col gap-1.5">
175
+ {resources.map((resource) => (
176
+ <article key={resource.uri} className="flex items-center gap-3 rounded-lg px-3 py-2.5 ring-1 ring-border">
177
+ <span className="flex min-w-0 flex-1 flex-col">
178
+ <strong className="truncate text-xs font-medium">{resource.name}</strong>
179
+ <small className="truncate font-mono text-[11px] text-muted-foreground">{resource.uri}</small>
180
+ </span>
181
+ <span className="flex shrink-0 flex-wrap justify-end gap-1">
182
+ {resource.requiredScopes.map((value) => <Badge key={value} variant="outline">{scopeLabel(value)}</Badge>)}
183
+ <Badge variant="secondary">{resource.mimeType}</Badge>
184
+ </span>
185
+ </article>
186
+ ))}
187
+ {!resources.length && <p className="py-6 text-center text-xs text-muted-foreground">{t('sandbox.env.mcp.noResource')}</p>}
188
+ </div>
189
+ )}
190
+ </div>
191
+ )
192
+ }
193
+
194
+ export function HttpCapabilityCatalog({ catalog, loading, error, onRetry }: {
195
+ catalog?: SandboxHttpApiCapabilityCatalog
196
+ loading: boolean
197
+ error: string
198
+ onRetry(): void
199
+ }) {
200
+ const t = useT()
201
+ const [query, setQuery] = React.useState('')
202
+ if (!catalog || loading || error) return <CatalogState loading={loading} error={error} onRetry={onRetry} unavailable={t('sandbox.env.httpUnavailable')} />
203
+
204
+ // 上限只用 MiB 一档:量级由服务端固定,换算成 KiB 或 GiB 读不出信息。
205
+ const mib = catalog.maxBodyBytes / (1024 * 1024)
206
+ const bodyLimit = `${Number.isInteger(mib) ? mib : mib.toFixed(1)} MiB`
207
+ // 示例路径取自服务端自述的 list-tools 路由,改了前缀或版本段,示例跟着变。
208
+ const listTools = catalog.routes.find((route) => route.kind === 'list-tools')
209
+ const example = listTools ? [
210
+ `TOKEN=<${t('sandbox.env.http.tokenPlaceholder')}>`,
211
+ '',
212
+ `# ${t('sandbox.env.http.exampleList')}`,
213
+ `curl -s -H "authorization: Bearer $TOKEN" "${catalog.baseUrl}${listTools.target}"`,
214
+ '',
215
+ `# ${t('sandbox.env.http.exampleCall')}`,
216
+ `curl -s -X POST -H "authorization: Bearer $TOKEN" "${catalog.baseUrl}${listTools.target}/get_server_info"`,
217
+ ].join('\n') : ''
218
+ // 按状态码归并:HTTP 消费者手里先有状态码,要问的是「这个 429 可能是哪几种原因」。
219
+ const keyword = query.trim().toLocaleLowerCase()
220
+ const grouped = new Map<number, string[]>()
221
+ for (const { code, status } of catalog.errorStatuses) {
222
+ if (keyword && !code.includes(keyword) && !String(status).includes(keyword)) continue
223
+ grouped.set(status, [...grouped.get(status) ?? [], code])
224
+ }
225
+ const statusGroups = [...grouped].sort(([left], [right]) => left - right)
226
+ const code = (text: string) => <code className="rounded bg-muted px-1 py-0.5 font-mono text-[11px]">{text}</code>
227
+
228
+ return (
229
+ <div className="flex flex-col gap-4 p-4">
230
+ {!catalog.enabled && (
231
+ <p className="rounded-lg bg-amber-500/10 p-3 text-xs leading-5 text-amber-800 dark:text-amber-300">{t('sandbox.env.http.disabledNotice')}</p>
232
+ )}
233
+ <Summary items={[
234
+ { value: catalog.routes.length, label: t('sandbox.env.http.routes') },
235
+ { value: catalog.errorStatuses.length, label: t('sandbox.env.http.errorMappings') },
236
+ { value: bodyLimit, label: t('sandbox.env.http.bodyLimit') },
237
+ ]} />
238
+ <div className="flex flex-wrap items-center gap-1.5 text-xs">
239
+ <span className="mr-1 text-muted-foreground">{t('sandbox.env.http.protocol')}</span>
240
+ <Badge variant={catalog.enabled ? 'secondary' : 'outline'}>{t(catalog.enabled ? 'sandbox.env.enabled' : 'sandbox.env.http.closed')}</Badge>
241
+ <Badge variant="outline">{t('sandbox.env.http.basePath', { path: catalog.basePath })}</Badge>
242
+ <Badge variant="outline">{t('sandbox.env.http.version', { version: catalog.version })}</Badge>
243
+ </div>
244
+ <section className="flex flex-col gap-2">
245
+ <h3 className="text-xs font-medium">{t('sandbox.env.http.auth')}</h3>
246
+ <p className="text-xs leading-5 text-muted-foreground">
247
+ {t('sandbox.env.http.authBefore')}{code(catalog.baseUrl)}{t('sandbox.env.http.authMiddle')}{code('Authorization')}{t('sandbox.env.http.authCarry')}{code(`Bearer <${t('sandbox.env.http.tokenPlaceholder')}>`)}{t('sandbox.env.http.authAfter')}
248
+ </p>
249
+ {example && <pre className="overflow-auto rounded-lg bg-muted/50 p-3 font-mono text-[11px] leading-5">{example}</pre>}
250
+ </section>
251
+ <section className="flex flex-col gap-2">
252
+ <h3 className="text-xs font-medium">{t('sandbox.env.http.routes')}</h3>
253
+ {catalog.routes.map((route) => (
254
+ <article key={route.kind} className="flex flex-col gap-1 rounded-lg px-3 py-2.5 ring-1 ring-border">
255
+ <p className="flex min-w-0 items-center gap-2">
256
+ <Badge variant="secondary" className="font-mono">{route.method}</Badge>
257
+ <code className="truncate font-mono text-xs">{route.target}</code>
258
+ </p>
259
+ <small className="text-[11px] text-muted-foreground">{route.summary}</small>
260
+ </article>
261
+ ))}
262
+ </section>
263
+ <section className="flex flex-col gap-2">
264
+ <h3 className="text-xs font-medium">{t('sandbox.env.http.statusTitle')}</h3>
265
+ <p className="text-xs leading-5 text-muted-foreground">{t('sandbox.env.http.statusBefore')}{code('Retry-After')}{t('sandbox.env.http.statusAfter')}</p>
266
+ <SearchInput value={query} onChange={setQuery} placeholder={t('sandbox.env.http.statusSearch')} />
267
+ {statusGroups.map(([status, codes]) => (
268
+ <article key={status} className="flex items-start gap-3 rounded-lg px-3 py-2 ring-1 ring-border">
269
+ <Badge variant={status >= 500 ? 'destructive' : 'outline'} className="font-mono">{status}</Badge>
270
+ <span className="flex min-w-0 flex-wrap gap-1">{codes.map((value) => <code key={value} className={cn('rounded bg-muted px-1 py-0.5 font-mono text-[11px]')}>{value}</code>)}</span>
271
+ </article>
272
+ ))}
273
+ {!statusGroups.length && <p className="py-4 text-center text-xs text-muted-foreground">{t('sandbox.env.http.noStatus')}</p>}
274
+ </section>
275
+ </div>
276
+ )
277
+ }
@@ -0,0 +1,257 @@
1
+ import * as React from 'react'
2
+ import { CopyIcon, PlusIcon } from 'lucide-react'
3
+ import {
4
+ AlertDialog,
5
+ AlertDialogAction,
6
+ AlertDialogCancel,
7
+ AlertDialogContent,
8
+ AlertDialogDescription,
9
+ AlertDialogFooter,
10
+ AlertDialogHeader,
11
+ AlertDialogTitle,
12
+ Badge,
13
+ Button,
14
+ Checkbox,
15
+ Dialog,
16
+ DialogContent,
17
+ DialogDescription,
18
+ DialogFooter,
19
+ DialogHeader,
20
+ DialogTitle,
21
+ Input,
22
+ Label,
23
+ } from '@chatluna/ui-kit'
24
+ import { toast } from '@chatluna/ui-client/client'
25
+ import type { SandboxMcpScope, SandboxTestPublicCredential } from '../../src/mcp/types'
26
+ import { useT } from '../i18n'
27
+ import { useDiscardConfirm } from '../shared/discard-confirm'
28
+ import { useRetained } from '../shared/use-retained'
29
+ import { errorText, invoke } from '../workspace/store'
30
+ import { MCP_SCOPES } from './capability-catalog'
31
+
32
+ /**
33
+ * 测试凭证:同一个凭证同时用于 MCP 客户端与 HTTP 脚本。每个写操作成功后都重新列举一次,
34
+ * 服务端是凭证的唯一拥有者,本地拼接会在 Token 明文可见性这类派生字段上与服务端分叉。
35
+ */
36
+ export function TestCredentialManager() {
37
+ const t = useT()
38
+ const [credentials, setCredentials] = React.useState<SandboxTestPublicCredential[]>([])
39
+ const [listError, setListError] = React.useState('')
40
+ const [form, setForm] = React.useState<{ editing?: SandboxTestPublicCredential, name: string, scopes: SandboxMcpScope[] }>()
41
+ const [formError, setFormError] = React.useState('')
42
+ const [saving, setSaving] = React.useState(false)
43
+ const [createdToken, setCreatedToken] = React.useState('')
44
+ const [revoking, setRevoking] = React.useState<SandboxTestPublicCredential>()
45
+
46
+ const refresh = React.useCallback(async () => {
47
+ try {
48
+ setCredentials(await invoke('onebot-sandbox.test-credentials', undefined))
49
+ setListError('')
50
+ } catch (failure) {
51
+ setListError(errorText(failure, t('sandbox.credential.loadFailed')))
52
+ }
53
+ }, [t])
54
+ React.useEffect(() => {
55
+ void refresh()
56
+ }, [refresh])
57
+
58
+ const guard = async (fallback: string, action: () => Promise<void>) => {
59
+ setSaving(true)
60
+ try {
61
+ await action()
62
+ } catch (failure) {
63
+ setFormError(errorText(failure, fallback))
64
+ } finally {
65
+ setSaving(false)
66
+ }
67
+ }
68
+
69
+ const submit = async () => {
70
+ if (!form) return
71
+ setFormError('')
72
+ if (!form.name.trim() || !form.scopes.length) {
73
+ setFormError(t('sandbox.credential.invalid'))
74
+ return
75
+ }
76
+ const editing = form.editing
77
+ if (editing) {
78
+ await guard(t('sandbox.credential.saveFailed'), async () => {
79
+ await invoke('onebot-sandbox.update-test-credential', { id: editing.id, name: form.name, scopes: form.scopes })
80
+ setForm(undefined)
81
+ await refresh()
82
+ })
83
+ } else {
84
+ await guard(t('sandbox.credential.createFailed'), async () => {
85
+ const created = await invoke('onebot-sandbox.create-test-credential', { name: form.name, scopes: form.scopes })
86
+ setForm(undefined)
87
+ setCreatedToken(created.token)
88
+ await refresh()
89
+ })
90
+ }
91
+ }
92
+
93
+ const rotate = async () => {
94
+ const editing = form?.editing
95
+ if (!editing) return
96
+ setFormError('')
97
+ await guard(t('sandbox.credential.rotateFailed'), async () => {
98
+ const rotated = await invoke('onebot-sandbox.rotate-test-credential-token', { id: editing.id })
99
+ setForm((value) => value && { ...value, editing: rotated })
100
+ await refresh()
101
+ })
102
+ }
103
+
104
+ const run = async (fallback: string, action: () => Promise<unknown>) => {
105
+ try {
106
+ await action()
107
+ await refresh()
108
+ } catch (failure) {
109
+ setListError(errorText(failure, fallback))
110
+ }
111
+ }
112
+
113
+ const copy = async (token: string) => {
114
+ try {
115
+ await navigator.clipboard.writeText(token)
116
+ toast.success(t('sandbox.credential.copied'))
117
+ } catch {
118
+ toast.error(t('sandbox.credential.copyFailed'))
119
+ }
120
+ }
121
+
122
+ // 退场动画期间沿用最后一份内容,标题、Token 区与输入框不在淡出时变成空态。
123
+ const shownForm = useRetained(form)
124
+ const shownRevoking = useRetained(revoking)
125
+ const shownToken = useRetained(createdToken || undefined) ?? ''
126
+ const baseline = form?.editing ? { name: form.editing.name, scopes: form.editing.scopes } : { name: '', scopes: ['read'] }
127
+ const dirty = !!form && (form.name !== baseline.name || [...form.scopes].sort().join() !== [...baseline.scopes].sort().join())
128
+ const { requestClose, confirm } = useDiscardConfirm(dirty, () => setForm(undefined))
129
+
130
+ const scopeText = (scopes: readonly SandboxMcpScope[]) => scopes.map((scope) => t(`sandbox.scope.${scope}`)).join(' · ')
131
+ const time = (value: string) => new Intl.DateTimeFormat(undefined, { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }).format(new Date(value))
132
+ const editing = shownForm?.editing
133
+
134
+ return (
135
+ <div className="flex flex-col gap-3 p-4">
136
+ <div className="flex flex-wrap items-start justify-between gap-3">
137
+ <p className="max-w-xl text-xs leading-5 text-muted-foreground">{t('sandbox.credential.hint')}</p>
138
+ <Button size="sm" onClick={() => {
139
+ setFormError('')
140
+ setForm({ name: '', scopes: ['read'] })
141
+ }}><PlusIcon />{t('sandbox.credential.create')}</Button>
142
+ </div>
143
+ {listError && <p role="alert" className="text-xs text-destructive">{listError}</p>}
144
+ {credentials.map((credential) => (
145
+ <article key={credential.id} className="flex flex-wrap items-center justify-between gap-3 rounded-lg px-3 py-2.5 ring-1 ring-border">
146
+ <button type="button" className="flex min-w-0 flex-col gap-0.5 text-left" onClick={() => {
147
+ setFormError('')
148
+ setForm({ editing: credential, name: credential.name, scopes: [...credential.scopes] })
149
+ }}>
150
+ <strong className="truncate text-xs font-medium">{credential.name}</strong>
151
+ <small className="text-[11px] text-muted-foreground">{scopeText(credential.scopes)} · {time(credential.createdAt)}</small>
152
+ </button>
153
+ <div className="flex shrink-0 items-center gap-1.5">
154
+ <Badge variant={credential.enabled ? 'secondary' : 'outline'}>{t(credential.enabled ? 'sandbox.env.enabled' : 'sandbox.env.disabled')}</Badge>
155
+ <Button size="sm" variant="outline" onClick={() => {
156
+ setFormError('')
157
+ setForm({ editing: credential, name: credential.name, scopes: [...credential.scopes] })
158
+ }}>{t('sandbox.credential.view')}</Button>
159
+ <Button size="sm" variant="outline" onClick={() => void run(t('sandbox.common.failed'), () => invoke('onebot-sandbox.set-test-credential-enabled', { id: credential.id, enabled: !credential.enabled }))}>
160
+ {t(credential.enabled ? 'sandbox.credential.disable' : 'sandbox.credential.enable')}
161
+ </Button>
162
+ <Button size="sm" variant="destructive" onClick={() => setRevoking(credential)}>{t('sandbox.credential.revoke')}</Button>
163
+ </div>
164
+ </article>
165
+ ))}
166
+ {!credentials.length && !listError && <p className="py-6 text-center text-xs text-muted-foreground">{t('sandbox.credential.empty')}</p>}
167
+
168
+ <Dialog open={!!form} onOpenChange={(open) => !open && requestClose()}>
169
+ <DialogContent className="flex flex-col overflow-hidden">
170
+ <DialogHeader>
171
+ <DialogTitle>{t(editing ? 'sandbox.credential.viewTitle' : 'sandbox.credential.createTitle')}</DialogTitle>
172
+ <DialogDescription>{t(editing ? 'sandbox.credential.viewDescription' : 'sandbox.credential.createDescription')}</DialogDescription>
173
+ </DialogHeader>
174
+ <div className="-mx-5 flex min-h-0 flex-col gap-4 overflow-y-auto px-5">
175
+ <div className="flex flex-col gap-2">
176
+ <Label htmlFor="sandbox-credential-name">{t('sandbox.credential.name')}</Label>
177
+ <Input id="sandbox-credential-name" autoComplete="off" value={shownForm?.name ?? ''} onChange={(event) => setForm((value) => value && { ...value, name: event.target.value })} />
178
+ </div>
179
+ <fieldset className="flex flex-col gap-2">
180
+ <legend className="mb-2 text-sm font-medium">{t('sandbox.credential.scopes')}</legend>
181
+ <div className="grid grid-cols-2 gap-2">
182
+ {MCP_SCOPES.map((scope) => (
183
+ <label key={scope} className="flex items-center gap-2 text-sm">
184
+ <Checkbox
185
+ checked={shownForm?.scopes.includes(scope) ?? false}
186
+ onCheckedChange={(checked) => setForm((value) => value && {
187
+ ...value,
188
+ scopes: checked === true ? [...new Set([...value.scopes, scope])] : value.scopes.filter((item) => item !== scope),
189
+ })}
190
+ />
191
+ {t(`sandbox.scope.${scope}`)}
192
+ </label>
193
+ ))}
194
+ </div>
195
+ </fieldset>
196
+ {editing && (
197
+ <div className="flex flex-col gap-2">
198
+ <Label>Token</Label>
199
+ {editing.token ? (
200
+ <div className="flex items-center gap-2">
201
+ <code className="min-w-0 flex-1 rounded-md bg-muted px-2.5 py-2 font-mono text-xs break-all">{editing.token}</code>
202
+ <Button size="icon-sm" variant="ghost" aria-label={t('sandbox.credential.copy')} onClick={() => void copy(editing.token!)}><CopyIcon /></Button>
203
+ </div>
204
+ ) : (
205
+ <p className="text-xs leading-5 text-muted-foreground">{t('sandbox.credential.noPlainToken')}</p>
206
+ )}
207
+ <Button size="sm" variant="outline" className="self-start" disabled={saving} onClick={() => void rotate()}>
208
+ {t(editing.token ? 'sandbox.credential.rotate' : 'sandbox.credential.generate')}
209
+ </Button>
210
+ <p className="text-[11px] text-muted-foreground">
211
+ {t('sandbox.credential.createdAt', { time: time(editing.createdAt) })} · {t(editing.enabled ? 'sandbox.env.enabled' : 'sandbox.env.disabled')}
212
+ </p>
213
+ </div>
214
+ )}
215
+ {formError && <p role="alert" className="text-xs text-destructive">{formError}</p>}
216
+ </div>
217
+ <DialogFooter>
218
+ <Button variant="outline" onClick={requestClose}>{t('sandbox.common.cancel')}</Button>
219
+ <Button disabled={saving} onClick={() => void submit()}>{t(editing ? 'sandbox.common.save' : 'sandbox.credential.createAction')}</Button>
220
+ </DialogFooter>
221
+ {confirm}
222
+ </DialogContent>
223
+ </Dialog>
224
+
225
+ <Dialog open={!!createdToken} onOpenChange={(open) => !open && setCreatedToken('')}>
226
+ <DialogContent>
227
+ <DialogHeader>
228
+ <DialogTitle>{t('sandbox.credential.tokenTitle')}</DialogTitle>
229
+ <DialogDescription>{t('sandbox.credential.tokenDescription')}</DialogDescription>
230
+ </DialogHeader>
231
+ <div className="flex items-center gap-2">
232
+ <Input readOnly value={shownToken} className="font-mono text-xs!" />
233
+ <Button size="icon-sm" variant="ghost" aria-label={t('sandbox.credential.copy')} onClick={() => void copy(shownToken)}><CopyIcon /></Button>
234
+ </div>
235
+ <DialogFooter><Button onClick={() => setCreatedToken('')}>{t('sandbox.credential.saved')}</Button></DialogFooter>
236
+ </DialogContent>
237
+ </Dialog>
238
+
239
+ <AlertDialog open={!!revoking} onOpenChange={(open) => !open && setRevoking(undefined)}>
240
+ <AlertDialogContent>
241
+ <AlertDialogHeader>
242
+ <AlertDialogTitle>{t('sandbox.credential.revokeTitle', { name: shownRevoking?.name ?? '' })}</AlertDialogTitle>
243
+ <AlertDialogDescription>{t('sandbox.credential.revokeDescription')}</AlertDialogDescription>
244
+ </AlertDialogHeader>
245
+ <AlertDialogFooter>
246
+ <AlertDialogCancel>{t('sandbox.common.cancel')}</AlertDialogCancel>
247
+ <AlertDialogAction variant="destructive" onClick={() => {
248
+ const target = revoking
249
+ setRevoking(undefined)
250
+ if (target) void run(t('sandbox.common.failed'), () => invoke('onebot-sandbox.revoke-test-credential', { id: target.id }))
251
+ }}>{t('sandbox.credential.revoke')}</AlertDialogAction>
252
+ </AlertDialogFooter>
253
+ </AlertDialogContent>
254
+ </AlertDialog>
255
+ </div>
256
+ )
257
+ }