@songsid/agend 2.4.0-beta.15 → 2.4.0-beta.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/dist/accounts-profiles.d.ts +1 -1
  2. package/dist/accounts-view.d.ts +3 -0
  3. package/dist/accounts-view.js.map +1 -1
  4. package/dist/auth-api.js +6 -0
  5. package/dist/auth-api.js.map +1 -1
  6. package/dist/backend/claude-code.d.ts +15 -1
  7. package/dist/backend/claude-code.js +64 -8
  8. package/dist/backend/claude-code.js.map +1 -1
  9. package/dist/backend/kiro.js +6 -1
  10. package/dist/backend/kiro.js.map +1 -1
  11. package/dist/backend/types.d.ts +8 -0
  12. package/dist/backend/types.js.map +1 -1
  13. package/dist/backend-command.d.ts +4 -2
  14. package/dist/backend-command.js +3 -0
  15. package/dist/backend-command.js.map +1 -1
  16. package/dist/browser-backend-signins.d.ts +1 -0
  17. package/dist/browser-backend-signins.js +3 -1
  18. package/dist/browser-backend-signins.js.map +1 -1
  19. package/dist/build-provenance.json +1 -1
  20. package/dist/classic-channel-manager.d.ts +1 -0
  21. package/dist/classic-channel-manager.js +4 -1
  22. package/dist/classic-channel-manager.js.map +1 -1
  23. package/dist/claude-credential-change.d.ts +22 -0
  24. package/dist/claude-credential-change.js +47 -0
  25. package/dist/claude-credential-change.js.map +1 -0
  26. package/dist/claude-credential-launch.d.ts +63 -0
  27. package/dist/claude-credential-launch.js +315 -0
  28. package/dist/claude-credential-launch.js.map +1 -0
  29. package/dist/claude-credential-runner.d.ts +1 -0
  30. package/dist/claude-credential-runner.js +56 -0
  31. package/dist/claude-credential-runner.js.map +1 -0
  32. package/dist/claude-credential-vault.d.ts +57 -0
  33. package/dist/claude-credential-vault.js +277 -0
  34. package/dist/claude-credential-vault.js.map +1 -0
  35. package/dist/claude-request-observation.d.ts +7 -0
  36. package/dist/claude-request-observation.js +26 -0
  37. package/dist/claude-request-observation.js.map +1 -0
  38. package/dist/claude-setup-token-transport.d.ts +9 -0
  39. package/dist/claude-setup-token-transport.js +82 -0
  40. package/dist/claude-setup-token-transport.js.map +1 -0
  41. package/dist/claude-setup-token.d.ts +51 -0
  42. package/dist/claude-setup-token.js +83 -0
  43. package/dist/claude-setup-token.js.map +1 -0
  44. package/dist/cli-audited.js +15 -12
  45. package/dist/cli-audited.js.map +1 -1
  46. package/dist/command-report.d.ts +11 -0
  47. package/dist/command-report.js +2 -0
  48. package/dist/command-report.js.map +1 -0
  49. package/dist/config-validator.js +9 -0
  50. package/dist/config-validator.js.map +1 -1
  51. package/dist/config.js +4 -2
  52. package/dist/config.js.map +1 -1
  53. package/dist/daemon.d.ts +5 -0
  54. package/dist/daemon.js +65 -3
  55. package/dist/daemon.js.map +1 -1
  56. package/dist/fleet-level-config.d.ts +1 -1
  57. package/dist/fleet-level-config.js +1 -0
  58. package/dist/fleet-level-config.js.map +1 -1
  59. package/dist/fleet-manager.d.ts +53 -2
  60. package/dist/fleet-manager.js +511 -22
  61. package/dist/fleet-manager.js.map +1 -1
  62. package/dist/general-knowledge/skills/web-appearance/SKILL.md +4 -1
  63. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +25 -6
  64. package/dist/host-monitoring-config.d.ts +15 -0
  65. package/dist/host-monitoring-config.js +36 -0
  66. package/dist/host-monitoring-config.js.map +1 -0
  67. package/dist/host-monitoring-history-files.d.ts +2 -0
  68. package/dist/host-monitoring-history-files.js +16 -0
  69. package/dist/host-monitoring-history-files.js.map +1 -0
  70. package/dist/host-monitoring-history-policy.d.ts +55 -0
  71. package/dist/host-monitoring-history-policy.js +93 -0
  72. package/dist/host-monitoring-history-policy.js.map +1 -0
  73. package/dist/host-monitoring-history-store.d.ts +52 -0
  74. package/dist/host-monitoring-history-store.js +176 -0
  75. package/dist/host-monitoring-history-store.js.map +1 -0
  76. package/dist/host-monitoring-history-worker.d.ts +1 -0
  77. package/dist/host-monitoring-history-worker.js +50 -0
  78. package/dist/host-monitoring-history-worker.js.map +1 -0
  79. package/dist/host-monitoring-history.d.ts +71 -0
  80. package/dist/host-monitoring-history.js +265 -0
  81. package/dist/host-monitoring-history.js.map +1 -0
  82. package/dist/host-monitoring-platform.d.ts +73 -0
  83. package/dist/host-monitoring-platform.js +273 -0
  84. package/dist/host-monitoring-platform.js.map +1 -0
  85. package/dist/host-monitoring-runtime.d.ts +34 -0
  86. package/dist/host-monitoring-runtime.js +80 -0
  87. package/dist/host-monitoring-runtime.js.map +1 -0
  88. package/dist/host-monitoring-settings-store.d.ts +5 -0
  89. package/dist/host-monitoring-settings-store.js +49 -0
  90. package/dist/host-monitoring-settings-store.js.map +1 -0
  91. package/dist/host-monitoring.d.ts +106 -0
  92. package/dist/host-monitoring.js +157 -0
  93. package/dist/host-monitoring.js.map +1 -0
  94. package/dist/hub/group-policy/resources.d.ts +1 -1
  95. package/dist/instance-config-impact.js +1 -1
  96. package/dist/instance-config-impact.js.map +1 -1
  97. package/dist/instructions.js +1 -0
  98. package/dist/instructions.js.map +1 -1
  99. package/dist/locale.d.ts +2 -0
  100. package/dist/locale.js +13 -1
  101. package/dist/locale.js.map +1 -1
  102. package/dist/office-share-page.js +1 -1
  103. package/dist/office-share-page.js.map +1 -1
  104. package/dist/profile-signins.d.ts +1 -0
  105. package/dist/profile-signins.js +3 -1
  106. package/dist/profile-signins.js.map +1 -1
  107. package/dist/public-web-gateway.js +6 -0
  108. package/dist/public-web-gateway.js.map +1 -1
  109. package/dist/public-web-link.d.ts +21 -2
  110. package/dist/public-web-link.js +22 -2
  111. package/dist/public-web-link.js.map +1 -1
  112. package/dist/runtime-cli-install.js +17 -16
  113. package/dist/runtime-cli-install.js.map +1 -1
  114. package/dist/settings-api.d.ts +15 -0
  115. package/dist/settings-api.js +154 -8
  116. package/dist/settings-api.js.map +1 -1
  117. package/dist/settings-baseline.d.ts +1 -0
  118. package/dist/settings-baseline.js +5 -4
  119. package/dist/settings-baseline.js.map +1 -1
  120. package/dist/settings-change.js +10 -0
  121. package/dist/settings-change.js.map +1 -1
  122. package/dist/settings-effect.d.ts +2 -0
  123. package/dist/settings-effect.js +15 -1
  124. package/dist/settings-effect.js.map +1 -1
  125. package/dist/topic-commands.d.ts +7 -1
  126. package/dist/topic-commands.js +98 -88
  127. package/dist/topic-commands.js.map +1 -1
  128. package/dist/transcript-monitor.d.ts +1 -0
  129. package/dist/transcript-monitor.js +18 -0
  130. package/dist/transcript-monitor.js.map +1 -1
  131. package/dist/types.d.ts +2 -0
  132. package/dist/ui/accounts-view.js +16 -8
  133. package/dist/ui/backend-signin.js +3 -1
  134. package/dist/ui/chat-commands.js +2 -0
  135. package/dist/ui/chat-popout-transport.js +49 -19
  136. package/dist/ui/chat-popout.js +15 -1
  137. package/dist/ui/chat-store.js +1 -1
  138. package/dist/ui/claude-credentials.js +123 -0
  139. package/dist/ui/claude-setup-token.js +36 -0
  140. package/dist/ui/contact-auth-client.js +7 -2
  141. package/dist/ui/contact-auth-strings.js +45 -14
  142. package/dist/ui/contact-authorizations.js +47 -26
  143. package/dist/ui/contact-needs.js +4 -4
  144. package/dist/ui/fleet-canvas.js +3 -2
  145. package/dist/ui/fleet-office-card.js +414 -41
  146. package/dist/ui/fleet-office-dialogue.js +3 -3
  147. package/dist/ui/fleet-office-pack.d.ts +67 -1
  148. package/dist/ui/fleet-office-pack.js +412 -18
  149. package/dist/ui/fleet-office-play.js +401 -3
  150. package/dist/ui/fleet-office-skin.js +133 -21
  151. package/dist/ui/fleet-office-store.js +41 -0
  152. package/dist/ui/fleet-office-zones.js +34 -9
  153. package/dist/ui/fleet-office.js +513 -62
  154. package/dist/ui/host-health-model.js +42 -0
  155. package/dist/ui/host-health.js +74 -0
  156. package/dist/ui/office-share-page.js +5 -1
  157. package/dist/ui/panel-chat.js +146 -46
  158. package/dist/ui/panel-fleet.js +24 -11
  159. package/dist/ui/panel-hub.js +5 -1
  160. package/dist/ui/panel-settings.js +5 -4
  161. package/dist/ui/preview-popout.js +134 -0
  162. package/dist/ui/reply-file-preview.js +1 -1
  163. package/dist/ui/search-dialog.js +8 -1
  164. package/dist/ui/settings-capabilities.js +2 -0
  165. package/dist/ui/settings-host-monitoring.js +69 -0
  166. package/dist/ui/settings-registry.js +4 -1
  167. package/dist/ui/settings-shared.js +3 -2
  168. package/dist/ui/shared/accounts.css +8 -4
  169. package/dist/ui/shared/agent-sheet.js +5 -2
  170. package/dist/ui/shared/app-route.js +1 -1
  171. package/dist/ui/shared/app.css +248 -27
  172. package/dist/ui/shared/app.js +8 -1
  173. package/dist/ui/shared/chat-strings.js +10 -4
  174. package/dist/ui/shared/chat-thread.js +42 -10
  175. package/dist/ui/shared/info-tip.js +64 -0
  176. package/dist/ui/shared/instance-nav.js +47 -5
  177. package/dist/ui/shared/jump-idle.js +36 -0
  178. package/dist/ui/shared/office-dialogue.css +12 -0
  179. package/dist/ui/shared/preview-panel.js +44 -18
  180. package/dist/ui/shared/preview-popout.css +11 -0
  181. package/dist/ui/shared/theme.js +15 -1
  182. package/dist/ui/shared/ui-menu.js +17 -11
  183. package/dist/ui/shared/usage-dialog.js +9 -34
  184. package/dist/ui/shared/view-strings.js +2 -0
  185. package/dist/usage/i18n-keys.d.ts +1 -1
  186. package/dist/usage/i18n-keys.js +1 -1
  187. package/dist/usage/i18n-keys.js.map +1 -1
  188. package/dist/usage/providers.d.ts +1 -0
  189. package/dist/usage/providers.js +14 -1
  190. package/dist/usage/providers.js.map +1 -1
  191. package/dist/usage/usage-api.js +5 -2
  192. package/dist/usage/usage-api.js.map +1 -1
  193. package/dist/web-api.d.ts +6 -1
  194. package/dist/web-api.js +83 -9
  195. package/dist/web-api.js.map +1 -1
  196. package/dist/web-chat-history.d.ts +7 -1
  197. package/dist/web-chat-history.js +19 -3
  198. package/dist/web-chat-history.js.map +1 -1
  199. package/dist/web-claude-credentials.d.ts +31 -0
  200. package/dist/web-claude-credentials.js +138 -0
  201. package/dist/web-claude-credentials.js.map +1 -0
  202. package/dist/web-commands.d.ts +5 -2
  203. package/dist/web-commands.js +4 -2
  204. package/dist/web-commands.js.map +1 -1
  205. package/dist/web-office-skins.d.ts +7 -2
  206. package/dist/web-office-skins.js +42 -16
  207. package/dist/web-office-skins.js.map +1 -1
  208. package/dist/web-session.d.ts +20 -1
  209. package/dist/web-session.js +27 -0
  210. package/dist/web-session.js.map +1 -1
  211. package/dist/web-shell-routes.d.ts +1 -1
  212. package/dist/web-shell-routes.js +1 -1
  213. package/dist/web-shell-routes.js.map +1 -1
  214. package/dist/web-terminal.d.ts +4 -0
  215. package/dist/web-terminal.js +16 -1
  216. package/dist/web-terminal.js.map +1 -1
  217. package/package.json +1 -1
@@ -0,0 +1,42 @@
1
+ // Presentation only: these helpers cannot sample, open history or turn monitoring on.
2
+ export const HOST_RANGES = ["1h", "24h", "7d", "30d"];
3
+ export const numberOrNull = (value, maximum = Number.MAX_SAFE_INTEGER) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= maximum ? value : null;
4
+ export function metricState(metric, interval, now = Date.now()) {
5
+ if (metric?.status !== "ok") return metric?.status === "stale" ? "stale" : "unavailable";
6
+ return numberOrNull(metric.sampledAt) === null || now - metric.sampledAt >= interval * 2 ? "stale" : "ok";
7
+ }
8
+ export function displayBytes(value) {
9
+ const n = numberOrNull(value);if (n === null) return null;
10
+ if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(1)} GiB`;
11
+ if (n >= 1024 ** 2) return `${(n / 1024 ** 2).toFixed(0)} MiB`;
12
+ return `${Math.round(n / 1024)} KiB`;
13
+ }
14
+ export function storageRows(snapshot) {
15
+ return (Array.isArray(snapshot?.disks?.value?.volumes) ? snapshot.disks.value.volumes : []).slice(0,8)
16
+ .filter(v => v && /^[a-f0-9]{16}$/.test(v.id) && Array.isArray(v.roles))
17
+ .sort((a,b) => (numberOrNull(a.availableBytes) ?? Infinity) - (numberOrNull(b.availableBytes) ?? Infinity));
18
+ }
19
+ export function historySeries(snapshot) {
20
+ return ["cpu.used", "memory.available", "memory.pressure", "swap.free", ...storageRows(snapshot).flatMap(v => [`disk.${v.id}.available`, `disk.${v.id}.used`])];
21
+ }
22
+ /** Null gaps break lines; even a damaged response cannot draw more than240 points. */
23
+ export function chartData(input) {
24
+ const buckets = Array.isArray(input) ? input.slice(0,240) : [];
25
+ const valid = b => b && numberOrNull(b.average) !== null && numberOrNull(b.min) !== null && numberOrNull(b.max) !== null && numberOrNull(b.count) > 0;
26
+ const values=buckets.filter(valid), min=values.length?Math.min(...values.map(b=>b.min)):null,max=values.length?Math.max(...values.map(b=>b.max)):null;
27
+ const ceiling=max===null?1:Math.max(1,max),segments=[];let points=[];
28
+ for(let i=0;i<buckets.length;i++) {
29
+ const b=buckets[i];if(!valid(b)){if(points.length)segments.push(points.join(' '));points=[];continue;}
30
+ points.push(`${(i*600/Math.max(1,buckets.length-1)).toFixed(2)},${(100-Math.min(100,b.average/ceiling*100)).toFixed(2)}`);
31
+ }
32
+ if(points.length)segments.push(points.join(' '));
33
+ const dots=segments.filter(s=>!s.includes(' ')).map(s=>{const [x,y]=s.split(',').map(Number);return{x,y};});
34
+ return {segments,dots,min,max,covered:values.length,total:buckets.length};
35
+ }
36
+
37
+ export function sampleCoverage(snapshot,now=Date.now()) {
38
+ const volumes=storageRows(snapshot),missingBacking=snapshot?.platform==='wsl'&&!volumes.some(v=>v.roles.includes('wsl-backing'));
39
+ const cpu=metricState(snapshot?.cpu,30000,now)==='ok'&&numberOrNull(snapshot?.cpu?.value?.usedPercent,100)!==null;
40
+ const memory=metricState(snapshot?.memory,30000,now)==='ok'&&(numberOrNull(snapshot?.memory?.value?.availableBytes)!==null||['normal','elevated','critical'].includes(snapshot?.memory?.value?.pressure));
41
+ return {covered:Number(cpu)+Number(memory)+(metricState(snapshot?.disks,60000,now)==='ok'?volumes.filter(v=>numberOrNull(v.availableBytes)!==null).length:0),total:2+volumes.length+Number(missingBacking)};
42
+ }
@@ -0,0 +1,74 @@
1
+ import {html,useEffect,useRef,useState} from '/assets/app-html.js';
2
+ import {register,t,lang} from '/assets/app-i18n.js';
3
+ import {PageHead} from '/assets/page-head.js';
4
+ import {Skeleton,ErrorState} from '/assets/ui-states.js';
5
+ import {Icon} from '/assets/ui-icons.js';
6
+ import {sectionPath} from '/assets/app-route.js';
7
+ import {HOST_RANGES,numberOrNull,metricState,displayBytes,storageRows,historySeries,chartData,sampleCoverage} from './host-health-model.js';
8
+
9
+ register('hostHealth',{
10
+ en:{title:'Host health',computer:'This computer',lead:'CPU, memory and storage from the latest recorded samples.',settings:'Monitoring settings',refresh:'Refresh',refreshing:'Refreshing…',unsupported:'Host monitoring is not available on this computer.',off:'Host monitoring is off',offHint:'Turn it on in Settings to collect samples and keep bounded local history.',admin:'Administrator sign-in required',adminHint:'Sign in as a Fleet administrator to see host metrics.',starting:'Waiting for the first samples',stopping:'Stopping monitoring',failedHint:'Monitoring could not complete. Check its settings and local storage permissions; history cleanup may still need attention.',failed:'Monitoring needs attention',unavailable:'Not available',stale:'Stale',lastLabel:'Last successful sample:',last:'Last successful sample: {0}',none:'No successful sample yet',wsl:'WSL 2',linux:'Linux',darwin:'macOS',wslNote:'CPU and memory describe WSL, not the physical Windows computer. The Windows backing drive is shown separately.',macNote:'APFS volumes may share free space. Do not add their free space together. Available memory is an estimate; pressure is shown separately.',linuxNote:'Local Linux filesystems and available memory. Unavailable fields are not treated as zero.',runtimeNote:'Paired Windows Runtimes are separate computers and are not included in these totals.',storage:'Storage',root:'Linux filesystem',state:'Fleet state',backing:'Windows backing drive',volume:'Local volume',drive:' ({0}:)',shared:'Shared APFS capacity',sharedHint:'Do not add free space across volumes.',free:'{0} available',used:'{0}% used',unknownDrive:'Windows drive not identified',chooseDrive:'Choose drive in Settings',unknownHint:'Linux free space alone does not show whether the Windows drive holding WSL has room.',cpu:'CPU',wslCpu:'WSL CPU',wslMemory:'WSL memory',cpuUsed:'{0}% used',cores:'{0} logical CPUs',loadLabel:'Load average:',load:'Load average: {0}',memory:'Memory',available:'{0} available of {1}',pressureLabel:'Memory pressure:',pressure:'Memory pressure: {0}',normal:'Normal',elevated:'Elevated',critical:'Critical',unknown:'Unknown',swap:'Swap free: {0}',history:'History',range:'History range',coverageSummary:'{0} of {1} readings have fresh data',collecting:'Collecting history…',noHistory:'No recorded samples in this range',historyUnavailable:'Recorded history is temporarily unavailable. Refresh to try again.',historyLoading:'Loading recorded history…',historyWaiting:'History has not started recording yet.',historyPaused:'History recording is paused.',historyFailed:'History could not be recorded. Current samples remain available.',lowSpace:'Low storage: keeping current samples in memory only.',recovering:'Waiting for both storage volumes to stay above 4 GiB for ten minutes.',diskUnavailable:'Storage data is unavailable; history is paused.',backingUnknown:'Identify the Windows backing drive before history can be recorded.',clockChanged:'The computer clock moved backwards; recording is waiting for it to catch up.',historyBusy:'History storage is busy; no additional write is queued.',minimum:'Minimum: {0}',maximum:'Peak: {0}',coverage:'{0} of {1} chart buckets contain recorded samples',gaps:'Gaps mean no sample was recorded; they are not zero.',retention:'History is capped at 64 MiB, with up to 24 hours of raw samples and 30 days of rollups. Older samples may be pruned earlier.',footprint:'Agent footprint is not available in this version.',snapshotOnly:'Refresh reads saved snapshots. It does not start a new probe.',samples:'Host every 30 s · storage every 60 s',chart:'{0} history',usedHistory:'Storage used',freeHistory:'Storage available',notMeasured:'Not measured'},
11
+ 'zh-TW':{title:'主機狀態',computer:'這台電腦',lead:'依最新記錄的取樣查看 CPU、記憶體與儲存空間。',settings:'監測設定',refresh:'重新整理',refreshing:'重新整理中…',unsupported:'這台電腦尚未提供主機監測。',off:'主機監測已關閉',offHint:'請在設定中開啟,開始取樣並保留容量受限的本機歷史。',admin:'需要管理員登入',adminHint:'請以 Fleet 管理員身分登入,才能查看主機資料。',starting:'等待第一筆取樣',stopping:'正在停止監測',failedHint:'主機監測未能完成操作,請檢查設定與本機儲存空間權限;歷史資料可能仍需清理。',failed:'主機監測需要處理',unavailable:'無法取得',stale:'資料已過期',lastLabel:'最後成功取樣:',last:'最後成功取樣:{0}',none:'尚無成功的取樣',wsl:'WSL 2',linux:'Linux',darwin:'macOS',wslNote:'CPU 與記憶體代表 WSL,不是實體 Windows 電腦。存放 WSL 的 Windows 磁碟會另外列出。',macNote:'APFS 磁碟區可能共用空間,請勿把可用空間相加。可用記憶體是估算值,記憶體壓力會另外顯示。',linuxNote:'本機 Linux 檔案系統與可用記憶體。無法取得的欄位不會當作零。',runtimeNote:'配對的 Windows 電腦是另一台,不算在這裡的數字裡。',storage:'儲存空間',root:'Linux 檔案系統',state:'Fleet 狀態資料',backing:'存放 WSL 的 Windows 磁碟',volume:'本機磁碟區',drive:'({0}:)',shared:'共用 APFS 容量',sharedHint:'請勿把各磁碟區的可用空間相加。',free:'可用 {0}',used:'已使用 {0}%',unknownDrive:'尚未確認 Windows 磁碟',chooseDrive:'到設定選擇磁碟',unknownHint:'只有 Linux 的可用空間,無法判斷存放 WSL 的 Windows 磁碟是否還有空間。',cpu:'CPU',wslCpu:'WSL CPU',wslMemory:'WSL 記憶體',cpuUsed:'使用率 {0}%',cores:'{0} 個邏輯 CPU',loadLabel:'平均負載:',load:'平均負載:{0}',memory:'記憶體',available:'可用 {0},共 {1}',pressureLabel:'記憶體壓力:',pressure:'記憶體壓力:{0}',normal:'正常',elevated:'偏高',critical:'嚴重',unknown:'未知',swap:'Swap 可用:{0}',history:'歷史紀錄',range:'歷史期間',coverageSummary:'{1} 項讀數中,{0} 項有最新資料',collecting:'正在累積歷史紀錄…',noHistory:'這段期間尚無記錄的取樣',historyUnavailable:'暫時無法取得歷史紀錄,請重新整理再試。',historyLoading:'正在載入歷史紀錄…',historyWaiting:'歷史紀錄尚未開始取樣。',historyPaused:'歷史紀錄已暫停。',historyFailed:'無法記錄歷史,目前的取樣仍可查看。',lowSpace:'儲存空間不足:目前取樣只保留在記憶體中。',recovering:'等待兩個儲存空間持續十分鐘都超過 4 GiB。',diskUnavailable:'無法取得儲存空間資料,歷史紀錄已暫停。',backingUnknown:'請先確認存放 WSL 的 Windows 磁碟,再記錄歷史。',clockChanged:'電腦時間往回調整,正在等待時間追上後再記錄。',historyBusy:'歷史儲存空間忙碌中,不會排入額外的寫入。',minimum:'最低:{0}',maximum:'最高:{0}',coverage:'{1} 個圖表區間中,{0} 個有記錄取樣',gaps:'缺口代表沒有記錄取樣,不是零。',retention:'歷史資料最多 64 MiB;原始取樣最多保留 24 小時,彙整最多 30 天。較舊的取樣可能提早清除。',footprint:'這個版本尚未提供 Agent 資源用量。',snapshotOnly:'重新整理只讀取已保存的取樣,不會啟動新的探測。',samples:'主機每 30 秒 · 儲存空間每 60 秒',chart:'{0} 歷史',usedHistory:'儲存空間使用率',freeHistory:'可用儲存空間',notMeasured:'未量測'}
12
+ });
13
+ const text=(key,...values)=>t(`hostHealth.${key}`,...values);
14
+ const date=value=>numberOrNull(value)===null?text('none'):new Date(value).toLocaleString(lang()==='zh-TW'?'zh-TW':'en-GB',{month:'short',day:'numeric',hour:'2-digit',minute:'2-digit',second:'2-digit',hour12:false});
15
+ const sampleTime=value=>html`${text('lastLabel')}${lang()==='zh-TW'?'':' '}<span class="host-sample-time">${date(value)}</span>`;
16
+ const settingLink=()=>sectionPath('notifications')+'#host-monitoring';
17
+ const metricLabel=(metric,interval)=>metricState(metric,interval)==='ok'?null:text(metricState(metric,interval));
18
+ export function historyMessage(status){
19
+ const reason={low_space:'lowSpace',recovering_space:'recovering',disk_unavailable:'diskUnavailable',backing_drive_unknown:'backingUnknown',clock_changed:'clockChanged',history_busy:'historyBusy'}[status?.reason];
20
+ return text(reason||({waiting:'historyWaiting',paused:'historyPaused',failed:'historyFailed',stopping:'stopping'}[status?.state]||'historyWaiting'));
21
+ }
22
+ function HistoryChart({answer,id,label,unit='percent'}){
23
+ const model=chartData(answer?.series?.find(s=>s.id===id)?.buckets);
24
+ const value=n=>n===null?text('unavailable'):unit==='bytes'?displayBytes(n):unit==='pressure'?text(({1:'normal',2:'elevated',3:'critical'})[Math.round(n)]||'unknown'):`${n.toFixed(1)}%`;
25
+ return html`<figure class="host-chart"><figcaption>${text('chart',label)}</figcaption>${model.covered>=4?html`<svg viewBox="0 0 600 110" role="img" aria-label=${`${text('chart',label)}. ${text('minimum',value(model.min))}. ${text('maximum',value(model.max))}. ${text('coverage',model.covered,model.total)}`}><line x1="0" x2="600" y1="100" y2="100" />${model.segments.map((points,i)=>html`<polyline key=${i} points=${points} />`)}${model.dots.map((point,i)=>html`<circle key=${i} cx=${point.x} cy=${point.y} r="2.5"/>`)}</svg><p class="note">${text('minimum',value(model.min))} · ${text('maximum',value(model.max))}</p><p class="note">${text('coverage',model.covered,model.total)}</p>`:html`<p class="note host-no-history">${text(answer===undefined?'historyLoading':answer?.unavailable?'historyUnavailable':model.covered?'collecting':'noHistory')}</p>`}</figure>`;
26
+ }
27
+ function ValueState({metric,interval}){const state=metricLabel(metric,interval);return state?html`<span class="tag">${state}</span>`:null;}
28
+ function Storage({health,history}){
29
+ const rows=storageRows(health),state=metricState(health.disks,60000);
30
+ return html`<section class="card host-storage"><h3>${text('storage')}</h3>${health.platform==='wsl'&&health.disks?.value?.backingDrive!=='identified'?html`<div class="notice warn"><strong>${text('unknownDrive')}</strong><p>${text('unknownHint')}</p><a class="btn btn-sm" href=${settingLink()}>${text('chooseDrive')}</a></div>`:null}${!rows.length?html`<p class="note">${text('unavailable')}</p>`:rows.map(v=>{
31
+ const name=v.roles.includes('wsl-backing')?text('backing'):v.roles.filter(r=>r==='root'||r==='state').map(r=>text(r==='root'?(health.platform==='darwin'?'volume':'root'):'state')).join(' · ')||text('volume');
32
+ const known=state==='ok'&&numberOrNull(v.availableBytes)!==null;
33
+ return html`<article key=${v.id} class="host-volume"><div class="host-row"><h4>${name}${/^[A-Z]$/.test(v.drive||'')?html`<span class="note">${text('drive',v.drive)}</span>`:null}</h4>${state!=='ok'||!known?html`<span class="tag">${text(state==='stale'?'stale':'unavailable')}</span>`:null}</div><p class="host-value">${numberOrNull(v.availableBytes)!==null?text('free',displayBytes(v.availableBytes)):text('unavailable')}</p><p class="note">${numberOrNull(v.usedPercent,100)!==null?text('used',v.usedPercent.toFixed(1)):text('unavailable')} · ${sampleTime(v.sampledAt)}</p>${numberOrNull(v.usedPercent,100)===null?null:html`<progress class="host-space-meter" value=${v.usedPercent} max="100" aria-label=${text('used',v.usedPercent.toFixed(1))}></progress>`}${health.platform==='darwin'&&v.shared?html`<p class="note">${text('shared')} · ${text('sharedHint')}</p>`:null}<${HistoryChart} answer=${history} id=${`disk.${v.id}.available`} label=${text('freeHistory')} unit="bytes" /></article>`;
34
+ })}</section>`;
35
+ }
36
+ export function HostHealthView({health,history,busy,range,onRange,onRefresh}){
37
+ const at=[health?.cpu?.sampledAt,health?.memory?.sampledAt,health?.disks?.sampledAt].filter(v=>numberOrNull(v)!==null),last=at.length?Math.max(...at):null;
38
+ const cpu=health?.cpu?.value,memory=health?.memory?.value,coverage=sampleCoverage(health);
39
+ const populated=health?.enabled&&health?.platformSupported!==false,platform=text(['wsl','linux','darwin'].includes(health?.platform)?health.platform:'unavailable');
40
+ return html`<section class="host-health" aria-busy=${busy}><${PageHead} title=${text('title')} scope=${text('computer')+(populated?' · '+platform:'')} lead=${text('lead')} note=${html`${last===null?text('none'):sampleTime(last)}${populated?' · '+text('coverageSummary',coverage.covered,coverage.total):''}`}><button type="button" class="btn btn-sm" disabled=${busy} onClick=${onRefresh}><${Icon} name="restart" size=${15}/>${text(busy?'refreshing':'refresh')}</button>${health?.platformSupported===false?null:html`<a class="btn btn-sm" href=${settingLink()}>${text('settings')}</a>`}</${PageHead}>
41
+ ${!populated?html`<p class="note">${text('snapshotOnly')}</p>`:null}
42
+ ${health?.platformSupported===false?html`<section class="card"><h3>${text('unsupported')}</h3></section>`:!health?.enabled?html`<section class="card host-off"><h3>${text(health?.state==='failed'?'failed':health?.state==='stopping'?'stopping':'off')}</h3><p>${text(health?.state==='failed'?'failedHint':health?.state==='stopping'?'stopping':'offHint')}</p><a class="btn btn-primary" href=${settingLink()}>${text('settings')}</a></section>`:html`
43
+ ${health.state!=='sampling'?html`<div class="notice" role="status">${text(({starting:'starting',stopping:'stopping',failed:'failed'})[health.state]||'unavailable')}</div>`:null}
44
+ ${health.history?.state!=='recording'?html`<p class="notice" role="status">${historyMessage(health.history)}</p>`:null}
45
+ <div class="host-range" role="group" aria-label=${text('range')}>${HOST_RANGES.map(r=>html`<button type="button" class=${`btn btn-sm${range===r?' active':''}`} aria-pressed=${range===r} onClick=${()=>onRange(r)}>${r}</button>`)}</div>
46
+ <div class="host-grid"><div class="host-compute"><section class="card"><div class="host-row"><h3>${text(health.platform==='wsl'?'wslCpu':'cpu')}</h3><${ValueState} metric=${health.cpu} interval=${30000}/></div><p class="host-value">${numberOrNull(cpu?.usedPercent,100)===null?text('unavailable'):text('cpuUsed',cpu.usedPercent.toFixed(1))}</p><p class="note">${numberOrNull(cpu?.logicalCpus)!==null?text('cores',cpu.logicalCpus):text('unavailable')}</p>${Array.isArray(cpu?.loadAverage)?html`<p class="note">${text('loadLabel')}${lang()==='zh-TW'?'':' '}<span class="host-load-value">${cpu.loadAverage.slice(0,3).map(n=>numberOrNull(n)===null?'—':n.toFixed(2)).join(' / ')}</span></p>`:null}<p class="note">${sampleTime(health.cpu?.sampledAt)}</p><${HistoryChart} answer=${history} id="cpu.used" label=${text('cpu')}/></section>
47
+ <section class="card"><div class="host-row"><h3>${text(health.platform==='wsl'?'wslMemory':'memory')}</h3><${ValueState} metric=${health.memory} interval=${30000}/></div><p class="host-value">${text('pressureLabel')}${lang()==='zh-TW'?'':' '}<span class="host-pressure-value">${text(metricState(health.memory,30000)==='ok'&&['normal','elevated','critical'].includes(memory?.pressure)?memory.pressure:'unknown')}</span></p><p class="note">${numberOrNull(memory?.availableBytes)===null?text('unavailable'):text('available',displayBytes(memory.availableBytes),displayBytes(memory.totalBytes)||text('unavailable'))}</p><p class="note">${text('swap',displayBytes(memory?.swapFreeBytes)||text('unavailable'))}</p><p class="note">${sampleTime(health.memory?.sampledAt)}</p><${HistoryChart} answer=${history} id="memory.available" label=${text('memory')} unit="bytes" /></section></div>
48
+ <${Storage} health=${health} history=${history}/></div><p class="note">${text(health.platform==='wsl'?'wslNote':health.platform==='darwin'?'macNote':'linuxNote')}</p><p class="note">${text('samples')} · ${text('snapshotOnly')}</p><p class="note">${text('runtimeNote')}</p><p class="note">${text('gaps')}</p><p class="note">${text('retention')}</p><p class="note">${text('footprint')}</p>`}
49
+ </section>`;
50
+ }
51
+ export function HostHealth({lease}){
52
+ const [data,setData]=useState(null),[history,setHistory]=useState(null),[range,setRange]=useState('1h'),[busy,setBusy]=useState(false),[error,setReadState]=useState(null),seq=useRef(0),inflight=useRef(false),pending=useRef(false),latest=useRef(null),alive=useRef(true);
53
+ const load=async()=>{
54
+ if(!alive.current||!lease.current())return;if(inflight.current){pending.current=true;return;}inflight.current=true;const mine=++seq.current;setBusy(true);
55
+ try{
56
+ const response=await lease.fetch('/ui/host-health',{cache:'no-store'});if(!alive.current||!lease.current()||mine!==seq.current)return;
57
+ if(response.status===401||response.status===403){setData(null);setHistory(null);setReadState('admin');return;}if(!response.ok)throw Error('read failed');
58
+ const health=await response.json();if(!alive.current||!lease.current()||mine!==seq.current)return;setData(health);setReadState(null);
59
+ if(!health.enabled||health.history?.state!=='recording'){setHistory(null);return;}
60
+ const params=new URLSearchParams({range});for(const id of historySeries(health))params.append('series',id);
61
+ const r=await lease.fetch('/ui/host-history?'+params,{cache:'no-store'});if(!alive.current||!lease.current()||mine!==seq.current)return;
62
+ if(r.status===401||r.status===403){setData(null);setHistory(null);setReadState('admin');return;}
63
+ const result=r.ok?await r.json():null;if(alive.current&&lease.current()&&mine===seq.current)setHistory({range,value:result?.ok?result.value:{unavailable:true}});
64
+ }catch{if(alive.current&&lease.current()&&mine===seq.current)setReadState('load');}finally{inflight.current=false;if(alive.current&&lease.current()&&mine===seq.current)setBusy(false);if(pending.current){pending.current=false;void latest.current?.();}}
65
+ };
66
+ latest.current=load;
67
+ useEffect(()=>{alive.current=true;return()=>{alive.current=false;seq.current++;};},[lease]);
68
+ useEffect(()=>{seq.current++;void load();},[lease,range]);
69
+ // Only an enabled visible page refreshes its cache. Off/unmounted pages own no monitoring poll.
70
+ useEffect(()=>{if(!data?.enabled)return;const timer=lease.interval(()=>{if(typeof document==='undefined'||!document.hidden)void load();},30000);return()=>lease.clear(timer);},[lease,data?.enabled,range]);
71
+ if(error==='admin')return html`<section class="card"><h2>${text('admin')}</h2><p>${text('adminHint')}</p></section>`;
72
+ if(!data)return error?html`<${ErrorState} onRetry=${load}/>`:html`<${Skeleton} lines=${5}/>`;
73
+ return html`<div>${error?html`<${ErrorState} onRetry=${load}/>`:null}<${HostHealthView} health=${data} history=${history?.range===range?history.value:busy?undefined:null} range=${range} onRange=${setRange} onRefresh=${load} busy=${busy}/></div>`;
74
+ }
@@ -89,7 +89,11 @@ function blobImage(blob) {
89
89
  return new Promise((resolve) => {
90
90
  if (typeof Image !== "function") { resolve(null); return; }
91
91
  const src = URL.createObjectURL(blob), im = new Image();
92
- im.onload = () => { URL.revokeObjectURL(src); resolve(im); };
92
+ const finish = () => { URL.revokeObjectURL(src); resolve(im); };
93
+ im.onload = () => {
94
+ if (typeof im.decode === "function") im.decode().then(finish, finish);
95
+ else finish();
96
+ };
93
97
  im.onerror = () => { URL.revokeObjectURL(src); resolve(null); };
94
98
  im.src = src;
95
99
  });
@@ -10,8 +10,9 @@ import { GeneralLocation } from "./general-location.js";
10
10
  // The instance's own actions (details, start, stop, restart, delete) are in the header's ⋯ menu, and only the ones
11
11
  // that apply to its state are offered (#1408 rough edges 4 and 7).
12
12
  import { html, Fragment, useEffect, useLayoutEffect, useRef, useState } from "/assets/app-html.js";
13
+ import { JUMP_IDLE_MS, useJumpIdle } from "/assets/jump-idle.js";
13
14
  import { lang, register, t } from "/assets/app-i18n.js";
14
- import { AgentSheetButton } from "/assets/agent-sheet.js";
15
+ import { AgentSheetButton, AgentSheet } from "/assets/agent-sheet.js";
15
16
  import { appStore, createStore, guestPage, guestTrusted, useStore } from "/assets/app-store.js";
16
17
  import { ComposerAuth, useWebAuthorization } from "/assets/web-authorize.js";
17
18
  import { useLease } from "/assets/app-ctx.js";
@@ -19,7 +20,7 @@ import * as paneContext from "/assets/app-ctx.js";
19
20
  import { backendLabel, modelText, namesOf, namesStore, navStore as instanceNavStore, supportsInstanceFeature } from "/assets/instance-nav.js";
20
21
  import { machineName } from "/assets/machine-name.js";
21
22
  import { PanelHeader, onPanelKey, setTitle, statusClass, statusLabel, openDrawer, requestNewInstance, needsCount, openSearch } from "/assets/app-shell.js";
22
- import { detailsPath, textLinkSegments, sectionPath, NEEDS_PATH, fleetEntryPath, settingsPath, viewPath, logPath } from "/assets/app-route.js";
23
+ import { chatPath, detailsPath, textLinkSegments, sectionPath, NEEDS_PATH, fleetEntryPath, settingsPath, viewPath, logPath } from "/assets/app-route.js";
23
24
  import { InstanceSwitch } from "/assets/instance-switch.js";
24
25
  import { HeaderTools, setTextSize, textSizeStore, usageOffered, TEXT_SIZES } from "/assets/header-tools.js";
25
26
  import { UsageDialog } from "/assets/usage-dialog.js";
@@ -113,6 +114,49 @@ const needKey = (item) => String(item?.nonce || item?.id || JSON.stringify(item
113
114
  * count), Fleet, Settings — then this chat's items, and ends with 「✓ 已驗證」 (the line under the composer no longer
114
115
  * says it). A Needs-you item that arrives meanwhile, for another agent, is a short toast. A desk's ⋯ is unchanged.
115
116
  */
117
+ /** One target-bound action list for the header and sidebar; the server remains the authority. */
118
+ export function chatAgentMenuItems({ name, inst, wide, pinCount = 0, onPins, onDelete,
119
+ onDetails = () => navigate(detailsPath(name)), onSplit = () => appStore.get().chatWorkspace?.open(name) }) {
120
+ if (guestPage()) return [];
121
+ const running = inst.status === "running";
122
+ const action = async (verb) => {
123
+ let r;
124
+ try { const res = await fetch(`/ui/${verb}/${encodeURIComponent(name)}`, { method: "POST", headers: { "Content-Type": "application/json" } }); r = await res.json(); }
125
+ catch (err) { r = { error: err && err.message ? err.message : t("chat.disconnected") }; }
126
+ if (r && r.error) toast(r.error, false);
127
+ else if (r && r.held) toast(r.message);
128
+ else toast(t(verb === "start" ? "chat.started" : verb === "stop" ? "chat.stoppedInst" : "chat.restarted", name));
129
+ };
130
+ return [
131
+ // #1523 N2: Details is a page now (the Fleet side of this instance), not a dialog.
132
+ supportsInstanceFeature(inst,"details") ? { key: "details", label: t("chat.details"), icon: "info", onSelect: () => onDetails() } : null,
133
+ appStore.get().chatWorkspace ? { key: "splitChat", label: t("chatWorkspace.split"), icon: "sidebar", onSelect: () => onSplit() } : null,
134
+ inst.runtime === "windows" ? {key:"settings",label:t("app.settings"),icon:"settings",onSelect:() => navigate(sectionPath("agents"))} : null,
135
+ running || !supportsInstanceFeature(inst,"lifecycle") ? null : { key: "start", label: t("chat.start"), icon: "play", onSelect: () => action("start") },
136
+ running && supportsInstanceFeature(inst,"lifecycle") ? { key: "restart", label: t("chat.restart"), icon: "restart", onSelect: () => action("restart") } : null,
137
+ running && supportsInstanceFeature(inst,"lifecycle") ? { key: "stop", label: t("chat.stopInstance"), icon: "stop", onSelect: () => action("stop") } : null,
138
+ // #1958: its identity colour and where it shows (the public link too, as profile edits).
139
+ // #3153 P1: the folder it works in, read-only — an admin only (M-3278: over the public link too), and not an
140
+ // agent on another machine (the server also refuses General and coordinators: their folder is the fleet's own).
141
+ inst.runtime === "windows" || inst.machine_id || inst.general_topic === true ? null
142
+ : { key: "workspace", label: t("chat.wsOpen"), icon: "file", onSelect: () => openWorkspace({ key: `ws:${name}`, instance: name }) },
143
+ // M-3271: the pinned list — here too, for a phone (its header shows ← title ⋯ only) and a narrow pane.
144
+ pinCount ? { key: "pins", label: `${t("chat.pinsTitle")} · ${pinCount}`, icon: "pin", onSelect: onPins } : null,
145
+ colorMenuItem(name, inst),
146
+ // #1629: a person's control over this agent's theme — not over the public link (it only views themes).
147
+ ...themeMenuItems(name),
148
+ // #2117: its ambient — why it is not showing here (with the way to change that), and a person's Clear.
149
+ ...ambientMenuItems(name, { publicLink: false, clear: clearAmbient }), // M-3278
150
+ // AGEND-181: the activity timeline above each reply (this browser's choice), when the Log is on.
151
+ ...(activityOffered() && activityInfo(name)?.level !== "off" ? [
152
+ { key: "activity", checkbox: true, checked: activityPrefs.get().on, label: t("act.menuActivity"), onSelect: () => setActivityOn(!activityPrefs.get().on) },
153
+ ...(activityInfo(name)?.thinking ? [{ key: "thinking", checkbox: true, checked: activityPrefs.get().thinking, disabled: !activityPrefs.get().on, label: t("act.menuThinking"), onSelect: () => setActivityThinking(!activityPrefs.get().thinking) }] : []),
154
+ ] : []),
155
+ narrowScreen() ? null : { key: "fullWidth", checkbox: true, checked: wide, label: t("chat.fullWidth"), onSelect: () => setChatWide(!wide) },
156
+ { key: "delete", label: t("chat.delete"), icon: "trash", danger: true, onSelect: onDelete },
157
+ ];
158
+ }
159
+
116
160
  function ChatMoreMenu({ items, name, inst = null, card = null, navKey, lease = null }) {
117
161
  const app = useStore(appStore);
118
162
  const auth = useWebAuthorization();
@@ -385,10 +429,11 @@ export function boot({ stream, boot: bootData, deps = {} }) {
385
429
  clearReply: (instance) => store.clearReply(instance),
386
430
  addToDraft: (instance, line) => { feedbackInstance = instance; recordEdit(composerField(instance)); store.addToDraft(instance, line); },
387
431
  focus: (instance = feedbackInstance) => {
432
+ import("./preview-popout.js").then(m => m.leavePreviewWindow()).catch(() => {});
388
433
  const el = composerField(instance); if (!el) return;
389
434
  el.focus();
390
435
  // After the render that shows the line: the caret at its end.
391
- setTimeout(() => { if (composerField(instance) !== el) return; try { const n = el.value.length; el.setSelectionRange(n, n); } catch { /* not a text field */ } }, 0);
436
+ setTimeout(() => { if (composerField(instance) !== el) return; el.focus(); try { const n = el.value.length; el.setSelectionRange(n, n); } catch { /* not a text field */ } }, 0);
392
437
  },
393
438
  });
394
439
  // #1604: the preview opt-in and Tour live in Settings → This device now (and on each preview card's menu).
@@ -446,6 +491,7 @@ export function ChatPanel({ route, navKey }) {
446
491
  const app = useStore(appStore);
447
492
  const name = route.instance;
448
493
  const inst = name ? app.instances.find(i => i.name === name) : null;
494
+
449
495
  useEffect(() => {
450
496
  if (store.show) {
451
497
  if (!name || !inst) return;
@@ -501,6 +547,16 @@ function useResolvedMode(lease) {
501
547
  }
502
548
 
503
549
  function ChatView({ name, inst, lease, navKey, exec, awaiting }) {
550
+ const [previewPopout, setPreviewPopout] = useState(null);
551
+ useEffect(() => {
552
+ let alive = true, owner = null; setPreviewPopout(null);
553
+ if (!name || !inst) return;
554
+ import("./preview-popout.js").then(m => m.createPreviewPopout(name)).then(value => {
555
+ if (!alive) { value?.close(); return; } owner = value;
556
+ if (owner) setPreviewPopout(() => spec => owner.open(spec));
557
+ }).catch(() => {});
558
+ return () => { alive = false; owner?.close(); };
559
+ }, [name, !!inst]);
504
560
  const pane = paneContext.usePane?.(), paneNow = useRef(pane); paneNow.current = pane;
505
561
  const bindings = useRef({ input: { current: null }, box: { current: null }, composing: false }).current;
506
562
  const ids = pane ? Object.fromEntries(["msgIn", "attachBtn", "stopBtn", "sendBtn", "cmdPalette"].map(key => [key, `pane-${pane.id}-${key}`])) : {};
@@ -584,43 +640,8 @@ function ChatView({ name, inst, lease, navKey, exec, awaiting }) {
584
640
  e.preventDefault();
585
641
  store.cancelReply(name);
586
642
  })), [lease]);
587
- const running = inst.status === "running";
588
- const action = async (verb) => {
589
- let r;
590
- try { const res = await fetch(`/ui/${verb}/${encodeURIComponent(name)}`, { method: "POST", headers: { "Content-Type": "application/json" } }); r = await res.json(); }
591
- catch (err) { r = { error: err && err.message ? err.message : t("chat.disconnected") }; }
592
- if (r && r.error) toast(r.error, false);
593
- else if (r && r.held) toast(r.message);
594
- else toast(t(verb === "start" ? "chat.started" : verb === "stop" ? "chat.stoppedInst" : "chat.restarted", name));
595
- };
596
- const items = [
597
- // #1523 N2: Details is a page now (the Fleet side of this instance), not a dialog.
598
- supportsInstanceFeature(inst,"details") ? { key: "details", label: t("chat.details"), icon: "info", onSelect: () => (paneNow.current?.navigate || navigate)(detailsPath(name)) } : null,
599
- appStore.get().chatWorkspace ? { key: "splitChat", label: t("chatWorkspace.split"), icon: "sidebar", onSelect: () => appStore.get().chatWorkspace.pick() } : null,
600
- inst.runtime === "windows" ? {key:"settings",label:t("app.settings"),icon:"settings",onSelect:() => navigate(sectionPath("agents"))} : null,
601
- running || !supportsInstanceFeature(inst,"lifecycle") ? null : { key: "start", label: t("chat.start"), icon: "play", onSelect: () => action("start") },
602
- running && supportsInstanceFeature(inst,"lifecycle") ? { key: "restart", label: t("chat.restart"), icon: "restart", onSelect: () => action("restart") } : null,
603
- running && supportsInstanceFeature(inst,"lifecycle") ? { key: "stop", label: t("chat.stopInstance"), icon: "stop", onSelect: () => action("stop") } : null,
604
- // #1958: its identity colour and where it shows (the public link too, as profile edits).
605
- // #3153 P1: the folder it works in, read-only — an admin only (M-3278: over the public link too), and not an
606
- // agent on another machine (the server also refuses General and coordinators: their folder is the fleet's own).
607
- inst.runtime === "windows" || inst.machine_id || inst.general_topic === true ? null
608
- : { key: "workspace", label: t("chat.wsOpen"), icon: "file", onSelect: () => openWorkspace({ key: `ws:${name}`, instance: name }) },
609
- // M-3271: the pinned list — here too, for a phone (its header shows ← title ⋯ only) and a narrow pane.
610
- pinCount ? { key: "pins", label: `${t("chat.pinsTitle")} · ${pinCount}`, icon: "pin", onSelect: openPins } : null,
611
- colorMenuItem(name, inst),
612
- // #1629: a person's control over this agent's theme — not over the public link (it only views themes).
613
- ...themeMenuItems(name),
614
- // #2117: its ambient — why it is not showing here (with the way to change that), and a person's Clear.
615
- ...ambientMenuItems(name, { publicLink: false, clear: clearAmbient }), // M-3278
616
- // AGEND-181: the activity timeline above each reply (this browser's choice), when the Log is on.
617
- ...(activityOffered() && activityInfo(name)?.level !== "off" ? [
618
- { key: "activity", checkbox: true, checked: activityPrefs.get().on, label: t("act.menuActivity"), onSelect: () => setActivityOn(!activityPrefs.get().on) },
619
- ...(activityInfo(name)?.thinking ? [{ key: "thinking", checkbox: true, checked: activityPrefs.get().thinking, disabled: !activityPrefs.get().on, label: t("act.menuThinking"), onSelect: () => setActivityThinking(!activityPrefs.get().thinking) }] : []),
620
- ] : []),
621
- narrowScreen() ? null : { key: "fullWidth", checkbox: true, checked: wide, label: t("chat.fullWidth"), onSelect: () => setChatWide(!wide) },
622
- { key: "delete", label: t("chat.delete"), icon: "trash", danger: true, onSelect: () => setDialog("delete") },
623
- ];
643
+ const items = chatAgentMenuItems({ name, inst, wide, pinCount, onPins: openPins, onDelete: () => setDialog("delete"),
644
+ onDetails: () => (paneNow.current?.navigate || navigate)(detailsPath(name)), onSplit: () => appStore.get().chatWorkspace.pick() });
624
645
  const cls = statusClass(inst, exec, awaiting);
625
646
  // #1920 phase 3: a guest has this chat only — no Details, View or Log to switch to, no lifecycle, colour, theme,
626
647
  // effect management or delete (a guest's status frame carries no model or effort either, so those chips do not show).
@@ -657,7 +678,7 @@ function ChatView({ name, inst, lease, navKey, exec, awaiting }) {
657
678
  <${ChatAmbient} name=${name} surface=${effectSurface} part="front" />
658
679
  </div>
659
680
  <${PreviewPanel} name=${name} split=${split} msgs=${() => store.state.msgs[name] || []} subscribe=${(fn) => store.subscribe(fn)}
660
- keyOf=${msgKey} reveal=${(k) => thread.current && thread.current.reveal(k)} download=${downloadHtml} allow=${(commit) => setPreviewOptIn(true, commit)} />
681
+ popout=${previewPopout} keyOf=${msgKey} reveal=${(k) => { const owner = thread.current; import("./preview-popout.js").then(m => m.leavePreviewWindow(), () => {}).then(() => { if (lease.current() && thread.current === owner) owner?.reveal(k); }); }} download=${downloadHtml} allow=${(commit) => setPreviewOptIn(true, commit)} />
661
682
  </div>
662
683
  <${LightboxHost} owner=${view} />
663
684
  ${attachmentsSupported ? html`<div data-trust="drop" class="drop-overlay" aria-hidden="true"><div class="drop-card"><${Icon} name="attach" size=${32} /><span>${t("chat.dropHere")}</span></div></div>` : null}
@@ -839,11 +860,14 @@ function follow(name, thread) {
839
860
  }
840
861
 
841
862
  /** The thread's view: Preact owns the scroller and the jump pill; the kept list (chat-thread.js) is put inside it. */
863
+ export { JUMP_IDLE_MS };
842
864
  function Thread({ name, label = name, th, bindings }) {
843
865
  const pane = paneContext.usePane?.(), paneNow = useRef(pane); paneNow.current = pane;
844
866
  const scroller = useRef(null), host = useRef(null);
845
867
  const [jump, setJump] = useState({ show: false, unseen: 0 });
846
868
  const [empty, setEmpty] = useState(false);
869
+ // M-3492/M-3493: 最新 fades out JUMP_IDLE_MS after the last scroll (shared with the Hub's threads: jump-idle.js).
870
+ const jumpIdle = useJumpIdle(scroller, jump.show, name);
847
871
  useLayoutEffect(() => { keptThreads.get(name)?.list.setAttribute("aria-label",t("chat.conversationWith",label)); },[name,label]);
848
872
  useLayoutEffect(() => {
849
873
  const doc = host.current.ownerDocument;
@@ -950,7 +974,8 @@ function Thread({ name, label = name, th, bindings }) {
950
974
  <div class="thread-host" ref=${host}></div>
951
975
  ${empty === "hidden" ? html`<${Empty} icon="chat" title=${t("chat.guestAllHidden")} hint=${t("chat.guestAllHiddenHint")} />`
952
976
  : empty ? html`<${Empty} icon="chat" title=${t("chat.noMessages")} />` : null}
953
- </div><div class="jump-dock">${jump.show ? html`<button data-trust="thread-control" type="button" class="jump-latest" onClick=${() => { const t2 = th.current; if (!t2) return; if (store.pagingState(name).detached) void store.backToLatest(name).then(() => t2.jumpLatest()); else t2.jumpLatest(); }}
977
+ </div><div class="jump-dock">${jump.show ? html`<button data-trust="thread-control" type="button" ref=${jumpIdle.ref} class=${`jump-latest${jumpIdle.idle ? " is-idle" : ""}`} onClick=${() => { const t2 = th.current; if (!t2) return; if (store.pagingState(name).detached) void store.backToLatest(name).then(() => t2.jumpLatest()); else t2.jumpLatest(); }}
978
+ onFocus=${jumpIdle.onFocus} onBlur=${jumpIdle.onBlur}
954
979
  aria-label=${jump.unseen > 0 ? t("chat.newBelow", jump.unseen) : t("chat.jumpLatest")}>
955
980
  <${Icon} name="down" size=${16} /><span class="jump-text">${jump.unseen > 0 ? t("chat.newBelow", jump.unseen) : t("chat.jumpLatest")}</span>${
956
981
  /* The user (before 2.4.0-beta.3): no unread counts for now — a phone's round button has no badge. */ ""}</button>` : null}</div>
@@ -996,6 +1021,38 @@ function openBackendSignIn(backend) {
996
1021
  import("./backend-signin.js").then((m) => m.openSignIn({ backend }), () => toast(t("app.loadFailed"), false));
997
1022
  }
998
1023
 
1024
+ /** Reports contain plain strings; HTM escapes every title, header, cell and note. */
1025
+ function CommandReport({ report, command }) {
1026
+ const [filter, setFilter] = useState("");
1027
+ const [expanded, setExpanded] = useState(false);
1028
+ const trigger = useRef(null);
1029
+ const wasExpanded = useRef(false);
1030
+ // The inline trigger is recreated when the modal closes; restore focus after its ref is mounted.
1031
+ useLayoutEffect(() => {
1032
+ if (wasExpanded.current && !expanded) trigger.current?.focus({ preventScroll: true });
1033
+ wasExpanded.current = expanded;
1034
+ }, [expanded]);
1035
+ const query = filter.trim().toLocaleLowerCase();
1036
+ const rows = command === "status" && query
1037
+ ? report.rows.filter(row => row.some(value => value.toLocaleLowerCase().includes(query))) : report.rows;
1038
+ const view = html`<section class=${`cmd-report cmd-report-${command}${expanded ? " cmd-report-expanded" : ""}`} aria-label=${report.title}>
1039
+ ${expanded ? null : html`<h3>${report.title}</h3>`}
1040
+ <div class="cmd-report-tools">
1041
+ ${command === "status" ? html`<label class="field"><span class="sr-only">${t("chat.cmdReportFilter")}</span>
1042
+ <input type="search" aria-label=${t("chat.cmdReportFilter")} placeholder=${t("chat.cmdReportFilter")}
1043
+ value=${filter} onInput=${e => setFilter(e.target.value)} /></label>` : null}
1044
+ ${expanded ? null : html`<button type="button" class="btn btn-sm btn-ghost" ref=${trigger} data-report-expand onClick=${() => setExpanded(true)}>${t("chat.cmdReportOpen")}</button>`}
1045
+ </div>
1046
+ ${command === "status" ? html`<p class="note cmd-report-count">${query ? t("chat.cmdReportMatches", rows.length, report.rows.length) : t("chat.cmdReportCount", report.rows.length)}${report.notes[0] ? " · " + report.notes[0] : ""}</p>` : null}
1047
+ <div class="cmd-report-body" tabIndex="0" aria-label=${report.title}>
1048
+ ${rows.length ? html`<table class=${command === "status" ? "us-table" : "cmd-metrics"}><thead><tr>${report.columns.map(label => html`<th scope="col">${label}</th>`)}</tr></thead>
1049
+ <tbody>${rows.map(row => html`<tr>${row.map((value, i) => html`<td data-label=${report.columns[i]}>${value}</td>`)}</tr>`)}</tbody></table>` : query ? html`<p class="note">${t("chat.cmdReportEmpty")}</p>` : null}
1050
+ ${(command === "status" ? report.notes.slice(1) : report.notes).map(note => html`<p class="note">${note}</p>`)}
1051
+ </div>
1052
+ </section>`;
1053
+ return expanded ? html`<div class="cmd-report-modal"><${Dialog} title=${report.title} wide onClose=${() => setExpanded(false)}>${view}</${Dialog}></div>` : view;
1054
+ }
1055
+
999
1056
  /** #1269: what the last chat command answered — its text, why it was refused, or a list to choose from. */
1000
1057
  // M-3166 PR 3: the model menu's words (kept beside their caller: a retained chat dictionary has no such words).
1001
1058
  register("modelMenu", {
@@ -1118,6 +1175,8 @@ function ModelMenu({ name, c, lease }) {
1118
1175
  return html`<div class="model-menu-scrim" onClick=${close}></div><div class="model-menu-pop" ref=${(el) => { pop.current = el; place(el); }} onKeyDown=${onKeys}>${body}</div>`;
1119
1176
  }
1120
1177
 
1178
+ const usesModelMenu = c => c?.command === "model" && (c.choices ? c.choices.step !== "backend" : c.busy && !c.error && !c.args);
1179
+
1121
1180
  function CommandCard({ name, lease }) {
1122
1181
  const c = store.state.commands[name];
1123
1182
  if (!c) return null;
@@ -1130,7 +1189,7 @@ function CommandCard({ name, lease }) {
1130
1189
  // bottom sheet on a phone — not a card above the box. A failure, its result text and /backend stay the card.
1131
1190
  // The menu is /model's list: shown with its choices, or while that list loads. A model being switched to (a pick from the
1132
1191
  // menu, a typed "/model <id>") is the card's, as before (#4003 review).
1133
- if (c.command === "model" && (c.choices ? c.choices.step !== "backend" : c.busy && !c.error && !c.args)) return html`<${ModelMenu} name=${name} c=${c} lease=${lease} />`;
1192
+ if (usesModelMenu(c)) return html`<${ModelMenu} name=${name} c=${c} lease=${lease} />`;
1134
1193
  const open = sub && sub.for === c.choices ? c.choices.options.find((o) => o.id === sub.id && o.effort) : null;
1135
1194
  const pickEffort = async (model, level) => {
1136
1195
  setSub(null);
@@ -1144,7 +1203,7 @@ function CommandCard({ name, lease }) {
1144
1203
  ${c.busy ? html`<span class="wait">${t("chat.cmdRunning", c.command)}</span>` : html`<button type="button" class="icon-btn" title=${t("chat.cmdDismiss")}
1145
1204
  aria-label=${t("chat.cmdDismiss")} onClick=${() => store.dismissCommand(name)}><${Icon} name="close" size=${14} /></button>`}</div></div>
1146
1205
  ${c.error ? html`<p class="cmd-text">${c.error}</p>` : null}
1147
- ${c.text ? html`<pre class="cmd-text">${c.text}</pre>` : null}
1206
+ ${c.report ? html`<${CommandReport} report=${c.report} command=${c.command} />` : c.text ? html`<pre class="cmd-text">${c.text}</pre>` : null}
1148
1207
  ${c.compact ? html`<p class="cmd-text cmd-phase">${c.compact === "running" ? t("chat.compactRunning")
1149
1208
  : c.compact === "done" ? t("chat.compactDone") : c.compact === "timeout" ? t("chat.compactTimeout", "10")
1150
1209
  : c.compact === "lost" ? t("chat.compactLost") : c.compact === "not_compacted" ? t("chat.compactNotCompacted") : t("chat.compactUnknown")}</p>` : null}
@@ -1426,7 +1485,7 @@ function FileChip({ f, i, name, bindings }) {
1426
1485
 
1427
1486
  // ── Dialogs ──
1428
1487
 
1429
- function DeleteDialog({ name, inst, onClose }) {
1488
+ function DeleteDialog({ name, inst, onClose, onDeleted = () => navigate("/ui") }) {
1430
1489
  // The dialog's own lease: it ends when the dialog goes (closed, or the chat left for another page). The delete
1431
1490
  // may still finish on the server, and says so, but a dialog that is gone never closes or navigates the page the
1432
1491
  // person is on now (#1425 review).
@@ -1453,7 +1512,7 @@ function DeleteDialog({ name, inst, onClose }) {
1453
1512
  if (handedOver || !lease.current()) return;
1454
1513
  setBusy(false);
1455
1514
  onClose();
1456
- navigate("/ui");
1515
+ onDeleted();
1457
1516
  }
1458
1517
  return html`<${Dialog} title=${t("chat.deleteTitle", name)} onClose=${onClose} busy=${busy}
1459
1518
  actions=${html`<button type="button" class="btn" onClick=${onClose} disabled=${busy}>${t("chat.cancel")}</button>
@@ -1465,3 +1524,44 @@ function DeleteDialog({ name, inst, onClose }) {
1465
1524
  </${Dialog}>`;
1466
1525
  }
1467
1526
  ChatPanel.workspaceVersion = 1;
1527
+
1528
+ /** Session-only injection: public InstanceNav never imports this module. */
1529
+ export function SidebarChatMenu({ inst, context, onClose, favorite = null }) {
1530
+ const name = inst.name || inst.instance_name, lease = useLease(`sidebar-menu:${name}`);
1531
+ const [phase, setPhase] = useState("menu");
1532
+ const [, redraw] = useState(0);
1533
+ const wide = useStore(chatWide).on;
1534
+ useStore(themesStore); useStore(activityInfoStore); useStore(activityPrefs);
1535
+ const auth = useWebAuthorization(), card = useCard(name, inst.card_v);
1536
+ const pinCount = usePins(name).pins?.length || 0;
1537
+ useEffect(() => store?.subscribe(target => { if (target === name) redraw(n => n + 1); }), [name]);
1538
+ useEffect(() => {
1539
+ if (phase !== "menu" || !activityShown() || activityInfo(name)?.level !== undefined) return;
1540
+ const feed = observeActivity(name, { changed: () => feed.stop(), wantThinking: () => activityPrefs.get().thinking });
1541
+ feed.start(); return () => feed.stop();
1542
+ }, [name, phase, activityPrefs.get().on]);
1543
+ const command = store?.state.commands[name];
1544
+ useEffect(() => { if ((phase === "command" && !command) || (phase === "card" && !card)) setPhase(null); }, [phase, command, card]);
1545
+ useEffect(() => { if (!phase) onClose(); }, [phase]);
1546
+ const items = chatAgentMenuItems({ name, inst, wide, pinCount, onPins: () => setPhase("pins"), onDelete: () => setPhase("delete") });
1547
+ const run = command => { setPhase("command"); void store.runCommand(name, command, "", { alive: () => lease.current() && !guestPage() }); };
1548
+ const dismiss = () => setPhase(null);
1549
+ const chat = { card: !!card, onCard: () => setPhase("card"),
1550
+ ...(supportsInstanceFeature(inst, "commands") ? { onModel: () => run("model"),
1551
+ modelText: `${shortModelName(modelLabel(inst.model || modelText(inst)))}${supportsInstanceFeature(inst, "effort") && effortChip(inst) ? ` · ${effortChip(inst)}` : ""}`,
1552
+ onBackend: () => inst.runtime === "windows" ? navigate(sectionPath("agents")) : run("backend"), backendText: backendLabel(inst.backend) } : {}) };
1553
+ return html`${phase === "menu" ? narrowScreen()
1554
+ ? html`<${AgentSheet} name=${name} inst=${inst} current="chat" items=${items} extra=${[favorite, items.find(item => item?.key === "splitChat")].filter(Boolean)} chat=${chat} targetLabel=${inst.display_name || name}
1555
+ verifiedUntil=${auth.st?.state === "verified" ? auth.st.until : null} onUsage=${() => setPhase("usage")} onClose=${dismiss} />`
1556
+ : html`<${Menu} cls="agent-menu" fit=${true} topLayer=${true} ownerKey=${name} context=${{...context, onClose: dismiss}} items=${[favorite, ...items]} label=${t("agentRow.actions", inst.display_name || name)} />` : null}
1557
+ ${phase === "delete" ? html`<${DeleteDialog} name=${name} inst=${inst} onClose=${dismiss}
1558
+ onDeleted=${() => { if (navStore.get().route?.instance === name) navigate("/ui"); }} />` : null}
1559
+ ${phase === "pins" ? html`<${PinsDialog} name=${name} onClose=${dismiss} onJump=${pin => { dismiss(); navigate(`${chatPath(name)}#m=${encodeURIComponent(pin.key)}`); }} />` : null}
1560
+ ${phase === "usage" ? html`<${UsageDialog} owner=${`chat:${name}`} onClose=${dismiss} />` : null}
1561
+ ${phase === "card" && card ? html`<${Dialog} title=${t("card.label", inst.display_name || name)} onClose=${dismiss}><${IdentityCard} name=${name} card=${card} compact=${true} /></${Dialog}>` : null}
1562
+ ${phase === "command" && command ? usesModelMenu(command)
1563
+ ? html`<${CommandCard} name=${name} lease=${lease} />`
1564
+ : html`<${Dialog} title=${inst.display_name || name} onClose=${() => { store.dismissCommand(name); dismiss(); }}><${CommandCard} name=${name} lease=${lease} /></${Dialog}>` : null}`;
1565
+ }
1566
+
1567
+ SidebarChatMenu.contextVersion = Menu.contextVersion === 1 && AgentSheet.sidebarTargetVersion === 1 ? 1 : 0;
@@ -9,7 +9,7 @@ import { html, useEffect, useLayoutEffect, useRef, useState } from "/assets/app-
9
9
  import { t, register, lang } from "/assets/app-i18n.js";
10
10
  import { appStore, useStore } from "/assets/app-store.js";
11
11
  import { useLease } from "/assets/app-ctx.js";
12
- import { PanelHeader, setTitle } from "/assets/app-shell.js";
12
+ import { PanelHeader, setTitle, useCanCreate, retryable } from "/assets/app-shell.js";
13
13
  import { HeaderTools } from "/assets/header-tools.js";
14
14
  import { navigate, renavigate } from "/assets/app-nav.js";
15
15
  import { RuntimePicker, AgentDraftAssistant, NativeAgendToolsHint, tr } from "./agent-runtime.js";
@@ -47,7 +47,7 @@ register("fleet", {
47
47
  hostMemory_elevated: "Host memory pressure: elevated — new agents start one at a time, at least 5 s apart",
48
48
  hostMemory_critical: "Host memory pressure: critical — new agents wait for memory to recover",
49
49
  hostMemory_top: "Largest: {0}", hostMemory_ownerFleet: "the fleet", hostMemory_ownerTmux: "tmux", hostMemory_ownerOther: "not an instance",
50
- title: "Fleet", tasks: "Tasks", schedules: "Schedules", teams: "Teams", org: "Org chart", cache: "Cache", usage: "Usage",
50
+ title: "Fleet", tasks: "Tasks", schedules: "Schedules", teams: "Teams", org: "Org chart", cache: "Cache", usage: "Usage", "host-health": "Host health",
51
51
  docs: "Docs", docsNewTab: "Docs (opens in a new tab)",
52
52
  newSchedule: "New schedule", newTeam: "New team",
53
53
  noSchedules: "No schedules yet", noSchedulesHint: "Automate recurring work with cron.",
@@ -75,7 +75,7 @@ register("fleet", {
75
75
  hostMemory_elevated: "主機記憶體壓力偏高:新的 agent 一次啟動一個,至少間隔 5 秒",
76
76
  hostMemory_critical: "主機記憶體壓力嚴重:新的 agent 會等記憶體恢復再啟動",
77
77
  hostMemory_top: "最大:{0}", hostMemory_ownerFleet: "fleet 本身", hostMemory_ownerTmux: "tmux", hostMemory_ownerOther: "不屬於任何 Agent",
78
- title: "Fleet", tasks: "Tasks", schedules: "排程", teams: "Teams", org: "組織圖", cache: "快取", usage: "用量",
78
+ title: "Fleet", tasks: "Tasks", schedules: "排程", teams: "Teams", org: "組織圖", cache: "快取", usage: "用量", "host-health": "主機狀態",
79
79
  docs: "文件", docsNewTab: "文件(在新分頁開啟)",
80
80
  newSchedule: "新增排程", newTeam: "新增 team",
81
81
  noSchedules: "還沒有排程", noSchedulesHint: "用 cron 自動執行例行工作。",
@@ -105,7 +105,7 @@ const DOCS_SITE = "https://songsid.github.io/AgEnD";
105
105
  export function docsUrl(language = lang()) {
106
106
  return `${DOCS_SITE}${language === "zh-TW" ? "/zh-tw" : ""}/docs/web-guide/`;
107
107
  }
108
- const ICONS = { tasks: "tasks", schedules: "clock", teams: "team", org: "org", cache: "chart", usage: "chart", authorizations: "key" };
108
+ const ICONS = { tasks: "tasks", schedules: "clock", teams: "team", org: "org", cache: "chart", usage: "chart", authorizations: "key", "host-health": "chart" };
109
109
  const BACKENDS = ["claude-code", "codex", "opencode", "kiro-cli", "antigravity", "grok", "muse"];
110
110
 
111
111
  async function api(method, path, body, lease) {
@@ -213,7 +213,9 @@ export function FleetPanel({ route, navKey }) {
213
213
  const tab = route.tab;
214
214
  useEffect(() => { setTitle(`${t("fleet.title")} · ${t(`fleet.${tab}`)}`); }, [tab, navKey]);
215
215
  useEffect(() => { rememberFleetTab(tab); }, [tab]); // #2183: the sidebar's and the phone's Fleet reopen it
216
- const Body = { tasks: TaskBoardTab, schedules: Schedules, teams: Teams, org: Org, cache: Cache, usage: UsageTab, authorizations: ContactAuthorizations }[tab] || TaskBoardTab;
216
+ const admin=useCanCreate();
217
+ const visibleTabs=FLEET_TABS.filter(k=>k!=="host-health"||admin);
218
+ const Body = { tasks: TaskBoardTab, schedules: Schedules, teams: Teams, org: Org, cache: Cache, usage: UsageTab, authorizations: ContactAuthorizations, "host-health":admin?LazyHostHealth:HostAdminRequired }[tab] || TaskBoardTab;
217
219
  // #1685: host memory pressure slowing or holding new agents — shown here, where macOS's routine "elevated" is not a chat notice.
218
220
  const { hostMemory, hostMemoryTop } = useStore(appStore);
219
221
  // #2015: and which processes hold the most, and whose — text only (never chat, #1712).
@@ -221,15 +223,15 @@ export function FleetPanel({ route, navKey }) {
221
223
  const sub = hostMemory ? html`<span class=${`status host-mem ${hostMemory}`} role="status"><span class=${`dot ${hostMemory === "critical" ? "bad" : "warn"}`} aria-hidden="true"></span>${t(`fleet.hostMemory_${hostMemory}`)}${top ? html`<span class="host-mem-top" title=${top}>${top}</span>` : null}</span>` : null;
222
224
  const root = useRef(null);
223
225
  const wide = useTabsInHeader(root), phone = usePhoneWidth();
224
- // The phone's tab row scrolls sideways when it does not fit beside ☰: bring the open tab into view (用量 is the last).
226
+ // Keep the active tab visible after async administrator-only tabs arrive, on either tab row.
225
227
  useLayoutEffect(() => {
226
- const nav = phone ? root.current?.querySelector(".fleet-phone-tabs") : null, on = nav?.querySelector(".active");
228
+ const nav = root.current?.querySelector("nav[data-trust='panel-navigation']"), on = nav?.querySelector(".active");
227
229
  if (!nav || !on) return;
228
230
  const n = nav.getBoundingClientRect(), a = on.getBoundingClientRect();
229
231
  if (a.right > n.right) nav.scrollLeft += a.right - n.right;
230
232
  else if (a.left < n.left) nav.scrollLeft -= n.left - a.left;
231
- }, [phone, tab]);
232
- const tabs = (cls) => html`<nav data-trust="panel-navigation" class=${cls} aria-label=${t("fleet.title")}>${FLEET_TABS.map(k => html`<a key=${k} href=${fleetPath(k)} class=${`seg-item${k === tab ? " active" : ""}`}
233
+ }, [phone, tab, admin, wide]);
234
+ const tabs = (cls) => html`<nav data-trust="panel-navigation" class=${cls} aria-label=${t("fleet.title")}>${visibleTabs.map(k => html`<a key=${k} href=${fleetPath(k)} class=${`seg-item${k === tab ? " active" : ""}`}
233
235
  aria-current=${k === tab ? "page" : undefined}><${Icon} name=${ICONS[k]} size=${16} /><span>${t(`fleet.${k}`)}</span></a>`)}</nav>`;
234
236
  return html`<div ref=${root} data-effect-panel="fleet" class="panel p-fleet">
235
237
  ${/* M-2542: the tabs share the title row (PanelHeader's nav slot, as the instance tabs do) when everything fits
@@ -240,11 +242,22 @@ export function FleetPanel({ route, navKey }) {
240
242
  ${/* M-3166 (Argon 5, the user's OK of round 2): a phone's Fleet is two rows — its tabs in the header's row (☰, then the
241
243
  tabs; the title, search, docs and text size give way: app.css), then the page's own tools. */ ""}
242
244
  <${PanelHeader} title=${t("fleet.title")} sub=${sub} nav=${wide ? tabs("fleet-tabs") : phone ? tabs("seg fleet-phone-tabs") : null}><${DocsLink} /><${HeaderTools} navKey=${navKey} /></${PanelHeader}>
243
- ${wide || phone ? null : tabs("seg")}
244
- <div data-trust="panel-content" class="panel-body"><div class=${`col${tab === "tasks" || tab === "org" || tab === "cache" || tab === "usage" ? " col-wide" : ""}`}><${Body} lease=${lease} /></div></div>
245
+ ${wide || phone ? null : tabs("seg fleet-tabs-row")}
246
+ <div data-trust="panel-content" class="panel-body"><div class=${`col${tab === "tasks" || tab === "org" || tab === "cache" || tab === "usage" || tab === "authorizations" || tab === "host-health" ? " col-wide" : ""}`}><${Body} lease=${lease} /></div></div>
245
247
  </div>`;
246
248
  }
247
249
 
250
+ // Code and data load only for the active administrator tab; a failed import can retry.
251
+ const loadHostHealth=retryable(attempt=>import(attempt?`./host-health.js?retry=${attempt}`:'./host-health.js'));
252
+ function LazyHostHealth({lease}) {
253
+ const [component,setComponent]=useState(null),[error,setError]=useState(false),active=useRef(true),generation=useRef(0);
254
+ const load=()=>{const mine=++generation.current;setError(false);loadHostHealth().then(m=>{if(active.current&&lease.current()&&mine===generation.current)setComponent(()=>m.HostHealth);},()=>{if(active.current&&lease.current()&&mine===generation.current)setError(true);});};
255
+ useEffect(()=>{active.current=true;load();return()=>{active.current=false;generation.current++;};},[lease]);
256
+ return component?html`<${component} lease=${lease}/>`:error?html`<${ErrorState} onRetry=${load}/>`:html`<${Skeleton} lines=${5}/>`;
257
+ }
258
+ function HostAdminRequired(){return html`<section class="card"><h2>${t('fleet.host-health')}</h2><p>${t('hostHealthAccess.admin')}</p></section>`;}
259
+ register('hostHealthAccess',{en:{admin:'Administrator sign-in is required to view host health.'},'zh-TW':{admin:'請以管理員身分登入,才能查看主機狀態。'}});
260
+
248
261
  /** #1844: the project's docs, from the overview — a link out (a new tab, no opener), not a Fleet tab; in front of the shared controls. */
249
262
  function DocsLink() {
250
263
  return html`<a class="btn btn-ghost btn-sm hd-docs" href=${docsUrl()} target="_blank" rel="noopener noreferrer" aria-label=${t("fleet.docsNewTab")} title=${t("fleet.docsNewTab")}>