@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
@@ -21,6 +21,7 @@ import { CompactMeter } from "/assets/usage-meter.js"; // #3321: the Usage pan
21
21
  import { CliProductMark, cliLabel } from "./cli-picker.js";
22
22
  import { identityText } from "./account-identity.js";
23
23
  import { UsageBlock } from "./usage-pool.js"; // AGEND-113: every pool and window an account reports, as the server sends them
24
+ import { credentialText, credentialRequestState, credentialStatusText, credentialVerificationTime, credentialRequestHint, removeClaudeCredential } from "./claude-credentials.js";
24
25
  import { openSignIn, refreshSignIn, signInStore } from "./backend-signin.js";
25
26
  import { capsOf } from "./cli-caps.js";
26
27
  import { toast } from "/assets/ui-toast.js";
@@ -72,7 +73,7 @@ register("accounts", {
72
73
  usedPopTitle: "Agents using this account — choose one to open its settings",
73
74
  },
74
75
  "zh-TW": {
75
- title: "帳號", hint: "這台 AgEnD 主機與已配對電腦上各 CLI 的連接:預設連接與具名帳號(憑證設定檔)、誰在使用,以及每週用量。",
76
+ title: "帳號", hint: "這台 AgEnD 主機與已配對電腦上各 CLI 的連接:預設連接與具名帳號、誰在使用,以及每週用量。",
76
77
  loading: "正在讀取帳號…", failed: "無法讀取帳號。", empty: "這台主機上沒有安裝或被 Agent 使用的 CLI。",
77
78
  def: "預設連接", profile: "帳號「{0}」", state_usable: "已連接", state_not_signed_in: "尚未連接", state_reconnect: "需要重新連接", state_unknown: "未確認",
78
79
  state_not_installed: "未安裝", state_too_old: "版本太舊",
@@ -134,6 +135,7 @@ export function listenAccountsEvent() {
134
135
  const on = appStore.get().streamOn;
135
136
  if (typeof on !== "function") return;
136
137
  // AGEND-133: the same event moves a dashboard install (started, ended): its run is read again with the accounts, on this one listener.
138
+ window.addEventListener("agend-credentials-changed",()=>{void refreshAccounts({fresh:true});void refreshSignIn();});
137
139
  accountsEventOff = on("backend_login", () => { if (accountsStore.get().loaded) { void refreshAccounts({ fresh: true }); void refreshHostInstall(); } }) || (() => {});
138
140
  }
139
141
  let reading = null, started = 0, applied = 0;
@@ -396,36 +398,42 @@ function Row({ cli, row, onMove, onRemove, onSignIn = openSignIn, onSignOut, ope
396
398
  const machine = row.scope && row.scope.kind === "machine" ? row.scope : null;
397
399
  // AGEND-124: the computer's OWN login of a CLI whose Runtime signs it out (Antigravity: `signOutOwn`) is signed out from here too; Claude Code's never is.
398
400
  const manageable = !machine || (row.signIn && (!!row.profile || row.signOutOwn === true));
399
- const canSignOut = manageable && typeof onSignOut === "function" && row.state === "usable" && SIGN_OUT_CLIS.has(row.backend);
400
- const who = identityText(row.identity);
401
+ const managed=!!row.credentialUnavailable||row.credential?.source==="managed";
402
+ const canSignOut = !managed && manageable && typeof onSignOut === "function" && row.state === "usable" && SIGN_OUT_CLIS.has(row.backend);
403
+ const who = managed ? "" : identityText(row.identity);
401
404
  // AGEND-133 (#3521): a CLI that is not installed on the host gets Install on its default row (the server looks up the command; the page sends the CLI's id).
402
405
  const canInstall = !machine && !row.profile && row.state === "not_installed" && !!row.install;
403
406
  const installState = useStore(hostInstallStore);
404
407
  const installRun = !machine && !row.profile ? runFor(installState, row.backend) : null;
405
408
  const installingNow = !!installRun && installRun.phase === "running";
406
409
  // Every pool and every window the account reports, as the server gives them (accounts-view.ts `accountUsage`); the page lays them out, it does not pick.
407
- const usageGroups = Array.isArray(row.usageGroups) ? row.usageGroups.filter((g) => g && Array.isArray(g.windows) && g.windows.length) : [];
410
+ const usageGroups = !managed && Array.isArray(row.usageGroups) ? row.usageGroups.filter((g) => g && Array.isArray(g.windows) && g.windows.length) : [];
408
411
  const why = machine && machine.readOnlyReason && !MACHINE_LEVEL.has(machine.readOnlyReason) ? reasonText(machine.readOnlyReason, machine.name, cliLabel(row.backend), (capsOf(row.backend) && capsOf(row.backend).structuredMinVersion) || "") : "";
409
412
  // Four layers in one box: the title bar (name, state, default tag · the buttons), the meta bar (who, used by), the usage block (every pool and window it reports) and Keep connection alive as the box's foot.
410
413
  return html`<div class="s-row s-account-row" data-account=${row.profile || "default"}>
411
414
  <div class="s-account-title-bar">
412
415
  <div class="s-account-title-left"><strong>${rowName(row)}</strong>
413
- <span class=${`tag s-auth-state is-${row.state || "unknown"}`}>${installingNow ? hostInstallText(installRun.mode === "update" ? "updating" : "installing") : tx(row.reconnect ? "state_reconnect" : `state_${row.state || "unknown"}`)}</span>
416
+ <span class=${`tag s-auth-state is-${managed?(credentialRequestState(row.credential)==="verified"?"usable":credentialRequestState(row.credential)==="needs-replacement"?"not_signed_in":"unknown"):row.state || "unknown"}`}>${managed?(row.credential?.kind?credentialStatusText(row.credential):tx("state_not_signed_in")):installingNow ? hostInstallText(installRun.mode === "update" ? "updating" : "installing") : tx(row.reconnect ? "state_reconnect" : `state_${row.state || "unknown"}`)}</span>
414
417
  ${row.usedBy.fleetDefault && cli.profiles ? html`<span class="tag s-account-default-tag">${machine ? tx("machineDefaultTag") : tx("fleetDefaultTag")}</span>` : null}</div>
415
418
  ${readOnly ? null : html`<span class="s-actions">
416
419
  ${canInstall ? html`<${InstallButton} backend=${row.backend} blocked=${running} />` : null}
417
- ${row.signIn && typeof onSignIn === "function" ? html`<button type="button" class=${row.state === "not_signed_in" ? "btn btn-sm btn-primary" : "btn btn-sm"} disabled=${running} onClick=${() => onSignIn({ backend: row.backend, ...(row.profile ? { profile: row.profile } : {}), ...(machine ? { machine } : {}) })}>${row.state === "usable" ? tx("signInAgain") : tx("signIn")}</button>` : null}
420
+ ${row.signIn && typeof onSignIn === "function" ? html`<button type="button" class=${row.state === "not_signed_in" ? "btn btn-sm btn-primary" : "btn btn-sm"} disabled=${running} onClick=${() => onSignIn({ backend: row.backend, ...(row.profile ? { profile: row.profile } : {}), ...(machine ? { machine } : {}),...(managed?{method:row.credential?.kind==="setup-token"?"oauth":"api"}:{}) })}>${row.credential?.kind?credentialText("replace"):row.state === "usable" ? tx("signInAgain") : tx("signIn")}</button>` : null}
418
421
  ${!machine && cli.profiles && row.state !== "not_signed_in" && row.state !== "not_installed" && typeof onMove === "function" ? html`<button type="button" class="btn btn-sm" onClick=${() => onMove(row)}>${tx("moveHere")}</button>` : null}
419
422
  ${canSignOut && !machine && !row.profile && row.signIn ? html`<button type="button" class="btn btn-sm s-account-switch" disabled=${running} onClick=${() => onSignOut(row, "switch")}>${manageWords.switchAccount()}</button>` : null}
423
+ ${managed&&row.credential?.kind?html`<button type="button" class="btn btn-sm danger" disabled=${running} onClick=${()=>removeClaudeCredential(row.profile)}>${credentialText("remove")}</button>`:null}
420
424
  ${canSignOut ? html`<button type="button" class="btn btn-sm btn-ghost s-account-signout" disabled=${running} onClick=${() => onSignOut(row, "signout")}>${manageWords.signOut()}</button>` : null}
421
- ${manageable && row.profile && typeof onRemove === "function" ? html`<button type="button" class="btn btn-sm btn-ghost danger s-account-remove" onClick=${() => onRemove(row)}>${manageWords.remove()}</button>` : null}
425
+ ${manageable && row.profile && typeof onRemove === "function" ? html`<button type="button" class="btn btn-sm danger s-account-remove" onClick=${() => onRemove(row)}>${manageWords.remove()}</button>` : null}
422
426
  </span>`}
423
427
  </div>
424
428
  <div class="s-account-meta-bar">
429
+ ${managed?html`<span class="tag">${row.credential?.kind?credentialText(row.credential.kind==="setup-token"?"tokenTag":"apiTag"):tx("state_not_signed_in")}</span>`:null}
430
+ ${managed&&credentialVerificationTime(row.credential)?html`<small data-credential-verified-at>${credentialVerificationTime(row.credential)}</small>`:null}
425
431
  ${who ? html`<span class="tag s-account-identity">${who}</span>` : null}
426
432
  <${UsedBy} row=${row} label=${usedText(row)} openAgent=${openAgent} />
427
433
  ${machine ? html`<small class="s-account-usage is-none" title=${tx("machineNoUsageHint")}>${tx("machineNoUsage")}</small>` : null}
428
434
  </div>
435
+ ${managed?html`<p class="note">${credentialText("usage")}</p>`:null}
436
+ ${managed&&credentialRequestHint(row.credential)?html`<p class="note" data-credential-request-hint>${credentialRequestHint(row.credential)}</p>`:null}
429
437
  ${usageGroups.length ? html`<${UsageBlock} groups=${usageGroups} stale=${row.usageStale === true} staleInfo=${row.usageStaleInfo} tagOf=${usageTag} label=${tx("usageLabel")} staleText=${tx("winStale")} />` : null}
430
438
  ${why ? html`<p class="note s-account-why">${why}</p>` : null}
431
439
  ${canInstall && !installRun ? html`<p class="note s-account-why">${hostInstallText("notInstalled")}</p>` : null}
@@ -434,7 +442,7 @@ function Row({ cli, row, onMove, onRemove, onSignIn = openSignIn, onSignOut, ope
434
442
  ${!machine && !row.profile && !readOnly ? html`<${VersionLine} row=${row} label=${cliLabel(row.backend)} blocked=${running} />` : null}
435
443
  ${!machine && !row.profile ? html`<${HostInstallRun} backend=${row.backend} label=${cliLabel(row.backend)} />` : null}
436
444
  ${!readOnly && !row.signIn && row.hostCommand ? html`<details class="s-host-cli-help"><summary>${machine ? tx("machineCommand") : tx("hostCommand")}</summary><p class="note">${machine ? tx("machineCommandHint", machine.name) : tx("hostCommandHint")}</p>${machine ? html`<p class="s-host-cli-command"><code>${row.hostCommand}</code></p>` : null}</details>` : null}
437
- ${!readOnly && row.keepAlive && row.state !== "not_installed" && (!row.scope || row.scope.kind === "host") ? html`<${KeepAliveControl} row=${row} onSaved=${() => refreshAccounts({ fresh: true })} />` : null}
445
+ ${!managed && !readOnly && row.keepAlive && row.state !== "not_installed" && (!row.scope || row.scope.kind === "host") ? html`<${KeepAliveControl} row=${row} onSaved=${() => refreshAccounts({ fresh: true })} />` : null}
438
446
  </div>`;
439
447
  }
440
448
 
@@ -5,6 +5,7 @@
5
5
  // session that started a sign-in gets its terminal link, access code and device code; every other admin page only that
6
6
  // one runs, on which device, and may cancel it. The stream's `backend_login` event carries nothing — it only says to
7
7
  // read again. Starting is two steps, as in chat: check (the server keeps what it found) and start (with its id).
8
+ import { openClaudeCredentials } from "./claude-credentials.js";
8
9
  import { html, useEffect, useState, useRef } from "/assets/app-html.js";
9
10
  import { t, register, lang, onLang } from "/assets/app-i18n.js";
10
11
  import { appStore, createStore, useStore } from "/assets/app-store.js";
@@ -231,7 +232,8 @@ export function installerSignInBackends(search) {
231
232
  export const profileSignInEndpoint = (backend, profile) => `/ui/browser-backend-signins?backend=${encodeURIComponent(backend)}&profile=${encodeURIComponent(profile)}`;
232
233
 
233
234
  /** Open the dialog for one login (a backend's default one, or a credential profile): the same dialog for both. */
234
- export function openSignIn({ backend, profile }) {
235
+ export function openSignIn({ backend, profile, method, machine, subscription = false }) {
236
+ if(backend === "claude-code" && !machine && !subscription)return openClaudeCredentials({backend,profile,initial:method||"subscription",continueSubscription:()=>openSignIn({backend,profile,subscription:true})});
235
237
  const caps = capsOf(backend);
236
238
  if (caps?.structuredSignIn && (!profile || caps.structuredNamedSignIn)) showDialog(BrowserSignInDialog, { backend, ...(profile ? { profile } : {}) });
237
239
  else showDialog(SignInDialog, { backend, ...(profile ? { profile } : {}) });
@@ -5,6 +5,8 @@
5
5
 
6
6
  /** The commands, in the palette's order. `arg`: the argument hint ("" = none; [..] optional, <..> required). */
7
7
  export const CHAT_COMMANDS = [
8
+ { name: "sysinfo", arg: "" },
9
+ { name: "status", arg: "" },
8
10
  { name: "ctx", arg: "" },
9
11
  { name: "compact", arg: "[instructions]" },
10
12
  { name: "clear", arg: "" },
@@ -1,17 +1,33 @@
1
1
  // #3637: a bounded data handoff between exact same-origin windows, never an authentication channel.
2
2
  import { isSafeInstanceName, chatPath } from "/assets/app-route.js";
3
- const channel = "agend-chat-popout-v1";
4
- const message = (type, fields) => ({ channel, type, ...fields });
5
- const valid = data => !!data && data.channel === channel && typeof data.type === "string";
3
+ const protocols = {
4
+ chat: { channel: "agend-chat-popout-v1", payload: "draft", presentation: "popout" },
5
+ preview: { channel: "agend-preview-popout-v1", payload: "locator", presentation: "preview" },
6
+ };
7
+ const message = (wire, type, fields) => ({ channel: wire.channel, type, ...fields });
8
+ const valid = (wire, data) => !!data && data.channel === wire.channel && typeof data.type === "string";
6
9
  export const POPOUT_DEADLINE_MS = 15_000;
10
+ function secureNonce(crypto) {
11
+ try {
12
+ if (typeof crypto?.randomUUID === "function") return crypto.randomUUID();
13
+ if (typeof crypto?.getRandomValues !== "function") return null;
14
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
15
+ bytes[6] = (bytes[6] & 15) | 64; bytes[8] = (bytes[8] & 63) | 128;
16
+ const hex = [...bytes].map(n => n.toString(16).padStart(2, "0")).join("");
17
+ return hex.slice(0, 8) + "-" + hex.slice(8, 12) + "-" + hex.slice(12, 16) + "-" + hex.slice(16, 20) + "-" + hex.slice(20);
18
+ } catch { return null; }
19
+ }
20
+
7
21
 
8
- export function createPopoutTransport({ win = window, scope, notify = () => {}, now = () => performance.now() }) {
22
+ export function createPopoutTransport({ win = window, scope, notify = () => {}, now = () => performance.now(), kind = "chat" }) {
23
+ const wire = Object.hasOwn(protocols, kind) ? protocols[kind] : null;
9
24
  let alive = true, pending = null;
10
25
  const cancel = reason => { if (pending) pending.finish(reason); };
11
26
  function open({ name, payload, current, complete }) {
12
- if (!alive || !scope || !isSafeInstanceName(name) || !current()) return false;
27
+ if (!wire || !alive || !scope || !isSafeInstanceName(name) || !current()) return false;
13
28
  if (pending) { notify("busy"); return false; }
14
- const origin = win.location.origin, nonce = win.crypto.randomUUID(), started = now();
29
+ const origin = win.location.origin, nonce = secureNonce(win.crypto), started = now();
30
+ if (!nonce) { notify("retained"); return false; }
15
31
  let child = null, offered = false, done = false;
16
32
  const time = () => now() >= started && now() < started + POPOUT_DEADLINE_MS;
17
33
  const finish = reason => {
@@ -21,13 +37,13 @@ export function createPopoutTransport({ win = window, scope, notify = () => {},
21
37
  if (reason) notify(reason);
22
38
  };
23
39
  const receive = event => {
24
- if (done || !child || event.source !== child || event.origin !== origin || !valid(event.data)) return;
40
+ if (done || !child || event.source !== child || event.origin !== origin || !valid(wire, event.data)) return;
25
41
  const data = event.data;
26
42
  if (data.name !== name || data.scope !== scope) return;
27
43
  if (!time() || child.closed || !current()) { finish("retained"); return; }
28
44
  if (data.type === "ready" && !offered) {
29
45
  offered = true;
30
- try { child.postMessage(message("draft", { name, scope, nonce, payload }), origin); } catch { finish("retained"); }
46
+ try { child.postMessage(message(wire, wire.payload, { name, scope, nonce, payload }), origin); } catch { finish("retained"); }
31
47
  } else if (offered && data.nonce === nonce && ["received", "refused"].includes(data.type)) {
32
48
  // Consume before invoking any callback; a duplicate ACK cannot close a later pane.
33
49
  finish();
@@ -39,7 +55,7 @@ export function createPopoutTransport({ win = window, scope, notify = () => {},
39
55
  const timer = setInterval(() => { if (!time() || child?.closed || !current()) finish("retained"); }, 100);
40
56
  pending = { finish }; win.addEventListener("message", receive);
41
57
  // This must stay in the click stack. noopener would return null even after a successful open.
42
- try { child = win.open(`${chatPath(name)}?presentation=popout`, "_blank", "popup,width=760,height=800"); } catch { /* blocked */ }
58
+ try { child = win.open(`${chatPath(name)}?presentation=${wire.presentation}`, "_blank", "popup,width=760,height=800"); } catch { /* blocked */ }
43
59
  if (!child) { finish("blocked"); return false; }
44
60
  return true;
45
61
  }
@@ -47,9 +63,10 @@ export function createPopoutTransport({ win = window, scope, notify = () => {},
47
63
  return { open, cancel, close() { alive = false; cancel(); win.removeEventListener("pagehide", hide); } };
48
64
  }
49
65
 
50
- export function receivePopoutDraft({ win = window, name, scope, ready, current, accept, notify = () => {}, now = () => performance.now() }) {
66
+ export function receivePopoutDraft({ win = window, name, scope, ready, current, accept, notify = () => {}, now = () => performance.now(), kind = "chat" }) {
67
+ const wire = Object.hasOwn(protocols, kind) ? protocols[kind] : null;
51
68
  const parent = win.opener, origin = win.location.origin, started = now();
52
- if (!parent || !scope || !isSafeInstanceName(name)) return () => {};
69
+ if (!wire || !parent || !scope || !isSafeInstanceName(name)) return () => {};
53
70
  let sent = false, done = false;
54
71
  const time = () => now() >= started && now() < started + POPOUT_DEADLINE_MS;
55
72
  const finish = () => {
@@ -58,23 +75,36 @@ export function receivePopoutDraft({ win = window, name, scope, ready, current,
58
75
  };
59
76
  const receive = event => {
60
77
  const data = event.data;
61
- if (done || !sent || event.source !== parent || event.origin !== origin || !valid(data) || data.type !== "draft"
78
+ if (done || !sent || event.source !== parent || event.origin !== origin || !valid(wire, data) || data.type !== wire.payload
62
79
  || data.name !== name || data.scope !== scope || typeof data.nonce !== "string" || !/^[0-9a-f-]{36}$/.test(data.nonce)) return;
63
- const allowed = time() && current() && ready();
64
- // One offer only, even when validation fails. Never overwrite later typing with a replay.
80
+ const stillCurrent = () => time() && current() && ready();
81
+ const allowed = stillCurrent();
82
+ // Consume before any asynchronous history read; no replay can initiate another read.
65
83
  finish();
66
- let accepted = false;
67
- try { accepted = allowed && accept(data.payload) === true; } catch { /* malformed/unclonable local data never becomes a send */ }
68
- try { parent.postMessage(message(accepted ? "received" : "refused", { name, scope, nonce: data.nonce }), origin); } catch { /* parent keeps its original */ }
69
- if (!accepted) notify("retained");
84
+ const answer = result => {
85
+ const accepted = result === true && (kind !== "preview" || stillCurrent());
86
+ try { parent.postMessage(message(wire, accepted ? "received" : "refused", { name, scope, nonce: data.nonce }), origin); } catch { /* parent keeps its original */ }
87
+ if (!accepted) notify("retained");
88
+ };
89
+ try {
90
+ const result = allowed && (kind === "preview" ? accept(data.payload, stillCurrent) : accept(data.payload));
91
+ if (kind === "preview" && result && typeof result.then === "function") result.then(answer, () => answer(false));
92
+ else answer(result);
93
+ } catch { answer(false); }
94
+
70
95
  };
71
96
  const tick = () => {
72
97
  if (!time() || !current() || parent.closed) { finish(); return; }
73
98
  if (!sent && ready()) {
74
99
  sent = true;
75
- try { parent.postMessage(message("ready", { name, scope }), origin); } catch { finish(); }
100
+ try { parent.postMessage(message(wire, "ready", { name, scope }), origin); } catch { finish(); }
76
101
  }
77
102
  };
78
103
  const timer = setInterval(tick, 50); win.addEventListener("message", receive); win.addEventListener("pagehide", finish); tick();
79
104
  return finish;
80
105
  }
106
+
107
+
108
+ // Preview uses the same bounded exact-window protocol, with a separate channel and asynchronous own-history validation.
109
+ export const createPreviewPopoutTransport = opts => createPopoutTransport({ ...opts, kind: "preview" });
110
+ export const receivePreviewPopout = opts => receivePopoutDraft({ ...opts, kind: "preview" });
@@ -1,7 +1,7 @@
1
1
  // #3637: optional presentation/data only. Every new window boots the existing authenticated chat independently.
2
2
  import { appStore, guestPage } from "/assets/app-store.js";
3
3
  import { agentRoute } from "/assets/chat-workspace-model.js";
4
- import { parseRoute } from "/assets/app-route.js";
4
+ import { parseRoute, chatPath, isSafeInstanceName } from "/assets/app-route.js";
5
5
  import { Shell, shellStore } from "/assets/app-shell.js";
6
6
  import { register, t } from "/assets/app-i18n.js";
7
7
  import { toast } from "/assets/ui-toast.js";
@@ -16,6 +16,20 @@ register("chatPopout", {
16
16
  export const popoutText = key => t(`chatPopout.${key}`);
17
17
  const supported = chat => chat?.popoutDraftVersion === 1 && chat.popoutDraftReady?.() === true && Shell.popoutVersion === 1
18
18
  && getComputedStyle(document.documentElement).getPropertyValue("--chat-popout-version").trim() === "1";
19
+ /** A fresh Office chat is not a pane transfer: leave the Office and every draft owner untouched. */
20
+ export function openOfficeChatWindow(name, { win = window, notify = reason => toast(popoutText(reason), false) } = {}) {
21
+ const boot = globalThis.document?.body?.dataset, auth = globalThis.AgendAuth, app = appStore.get();
22
+ if (guestPage() || boot?.chatWorkspace !== "1" || !boot.chatLayoutScope || !app.ready
23
+ || typeof auth?.sessionEnded !== "function" || auth.sessionEnded() || !isSafeInstanceName(name)
24
+ || !app.instances.some(it => it.name === name)) return false;
25
+ let child;
26
+ // Keep the normal popup handle for reliable blocked-window feedback, then immediately detach the opener.
27
+ try { child = win.open(`${chatPath(name)}?presentation=popout`, "_blank", "popup,width=760,height=800"); } catch { /* blocked */ }
28
+ if (!child) { notify("blocked"); return false; }
29
+ try { child.opener = null; } catch { /* the browser may already have detached it */ }
30
+ return true;
31
+ }
32
+
19
33
  export function createPanePopout({ scope, chat, win = window, notify = reason => toast(popoutText(reason), false) }) {
20
34
  if (!supported(chat) || guestPage() || !scope) return null;
21
35
  let alive = true;
@@ -717,7 +717,7 @@ export function createChatStore(deps) {
717
717
  const follow = r && r.follow && r.follow.kind === "compact" ? r.follow : null;
718
718
  showCommand(target, r && r.choices ? { command, busy: false, choices: r.choices }
719
719
  : r && r.error ? { command, busy: false, error: r.error, ...(opts.action ? { choices: pending.choices } : {}) }
720
- : { command, busy: false, text: (r && r.text) || "", ...(r && r.sent === true ? { sent: true } : {}), ...(follow ? { compact: follow.id ? "running" : "unknown", watch: follow.id } : {}) });
720
+ : { command, busy: false, text: (r && r.text) || "", ...(r && r.report ? { report: r.report } : {}), ...(r && r.sent === true ? { sent: true } : {}), ...(follow ? { compact: follow.id ? "running" : "unknown", watch: follow.id } : {}) });
721
721
  changed(target);
722
722
  }
723
723
  // Board 003648ac: an answer the server marks `sent` leaves by itself; a sent /compact says "compacting…" until the
@@ -0,0 +1,123 @@
1
+ import { ClaudeTokenFetch } from "./claude-setup-token.js";
2
+ // Local verified credential management; no credential is read back or persisted by this page.
3
+ import { html, useEffect, useRef, useState } from "/assets/app-html.js";
4
+ import { register, t, lang } from "/assets/app-i18n.js";
5
+ import { showDialog, closeDialog } from "/assets/app-shell.js";
6
+ import { Dialog } from "/assets/ui-dialog.js";
7
+ import { confirmDialog } from "/assets/ui-confirm.js";
8
+ import { Icon } from "/assets/ui-icons.js";
9
+ import { Skeleton, ErrorState } from "/assets/ui-states.js";
10
+ import { toast } from "/assets/ui-toast.js";
11
+ register("claudeCredentials", {
12
+ en: {
13
+ title: "Connect Claude Code", profile: "Account", default: "Default connection",
14
+ help: "What’s this?", method: "Connection method", subscription: "Subscription login", oauth: "Token from setup-token", api: "Anthropic API key",
15
+ subscriptionHint: "Continue to Claude’s official sign-in page.",
16
+ oauthHint: "Paste a subscription token you already obtained with setup-token. This uses your Claude subscription; subscription limits still apply.",
17
+ apiHint: "Create a key in Anthropic Console. API usage is billed separately from a Claude subscription.",
18
+ tokenLabel: "Setup token", apiLabel: "API key", paste: "Paste the credential here", local: "Only on this AgEnD computer, with a verified administrator session.",
19
+ saved: "Stored encrypted. This does not confirm that Anthropic accepts it. No model request is made on Save.",
20
+ runtime: "Same-user access", runtimeHint: "An agent running as the same OS user can still obtain the credential at runtime. Encryption is not isolation.",
21
+ cancel: "Cancel", close: "Close", continue: "Continue to sign in", save: "Save credential", done: "Saved · not verified. No model request was made.",
22
+ usage: "No subscription meters for pasted credentials. Local usage, when available, is an estimate.",
23
+ replace: "Replace credential", replacement: "Replacement keeps this account’s name and assignments. A confirmation lists the agents that must restart. If format or storage checks fail, the earlier credential stays unchanged.",
24
+ remove: "Remove saved credential", removeTitle: "Remove this credential?", removeHint: "The account and conversation stay. Move or stop its agents first. This removes only AgEnD’s copy; revoke the credential at Anthropic to invalidate it elsewhere.",
25
+ verified: "Verified", verifiedAt: "Verified at {0}", needsReplacement: "Needs replacement", requestUnknown: "Unknown · request not confirmed", authHint: "The last request was refused (401/403). Replace the saved credential, then continue normal work.", requestUnknownHint: "The last request could not be confirmed. A connection error does not mean the credential is invalid.",
26
+ tokenTag: "Subscription token", apiTag: "API key · pay as you go", notChecked: "Saved · not verified", restriction: "Open this computer’s local dashboard to paste, replace or remove a credential. Public links are refused, even for a verified administrator."
27
+ },
28
+ "zh-TW": {
29
+ title: "連接 Claude Code", profile: "帳號", default: "預設連接",
30
+ help: "這是什麼?", method: "連接方式", subscription: "訂閱帳號登入", oauth: "貼上 setup-token", api: "貼上 Anthropic API key",
31
+ subscriptionHint: "前往 Claude 官方網站完成登入。",
32
+ oauthHint: "貼上你已透過 setup-token 取得的訂閱 token。這會使用 Claude 訂閱,仍受訂閱額度限制。",
33
+ apiHint: "在 Anthropic Console 建立 API key。API 用量另行計費,不包含在 Claude 訂閱中。",
34
+ tokenLabel: "Setup token", apiLabel: "API key", paste: "在這裡貼上憑證", local: "僅限在這台 AgEnD 電腦,以已驗證的管理員身分操作。",
35
+ saved: "加密儲存不代表 Anthropic 已接受這組憑證。按儲存不會送出模型請求。",
36
+ runtime: "同一使用者的存取範圍", runtimeHint: "以同一個作業系統使用者執行的 Agent,仍可能在執行時取得憑證。加密不代表隔離。",
37
+ cancel: "取消", close: "關閉", continue: "繼續登入", save: "儲存憑證", done: "已儲存・尚未驗證,沒有送出模型請求。",
38
+ usage: "貼上的憑證不顯示訂閱額度表;若有本機用量紀錄,會標明是估計值。",
39
+ replace: "替換憑證", replacement: "替換後保留帳號名稱與 Agent 指派。確認畫面會列出需要重新啟動的 Agent;新憑證若未通過儲存檢查,原憑證保持不變。",
40
+ remove: "移除儲存的憑證", removeTitle: "移除這組憑證?", removeHint: "保留帳號與對話。請先移走或停止使用它的 Agent。這只會移除 AgEnD 的副本;如要讓其他地方也無法使用,請到 Anthropic 撤銷憑證。",
41
+ verified: "已驗證", verifiedAt: "驗證時間:{0}", needsReplacement: "需要替換憑證", requestUnknown: "未知・尚未確認請求", authHint: "上次請求被拒絕,錯誤碼:401/403。請替換儲存的憑證,再繼續原本的工作。", requestUnknownHint: "無法確認上次請求。連線錯誤不代表憑證失效。",
42
+ tokenTag: "訂閱 token", apiTag: "API key · 按量付費", notChecked: "已儲存 · 尚未驗證", restriction: "請在這台電腦的本機儀表板貼上、替換或移除憑證。公開連結一律拒絕,即使已驗證的管理員也一樣。"
43
+ }
44
+ });
45
+
46
+ register("claudeCredentialErrors", {
47
+ en:{local:"Open the local dashboard on the AgEnD computer and verify your administrator session, then try again. Public links cannot manage saved credentials.",inUse:"This account is in use. Wait for its agents to finish, or stop paused sessions, then try again. No credential was changed.",conflict:"This account changed in another session. Reload its connection details and try again.",invalid:"Enter a single-line credential between 16 and 16,384 bytes.",failed:"The credential could not be saved. The previous credential is unchanged; retry from the local dashboard.",read:"Could not read this account’s connection details.",retry:"Retry",restart:"Agents using this account; running agents restart only when idle:",stop:"Agents using this account; running agents stop only when idle:",pending:"Saved, but these agents still need a restart from their page:",confirm:"Save and restart idle agents",removed:"Saved credential removed. The account and conversation remain.",managedPolicy:"Organization-managed Claude settings are not supported."},
48
+ "zh-TW":{local:"請在執行 AgEnD 的電腦開啟本機儀表板、驗證管理員身分後再試。公開連結不能管理保存的憑證。",inUse:"這個帳號正在使用中。請等 Agent 完成工作,或先停止暫停的工作階段後再試;憑證尚未變更。",conflict:"其他工作階段已變更這個帳號。請重新讀取連接資訊後再試。",invalid:"請輸入單行憑證,長度須為 16 至 16,384 位元組。",failed:"無法儲存憑證。原憑證保持不變,請從本機儀表板重試。",read:"無法讀取這個帳號的連接資訊。",retry:"重試",restart:"使用這個帳號的 Agent;執行中的 Agent 只會在空閒時重啟:",stop:"使用這個帳號的 Agent;執行中的 Agent 只會在空閒時停止:",pending:"已儲存,以下 Agent 仍需從各自的頁面重新啟動:",confirm:"儲存並重啟空閒的 Agent",removed:"已移除保存的憑證,帳號與對話仍保留。",managedPolicy:"不支援由組織管理的 Claude 設定。"}
49
+ });
50
+ export const credentialText=(key,...args)=>t("claudeCredentials."+key,...args);
51
+ export function credentialRequestState(metadata){
52
+ if(!metadata?.kind)return "not-connected";
53
+ if(metadata.state==="verified")return typeof metadata.verifiedAt==="string"&&Number.isFinite(Date.parse(metadata.verifiedAt))?"verified":"unknown";
54
+ return ["needs-replacement","unknown"].includes(metadata.state)?metadata.state:"saved-unverified";
55
+ }
56
+ export function credentialStatusText(metadata){const state=credentialRequestState(metadata);return credentialText(state==="verified"?"verified":state==="needs-replacement"?"needsReplacement":state==="unknown"?"requestUnknown":"notChecked");}
57
+ export function credentialVerificationTime(metadata){return credentialRequestState(metadata)==="verified"?credentialText("verifiedAt",new Intl.DateTimeFormat(lang()==="zh-TW"?"zh-TW":"en",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(new Date(metadata.verifiedAt))):null;}
58
+ export function credentialRequestHint(metadata){const state=credentialRequestState(metadata);return state==="needs-replacement"?credentialText("authHint"):state==="unknown"?credentialText("requestUnknownHint"):null;}
59
+
60
+ const e=key=>t("claudeCredentialErrors."+key);
61
+ export const credentialError=code=>{const key=String(code||"").replace(/-/g,"_");return e(["credential_local_verified_required","credential_session_changed","unauthorized","forbidden"].includes(key)?"local":key==="credential_in_use"?"inUse":key==="credential_conflict"?"conflict":key==="credential_invalid"||key==="credential_body_bound"?"invalid":"failed");};
62
+ export function credentialHelpUrl(method){return "https://songsid.github.io/AgEnD/"+(lang()==="zh-TW"?"zh-tw/":"")+"docs/claude-credentials/#"+method;}
63
+ async function api(profile,method="GET",body){
64
+ const path="/ui/claude-credentials"+(method==="GET"&&profile?"?profile="+encodeURIComponent(profile):"");
65
+ try{const r=await fetch(path,{method,credentials:"same-origin",cache:"no-store",...(body?{headers:{"Content-Type":"application/json"},body:JSON.stringify(body)}:{})});const result=await r.json();return {ok:r.ok,...result};}
66
+ catch{return {ok:false,error:"credential_unavailable"};}
67
+ }
68
+ async function loadConnection(profile){
69
+ const result=await api(profile);if(result.ok)return {...result,local:true};
70
+ if(result.error!=="credential_local_verified_required")return result;
71
+ try{const response=await fetch("/ui/accounts",{credentials:"same-origin",cache:"no-store"});if(!response.ok)return result;
72
+ const view=await response.json(),row=view.clis?.find(cli=>cli.backend==="claude-code")?.rows?.find(row=>row.scope?.kind==="host"&&(row.profile||null)===(profile||null));
73
+ if(!row||row.credentialUnavailable)return result;return {ok:true,local:false,credential:row.credential||null};
74
+ }catch{return result;}
75
+ }
76
+ const changed=()=>window.dispatchEvent(new Event("agend-credentials-changed"));
77
+ export function openClaudeCredentials(options){return showDialog(ClaudeCredentialsDialog,options);}
78
+ export async function removeClaudeCredential(profile){
79
+ const result=await api(profile);if(!result.ok){toast(credentialError(result.error));return;}
80
+ if(!await confirmDialog({title:credentialText("removeTitle"),message:[profile||credentialText("default"),credentialText("removeHint"),...(result.consumers?.users?.length?[e("stop"),...result.consumers.users]:[])].join("\n\n"),confirmLabel:credentialText("remove"),danger:true}))return;
81
+ const saved=await api(profile,"DELETE",{profile:profile||null,revision:result.credential?.revision||0,confirm:true,...(result.consumers?.users?.length?{restart:true,consumersRevision:result.consumers.revision}:{})});
82
+ if(!saved.ok){toast(credentialError(saved.error));return;}changed();toast(e("removed"),true);
83
+ }
84
+ export function ClaudeCredentialsDialog({profile,initial="subscription",continueSubscription,onClose}){
85
+ const [method,setMethod]=useState(initial),[read,setRead]=useState(null),[busy,setBusy]=useState(false),[error,setError]=useState(""),[done,setDone]=useState(false),[pending,setPending]=useState([]),[hasInput,setHasInput]=useState(false),input=useRef(null),active=useRef(true);
86
+ const inputRef=useRef(node=>{if(input.current&&input.current!==node)input.current.value="";input.current=node;});
87
+ const close=()=>{if(input.current)input.current.value="";active.current=false;(onClose||closeDialog)();};
88
+ const load=()=>{setRead(null);void loadConnection(profile).then(result=>{if(active.current)setRead(result);});};
89
+ useEffect(()=>{active.current=true;load();return()=>{active.current=false;if(input.current)input.current.value="";};},[profile]);
90
+ const save=async()=>{
91
+ setError("");if(!read?.ok){setError(credentialError(read?.error));return;}
92
+ if(!read.local){
93
+ // Public/native sign-in retains its existing flow; changing a managed source remains local-only.
94
+ if(method==="subscription"&&read.credential?.source!=="managed"){close();continueSubscription?.();return;}
95
+ setError(e("local"));return;
96
+ }
97
+ const value=input.current?.value||"";
98
+ if(method!=="subscription"&&(!value||/\s/.test(value)||new TextEncoder().encode(value).length<16||new TextEncoder().encode(value).length>16384)){setError(e("invalid"));return;}
99
+ setBusy(true);
100
+ try{
101
+ const consumers=read.consumers;
102
+ if(consumers?.users?.length&&!await confirmDialog({title:d(method==="subscription"?"continue":"replace"),message:[d("replacement"),e("restart"),...consumers.users].join("\n\n"),confirmLabel:e("confirm")}))return;
103
+ if(!active.current)return;
104
+ const result=await api(profile,method==="subscription"?"POST":"PUT",{profile:profile||null,revision:read.credential?.revision||0,...(consumers?.users?.length?{restart:true,consumersRevision:consumers.revision}:{}),...(method==="subscription"?{source:"subscription",confirm:true}:{kind:method==="oauth"?"setup-token":"api-key",value})});
105
+ if(!active.current)return;
106
+ if(!result.ok){setError(credentialError(result.error));return;}
107
+ if(input.current)input.current.value="";setHasInput(false);changed();setPending(result.pending||[]);setRead({...read,ok:true,credential:result.credential});
108
+ if(method==="subscription"){close();continueSubscription?.();}else setDone(true);
109
+ }finally{if(active.current)setBusy(false);}
110
+ };
111
+ const d=credentialText;
112
+ return html`<${Dialog} title=${d(initial==="subscription"?"title":"replace")} cls="credential-dialog" busy=${busy} onClose=${close} actions=${html`<button type="button" class="btn" disabled=${busy} onClick=${close}>${d(done?"close":"cancel")}</button><button type="button" class="btn btn-primary" disabled=${busy||!read?.ok||done||(method!=="subscription"&&(!hasInput||!read.local))} onClick=${save}>${d(method==="subscription"?"continue":"save")}</button>`}>
113
+ <p><strong>${d("profile")}: ${profile||d("default")}</strong></p>
114
+ <fieldset class="field" disabled=${busy}><legend>${d("method")}</legend><div class="checks">${["subscription","oauth","api"].map(kind=>html`<div class="credential-method-row"><label class="check"><input type="radio" name="claude-credential-method" value=${kind} checked=${method===kind} onChange=${()=>{if(input.current)input.current.value="";setMethod(kind);setHasInput(false);setDone(false);setError("");}} /><span>${d(kind)}</span></label><a class="btn btn-ghost credential-help" data-trust="navigation" href=${credentialHelpUrl(kind)} target="_blank" rel="noopener noreferrer">${d("help")}<${Icon} name="external" size=${14} /></a></div>`)}</div></fieldset>
115
+ <p>${d(method+"Hint")}</p>
116
+ ${!read?html`<${Skeleton} variant="rows" lines=${2} />`:!read.ok?html`<${ErrorState} title=${e("read")} message=${["credential_unavailable"].includes(read.error)?e("read"):credentialError(read.error)} onRetry=${load} />`:null}
117
+ ${method==="oauth"?html`<${ClaudeTokenFetch} key=${profile?"profile:"+profile:"default"} profile=${profile} read=${read} onBusy=${setBusy} onSaved=${result=>{if(input.current)input.current.value="";setHasInput(false);changed();setRead({...read,credential:result.credential});setPending(result.pending||[]);setDone(true);}} />`:null}
118
+ ${method!=="subscription"?html`<div class="field"><label for="claudeCredentialSecret">${d(method==="oauth"?"tokenLabel":"apiLabel")}</label><input ref=${inputRef.current} id="claudeCredentialSecret" type="password" onInput=${event=>setHasInput(!!event.target.value)} disabled=${busy||done||!read?.ok||!read.local} autocomplete="off" spellcheck=${false} placeholder=${d("paste")} /><p class="note">${d("saved")}</p></div><p class="note">${read?.local?d("local"):e("local")}</p>${initial!=="subscription"?html`<p class="note">${d("replacement")}</p>`:null}<details class="credential-disclosure"><summary><span>${d("runtime")}</span><${Icon} name="chevron" size=${16} /></summary><p class="note">${d("runtimeHint")}</p></details>`:null}
119
+ <p class="note credential-managed-policy">${e("managedPolicy")}</p>
120
+ ${pending.length?html`<p role="status" class="note">${e("pending")} ${pending.join(", ")}</p>`:null}
121
+ ${error?html`<p role="alert" class="err">${error}</p>`:null}${done?html`<p role="status">${d("done")}</p>`:null}
122
+ </${Dialog}>`;
123
+ }
@@ -0,0 +1,36 @@
1
+ // Safe Connect-account views only. The token never reaches this module.
2
+ import { html, useEffect, useRef, useState } from "/assets/app-html.js";
3
+ import { register, t } from "/assets/app-i18n.js";
4
+ import { confirmDialog } from "/assets/ui-confirm.js";
5
+ register("claudeTokenFetch",{
6
+ en:{get:"Get a token for me",paste:"Or paste a setup-token below",hint:"AgEnD opens a private sign-in session. Sign in on Claude’s website; the token goes straight into encrypted storage and is never displayed.",open:"Open sign-in page",code:"Authorization code",submit:"Submit authorization code",cancel:"Cancel connecting",waiting:"Waiting for Claude’s sign-in page…",working:"Waiting for you to finish signing in…",done:"Token saved. No model request was made.",failed:"The token could not be confirmed saved. Read the account status before retrying here or pasting a token below.",expired:"Sign-in timed out after 10 minutes. Retry here or paste a token below.",revoked:"Your verified session changed. Open this computer’s local dashboard, verify again, and retry.",cleanup:"The private session could not be confirmed closed. Ask the host operator to check it before reconnecting.",confirm:"Get a token and replace the saved credential?",restart:"After sign-in, agents using this account restart only when idle:",go:"Continue",pending:"Saved; these agents still need a restart:"},
7
+ "zh-TW":{get:"幫我取得 Token",paste:"或在下方貼上 setup-token",hint:"AgEnD 會開啟私密登入工作階段。請在 Claude 網站登入;Token 會直接加密保存,不會顯示出來。",open:"開啟登入頁面",code:"授權碼",submit:"送出授權碼",cancel:"取消連接",waiting:"正在等候 Claude 登入頁面…",working:"正在等你完成登入…",done:"Token 已儲存,沒有發出模型請求。",failed:"無法確認 Token 是否已儲存。請先讀取帳號狀態,再在這裡重試或在下方貼上 Token。",expired:"登入已超過 10 分鐘。請重試,或在下方貼上 Token。",revoked:"已驗證的工作階段已變更。請在這台電腦開啟本機儀表板,重新驗證後再試。",cleanup:"無法確認私密工作階段已關閉。請先請主機操作者檢查,再重新連接。",confirm:"要取得 Token 並取代保存的憑證嗎?",restart:"登入後,使用這個帳號的 Agent 只會在空閒時重啟:",go:"繼續",pending:"已儲存,以下 Agent 仍需重啟:"}
8
+ });
9
+ const text=k=>t("claudeTokenFetch."+k);
10
+ async function request(body){try{const r=await fetch("/ui/claude-credentials/setup-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)});const value=await r.json();return r.ok?value:{error:value.error||"credential_unavailable"};}catch{return {error:"credential_unavailable"};}}
11
+ export function ClaudeTokenFetch({profile,read,onBusy,onSaved}){
12
+ const [run,setRun]=useState(null),[error,setError]=useState(""),[starting,setStarting]=useState(false);
13
+ const current=useRef(null),alive=useRef(true),input=useRef(null),owned=useRef(null),pending=useRef(false);
14
+ const ongoing=run&&!["done","failed"].includes(run.login.phase);
15
+ const receive=value=>{if(!alive.current)return;if(value.error){setError(value.error.includes("session")||value.error.includes("verified")?"revoked":"failed");onBusy?.(false);setRun(previous=>previous?{...previous,login:{...previous.login,phase:"failed"}}:null);return;}current.current=value;setRun(value);if(value.login.phase==="done"){owned.current=null;onSaved?.(value);}if(value.login.phase==="done"||value.login.phase==="failed")onBusy?.(false);};
16
+ useEffect(()=>{alive.current=true;return()=>{alive.current=false;if(input.current)input.current.value="";const id=owned.current;if(id)void request({operation:"cancel",id});onBusy?.(false);};},[]);
17
+ useEffect(()=>{if(!ongoing)return;let stopped=false;const timer=setInterval(()=>{if(pending.current)return;pending.current=true;void request({operation:"read",id:run.login.id}).then(value=>{if(!stopped)receive(value);}).finally(()=>{pending.current=false;});},500);return()=>{stopped=true;clearInterval(timer);};},[ongoing,run?.login.id]);
18
+ const start=async()=>{setError("");if(!read?.ok||!read.local)return;setStarting(true);try{
19
+ const consumers=read.consumers;
20
+ if(consumers?.users?.length&&!await confirmDialog({title:text("confirm"),message:[text("restart"),...consumers.users].join("\n\n"),confirmLabel:text("go")}))return;
21
+ if(!alive.current)return;onBusy?.(true);
22
+ const result=await request({operation:"start",profile:profile||null,revision:read.credential?.revision||0,...(consumers?.users?.length?{restart:true,consumersRevision:consumers.revision}:{})});
23
+ if(result.started)owned.current=result.started;
24
+ if(!alive.current){if(result.started)void request({operation:"cancel",id:result.started});return;}
25
+ if(result.error)onBusy?.(false);receive(result);
26
+ }finally{if(alive.current)setStarting(false);}};
27
+ const cancel=async()=>{const id=owned.current||current.current?.login?.id;if(!id)return;owned.current=null;receive(await request({operation:"cancel",id}));};
28
+ const submit=async()=>{const value=input.current?.value||"";if(!value||!current.current)return;const login=current.current.login;const result=await request({operation:"input",id:login.id,revision:login.revision,action:{kind:"code",value}});if(input.current)input.current.value="";receive(result);};
29
+ const login=run?.login,reason=login?.reason,fail=reason==="expired"?"expired":reason==="revoked"?"revoked":reason==="cleanup_failed"?"cleanup":"failed";
30
+ return html`<section class="field credential-token-fetch"><button type="button" class="btn" disabled=${starting||ongoing||!read?.ok||!read.local} onClick=${start}>${text("get")}</button><p class="note">${text("hint")}</p>
31
+ ${ongoing?html`<p role="status">${text(login.url?"working":"waiting")}</p>${login.url?html`<a class="btn btn-primary" data-trust="navigation" href=${login.url} target="_blank" rel="noopener noreferrer">${text("open")}</a>`:null}
32
+ ${login.phase==="code"&&login.canAct?html`<div class="field"><label for="claudeSetupTokenCode">${text("code")}</label><input ref=${input} id="claudeSetupTokenCode" type="password" autocomplete="off" spellcheck=${false} /><button type="button" class="btn" onClick=${submit}>${text("submit")}</button></div>`:null}
33
+ <button type="button" class="btn danger" onClick=${cancel}>${text("cancel")}</button>`:null}
34
+ ${error||login?.phase==="failed"?html`<p role="alert" class="err">${text(error||fail)}</p>`:null}${login?.phase==="done"?html`<p role="status">${text("done")}</p>`:null}
35
+ ${run?.pending?.length?html`<p class="note">${text("pending")} ${run.pending.join(", ")}</p>`:null}<p class="note">${text("paste")}</p></section>`;
36
+ }
@@ -16,8 +16,10 @@ async function call(method, url, body) {
16
16
  } catch { return { ok: false, status: 0, code: "failed" }; }
17
17
  if (!r.ok) {
18
18
  let code = codeOf(r.status);
19
- if (r.status === 409 || r.status === 400) {
20
- try { const b = await r.json(); const c = b && (b.code || b.error); if (CONFLICTS.has(c) || c === "invalid-approver") code = c; } catch { /* no body: the status's own code */ }
19
+ if (r.status === 409 || r.status === 400 || r.status === 403) {
20
+ try { const b = await r.json(); const c = b && (b.code || b.error); if (CONFLICTS.has(c) || c === "invalid-approver" || c === "verification-required") code = c;
21
+ else if (c === "Write rejected — missing or wrong CSRF token (reload the page)") code = "csrf";
22
+ else if (c === "Cross-site request rejected") code = "cross-site"; } catch { /* no body: the status's own code */ }
21
23
  }
22
24
  return { ok: false, status: r.status, code };
23
25
  }
@@ -48,3 +50,6 @@ export const shortTicketId = (id) => { const s = String(id || ""); return /^R[a-
48
50
  /** A person's whole server identity as the server's canonical key — JSON of [platform, adapterId, userId] (ids may hold any
49
51
  * punctuation) — what the person filter takes; never a name. */
50
52
  export const personKey = (p) => (p ? JSON.stringify([p.platform, p.adapterId, p.userId]) : "");
53
+
54
+ /** Reminder dismissal only; never a contact approval or a permissions write. */
55
+ export const dismissSuggestion = (id) => call("POST", "/ui/needs/ack", { id });