dsh-rayrun-bots 0.0.0-stage → 0.1.1-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,3837 @@
1
+ /**
2
+ * Client half of the Rayrun Bot bundle.
3
+ *
4
+ * v0.1 shell: chat list, conversation, details, new bot, setup, and settings,
5
+ * in the layout of docs/ui-design.md and docs/mockups/index.html. Copy comes
6
+ * from locale/en.json and locale/zh.json (embedded below; the locale audit
7
+ * checks they match). The host half persists the bot roster; the chat list
8
+ * reads it when it has entries, and creating a bot writes through to it.
9
+ * Messages, approvals, routines and settings on this page are still in-memory
10
+ * preview state; decisions are not sent to a worker.
11
+ *
12
+ * Preview states with these DSH page URL parameters: ?first-run=1,
13
+ * ?low-balance=1, ?computer=live|reconnecting|sleeping|unreachable.
14
+ */
15
+ window.__ModuleLoader__.load({
16
+ id: 'dsh-rayrun-bots',
17
+ factory(require) {
18
+ const React = require('react')
19
+ const h = React.createElement
20
+ const { useEffect, useRef, useState } = React
21
+ const PREVIEW = new URLSearchParams(window.location.search)
22
+ const FIRST_RUN_PREVIEW = PREVIEW.get('first-run') === '1'
23
+ const LOW_BALANCE_PREVIEW = PREVIEW.get('low-balance') === '1'
24
+ const COMPUTER_PREVIEW = ['live', 'reconnecting', 'sleeping', 'unreachable'].includes(PREVIEW.get('computer'))
25
+ ? PREVIEW.get('computer')
26
+ : null
27
+
28
+ const EN = {
29
+ "meta": {
30
+ "title": "Rayrun Bot",
31
+ "description": "Adds a Bots entry and the v0.1 three-column shell: chat list, conversation with approval cards, details, setup and settings. Everything on the page is an in-memory preview; no machine and no credential are used."
32
+ },
33
+ "panel": {
34
+ "label": "Bots"
35
+ },
36
+ "brand": "Rayrun Bot",
37
+ "preview": {
38
+ "badge": "Preview"
39
+ },
40
+ "chat": {
41
+ "working": "Working…",
42
+ "simulatedReply": "Done. This reply is simulated in the preview; the approval below is also local.",
43
+ "simulatedSnippet": "Needs approval: simulated result",
44
+ "simulatedApprovalTitle": "Post the simulated result to the team channel",
45
+ "simulatedApprovalMeta": "Requested just now",
46
+ "simulatedTarget": "Team channel",
47
+ "sending": "Sending…",
48
+ "sendFailed": "Could not send. Try again.",
49
+ "runtimeUnavailable": "The cloud runtime is unavailable. Install dsh-rayrun-computer and reload DSH.",
50
+ "connectRayrun": "Connect Rayrun in setup before sending.",
51
+ "noComputer": "No cloud computer yet. Create one in setup first.",
52
+ "machineBusy": "The cloud computer is busy. Try again shortly.",
53
+ "balanceLow": "The Rayrun balance is low. Add credit before sending.",
54
+ "queueFull": "Too many messages are queued. Wait for a reply.",
55
+ "messageInvalid": "That message can't be sent: it is empty, too long, or invalid.",
56
+ "historyFailed": "Could not load this conversation. Reload the page to retry.",
57
+ "turnTimeout": "The cloud turn is taking too long. Reopen the page to check again.",
58
+ "turnInterrupted": "The previous turn was interrupted. Send it again.",
59
+ "errorTitle": "Turn failed"
60
+ },
61
+ "list": {
62
+ "search": "Search",
63
+ "searchPlaceholder": "Search bots",
64
+ "newBot": "New bot",
65
+ "settings": "Settings",
66
+ "empty": "No matching bots"
67
+ },
68
+ "attention": {
69
+ "needs": "needs attention",
70
+ "unread": "unread",
71
+ "working": "working"
72
+ },
73
+ "approval": {
74
+ "title": "Needs approval",
75
+ "allowOnce": "Allow once",
76
+ "deny": "Deny",
77
+ "waits": "waits for you",
78
+ "expires": "expires in {n} min",
79
+ "expired": "Expired — the bot did not act",
80
+ "irreversible": "This can't be undone.",
81
+ "outside": "This shares data outside your computer.",
82
+ "originChat": "From this chat",
83
+ "originBackground": "From a routine",
84
+ "riskOutside": "Outside your computer",
85
+ "riskIrreversible": "Can't be undone",
86
+ "warning": "This shares data outside your computer, and it can't be undone.",
87
+ "allowedLocal": "Allowed once, on this page only. Nothing was sent.",
88
+ "deniedLocal": "Denied, on this page only. Nothing was sent.",
89
+ "snippetAllowed": "Allowed once — not sent",
90
+ "snippetDenied": "Denied — not sent",
91
+ "realStart": "Start cloud computer “{machine}”",
92
+ "realStop": "Stop cloud computer “{machine}”",
93
+ "realPause": "Pause cloud computer “{machine}”",
94
+ "realResume": "Resume cloud computer “{machine}”",
95
+ "realUnknown": "Run an approved action on “{machine}”",
96
+ "realMeta": "Requested {time}",
97
+ "allowedReal": "Approved and executed on your local side.",
98
+ "deniedReal": "Denied. Nothing was executed.",
99
+ "executionPending": "Approved. Waiting for local execution.",
100
+ "executionFailed": "Approved, but local execution failed. Nothing more will run.",
101
+ "executionRefused": "Approved, but this action is not supported locally. Nothing was executed.",
102
+ "riskCost": "Spends machine time",
103
+ "allowedSide": "Approved",
104
+ "deniedSide": "Denied",
105
+ "waitingSide": "Waiting to execute",
106
+ "failedSide": "Execution failed",
107
+ "continue": "Continue bot",
108
+ "continuePrompt": "Continue from the approval result above. Do not repeat the approved action; ask before another controlled action."
109
+ },
110
+ "draft": {
111
+ "send": "Send",
112
+ "discard": "Discard"
113
+ },
114
+ "details": {
115
+ "activity": "Activity",
116
+ "library": "Library",
117
+ "recent": "Recent",
118
+ "recentEmpty": "No activity yet.",
119
+ "recentEmptyHint": "Replies and receipts show up here after your bot works.",
120
+ "upcoming": "Upcoming",
121
+ "computer": "Computer",
122
+ "usage": "Usage",
123
+ "jobComputer": "{job} · {computer}"
124
+ },
125
+ "receipt": {
126
+ "ready": "Ready",
127
+ "waiting": "Waiting",
128
+ "done": "Done"
129
+ },
130
+ "library": {
131
+ "today": "Today",
132
+ "week": "This week",
133
+ "older": "Older",
134
+ "empty": "No artifacts yet.",
135
+ "emptyHint": "Files your bot saves in the workspace show up here."
136
+ },
137
+ "routine": {
138
+ "empty": "No routines yet.",
139
+ "emptyHint": "Routines run on a schedule and stop for approval before acting outside your computer.",
140
+ "paused": "All routines are paused.",
141
+ "origin": "Scheduled routine",
142
+ "every": "Every {minutes} min",
143
+ "everyHours": "Every {hours} h",
144
+ "everyDays": "Every {days} d",
145
+ "add": "New routine",
146
+ "titleLabel": "Routine name",
147
+ "promptLabel": "What should the bot do?",
148
+ "minutesLabel": "Every (minutes)",
149
+ "costHint": "A due run may wake a stopped computer and incur machine-hour charges.",
150
+ "create": "Create routine",
151
+ "cancel": "Cancel",
152
+ "remove": "Remove",
153
+ "createFailed": "Could not create the routine: {message}",
154
+ "updateFailed": "Could not update the routine: {message}",
155
+ "removeFailed": "Could not remove the routine: {message}",
156
+ "on": "on",
157
+ "off": "off"
158
+ },
159
+ "computer": {
160
+ "live": "live",
161
+ "reconnecting": "reconnecting…",
162
+ "unreachable": "Couldn't reach the computer.",
163
+ "sleeping": "sleeping",
164
+ "takeOver": "Take over",
165
+ "open": "Open",
166
+ "view": "View",
167
+ "onComputer": "On the computer · {where}",
168
+ "desktopLater": "The desktop opens in the cloud-computer plugin. This page can't open it yet.",
169
+ "noMachine": "No cloud computer yet. Create one in the cloud-computer plugin.",
170
+ "noMachineShort": "No computer",
171
+ "stop": "Stop",
172
+ "stopConfirm": "Stop the computer? Running work will pause.",
173
+ "stopConfirmAction": "Stop computer",
174
+ "cancel": "Cancel",
175
+ "stopping": "Stopping…",
176
+ "stopped": "Computer stopped.",
177
+ "stopTimeout": "The computer is still stopping.",
178
+ "stopFailed": "Could not stop the computer: {message}",
179
+ "connectFirst": "Connect Rayrun first (Settings → Set up).",
180
+ "popupBlocked": "Allow pop-ups for this page to open the desktop.",
181
+ "starting": "Starting the computer…",
182
+ "startTimeout": "The computer did not start in time.",
183
+ "noDesktop": "This computer has no remote desktop.",
184
+ "openFailed": "Could not open the computer: {message}",
185
+ "opened": "Computer opened in a new tab.",
186
+ "passwordTitle": "Desktop password",
187
+ "passwordBody": "Use this password on the desktop page.",
188
+ "passwordEmpty": "No desktop password found.",
189
+ "copy": "Copy",
190
+ "copied": "Copied",
191
+ "copyFailed": "Copy failed. Select the password manually.",
192
+ "close": "Close"
193
+ },
194
+ "notice": {
195
+ "recovering": "The bot host is restarting. This conversation resumes on its own.",
196
+ "reconnecting": "Computer reconnecting… retrying in 5s",
197
+ "sleeping": "Computer is sleeping. Open it in the cloud-computer plugin to wake it.",
198
+ "attach": "Attachments aren't available in this preview.",
199
+ "preview": "In-memory preview. Nothing on this page is saved, and approvals are not sent to a worker."
200
+ },
201
+ "composer": {
202
+ "placeholder": "Message {name}…",
203
+ "attach": "Add attachment",
204
+ "send": "Send"
205
+ },
206
+ "usage": {
207
+ "balanceLine": "Balance {balance} · {hours} machine-hours",
208
+ "weekLine": "This week {spend} · idle stop {idle}",
209
+ "liveLine": "Live from your Rayrun account · idle stop {idle}",
210
+ "sampleBalance": "¥41.20",
211
+ "sampleHours": "38.4",
212
+ "sampleSpend": "¥6.80"
213
+ },
214
+ "cost": {
215
+ "low": "Balance is low — top up in the Rayrun console. Stop is safe; destroy is not.",
216
+ "lowShort": "Balance low"
217
+ },
218
+ "empty": {
219
+ "heading": "No bots yet",
220
+ "body": "Create one with the plus button. It stays on this page until a bot host exists.",
221
+ "thread": "No messages yet. What you type stays on this page.",
222
+ "threadReal": "No messages yet. Say hello to start a cloud turn.",
223
+ "snippet": "No messages yet"
224
+ },
225
+ "newBot": {
226
+ "title": "New bot",
227
+ "sub": "Give it a name and one job. Instructions can be changed later.",
228
+ "monogramHint": "Letter avatar · color is assigned from the name",
229
+ "name": "Name",
230
+ "job": "Job, one line",
231
+ "instructions": "Instructions, optional",
232
+ "placeholder": "You are {name}, a teammate on the user's team. Your job: …",
233
+ "defaultName": "Weekly Watch",
234
+ "defaultJob": "Summarises weekly PRs and drafts the digest",
235
+ "cancel": "Cancel",
236
+ "create": "Create bot"
237
+ },
238
+ "persona": {
239
+ "template": "You are {name}, a teammate on the user's team.\nYour job: {job}.\nWork in short, factual updates. Say what you did, what you did not do, and what you need next. Ask before any action that leaves this computer (messages, publishing, spending, another machine). Never claim work you have not verified.\nIf something is unclear, ask one question instead of guessing."
240
+ },
241
+ "setup": {
242
+ "title": "Set up Rayrun Bot",
243
+ "sub": "Four steps. Each one says what is missing and where to fix it.",
244
+ "back": "Back",
245
+ "skip": "Skip for now",
246
+ "continue": "Continue",
247
+ "steps": {
248
+ "dependency": "Dependency",
249
+ "rayrun": "Rayrun",
250
+ "key": "Computer",
251
+ "bot": "First bot"
252
+ },
253
+ "dependencyTitle": "Cloud-computer plugin",
254
+ "dependencyBody": "Cloud computers come from the separate dsh-rayrun-computer plugin. The host checks whether it is installed; fix it and restart DSH before connecting Rayrun.",
255
+ "dependencyStatus": "Not checked",
256
+ "dependencyOk": "Installed · v{version}",
257
+ "dependencyMissing": "Missing — install dsh-rayrun-computer, then restart DSH.",
258
+ "dependencyIncompatible": "Not supported · {version} (need {required}).",
259
+ "rayrunTitle": "Connect Rayrun",
260
+ "rayrunBody": "The cloud computer is provided by Rayrun. Paste a Rayrun API token; the cloud-computer plugin stores it in the DSH vault.",
261
+ "notConnected": "Not connected",
262
+ "tokenPlaceholder": "Paste a Rayrun API token",
263
+ "useToken": "Use API token",
264
+ "tokenHint": "Paste a Rayrun API token from the console. The cloud-computer plugin stores it in the DSH vault.",
265
+ "tokenRequired": "Paste a Rayrun API token first.",
266
+ "connecting": "Connecting…",
267
+ "connected": "Connected · balance {balance} · {machines} machines",
268
+ "connectedShort": "Connected",
269
+ "connectFailed": "Could not connect: {message}",
270
+ "tokenRejected": "Rayrun rejected this API token. Check the token and try again.",
271
+ "connect": "Connect",
272
+ "accountLine": "Account: — · Balance: —",
273
+ "computerTitle": "Cloud computer",
274
+ "computerBody": "Bots creates one cloud computer on your Rayrun account. It is billable while it runs. The DeepSeek key becomes its model credential and does not go into the workspace.",
275
+ "computerExisting": "Using your existing computer · {name}",
276
+ "computerExistingHint": "The cloud-computer plugin owns this machine's settings and model credential.",
277
+ "computerNeedsRayrun": "Connect Rayrun on the previous step before creating a computer.",
278
+ "computerChecking": "Checking your Rayrun computers…",
279
+ "computerLoadFailed": "Could not read your Rayrun computers: {message}",
280
+ "computerName": "Computer name",
281
+ "computerKeyPlaceholder": "Paste a DeepSeek API key (optional)",
282
+ "computerKeyHint": "Optional if this machine already has a DeepSeek credential.",
283
+ "computerCreate": "Create cloud computer",
284
+ "computerCreating": "Creating… about 15 seconds",
285
+ "computerCreated": "Created · {name}",
286
+ "computerCreateFailed": "Could not create the computer: {message}",
287
+ "computerCost": "Creates a billable machine on your Rayrun account. Bots never destroys it.",
288
+ "botTitle": "First bot",
289
+ "botBody": "Give it a name and one job. It is added to this page only, not to a cloud computer."
290
+ },
291
+ "settings": {
292
+ "title": "Settings",
293
+ "sub": "Account, usage, and the few settings this plugin owns.",
294
+ "account": "Account",
295
+ "usage": "Usage",
296
+ "notifications": "Notifications",
297
+ "appearance": "Appearance",
298
+ "rayrunAccount": "Rayrun account",
299
+ "rayrunHint": "Token stays in the DSH vault · host side only",
300
+ "setup": "Set up",
301
+ "host": "Rayrun Bot host",
302
+ "hostHint": "Same-origin health check. No Rayrun token or DeepSeek key.",
303
+ "hostChecking": "Checking…",
304
+ "hostLoaded": "Loaded · v{version} · bot layer not ready",
305
+ "hostReady": "Ready · v{version}",
306
+ "hostDepMissing": "Cloud-computer plugin missing — install dsh-rayrun-computer, then restart DSH.",
307
+ "hostDepVersion": "Cloud-computer plugin {version} is not supported (need {required}).",
308
+ "retry": "Retry",
309
+ "plugin": "Cloud-computer plugin",
310
+ "pluginHint": "dsh-rayrun-computer v1.0.0",
311
+ "pluginOk": "OK",
312
+ "pluginMissing": "Missing",
313
+ "pluginIncompatible": "Incompatible",
314
+ "pluginUnknown": "Unknown",
315
+ "usageHint": "From your Rayrun account. Same-origin RPC; no token in the page.",
316
+ "usageLine": "Balance {balance} · {hours} machine-hours · {machines} machines",
317
+ "usageConnect": "Connect Rayrun to see usage.",
318
+ "usageFailed": "Could not read usage: {message}",
319
+ "idle": "Idle stop",
320
+ "idleHint": "Stop the computer when idle. Never destroy it.",
321
+ "idle15": "15 minutes",
322
+ "idle30": "30 minutes",
323
+ "idleOff": "Off",
324
+ "lowBalance": "Low-balance reminder",
325
+ "lowBalanceHint": "Show a notice when the balance drops below this.",
326
+ "notify": "Notifications",
327
+ "notifyHint": "Notify when a bot finishes or needs you.",
328
+ "language": "Language",
329
+ "languageHint": "Chinese is primary; English is available.",
330
+ "langEn": "English",
331
+ "langZh": "简体中文"
332
+ },
333
+ "sample": {
334
+ "user": {
335
+ "name": "Haoyi",
336
+ "initials": "HY",
337
+ "foot": "Rayrun connected · {balance}"
338
+ },
339
+ "nora": {
340
+ "name": "Nora",
341
+ "job": "weekly digest",
342
+ "snippet": "Draft is in the library, waiting for you",
343
+ "time": "20:07",
344
+ "user": "Summarize last week's PRs and draft the weekly digest. Wait for me before publishing.",
345
+ "day": "Today 20:07",
346
+ "reply1": "The draft is ready. I kept it to five sections, and each item links back to its PR.\n\n- **Scope.** 14 merged PRs, 2 still open, 1 reverted.\n- **Draft.** `week-45-digest.md` in the workspace, 420 words.\n- **Next.** Publishing to `#weekly` needs your approval.",
347
+ "reply2": "The draft is in the Library tab if you want to read it first. I'll wait for your answer.",
348
+ "computerTitle": "On the computer · Feishu #weekly",
349
+ "computerSub": "Pasted the digest, waiting for your approval",
350
+ "approvalTitle": "Publish “Week 45 digest” to Feishu #weekly",
351
+ "approvalMeta": "Requested 20:07",
352
+ "r1": "Draft the weekly digest",
353
+ "r1meta": "09:13 · 3 artifacts · today ¥3.10",
354
+ "r2": "Publish to #weekly",
355
+ "r2meta": "Needs your approval · waits for you",
356
+ "r3": "Docs refresh",
357
+ "r3meta": "08:40 · 3 pages · today ¥0.60",
358
+ "f1": "week-45-digest.md",
359
+ "f1badge": "420 words",
360
+ "f1meta": "Created by Nora · 09:13",
361
+ "f2": "channel-preview.png",
362
+ "f2badge": "Image",
363
+ "f2meta": "Sent in this chat · 09:12",
364
+ "f3": "week-44-digest.md",
365
+ "f3badge": "Done",
366
+ "f3meta": "Created by Nora · Monday",
367
+ "f4": "Feishu channel",
368
+ "f4badge": "Link",
369
+ "f4meta": "Last week"
370
+ },
371
+ "eli": {
372
+ "name": "Eli",
373
+ "job": "channel publish",
374
+ "snippet": "Needs approval: publish the digest",
375
+ "time": "09:13",
376
+ "day": "Today 09:13",
377
+ "reply": "Publishing would send the digest to the channel. I'm stopped here until you approve.",
378
+ "approvalTitle": "Publish “Week 45 digest” to Feishu #weekly",
379
+ "approvalMeta": "Requested 09:13",
380
+ "expiredDay": "Yesterday 18:00",
381
+ "expiredTitle": "Publish “Week 44 digest” to Feishu #weekly",
382
+ "expiredMeta": "Requested yesterday 18:00"
383
+ },
384
+ "june": {
385
+ "name": "June",
386
+ "job": "docs",
387
+ "snippet": "Docs refresh finished — 3 pages",
388
+ "time": "08:40",
389
+ "day": "Today 08:40",
390
+ "reply": "Docs refresh is finished, 3 pages. Nothing needs your approval.",
391
+ "r1": "Docs refresh",
392
+ "r1meta": "08:40 · 3 pages · today ¥0.60"
393
+ },
394
+ "routine": {
395
+ "weekly": "Weekly digest",
396
+ "weeklyWhen": "Friday · 09:00",
397
+ "inbox": "Inbox sweep",
398
+ "inboxWhen": "Weekdays · 08:00",
399
+ "standup": "Standup notes",
400
+ "standupWhen": "Weekdays · 18:00"
401
+ },
402
+ "computerName": "dsh-workspace"
403
+ },
404
+ "error": {
405
+ "hostDown": "The bot host is not responding.",
406
+ "botCreate": "Could not save the bot: {message}"
407
+ }
408
+ }
409
+ const ZH = {
410
+ "meta": {
411
+ "title": "Rayrun Bot",
412
+ "description": "在侧边栏加入 Bots 入口和 v0.1 三栏界面:会话列表、带审批卡的对话、详情面板、初始化与设置。页面内容全部是内存预览,不连接机器,也不使用凭据。"
413
+ },
414
+ "panel": {
415
+ "label": "Bots"
416
+ },
417
+ "brand": "Rayrun Bot",
418
+ "preview": {
419
+ "badge": "预览"
420
+ },
421
+ "chat": {
422
+ "working": "正在处理…",
423
+ "simulatedReply": "完成。这是预览里的模拟回复;下面的审批也只在本页。",
424
+ "simulatedSnippet": "待审批:模拟结果",
425
+ "simulatedApprovalTitle": "把模拟结果发到团队频道",
426
+ "simulatedApprovalMeta": "刚刚请求",
427
+ "simulatedTarget": "团队频道",
428
+ "sending": "正在发送…",
429
+ "sendFailed": "发送失败,请重试。",
430
+ "runtimeUnavailable": "云端 runtime 不可用。请安装 dsh-rayrun-computer 并重启 DSH。",
431
+ "connectRayrun": "请先在设置里连接 Rayrun。",
432
+ "noComputer": "还没有云电脑。请先在设置里创建一台。",
433
+ "machineBusy": "云电脑正忙,请稍后再试。",
434
+ "balanceLow": "Rayrun 余额偏低,请先充值。",
435
+ "queueFull": "排队消息太多,请等回复后再发送。",
436
+ "messageInvalid": "这条消息无法发送:为空、过长或格式无效。",
437
+ "historyFailed": "无法加载这段对话。刷新页面后重试。",
438
+ "turnTimeout": "云端回合时间过长。重新打开页面查看结果。",
439
+ "turnInterrupted": "上一回合被中断了。请重新发送。",
440
+ "errorTitle": "回合失败"
441
+ },
442
+ "list": {
443
+ "search": "搜索",
444
+ "searchPlaceholder": "搜索 Bot",
445
+ "newBot": "新建 Bot",
446
+ "settings": "设置",
447
+ "empty": "没有匹配的 Bot"
448
+ },
449
+ "attention": {
450
+ "needs": "待你处理",
451
+ "unread": "未读",
452
+ "working": "工作中"
453
+ },
454
+ "approval": {
455
+ "title": "需要审批",
456
+ "allowOnce": "仅批准这一次",
457
+ "deny": "拒绝",
458
+ "waits": "等你处理",
459
+ "expires": "{n} 分钟后过期",
460
+ "expired": "已过期——Bot 没有执行",
461
+ "irreversible": "此操作无法撤销。",
462
+ "outside": "这会把数据发到你的电脑之外。",
463
+ "originChat": "来自本对话",
464
+ "originBackground": "来自定时任务",
465
+ "riskOutside": "离开你的电脑",
466
+ "riskIrreversible": "无法撤销",
467
+ "warning": "这会把数据发到你的电脑之外,且无法撤销。",
468
+ "allowedLocal": "只记在这一页:已批准一次。没有发送到任何地方。",
469
+ "deniedLocal": "只记在这一页:已拒绝。没有发送到任何地方。",
470
+ "snippetAllowed": "已批准一次 · 未发送",
471
+ "snippetDenied": "已拒绝 · 未发送",
472
+ "realStart": "启动云电脑“{machine}”",
473
+ "realStop": "停止云电脑“{machine}”",
474
+ "realPause": "暂停云电脑“{machine}”",
475
+ "realResume": "恢复云电脑“{machine}”",
476
+ "realUnknown": "在“{machine}”上执行已批准动作",
477
+ "realMeta": "请求于 {time}",
478
+ "allowedReal": "已批准,并已在本机执行。",
479
+ "deniedReal": "已拒绝,没有执行任何动作。",
480
+ "executionPending": "已批准,等待本机执行。",
481
+ "executionFailed": "已批准,但本机执行失败。不会继续执行。",
482
+ "executionRefused": "已批准,但本地不支持该动作。没有执行任何动作。",
483
+ "riskCost": "消耗机时",
484
+ "allowedSide": "已批准",
485
+ "deniedSide": "已拒绝",
486
+ "waitingSide": "等待执行",
487
+ "failedSide": "执行失败",
488
+ "continue": "让 bot 继续",
489
+ "continuePrompt": "根据上面的审批结果继续。不要重复已批准的动作;下一个受控动作前先询问。"
490
+ },
491
+ "draft": {
492
+ "send": "发送",
493
+ "discard": "丢弃"
494
+ },
495
+ "details": {
496
+ "activity": "动态",
497
+ "library": "资料库",
498
+ "recent": "最近",
499
+ "recentEmpty": "还没有动态。",
500
+ "recentEmptyHint": "Bot 开始工作后,回复和收据会出现在这里。",
501
+ "upcoming": "即将进行",
502
+ "computer": "电脑",
503
+ "usage": "用量",
504
+ "jobComputer": "{job} · {computer}"
505
+ },
506
+ "receipt": {
507
+ "ready": "已就绪",
508
+ "waiting": "等待中",
509
+ "done": "已完成"
510
+ },
511
+ "library": {
512
+ "today": "今天",
513
+ "week": "本周",
514
+ "older": "更早",
515
+ "empty": "还没有产物。",
516
+ "emptyHint": "Bot 保存在工作区里的文件会出现在这里。"
517
+ },
518
+ "routine": {
519
+ "empty": "还没有日程。",
520
+ "emptyHint": "日程按计划运行;在电脑之外执行动作前会停下来等审批。",
521
+ "paused": "所有日程都已暂停。",
522
+ "origin": "定时任务",
523
+ "every": "每 {minutes} 分钟",
524
+ "everyHours": "每 {hours} 小时",
525
+ "everyDays": "每 {days} 天",
526
+ "add": "新建日程",
527
+ "titleLabel": "日程名称",
528
+ "promptLabel": "Bot 要做什么?",
529
+ "minutesLabel": "间隔(分钟)",
530
+ "costHint": "到期运行可能会唤醒已停止的电脑,并产生机时费用。",
531
+ "create": "创建日程",
532
+ "cancel": "取消",
533
+ "remove": "删除",
534
+ "createFailed": "创建日程失败:{message}",
535
+ "updateFailed": "更新日程失败:{message}",
536
+ "removeFailed": "删除日程失败:{message}",
537
+ "on": "开",
538
+ "off": "关"
539
+ },
540
+ "computer": {
541
+ "live": "在线",
542
+ "reconnecting": "正在重连…",
543
+ "unreachable": "连不上电脑。",
544
+ "sleeping": "休眠",
545
+ "takeOver": "接管",
546
+ "open": "打开",
547
+ "view": "查看",
548
+ "onComputer": "电脑上 · {where}",
549
+ "desktopLater": "桌面在云电脑插件里。这一页还打不开它。",
550
+ "noMachine": "还没有云电脑。在云电脑插件里创建一台。",
551
+ "noMachineShort": "还没有电脑",
552
+ "stop": "停止",
553
+ "stopConfirm": "停止云电脑?正在运行的工作会暂停。",
554
+ "stopConfirmAction": "停止电脑",
555
+ "cancel": "取消",
556
+ "stopping": "正在停止…",
557
+ "stopped": "云电脑已停止。",
558
+ "stopTimeout": "云电脑仍在停止中。",
559
+ "stopFailed": "停止云电脑失败:{message}",
560
+ "connectFirst": "先连接 Rayrun(设置 → 首次设置)。",
561
+ "popupBlocked": "允许此页面弹窗,才能打开桌面。",
562
+ "starting": "正在启动云电脑…",
563
+ "startTimeout": "云电脑没有在预期时间内启动。",
564
+ "noDesktop": "这台云电脑没有远程桌面。",
565
+ "openFailed": "打开云电脑失败:{message}",
566
+ "opened": "云电脑已在新标签打开。",
567
+ "passwordTitle": "桌面密码",
568
+ "passwordBody": "在桌面页面输入这个密码。",
569
+ "passwordEmpty": "没有读到桌面密码。",
570
+ "copy": "复制",
571
+ "copied": "已复制",
572
+ "copyFailed": "复制失败,请手动选中密码。",
573
+ "close": "关闭"
574
+ },
575
+ "notice": {
576
+ "recovering": "Bot host 正在重启,这个会话会自动恢复。",
577
+ "reconnecting": "电脑正在重连… 5 秒后重试",
578
+ "sleeping": "电脑正在休眠。打开云电脑插件即可唤醒。",
579
+ "attach": "这个预览里还不能添加附件。",
580
+ "preview": "这是页内预览。内容不会保存,审批也不会发给 worker。"
581
+ },
582
+ "composer": {
583
+ "placeholder": "给 {name} 发消息…",
584
+ "attach": "添加附件",
585
+ "send": "发送"
586
+ },
587
+ "usage": {
588
+ "balanceLine": "余额 {balance} · {hours} 机时",
589
+ "weekLine": "本周 {spend} · 空闲停机 {idle}",
590
+ "liveLine": "来自你的 Rayrun 账号 · 空闲停机 {idle}",
591
+ "sampleBalance": "¥41.20",
592
+ "sampleHours": "38.4",
593
+ "sampleSpend": "¥6.80"
594
+ },
595
+ "cost": {
596
+ "low": "余额偏低——去 Rayrun 控制台充值。停机会保留磁盘,销毁不会。",
597
+ "lowShort": "余额偏低"
598
+ },
599
+ "empty": {
600
+ "heading": "还没有 Bot",
601
+ "body": "用加号新建一个。在 Bot host 出现之前,它只留在这一页。",
602
+ "thread": "还没有消息。你输入的内容只留在这一页。",
603
+ "threadReal": "还没有消息。发一句话开始云端回合。",
604
+ "snippet": "还没有消息"
605
+ },
606
+ "newBot": {
607
+ "title": "新建 Bot",
608
+ "sub": "给它一个名字和一项职责,指令之后可以再改。",
609
+ "monogramHint": "字母头像 · 颜色由名字自动分配",
610
+ "name": "名字",
611
+ "job": "职责(一行)",
612
+ "instructions": "指令(可选)",
613
+ "placeholder": "你是 {name},用户团队里的一名同事。你的职责: …",
614
+ "defaultName": "Weekly Watch",
615
+ "defaultJob": "Summarises weekly PRs and drafts the digest",
616
+ "cancel": "取消",
617
+ "create": "创建 Bot"
618
+ },
619
+ "persona": {
620
+ "template": "你是 {name},用户团队里的一名同事。\n你的职责:{job}。\n用简短、事实性的更新汇报:做了什么、没做什么、下一步需要什么。任何离开这台电脑的动作(发消息、发布、花钱、动另一台机器)先征求同意。不要声称未经验证的结果。不清楚时只问一个关键问题,不要猜。"
621
+ },
622
+ "setup": {
623
+ "title": "设置 Rayrun Bot",
624
+ "sub": "四步。每一步都会显示还缺什么、去哪里补。",
625
+ "back": "返回",
626
+ "skip": "暂时跳过",
627
+ "continue": "继续",
628
+ "steps": {
629
+ "dependency": "依赖",
630
+ "rayrun": "Rayrun",
631
+ "key": "云电脑",
632
+ "bot": "第一个 Bot"
633
+ },
634
+ "dependencyTitle": "检查云电脑插件",
635
+ "dependencyBody": "云电脑由单独的 dsh-rayrun-computer 插件提供。Host 会检查它是否已安装;修好并重启 DSH 后再连接 Rayrun。",
636
+ "dependencyStatus": "未检查",
637
+ "dependencyOk": "已安装 · v{version}",
638
+ "dependencyMissing": "缺失 — 安装 dsh-rayrun-computer 后重启 DSH。",
639
+ "dependencyIncompatible": "不受支持 · {version}(需要 {required})。",
640
+ "rayrunTitle": "连接 Rayrun",
641
+ "rayrunBody": "云电脑由 Rayrun 提供。粘贴 Rayrun API token;云电脑插件会把它存进 DSH 凭证库。",
642
+ "notConnected": "未连接",
643
+ "tokenPlaceholder": "粘贴 Rayrun API token",
644
+ "useToken": "使用 API Token",
645
+ "tokenHint": "从 Rayrun 控制台粘贴 API token;云电脑插件会把它存进 DSH 凭证库。",
646
+ "tokenRequired": "请先粘贴 Rayrun API token。",
647
+ "connecting": "连接中…",
648
+ "connected": "已连接 · 余额 {balance} · {machines} 台云电脑",
649
+ "connectedShort": "已连接",
650
+ "connectFailed": "连接失败:{message}",
651
+ "tokenRejected": "Rayrun 拒绝了这个 API token。检查后重试。",
652
+ "connect": "连接",
653
+ "accountLine": "账号:— · 余额:—",
654
+ "computerTitle": "云电脑",
655
+ "computerBody": "Bots 会在你的 Rayrun 账号上创建一台云电脑。运行期间会计费。DeepSeek key 会成为它的模型凭据,不会进入工作区。",
656
+ "computerExisting": "使用已有云电脑 · {name}",
657
+ "computerExistingHint": "这台机器的设置和模型凭据由云电脑插件管理。",
658
+ "computerNeedsRayrun": "先在上一页连接 Rayrun,才能创建云电脑。",
659
+ "computerChecking": "正在检查你的 Rayrun 云电脑…",
660
+ "computerLoadFailed": "读取 Rayrun 云电脑失败:{message}",
661
+ "computerName": "云电脑名称",
662
+ "computerKeyPlaceholder": "粘贴 DeepSeek API key(可选)",
663
+ "computerKeyHint": "如果这台机器已有 DeepSeek 凭据,可以留空。",
664
+ "computerCreate": "创建云电脑",
665
+ "computerCreating": "创建中…约 15 秒",
666
+ "computerCreated": "已创建 · {name}",
667
+ "computerCreateFailed": "创建云电脑失败:{message}",
668
+ "computerCost": "会在你的 Rayrun 账号上创建一台计费机器。Bots 永不销毁它。",
669
+ "botTitle": "第一个 Bot",
670
+ "botBody": "给它一个名字和一项职责。它只加到这一页,不会出现在云电脑上。"
671
+ },
672
+ "settings": {
673
+ "title": "设置",
674
+ "sub": "账号、用量,以及这个插件自己的少量设置。",
675
+ "account": "账号",
676
+ "usage": "用量",
677
+ "notifications": "通知",
678
+ "appearance": "外观",
679
+ "rayrunAccount": "Rayrun 账号",
680
+ "rayrunHint": "token 存在 DSH 凭证库 · 只在 Host 侧",
681
+ "setup": "首次设置",
682
+ "host": "Rayrun Bot host",
683
+ "hostHint": "同源健康检查,不携带 Rayrun token 或 DeepSeek key。",
684
+ "hostChecking": "检查中…",
685
+ "hostLoaded": "已加载 · v{version} · Bot 层尚未就绪",
686
+ "hostReady": "已就绪 · v{version}",
687
+ "hostDepMissing": "缺少云电脑插件 — 安装 dsh-rayrun-computer 后重启 DSH。",
688
+ "hostDepVersion": "云电脑插件 {version} 不受支持(需要 {required})。",
689
+ "retry": "重试",
690
+ "plugin": "云电脑插件",
691
+ "pluginHint": "dsh-rayrun-computer v1.0.0",
692
+ "pluginOk": "正常",
693
+ "pluginMissing": "缺失",
694
+ "pluginIncompatible": "不兼容",
695
+ "pluginUnknown": "未知",
696
+ "usageHint": "来自你的 Rayrun 账号。同源 RPC;页面不持有 token。",
697
+ "usageLine": "余额 {balance} · {hours} 机时 · {machines} 台云电脑",
698
+ "usageConnect": "连接 Rayrun 后显示用量。",
699
+ "usageFailed": "读取用量失败:{message}",
700
+ "idle": "空闲停机",
701
+ "idleHint": "空闲时停止电脑,绝不销毁。",
702
+ "idle15": "15 分钟",
703
+ "idle30": "30 分钟",
704
+ "idleOff": "关闭",
705
+ "lowBalance": "低余额提醒",
706
+ "lowBalanceHint": "余额低于该值时显示提示。",
707
+ "notify": "通知",
708
+ "notifyHint": "Bot 完成或等你处理时通知。",
709
+ "language": "语言",
710
+ "languageHint": "以简体中文为主,可切换 English。",
711
+ "langEn": "English",
712
+ "langZh": "简体中文"
713
+ },
714
+ "sample": {
715
+ "user": {
716
+ "name": "Haoyi",
717
+ "initials": "HY",
718
+ "foot": "Rayrun 已连接 · {balance}"
719
+ },
720
+ "nora": {
721
+ "name": "Nora",
722
+ "job": "每周摘要",
723
+ "snippet": "草稿在资料库里,等你答复",
724
+ "time": "20:07",
725
+ "user": "总结上周的 PR,并起草每周摘要。发布前等我确认。",
726
+ "day": "今天 20:07",
727
+ "reply1": "草稿好了。我控制在五个小节,每一项都链回了对应 PR。\n\n- **范围。**14 个已合并 PR,2 个仍开着,1 个已回滚。\n- **草稿。**工作区里的 `week-45-digest.md`,420 字。\n- **下一步。**发布到 `#weekly` 需要你批准。",
728
+ "reply2": "如果你想先看草稿,它在「资料库」标签里。我会等你答复。",
729
+ "computerTitle": "电脑上 · Feishu #weekly",
730
+ "computerSub": "已粘贴摘要,等待你的审批",
731
+ "approvalTitle": "发布《Week 45 摘要》到 Feishu #weekly",
732
+ "approvalMeta": "请求于 20:07",
733
+ "r1": "起草每周摘要",
734
+ "r1meta": "09:13 · 3 个产物 · 今日 ¥3.10",
735
+ "r2": "发布到 #weekly",
736
+ "r2meta": "需要你的审批 · 等你处理",
737
+ "r3": "文档刷新",
738
+ "r3meta": "08:40 · 3 页 · 今日 ¥0.60",
739
+ "f1": "week-45-digest.md",
740
+ "f1badge": "420 字",
741
+ "f1meta": "由 Nora 创建 · 09:13",
742
+ "f2": "channel-preview.png",
743
+ "f2badge": "图片",
744
+ "f2meta": "本对话中发送 · 09:12",
745
+ "f3": "week-44-digest.md",
746
+ "f3badge": "已完成",
747
+ "f3meta": "由 Nora 创建 · 周一",
748
+ "f4": "Feishu 频道",
749
+ "f4badge": "链接",
750
+ "f4meta": "上周"
751
+ },
752
+ "eli": {
753
+ "name": "Eli",
754
+ "job": "频道发布",
755
+ "snippet": "待审批:发布摘要",
756
+ "time": "09:13",
757
+ "day": "今天 09:13",
758
+ "reply": "发布会把摘要发到频道里,我停在这里等你批准。",
759
+ "approvalTitle": "发布《Week 45 摘要》到 Feishu #weekly",
760
+ "approvalMeta": "请求于 09:13",
761
+ "expiredDay": "昨天 18:00",
762
+ "expiredTitle": "发布《Week 44 摘要》到 Feishu #weekly",
763
+ "expiredMeta": "请求于昨天 18:00"
764
+ },
765
+ "june": {
766
+ "name": "June",
767
+ "job": "文档",
768
+ "snippet": "文档刷新完成 — 3 页",
769
+ "time": "08:40",
770
+ "day": "今天 08:40",
771
+ "reply": "文档刷新完成,一共 3 页。没有需要你批准的动作。",
772
+ "r1": "文档刷新",
773
+ "r1meta": "08:40 · 3 页 · 今日 ¥0.60"
774
+ },
775
+ "routine": {
776
+ "weekly": "每周摘要",
777
+ "weeklyWhen": "周五 · 09:00",
778
+ "inbox": "收件箱清扫",
779
+ "inboxWhen": "工作日 · 08:00",
780
+ "standup": "站会纪要",
781
+ "standupWhen": "工作日 · 18:00"
782
+ },
783
+ "computerName": "dsh-workspace"
784
+ },
785
+ "error": {
786
+ "hostDown": "Bot host 没有响应。",
787
+ "botCreate": "无法保存 Bot:{message}"
788
+ }
789
+ }
790
+
791
+ const PANEL_ID = 'rayrun-bots'
792
+ const SAMPLE_COMPUTER = 'dsh-workspace'
793
+ const DEFAULT_COMPUTER = 'rayrun-bot'
794
+ const SESSION_POLL_MS = 1000
795
+ const SESSION_POLL_LIMIT_MS = 16 * 60 * 1000
796
+ const pickMachine = (machines) => machines.find((item) => item.name === DEFAULT_COMPUTER)
797
+ || machines.find((item) => item.remote_desktop && item.desktop_url)
798
+ || machines[0]
799
+ const machineStatus = (status) => status === 'Running' ? 'live'
800
+ : status === 'Starting' || status === 'Stopping' ? 'reconnecting'
801
+ : status === 'Stopped' || status === 'Paused' ? 'sleeping'
802
+ : 'unreachable'
803
+ const MARK_PATHS = [
804
+ 'M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z',
805
+ 'm7 16.5-4.74-2.85',
806
+ 'm7 16.5 5-3',
807
+ 'M7 16.5v5.17',
808
+ 'M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z',
809
+ 'm17 16.5-5-3',
810
+ 'm17 16.5 4.74-2.85',
811
+ 'M17 16.5v5.17',
812
+ 'M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z',
813
+ 'M12 8 7.26 5.15',
814
+ 'm12 8 4.74-2.85',
815
+ 'M12 13.5V8',
816
+ ]
817
+ const AVATAR_PALETTE = [
818
+ ['#1d4ed8', '#e3eafc'],
819
+ ['#1e40af', '#e7eefc'],
820
+ ['#3730a3', '#ecebfe'],
821
+ ['#0f766e', '#e7f4f2'],
822
+ ['#9a3412', '#f8eee8'],
823
+ ]
824
+ const PINNED_AVATARS = new Set(['Nora', 'Eli', 'June', 'Weekly Watch', 'Haoyi'])
825
+
826
+ const CSS = `
827
+ .rb-frame, .rb-frame *, .rb-frame *::before, .rb-frame *::after { box-sizing: border-box; }
828
+ .rb-frame { position: fixed; inset: var(--dsh-frame-chrome-top, 0px) 0 0 0; z-index: 10; min-height: 0; display: flex; flex-direction: column; overflow: hidden; background: #fff; color: #0f172a; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Microsoft YaHei", sans-serif; font-size: 14px; line-height: 1.55; -webkit-font-smoothing: antialiased; }
829
+ .rb-frame button, .rb-frame input, .rb-frame textarea, .rb-frame select { font: inherit; color: inherit; }
830
+ .rb-frame button.rb-icon { color: #5b6472; }
831
+ .rb-frame button.rb-send { color: #fff; }
832
+ .rb-frame button.rb-tab { color: #8a93a3; }
833
+ .rb-frame button.rb-tab.rb-active { color: #0e2050; }
834
+ .rb-frame button.rb-textbtn { color: #8a93a3; }
835
+ .rb-frame .rb-snav button { color: #8a93a3; }
836
+ .rb-frame .rb-snav button.rb-active { color: #0e2050; }
837
+ .rb-frame button { cursor: pointer; }
838
+ .rb-frame :focus { outline: none; }
839
+ .rb-frame :focus-visible { outline: 2px solid #1d4ed8; outline-offset: 2px; }
840
+ .rb-frame ::-webkit-scrollbar { width: 9px; }
841
+ .rb-frame ::-webkit-scrollbar-thumb { background: #d5dbe6; border-radius: 5px; }
842
+ .rb-app { flex: 1; min-height: 0; display: grid; overflow: hidden; }
843
+ .rb-desktop-toast { position: fixed; right: 20px; bottom: 20px; z-index: 30; width: min(360px, calc(100vw - 40px)); background: #fff; border: 1px solid #e2e8f0; border-radius: 12px; box-shadow: 0 12px 32px rgba(15, 23, 42, 0.16); padding: 14px 16px; }
844
+ .rb-desktop-toast h3 { margin: 0 0 4px; font-size: 13px; font-weight: 650; color: #0e2050; }
845
+ .rb-desktop-toast p { margin: 0 0 8px; font-size: 12px; color: #64748b; }
846
+ .rb-desktop-toast code { display: block; padding: 8px 10px; border: 1px solid #e2e8f0; border-radius: 8px; background: #f8fafc; font-size: 13px; word-break: break-all; }
847
+ .rb-desktop-toast .rb-line { display: flex; gap: 8px; margin-top: 10px; }
848
+ .rb-sr { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
849
+ .rb-list { background: #f7f8fa; border-right: 1px solid #eef1f6; display: flex; flex-direction: column; min-height: 0; min-width: 0; }
850
+ .rb-list-top { display: flex; align-items: center; justify-content: space-between; padding: 14px 16px 8px; gap: 8px; }
851
+ .rb-brand { display: flex; align-items: center; gap: 8px; color: #0e2050; font-weight: 650; font-size: 13px; min-width: 0; }
852
+ .rb-preview-pill { padding: 1px 7px; border: 1px solid #d8e3f5; border-radius: 999px; background: #eef4ff; color: #1d4ed8; font-size: 10.5px; font-weight: 600; line-height: 1.7; letter-spacing: .02em; }
853
+ .rb-mark { flex: none; }
854
+ .rb-tools { display: flex; gap: 4px; }
855
+ .rb-icon { width: 28px; height: 28px; border: 0; border-radius: 8px; background: transparent; color: #5b6472; display: grid; place-items: center; padding: 0; }
856
+ .rb-icon:hover { background: #eef2f8; color: #0f172a; }
857
+ .rb-search { margin: 0 16px 8px; }
858
+ .rb-search input { width: 100%; background: #fff; border: 1px solid #e4e8f0; border-radius: 9px; padding: 6px 10px; font-size: 13px; }
859
+ .rb-current { display: grid; justify-items: center; gap: 5px; padding: 6px 16px 16px; text-align: center; }
860
+ .rb-avatar { border-radius: 50%; display: grid; place-items: center; font-weight: 600; color: #1d4ed8; background: #e3eafc; flex: none; }
861
+ .rb-avatar.rb-big { width: 52px; height: 52px; font-size: 18px; }
862
+ .rb-avatar.rb-mid { width: 34px; height: 34px; font-size: 12px; }
863
+ .rb-avatar.rb-sm { width: 26px; height: 26px; font-size: 10px; }
864
+ .rb-avatar.rb-new { width: 38px; height: 38px; font-size: 13px; }
865
+ .rb-current .rb-name, .rb-profile .rb-name { font-size: 15px; font-weight: 600; }
866
+ .rb-current .rb-label, .rb-profile .rb-sub { color: #8a93a3; font-size: 11.5px; }
867
+ .rb-profile .rb-sub { font-size: 11px; }
868
+ .rb-chats { overflow: auto; padding: 2px 10px 10px; display: flex; flex-direction: column; gap: 1px; min-height: 0; }
869
+ .rb-row { display: grid; grid-template-columns: 34px minmax(0, 1fr) auto; gap: 10px; align-items: center; padding: 8px 9px; border: 0; border-radius: 10px; background: transparent; text-align: left; width: 100%; }
870
+ .rb-row:hover { background: #eef2f8; }
871
+ .rb-row.rb-active { background: #eaf1fd; }
872
+ .rb-nm { font-size: 13px; font-weight: 500; display: flex; align-items: center; gap: 6px; }
873
+ .rb-sn { color: #8a93a3; font-size: 11.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
874
+ .rb-tm { color: #8a93a3; font-size: 10.5px; }
875
+ .rb-dot { width: 6px; height: 6px; border-radius: 50%; background: #8a93a3; flex: none; display: inline-block; }
876
+ .rb-dot.rb-needs { background: #b45309; }
877
+ .rb-dot.rb-working { background: #15803d; }
878
+ .rb-dot.rb-unread { background: #5b7fc4; }
879
+ .rb-dot.rb-danger { background: #b42318; }
880
+ .rb-foot { margin-top: auto; border-top: 1px solid #eef1f6; padding: 10px 14px; display: flex; align-items: center; gap: 9px; }
881
+ .rb-who { flex: 1; font-size: 12px; min-width: 0; }
882
+ .rb-who small { display: block; color: #8a93a3; font-size: 10.5px; }
883
+ .rb-textbtn { border: 0; background: transparent; padding: 0; color: #8a93a3; font-size: 10.5px; text-align: left; }
884
+ .rb-textbtn:hover { color: #0f172a; }
885
+ .rb-frame button.rb-textbtn.rb-textbtn-low { color: #b45309; }
886
+ .rb-textbtn .rb-dot { margin-right: 4px; vertical-align: middle; }
887
+ .rb-empty-list { color: #8a93a3; font-size: 12px; padding: 8px 10px; }
888
+ .rb-firstrun { padding: 10px; }
889
+ .rb-main { background: #fff; display: flex; flex-direction: column; min-width: 0; min-height: 0; }
890
+ .rb-thread { flex: 1; overflow: auto; padding: 26px 34px 12px; display: flex; flex-direction: column; gap: 20px; }
891
+ .rb-thread > * { max-width: 760px; width: 100%; align-self: center; }
892
+ .rb-day { text-align: center; color: #8a93a3; font-size: 10.5px; margin: 4px 0 2px; }
893
+ .rb-msg { display: grid; grid-template-columns: 28px minmax(0, 1fr); gap: 12px; }
894
+ .rb-msg-avatar { margin-top: 2px; }
895
+ .rb-msg .rb-body { min-width: 0; }
896
+ .rb-msg .rb-who-line { font-size: 11.5px; color: #5b6472; margin-bottom: 3px; display: flex; gap: 8px; align-items: baseline; }
897
+ .rb-msg .rb-who-line b { color: #0f172a; font-weight: 600; font-size: 12.5px; }
898
+ .rb-msg p { margin: 0 0 9px; }
899
+ .rb-msg p:last-child { margin-bottom: 0; }
900
+ .rb-msg ul { margin: 0 0 9px; padding-left: 18px; }
901
+ .rb-msg li { margin-bottom: 3px; }
902
+ .rb-msg code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; background: #eef2f8; border-radius: 4px; padding: 1px 4px; }
903
+ .rb-msg.rb-user { grid-template-columns: minmax(0, 1fr); justify-items: end; }
904
+ .rb-bubble { background: #f1f4f9; border-radius: 12px; padding: 8px 13px; max-width: 560px; font-size: 13.5px; overflow-wrap: anywhere; }
905
+ .rb-card { border: 1px solid #e4e8f0; background: #fff; border-radius: 12px; padding: 13px 15px; display: grid; gap: 8px; }
906
+ .rb-card-expired { opacity: .72; }
907
+ .rb-card-fields { display: flex; flex-wrap: wrap; gap: 6px; }
908
+ .rb-chip { border: 1px solid #e4e8f0; border-radius: 999px; padding: 1px 7px; color: #5b6472; font-size: 10.5px; line-height: 1.6; }
909
+ .rb-bubble .rb-chip { display: inline-block; margin-bottom: 4px; }
910
+ .rb-chip-target { color: #3a4351; background: #f6f8fb; }
911
+ .rb-card-top { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; }
912
+ .rb-card-title { font-size: 13px; font-weight: 600; display: flex; align-items: center; gap: 6px; min-width: 0; }
913
+ .rb-warn { color: #b45309; }
914
+ .rb-m { color: #8a93a3; font-size: 10.5px; white-space: nowrap; }
915
+ .rb-warnline { color: #b42318; font-size: 11.5px; }
916
+ .rb-meta { color: #8a93a3; font-size: 10.5px; }
917
+ .rb-result { color: #5b6472; font-size: 12.5px; }
918
+ .rb-actions { display: flex; justify-content: flex-end; gap: 8px; padding-top: 2px; }
919
+ .rb-btn { border: 1px solid #e4e8f0; background: #fff; color: #0f172a; border-radius: 9px; padding: 5px 12px; font-size: 12.5px; font-weight: 500; }
920
+ .rb-btn:hover { background: #f5f7fb; }
921
+ .rb-btn.rb-primary { background: #0e2050; border-color: #0e2050; color: #fff; }
922
+ .rb-btn.rb-primary:hover { background: #16306e; }
923
+ .rb-btn.rb-ghost { border-color: transparent; background: transparent; color: #5b6472; }
924
+ .rb-btn.rb-ghost:hover { color: #0f172a; background: #eef2f8; }
925
+ .rb-btn:disabled { opacity: .45; cursor: not-allowed; }
926
+ .rb-notice { margin: 0 34px 8px; max-width: 760px; align-self: center; width: 100%; color: #b45309; font-size: 11.5px; display: flex; gap: 7px; align-items: center; }
927
+ .rb-notice.rb-quiet { color: #5b6472; }
928
+ .rb-notice.rb-error { color: #b42318; }
929
+ .rb-composer { max-width: 760px; width: 100%; align-self: center; display: flex; align-items: center; gap: 8px; border: 1px solid #e4e8f0; background: #fff; border-radius: 14px; padding: 7px 8px 7px 10px; margin: 0 34px 18px; }
930
+ .rb-composer input { flex: 1; border: 0; outline: 0; background: transparent; font-size: 13.5px; min-width: 0; }
931
+ .rb-composer input:focus { outline: none; }
932
+ .rb-composer input::placeholder { color: #8a93a3; }
933
+ .rb-send { width: 30px; height: 30px; border-radius: 50%; border: 0; background: #0e2050; color: #fff; font-size: 13px; display: grid; place-items: center; padding: 0; flex: none; }
934
+ .rb-send:hover { background: #16306e; }
935
+ .rb-detail { background: #f7f8fa; border-left: 1px solid #eef1f6; display: flex; flex-direction: column; min-height: 0; min-width: 0; overflow: auto; }
936
+ .rb-profile { display: grid; justify-items: center; gap: 5px; padding: 22px 16px 12px; text-align: center; }
937
+ .rb-tabs { display: flex; justify-content: center; gap: 22px; border-bottom: 1px solid #eef1f6; padding: 4px 16px 0; }
938
+ .rb-tab { border: 0; background: transparent; color: #8a93a3; font-size: 12px; padding: 7px 0 9px; border-bottom: 1.5px solid transparent; }
939
+ .rb-tab.rb-active { color: #0e2050; border-bottom-color: #1d4ed8; }
940
+ .rb-computer-act { display: grid; grid-template-columns: 44px minmax(0, 1fr) auto; gap: 10px; align-items: center; border: 1px solid #e4e8f0; background: #fff; border-radius: 10px; padding: 8px 10px; }
941
+ .rb-computer-act .rb-t, .rb-computer .rb-nm { font-size: 12px; }
942
+ .rb-computer-act .rb-s, .rb-computer .rb-st, .rb-act .rb-s, .rb-routine .rb-s { color: #8a93a3; font-size: 10.5px; }
943
+ .rb-computer .rb-st { display: flex; align-items: center; gap: 5px; }
944
+ .rb-computer .rb-st.rb-st-live { color: #15803d; }
945
+ .rb-computer .rb-st.rb-st-reconnecting { color: #b45309; }
946
+ .rb-computer .rb-st.rb-st-sleeping { color: #8a93a3; }
947
+ .rb-computer .rb-st.rb-st-offline { color: #8a93a3; }
948
+ .rb-computer .rb-st.rb-st-unreachable { color: #b42318; }
949
+ .rb-sections { padding: 14px 16px 24px; display: grid; gap: 20px; }
950
+ .rb-sec h3 { margin: 0 0 8px; color: #8a93a3; font-size: 10px; font-weight: 500; letter-spacing: .08em; text-transform: uppercase; display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }
951
+ .rb-count { color: #8a93a3; font-size: 10px; font-weight: 500; letter-spacing: 0; text-transform: none; }
952
+ .rb-empty { background: #fff; border: 1px dashed #e4e8f0; border-radius: 10px; padding: 12px; display: grid; gap: 3px; }
953
+ .rb-empty-title { color: #5b6472; font-size: 12px; font-weight: 500; }
954
+ .rb-empty-hint { color: #8a93a3; font-size: 10.5px; line-height: 1.5; }
955
+ .rb-act { background: #fff; border: 1px solid #e4e8f0; border-radius: 10px; padding: 10px 12px; display: grid; gap: 4px; margin-bottom: 7px; }
956
+ .rb-act .rb-t { font-size: 12px; font-weight: 600; display: flex; justify-content: space-between; gap: 8px; }
957
+ .rb-ok { color: #15803d; font-weight: 500; font-size: 11px; white-space: nowrap; }
958
+ .rb-paused { color: #8a93a3; font-size: 11px; margin: 0 0 4px; }
959
+ .rb-routine { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 10px; align-items: center; padding: 7px 0; border-bottom: 1px solid #eef1f6; }
960
+ .rb-routine:last-child { border-bottom: 0; }
961
+ .rb-routine .rb-t { font-size: 12px; }
962
+ .rb-routine-head, .rb-routine-actions { display: flex; align-items: center; gap: 8px; }
963
+ .rb-routine-form { margin-top: 12px; padding-top: 12px; border-top: 1px solid #eef1f6; }
964
+ .rb-toggle { width: 34px; height: 19px; border-radius: 10px; border: 0; background: #cbd5e1; position: relative; flex: none; padding: 0; }
965
+ .rb-toggle::after { content: ""; position: absolute; top: 2px; left: 2px; width: 15px; height: 15px; border-radius: 50%; background: #fff; transition: left .12s; }
966
+ .rb-toggle.rb-on { background: #0e2050; }
967
+ .rb-toggle.rb-on::after { left: 17px; }
968
+ .rb-computer { display: grid; gap: 8px; }
969
+ .rb-comp-row { display: flex; align-items: center; gap: 9px; }
970
+ .rb-thumb { width: 44px; height: 30px; border-radius: 5px; background: #0b1b3a; border: 1px solid #e4e8f0; position: relative; overflow: hidden; flex: none; }
971
+ .rb-thumb::before { content: ""; position: absolute; inset: 18% 46% 18% 8%; background: #14285a; border-radius: 2px; }
972
+ .rb-thumb::after { content: ""; position: absolute; inset: 28% 8% 22% 58%; background: #22407f; border-radius: 2px; }
973
+ .rb-comp-acts { display: flex; justify-content: flex-end; gap: 6px; }
974
+ .rb-stop-confirm { padding: 8px 10px; border: 1px solid #e2e8f0; border-radius: 8px; background: #f8fafc; }
975
+ .rb-stop-confirm p { margin: 0 0 6px; font-size: 11.5px; color: #5b6472; }
976
+ .rb-comp-acts .rb-btn { padding: 4px 9px; font-size: 11px; }
977
+ .rb-usage { color: #5b6472; font-size: 12px; display: grid; gap: 3px; }
978
+ .rb-usage b { color: #0f172a; font-weight: 600; }
979
+ .rb-usage .rb-usage-low b { color: #b45309; }
980
+ .rb-low { color: #b45309; font-size: 12px; }
981
+ .rb-faint { color: #8a93a3; font-size: 11px; }
982
+ .rb-page { background: #fff; overflow: auto; display: flex; flex-direction: column; min-height: 0; min-width: 0; }
983
+ .rb-wizard-wrap { min-height: 100%; display: grid; place-items: center; padding: 40px 20px; }
984
+ .rb-wizard { width: 480px; max-width: 100%; }
985
+ .rb-wizard h1, .rb-page-inner h1 { margin: 0 0 4px; font-size: 18px; font-weight: 650; }
986
+ .rb-wizard .rb-sub { color: #8a93a3; margin: 0 0 24px; font-size: 11.5px; }
987
+ .rb-steps { display: flex; gap: 6px; margin-bottom: 24px; }
988
+ .rb-step { flex: 1; display: grid; gap: 5px; }
989
+ .rb-bar { height: 2px; border-radius: 1px; background: #e4e8f0; }
990
+ .rb-step.rb-done .rb-bar { background: #b6c2d6; }
991
+ .rb-step.rb-current .rb-bar { background: #0f172a; }
992
+ .rb-lbl { font-size: 10px; color: #8a93a3; }
993
+ .rb-step.rb-current .rb-lbl { color: #0f172a; }
994
+ .rb-wizard h2 { margin: 0 0 6px; font-size: 14px; font-weight: 600; }
995
+ .rb-say { color: #5b6472; margin: 0 0 16px; font-size: 12px; }
996
+ .rb-line { display: flex; gap: 8px; align-items: center; }
997
+ .rb-stack { display: grid; gap: 10px; }
998
+ .rb-field { flex: 1; width: 100%; background: #fff; border: 1px solid #e4e8f0; border-radius: 9px; color: #0f172a; padding: 8px 10px; font-size: 13px; }
999
+ .rb-field.rb-area { min-height: 66px; resize: vertical; }
1000
+ .rb-flabel { display: grid; gap: 5px; font-size: 11px; color: #5b6472; }
1001
+ .rb-form-foot { display: flex; justify-content: space-between; align-items: center; margin-top: 26px; padding-top: 14px; border-top: 1px solid #eef1f6; gap: 12px; }
1002
+ .rb-mono { margin-bottom: 16px; }
1003
+ .rb-hint { color: #8a93a3; font-size: 11.5px; }
1004
+ .rb-page-inner { max-width: 760px; width: 100%; align-self: center; padding: 34px 34px 60px; }
1005
+ .rb-page-inner .rb-back { margin: 0 0 14px; padding-left: 0; }
1006
+ .rb-page-inner .rb-sub { color: #8a93a3; margin: 0 0 22px; font-size: 11.5px; }
1007
+ .rb-snav { display: flex; gap: 16px; border-bottom: 1px solid #eef1f6; margin-bottom: 8px; }
1008
+ .rb-snav button { border: 0; background: transparent; color: #8a93a3; font-size: 12px; padding: 8px 0; border-bottom: 1.5px solid transparent; }
1009
+ .rb-snav button.rb-active { color: #0e2050; border-bottom-color: #1d4ed8; }
1010
+ .rb-srow { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 13px 0; border-bottom: 1px solid #eef1f6; }
1011
+ .rb-srow:last-child { border-bottom: 0; }
1012
+ .rb-srow .rb-l { display: grid; gap: 1px; font-size: 13px; }
1013
+ .rb-srow .rb-l small { color: #8a93a3; font-size: 11px; }
1014
+ .rb-srow select, .rb-srow input { background: #fff; border: 1px solid #e4e8f0; border-radius: 8px; color: #0f172a; font-size: 12.5px; padding: 5px 8px; }
1015
+ .rb-status { display: flex; align-items: center; gap: 6px; color: #5b6472; font-size: 11.5px; border: 0; background: transparent; padding: 0; }
1016
+ .rb-status .rb-retry { padding: 2px 8px; font-size: 11px; }
1017
+ .rb-center-empty { margin: auto; max-width: 420px; text-align: center; display: grid; gap: 8px; justify-items: center; padding: 48px 24px; }
1018
+ .rb-center-empty h2 { margin: 0; font-size: 18px; font-weight: 650; }
1019
+ .rb-center-empty p { margin: 0; color: #5b6472; font-size: 13px; }
1020
+ .rb-thread-empty { color: #8a93a3; font-size: 13px; text-align: center; padding: 24px 0; }
1021
+ .rb-thread-welcome { margin: auto; display: grid; gap: 6px; justify-items: center; text-align: center; padding: 40px 16px; }
1022
+ .rb-thread-welcome-title { font-size: 15px; font-weight: 650; }
1023
+ .rb-thread-welcome-job { color: #8a93a3; font-size: 12px; }
1024
+ .rb-thread-welcome .rb-thread-empty { padding: 0; }
1025
+ .rb-working-row { display: flex; align-items: center; gap: 8px; color: #5b6472; font-size: 13px; }
1026
+ .rb-error-row { max-width: 760px; width: 100%; align-self: center; display: grid; gap: 3px; margin: 2px 0; padding: 9px 12px; border: 1px solid #f3d1d1; border-radius: 10px; background: #fff5f5; color: #9b1c1c; font-size: 12.5px; }
1027
+ .rb-error-code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 10.5px; opacity: .75; }
1028
+ .rb-error-text { line-height: 1.5; }
1029
+ .rb-mini { display: flex; gap: 8px; padding: 8px 12px; border-bottom: 1px solid #eef1f6; }
1030
+ @media (prefers-reduced-motion: reduce) {
1031
+ .rb-toggle::after { transition: none; }
1032
+ }
1033
+ `
1034
+
1035
+ function lookup(catalog, key) {
1036
+ const parts = String(key || '').split('.')
1037
+ let cur = catalog
1038
+ for (const part of parts) {
1039
+ if (!cur || typeof cur !== 'object') return key
1040
+ cur = cur[part]
1041
+ }
1042
+ return typeof cur === 'string' ? cur : key
1043
+ }
1044
+
1045
+ function fill(text, vars) {
1046
+ return String(text).replace(/\{(\w+)\}/g, (token, name) => {
1047
+ if (!vars || vars[name] == null || vars[name] === '') return token
1048
+ return String(vars[name])
1049
+ })
1050
+ }
1051
+
1052
+ function makeT(catalog) {
1053
+ return (key, vars) => fill(lookup(catalog, key), vars)
1054
+ }
1055
+
1056
+ function moneyNumber(value) {
1057
+ const n = Number(String(value ?? '').replace(/[^\d.]/g, ''))
1058
+ return Number.isFinite(n) ? n : NaN
1059
+ }
1060
+
1061
+ /** Same-origin POST to one of the two plugin RPC routes. */
1062
+ async function pluginRpc(path, action, payload = {}) {
1063
+ const res = await fetch(path, {
1064
+ method: 'POST',
1065
+ mode: 'same-origin',
1066
+ credentials: 'same-origin',
1067
+ cache: 'no-store',
1068
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
1069
+ body: JSON.stringify({ action, ...payload }),
1070
+ })
1071
+ let body = null
1072
+ try { body = await res.json() } catch { body = null }
1073
+ if (!res.ok || body?.ok !== true) {
1074
+ const error = body?.error
1075
+ const code = typeof error === 'string' ? error : error?.code ?? `http_${res.status}`
1076
+ const message = error && typeof error === 'object' && error.message
1077
+ ? error.message
1078
+ : `RPC failed (${res.status}).`
1079
+ const failure = new Error(`${code}: ${message}`)
1080
+ failure.code = code
1081
+ throw failure
1082
+ }
1083
+ return body
1084
+ }
1085
+
1086
+ /** Call into the cloud-computer plugin; the token never enters this plugin. */
1087
+ const rayRpc = (action, payload) => pluginRpc('/plugins/rayrun/rpc', action, payload)
1088
+
1089
+ /** Call into this bundle's host half; health stays a GET. */
1090
+ const hostRpc = (action, payload) => pluginRpc('/plugins/rayrun-bots', action, payload)
1091
+
1092
+ function balanceText(balance) {
1093
+ const cents = Number(balance?.balance_cents)
1094
+ if (!Number.isFinite(cents)) return '—'
1095
+ return `${balance?.currency === 'USD' ? '$' : '¥'}${(cents / 100).toFixed(2)}`
1096
+ }
1097
+
1098
+ function monogram(name) {
1099
+ const trimmed = String(name || '').trim()
1100
+ if (!trimmed) return '?'
1101
+ const chars = Array.from(trimmed)
1102
+ return chars[0].toUpperCase()
1103
+ }
1104
+
1105
+ function avatarStyle(seed) {
1106
+ const key = String(seed || '')
1107
+ if (PINNED_AVATARS.has(key)) return { color: '#1d4ed8', background: '#e3eafc' }
1108
+ let hash = 0
1109
+ for (const ch of Array.from(key)) hash = (hash * 31 + ch.codePointAt(0)) >>> 0
1110
+ const [color, background] = AVATAR_PALETTE[hash % AVATAR_PALETTE.length]
1111
+ return { color, background }
1112
+ }
1113
+
1114
+ /** Map one host routine to the client's display shape. */
1115
+ function realRoutine(routine) {
1116
+ return {
1117
+ id: routine.id,
1118
+ title: routine.title,
1119
+ everyMinutes: routine.everyMinutes,
1120
+ nextAt: routine.nextAt,
1121
+ on: routine.enabled === true,
1122
+ real: true,
1123
+ }
1124
+ }
1125
+
1126
+ function realRoutines(list) {
1127
+ return Array.isArray(list) ? list.map(realRoutine) : []
1128
+ }
1129
+
1130
+ function intervalLabel(t, minutes) {
1131
+ if (Number.isInteger(minutes) && minutes > 0 && minutes % 1440 === 0) {
1132
+ return t('routine.everyDays', { days: minutes / 1440 })
1133
+ }
1134
+ if (Number.isInteger(minutes) && minutes > 0 && minutes % 60 === 0) {
1135
+ return t('routine.everyHours', { hours: minutes / 60 })
1136
+ }
1137
+ return t('routine.every', { minutes })
1138
+ }
1139
+
1140
+ /** Map one host roster entry to the client's bot shape; its session comes from the host. */
1141
+ function realBot(bot, routines = []) {
1142
+ return {
1143
+ id: bot.id,
1144
+ name: bot.name,
1145
+ job: bot.label,
1146
+ source: 'real',
1147
+ attention: null,
1148
+ time: '',
1149
+ snippetKey: 'empty.snippet',
1150
+ messages: [],
1151
+ approvals: {},
1152
+ receipts: [],
1153
+ routines: realRoutines(routines),
1154
+ library: [],
1155
+ session: null,
1156
+ sessionCursor: 0,
1157
+ historyLoaded: false,
1158
+ working: false,
1159
+ }
1160
+ }
1161
+
1162
+ /** Map a host approval into the card shape without trusting display fields. */
1163
+ function realApproval(approval, t) {
1164
+ const action = approval?.action && typeof approval.action === 'object' ? approval.action : {}
1165
+ const machine = typeof action.machine === 'string' ? action.machine : ''
1166
+ const kind = action.kind
1167
+ const execution = approval?.execution ?? null
1168
+ let state = approval?.state ?? 'pending'
1169
+ if (state === 'approved') {
1170
+ if (execution?.state === 'done') state = 'allowed'
1171
+ else if (execution?.state === 'failed' || execution?.state === 'refused') state = 'execution-failed'
1172
+ else state = 'approved-waiting'
1173
+ }
1174
+ let expiresMin
1175
+ if (state === 'pending' && approval?.expiresAt) {
1176
+ const remaining = Date.parse(approval.expiresAt) - Date.now()
1177
+ expiresMin = Number.isFinite(remaining) ? Math.max(0, Math.ceil(remaining / 60000)) : undefined
1178
+ }
1179
+ return {
1180
+ id: approval.id,
1181
+ real: true,
1182
+ title: t(kind === 'rayrun.machine.start'
1183
+ ? 'approval.realStart'
1184
+ : kind === 'rayrun.machine.stop'
1185
+ ? 'approval.realStop'
1186
+ : kind === 'rayrun.machine.pause'
1187
+ ? 'approval.realPause'
1188
+ : kind === 'rayrun.machine.resume' ? 'approval.realResume' : 'approval.realUnknown', { machine }),
1189
+ meta: t('approval.realMeta', { time: timeOf(approval.createdAt) }),
1190
+ state,
1191
+ origin: approval.origin,
1192
+ target: machine,
1193
+ risk: Array.isArray(approval.risk) ? approval.risk : [],
1194
+ execution,
1195
+ ...(expiresMin === undefined ? {} : { expiresMin }),
1196
+ }
1197
+ }
1198
+
1199
+ /** Replace the bot's real approval cards; other messages stay in place. */
1200
+ function applyApprovals(bot, list, t) {
1201
+ if (!Array.isArray(list)) return bot
1202
+ const entries = list.filter((approval) => approval && typeof approval.id === 'string')
1203
+ const approvals = { ...bot.approvals }
1204
+ const cards = []
1205
+ for (const approval of entries) {
1206
+ const mapped = realApproval(approval, t)
1207
+ approvals[mapped.id] = mapped
1208
+ cards.push({ id: `approval-${mapped.id}`, kind: 'approval', approvalId: mapped.id })
1209
+ }
1210
+ const messages = [...bot.messages.filter((entry) => entry.kind !== 'approval'), ...cards]
1211
+ const pending = cards.some((card) => approvals[card.approvalId]?.state === 'pending')
1212
+ return {
1213
+ ...bot,
1214
+ approvals,
1215
+ messages,
1216
+ attention: pending ? 'needs' : bot.attention === 'needs' ? null : bot.attention,
1217
+ }
1218
+ }
1219
+
1220
+ /** Apply one decision/execution result without moving the card to the end twice. */
1221
+ function applyApprovalResult(bot, approval, t) {
1222
+ if (!approval || typeof approval.id !== 'string') return bot
1223
+ const mapped = realApproval(approval, t)
1224
+ const approvals = { ...bot.approvals, [mapped.id]: mapped }
1225
+ const exists = bot.messages.some((entry) => entry.kind === 'approval' && entry.approvalId === mapped.id)
1226
+ const messages = exists
1227
+ ? bot.messages
1228
+ : [...bot.messages, { id: `approval-${mapped.id}`, kind: 'approval', approvalId: mapped.id }]
1229
+ const pending = Object.values(approvals).some((item) => item.state === 'pending')
1230
+ return {
1231
+ ...bot,
1232
+ approvals,
1233
+ messages,
1234
+ attention: pending ? 'needs' : bot.attention === 'needs' ? null : bot.attention,
1235
+ }
1236
+ }
1237
+
1238
+ let seq = 0
1239
+ function uid(prefix) {
1240
+ seq += 1
1241
+ return `${prefix}-${seq}`
1242
+ }
1243
+
1244
+ function clock() {
1245
+ const now = new Date()
1246
+ const h = String(now.getHours()).padStart(2, '0')
1247
+ const m = String(now.getMinutes()).padStart(2, '0')
1248
+ return `${h}:${m}`
1249
+ }
1250
+
1251
+ const SESSION_ERROR_KEYS = {
1252
+ E_DEP_MISSING: 'chat.runtimeUnavailable',
1253
+ E_RUNTIME_UNAVAILABLE: 'chat.runtimeUnavailable',
1254
+ E_TOKEN_REQUIRED: 'chat.connectRayrun',
1255
+ E_MACHINE_STOPPED: 'chat.noComputer',
1256
+ E_MACHINE_BUSY: 'chat.machineBusy',
1257
+ E_BALANCE_LOW: 'chat.balanceLow',
1258
+ E_QUEUE_FULL: 'chat.queueFull',
1259
+ E_SESSION_INVALID: 'chat.messageInvalid',
1260
+ E_HOST_DOWN: 'chat.turnInterrupted',
1261
+ }
1262
+
1263
+ function timeOf(at) {
1264
+ const value = new Date(at)
1265
+ if (Number.isNaN(value.getTime())) return clock()
1266
+ return `${String(value.getHours()).padStart(2, '0')}:${String(value.getMinutes()).padStart(2, '0')}`
1267
+ }
1268
+
1269
+ function sessionWorking(session) {
1270
+ return session?.state === 'running' || session?.state === 'queued'
1271
+ }
1272
+
1273
+ function sessionErrorText(t, code, fallback) {
1274
+ const key = SESSION_ERROR_KEYS[code]
1275
+ return key ? t(key) : (fallback || t('chat.sendFailed'))
1276
+ }
1277
+
1278
+ function sessionEntry(message, t) {
1279
+ const entry = { id: `session-${message.seq}`, at: message.at, text: message.text }
1280
+ if (message.role === 'user') {
1281
+ return { ...entry, kind: 'user', ...(message.origin === 'routine' ? { origin: 'routine' } : {}) }
1282
+ }
1283
+ if (message.role === 'bot') return { ...entry, kind: 'bot' }
1284
+ return {
1285
+ ...entry,
1286
+ kind: 'error',
1287
+ code: message.code || 'E_INTERNAL',
1288
+ text: sessionErrorText(t, message.code, message.text),
1289
+ }
1290
+ }
1291
+
1292
+ function snippetOf(text) {
1293
+ const value = String(text || '').trim()
1294
+ return value.length > 48 ? `${value.slice(0, 47)}…` : value
1295
+ }
1296
+
1297
+ function applySession(bot, payload, t, { append = false, unread = false } = {}) {
1298
+ const incoming = Array.isArray(payload?.messages)
1299
+ ? payload.messages.map((message) => sessionEntry(message, t))
1300
+ : []
1301
+ const base = append
1302
+ ? [...bot.messages.filter((entry) => entry.kind !== 'working'), ...incoming]
1303
+ : incoming
1304
+ const seen = new Set()
1305
+ const messages = []
1306
+ for (const entry of base) {
1307
+ if (seen.has(entry.id)) continue
1308
+ seen.add(entry.id)
1309
+ messages.push(entry)
1310
+ }
1311
+ for (const entry of bot.messages) {
1312
+ if (entry.kind !== 'approval' || seen.has(entry.id)) continue
1313
+ seen.add(entry.id)
1314
+ messages.push(entry)
1315
+ }
1316
+ const session = payload?.session ?? null
1317
+ if (sessionWorking(session)) messages.push({ id: `working-${bot.id}`, kind: 'working' })
1318
+ const last = [...messages].reverse().find((entry) => entry.kind === 'bot' || entry.kind === 'error' || entry.kind === 'user')
1319
+ return {
1320
+ ...bot,
1321
+ session,
1322
+ sessionCursor: Number.isInteger(session?.lastSeq) ? session.lastSeq : bot.sessionCursor,
1323
+ historyLoaded: true,
1324
+ working: sessionWorking(session),
1325
+ attention: sessionWorking(session)
1326
+ ? 'working'
1327
+ : session?.state === 'failed' || session?.state === 'interrupted'
1328
+ ? 'needs'
1329
+ : unread ? 'unread' : null,
1330
+ snippet: last ? snippetOf(last.text) : '',
1331
+ snippetKey: last ? null : 'empty.snippet',
1332
+ time: last?.at ? timeOf(last.at) : sessionWorking(session) ? clock() : '',
1333
+ timeKey: null,
1334
+ messages,
1335
+ }
1336
+ }
1337
+
1338
+ function appendSessionError(bot, text, code) {
1339
+ const value = String(text || '').trim() || code
1340
+ return {
1341
+ ...bot,
1342
+ working: false,
1343
+ attention: 'needs',
1344
+ snippet: snippetOf(value),
1345
+ snippetKey: null,
1346
+ time: clock(),
1347
+ timeKey: null,
1348
+ messages: [
1349
+ ...bot.messages.filter((entry) => entry.kind !== 'working'),
1350
+ { id: uid('error'), kind: 'error', code, text: value },
1351
+ ],
1352
+ }
1353
+ }
1354
+
1355
+ function markdownBlocks(text) {
1356
+ const blocks = []
1357
+ let paragraph = []
1358
+ let list = []
1359
+ const flushParagraph = () => {
1360
+ if (!paragraph.length) return
1361
+ const value = paragraph.join(' ').trim()
1362
+ if (value) blocks.push({ type: 'p', text: value })
1363
+ paragraph = []
1364
+ }
1365
+ const flushList = () => {
1366
+ if (!list.length) return
1367
+ blocks.push({ type: 'ul', items: list })
1368
+ list = []
1369
+ }
1370
+ for (const line of String(text || '').split('\n')) {
1371
+ const item = /^\s*[-*]\s+(.*)$/.exec(line)
1372
+ if (item) {
1373
+ flushParagraph()
1374
+ list.push(item[1])
1375
+ continue
1376
+ }
1377
+ if (line.trim() === '') {
1378
+ flushParagraph()
1379
+ flushList()
1380
+ continue
1381
+ }
1382
+ flushList()
1383
+ paragraph.push(line.trim())
1384
+ }
1385
+ flushParagraph()
1386
+ flushList()
1387
+ return blocks
1388
+ }
1389
+
1390
+ function inlineNodes(text, keyPrefix) {
1391
+ const nodes = []
1392
+ const re = /(\*\*([^*]+)\*\*|`([^`]+)`)/g
1393
+ let last = 0
1394
+ let match = re.exec(text)
1395
+ let index = 0
1396
+ while (match) {
1397
+ if (match.index > last) nodes.push(text.slice(last, match.index))
1398
+ if (match[2] != null) nodes.push(h('strong', { key: `${keyPrefix}-b${index}` }, match[2]))
1399
+ else nodes.push(h('code', { key: `${keyPrefix}-c${index}` }, match[3]))
1400
+ last = match.index + match[0].length
1401
+ index += 1
1402
+ match = re.exec(text)
1403
+ }
1404
+ if (last < text.length) nodes.push(text.slice(last))
1405
+ return nodes
1406
+ }
1407
+
1408
+ function RichText({ text }) {
1409
+ return markdownBlocks(text).map((block, index) => {
1410
+ if (block.type === 'ul') {
1411
+ return h(
1412
+ 'ul',
1413
+ { key: `ul${index}` },
1414
+ block.items.map((item, itemIndex) => h('li', { key: itemIndex }, inlineNodes(item, `i${index}-${itemIndex}`))),
1415
+ )
1416
+ }
1417
+ return h('p', { key: `p${index}` }, inlineNodes(block.text, `p${index}`))
1418
+ })
1419
+ }
1420
+
1421
+ function seedBots() {
1422
+ return [
1423
+ {
1424
+ id: 'nora',
1425
+ nameKey: 'sample.nora.name',
1426
+ jobKey: 'sample.nora.job',
1427
+ attention: 'working',
1428
+ timeKey: 'sample.nora.time',
1429
+ snippetKey: 'sample.nora.snippet',
1430
+ messages: [
1431
+ { id: 'nora-u', kind: 'user', textKey: 'sample.nora.user' },
1432
+ { id: 'nora-d', kind: 'day', textKey: 'sample.nora.day' },
1433
+ { id: 'nora-b1', kind: 'bot', textKey: 'sample.nora.reply1' },
1434
+ { id: 'nora-c', kind: 'computer', titleKey: 'sample.nora.computerTitle', subKey: 'sample.nora.computerSub' },
1435
+ { id: 'nora-a', kind: 'approval', approvalId: 'nora-pub' },
1436
+ { id: 'nora-b2', kind: 'bot', textKey: 'sample.nora.reply2' },
1437
+ ],
1438
+ approvals: {
1439
+ 'nora-pub': {
1440
+ id: 'nora-pub',
1441
+ titleKey: 'sample.nora.approvalTitle',
1442
+ metaKey: 'sample.nora.approvalMeta',
1443
+ state: 'pending',
1444
+ origin: 'chat',
1445
+ target: 'Feishu #weekly',
1446
+ risk: ['outside', 'irreversible'],
1447
+ },
1448
+ },
1449
+ receipts: [
1450
+ { titleKey: 'sample.nora.r1', stateKey: 'receipt.ready', metaKey: 'sample.nora.r1meta' },
1451
+ { titleKey: 'sample.nora.r2', stateKey: 'receipt.waiting', metaKey: 'sample.nora.r2meta' },
1452
+ { titleKey: 'sample.nora.r3', stateKey: 'receipt.done', metaKey: 'sample.nora.r3meta' },
1453
+ ],
1454
+ routines: [
1455
+ { titleKey: 'sample.routine.weekly', scheduleKey: 'sample.routine.weeklyWhen', on: true },
1456
+ { titleKey: 'sample.routine.inbox', scheduleKey: 'sample.routine.inboxWhen', on: true },
1457
+ { titleKey: 'sample.routine.standup', scheduleKey: 'sample.routine.standupWhen', on: false },
1458
+ ],
1459
+ library: [
1460
+ { group: 'today', titleKey: 'sample.nora.f1', badgeKey: 'sample.nora.f1badge', metaKey: 'sample.nora.f1meta' },
1461
+ { group: 'today', titleKey: 'sample.nora.f2', badgeKey: 'sample.nora.f2badge', metaKey: 'sample.nora.f2meta' },
1462
+ { group: 'week', titleKey: 'sample.nora.f3', badgeKey: 'sample.nora.f3badge', metaKey: 'sample.nora.f3meta' },
1463
+ { group: 'older', titleKey: 'sample.nora.f4', badgeKey: 'sample.nora.f4badge', metaKey: 'sample.nora.f4meta' },
1464
+ ],
1465
+ },
1466
+ {
1467
+ id: 'eli',
1468
+ nameKey: 'sample.eli.name',
1469
+ jobKey: 'sample.eli.job',
1470
+ attention: 'needs',
1471
+ timeKey: 'sample.eli.time',
1472
+ snippetKey: 'sample.eli.snippet',
1473
+ messages: [
1474
+ { id: 'eli-xd', kind: 'day', textKey: 'sample.eli.expiredDay' },
1475
+ { id: 'eli-x', kind: 'approval', approvalId: 'eli-expired' },
1476
+ { id: 'eli-d', kind: 'day', textKey: 'sample.eli.day' },
1477
+ { id: 'eli-b', kind: 'bot', textKey: 'sample.eli.reply' },
1478
+ { id: 'eli-a', kind: 'approval', approvalId: 'eli-pub' },
1479
+ ],
1480
+ approvals: {
1481
+ 'eli-expired': {
1482
+ id: 'eli-expired',
1483
+ titleKey: 'sample.eli.expiredTitle',
1484
+ metaKey: 'sample.eli.expiredMeta',
1485
+ state: 'expired',
1486
+ origin: 'background',
1487
+ target: 'Feishu #weekly',
1488
+ risk: ['outside', 'irreversible'],
1489
+ },
1490
+ 'eli-pub': {
1491
+ id: 'eli-pub',
1492
+ titleKey: 'sample.eli.approvalTitle',
1493
+ metaKey: 'sample.eli.approvalMeta',
1494
+ state: 'pending',
1495
+ expiresMin: 1,
1496
+ origin: 'background',
1497
+ target: 'Feishu #weekly',
1498
+ risk: ['outside', 'irreversible'],
1499
+ },
1500
+ },
1501
+ receipts: [
1502
+ { titleKey: 'sample.nora.r2', stateKey: 'receipt.waiting', metaKey: 'sample.eli.approvalMeta' },
1503
+ ],
1504
+ routines: [],
1505
+ library: [],
1506
+ },
1507
+ {
1508
+ id: 'june',
1509
+ nameKey: 'sample.june.name',
1510
+ jobKey: 'sample.june.job',
1511
+ attention: 'unread',
1512
+ timeKey: 'sample.june.time',
1513
+ snippetKey: 'sample.june.snippet',
1514
+ messages: [
1515
+ { id: 'june-d', kind: 'day', textKey: 'sample.june.day' },
1516
+ { id: 'june-b', kind: 'bot', textKey: 'sample.june.reply' },
1517
+ ],
1518
+ approvals: {},
1519
+ receipts: [
1520
+ { titleKey: 'sample.june.r1', stateKey: 'receipt.done', metaKey: 'sample.june.r1meta' },
1521
+ ],
1522
+ routines: [],
1523
+ library: [],
1524
+ },
1525
+ ]
1526
+ }
1527
+
1528
+ function createState() {
1529
+ return {
1530
+ screen: 'chat',
1531
+ selectedId: 'nora',
1532
+ tab: 'activity',
1533
+ computer: COMPUTER_PREVIEW,
1534
+ realOverview: null,
1535
+ realMachine: null,
1536
+ realError: '',
1537
+ searchOpen: false,
1538
+ search: '',
1539
+ composer: '',
1540
+ flash: null,
1541
+ live: '',
1542
+ focusComposer: false,
1543
+ settingsTab: 'account',
1544
+ setupStep: 0,
1545
+ forceList: false,
1546
+ forceDetail: false,
1547
+ settings: {
1548
+ idle: '15',
1549
+ lowBalance: '10',
1550
+ notifications: true,
1551
+ lang: null,
1552
+ },
1553
+ bots: FIRST_RUN_PREVIEW ? [] : seedBots(),
1554
+ }
1555
+ }
1556
+
1557
+ function tickApprovals(state) {
1558
+ let changed = false
1559
+ const bots = state.bots.map((bot) => {
1560
+ let botChanged = false
1561
+ let botExpired = false
1562
+ const approvals = {}
1563
+ for (const [id, approval] of Object.entries(bot.approvals)) {
1564
+ if (approval.state !== 'pending' || !Number.isFinite(approval.expiresMin)) {
1565
+ approvals[id] = approval
1566
+ continue
1567
+ }
1568
+ const next = approval.expiresMin - 1
1569
+ approvals[id] = next <= 0
1570
+ ? { ...approval, state: 'expired', expiresMin: 0 }
1571
+ : { ...approval, expiresMin: next }
1572
+ botChanged = true
1573
+ if (next <= 0) botExpired = true
1574
+ }
1575
+ if (!botChanged) return bot
1576
+ changed = true
1577
+ const stillPending = Object.values(approvals).some((approval) => approval.state === 'pending')
1578
+ return {
1579
+ ...bot,
1580
+ approvals,
1581
+ attention: bot.attention === 'needs' && !stillPending ? null : bot.attention,
1582
+ snippet: botExpired && !stillPending ? null : bot.snippet,
1583
+ snippetKey: botExpired && !stillPending ? 'approval.expired' : bot.snippetKey,
1584
+ time: botExpired && !stillPending ? clock() : bot.time,
1585
+ timeKey: botExpired && !stillPending ? null : bot.timeKey,
1586
+ }
1587
+ })
1588
+ return changed ? { ...state, bots } : state
1589
+ }
1590
+
1591
+ function botName(bot, t) {
1592
+ return bot.name || t(bot.nameKey)
1593
+ }
1594
+
1595
+ function botJob(bot, t) {
1596
+ return bot.job || (bot.jobKey ? t(bot.jobKey) : '')
1597
+ }
1598
+
1599
+ function botSnippet(bot, t) {
1600
+ if (bot.snippet) return bot.snippet
1601
+ if (bot.snippetKey) return t(bot.snippetKey)
1602
+ return ''
1603
+ }
1604
+
1605
+ function botTime(bot, t) {
1606
+ if (bot.time) return bot.time
1607
+ if (bot.timeKey) return t(bot.timeKey)
1608
+ return ''
1609
+ }
1610
+
1611
+ function attentionText(bot, t) {
1612
+ if (bot.attention === 'needs') return t('attention.needs')
1613
+ if (bot.attention === 'unread') return t('attention.unread')
1614
+ if (bot.attention === 'working') return t('attention.working')
1615
+ return ''
1616
+ }
1617
+
1618
+ function textOf(entry, t) {
1619
+ if (entry.text) return entry.text
1620
+ if (entry.textKey) return t(entry.textKey)
1621
+ return ''
1622
+ }
1623
+
1624
+ function fieldText(entry, t, keyName) {
1625
+ if (entry.text) return entry.text
1626
+ const key = entry[keyName]
1627
+ return key ? t(key) : ''
1628
+ }
1629
+
1630
+ function useDshLang(ctx) {
1631
+ const locale = ctx?.get?.('locale') ?? ctx?.locale
1632
+ const read = () => {
1633
+ try {
1634
+ return String(locale?.getLocale?.()?.active ?? '')
1635
+ } catch {
1636
+ return ''
1637
+ }
1638
+ }
1639
+ const [id, setId] = useState(read)
1640
+ useEffect(() => {
1641
+ if (typeof locale?.subscribe !== 'function') return undefined
1642
+ return locale.subscribe(() => setId(read()))
1643
+ }, [locale])
1644
+ return id
1645
+ }
1646
+
1647
+ function resolveLang(dshId, override) {
1648
+ const chosen = String(override || '').toLowerCase()
1649
+ if (chosen === 'zh' || chosen === 'en') return chosen
1650
+ const id = String(dshId || '').toLowerCase()
1651
+ if (id.startsWith('zh')) return 'zh'
1652
+ if (id.startsWith('en')) return 'en'
1653
+ return 'zh'
1654
+ }
1655
+
1656
+ function useContainerWidth(ref) {
1657
+ const [width, setWidth] = useState(1280)
1658
+ useEffect(() => {
1659
+ const el = ref.current
1660
+ if (!el || typeof ResizeObserver !== 'function') return undefined
1661
+ const measure = () => setWidth(el.clientWidth || 1280)
1662
+ measure()
1663
+ const observer = new ResizeObserver(measure)
1664
+ observer.observe(el)
1665
+ return () => observer.disconnect()
1666
+ }, [ref])
1667
+ return width
1668
+ }
1669
+
1670
+ function Mark() {
1671
+ return h(
1672
+ 'svg',
1673
+ {
1674
+ className: 'rb-mark',
1675
+ width: 20,
1676
+ height: 20,
1677
+ viewBox: '0 0 24 24',
1678
+ fill: 'none',
1679
+ stroke: '#003d9b',
1680
+ strokeWidth: 2,
1681
+ strokeLinecap: 'round',
1682
+ strokeLinejoin: 'round',
1683
+ 'aria-hidden': 'true',
1684
+ },
1685
+ MARK_PATHS.map((d) => h('path', { key: d, d })),
1686
+ )
1687
+ }
1688
+
1689
+ function SearchIcon() {
1690
+ return h(
1691
+ 'svg',
1692
+ { width: 15, height: 15, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', 'aria-hidden': 'true' },
1693
+ h('circle', { cx: 11, cy: 11, r: 7 }),
1694
+ h('path', { d: 'm16.5 16.5 4.5 4.5' }),
1695
+ )
1696
+ }
1697
+
1698
+ function GearIcon() {
1699
+ return h(
1700
+ 'svg',
1701
+ { width: 15, height: 15, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', 'aria-hidden': 'true' },
1702
+ h('path', { d: 'M4 7h9M18 7h2M4 12h3M11 12h9M4 17h7M15 17h5' }),
1703
+ h('circle', { cx: 15, cy: 7, r: 2 }),
1704
+ h('circle', { cx: 9, cy: 12, r: 2 }),
1705
+ h('circle', { cx: 13, cy: 17, r: 2 }),
1706
+ )
1707
+ }
1708
+
1709
+ function Avatar({ size, name, text, className }) {
1710
+ return h(
1711
+ 'div',
1712
+ {
1713
+ className: `rb-avatar rb-${size}${className ? ` ${className}` : ''}`,
1714
+ style: avatarStyle(name),
1715
+ 'aria-hidden': 'true',
1716
+ },
1717
+ text || monogram(name),
1718
+ )
1719
+ }
1720
+
1721
+ function lineParts(template, vars, boldKeys) {
1722
+ const nodes = []
1723
+ const re = /\{(\w+)\}/g
1724
+ let last = 0
1725
+ let index = 0
1726
+ let match = re.exec(template)
1727
+ while (match) {
1728
+ if (match.index > last) nodes.push(template.slice(last, match.index))
1729
+ const name = match[1]
1730
+ const value = vars && vars[name] != null ? String(vars[name]) : ''
1731
+ nodes.push(boldKeys.has(name) ? h('b', { key: `${name}${index}` }, value) : value)
1732
+ last = match.index + match[0].length
1733
+ index += 1
1734
+ match = re.exec(template)
1735
+ }
1736
+ if (last < template.length) nodes.push(template.slice(last))
1737
+ return nodes
1738
+ }
1739
+
1740
+ function Toggle({ on, label, onClick }) {
1741
+ return h('button', {
1742
+ type: 'button',
1743
+ className: on ? 'rb-toggle rb-on' : 'rb-toggle',
1744
+ 'aria-pressed': on ? 'true' : 'false',
1745
+ 'aria-label': label,
1746
+ onClick,
1747
+ })
1748
+ }
1749
+
1750
+ function BotFields({ t, name, job, instructions, onName, onJob, onInstructions }) {
1751
+ return h(
1752
+ 'div',
1753
+ null,
1754
+ h(
1755
+ 'div',
1756
+ { className: 'rb-line rb-mono' },
1757
+ h(Avatar, { size: 'new', name: name || t('newBot.defaultName') }),
1758
+ h('div', { className: 'rb-hint' }, t('newBot.monogramHint')),
1759
+ ),
1760
+ h(
1761
+ 'div',
1762
+ { className: 'rb-stack' },
1763
+ h(
1764
+ 'label',
1765
+ { className: 'rb-flabel' },
1766
+ t('newBot.name'),
1767
+ h('input', {
1768
+ className: 'rb-field',
1769
+ value: name,
1770
+ maxLength: 40,
1771
+ autoFocus: true,
1772
+ onChange: (event) => onName(event.target.value),
1773
+ }),
1774
+ ),
1775
+ h(
1776
+ 'label',
1777
+ { className: 'rb-flabel' },
1778
+ t('newBot.job'),
1779
+ h('input', {
1780
+ className: 'rb-field',
1781
+ value: job,
1782
+ maxLength: 80,
1783
+ onChange: (event) => onJob(event.target.value),
1784
+ }),
1785
+ ),
1786
+ h(
1787
+ 'label',
1788
+ { className: 'rb-flabel' },
1789
+ t('newBot.instructions'),
1790
+ h('textarea', {
1791
+ className: 'rb-field rb-area',
1792
+ rows: 4,
1793
+ value: instructions,
1794
+ placeholder: t('newBot.placeholder', { name: name || t('newBot.defaultName') }),
1795
+ onChange: (event) => onInstructions(event.target.value),
1796
+ }),
1797
+ ),
1798
+ ),
1799
+ )
1800
+ }
1801
+
1802
+ function idleLabel(t, idle) {
1803
+ if (idle === '30') return t('settings.idle30')
1804
+ if (idle === '0') return t('settings.idleOff')
1805
+ return t('settings.idle15')
1806
+ }
1807
+
1808
+ function BotsApp({ ctx }) {
1809
+ const [state, setState] = useState(createState)
1810
+ const [host, setHost] = useState({ status: 'checking' })
1811
+ const [hostAttempt, setHostAttempt] = useState(0)
1812
+ const [desktop, setDesktop] = useState(null)
1813
+ const dshLang = useDshLang(ctx)
1814
+ const lang = resolveLang(dshLang, state.settings.lang)
1815
+
1816
+ useEffect(() => {
1817
+ const previous = document.title
1818
+ document.title = 'Rayrun Bot'
1819
+ return () => { document.title = previous }
1820
+ }, [])
1821
+ const t = makeT(lang === 'zh' ? ZH : EN)
1822
+ const frameRef = useRef(null)
1823
+ const searchRef = useRef(null)
1824
+ const composerRef = useRef(null)
1825
+ const replyTimers = useRef(new Map())
1826
+ const sessionPolls = useRef(new Map())
1827
+ const selectedIdRef = useRef(state.selectedId)
1828
+ const width = useContainerWidth(frameRef)
1829
+
1830
+ useEffect(() => {
1831
+ selectedIdRef.current = state.selectedId
1832
+ }, [state.selectedId])
1833
+
1834
+ useEffect(() => {
1835
+ const onKey = (event) => {
1836
+ if (event.key !== 'Escape') return
1837
+ setState((current) => {
1838
+ if (current.searchOpen) return { ...current, searchOpen: false, search: '' }
1839
+ if (current.screen !== 'chat') return { ...current, screen: 'chat', flash: null }
1840
+ return current
1841
+ })
1842
+ }
1843
+ document.addEventListener('keydown', onKey)
1844
+ return () => document.removeEventListener('keydown', onKey)
1845
+ }, [])
1846
+
1847
+ useEffect(() => () => {
1848
+ for (const timer of replyTimers.current.values()) clearTimeout(timer)
1849
+ replyTimers.current.clear()
1850
+ for (const record of sessionPolls.current.values()) {
1851
+ record.cancelled = true
1852
+ if (record.timer) clearTimeout(record.timer)
1853
+ }
1854
+ sessionPolls.current.clear()
1855
+ }, [])
1856
+
1857
+ useEffect(() => {
1858
+ const timer = setInterval(() => setState(tickApprovals), 60 * 1000)
1859
+ return () => clearInterval(timer)
1860
+ }, [])
1861
+
1862
+ useEffect(() => {
1863
+ if (state.searchOpen) searchRef.current?.focus()
1864
+ }, [state.searchOpen])
1865
+
1866
+ useEffect(() => {
1867
+ if (!state.focusComposer || state.screen !== 'chat') return
1868
+ composerRef.current?.focus()
1869
+ setState((current) => ({ ...current, focusComposer: false }))
1870
+ }, [state.focusComposer, state.screen])
1871
+
1872
+ useEffect(() => {
1873
+ const controller = new AbortController()
1874
+ const run = async () => {
1875
+ setHost({ status: 'checking' })
1876
+ try {
1877
+ const response = await fetch('/plugins/rayrun-bots?action=health', {
1878
+ method: 'GET',
1879
+ mode: 'same-origin',
1880
+ credentials: 'same-origin',
1881
+ cache: 'no-store',
1882
+ headers: { Accept: 'application/json' },
1883
+ signal: controller.signal,
1884
+ })
1885
+ if (!response.ok) throw new Error(`health ${response.status}`)
1886
+ const body = await response.json()
1887
+ if (!body || body.ok !== true || body.plugin !== 'rayrun-bots') throw new Error('bad health envelope')
1888
+ setHost({ status: 'loaded', version: String(body.version ?? ''), ready: body.ready === true, dependency: body.dependency ?? null })
1889
+ } catch (error) {
1890
+ if (error?.name === 'AbortError') return
1891
+ setHost({ status: 'down' })
1892
+ }
1893
+ }
1894
+ run()
1895
+ return () => controller.abort()
1896
+ }, [hostAttempt])
1897
+
1898
+ useEffect(() => {
1899
+ if (host.status !== 'loaded') return undefined
1900
+ let cancelled = false
1901
+ void (async () => {
1902
+ try {
1903
+ const body = await hostRpc('bots.list')
1904
+ const bots = Array.isArray(body.bots) ? body.bots : []
1905
+ if (cancelled || bots.length === 0) return
1906
+ setState((current) => {
1907
+ const roster = bots.map((bot) => realBot(bot, body.routines?.[bot.id]))
1908
+ const selectedId = roster.some((bot) => bot.id === current.selectedId)
1909
+ ? current.selectedId
1910
+ : roster[0].id
1911
+ return { ...current, bots: roster, selectedId }
1912
+ })
1913
+ } catch {
1914
+ // Keep the preview; the Settings host row reports the failure.
1915
+ }
1916
+ })()
1917
+ return () => { cancelled = true }
1918
+ }, [host.status])
1919
+
1920
+ const selected = state.bots.find((bot) => bot.id === state.selectedId) || state.bots[0] || null
1921
+ const listOn = width >= 900 || state.forceList
1922
+ const detailOn = state.screen === 'chat' && (width >= 1120 || state.forceDetail)
1923
+ const columns = `${listOn ? '296px ' : ''}minmax(0,1fr)${detailOn ? ' 328px' : ''}`
1924
+
1925
+ const patch = (partial) => setState((current) => ({ ...current, ...partial }))
1926
+
1927
+ useEffect(() => {
1928
+ if (state.screen !== 'chat') return undefined
1929
+ let cancelled = false
1930
+ void (async () => {
1931
+ try {
1932
+ const overview = await rayRpc('overview')
1933
+ if (cancelled) return
1934
+ const machines = Array.isArray(overview.machines) ? overview.machines : []
1935
+ patch({ realOverview: overview, realMachine: pickMachine(machines) || null, realError: '' })
1936
+ } catch (error) {
1937
+ if (!cancelled) patch({ realError: String(error?.message ?? error) })
1938
+ }
1939
+ })()
1940
+ return () => {
1941
+ cancelled = true
1942
+ }
1943
+ }, [state.screen])
1944
+
1945
+ const realConfigured = state.realOverview?.connection?.configured === true
1946
+ const realBalanceCents = Number(state.realOverview?.balance?.balance_cents)
1947
+ const realBalance = Number.isFinite(realBalanceCents) ? realBalanceCents / 100 : NaN
1948
+
1949
+ const openScreen = (screen) => patch({ screen, flash: null, searchOpen: false })
1950
+
1951
+ const selectBot = (id) => {
1952
+ selectedIdRef.current = id
1953
+ setState((current) => ({
1954
+ ...current,
1955
+ selectedId: id,
1956
+ screen: 'chat',
1957
+ tab: 'activity',
1958
+ forceList: false,
1959
+ flash: null,
1960
+ bots: current.bots.map((bot) => (bot.id === id && bot.attention === 'unread' ? { ...bot, attention: null } : bot)),
1961
+ }))
1962
+ }
1963
+
1964
+ const updateBot = (id, fn) => {
1965
+ setState((current) => ({
1966
+ ...current,
1967
+ bots: current.bots.map((bot) => (bot.id === id ? fn(bot) : bot)),
1968
+ }))
1969
+ }
1970
+
1971
+ const startPolling = (botId, after) => {
1972
+ if (sessionPolls.current.has(botId)) return
1973
+ const record = { cancelled: false, timer: null, startedAt: Date.now() }
1974
+ sessionPolls.current.set(botId, record)
1975
+ let cursor = Number.isInteger(after) ? after : 0
1976
+ const stop = () => {
1977
+ record.cancelled = true
1978
+ if (record.timer) clearTimeout(record.timer)
1979
+ sessionPolls.current.delete(botId)
1980
+ }
1981
+ const tick = async () => {
1982
+ if (record.cancelled) return
1983
+ if (Date.now() - record.startedAt > SESSION_POLL_LIMIT_MS) {
1984
+ updateBot(botId, (bot) => appendSessionError(bot, t('chat.turnTimeout'), 'E_INTERNAL'))
1985
+ setState((current) => ({ ...current, live: t('chat.turnTimeout') }))
1986
+ stop()
1987
+ return
1988
+ }
1989
+ try {
1990
+ const body = await hostRpc('session.history', { botId, after: cursor })
1991
+ if (record.cancelled) return
1992
+ const session = body.session
1993
+ if (Number.isInteger(session?.lastSeq)) cursor = Math.max(cursor, session.lastSeq)
1994
+ const lastBot = [...(body.messages ?? [])].reverse().find((message) => message.role === 'bot')
1995
+ updateBot(botId, (bot) => applySession(bot, body, t, {
1996
+ append: true,
1997
+ unread: Boolean(lastBot) && selectedIdRef.current !== botId,
1998
+ }))
1999
+ if (lastBot?.text) {
2000
+ setState((current) => ({ ...current, live: String(lastBot.text).slice(0, 200) }))
2001
+ }
2002
+ if (sessionWorking(session)) record.timer = setTimeout(tick, SESSION_POLL_MS)
2003
+ else stop()
2004
+ } catch (error) {
2005
+ if (record.cancelled) return
2006
+ const message = sessionErrorText(t, error?.code, t('chat.historyFailed'))
2007
+ updateBot(botId, (bot) => appendSessionError(bot, message, error?.code ?? 'E_INTERNAL'))
2008
+ setState((current) => ({ ...current, live: message }))
2009
+ stop()
2010
+ }
2011
+ }
2012
+ record.timer = setTimeout(tick, SESSION_POLL_MS)
2013
+ }
2014
+
2015
+ useEffect(() => {
2016
+ if (!selected || selected.source !== 'real' || selected.historyLoaded || host.status !== 'loaded') {
2017
+ return undefined
2018
+ }
2019
+ let cancelled = false
2020
+ void (async () => {
2021
+ try {
2022
+ void hostRpc('routines.sync', { botId: selected.id }).catch(() => null)
2023
+ const [body, approvalBody] = await Promise.all([
2024
+ hostRpc('session.history', { botId: selected.id, tail: true }),
2025
+ hostRpc('approvals.list', { botId: selected.id }).catch(() => null),
2026
+ ])
2027
+ if (cancelled) return
2028
+ updateBot(selected.id, (bot) => {
2029
+ const next = bot.messages.length > 0
2030
+ ? { ...bot, historyLoaded: true }
2031
+ : applySession(bot, body, t)
2032
+ return approvalBody?.approvals ? applyApprovals(next, approvalBody.approvals, t) : next
2033
+ })
2034
+ if (sessionWorking(body.session)) startPolling(selected.id, body.session.lastSeq ?? 0)
2035
+ } catch (error) {
2036
+ if (cancelled) return
2037
+ const message = sessionErrorText(t, error?.code, t('chat.historyFailed'))
2038
+ updateBot(selected.id, (bot) => appendSessionError(bot, message, error?.code ?? 'E_INTERNAL'))
2039
+ }
2040
+ })()
2041
+ return () => { cancelled = true }
2042
+ }, [selected?.id, selected?.source, selected?.historyLoaded, host.status])
2043
+
2044
+ useEffect(() => {
2045
+ if (!selected || selected.source !== 'real' || host.status !== 'loaded') return undefined
2046
+ let cancelled = false
2047
+ let timer
2048
+ let running = false
2049
+ const load = async () => {
2050
+ if (running) return
2051
+ running = true
2052
+ try {
2053
+ await hostRpc('approvals.sync', { botId: selected.id })
2054
+ if (cancelled) return
2055
+ await hostRpc('routines.sync', { botId: selected.id }).catch(() => null)
2056
+ if (cancelled) return
2057
+ const [body, history] = await Promise.all([
2058
+ hostRpc('approvals.list', { botId: selected.id }),
2059
+ hostRpc('session.history', { botId: selected.id, tail: true }),
2060
+ ])
2061
+ if (cancelled) return
2062
+ updateBot(selected.id, (bot) => {
2063
+ if (bot.working || sessionWorking(history.session)) {
2064
+ return applyApprovals(bot, body.approvals, t)
2065
+ }
2066
+ const next = applySession(bot, history, t, { append: true })
2067
+ return applyApprovals(next, body.approvals, t)
2068
+ })
2069
+ } catch {
2070
+ if (timer) clearInterval(timer)
2071
+ } finally {
2072
+ running = false
2073
+ }
2074
+ }
2075
+ timer = setInterval(load, 5000)
2076
+ void load()
2077
+ return () => {
2078
+ cancelled = true
2079
+ if (timer) clearInterval(timer)
2080
+ }
2081
+ }, [selected?.id, selected?.source, host.status])
2082
+
2083
+ const send = (override) => {
2084
+ const text = typeof override === 'string' ? override.trim() : state.composer.trim()
2085
+ if (!text || !selected || selected.working) return
2086
+ const botId = selected.id
2087
+ const workingId = uid('working')
2088
+ const userId = uid('user')
2089
+ const at = new Date().toISOString()
2090
+ const snippet = text.length > 48 ? `${text.slice(0, 47)}…` : text
2091
+ setState((current) => ({
2092
+ ...current,
2093
+ composer: typeof override === 'string' ? current.composer : '',
2094
+ flash: null,
2095
+ live: t('chat.sending'),
2096
+ bots: current.bots.map((bot) => {
2097
+ if (bot.id !== botId) return bot
2098
+ return {
2099
+ ...bot,
2100
+ working: true,
2101
+ attention: 'working',
2102
+ snippet,
2103
+ snippetKey: null,
2104
+ time: clock(),
2105
+ timeKey: null,
2106
+ messages: [...bot.messages, { id: userId, kind: 'user', text, at }, { id: workingId, kind: 'working' }],
2107
+ }
2108
+ }),
2109
+ }))
2110
+ if (selected.source === 'real') {
2111
+ void (async () => {
2112
+ try {
2113
+ const body = await hostRpc('session.send', { botId, text })
2114
+ const cursor = Number.isInteger(body.message?.seq)
2115
+ ? body.message.seq
2116
+ : Number.isInteger(body.session?.lastSeq) ? body.session.lastSeq : 0
2117
+ const serverId = Number.isInteger(body.message?.seq) ? `session-${body.message.seq}` : null
2118
+ updateBot(botId, (bot) => ({
2119
+ ...bot,
2120
+ session: body.session ?? bot.session,
2121
+ sessionCursor: cursor,
2122
+ historyLoaded: true,
2123
+ messages: serverId
2124
+ ? bot.messages.map((entry) => (entry.id === userId ? { ...entry, id: serverId } : entry))
2125
+ : bot.messages,
2126
+ }))
2127
+ startPolling(botId, cursor)
2128
+ } catch (error) {
2129
+ const message = sessionErrorText(t, error?.code, t('chat.sendFailed'))
2130
+ updateBot(botId, (bot) => appendSessionError(bot, message, error?.code ?? 'E_INTERNAL'))
2131
+ setState((current) => ({ ...current, live: message }))
2132
+ }
2133
+ })()
2134
+ return
2135
+ }
2136
+ const timer = setTimeout(() => {
2137
+ replyTimers.current.delete(botId)
2138
+ setState((current) => ({
2139
+ ...current,
2140
+ live: t('chat.simulatedReply'),
2141
+ bots: current.bots.map((bot) => {
2142
+ if (bot.id !== botId) return bot
2143
+ const approvalId = uid('approval')
2144
+ return {
2145
+ ...bot,
2146
+ working: false,
2147
+ attention: 'needs',
2148
+ snippet: null,
2149
+ snippetKey: 'chat.simulatedSnippet',
2150
+ time: clock(),
2151
+ timeKey: null,
2152
+ messages: [
2153
+ ...bot.messages.filter((entry) => entry.id !== workingId),
2154
+ { id: uid('bot'), kind: 'bot', textKey: 'chat.simulatedReply' },
2155
+ { id: uid('approval-card'), kind: 'approval', approvalId },
2156
+ ],
2157
+ approvals: {
2158
+ ...bot.approvals,
2159
+ [approvalId]: {
2160
+ id: approvalId,
2161
+ titleKey: 'chat.simulatedApprovalTitle',
2162
+ metaKey: 'chat.simulatedApprovalMeta',
2163
+ state: 'pending',
2164
+ origin: 'chat',
2165
+ targetKey: 'chat.simulatedTarget',
2166
+ risk: ['outside', 'irreversible'],
2167
+ },
2168
+ },
2169
+ }
2170
+ }),
2171
+ }))
2172
+ }, 1200)
2173
+ replyTimers.current.set(botId, timer)
2174
+ }
2175
+
2176
+ const decide = (approvalId, decision) => {
2177
+ if (!selected) return
2178
+ const allowed = decision === 'allowed'
2179
+ const currentApproval = selected.approvals[approvalId]
2180
+ if (selected.source === 'real' && currentApproval?.real) {
2181
+ const botId = selected.id
2182
+ void (async () => {
2183
+ try {
2184
+ const body = await hostRpc('approvals.decide', {
2185
+ botId,
2186
+ id: approvalId,
2187
+ decision: allowed ? 'approve' : 'deny',
2188
+ })
2189
+ const approval = body.approval
2190
+ ? { ...body.approval, execution: body.execution ?? body.approval.execution }
2191
+ : null
2192
+ let sentence
2193
+ if (!allowed) sentence = t('approval.deniedReal')
2194
+ else if (body.execution?.state === 'done') sentence = t('approval.allowedReal')
2195
+ else if (body.execution?.state === 'refused') sentence = t('approval.executionRefused')
2196
+ else if (body.execution?.state === 'failed') sentence = t('approval.executionFailed')
2197
+ else sentence = t('approval.executionPending')
2198
+ updateBot(botId, (bot) => (approval ? applyApprovalResult(bot, approval, t) : bot))
2199
+ setState((current) => ({ ...current, flash: sentence, live: sentence }))
2200
+ } catch (error) {
2201
+ const message = sessionErrorText(t, error?.code, t('approval.executionFailed'))
2202
+ updateBot(botId, (bot) => appendSessionError(bot, message, error?.code ?? 'E_INTERNAL'))
2203
+ setState((current) => ({ ...current, flash: message, live: message }))
2204
+ }
2205
+ })()
2206
+ return
2207
+ }
2208
+ const sentence = t(allowed ? 'approval.allowedLocal' : 'approval.deniedLocal')
2209
+ const snippet = t(allowed ? 'approval.snippetAllowed' : 'approval.snippetDenied')
2210
+ setState((current) => ({
2211
+ ...current,
2212
+ flash: sentence,
2213
+ live: sentence,
2214
+ bots: current.bots.map((bot) => {
2215
+ if (bot.id !== selected.id) return bot
2216
+ const currentApproval = bot.approvals[approvalId]
2217
+ if (!currentApproval || currentApproval.state !== 'pending') return bot
2218
+ const approvals = { ...bot.approvals, [approvalId]: { ...currentApproval, state: decision } }
2219
+ const stillPending = Object.values(approvals).some((item) => item.state === 'pending')
2220
+ return {
2221
+ ...bot,
2222
+ approvals,
2223
+ attention: bot.attention === 'needs' && !stillPending ? null : bot.attention,
2224
+ snippet: stillPending ? bot.snippet : snippet,
2225
+ snippetKey: stillPending ? bot.snippetKey : null,
2226
+ }
2227
+ }),
2228
+ }))
2229
+ }
2230
+
2231
+ const createBot = async (draft) => {
2232
+ const name = draft.name.trim()
2233
+ if (!name) return
2234
+ const job = draft.job.trim()
2235
+ const instructions = draft.instructions.trim() || t('persona.template', { name, job: job || '…' })
2236
+ const body = await hostRpc('bots.create', { name, label: job, instructions })
2237
+ const bot = body.bot
2238
+ if (!bot || typeof bot.id !== 'string') throw new Error('bots.create returned no bot')
2239
+ setState((current) => ({
2240
+ ...current,
2241
+ screen: 'chat',
2242
+ selectedId: bot.id,
2243
+ tab: 'activity',
2244
+ flash: null,
2245
+ focusComposer: true,
2246
+ bots: [...current.bots.filter((item) => item.source === 'real'), realBot(bot)],
2247
+ }))
2248
+ }
2249
+
2250
+ const flash = (text) => patch({ flash: text, live: text })
2251
+
2252
+ const toggleRoutine = async (bot, index) => {
2253
+ const routine = bot.routines[index]
2254
+ if (!routine) return
2255
+ if (bot.source !== 'real') {
2256
+ updateBot(bot.id, (current) => ({
2257
+ ...current,
2258
+ routines: current.routines.map((item, routineIndex) => (
2259
+ routineIndex === index ? { ...item, on: !item.on } : item
2260
+ )),
2261
+ }))
2262
+ return
2263
+ }
2264
+ try {
2265
+ const body = await hostRpc('routines.update', {
2266
+ botId: bot.id,
2267
+ id: routine.id,
2268
+ patch: { enabled: !routine.on },
2269
+ })
2270
+ updateBot(bot.id, (current) => ({ ...current, routines: realRoutines(body.routines) }))
2271
+ } catch (error) {
2272
+ flash(t('routine.updateFailed', { message: String(error?.message ?? error) }))
2273
+ }
2274
+ }
2275
+
2276
+ const createRoutine = async (bot, draft) => {
2277
+ const body = await hostRpc('routines.create', {
2278
+ botId: bot.id,
2279
+ title: draft.title,
2280
+ prompt: draft.prompt,
2281
+ everyMinutes: draft.everyMinutes,
2282
+ })
2283
+ updateBot(bot.id, (current) => ({ ...current, routines: realRoutines(body.routines) }))
2284
+ }
2285
+
2286
+ const removeRoutine = async (bot, index) => {
2287
+ const routine = bot.routines[index]
2288
+ if (!routine) return
2289
+ try {
2290
+ const body = await hostRpc('routines.remove', { botId: bot.id, id: routine.id })
2291
+ updateBot(bot.id, (current) => ({ ...current, routines: realRoutines(body.routines) }))
2292
+ } catch (error) {
2293
+ flash(t('routine.removeFailed', { message: String(error?.message ?? error) }))
2294
+ }
2295
+ }
2296
+
2297
+ const openComputer = async () => {
2298
+ const win = window.open('', '_blank')
2299
+ if (!win) {
2300
+ flash(t('computer.popupBlocked'))
2301
+ return
2302
+ }
2303
+ win.opener = null
2304
+ try {
2305
+ const overview = await rayRpc('overview')
2306
+ if (overview.connection?.configured !== true) {
2307
+ win.close()
2308
+ flash(t('computer.connectFirst'))
2309
+ return
2310
+ }
2311
+ const machines = Array.isArray(overview.machines) ? overview.machines : []
2312
+ const selectedMachine = pickMachine(machines)
2313
+ patch({ realOverview: overview, realMachine: selectedMachine || null, realError: '' })
2314
+ let machine = selectedMachine
2315
+ if (!machine) {
2316
+ win.close()
2317
+ flash(t('computer.noMachine'))
2318
+ return
2319
+ }
2320
+ if (machine.status !== 'Running') {
2321
+ flash(t('computer.starting'))
2322
+ await rayRpc('machine.action', {
2323
+ id: machine.id,
2324
+ verb: machine.status === 'Paused' ? 'resume' : 'start',
2325
+ })
2326
+ for (let i = 0; i < 40; i += 1) {
2327
+ await new Promise((resolve) => setTimeout(resolve, 1500))
2328
+ machine = (await rayRpc('machine.get', { id: machine.id })).machine
2329
+ if (machine?.status === 'Running') break
2330
+ }
2331
+ }
2332
+ if (machine?.status !== 'Running') {
2333
+ win.close()
2334
+ flash(t('computer.startTimeout'))
2335
+ return
2336
+ }
2337
+ patch({ realMachine: machine })
2338
+ await rayRpc('machine.desktopRepair', { id: machine.id }).catch(() => {})
2339
+ if (!machine.desktop_url) {
2340
+ win.close()
2341
+ flash(t('computer.noDesktop'))
2342
+ return
2343
+ }
2344
+ const password = await rayRpc('machine.password', { id: machine.id })
2345
+ const result = password.result ?? {}
2346
+ const secret = [result.stdout, result.stderr].filter(Boolean).join('\n').trim()
2347
+ if (!win.closed) win.location = machine.desktop_url
2348
+ setDesktop({ password: secret, copied: false })
2349
+ flash(t('computer.opened'))
2350
+ } catch (error) {
2351
+ win.close()
2352
+ const detail = String(error?.message ?? error)
2353
+ flash(/token_required|unauthorized/i.test(detail)
2354
+ ? t('computer.connectFirst')
2355
+ : t('computer.openFailed', { message: detail }))
2356
+ }
2357
+ }
2358
+
2359
+ const stopComputer = async () => {
2360
+ const machine = state.realMachine
2361
+ if (!machine?.id) {
2362
+ flash(t('computer.noMachineShort'))
2363
+ return
2364
+ }
2365
+ if (machine.status !== 'Running') return
2366
+ try {
2367
+ flash(t('computer.stopping'))
2368
+ const result = await rayRpc('machine.action', { id: machine.id, verb: 'stop' })
2369
+ let next = result?.machine ?? machine
2370
+ for (let i = 0; i < 20; i += 1) {
2371
+ await new Promise((resolve) => setTimeout(resolve, 1500))
2372
+ next = (await rayRpc('machine.get', { id: machine.id })).machine ?? next
2373
+ if (next?.status !== 'Running' && next?.status !== 'Stopping') break
2374
+ }
2375
+ patch({ realMachine: next })
2376
+ const overview = await rayRpc('overview').catch(() => null)
2377
+ if (overview) patch({ realOverview: overview })
2378
+ if (next?.status === 'Running' || next?.status === 'Stopping') flash(t('computer.stopTimeout'))
2379
+ else flash(t('computer.stopped'))
2380
+ } catch (error) {
2381
+ const detail = String(error?.message ?? error)
2382
+ flash(/token_required|unauthorized/i.test(detail)
2383
+ ? t('computer.connectFirst')
2384
+ : t('computer.stopFailed', { message: detail }))
2385
+ }
2386
+ }
2387
+
2388
+ const catalog = lang === 'zh' ? ZH : EN
2389
+ const balance = Number.isFinite(realBalance) ? realBalance : moneyNumber(t('usage.sampleBalance'))
2390
+ const threshold = moneyNumber(state.settings.lowBalance)
2391
+ const low = LOW_BALANCE_PREVIEW
2392
+ || (realConfigured && Number.isFinite(realBalance) && Number.isFinite(threshold) && realBalance < threshold)
2393
+
2394
+ const query = state.search.trim().toLowerCase()
2395
+ const rows = state.bots.filter((bot) => {
2396
+ if (selected && bot.id === selected.id) return false
2397
+ if (!query) return true
2398
+ const hay = `${botName(bot, t)} ${botJob(bot, t)} ${botSnippet(bot, t)}`.toLowerCase()
2399
+ return hay.includes(query)
2400
+ })
2401
+
2402
+ const center = renderCenter({
2403
+ state,
2404
+ t,
2405
+ lang,
2406
+ selected,
2407
+ low,
2408
+ onComposer: (composer) => patch({ composer }),
2409
+ onSend: send,
2410
+ onDecide: decide,
2411
+ onContinue: () => send(t('approval.continuePrompt')),
2412
+ onView: () => flash(t('computer.desktopLater')),
2413
+ onAttach: () => flash(t('notice.attach')),
2414
+ onCreate: createBot,
2415
+ onScreen: openScreen,
2416
+ onSetupStep: (setupStep) => patch({ setupStep }),
2417
+ onFlash: flash,
2418
+ onSettings: (partial) => {
2419
+ let next = partial
2420
+ if (partial?.lang === 'zh' || partial?.lang === 'en') {
2421
+ try {
2422
+ const locale = ctx?.get?.('locale') ?? ctx?.locale
2423
+ if (typeof locale?.setLocale === 'function') {
2424
+ locale.setLocale(partial.lang)
2425
+ // DSH owns the persisted preference; follow it instead of
2426
+ // pinning a session-only override.
2427
+ next = { ...partial, lang: null }
2428
+ }
2429
+ } catch {
2430
+ // Keep the in-memory language when DSH cannot persist the choice.
2431
+ }
2432
+ }
2433
+ setState((current) => ({ ...current, settings: { ...current.settings, ...next } }))
2434
+ },
2435
+ onSettingsTab: (settingsTab) => patch({ settingsTab }),
2436
+ catalog,
2437
+ width,
2438
+ composerRef,
2439
+ host,
2440
+ onRetryHost: () => setHostAttempt((n) => n + 1),
2441
+ onToggleList: () => patch({ forceList: !state.forceList }),
2442
+ onToggleDetail: () => patch({ forceDetail: !state.forceDetail }),
2443
+ })
2444
+
2445
+ return h(
2446
+ 'div',
2447
+ { className: 'rb-frame', ref: frameRef, id: 'rayrun-bots-root' },
2448
+ h('style', null, CSS),
2449
+ h('p', { className: 'rb-sr' }, t('notice.preview')),
2450
+ h('div', { className: 'rb-sr', 'aria-live': 'polite' }, state.live),
2451
+ h(
2452
+ 'div',
2453
+ { className: 'rb-app', style: { gridTemplateColumns: columns } },
2454
+ listOn ? h(ChatList, {
2455
+ t,
2456
+ state,
2457
+ rows,
2458
+ selected,
2459
+ searchRef,
2460
+ low,
2461
+ connected: realConfigured,
2462
+ balance: realConfigured ? balanceText(state.realOverview?.balance) : null,
2463
+ onSearchToggle: () => patch({ searchOpen: !state.searchOpen, search: state.searchOpen ? '' : state.search }),
2464
+ onSearch: (search) => patch({ search }),
2465
+ onSelect: selectBot,
2466
+ onNew: () => openScreen('newbot'),
2467
+ onSettings: () => openScreen('settings'),
2468
+ onSetup: () => {
2469
+ patch({ screen: 'setup', setupStep: 0, flash: null, searchOpen: false })
2470
+ },
2471
+ }) : null,
2472
+ center,
2473
+ detailOn && selected ? h(Details, {
2474
+ t,
2475
+ catalog,
2476
+ bot: selected,
2477
+ tab: state.tab,
2478
+ onTab: (tab) => patch({ tab }),
2479
+ computer: state.computer,
2480
+ machine: state.realMachine,
2481
+ configured: realConfigured,
2482
+ overview: state.realOverview,
2483
+ usageError: state.realError,
2484
+ usagePreview: LOW_BALANCE_PREVIEW,
2485
+ low,
2486
+ idle: idleLabel(t, state.settings.idle),
2487
+ onToggleRoutine: (index) => toggleRoutine(selected, index),
2488
+ onCreateRoutine: (draft) => createRoutine(selected, draft),
2489
+ onRemoveRoutine: (index) => removeRoutine(selected, index),
2490
+ onComputer: openComputer,
2491
+ onStop: stopComputer,
2492
+ }) : null,
2493
+ ),
2494
+ desktop ? h(
2495
+ 'div',
2496
+ { className: 'rb-desktop-toast', role: 'status' },
2497
+ h('h3', null, t('computer.passwordTitle')),
2498
+ h('p', null, t('computer.passwordBody')),
2499
+ h('code', null, desktop.password || t('computer.passwordEmpty')),
2500
+ h(
2501
+ 'div',
2502
+ { className: 'rb-line' },
2503
+ h('button', {
2504
+ type: 'button',
2505
+ className: 'rb-btn',
2506
+ disabled: !desktop.password,
2507
+ onClick: async () => {
2508
+ try {
2509
+ await navigator.clipboard.writeText(desktop.password)
2510
+ setDesktop({ ...desktop, copied: true })
2511
+ } catch {
2512
+ flash(t('computer.copyFailed'))
2513
+ }
2514
+ },
2515
+ }, desktop.copied ? t('computer.copied') : t('computer.copy')),
2516
+ h('button', { type: 'button', className: 'rb-btn rb-ghost', onClick: () => setDesktop(null) }, t('computer.close')),
2517
+ ),
2518
+ ) : null,
2519
+ )
2520
+ }
2521
+
2522
+ function ChatList({ t, state, rows, selected, searchRef, low, connected, balance, onSearchToggle, onSearch, onSelect, onNew, onSettings, onSetup }) {
2523
+ const userName = t('sample.user.name')
2524
+ return h(
2525
+ 'aside',
2526
+ { className: 'rb-list', 'aria-label': t('panel.label') },
2527
+ h(
2528
+ 'div',
2529
+ { className: 'rb-list-top' },
2530
+ h('div', { className: 'rb-brand' }, h(Mark), h('span', null, t('brand')), h('span', { className: 'rb-preview-pill' }, t('preview.badge'))),
2531
+ h(
2532
+ 'div',
2533
+ { className: 'rb-tools' },
2534
+ h('button', { type: 'button', className: 'rb-icon', title: t('list.search'), 'aria-label': t('list.search'), 'aria-pressed': state.searchOpen ? 'true' : 'false', onClick: onSearchToggle }, h(SearchIcon)),
2535
+ h('button', { type: 'button', className: 'rb-icon', title: t('list.newBot'), 'aria-label': t('list.newBot'), onClick: onNew }, '+'),
2536
+ ),
2537
+ ),
2538
+ state.searchOpen ? h(
2539
+ 'div',
2540
+ { className: 'rb-search' },
2541
+ h('input', {
2542
+ ref: searchRef,
2543
+ value: state.search,
2544
+ placeholder: t('list.searchPlaceholder'),
2545
+ 'aria-label': t('list.search'),
2546
+ onChange: (event) => onSearch(event.target.value),
2547
+ }),
2548
+ ) : null,
2549
+ selected ? h(
2550
+ 'div',
2551
+ { className: 'rb-current' },
2552
+ h(Avatar, { size: 'big', name: botName(selected, t) }),
2553
+ h('div', { className: 'rb-name' }, botName(selected, t)),
2554
+ h('div', { className: 'rb-label' }, attentionText(selected, t) ? `${botJob(selected, t)} · ${attentionText(selected, t)}` : botJob(selected, t)),
2555
+ ) : h(
2556
+ 'div',
2557
+ { className: 'rb-current' },
2558
+ h('div', { className: 'rb-name' }, t('empty.heading')),
2559
+ h('div', { className: 'rb-label' }, t('empty.body')),
2560
+ ),
2561
+ h(
2562
+ 'div',
2563
+ { className: 'rb-chats' },
2564
+ rows.length ? rows.map((bot) => {
2565
+ const name = botName(bot, t)
2566
+ const snippet = botSnippet(bot, t)
2567
+ const attention = attentionText(bot, t)
2568
+ return h(
2569
+ 'button',
2570
+ {
2571
+ type: 'button',
2572
+ key: bot.id,
2573
+ className: 'rb-row',
2574
+ onClick: () => onSelect(bot.id),
2575
+ 'aria-label': attention ? `${name}. ${snippet}. ${attention}` : `${name}. ${snippet}`,
2576
+ },
2577
+ h(Avatar, { size: 'mid', name }),
2578
+ h(
2579
+ 'div',
2580
+ { style: { minWidth: 0 } },
2581
+ h(
2582
+ 'div',
2583
+ { className: 'rb-nm' },
2584
+ name,
2585
+ bot.attention ? h('span', { className: `rb-dot rb-${bot.attention}`, title: attention }) : null,
2586
+ ),
2587
+ h('div', { className: 'rb-sn' }, snippet),
2588
+ ),
2589
+ h('div', { className: 'rb-tm' }, botTime(bot, t)),
2590
+ )
2591
+ }) : state.bots.length === 0
2592
+ ? h(
2593
+ 'div',
2594
+ { className: 'rb-firstrun' },
2595
+ h('button', { type: 'button', className: 'rb-btn rb-primary', onClick: onNew }, t('newBot.create')),
2596
+ )
2597
+ : state.search.trim()
2598
+ ? h('div', { className: 'rb-empty-list' }, t('list.empty'))
2599
+ : null,
2600
+ ),
2601
+ h(
2602
+ 'div',
2603
+ { className: 'rb-foot' },
2604
+ h(Avatar, { size: 'sm', name: userName, text: t('sample.user.initials') }),
2605
+ h(
2606
+ 'div',
2607
+ { className: 'rb-who' },
2608
+ userName,
2609
+ h(
2610
+ 'small',
2611
+ null,
2612
+ h('button', {
2613
+ type: 'button',
2614
+ className: low ? 'rb-textbtn rb-textbtn-low' : 'rb-textbtn',
2615
+ onClick: onSetup,
2616
+ title: t('setup.title'),
2617
+ },
2618
+ low ? h('span', { className: 'rb-dot rb-needs', 'aria-hidden': 'true' }) : null,
2619
+ connected ? t('sample.user.foot', { balance }) : t('setup.notConnected'),
2620
+ low ? h('span', { className: 'rb-sr' }, t('cost.lowShort')) : null),
2621
+ ),
2622
+ ),
2623
+ h('button', { type: 'button', className: 'rb-icon', title: t('list.settings'), 'aria-label': t('list.settings'), onClick: onSettings }, h(GearIcon)),
2624
+ ),
2625
+ )
2626
+ }
2627
+
2628
+ function ApprovalCard({ t, approval, onDecide, onContinue }) {
2629
+ const pending = approval.state === 'pending'
2630
+ const expired = approval.state === 'expired'
2631
+ const real = approval.real === true
2632
+ const executionFailed = approval.state === 'execution-failed'
2633
+ const waiting = approval.state === 'approved-waiting'
2634
+ const title = approval.title || fieldText(approval, t, 'titleKey')
2635
+ const meta = approval.meta || fieldText(approval, t, 'metaKey')
2636
+ const origin = approval.origin === 'background'
2637
+ ? t('approval.originBackground')
2638
+ : approval.origin === 'chat'
2639
+ ? t('approval.originChat')
2640
+ : ''
2641
+ const target = approval.targetKey ? t(approval.targetKey) : approval.target || ''
2642
+ const risks = Array.isArray(approval.risk)
2643
+ ? approval.risk
2644
+ .map((risk) => risk === 'outside'
2645
+ ? t('approval.riskOutside')
2646
+ : risk === 'irreversible'
2647
+ ? t('approval.riskIrreversible')
2648
+ : risk === 'cost' ? t('approval.riskCost') : null)
2649
+ .filter(Boolean)
2650
+ : []
2651
+ const riskLine = risks.length ? risks.join(' · ') : t('approval.warning')
2652
+ let side = t('approval.waits')
2653
+ if (pending && Number.isFinite(approval.expiresMin)) side = t('approval.expires', { n: approval.expiresMin })
2654
+ if (approval.state === 'allowed') side = t(real ? 'approval.allowedSide' : 'approval.snippetAllowed')
2655
+ if (approval.state === 'denied') side = t(real ? 'approval.deniedSide' : 'approval.snippetDenied')
2656
+ if (waiting) side = t('approval.waitingSide')
2657
+ if (executionFailed) side = t('approval.failedSide')
2658
+ if (expired) side = t('approval.expired')
2659
+ let resultText = t(approval.state === 'allowed' ? 'approval.allowedLocal' : 'approval.deniedLocal')
2660
+ if (real && approval.state === 'allowed') resultText = t('approval.allowedReal')
2661
+ if (real && approval.state === 'denied') resultText = t('approval.deniedReal')
2662
+ if (real && waiting) resultText = t('approval.executionPending')
2663
+ if (real && executionFailed) {
2664
+ resultText = t(approval.execution?.code === 'E_APPROVAL_UNSUPPORTED'
2665
+ ? 'approval.executionRefused'
2666
+ : 'approval.executionFailed')
2667
+ }
2668
+ return h(
2669
+ 'div',
2670
+ { className: expired ? 'rb-card rb-card-expired' : 'rb-card', 'data-state': approval.state, role: 'group', 'aria-label': title },
2671
+ h(
2672
+ 'div',
2673
+ { className: 'rb-card-top' },
2674
+ h('span', { className: 'rb-card-title' }, h('span', { className: 'rb-warn', 'aria-hidden': 'true' }, '⚠'), title),
2675
+ h('span', { className: 'rb-m' }, side),
2676
+ ),
2677
+ origin || target ? h(
2678
+ 'div',
2679
+ { className: 'rb-card-fields' },
2680
+ origin ? h('span', { className: 'rb-chip' }, origin) : null,
2681
+ target ? h('span', { className: 'rb-chip rb-chip-target' }, target) : null,
2682
+ ) : null,
2683
+ pending ? h('div', { className: 'rb-warnline' }, riskLine) : expired ? null : h('div', { className: 'rb-result' }, resultText),
2684
+ h('div', { className: 'rb-meta' }, meta),
2685
+ pending ? h(
2686
+ 'div',
2687
+ { className: 'rb-actions' },
2688
+ h('button', { type: 'button', className: 'rb-btn rb-ghost', onClick: () => onDecide(approval.id, 'denied') }, t('approval.deny')),
2689
+ h('button', { type: 'button', className: 'rb-btn rb-primary', onClick: () => onDecide(approval.id, 'allowed') }, t('approval.allowOnce')),
2690
+ ) : real && !expired ? h(
2691
+ 'div',
2692
+ { className: 'rb-actions' },
2693
+ h('button', { type: 'button', className: 'rb-btn rb-primary', onClick: () => onContinue(approval.id) }, t('approval.continue')),
2694
+ ) : null,
2695
+ )
2696
+ }
2697
+
2698
+ function Notice({ t, flash, computer }) {
2699
+ if (flash) {
2700
+ return h(
2701
+ 'div',
2702
+ { className: 'rb-notice', role: 'status', 'data-computer': computer },
2703
+ h('span', { className: 'rb-dot rb-needs', 'aria-hidden': 'true' }),
2704
+ flash,
2705
+ )
2706
+ }
2707
+ if (!computer || computer === 'live') return null
2708
+ const sleeping = computer === 'sleeping'
2709
+ const unreachable = computer === 'unreachable'
2710
+ return h(
2711
+ 'div',
2712
+ {
2713
+ className: unreachable ? 'rb-notice rb-error' : sleeping ? 'rb-notice rb-quiet' : 'rb-notice',
2714
+ role: 'status',
2715
+ 'data-computer': computer,
2716
+ },
2717
+ h('span', { className: `rb-dot${unreachable ? ' rb-danger' : sleeping ? '' : ' rb-needs'}`, 'aria-hidden': 'true' }),
2718
+ t(sleeping ? 'notice.sleeping' : unreachable ? 'computer.unreachable' : 'notice.reconnecting'),
2719
+ )
2720
+ }
2721
+
2722
+ function Conversation({ t, state, bot, composerRef, onComposer, onSend, onDecide, onContinue, onView, onAttach, showListButton, showDetailButton, onToggleList, onToggleDetail }) {
2723
+ const name = botName(bot, t)
2724
+ const job = botJob(bot, t)
2725
+ const threadRef = useRef(null)
2726
+ useEffect(() => {
2727
+ const thread = threadRef.current
2728
+ if (thread) thread.scrollTop = thread.scrollHeight
2729
+ }, [bot.id, bot.messages.length, bot.session?.lastSeq])
2730
+ return h(
2731
+ 'main',
2732
+ { className: 'rb-main', 'data-screen': 'chat' },
2733
+ showListButton || showDetailButton ? h(
2734
+ 'div',
2735
+ { className: 'rb-mini' },
2736
+ showListButton ? h('button', { type: 'button', className: 'rb-btn', 'aria-pressed': state.forceList ? 'true' : 'false', onClick: onToggleList }, t('panel.label')) : null,
2737
+ showDetailButton ? h('button', { type: 'button', className: 'rb-btn', 'aria-pressed': state.forceDetail ? 'true' : 'false', onClick: onToggleDetail }, name) : null,
2738
+ ) : null,
2739
+ h(
2740
+ 'div',
2741
+ { className: 'rb-thread', ref: threadRef },
2742
+ bot.messages.length ? bot.messages.map((entry) => {
2743
+ if (entry.kind === 'working') return h('div', { key: entry.id, className: 'rb-working-row', role: 'status' }, h('span', { className: 'rb-dot rb-working', 'aria-hidden': 'true' }), t('chat.working'))
2744
+ if (entry.kind === 'error') {
2745
+ return h(
2746
+ 'div',
2747
+ { key: entry.id, className: 'rb-error-row', role: 'alert' },
2748
+ h('div', { className: 'rb-error-code' }, entry.code || t('chat.errorTitle')),
2749
+ h('div', { className: 'rb-error-text' }, entry.text),
2750
+ )
2751
+ }
2752
+ if (entry.kind === 'day') return h('div', { key: entry.id, className: 'rb-day' }, textOf(entry, t))
2753
+ if (entry.kind === 'user') {
2754
+ return h(
2755
+ 'div',
2756
+ { key: entry.id, className: 'rb-msg rb-user' },
2757
+ h(
2758
+ 'div',
2759
+ { className: 'rb-bubble' },
2760
+ entry.origin === 'routine' ? h('div', { className: 'rb-chip' }, t('routine.origin')) : null,
2761
+ textOf(entry, t),
2762
+ ),
2763
+ )
2764
+ }
2765
+ if (entry.kind === 'computer') {
2766
+ return h(
2767
+ 'div',
2768
+ { key: entry.id, className: 'rb-computer-act' },
2769
+ h('div', { className: 'rb-thumb', 'aria-hidden': 'true' }),
2770
+ h('div', null, h('div', { className: 'rb-t' }, t(entry.titleKey)), h('div', { className: 'rb-s' }, t(entry.subKey))),
2771
+ h('button', { type: 'button', className: 'rb-btn rb-ghost', onClick: onView }, t('computer.view')),
2772
+ )
2773
+ }
2774
+ if (entry.kind === 'approval') {
2775
+ const approval = bot.approvals[entry.approvalId]
2776
+ if (!approval) return null
2777
+ return h(ApprovalCard, { key: entry.id, t, approval, onDecide, onContinue })
2778
+ }
2779
+ return h(
2780
+ 'div',
2781
+ { key: entry.id, className: 'rb-msg' },
2782
+ h(Avatar, { size: 'sm', name, className: 'rb-msg-avatar' }),
2783
+ h(
2784
+ 'div',
2785
+ { className: 'rb-body' },
2786
+ h('div', { className: 'rb-who-line' }, h('b', null, name), h('span', null, job)),
2787
+ h(RichText, { text: textOf(entry, t) }),
2788
+ ),
2789
+ )
2790
+ }) : h(
2791
+ 'div',
2792
+ { className: 'rb-thread-welcome' },
2793
+ h(Avatar, { size: 'big', name }),
2794
+ h('div', { className: 'rb-thread-welcome-title' }, name),
2795
+ h('div', { className: 'rb-thread-welcome-job' }, job),
2796
+ h('p', { className: 'rb-thread-empty' }, t(bot.source === 'real' ? 'empty.threadReal' : 'empty.thread')),
2797
+ ),
2798
+ ),
2799
+ h(Notice, { t, flash: state.flash, computer: state.computer }),
2800
+ h(
2801
+ 'div',
2802
+ { className: 'rb-composer' },
2803
+ h('button', { type: 'button', className: 'rb-icon', title: t('composer.attach'), 'aria-label': t('composer.attach'), onClick: onAttach }, '+'),
2804
+ h('input', {
2805
+ ref: composerRef,
2806
+ value: state.composer,
2807
+ disabled: !!bot.working,
2808
+ placeholder: t('composer.placeholder', { name }),
2809
+ 'aria-label': t('composer.placeholder', { name }),
2810
+ onChange: (event) => onComposer(event.target.value),
2811
+ onKeyDown: (event) => {
2812
+ if (event.key === 'Enter' && !event.shiftKey) {
2813
+ event.preventDefault()
2814
+ onSend()
2815
+ }
2816
+ },
2817
+ }),
2818
+ h('button', { type: 'button', className: 'rb-send', disabled: !!bot.working, title: t('composer.send'), 'aria-label': t('composer.send'), onClick: onSend }, '↑'),
2819
+ ),
2820
+ )
2821
+ }
2822
+
2823
+ function EmptyBlock({ name, title, hint }) {
2824
+ return h(
2825
+ 'div',
2826
+ { className: 'rb-empty', 'data-empty': name },
2827
+ h('div', { className: 'rb-empty-title' }, title),
2828
+ h('div', { className: 'rb-empty-hint' }, hint),
2829
+ )
2830
+ }
2831
+
2832
+ function Details({ t, catalog, bot, tab, onTab, computer, machine, configured, overview, usageError, usagePreview, low, idle, onToggleRoutine, onCreateRoutine, onRemoveRoutine, onComputer, onStop }) {
2833
+ const name = botName(bot, t)
2834
+ const job = botJob(bot, t)
2835
+ const [routineOpen, setRoutineOpen] = useState(false)
2836
+ const [routineTitle, setRoutineTitle] = useState('')
2837
+ const [routinePrompt, setRoutinePrompt] = useState('')
2838
+ const [routineMinutes, setRoutineMinutes] = useState('15')
2839
+ const [routineBusy, setRoutineBusy] = useState(false)
2840
+ const [routineError, setRoutineError] = useState('')
2841
+ const canEditRoutines = bot.source === 'real'
2842
+ const submitRoutine = async () => {
2843
+ const title = routineTitle.trim()
2844
+ const prompt = routinePrompt.trim()
2845
+ const everyMinutes = Number(routineMinutes)
2846
+ if (!title || !prompt || routineBusy) return
2847
+ setRoutineBusy(true)
2848
+ setRoutineError('')
2849
+ try {
2850
+ await onCreateRoutine({ title, prompt, everyMinutes })
2851
+ setRoutineTitle('')
2852
+ setRoutinePrompt('')
2853
+ setRoutineMinutes('15')
2854
+ setRoutineOpen(false)
2855
+ } catch (error) {
2856
+ setRoutineError(t('routine.createFailed', { message: String(error?.message ?? error) }))
2857
+ } finally {
2858
+ setRoutineBusy(false)
2859
+ }
2860
+ }
2861
+ const count = (n) => (n ? h('span', { className: 'rb-count' }, String(n)) : null)
2862
+ const routinesPaused = bot.routines.length > 0 && bot.routines.every((routine) => !routine.on)
2863
+ const groups = [
2864
+ ['today', 'library.today'],
2865
+ ['week', 'library.week'],
2866
+ ['older', 'library.older'],
2867
+ ]
2868
+ const computerStatus = computer || (machine ? machineStatus(machine.status) : 'offline')
2869
+ const computerName = machine?.name ?? (computer ? t('sample.computerName') : '—')
2870
+ return h(
2871
+ 'aside',
2872
+ { className: 'rb-detail', 'aria-label': name },
2873
+ h(
2874
+ 'div',
2875
+ { className: 'rb-profile' },
2876
+ h(Avatar, { size: 'big', name }),
2877
+ h('div', { className: 'rb-name' }, name),
2878
+ h('div', { className: 'rb-sub' }, t('details.jobComputer', { job, computer: computerName })),
2879
+ ),
2880
+ h(
2881
+ 'div',
2882
+ { className: 'rb-tabs', role: 'tablist' },
2883
+ h('button', { type: 'button', className: tab === 'activity' ? 'rb-tab rb-active' : 'rb-tab', role: 'tab', 'aria-selected': tab === 'activity' ? 'true' : 'false', onClick: () => onTab('activity') }, t('details.activity')),
2884
+ h('button', { type: 'button', className: tab === 'library' ? 'rb-tab rb-active' : 'rb-tab', role: 'tab', 'aria-selected': tab === 'library' ? 'true' : 'false', onClick: () => onTab('library') }, t('details.library')),
2885
+ ),
2886
+ tab === 'activity' ? h(
2887
+ 'div',
2888
+ { className: 'rb-sections' },
2889
+ h(
2890
+ 'section',
2891
+ { className: 'rb-sec' },
2892
+ h('h3', null, t('details.recent'), count(bot.receipts.length)),
2893
+ bot.receipts.length ? bot.receipts.map((receipt, index) => h(
2894
+ 'div',
2895
+ { key: index, className: 'rb-act' },
2896
+ h('div', { className: 'rb-t' }, h('span', null, t(receipt.titleKey)), h('span', { className: 'rb-ok' }, t(receipt.stateKey))),
2897
+ h('div', { className: 'rb-s' }, t(receipt.metaKey)),
2898
+ )) : h(EmptyBlock, { name: 'recent', title: t('details.recentEmpty'), hint: t('details.recentEmptyHint') }),
2899
+ ),
2900
+ h(
2901
+ 'section',
2902
+ { className: 'rb-sec' },
2903
+ h(
2904
+ 'h3',
2905
+ null,
2906
+ t('details.upcoming'),
2907
+ h(
2908
+ 'span',
2909
+ { className: 'rb-routine-head' },
2910
+ count(bot.routines.length),
2911
+ canEditRoutines ? h('button', {
2912
+ type: 'button',
2913
+ className: 'rb-textbtn',
2914
+ onClick: () => {
2915
+ setRoutineOpen((open) => !open)
2916
+ setRoutineError('')
2917
+ },
2918
+ }, t('routine.add')) : null,
2919
+ ),
2920
+ ),
2921
+ routinesPaused ? h('div', { className: 'rb-paused', 'data-paused': 'true', role: 'status' }, t('routine.paused')) : null,
2922
+ bot.routines.length ? bot.routines.map((routine, index) => {
2923
+ const title = routine.titleKey ? t(routine.titleKey) : routine.title
2924
+ const schedule = routine.scheduleKey
2925
+ ? t(routine.scheduleKey)
2926
+ : intervalLabel(t, routine.everyMinutes)
2927
+ return h(
2928
+ 'div',
2929
+ { key: routine.id ?? title, className: 'rb-routine' },
2930
+ h('div', null, h('div', { className: 'rb-t' }, title), h('div', { className: 'rb-s' }, schedule)),
2931
+ h(
2932
+ 'div',
2933
+ { className: 'rb-routine-actions' },
2934
+ h(Toggle, {
2935
+ on: routine.on,
2936
+ label: `${title} ${routine.on ? t('routine.on') : t('routine.off')}`,
2937
+ onClick: () => onToggleRoutine(index),
2938
+ }),
2939
+ canEditRoutines ? h('button', {
2940
+ type: 'button',
2941
+ className: 'rb-textbtn',
2942
+ onClick: () => onRemoveRoutine(index),
2943
+ }, t('routine.remove')) : null,
2944
+ ),
2945
+ )
2946
+ }) : h(EmptyBlock, { name: 'routines', title: t('routine.empty'), hint: t('routine.emptyHint') }),
2947
+ canEditRoutines && routineOpen ? h(
2948
+ 'div',
2949
+ { className: 'rb-stack rb-routine-form' },
2950
+ h(
2951
+ 'label',
2952
+ { className: 'rb-flabel' },
2953
+ t('routine.titleLabel'),
2954
+ h('input', {
2955
+ className: 'rb-field',
2956
+ value: routineTitle,
2957
+ maxLength: 80,
2958
+ onChange: (event) => setRoutineTitle(event.target.value),
2959
+ }),
2960
+ ),
2961
+ h(
2962
+ 'label',
2963
+ { className: 'rb-flabel' },
2964
+ t('routine.promptLabel'),
2965
+ h('textarea', {
2966
+ className: 'rb-field rb-area',
2967
+ rows: 3,
2968
+ value: routinePrompt,
2969
+ onChange: (event) => setRoutinePrompt(event.target.value),
2970
+ }),
2971
+ ),
2972
+ h(
2973
+ 'label',
2974
+ { className: 'rb-flabel' },
2975
+ t('routine.minutesLabel'),
2976
+ h('input', {
2977
+ className: 'rb-field',
2978
+ type: 'number',
2979
+ min: 1,
2980
+ max: 10080,
2981
+ value: routineMinutes,
2982
+ onChange: (event) => setRoutineMinutes(event.target.value),
2983
+ }),
2984
+ ),
2985
+ h('p', { className: 'rb-faint' }, t('routine.costHint')),
2986
+ routineError ? h('p', { className: 'rb-say', role: 'alert', style: { color: '#b45309' } }, routineError) : null,
2987
+ h(
2988
+ 'div',
2989
+ { className: 'rb-line' },
2990
+ h('button', {
2991
+ type: 'button',
2992
+ className: 'rb-btn rb-primary',
2993
+ disabled: routineBusy || !routineTitle.trim() || !routinePrompt.trim(),
2994
+ onClick: submitRoutine,
2995
+ }, t('routine.create')),
2996
+ h('button', {
2997
+ type: 'button',
2998
+ className: 'rb-btn rb-ghost',
2999
+ disabled: routineBusy,
3000
+ onClick: () => {
3001
+ setRoutineOpen(false)
3002
+ setRoutineError('')
3003
+ },
3004
+ }, t('routine.cancel')),
3005
+ ),
3006
+ ) : null,
3007
+ ),
3008
+ h(ComputerBlock, { t, status: computerStatus, name: computerName, configured, onComputer, onStop }),
3009
+ h(UsageBlock, { t, catalog, idle, low, overview, configured, error: usageError, preview: usagePreview }),
3010
+ ) : h(
3011
+ 'div',
3012
+ { className: 'rb-sections' },
3013
+ bot.library.length ? groups.map(([group, labelKey]) => {
3014
+ const items = bot.library.filter((item) => item.group === group)
3015
+ if (!items.length) return null
3016
+ return h(
3017
+ 'section',
3018
+ { key: group, className: 'rb-sec' },
3019
+ h('h3', null, t(labelKey), count(items.length)),
3020
+ items.map((item, index) => h(
3021
+ 'div',
3022
+ { key: `${group}-${index}`, className: 'rb-act' },
3023
+ h('div', { className: 'rb-t' }, h('span', null, t(item.titleKey)), h('span', { className: 'rb-ok' }, t(item.badgeKey))),
3024
+ h('div', { className: 'rb-s' }, t(item.metaKey)),
3025
+ )),
3026
+ )
3027
+ }) : h(EmptyBlock, { name: 'library', title: t('library.empty'), hint: t('library.emptyHint') }),
3028
+ ),
3029
+ )
3030
+ }
3031
+
3032
+ function ComputerBlock({ t, status, name, configured, onComputer, onStop }) {
3033
+ const [confirming, setConfirming] = useState(false)
3034
+ useEffect(() => {
3035
+ if (status !== 'live') setConfirming(false)
3036
+ }, [status])
3037
+ const canStop = status === 'live' && Boolean(onStop)
3038
+ const label = status === 'live' ? t('computer.live')
3039
+ : status === 'sleeping' ? t('computer.sleeping')
3040
+ : status === 'unreachable' ? t('computer.unreachable')
3041
+ : status === 'reconnecting' ? t('computer.reconnecting')
3042
+ : configured ? t('computer.noMachineShort')
3043
+ : t('setup.notConnected')
3044
+ const dot = status === 'live' ? 'rb-working'
3045
+ : status === 'unreachable' ? 'rb-danger'
3046
+ : status === 'sleeping' || status === 'offline' ? ''
3047
+ : 'rb-needs'
3048
+ return h(
3049
+ 'section',
3050
+ { className: 'rb-sec' },
3051
+ h('h3', null, t('details.computer')),
3052
+ h(
3053
+ 'div',
3054
+ { className: 'rb-computer', 'data-state': status },
3055
+ h(
3056
+ 'div',
3057
+ { className: 'rb-comp-row' },
3058
+ h(
3059
+ 'div',
3060
+ null,
3061
+ h('div', { className: 'rb-nm' }, name),
3062
+ h(
3063
+ 'div',
3064
+ { className: `rb-st rb-st-${status}` },
3065
+ h('span', { className: `rb-dot ${dot}`.trim(), 'aria-hidden': 'true' }),
3066
+ label,
3067
+ ),
3068
+ ),
3069
+ h('div', { className: 'rb-thumb', 'aria-hidden': 'true' }),
3070
+ ),
3071
+ h(
3072
+ 'div',
3073
+ { className: 'rb-comp-acts' },
3074
+ h('button', { type: 'button', className: 'rb-btn', onClick: onComputer }, t('computer.open')),
3075
+ h('button', { type: 'button', className: 'rb-btn', onClick: onComputer }, t('computer.takeOver')),
3076
+ canStop ? h('button', { type: 'button', className: 'rb-btn', onClick: () => setConfirming(true) }, t('computer.stop')) : null,
3077
+ ),
3078
+ canStop && confirming ? h(
3079
+ 'div',
3080
+ { className: 'rb-stop-confirm', role: 'status' },
3081
+ h('p', null, t('computer.stopConfirm')),
3082
+ h(
3083
+ 'div',
3084
+ { className: 'rb-line' },
3085
+ h('button', {
3086
+ type: 'button',
3087
+ className: 'rb-btn',
3088
+ onClick: () => {
3089
+ setConfirming(false)
3090
+ onStop()
3091
+ },
3092
+ }, t('computer.stopConfirmAction')),
3093
+ h('button', { type: 'button', className: 'rb-btn rb-ghost', onClick: () => setConfirming(false) }, t('computer.cancel')),
3094
+ ),
3095
+ ) : null,
3096
+ ),
3097
+ )
3098
+ }
3099
+
3100
+ function UsageBlock({ t, catalog, idle, low, overview, configured, error, preview }) {
3101
+ if (configured) {
3102
+ const balance = balanceText(overview?.balance)
3103
+ const hours = Number(overview?.usage?.vm_hours)
3104
+ return h(
3105
+ 'section',
3106
+ { className: 'rb-sec' },
3107
+ h('h3', null, t('details.usage')),
3108
+ h(
3109
+ 'div',
3110
+ { className: 'rb-usage', 'data-low': low ? 'true' : 'false' },
3111
+ h('span', { className: low ? 'rb-usage-low' : '' }, lineParts(lookup(catalog, 'usage.balanceLine'), { balance, hours: Number.isFinite(hours) ? hours.toFixed(1) : '—' }, new Set(['balance']))),
3112
+ h('span', null, t('usage.liveLine', { idle })),
3113
+ low ? h('span', { className: 'rb-low' }, t('cost.low')) : null,
3114
+ ),
3115
+ )
3116
+ }
3117
+ if (preview) {
3118
+ const balance = t('usage.sampleBalance')
3119
+ const hours = t('usage.sampleHours')
3120
+ const spend = t('usage.sampleSpend')
3121
+ return h(
3122
+ 'section',
3123
+ { className: 'rb-sec' },
3124
+ h('h3', null, t('details.usage')),
3125
+ h(
3126
+ 'div',
3127
+ { className: 'rb-usage', 'data-low': low ? 'true' : 'false' },
3128
+ h('span', { className: low ? 'rb-usage-low' : '' }, lineParts(lookup(catalog, 'usage.balanceLine'), { balance, hours }, new Set(['balance']))),
3129
+ h('span', null, lineParts(lookup(catalog, 'usage.weekLine'), { spend, idle }, new Set(['spend']))),
3130
+ low ? h('span', { className: 'rb-low' }, t('cost.low')) : null,
3131
+ ),
3132
+ )
3133
+ }
3134
+ return h(
3135
+ 'section',
3136
+ { className: 'rb-sec' },
3137
+ h('h3', null, t('details.usage')),
3138
+ h(
3139
+ 'div',
3140
+ { className: 'rb-usage', 'data-low': 'false' },
3141
+ h('span', null, error ? t('settings.usageFailed', { message: error }) : t('settings.usageConnect')),
3142
+ ),
3143
+ )
3144
+ }
3145
+
3146
+ function HostStatus({ t, host, onRetry }) {
3147
+ if (host.status === 'loaded') {
3148
+ if (host.dependency?.status === 'missing') {
3149
+ return h(
3150
+ 'span',
3151
+ { className: 'rb-status', 'data-host': 'missing' },
3152
+ h('span', { className: 'rb-dot rb-danger', 'aria-hidden': 'true' }),
3153
+ t('settings.hostDepMissing'),
3154
+ )
3155
+ }
3156
+ if (host.dependency?.status === 'incompatible') {
3157
+ return h(
3158
+ 'span',
3159
+ { className: 'rb-status', 'data-host': 'incompatible' },
3160
+ h('span', { className: 'rb-dot rb-danger', 'aria-hidden': 'true' }),
3161
+ t('settings.hostDepVersion', { version: host.dependency.version ?? '?', required: host.dependency.required ?? '' }),
3162
+ )
3163
+ }
3164
+ return h(
3165
+ 'span',
3166
+ { className: 'rb-status', 'data-host': 'loaded' },
3167
+ h('span', { className: 'rb-dot rb-working', 'aria-hidden': 'true' }),
3168
+ t(host.ready ? 'settings.hostReady' : 'settings.hostLoaded', { version: host.version }),
3169
+ )
3170
+ }
3171
+ if (host.status === 'down') {
3172
+ return h(
3173
+ 'span',
3174
+ { className: 'rb-status', 'data-host': 'down' },
3175
+ h('span', { className: 'rb-dot rb-danger', 'aria-hidden': 'true' }),
3176
+ t('error.hostDown'),
3177
+ h('button', { type: 'button', className: 'rb-btn rb-ghost rb-retry', onClick: onRetry }, t('settings.retry')),
3178
+ )
3179
+ }
3180
+ return h(
3181
+ 'span',
3182
+ { className: 'rb-status', 'data-host': 'checking' },
3183
+ h('span', { className: 'rb-dot', 'aria-hidden': 'true' }),
3184
+ t('settings.hostChecking'),
3185
+ )
3186
+ }
3187
+
3188
+ function renderCenter(ctx) {
3189
+ const { state, t, selected, width } = ctx
3190
+ if (state.screen === 'newbot') return h(NewBotScreen, { t, onCancel: () => ctx.onScreen('chat'), onCreate: ctx.onCreate })
3191
+ if (state.screen === 'setup') {
3192
+ return h(SetupScreen, {
3193
+ t,
3194
+ step: state.setupStep,
3195
+ flash: state.flash,
3196
+ host: ctx.host,
3197
+ onRetryHost: ctx.onRetryHost,
3198
+ onStep: ctx.onSetupStep,
3199
+ onClose: () => ctx.onScreen('chat'),
3200
+ onCreate: ctx.onCreate,
3201
+ onFlash: ctx.onFlash,
3202
+ })
3203
+ }
3204
+ if (state.screen === 'settings') {
3205
+ return h(SettingsScreen, {
3206
+ t,
3207
+ lang: ctx.lang,
3208
+ state,
3209
+ host: ctx.host,
3210
+ onRetryHost: ctx.onRetryHost,
3211
+ onTab: ctx.onSettingsTab,
3212
+ onChange: ctx.onSettings,
3213
+ onClose: () => ctx.onScreen('chat'),
3214
+ onSetup: () => {
3215
+ ctx.onSetupStep(0)
3216
+ ctx.onScreen('setup')
3217
+ },
3218
+ })
3219
+ }
3220
+ if (!selected) {
3221
+ return h(
3222
+ 'main',
3223
+ { className: 'rb-main', 'data-screen': 'chat' },
3224
+ h('div', { className: 'rb-center-empty' }, h('h2', null, t('empty.heading')), h('p', null, t('empty.body')), h('button', { type: 'button', className: 'rb-btn rb-primary', onClick: () => ctx.onScreen('newbot') }, t('newBot.create'))),
3225
+ )
3226
+ }
3227
+ return h(Conversation, {
3228
+ t,
3229
+ state,
3230
+ bot: selected,
3231
+ composerRef: ctx.composerRef,
3232
+ onComposer: ctx.onComposer,
3233
+ onSend: ctx.onSend,
3234
+ onDecide: ctx.onDecide,
3235
+ onContinue: ctx.onContinue,
3236
+ onView: ctx.onView,
3237
+ onAttach: ctx.onAttach,
3238
+ showListButton: width < 900,
3239
+ showDetailButton: width < 1120,
3240
+ onToggleList: ctx.onToggleList,
3241
+ onToggleDetail: ctx.onToggleDetail,
3242
+ })
3243
+ }
3244
+
3245
+ function NewBotScreen({ t, onCancel, onCreate }) {
3246
+ const [name, setName] = useState(() => t('newBot.defaultName'))
3247
+ const [job, setJob] = useState(() => t('newBot.defaultJob'))
3248
+ const [instructions, setInstructions] = useState('')
3249
+ const [busy, setBusy] = useState(false)
3250
+ const [error, setError] = useState('')
3251
+ const submit = async () => {
3252
+ if (!name.trim() || busy) return
3253
+ setBusy(true)
3254
+ setError('')
3255
+ try {
3256
+ await onCreate({ name, job, instructions })
3257
+ } catch (failure) {
3258
+ setError(t('error.botCreate', { message: String(failure?.message ?? failure) }))
3259
+ } finally {
3260
+ setBusy(false)
3261
+ }
3262
+ }
3263
+ return h(
3264
+ 'main',
3265
+ { className: 'rb-page', 'data-screen': 'newbot' },
3266
+ h(
3267
+ 'div',
3268
+ { className: 'rb-wizard-wrap' },
3269
+ h(
3270
+ 'div',
3271
+ { className: 'rb-wizard' },
3272
+ h('h1', null, t('newBot.title')),
3273
+ h('p', { className: 'rb-sub' }, t('newBot.sub')),
3274
+ h(BotFields, { t, name, job, instructions, onName: setName, onJob: setJob, onInstructions: setInstructions }),
3275
+ error ? h('p', { className: 'rb-say', role: 'alert', style: { color: '#b45309' } }, error) : null,
3276
+ h(
3277
+ 'div',
3278
+ { className: 'rb-form-foot' },
3279
+ h('button', { type: 'button', className: 'rb-btn rb-ghost', onClick: onCancel }, t('newBot.cancel')),
3280
+ h('button', {
3281
+ type: 'button',
3282
+ className: 'rb-btn rb-primary',
3283
+ disabled: busy || !name.trim(),
3284
+ onClick: submit,
3285
+ }, t('newBot.create')),
3286
+ ),
3287
+ ),
3288
+ ),
3289
+ )
3290
+ }
3291
+
3292
+ function SetupScreen({ t, step, flash, host, onRetryHost, onStep, onClose, onCreate, onFlash }) {
3293
+ const [name, setName] = useState(() => t('newBot.defaultName'))
3294
+ const [job, setJob] = useState(() => t('newBot.defaultJob'))
3295
+ const [instructions, setInstructions] = useState('')
3296
+ const tokenRef = useRef(null)
3297
+ const keyRef = useRef(null)
3298
+ const [tokenBusy, setTokenBusy] = useState(false)
3299
+ const [tokenError, setTokenError] = useState('')
3300
+ const [connection, setConnection] = useState(null)
3301
+ const [machine, setMachine] = useState(null)
3302
+ const [machineLoading, setMachineLoading] = useState(false)
3303
+ const [machineBusy, setMachineBusy] = useState(false)
3304
+ const [machineError, setMachineError] = useState('')
3305
+ const [creating, setCreating] = useState(false)
3306
+ const [computerName, setComputerName] = useState(DEFAULT_COMPUTER)
3307
+ const steps = [
3308
+ ['dependency', 'setup.steps.dependency'],
3309
+ ['rayrun', 'setup.steps.rayrun'],
3310
+ ['key', 'setup.steps.key'],
3311
+ ['bot', 'setup.steps.bot'],
3312
+ ]
3313
+ const dependency = host.status === 'loaded' ? host.dependency : null
3314
+ const dependencyLine = dependency?.status === 'ok'
3315
+ ? t('setup.dependencyOk', { version: dependency.version ?? '?' })
3316
+ : dependency?.status === 'missing'
3317
+ ? t('setup.dependencyMissing')
3318
+ : dependency?.status === 'incompatible'
3319
+ ? t('setup.dependencyIncompatible', { version: dependency.version ?? '?', required: dependency.required ?? '' })
3320
+ : t('setup.dependencyStatus')
3321
+ const configured = connection?.connection?.configured === true
3322
+ const canContinue = step === 0
3323
+ ? dependency?.status === 'ok'
3324
+ : step === 1
3325
+ ? configured
3326
+ : step === 2
3327
+ ? Boolean(machine)
3328
+ : step === 3
3329
+ ? Boolean(name.trim())
3330
+ : false
3331
+ useEffect(() => {
3332
+ if (step !== 2) return undefined
3333
+ let cancelled = false
3334
+ setMachineLoading(true)
3335
+ setMachineError('')
3336
+ void (async () => {
3337
+ try {
3338
+ const overview = await rayRpc('overview')
3339
+ if (cancelled) return
3340
+ setConnection(overview)
3341
+ const machines = Array.isArray(overview.machines) ? overview.machines : []
3342
+ setMachine(pickMachine(machines) || null)
3343
+ } catch (error) {
3344
+ if (!cancelled) setMachineError(t('setup.computerLoadFailed', { message: String(error?.message ?? error) }))
3345
+ } finally {
3346
+ if (!cancelled) setMachineLoading(false)
3347
+ }
3348
+ })()
3349
+ return () => {
3350
+ cancelled = true
3351
+ }
3352
+ }, [step])
3353
+ const back = () => {
3354
+ if (step === 0) onClose()
3355
+ else onStep(step - 1)
3356
+ }
3357
+ const skip = () => {
3358
+ if (step >= 3) onClose()
3359
+ else onStep(step + 1)
3360
+ }
3361
+ const next = async () => {
3362
+ if (!canContinue || creating) return
3363
+ if (step < 3) {
3364
+ onStep(step + 1)
3365
+ return
3366
+ }
3367
+ setCreating(true)
3368
+ try {
3369
+ await onCreate({ name, job, instructions })
3370
+ } catch (error) {
3371
+ onFlash(t('error.botCreate', { message: String(error?.message ?? error) }))
3372
+ } finally {
3373
+ setCreating(false)
3374
+ }
3375
+ }
3376
+ const createComputer = async () => {
3377
+ const name = computerName.trim()
3378
+ const key = keyRef.current?.value.trim() ?? ''
3379
+ setMachineBusy(true)
3380
+ setMachineError('')
3381
+ try {
3382
+ const overview = await rayRpc('overview')
3383
+ if (overview.connection?.configured !== true) {
3384
+ setConnection(overview)
3385
+ setMachineError(t('setup.computerNeedsRayrun'))
3386
+ return
3387
+ }
3388
+ const machines = Array.isArray(overview.machines) ? overview.machines : []
3389
+ const existing = machines.find((item) => item.name === name) || pickMachine(machines)
3390
+ if (existing) {
3391
+ setConnection(overview)
3392
+ setMachine(existing)
3393
+ onFlash(t('setup.computerExisting', { name: existing.name ?? existing.id ?? '—' }))
3394
+ return
3395
+ }
3396
+ const defaults = overview.defaults ?? {}
3397
+ const result = await rayRpc('machine.create', {
3398
+ name,
3399
+ agent: defaults.agent || 'deepseek-harness@1',
3400
+ cpu_cores: Number(defaults.cpu_cores) || 2,
3401
+ memory_mb: Math.max(2048, Number(defaults.memory_mb) || 2048),
3402
+ remote_desktop: true,
3403
+ ...(key ? { modelKey: key } : {}),
3404
+ })
3405
+ if (keyRef.current) keyRef.current.value = ''
3406
+ setConnection({ ...overview, machines: [result.machine, ...(Array.isArray(overview.machines) ? overview.machines : [])] })
3407
+ setMachine(result.machine)
3408
+ onFlash(t('setup.computerCreated', { name: result.machine?.name ?? name }))
3409
+ } catch (error) {
3410
+ const detail = String(error?.message ?? error)
3411
+ setMachineError(/token_required|unauthorized/i.test(detail)
3412
+ ? t('setup.computerNeedsRayrun')
3413
+ : t('setup.computerCreateFailed', { message: detail }))
3414
+ } finally {
3415
+ setMachineBusy(false)
3416
+ }
3417
+ }
3418
+ const connectToken = async () => {
3419
+ const token = tokenRef.current?.value.trim() ?? ''
3420
+ if (!token) {
3421
+ setTokenError(t('setup.tokenRequired'))
3422
+ return
3423
+ }
3424
+ setTokenBusy(true)
3425
+ setTokenError('')
3426
+ try {
3427
+ await rayRpc('connection.save', { token })
3428
+ const overview = await rayRpc('overview')
3429
+ if (tokenRef.current) tokenRef.current.value = ''
3430
+ setConnection(overview)
3431
+ } catch (error) {
3432
+ const detail = String(error?.message ?? error)
3433
+ setTokenError(/unauthorized/i.test(detail)
3434
+ ? t('setup.tokenRejected')
3435
+ : t('setup.connectFailed', { message: detail }))
3436
+ } finally {
3437
+ setTokenBusy(false)
3438
+ }
3439
+ }
3440
+ return h(
3441
+ 'main',
3442
+ { className: 'rb-page', 'data-screen': 'setup' },
3443
+ h(
3444
+ 'div',
3445
+ { className: 'rb-wizard-wrap' },
3446
+ h(
3447
+ 'div',
3448
+ { className: 'rb-wizard' },
3449
+ h('h1', null, t('setup.title')),
3450
+ h('p', { className: 'rb-sub' }, t('setup.sub')),
3451
+ h(
3452
+ 'div',
3453
+ { className: 'rb-steps' },
3454
+ steps.map(([id, labelKey], index) => h(
3455
+ 'div',
3456
+ { key: id, className: index < step ? 'rb-step rb-done' : index === step ? 'rb-step rb-current' : 'rb-step' },
3457
+ h('div', { className: 'rb-bar' }),
3458
+ h('div', { className: 'rb-lbl' }, t(labelKey)),
3459
+ )),
3460
+ ),
3461
+ step === 0 ? h(
3462
+ 'div',
3463
+ null,
3464
+ h('h2', null, t('setup.dependencyTitle')),
3465
+ h('p', { className: 'rb-say' }, t('setup.dependencyBody')),
3466
+ h('div', { className: 'rb-faint' }, dependencyLine),
3467
+ h(
3468
+ 'div',
3469
+ { className: 'rb-line', style: { marginTop: 10 } },
3470
+ h('span', { className: 'rb-faint' }, t('settings.host')),
3471
+ h(HostStatus, { t, host, onRetry: onRetryHost }),
3472
+ ),
3473
+ ) : null,
3474
+ step === 1 ? h(
3475
+ 'div',
3476
+ null,
3477
+ h('h2', null, t('setup.rayrunTitle')),
3478
+ h('p', { className: 'rb-say' }, t('setup.rayrunBody')),
3479
+ h(
3480
+ 'div',
3481
+ { className: 'rb-line' },
3482
+ h('button', {
3483
+ type: 'button',
3484
+ className: 'rb-btn rb-primary',
3485
+ onClick: () => {
3486
+ tokenRef.current?.focus()
3487
+ onFlash(t('setup.tokenHint'))
3488
+ },
3489
+ }, t('setup.useToken')),
3490
+ h('span', { className: 'rb-faint' }, configured ? t('setup.connectedShort') : t('setup.notConnected')),
3491
+ ),
3492
+ h(
3493
+ 'div',
3494
+ { className: 'rb-line', style: { marginTop: 9 } },
3495
+ h('input', {
3496
+ ref: tokenRef,
3497
+ className: 'rb-field',
3498
+ type: 'password',
3499
+ autoComplete: 'off',
3500
+ spellCheck: false,
3501
+ placeholder: t('setup.tokenPlaceholder'),
3502
+ 'aria-label': t('setup.tokenPlaceholder'),
3503
+ }),
3504
+ h('button', { type: 'button', className: 'rb-btn', disabled: tokenBusy, onClick: connectToken }, tokenBusy ? t('setup.connecting') : t('setup.connect')),
3505
+ ),
3506
+ tokenError ? h('p', { className: 'rb-say', role: 'alert', style: { color: '#b45309' } }, tokenError) : null,
3507
+ h(
3508
+ 'div',
3509
+ { className: 'rb-faint', style: { marginTop: 10 } },
3510
+ configured
3511
+ ? t('setup.connected', { balance: balanceText(connection.balance), machines: connection.machines.length })
3512
+ : t('setup.accountLine'),
3513
+ ),
3514
+ ) : null,
3515
+ step === 2 ? h(
3516
+ 'div',
3517
+ null,
3518
+ h('h2', null, t('setup.computerTitle')),
3519
+ h('p', { className: 'rb-say' }, t('setup.computerBody')),
3520
+ machineLoading ? h('p', { className: 'rb-faint' }, t('setup.computerChecking')) : null,
3521
+ !machineLoading && machine ? h(
3522
+ 'div',
3523
+ null,
3524
+ h('p', { className: 'rb-say' }, t('setup.computerExisting', { name: machine.name ?? machine.id ?? '—' })),
3525
+ h('p', { className: 'rb-faint' }, t('setup.computerExistingHint')),
3526
+ ) : null,
3527
+ !machineLoading && !machine && !configured ? h('p', { className: 'rb-say', role: 'status' }, t('setup.computerNeedsRayrun')) : null,
3528
+ !machineLoading && !machine && configured ? h(
3529
+ 'div',
3530
+ null,
3531
+ h(
3532
+ 'div',
3533
+ { className: 'rb-line' },
3534
+ h('input', {
3535
+ className: 'rb-field',
3536
+ value: computerName,
3537
+ maxLength: 64,
3538
+ placeholder: t('setup.computerName'),
3539
+ 'aria-label': t('setup.computerName'),
3540
+ onChange: (event) => setComputerName(event.target.value),
3541
+ }),
3542
+ ),
3543
+ h(
3544
+ 'div',
3545
+ { className: 'rb-line', style: { marginTop: 9 } },
3546
+ h('input', {
3547
+ ref: keyRef,
3548
+ className: 'rb-field',
3549
+ type: 'password',
3550
+ autoComplete: 'off',
3551
+ spellCheck: false,
3552
+ placeholder: t('setup.computerKeyPlaceholder'),
3553
+ 'aria-label': t('setup.computerKeyPlaceholder'),
3554
+ }),
3555
+ ),
3556
+ h('p', { className: 'rb-faint' }, t('setup.computerKeyHint')),
3557
+ h(
3558
+ 'div',
3559
+ { className: 'rb-line', style: { marginTop: 10 } },
3560
+ h('button', {
3561
+ type: 'button',
3562
+ className: 'rb-btn rb-primary',
3563
+ disabled: machineBusy || !computerName.trim(),
3564
+ onClick: createComputer,
3565
+ }, machineBusy ? t('setup.computerCreating') : t('setup.computerCreate')),
3566
+ ),
3567
+ h('p', { className: 'rb-faint' }, t('setup.computerCost')),
3568
+ ) : null,
3569
+ machineError ? h('p', { className: 'rb-say', role: 'alert', style: { color: '#b45309' } }, machineError) : null,
3570
+ ) : null,
3571
+ step === 3 ? h(
3572
+ 'div',
3573
+ null,
3574
+ h('h2', null, t('setup.botTitle')),
3575
+ h('p', { className: 'rb-say' }, t('setup.botBody')),
3576
+ h(BotFields, { t, name, job, instructions, onName: setName, onJob: setJob, onInstructions: setInstructions }),
3577
+ ) : null,
3578
+ flash ? h('p', { className: 'rb-say', role: 'status', style: { color: '#b45309' } }, flash) : null,
3579
+ h(
3580
+ 'div',
3581
+ { className: 'rb-form-foot' },
3582
+ h('button', { type: 'button', className: 'rb-btn rb-ghost', disabled: creating, onClick: back }, t('setup.back')),
3583
+ h(
3584
+ 'div',
3585
+ { className: 'rb-line' },
3586
+ h('button', { type: 'button', className: 'rb-btn rb-ghost', disabled: creating, onClick: skip }, t('setup.skip')),
3587
+ h('button', { type: 'button', className: 'rb-btn rb-primary', disabled: creating || !canContinue, onClick: next }, t('setup.continue')),
3588
+ ),
3589
+ ),
3590
+ ),
3591
+ ),
3592
+ )
3593
+ }
3594
+
3595
+ function SettingsScreen({ t, lang, state, host, onRetryHost, onTab, onChange, onClose, onSetup }) {
3596
+ const shownLang = state.settings.lang || lang || 'zh'
3597
+ const [usage, setUsage] = useState(null)
3598
+ const [usageLoading, setUsageLoading] = useState(true)
3599
+ const [usageError, setUsageError] = useState('')
3600
+ useEffect(() => {
3601
+ let cancelled = false
3602
+ void (async () => {
3603
+ try {
3604
+ const overview = await rayRpc('overview')
3605
+ if (!cancelled) setUsage(overview)
3606
+ } catch (error) {
3607
+ if (!cancelled) setUsageError(String(error?.message ?? error))
3608
+ } finally {
3609
+ if (!cancelled) setUsageLoading(false)
3610
+ }
3611
+ })()
3612
+ return () => {
3613
+ cancelled = true
3614
+ }
3615
+ }, [])
3616
+ const usageConfigured = usage?.connection?.configured === true
3617
+ const usageHours = Number(usage?.usage?.vm_hours)
3618
+ const usageLine = usageLoading
3619
+ ? t('settings.hostChecking')
3620
+ : usageError
3621
+ ? t('settings.usageFailed', { message: usageError })
3622
+ : usageConfigured
3623
+ ? t('settings.usageLine', {
3624
+ balance: balanceText(usage.balance),
3625
+ hours: Number.isFinite(usageHours) ? usageHours.toFixed(1) : '—',
3626
+ machines: Array.isArray(usage.machines) ? usage.machines.length : 0,
3627
+ })
3628
+ : t('settings.usageConnect')
3629
+ const scrollTo = (id) => {
3630
+ onTab(id)
3631
+ const reduce = typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches
3632
+ document.getElementById(`rb-settings-${id}`)?.scrollIntoView({ block: 'start', behavior: reduce ? 'auto' : 'smooth' })
3633
+ }
3634
+ return h(
3635
+ 'main',
3636
+ { className: 'rb-page', 'data-screen': 'settings' },
3637
+ h(
3638
+ 'div',
3639
+ { className: 'rb-page-inner' },
3640
+ h('button', {
3641
+ type: 'button',
3642
+ className: 'rb-btn rb-ghost rb-back',
3643
+ 'aria-label': t('setup.back'),
3644
+ onClick: onClose,
3645
+ }, `← ${t('setup.back')}`),
3646
+ h('h1', null, t('settings.title')),
3647
+ h('p', { className: 'rb-sub' }, t('settings.sub')),
3648
+ h(
3649
+ 'div',
3650
+ { className: 'rb-snav' },
3651
+ ['account', 'usage', 'notifications', 'appearance'].map((id) => h(
3652
+ 'button',
3653
+ {
3654
+ type: 'button',
3655
+ key: id,
3656
+ className: state.settingsTab === id ? 'rb-active' : '',
3657
+ onClick: () => scrollTo(id),
3658
+ },
3659
+ t(`settings.${id}`),
3660
+ )),
3661
+ ),
3662
+ h(
3663
+ 'div',
3664
+ { id: 'rb-settings-account', className: 'rb-srow' },
3665
+ h('div', { className: 'rb-l' }, t('settings.rayrunAccount'), h('small', null, t('settings.rayrunHint'))),
3666
+ h(
3667
+ 'button',
3668
+ { type: 'button', className: 'rb-status', onClick: onSetup },
3669
+ h('span', { className: 'rb-dot', 'aria-hidden': 'true' }),
3670
+ t('settings.setup'),
3671
+ ),
3672
+ ),
3673
+ h(
3674
+ 'div',
3675
+ { className: 'rb-srow' },
3676
+ h('div', { className: 'rb-l' }, t('settings.host'), h('small', null, t('settings.hostHint'))),
3677
+ h(HostStatus, { t, host, onRetry: onRetryHost }),
3678
+ ),
3679
+ h(
3680
+ 'div',
3681
+ { className: 'rb-srow' },
3682
+ h('div', { className: 'rb-l' }, t('settings.plugin'), h('small', null, t('settings.pluginHint'))),
3683
+ h(
3684
+ 'span',
3685
+ { className: 'rb-status' },
3686
+ h('span', {
3687
+ className: host.status === 'loaded' && (host.dependency?.status === 'missing' || host.dependency?.status === 'incompatible') ? 'rb-dot rb-danger' : 'rb-dot rb-working',
3688
+ 'aria-hidden': 'true',
3689
+ }),
3690
+ t(
3691
+ host.status !== 'loaded'
3692
+ ? 'settings.pluginUnknown'
3693
+ : host.dependency?.status === 'missing'
3694
+ ? 'settings.pluginMissing'
3695
+ : host.dependency?.status === 'incompatible'
3696
+ ? 'settings.pluginIncompatible'
3697
+ : 'settings.pluginOk',
3698
+ ),
3699
+ ),
3700
+ ),
3701
+ h(
3702
+ 'div',
3703
+ { id: 'rb-settings-usage', className: 'rb-srow' },
3704
+ h('div', { className: 'rb-l' }, t('settings.usage'), h('small', null, t('settings.usageHint'))),
3705
+ h(
3706
+ 'span',
3707
+ { className: 'rb-status' },
3708
+ h('span', {
3709
+ className: usageError ? 'rb-dot rb-danger' : usageLoading || !usageConfigured ? 'rb-dot' : 'rb-dot rb-working',
3710
+ 'aria-hidden': 'true',
3711
+ }),
3712
+ usageLine,
3713
+ ),
3714
+ ),
3715
+ h(
3716
+ 'div',
3717
+ { className: 'rb-srow' },
3718
+ h('div', { className: 'rb-l' }, t('settings.idle'), h('small', null, t('settings.idleHint'))),
3719
+ h(
3720
+ 'select',
3721
+ {
3722
+ value: state.settings.idle,
3723
+ 'aria-label': t('settings.idle'),
3724
+ onChange: (event) => onChange({ idle: event.target.value }),
3725
+ },
3726
+ h('option', { value: '15' }, t('settings.idle15')),
3727
+ h('option', { value: '30' }, t('settings.idle30')),
3728
+ h('option', { value: '0' }, t('settings.idleOff')),
3729
+ ),
3730
+ ),
3731
+ h(
3732
+ 'div',
3733
+ { className: 'rb-srow' },
3734
+ h('div', { className: 'rb-l' }, t('settings.lowBalance'), h('small', null, t('settings.lowBalanceHint'))),
3735
+ h('input', {
3736
+ value: state.settings.lowBalance,
3737
+ style: { width: 76 },
3738
+ inputMode: 'decimal',
3739
+ 'aria-label': t('settings.lowBalance'),
3740
+ onChange: (event) => onChange({ lowBalance: event.target.value.replace(/[^\d.]/g, '').slice(0, 8) }),
3741
+ }),
3742
+ ),
3743
+ h(
3744
+ 'div',
3745
+ { id: 'rb-settings-notifications', className: 'rb-srow' },
3746
+ h('div', { className: 'rb-l' }, t('settings.notify'), h('small', null, t('settings.notifyHint'))),
3747
+ h(Toggle, {
3748
+ on: state.settings.notifications,
3749
+ label: `${t('settings.notify')} ${state.settings.notifications ? t('routine.on') : t('routine.off')}`,
3750
+ onClick: () => onChange({ notifications: !state.settings.notifications }),
3751
+ }),
3752
+ ),
3753
+ h(
3754
+ 'div',
3755
+ { id: 'rb-settings-appearance', className: 'rb-srow' },
3756
+ h('div', { className: 'rb-l' }, t('settings.language'), h('small', null, t('settings.languageHint'))),
3757
+ h(
3758
+ 'select',
3759
+ {
3760
+ value: shownLang,
3761
+ 'aria-label': t('settings.language'),
3762
+ onChange: (event) => onChange({ lang: event.target.value }),
3763
+ },
3764
+ h('option', { value: 'zh' }, t('settings.langZh')),
3765
+ h('option', { value: 'en' }, t('settings.langEn')),
3766
+ ),
3767
+ ),
3768
+ ),
3769
+ )
3770
+ }
3771
+
3772
+ function PanelIcon({ size }) {
3773
+ const edge = typeof size === 'number' && size > 0 ? size : 20
3774
+ return h(
3775
+ 'svg',
3776
+ {
3777
+ width: edge,
3778
+ height: edge,
3779
+ viewBox: '0 0 24 24',
3780
+ fill: 'none',
3781
+ stroke: 'currentColor',
3782
+ strokeWidth: 1.7,
3783
+ strokeLinecap: 'round',
3784
+ strokeLinejoin: 'round',
3785
+ 'aria-hidden': 'true',
3786
+ },
3787
+ h('rect', { x: 3.2, y: 4.2, width: 17.6, height: 12.4, rx: 2 }),
3788
+ h('path', { d: 'M8 20.4h8M12 16.6v3.8' }),
3789
+ h('circle', { cx: 9, cy: 10.4, r: 1.1 }),
3790
+ h('circle', { cx: 15, cy: 10.4, r: 1.1 }),
3791
+ )
3792
+ }
3793
+
3794
+ return {
3795
+ inject: ['slots', 'locale'],
3796
+ apply(ctx) {
3797
+ ctx.slots.inject('sidebar.panellist', () =>
3798
+ ctx.slots.register(
3799
+ {
3800
+ name: 'sidebar.panellist',
3801
+ id: PANEL_ID,
3802
+ order: 30,
3803
+ label: () => {
3804
+ try {
3805
+ const id = String((ctx.get?.('locale') ?? ctx.locale)?.getLocale?.()?.active ?? '')
3806
+ return id.toLowerCase().startsWith('zh') ? ZH.panel.label : EN.panel.label
3807
+ } catch {
3808
+ return 'Bots'
3809
+ }
3810
+ },
3811
+ },
3812
+ PanelIcon,
3813
+ ),
3814
+ )
3815
+ ctx.slots.inject('main', () => {
3816
+ const dispose = ctx.slots.register(
3817
+ {
3818
+ name: 'main',
3819
+ key: PANEL_ID,
3820
+ },
3821
+ () => h(BotsApp, { ctx }),
3822
+ )
3823
+ // Bots is the product surface: activate it on entry when DSH exposes
3824
+ // the layout service. Without that service, stay on the DSH page.
3825
+ ctx.inject?.(['layout'], (child) => {
3826
+ try {
3827
+ child.layout.selectPanel(PANEL_ID)
3828
+ } catch (error) {
3829
+ ctx.logger?.warn?.(`dsh-rayrun-bots: could not activate Bots: ${String(error?.message ?? error)}`)
3830
+ }
3831
+ })
3832
+ return dispose
3833
+ })
3834
+ },
3835
+ }
3836
+ },
3837
+ })