@huaweidevtools/aishell-dsh-client-credentials 0.0.6 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js CHANGED
@@ -143,9 +143,9 @@ const CHIP_CLASS = "aishell-account-hint";
143
143
  * `style[data-plugin="<id>"]` on module teardown, so a tag written here is
144
144
  * reachable by the same mechanism as the generated ones.
145
145
  */
146
- const PLUGIN_ID = "@huaweidevtools/aishell-dsh-client-credentials";
146
+ const PLUGIN_ID$1 = "@huaweidevtools/aishell-dsh-client-credentials";
147
147
  /** Dedupe key for the one sheet this module owns. */
148
- const CHIP_STYLE_KEY = `${PLUGIN_ID}/chip-hover`;
148
+ const CHIP_STYLE_KEY = `${PLUGIN_ID$1}/chip-hover`;
149
149
  /**
150
150
  * Mount the chips' hover/focus rule for the owning plugin's lifetime.
151
151
  *
@@ -169,7 +169,7 @@ function installChipStyles(ctx) {
169
169
  if (typeof document === "undefined") return;
170
170
  ctx.effect(() => {
171
171
  const tag = document.createElement("style");
172
- tag.dataset.plugin = PLUGIN_ID;
172
+ tag.dataset.plugin = PLUGIN_ID$1;
173
173
  tag.dataset.pluginCss = CHIP_STYLE_KEY;
174
174
  tag.textContent = `.${CHIP_CLASS}:hover{background:var(--dsw-alias-interactive-bg-hover)}.${CHIP_CLASS}:focus-visible{outline:2px solid var(--dsw-alias-label-primary);outline-offset:-2px}`;
175
175
  document.head.appendChild(tag);
@@ -457,20 +457,234 @@ function AishellHeroChip(props) {
457
457
  */
458
458
  const CREDENTIAL_URL = "https://console.huaweicloud.com/apiexplorer/#/openapi/IAM/doc?version=v3&api=CreateTemporaryAccessKeyByToken";
459
459
 
460
+ //#endregion
461
+ //#region src/login-status.ts
462
+ /**
463
+ * Header the reachability probe sends, to force a CORS preflight.
464
+ *
465
+ * Any non-safelisted header would do it; this one names why. Declared here
466
+ * because both halves need the same string and neither owns it: the browser
467
+ * half sends it, the host's listener must allow it in its preflight answer,
468
+ * and a mismatch between the two is a probe that fails on a deployment that
469
+ * would actually work — the entry hidden for no reason.
470
+ */
471
+ const PROBE_HEADER = "x-aishell-probe";
472
+ /**
473
+ * Read an outcome back out of the document.
474
+ *
475
+ * Anything unreadable reads as no outcome: a corrupt field should show
476
+ * nothing, not a spurious success.
477
+ *
478
+ * @param raw - the stored string, if any.
479
+ * @returns the outcome, or `undefined` when there is none usable.
480
+ */
481
+ function decodeOutcome(raw) {
482
+ if (raw === void 0 || raw === "") return void 0;
483
+ let parsed;
484
+ try {
485
+ parsed = JSON.parse(raw);
486
+ } catch {
487
+ return void 0;
488
+ }
489
+ if (parsed === null || typeof parsed !== "object") return void 0;
490
+ const candidate = parsed;
491
+ if (candidate.kind === "succeeded" && typeof candidate.accountName === "string") return {
492
+ kind: "succeeded",
493
+ accountName: candidate.accountName
494
+ };
495
+ if (candidate.kind === "failed" && typeof candidate.error === "string") return {
496
+ kind: "failed",
497
+ error: candidate.error
498
+ };
499
+ return void 0;
500
+ }
501
+
502
+ //#endregion
503
+ //#region src/client/login-flow.ts
504
+ /**
505
+ * How long either half of the capability check may take.
506
+ *
507
+ * Short, because both are expected to be immediate: a loopback request that
508
+ * works answers in well under a millisecond. The bound exists so a deployment
509
+ * that cannot do this says so by falling through to the manual form rather
510
+ * than by leaving the card blank.
511
+ */
512
+ const PROBE_TIMEOUT_MS = 3e3;
513
+ /** Routes the browser half drives a login through. */
514
+ const LOGIN_START_ROUTE = "api/aishell/credentials/login/start";
515
+ const LOGIN_CANCEL_ROUTE = "api/aishell/credentials/login/cancel";
516
+ /**
517
+ * Reachability check, then login.
518
+ *
519
+ * Starts a login on the host and then proves this page can reach the listener
520
+ * it bound. The probe request goes from this browser to loopback, which is the
521
+ * same journey the cloud's callback will make.
522
+ *
523
+ * ## Why the probe is not a plain GET
524
+ *
525
+ * It carries a custom header, which makes it a non-simple request: the browser
526
+ * must send a CORS preflight first, and only proceeds if the answer is right.
527
+ * The cloud's callback is a JSON POST and therefore *always* preflights, so a
528
+ * plain GET would test a path the callback never takes — and could pass on a
529
+ * deployment where the real preflight fails (a missing Private Network Access
530
+ * allow header, say), which is the one wrong answer this check must not give.
531
+ *
532
+ * @returns a handle when the login is reachable, or `undefined` when it is
533
+ * not — the ordinary outcome on a deployment where the browser is elsewhere.
534
+ */
535
+ async function startBrowserLogin() {
536
+ let started;
537
+ try {
538
+ const response = await fetch(LOGIN_START_ROUTE, {
539
+ method: "POST",
540
+ headers: { "content-type": "application/json" },
541
+ body: JSON.stringify({}),
542
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS)
543
+ });
544
+ started = await response.json();
545
+ } catch {
546
+ return void 0;
547
+ }
548
+ if (started.ok !== true || started.loginUrl === void 0) return void 0;
549
+ const loginUrl = started.loginUrl;
550
+ const providerName = started.providerName ?? "";
551
+ const expiresInSeconds = started.expiresInSeconds ?? 0;
552
+ const cancel = () => {
553
+ fetch(LOGIN_CANCEL_ROUTE, { method: "POST" }).catch(() => {});
554
+ };
555
+ if (started.probeUrl === void 0 || started.probeUrl === "") {
556
+ cancel();
557
+ return void 0;
558
+ }
559
+ try {
560
+ const probe = await fetch(started.probeUrl, {
561
+ method: "GET",
562
+ headers: { [PROBE_HEADER]: "1" },
563
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS)
564
+ });
565
+ if (!probe.ok) {
566
+ cancel();
567
+ return void 0;
568
+ }
569
+ } catch (error) {
570
+ cancel();
571
+ return void 0;
572
+ }
573
+ return {
574
+ loginUrl,
575
+ providerName,
576
+ expiresInSeconds,
577
+ cancel
578
+ };
579
+ }
580
+ /**
581
+ * Open a login URL in a new tab.
582
+ *
583
+ * A separate tab rather than a redirect: the form has unsaved state and the
584
+ * person may come back to paste a key instead, and a login that navigated away
585
+ * from the conversation would lose it.
586
+ *
587
+ * ## Why `noopener` is set after opening, not passed in
588
+ *
589
+ * `window.open` returns `null` whenever `noopener` appears in its features
590
+ * string — by specification, not as a failure. Passing it there would make
591
+ * every successful open look blocked, so the tab is opened plainly and the
592
+ * opener reference is severed immediately afterwards, which is the same
593
+ * protection without losing the success signal.
594
+ *
595
+ * @param url - the URL the host returned.
596
+ * @returns whether the browser opened it; a popup blocker says no.
597
+ */
598
+ function openLoginWindow(url) {
599
+ const opened = window.open(url, "_blank");
600
+ if (opened === null) return false;
601
+ try {
602
+ opened.opener = null;
603
+ } catch {}
604
+ return true;
605
+ }
606
+
607
+ //#endregion
608
+ //#region src/client/start-page.ts
609
+ /**
610
+ * The page a card opens on.
611
+ *
612
+ * `undefined` means the probe has not answered yet, and is the honest value for
613
+ * that moment: rendering either page then is what makes the fields appear and
614
+ * get replaced a moment later.
615
+ *
616
+ * @param options - the two facts the decision turns on.
617
+ * @param options.browserAvailable - whether a browser login is possible here;
618
+ * `undefined` while the probe is still running.
619
+ * @param options.alreadyConfigured - whether a credential is already stored.
620
+ * @returns the page to show, or `undefined` while the answer is unknown.
621
+ */
622
+ function startPage(options) {
623
+ const { browserAvailable, alreadyConfigured } = options;
624
+ if (browserAvailable === void 0) return void 0;
625
+ if (!browserAvailable) return "manual";
626
+ if (alreadyConfigured) return "manual";
627
+ return "choose";
628
+ }
629
+ /**
630
+ * The page after a credential is cleared.
631
+ *
632
+ * Clearing puts the person back where someone with no credential stands, so the
633
+ * question is once again "how would you like to authenticate" — which is the
634
+ * choice page. It is also the only route to the browser login from the form, so
635
+ * a person who came here to switch methods lands where that is offered.
636
+ *
637
+ * @param options - the same facts {@link startPage} takes.
638
+ * @returns the page to show; never `undefined`, since this is not a first render.
639
+ */
640
+ function afterClear(options) {
641
+ return options.browserAvailable === true ? "choose" : "manual";
642
+ }
643
+
644
+ //#endregion
645
+ //#region src/client/spinner.ts
646
+ /** Class the waiting spinner carries. */
647
+ const SPINNER_CLASS = "aishell-spinner";
648
+ /** Marker identifying this sheet, so teardown sweeps exactly it. */
649
+ const SPINNER_STYLE_KEY = "aishell-credentials:spinner";
650
+ /** Plugin id the loader attributes the tag to. */
651
+ const PLUGIN_ID = "@huaweidevtools/aishell-dsh-client-credentials";
652
+ /**
653
+ * Install the spinner keyframes for the lifetime of the plugin fiber.
654
+ *
655
+ * Respects `prefers-reduced-motion`: a continuous rotation is exactly the kind
656
+ * of motion that setting exists to suppress, and the countdown beside it still
657
+ * conveys that work is in progress.
658
+ *
659
+ * @param ctx - the client context, for `ctx.effect`.
660
+ */
661
+ function installSpinnerStyles(ctx) {
662
+ if (typeof document === "undefined") return;
663
+ ctx.effect(() => {
664
+ const tag = document.createElement("style");
665
+ tag.dataset.plugin = PLUGIN_ID;
666
+ tag.dataset.pluginCss = SPINNER_STYLE_KEY;
667
+ tag.textContent = `@keyframes ${SPINNER_CLASS}-rotate{to{transform:rotate(360deg)}}.${SPINNER_CLASS}{display:inline-block;border-radius:50%;border:2px solid var(--dsw-alias-border-l4);border-top-color:var(--dsw-alias-label-secondary);animation:${SPINNER_CLASS}-rotate .8s linear infinite}@media (prefers-reduced-motion:reduce){.${SPINNER_CLASS}{animation:none}}`;
668
+ document.head.appendChild(tag);
669
+ return () => {
670
+ tag.remove();
671
+ };
672
+ }, "aishell-credentials: spinner styles");
673
+ }
674
+
460
675
  //#endregion
461
676
  //#region src/client/CredentialRequestForm.tsx
462
677
  /**
463
678
  * The masked credential form.
464
679
  *
465
- * Submitting saves through the Host route; the Host then tells the waiting tool
466
- * call there is now a credential, and clears the pending flag this component
467
- * renders from — so a successful submit does not need to unmount itself. A
468
- * manually-opened form has no request behind it, so it closes itself after a
469
- * successful save (the chip flipping to the account name is the feedback).
680
+ * Submitting saves through the Host route; the form then closes itself, and the
681
+ * chip flipping to the account name is the feedback that it worked. There is no
682
+ * request behind an open form — a chip opened it — so nothing else takes it
683
+ * down.
470
684
  */
471
685
  function CredentialRequestForm(props) {
472
686
  const t = props.t;
473
- const { save, clear, dismiss, closeManual } = props;
687
+ const { save, clear, close, cancel } = props;
474
688
  const status = props.useCredentials((snapshot) => snapshot);
475
689
  const [ak, setAk] = (0, react.useState)("");
476
690
  const [sk, setSk] = (0, react.useState)("");
@@ -478,8 +692,162 @@ function CredentialRequestForm(props) {
478
692
  const [saving, setSaving] = (0, react.useState)(false);
479
693
  const [clearing, setClearing] = (0, react.useState)(false);
480
694
  const [error, setError] = (0, react.useState)(void 0);
481
- const pending = props.pendingInteraction;
482
- const manual = pending?.manual === true;
695
+ /**
696
+ * Whether the fields were seeded from the environment.
697
+ *
698
+ * Shown so the person knows where the values came from — a credential that
699
+ * silently appeared in a field is worse than an empty one, because they
700
+ * cannot tell whether to trust it.
701
+ */
702
+ const [prefilled, setPrefilled] = (0, react.useState)(false);
703
+ /**
704
+ * The browser-login entry, once the host has started one and this page has
705
+ * proved it can reach the listener.
706
+ *
707
+ * `undefined` while that is still being decided, and `null` once it is
708
+ * decided against — the distinction matters, because "still checking" must
709
+ * not render the entry and "cannot" must not either, but only one of them
710
+ * resolves into it appearing.
711
+ */
712
+ const [browserLogin, setBrowserLogin] = (0, react.useState)(void 0);
713
+ /**
714
+ * Which page the card is on.
715
+ *
716
+ * `choose` is the first page: the browser entry, if this deployment has one,
717
+ * and the way to the manual form. `manual` is the AK/SK form. `waiting` is a
718
+ * browser login in flight.
719
+ *
720
+ * Where it opens depends on whether a credential is already stored — see
721
+ * {@link startPage}. `undefined` is "not decided yet", and renders the card's
722
+ * frame with neither page's body, which is what stops the fields appearing
723
+ * and being replaced a moment later.
724
+ */
725
+ const [page, setPage] = (0, react.useState)(void 0);
726
+ /** Seconds left before the login can no longer complete; `undefined` when idle. */
727
+ const [secondsLeft, setSecondsLeft] = (0, react.useState)(void 0);
728
+ /**
729
+ * Whether a credential is already stored, as of this open.
730
+ *
731
+ * Read from the status the chips read, so the card and the chip agree about
732
+ * whether there is anything to show. Captured by the probe effect below,
733
+ * whose empty dependency list makes it the value at mount — "was there a
734
+ * credential when this card opened", which is the question the first page
735
+ * answers.
736
+ */
737
+ const hasCredentials = status.hasAccessKey || status.hasSecretKey;
738
+ /**
739
+ * Whether the person has started filling the manual form.
740
+ *
741
+ * The probe is fast on the deployments this works on and slow on the ones it
742
+ * does not, so its answer can arrive after someone has begun typing. When it
743
+ * does, the choice page must not replace the form under their cursor.
744
+ */
745
+ const interacted = (0, react.useRef)(false);
746
+ (0, react.useEffect)(() => {
747
+ let live = true;
748
+ props.readPrefill().then((prefill) => {
749
+ const { accessKeyId, secretAccessKey } = prefill;
750
+ if (!live || accessKeyId === void 0 || secretAccessKey === void 0) return;
751
+ setAk((current) => current === "" ? accessKeyId : current);
752
+ setSk((current) => current === "" ? secretAccessKey : current);
753
+ setToken((current) => current === "" ? prefill.securityToken ?? "" : current);
754
+ setPrefilled(true);
755
+ }).catch(() => {});
756
+ return () => {
757
+ live = false;
758
+ };
759
+ }, []);
760
+ (0, react.useEffect)(() => {
761
+ let live = true;
762
+ const alreadyConfigured = status.hasAccessKey || status.hasSecretKey;
763
+ props.startBrowserLogin().then((handle) => {
764
+ if (!live) {
765
+ handle?.cancel();
766
+ return;
767
+ }
768
+ setBrowserLogin(handle ?? null);
769
+ if (interacted.current) return;
770
+ setPage(startPage({
771
+ browserAvailable: handle !== null,
772
+ alreadyConfigured
773
+ }));
774
+ }).catch(() => {
775
+ if (!live) return;
776
+ setBrowserLogin(null);
777
+ if (!interacted.current) setPage("manual");
778
+ });
779
+ return () => {
780
+ live = false;
781
+ };
782
+ }, []);
783
+ (0, react.useEffect)(() => () => {
784
+ browserLogin?.cancel();
785
+ }, [browserLogin]);
786
+ (0, react.useEffect)(() => {
787
+ if (page !== "waiting" || secondsLeft === void 0) return;
788
+ const deadline = Date.now() + secondsLeft * 1e3;
789
+ const timer = window.setInterval(() => {
790
+ setSecondsLeft(Math.max(0, Math.round((deadline - Date.now()) / 1e3)));
791
+ }, 1e3);
792
+ return () => {
793
+ window.clearInterval(timer);
794
+ };
795
+ }, [page]);
796
+ const outcomeRaw = props.useLoginOutcome((snapshot) => snapshot);
797
+ /**
798
+ * The outcome already recorded when this form opened.
799
+ *
800
+ * The document keeps the last login's outcome, so a form opened later would
801
+ * otherwise react to a result that has nothing to do with it: after a
802
+ * successful login the next open would close itself on the spot, and after a
803
+ * failed one it would show that error before the person typed anything.
804
+ * Baselines are per mount, which is per open — the interaction's key changes
805
+ * on reopen, so the component remounts.
806
+ */
807
+ const outcomeAtMount = (0, react.useRef)(null);
808
+ if (outcomeAtMount.current === null) outcomeAtMount.current = outcomeRaw;
809
+ (0, react.useEffect)(() => {
810
+ if (outcomeRaw === outcomeAtMount.current) return;
811
+ const outcome = decodeOutcome(outcomeRaw);
812
+ if (outcome === void 0) return;
813
+ if (outcome.kind === "succeeded") {
814
+ setAk("");
815
+ setSk("");
816
+ setToken("");
817
+ close();
818
+ return;
819
+ }
820
+ setPage(browserLogin ? "choose" : "manual");
821
+ setSecondsLeft(void 0);
822
+ setError(outcome.kind === "failed" && outcome.error !== "" ? t("form.browser.failed") + outcome.error : void 0);
823
+ }, [outcomeRaw]);
824
+ const onBrowserLogin = () => {
825
+ if (browserLogin === null || browserLogin === void 0) return;
826
+ setError(void 0);
827
+ if (!openLoginWindow(browserLogin.loginUrl)) {
828
+ setError(t("form.browser.blocked"));
829
+ return;
830
+ }
831
+ setPage("waiting");
832
+ setSecondsLeft(browserLogin.expiresInSeconds);
833
+ };
834
+ /**
835
+ * Abandon the browser login.
836
+ *
837
+ * This is a cancel, not a dismissal: the card is up because a tool call is
838
+ * blocked on it, so closing it has to answer that call. `cancel` does both —
839
+ * it records the refusal against the request token (so the tool stops
840
+ * asking) and withdraws the interaction — and it releases the host's
841
+ * listener, whose URL is dead the moment this card goes away.
842
+ */
843
+ const onCancelWaiting = () => {
844
+ onCancel();
845
+ };
846
+ /** Reopen the sign-in tab after the person closed it by accident. */
847
+ const onReopen = () => {
848
+ if (browserLogin === null || browserLogin === void 0) return;
849
+ if (!openLoginWindow(browserLogin.loginUrl)) setError(t("form.browser.blocked"));
850
+ };
483
851
  const onSubmit = async (event) => {
484
852
  event.preventDefault();
485
853
  setSaving(true);
@@ -493,7 +861,7 @@ function CredentialRequestForm(props) {
493
861
  setAk("");
494
862
  setSk("");
495
863
  setToken("");
496
- if (manual) closeManual();
864
+ close();
497
865
  } catch (err) {
498
866
  setError(err instanceof Error ? err.message : String(err));
499
867
  } finally {
@@ -505,7 +873,11 @@ function CredentialRequestForm(props) {
505
873
  setError(void 0);
506
874
  try {
507
875
  const verdict = await clear();
508
- if (!verdict.ok) setError(verdict.error ?? t("form.clear.failed"));
876
+ if (!verdict.ok) {
877
+ setError(verdict.error ?? t("form.clear.failed"));
878
+ return;
879
+ }
880
+ if (!interacted.current) setPage(afterClear({ browserAvailable: browserLogin !== null && browserLogin !== void 0 }));
509
881
  } catch (err) {
510
882
  setError(err instanceof Error ? err.message : String(err));
511
883
  } finally {
@@ -513,11 +885,8 @@ function CredentialRequestForm(props) {
513
885
  }
514
886
  };
515
887
  const onCancel = () => {
516
- if (manual) {
517
- closeManual();
518
- return;
519
- }
520
- dismiss();
888
+ browserLogin?.cancel();
889
+ cancel();
521
890
  };
522
891
  const fieldStyle = {
523
892
  display: "flex",
@@ -558,10 +927,9 @@ function CredentialRequestForm(props) {
558
927
  });
559
928
  const busy = saving || clearing;
560
929
  const disabled = busy || !ak || !sk;
561
- const hasCredentials = status.hasAccessKey || status.hasSecretKey;
562
930
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
563
931
  role: "group",
564
- "aria-label": t(manual ? "form.title.manual" : "form.title"),
932
+ "aria-label": t("form.title.manual"),
565
933
  style: {
566
934
  padding: "6px calc(var(--dsh-composer-side-clearance) + 16px) 10px",
567
935
  display: "flex",
@@ -582,157 +950,382 @@ function CredentialRequestForm(props) {
582
950
  gap: 12
583
951
  },
584
952
  children: [
585
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
586
- style: {
587
- display: "flex",
588
- flexDirection: "column",
589
- gap: 4
590
- },
591
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
953
+ page === "choose" && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
954
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
592
955
  style: {
593
- fontSize: 14,
594
- fontWeight: 500,
595
- lineHeight: "22px"
956
+ display: "flex",
957
+ flexDirection: "column",
958
+ gap: 4
596
959
  },
597
- children: t(manual ? "form.title.manual" : "form.title")
598
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
960
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
961
+ style: {
962
+ fontSize: 14,
963
+ fontWeight: 500,
964
+ lineHeight: "22px"
965
+ },
966
+ children: t("form.intro")
967
+ })
968
+ }),
969
+ error !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
599
970
  style: {
971
+ margin: 0,
600
972
  fontSize: 12,
601
973
  lineHeight: "18px",
602
- color: "var(--dsw-alias-label-tertiary)"
974
+ color: "var(--dsw-alias-state-warn-label)"
975
+ },
976
+ children: error
977
+ }),
978
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
979
+ style: {
980
+ display: "flex",
981
+ gap: 8
603
982
  },
604
983
  children: [
605
- t("section.credentials.hint.prefix"),
606
- " ",
607
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", {
608
- href: CREDENTIAL_URL,
609
- target: "_blank",
610
- rel: "noreferrer noopener",
984
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
985
+ type: "button",
986
+ onClick: () => {
987
+ onBrowserLogin();
988
+ },
989
+ style: {
990
+ ...buttonStyle(false),
991
+ background: "var(--dsw-alias-button-primary-fill)",
992
+ color: "var(--dsw-alias-label-primary-foreground)"
993
+ },
994
+ children: t("form.browser.action")
995
+ }),
996
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
997
+ type: "button",
998
+ onClick: () => {
999
+ setPage("manual");
1000
+ setError(void 0);
1001
+ },
611
1002
  style: {
612
- color: "var(--dsw-alias-button-primary-fill)",
613
- textDecoration: "underline"
1003
+ ...buttonStyle(false),
1004
+ background: "transparent",
1005
+ color: "var(--dsw-alias-label-primary)",
1006
+ border: "0.5px solid var(--dsw-alias-border-l4)"
614
1007
  },
615
- children: t("section.credentials.hint.link")
1008
+ children: t("form.browser.aksk")
616
1009
  }),
617
- " ",
618
- t("section.credentials.hint.suffix")
1010
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1011
+ type: "button",
1012
+ onClick: onCancel,
1013
+ style: {
1014
+ ...buttonStyle(false),
1015
+ background: "transparent",
1016
+ color: "var(--dsw-alias-label-primary)",
1017
+ border: "0.5px solid var(--dsw-alias-border-l4)",
1018
+ marginLeft: "auto"
1019
+ },
1020
+ children: t("form.browser.decline")
1021
+ })
619
1022
  ]
620
- })]
621
- }),
622
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
623
- style: fieldStyle,
624
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
625
- style: labelStyle,
626
- children: [t("section.field.accessKey"), status.accessKeyIdHint && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
627
- style: {
628
- color: "var(--dsw-alias-label-tertiary)",
629
- fontWeight: 400
630
- },
631
- children: [
632
- "(",
633
- status.accessKeyIdHint,
634
- ")"
635
- ]
636
- })]
637
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
638
- type: "password",
639
- value: ak,
640
- onChange: (e) => setAk(e.target.value),
641
- style: inputStyle,
642
- placeholder: t("section.field.accessKey.placeholder"),
643
- "aria-label": t("section.field.accessKey"),
644
- autoComplete: "off",
645
- autoFocus: true
646
- })]
647
- }),
648
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
649
- style: fieldStyle,
650
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
651
- style: labelStyle,
652
- children: t("section.field.secretKey")
653
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
654
- type: "password",
655
- value: sk,
656
- onChange: (e) => setSk(e.target.value),
657
- style: inputStyle,
658
- placeholder: t("section.field.secretKey.placeholder"),
659
- "aria-label": t("section.field.secretKey"),
660
- autoComplete: "off"
661
- })]
662
- }),
663
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
664
- style: fieldStyle,
665
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
666
- style: labelStyle,
667
- children: t("section.field.token")
668
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
669
- type: "password",
670
- value: token,
671
- onChange: (e) => setToken(e.target.value),
672
- style: inputStyle,
673
- placeholder: t("section.field.token.placeholder"),
674
- "aria-label": t("section.field.token"),
675
- autoComplete: "off"
676
- })]
677
- }),
678
- error !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
679
- style: {
680
- margin: 0,
681
- fontSize: 12,
682
- lineHeight: "18px",
683
- color: "var(--dsw-alias-state-warn-label)"
684
- },
685
- children: error
686
- }),
687
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
688
- style: {
689
- display: "flex",
690
- gap: 8
691
- },
692
- children: [
693
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
694
- type: "submit",
695
- disabled,
696
- style: {
697
- ...buttonStyle(disabled),
698
- background: "var(--dsw-alias-button-primary-fill)",
699
- color: "var(--dsw-alias-label-primary-foreground)"
700
- },
701
- children: saving ? t("section.credentials.saving") : t("form.submit")
702
- }),
703
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1023
+ })
1024
+ ] }),
1025
+ page === "waiting" && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
1026
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1027
+ style: {
1028
+ display: "flex",
1029
+ flexDirection: "column",
1030
+ alignItems: "center",
1031
+ gap: 12,
1032
+ padding: "8px 0"
1033
+ },
1034
+ children: [
1035
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1036
+ role: "status",
1037
+ style: {
1038
+ fontSize: 14,
1039
+ fontWeight: 500,
1040
+ lineHeight: "22px"
1041
+ },
1042
+ children: t("form.browser.waiting")
1043
+ }),
1044
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1045
+ className: SPINNER_CLASS,
1046
+ style: {
1047
+ width: 28,
1048
+ height: 28
1049
+ },
1050
+ "aria-hidden": true
1051
+ }),
1052
+ secondsLeft !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1053
+ style: {
1054
+ fontSize: 13,
1055
+ fontVariantNumeric: "tabular-nums",
1056
+ color: "var(--dsw-alias-label-tertiary)"
1057
+ },
1058
+ children: t("form.browser.countdown", { time: formatCountdown(secondsLeft) })
1059
+ })
1060
+ ]
1061
+ }),
1062
+ error !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
1063
+ style: {
1064
+ margin: 0,
1065
+ fontSize: 12,
1066
+ lineHeight: "18px",
1067
+ color: "var(--dsw-alias-state-warn-label)"
1068
+ },
1069
+ children: error
1070
+ }),
1071
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1072
+ style: {
1073
+ display: "flex",
1074
+ gap: 8
1075
+ },
1076
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
704
1077
  type: "button",
705
- onClick: onCancel,
706
- disabled: busy,
1078
+ onClick: onCancelWaiting,
707
1079
  style: {
708
- ...buttonStyle(busy),
1080
+ ...buttonStyle(false),
709
1081
  background: "transparent",
710
1082
  color: "var(--dsw-alias-label-primary)",
711
1083
  border: "0.5px solid var(--dsw-alias-border-l4)"
712
1084
  },
713
1085
  children: t("form.dismiss")
714
- }),
715
- hasCredentials && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1086
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
716
1087
  type: "button",
717
- onClick: () => {
718
- onClear();
719
- },
720
- disabled: busy,
1088
+ onClick: onReopen,
721
1089
  style: {
722
- ...buttonStyle(busy),
1090
+ ...buttonStyle(false),
723
1091
  background: "transparent",
724
1092
  color: "var(--dsw-alias-label-primary)",
725
1093
  border: "0.5px solid var(--dsw-alias-border-l4)",
726
1094
  marginLeft: "auto"
727
1095
  },
728
- children: clearing ? t("form.clearing") : t("form.clear")
729
- })
730
- ]
731
- })
1096
+ children: t("form.browser.reopen")
1097
+ })]
1098
+ })
1099
+ ] }),
1100
+ page === void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1101
+ style: {
1102
+ display: "flex",
1103
+ alignItems: "center",
1104
+ gap: 10
1105
+ },
1106
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1107
+ className: SPINNER_CLASS,
1108
+ style: {
1109
+ width: 16,
1110
+ height: 16
1111
+ },
1112
+ "aria-hidden": true
1113
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1114
+ role: "status",
1115
+ style: {
1116
+ fontSize: 14,
1117
+ lineHeight: "22px",
1118
+ color: "var(--dsw-alias-label-secondary)"
1119
+ },
1120
+ children: t("form.checking")
1121
+ })]
1122
+ }),
1123
+ page === "manual" && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
1124
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1125
+ style: {
1126
+ display: "flex",
1127
+ flexDirection: "column",
1128
+ gap: 4
1129
+ },
1130
+ children: [
1131
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1132
+ style: {
1133
+ fontSize: 14,
1134
+ fontWeight: 500,
1135
+ lineHeight: "22px"
1136
+ },
1137
+ children: t("form.title.manual")
1138
+ }),
1139
+ prefilled && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1140
+ role: "note",
1141
+ style: {
1142
+ fontSize: 12,
1143
+ lineHeight: "18px",
1144
+ color: "var(--dsw-alias-state-warn-label)"
1145
+ },
1146
+ children: t("form.prefilledFromEnv")
1147
+ }),
1148
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1149
+ style: {
1150
+ fontSize: 12,
1151
+ lineHeight: "18px",
1152
+ color: "var(--dsw-alias-label-tertiary)"
1153
+ },
1154
+ children: [
1155
+ t("section.credentials.hint.prefix"),
1156
+ " ",
1157
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", {
1158
+ href: CREDENTIAL_URL,
1159
+ target: "_blank",
1160
+ rel: "noreferrer noopener",
1161
+ style: {
1162
+ color: "var(--dsw-alias-button-primary-fill)",
1163
+ textDecoration: "underline"
1164
+ },
1165
+ children: t("section.credentials.hint.link")
1166
+ }),
1167
+ " ",
1168
+ t("section.credentials.hint.suffix")
1169
+ ]
1170
+ })
1171
+ ]
1172
+ }),
1173
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1174
+ style: fieldStyle,
1175
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1176
+ style: labelStyle,
1177
+ children: [t("section.field.accessKey"), status.accessKeyIdHint && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1178
+ style: {
1179
+ color: "var(--dsw-alias-label-tertiary)",
1180
+ fontWeight: 400
1181
+ },
1182
+ children: [
1183
+ "(",
1184
+ status.accessKeyIdHint,
1185
+ ")"
1186
+ ]
1187
+ })]
1188
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
1189
+ type: "password",
1190
+ value: ak,
1191
+ onChange: (e) => {
1192
+ interacted.current = true;
1193
+ setAk(e.target.value);
1194
+ },
1195
+ style: inputStyle,
1196
+ placeholder: t("section.field.accessKey.placeholder"),
1197
+ "aria-label": t("section.field.accessKey"),
1198
+ autoComplete: "off",
1199
+ autoFocus: true
1200
+ })]
1201
+ }),
1202
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1203
+ style: fieldStyle,
1204
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1205
+ style: labelStyle,
1206
+ children: t("section.field.secretKey")
1207
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
1208
+ type: "password",
1209
+ value: sk,
1210
+ onChange: (e) => {
1211
+ interacted.current = true;
1212
+ setSk(e.target.value);
1213
+ },
1214
+ style: inputStyle,
1215
+ placeholder: t("section.field.secretKey.placeholder"),
1216
+ "aria-label": t("section.field.secretKey"),
1217
+ autoComplete: "off"
1218
+ })]
1219
+ }),
1220
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1221
+ style: fieldStyle,
1222
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1223
+ style: labelStyle,
1224
+ children: t("section.field.token")
1225
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
1226
+ type: "password",
1227
+ value: token,
1228
+ onChange: (e) => {
1229
+ interacted.current = true;
1230
+ setToken(e.target.value);
1231
+ },
1232
+ style: inputStyle,
1233
+ placeholder: t("section.field.token.placeholder"),
1234
+ "aria-label": t("section.field.token"),
1235
+ autoComplete: "off"
1236
+ })]
1237
+ }),
1238
+ error !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
1239
+ style: {
1240
+ margin: 0,
1241
+ fontSize: 12,
1242
+ lineHeight: "18px",
1243
+ color: "var(--dsw-alias-state-warn-label)"
1244
+ },
1245
+ children: error
1246
+ }),
1247
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1248
+ style: {
1249
+ display: "flex",
1250
+ gap: 8
1251
+ },
1252
+ children: [
1253
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1254
+ type: "submit",
1255
+ disabled,
1256
+ style: {
1257
+ ...buttonStyle(disabled),
1258
+ background: "var(--dsw-alias-button-primary-fill)",
1259
+ color: "var(--dsw-alias-label-primary-foreground)"
1260
+ },
1261
+ children: saving ? t("section.credentials.saving") : t("form.submit")
1262
+ }),
1263
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1264
+ type: "button",
1265
+ onClick: onCancel,
1266
+ disabled: busy,
1267
+ style: {
1268
+ ...buttonStyle(busy),
1269
+ background: "transparent",
1270
+ color: "var(--dsw-alias-label-primary)",
1271
+ border: "0.5px solid var(--dsw-alias-border-l4)"
1272
+ },
1273
+ children: t("form.dismiss")
1274
+ }),
1275
+ browserLogin !== null && browserLogin !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1276
+ type: "button",
1277
+ onClick: () => {
1278
+ setPage("choose");
1279
+ setError(void 0);
1280
+ },
1281
+ disabled: busy,
1282
+ style: {
1283
+ ...buttonStyle(busy),
1284
+ background: "transparent",
1285
+ color: "var(--dsw-alias-label-primary)",
1286
+ border: "0.5px solid var(--dsw-alias-border-l4)"
1287
+ },
1288
+ children: t("form.back")
1289
+ }),
1290
+ hasCredentials && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1291
+ type: "button",
1292
+ onClick: () => {
1293
+ onClear();
1294
+ },
1295
+ disabled: busy,
1296
+ style: {
1297
+ ...buttonStyle(busy),
1298
+ background: "transparent",
1299
+ color: "var(--dsw-alias-label-primary)",
1300
+ border: "0.5px solid var(--dsw-alias-border-l4)",
1301
+ marginLeft: "auto"
1302
+ },
1303
+ children: clearing ? t("form.clearing") : t("form.clear")
1304
+ })
1305
+ ]
1306
+ })
1307
+ ] })
732
1308
  ]
733
1309
  })
734
1310
  });
735
1311
  }
1312
+ /**
1313
+ * Render a countdown as `m:ss`.
1314
+ *
1315
+ * Language-neutral on purpose: the surrounding sentence is localised, and a
1316
+ * number plus a unit needs no translation to read — whereas spelling out
1317
+ * "minutes"/"分" would put a second copy of the same unit in both dictionaries
1318
+ * for no gain. Tabular figures are applied at the call site so the digits do
1319
+ * not jitter as they change.
1320
+ *
1321
+ * @param seconds - seconds remaining.
1322
+ */
1323
+ function formatCountdown(seconds) {
1324
+ const whole = Math.max(0, Math.floor(seconds));
1325
+ const minutes = Math.floor(whole / 60);
1326
+ const rest = whole % 60;
1327
+ return `${String(minutes)}:${String(rest).padStart(2, "0")}`;
1328
+ }
736
1329
 
737
1330
  //#endregion
738
1331
  //#region src/client/CredentialFormInteraction.ts
@@ -742,15 +1335,13 @@ let nextKey = 0;
742
1335
  * Build an interaction for one session.
743
1336
  *
744
1337
  * @param sessionId - the conversation the form belongs to.
745
- * @param manual - true when a chip opened the form (no request behind it).
746
1338
  */
747
- function credentialFormInteraction(sessionId, manual) {
1339
+ function credentialFormInteraction(sessionId) {
748
1340
  nextKey += 1;
749
1341
  return {
750
1342
  kind: "aishell-credential-form",
751
1343
  key: `aishell-credential-form:${String(nextKey)}`,
752
- sessionId,
753
- manual
1344
+ sessionId
754
1345
  };
755
1346
  }
756
1347
  /**
@@ -765,15 +1356,35 @@ function credentialFormInteraction(sessionId, manual) {
765
1356
  function isCredentialForm(value) {
766
1357
  return value?.kind === "aishell-credential-form";
767
1358
  }
1359
+
1360
+ //#endregion
1361
+ //#region src/form-request.ts
768
1362
  /**
769
- * Route the Host exposes to abandon a pending credential request.
1363
+ * Read a request back out of the document.
1364
+ *
1365
+ * Anything unreadable reads as no request: a corrupt field should show nothing,
1366
+ * not open a form bound to a session that does not exist.
770
1367
  *
771
- * Sits with the other credential routes: `clear`, `reset`, and this one all end
772
- * a credential state, and keeping them together is what makes the route table
773
- * readable. Without it a person who does not want to enter credentials would
774
- * leave the blocked tool call waiting until the turn ended.
1368
+ * @param raw - the stored string, if any.
1369
+ * @returns the request, or `undefined` when there is none usable.
775
1370
  */
776
- const DISMISS_ROUTE = "api/aishell/credentials/dismiss";
1371
+ function decodeRequest(raw) {
1372
+ if (raw === void 0 || raw === "") return void 0;
1373
+ let parsed;
1374
+ try {
1375
+ parsed = JSON.parse(raw);
1376
+ } catch {
1377
+ return void 0;
1378
+ }
1379
+ if (parsed === null || typeof parsed !== "object") return void 0;
1380
+ const candidate = parsed;
1381
+ if (typeof candidate.token !== "string" || candidate.token === "") return void 0;
1382
+ if (typeof candidate.sessionId !== "string" || candidate.sessionId === "") return void 0;
1383
+ return {
1384
+ token: candidate.token,
1385
+ sessionId: candidate.sessionId
1386
+ };
1387
+ }
777
1388
 
778
1389
  //#endregion
779
1390
  //#region src/client/credential-form-visibility.ts
@@ -785,43 +1396,21 @@ const DISMISS_ROUTE = "api/aishell/credentials/dismiss";
785
1396
  function createCredentialFormVisibility(publish) {
786
1397
  let open;
787
1398
  let withdraw;
788
- let manual = false;
789
1399
  const clear = () => {
790
1400
  withdraw?.();
791
1401
  withdraw = void 0;
792
1402
  open = void 0;
793
- manual = false;
794
- };
795
- const publishFor = (sessionId, isManual) => {
796
- withdraw?.();
797
- const interaction = credentialFormInteraction(sessionId, isManual);
798
- open = interaction;
799
- manual = isManual;
800
- withdraw = publish(interaction);
801
- return interaction;
802
1403
  };
803
1404
  return {
804
1405
  current: () => open,
805
- manual: () => manual && open !== void 0,
806
- sync: (sessionId) => {
807
- if (sessionId === "") {
808
- if (open === void 0) return;
809
- clear();
810
- return;
811
- }
812
- if (open?.sessionId === sessionId) {
813
- if (!manual) return;
814
- publishFor(sessionId, false);
815
- return;
816
- }
817
- publishFor(sessionId, false);
818
- },
819
1406
  open: (sessionId) => {
820
1407
  if (open !== void 0) return;
821
- publishFor(sessionId, true);
1408
+ const interaction = credentialFormInteraction(sessionId);
1409
+ open = interaction;
1410
+ withdraw = publish(interaction);
822
1411
  },
823
1412
  close: () => {
824
- if (open === void 0 || !manual) return;
1413
+ if (open === void 0) return;
825
1414
  clear();
826
1415
  },
827
1416
  dispose: () => {
@@ -848,15 +1437,15 @@ const zh = {
848
1437
  "mode.unavailable": "权限模式不可用",
849
1438
  "mode.readonly.hint": "当前:只读 — 只允许查询云资源,点击切换为读写",
850
1439
  "mode.readwrite.hint": "当前:读写 — 允许变更云资源,点击切换为只读",
851
- "mode.unavailable.hint": "无法从 MCP 服务器读取权限模式;切换按钮暂不可用",
1440
+ "mode.unavailable.hint": "无法读取权限模式;切换按钮暂不可用",
852
1441
  "mode.switchToReadonly": "切换为只读模式",
853
1442
  "mode.switchToReadwrite": "切换为读写模式",
854
1443
  "section.credentials.hint.prefix": "需要进行华为云 IAM 认证,建议从",
855
1444
  "section.credentials.hint.link": "API Explorer",
856
1445
  "section.credentials.hint.suffix": "获取临时凭据,避免使用永久凭据。",
857
1446
  "section.credentials.saving": "保存中…",
858
- "form.title": "需要华为云凭据",
859
1447
  "form.title.manual": "配置华为云凭据",
1448
+ "form.prefilledFromEnv": "检测到环境变量,已填入表单",
860
1449
  "form.submit": "提交",
861
1450
  "form.dismiss": "取消",
862
1451
  "form.failed": "保存凭据失败",
@@ -864,8 +1453,17 @@ const zh = {
864
1453
  "form.clearing": "清除中…",
865
1454
  "form.clear.failed": "清除凭据失败",
866
1455
  "error.unreachable": "无法连接宿主凭据服务:",
867
- "error.clear.serverFailed": "本机凭据已清除,但服务端凭据未清除(HTTP {status})",
868
- "error.clear.serverUnreachable": "本机凭据已清除,但无法连接 MCP 服务器清除服务端凭据:",
1456
+ "form.intro": "需要进行华为云 IAM 认证",
1457
+ "form.checking": "正在检查登录方式…",
1458
+ "form.browser.action": "浏览器登录",
1459
+ "form.browser.aksk": "我有AK/SK",
1460
+ "form.browser.decline": "暂不认证",
1461
+ "form.browser.waiting": "正在等待浏览器完成登录…",
1462
+ "form.browser.countdown": "剩余 {time}",
1463
+ "form.browser.reopen": "重新打开",
1464
+ "form.back": "返回",
1465
+ "form.browser.blocked": "浏览器拦截了新标签页,请允许弹出窗口后重试。",
1466
+ "form.browser.failed": "浏览器登录未完成:",
869
1467
  "section.field.accessKey": "Access Key",
870
1468
  "section.field.accessKey.placeholder": "华为云 Access Key",
871
1469
  "section.field.accessKey.hint": "Access Key 与 Secret Key 须同时填写,只填其一时不会保存。",
@@ -884,15 +1482,15 @@ const en = {
884
1482
  "mode.unavailable": "Mode unavailable",
885
1483
  "mode.readonly.hint": "Read-only — cloud queries only. Click for read-write",
886
1484
  "mode.readwrite.hint": "Read-write — cloud changes allowed. Click for read-only",
887
- "mode.unavailable.hint": "Could not read the permission mode from the MCP server; the toggle is unavailable",
1485
+ "mode.unavailable.hint": "Could not read the permission mode; the toggle is unavailable",
888
1486
  "mode.switchToReadonly": "Switch to read-only mode",
889
1487
  "mode.switchToReadwrite": "Switch to read-write mode",
890
1488
  "section.credentials.hint.prefix": "Authenticate against Huawei Cloud IAM. Obtain temporary credentials from",
891
1489
  "section.credentials.hint.link": "API Explorer",
892
1490
  "section.credentials.hint.suffix": "and avoid permanent ones.",
893
1491
  "section.credentials.saving": "Saving…",
894
- "form.title": "Huawei Cloud credentials required",
895
1492
  "form.title.manual": "Configure Huawei Cloud credentials",
1493
+ "form.prefilledFromEnv": "Detected environment variables — filled in from them",
896
1494
  "form.submit": "Submit",
897
1495
  "form.dismiss": "Cancel",
898
1496
  "form.failed": "Could not save credentials",
@@ -900,8 +1498,17 @@ const en = {
900
1498
  "form.clearing": "Clearing…",
901
1499
  "form.clear.failed": "Could not clear credentials",
902
1500
  "error.unreachable": "Could not reach the host credential service: ",
903
- "error.clear.serverFailed": "Local credentials were cleared, but the server copy was not (HTTP {status})",
904
- "error.clear.serverUnreachable": "Local credentials were cleared, but the MCP server could not be reached to clear the server copy: ",
1501
+ "form.intro": "Huawei Cloud IAM authentication is required",
1502
+ "form.checking": "Checking sign-in options…",
1503
+ "form.browser.action": "Sign in with a browser",
1504
+ "form.browser.aksk": "I have one",
1505
+ "form.browser.decline": "Not now",
1506
+ "form.browser.waiting": "Waiting for the browser sign-in to finish…",
1507
+ "form.browser.countdown": "{time} left",
1508
+ "form.browser.reopen": "Reopen",
1509
+ "form.back": "Back",
1510
+ "form.browser.blocked": "The browser blocked the new tab. Allow pop-ups for this page, then try again.",
1511
+ "form.browser.failed": "The browser sign-in did not complete: ",
905
1512
  "section.field.accessKey": "Access Key",
906
1513
  "section.field.accessKey.placeholder": "Huawei Access Key",
907
1514
  "section.field.accessKey.hint": "Access Key and Secret Key are stored as a pair; one without the other is not saved.",
@@ -926,20 +1533,10 @@ const AISHELL_CREDENTIALS_NS = "aishell-client-credentials";
926
1533
  const CREDENTIALS_ROUTE = "api/aishell/credentials";
927
1534
  /** Clear route; the Host's fetch registry has no DELETE, so clearing is a POST. */
928
1535
  const CLEAR_ROUTE = "api/aishell/credentials/clear";
929
- /**
930
- * The MCP server's own credential store, cleared through the ops-deploy
931
- * plugin's route.
932
- *
933
- * Clearing is a two-store operation: this plugin's store (CLEAR_ROUTE) and the
934
- * MCP server's, which keeps its own copy scoped to this client. Only the first
935
- * existed until the scope work made the second reachable, and the half-cleared
936
- * state it left — the chip showing "no credentials" while cloud calls still
937
- * worked — is the bug this fixes.
938
- *
939
- * An absolute host route owned by another package, reached the same way the
940
- * permission-mode route already is: by URL, not by import.
941
- */
942
- const SERVER_CREDENTIALS_ROUTE = "api/aishell/credentials/reset";
1536
+ /** Cancel route; names the request token the person declined. */
1537
+ const CANCEL_ROUTE = "api/aishell/credentials/cancel";
1538
+ /** Prefill route; returns the values the host's environment already holds. */
1539
+ const PREFILL_ROUTE = "api/aishell/credentials/prefill";
943
1540
  /**
944
1541
  * POST one JSON body to a Host credential route and read back its verdict.
945
1542
  * A non-JSON or unreadable body is reported as a transport failure rather than
@@ -969,55 +1566,55 @@ async function postJson(route, t, body) {
969
1566
  /**
970
1567
  * Store one credential through the Host route.
971
1568
  *
972
- * Both ways the form comes up — a chip click and a blocked MCP call — go
1569
+ * Both ways the form comes up — a chip click and a blocked tool call — go
973
1570
  * through this, so there is exactly one body shape for the credential route.
974
1571
  *
975
1572
  * An absent SecurityToken is omitted rather than sent empty: the Host reads an
976
1573
  * empty string as absent anyway, so sending it would only make the wire shape
977
1574
  * depend on which form was used.
978
1575
  */
979
- function saveCredential(t, accessKeyId, secretAccessKey, securityToken) {
1576
+ function saveCredential(t, accessKeyId, secretAccessKey, securityToken, requestToken) {
980
1577
  return postJson(CREDENTIALS_ROUTE, t, {
981
1578
  accessKeyId,
982
1579
  secretAccessKey,
983
- ...securityToken === void 0 ? {} : { securityToken }
1580
+ ...securityToken === void 0 ? {} : { securityToken },
1581
+ ...requestToken === void 0 ? {} : { requestToken }
984
1582
  });
985
1583
  }
986
1584
  /**
987
- * Clear both credential stores, reporting the first failure.
1585
+ * Clear the stored credentials.
988
1586
  *
989
- * The order matters: this plugin's store goes first, because it is the one
990
- * whose absence *stops* the chat from authenticating. A failure there leaves
991
- * both stores intact (nothing cleared, nothing to misreport). A failure on the
992
- * second leaves a state the user can still act on — no credentials locally, a
993
- * server copy that a second attempt or a server restart will clear — which is
994
- * why the message names which half failed rather than saying "clear failed".
995
- *
996
- * The second store is best-effort by design: if the MCP server is unreachable
997
- * or older than `credential/reset`, the local clear has already succeeded and
998
- * saying so is more accurate than reporting the whole action as failed.
1587
+ * One store, one write: the credentials live in the host's keyring and nowhere
1588
+ * else, so this is the local clear and its failure is the only one there is to
1589
+ * report.
999
1590
  *
1000
1591
  * @param t - the form's translator; the failure copy is user-visible.
1001
1592
  */
1002
1593
  async function clearBothStores(t) {
1003
- const local = await postJson(CLEAR_ROUTE, t);
1004
- if (!local.ok) return local;
1594
+ return postJson(CLEAR_ROUTE, t);
1595
+ }
1596
+ /**
1597
+ * Read the credential prefills the host has in its environment.
1598
+ *
1599
+ * Failure is not an event: a host with nothing in its environment answers an
1600
+ * empty object, and a route that cannot be reached answers `{}` too, because a
1601
+ * form that starts empty is exactly the behaviour before this existed.
1602
+ *
1603
+ * @returns the prefills, or an empty object.
1604
+ */
1605
+ async function readPrefill() {
1005
1606
  try {
1006
- const response = await fetch(SERVER_CREDENTIALS_ROUTE, { method: "POST" });
1007
- if (!response.ok) {
1008
- const body = await response.json();
1009
- return {
1010
- ok: false,
1011
- error: typeof body.error === "string" ? body.error : t("error.clear.serverFailed", { status: String(response.status) })
1012
- };
1013
- }
1014
- } catch (error) {
1015
- return {
1016
- ok: false,
1017
- error: t("error.clear.serverUnreachable") + (error instanceof Error ? error.message : String(error))
1018
- };
1607
+ const response = await fetch(PREFILL_ROUTE, { headers: { accept: "application/json" } });
1608
+ if (!response.ok) return {};
1609
+ const body = await response.json();
1610
+ return typeof body.accessKeyId === "string" && body.accessKeyId !== "" && typeof body.secretAccessKey === "string" && body.secretAccessKey !== "" ? {
1611
+ accessKeyId: body.accessKeyId,
1612
+ secretAccessKey: body.secretAccessKey,
1613
+ ...typeof body.securityToken === "string" && body.securityToken !== "" ? { securityToken: body.securityToken } : {}
1614
+ } : {};
1615
+ } catch {
1616
+ return {};
1019
1617
  }
1020
- return { ok: true };
1021
1618
  }
1022
1619
  /** Required services. */
1023
1620
  const inject = [
@@ -1033,6 +1630,7 @@ function apply(ctx) {
1033
1630
  }), "aishell-credentials: dictionaries");
1034
1631
  const t = ctx.locale.bind(NS);
1035
1632
  installChipStyles(ctx);
1633
+ installSpinnerStyles(ctx);
1036
1634
  const form = ctx.configForms.get(AISHELL_CREDENTIALS_NS);
1037
1635
  const status = (0, __deepseek_ai_dsh_client_store.createSnapshotStore)({
1038
1636
  hasAccessKey: false,
@@ -1054,16 +1652,51 @@ function apply(ctx) {
1054
1652
  };
1055
1653
  ctx.effect(() => form.subscribe(derive), "aishell-credentials: credential presence");
1056
1654
  derive();
1655
+ const loginOutcome = (0, __deepseek_ai_dsh_client_store.createSnapshotStore)(form.getSnapshot().value?.loginOutcome ?? "");
1656
+ ctx.effect(() => form.subscribe(() => {
1657
+ loginOutcome.set(form.getSnapshot().value?.loginOutcome ?? "");
1658
+ }), "aishell-credentials: login outcome");
1057
1659
  const publishCredentialForm = ctx.uiSession.registerPendingInteraction(() => 0);
1058
1660
  const visibility = createCredentialFormVisibility((interaction) => publishCredentialForm(interaction, () => Promise.resolve()));
1059
- const syncCredentialForm = () => {
1060
- visibility.sync(form.getSnapshot().value?.credentialRequestSession ?? "");
1661
+ /** The last request the browser acted on, so a re-read is not a re-open. */
1662
+ let lastRequestToken;
1663
+ /**
1664
+ * The token of the request this form is currently answering, if any.
1665
+ *
1666
+ * A chip-opened form has none: nothing asked for it, so a cancel must not
1667
+ * report one — a submit or cancel names a request, and there is no request to
1668
+ * name.
1669
+ */
1670
+ let pendingRequestToken;
1671
+ const applyFormRequest = () => {
1672
+ const request = decodeRequest(form.getSnapshot().value?.credentialFormRequest);
1673
+ if (request === void 0 || request.token === lastRequestToken) return;
1674
+ lastRequestToken = request.token;
1675
+ pendingRequestToken = request.token;
1676
+ visibility.open(request.sessionId);
1061
1677
  };
1062
- ctx.effect(() => form.subscribe(syncCredentialForm), "aishell-credentials: credential form visibility");
1063
- syncCredentialForm();
1678
+ ctx.effect(() => form.subscribe(applyFormRequest), "aishell-credentials: form requests");
1679
+ applyFormRequest();
1064
1680
  ctx.effect(() => () => {
1065
1681
  visibility.dispose();
1066
1682
  }, "aishell-credentials: credential form teardown");
1683
+ /**
1684
+ * Record a cancel against the request it belongs to.
1685
+ *
1686
+ * Only when this form was opened by a request: a chip-opened form has no
1687
+ * request behind it, and recording a cancel for one would make the *next*
1688
+ * `auth` call believe the person refused a question nobody asked.
1689
+ */
1690
+ const cancelRequest = () => {
1691
+ const token = pendingRequestToken;
1692
+ pendingRequestToken = void 0;
1693
+ if (token === void 0) return;
1694
+ fetch(CANCEL_ROUTE, {
1695
+ method: "POST",
1696
+ headers: { "content-type": "application/json" },
1697
+ body: JSON.stringify({ token })
1698
+ }).catch(() => {});
1699
+ };
1067
1700
  ctx.effect(() => ctx.slots.inject("conversation.composer.dock", () => ctx.slots.register({
1068
1701
  name: "conversation.composer.dock",
1069
1702
  id: "aishell-account",
@@ -1097,13 +1730,19 @@ function apply(ctx) {
1097
1730
  select: ({ pendingInteraction }) => isCredentialForm(pendingInteraction) ? pendingInteraction : null,
1098
1731
  locale: NS,
1099
1732
  inject: () => ({
1100
- hooks: { credentials: status },
1101
- save: (ak, sk, token) => saveCredential(t, ak, sk, token),
1733
+ hooks: {
1734
+ credentials: status,
1735
+ loginOutcome
1736
+ },
1737
+ save: (ak, sk, token) => saveCredential(t, ak, sk, token, pendingRequestToken),
1738
+ readPrefill: () => readPrefill(),
1739
+ startBrowserLogin: () => startBrowserLogin(),
1102
1740
  clear: () => clearBothStores(t),
1103
- dismiss: () => {
1104
- fetch(DISMISS_ROUTE, { method: "POST" });
1741
+ close: () => {
1742
+ visibility.close();
1105
1743
  },
1106
- closeManual: () => {
1744
+ cancel: () => {
1745
+ cancelRequest();
1107
1746
  visibility.close();
1108
1747
  }
1109
1748
  })