From e8e9289f4654822249a6e5014cd60c8620debabd Mon Sep 17 00:00:00 2001 From: Matt Briones Date: Wed, 21 Oct 2026 21:43:59 +0000 Subject: [PATCH] fix(dashboard): keep feature-preview switches on the gateway The Feature previews switches lived only in browser localStorage, so a new origin, the desktop app beside a browser tab, or cleared site data turned them back off. Each switch is now stored in the gateway config under dashboard.feature_previews., written through the existing owner-only config PATCH, with localStorage kept as a cache. A switch set only in this browser is carried up once with if_unset; a refused toggle names the switch that went back and says why. A carry-up refused as owner-only says the switch stays on in this browser only, with no reload step, and that notice clears once the gateway holds a value for the switch. Each browser records which switches it has seen the gateway hold, so a switch removed there reads as off even when another switch's carry-up failed. An accepted save is written into the cached config with the shared setConfigPathValue helper. A switch saved from one dashboard now reaches the other open ones without a reload: the gateway's config watcher pushes a config refresh when dashboard.feature_previews changes. The section intro now says the choices are saved on this gateway and apply wherever the dashboard is opened, instead of "saved for everyone". The Preview-gated surfaces paragraph in the dashboard module spec now says the switch is kept under dashboard.feature_previews., that localStorage is a cache, that writes go through the owner-only config PATCH, and names usePreviewFlagServerSync. Fixes #21396 --- config-baseline.json | 127 ++++ .../modules/learn-cron-dashboard.md | 2 +- src/kiro_crew/change_card_catalog.py | 1 + src/kiro_crew/change_card_catalog_kinds.py | 6 +- src/kiro_crew/config/loader.py | 1 + src/kiro_crew/config/loader_builders.py | 17 + src/kiro_crew/config/sections.py | 1 + src/kiro_crew/config/sections_dashboard.py | 39 ++ src/kiro_crew/dashboard/handlers/core.py | 1 + .../dashboard/handlers/core_config_schema.py | 10 + .../dashboard/server_runtime/config_watch.py | 13 + src/kiro_crew/docs/configuration.md | 1 + test/test_config_live_server_appliers.py | 24 + test/test_feature_previews_config.py | 176 ++++++ website/src/hooks/usePreviewFlagServerSync.ts | 326 ++++++++++ website/src/i18n/locales/bn.json | 8 +- website/src/i18n/locales/de.json | 8 +- website/src/i18n/locales/en-XA.json | 6 +- website/src/i18n/locales/en.manual.json | 6 +- website/src/i18n/locales/es.json | 8 +- website/src/i18n/locales/fr.json | 8 +- website/src/i18n/locales/hi.json | 8 +- website/src/i18n/locales/it.json | 8 +- website/src/i18n/locales/ja.json | 8 +- website/src/i18n/locales/ko.json | 8 +- website/src/i18n/locales/pt.json | 8 +- website/src/i18n/locales/ru.json | 8 +- website/src/i18n/locales/zh-CN.json | 8 +- .../pages/settings/FeaturePreviewsSection.tsx | 70 +- website/src/shell/appShell.tsx | 4 + .../featurePreviewsSectionNotice.test.tsx | 134 ++++ .../src/test/previewFlagServerSync.test.tsx | 598 ++++++++++++++++++ website/src/test/previewSurfaces.test.tsx | 22 + website/src/utils/previewFlags.ts | 87 ++- 34 files changed, 1713 insertions(+), 47 deletions(-) create mode 100644 test/test_feature_previews_config.py create mode 100644 website/src/hooks/usePreviewFlagServerSync.ts create mode 100644 website/src/test/featurePreviewsSectionNotice.test.tsx create mode 100644 website/src/test/previewFlagServerSync.test.tsx diff --git a/config-baseline.json b/config-baseline.json index 90f33259bbd0..fb5e77ed796c 100644 --- a/config-baseline.json +++ b/config-baseline.json @@ -8076,6 +8076,7 @@ "dynamic_dashboard_cards": false, "crewmate_threads": false, "crewmates_in_agent_picker": false, + "feature_previews": {}, "qr_session_until_restart": true, "qr_session_persist_across_restart": false, "restore_window_minutes": 30, @@ -8487,6 +8488,132 @@ "enumValues": null, "defaultValue": false }, + { + "path": "dashboard.feature_previews", + "kind": "core", + "type": "object", + "required": false, + "deprecated": false, + "sensitive": false, + "tags": [], + "label": "Feature previews", + "help": "Which unreleased dashboard features are turned on under Settings > Developer > Feature previews, by name, each true or false. Kept here so a switch stays as set on every browser, device and dashboard address of this gateway. A name that is absent reads as off. Takes effect on the next dashboard read; no restart.", + "hasChildren": true, + "enumValues": null, + "defaultValue": {} + }, + { + "path": "dashboard.feature_previews.artifact_deploy", + "kind": "core", + "type": "boolean", + "required": false, + "deprecated": false, + "sensitive": false, + "tags": [], + "label": "Feature preview: artifact_deploy", + "help": "Turn on the 'artifact_deploy' feature preview.", + "hasChildren": false, + "enumValues": null, + "defaultValue": false + }, + { + "path": "dashboard.feature_previews.crew_mode", + "kind": "core", + "type": "boolean", + "required": false, + "deprecated": false, + "sensitive": false, + "tags": [], + "label": "Feature preview: crew_mode", + "help": "Turn on the 'crew_mode' feature preview.", + "hasChildren": false, + "enumValues": null, + "defaultValue": false + }, + { + "path": "dashboard.feature_previews.crewmate_harness", + "kind": "core", + "type": "boolean", + "required": false, + "deprecated": false, + "sensitive": false, + "tags": [], + "label": "Feature preview: crewmate_harness", + "help": "Turn on the 'crewmate_harness' feature preview.", + "hasChildren": false, + "enumValues": null, + "defaultValue": false + }, + { + "path": "dashboard.feature_previews.folder_conductor", + "kind": "core", + "type": "boolean", + "required": false, + "deprecated": false, + "sensitive": false, + "tags": [], + "label": "Feature preview: folder_conductor", + "help": "Turn on the 'folder_conductor' feature preview.", + "hasChildren": false, + "enumValues": null, + "defaultValue": false + }, + { + "path": "dashboard.feature_previews.layout_harness", + "kind": "core", + "type": "boolean", + "required": false, + "deprecated": false, + "sensitive": false, + "tags": [], + "label": "Feature preview: layout_harness", + "help": "Turn on the 'layout_harness' feature preview.", + "hasChildren": false, + "enumValues": null, + "defaultValue": false + }, + { + "path": "dashboard.feature_previews.remote_crew_chat", + "kind": "core", + "type": "boolean", + "required": false, + "deprecated": false, + "sensitive": false, + "tags": [], + "label": "Feature preview: remote_crew_chat", + "help": "Turn on the 'remote_crew_chat' feature preview.", + "hasChildren": false, + "enumValues": null, + "defaultValue": false + }, + { + "path": "dashboard.feature_previews.session_environments", + "kind": "core", + "type": "boolean", + "required": false, + "deprecated": false, + "sensitive": false, + "tags": [], + "label": "Feature preview: session_environments", + "help": "Turn on the 'session_environments' feature preview.", + "hasChildren": false, + "enumValues": null, + "defaultValue": false + }, + { + "path": "dashboard.feature_previews.webhooks", + "kind": "core", + "type": "boolean", + "required": false, + "deprecated": false, + "sensitive": false, + "tags": [], + "label": "Feature preview: webhooks", + "help": "Turn on the 'webhooks' feature preview.", + "hasChildren": false, + "enumValues": null, + "defaultValue": false + }, { "path": "dashboard.qr_session_until_restart", "kind": "core", diff --git a/docs/system-specs/modules/learn-cron-dashboard.md b/docs/system-specs/modules/learn-cron-dashboard.md index 7c0908eac62c..fe0224acdd04 100644 --- a/docs/system-specs/modules/learn-cron-dashboard.md +++ b/docs/system-specs/modules/learn-cron-dashboard.md @@ -5238,7 +5238,7 @@ polled by this watchdog. **Nav sidebar** — Collapsible: full mode (236px with labels) or icon-only mode (74px). The sidebar toggle lives in the rail's own top "menu row" (hamburger, plus a `panel-left-close` collapse control on the right while expanded) — not in the topbar, which shows only the brand. State persisted in `localStorage('mc-nav')`. Three vertically-stacked regions: (1) **top-fixed** — menu row, then Sessions (the chat surface, formerly labeled "Chat"), Schedule, Artifacts, Knowledge, then an **Apps** section header whose right side is an accent-colored **Explore** link (lucide `layout-grid`) to the App Store at `/apps` (the store's surface is `hiddenFromNav`; the link carries the `data-onboarding-nav="apps"` anchor); (2) **Apps frame** — the enabled-apps list scrolls in its own frame (`flex-1 min-h-0 overflow-y-auto`) so many apps never push the pinned sections; drag-reorderable via dnd-kit sortable (`SortableAppNavRow` + `DndContext`/`SortableContext`/`DragOverlay`, `MouseSensor` 8px distance + `TouchSensor` press-and-hold so a plain click still navigates): rows reflow to open a gap as one is dragged, the source dims, and a `DragOverlay` ghost follows the cursor; order persists to `localStorage('mc-app-nav-order')` (`arrayMove`); reorder is scoped to the currently visible Apps rows (the "N more" overflow collapse hides the rest); (3) **bottom-fixed** — Customize, Developer (dev mode only), Settings, and a **Contact Us** row with icon links to kiro.dev, the GitHub repo, and the Discord community (folds away — `max-h-0` + `inert` — while collapsed). Collapsed mode renders icon-only rows with portaled hover labels; the Explore row fades in and slides up into place. The former Shortcuts nav row moved to **Settings → Shortcuts** (`ShortcutsPanel`, sharing the same content the Alt+K shortcuts modal shows; tab sits above Developer). The Alt+K modal has a search field that filters entries by action label, group name or chord (a `+` in the query also matches as a space, so `ctrl+k` finds "Ctrl K"); no match shows an empty state with a clear action, and Escape first clears a non-empty query, then closes the modal. -**Preview-gated surfaces** — a registry entry may carry `previewFlag`, the localStorage key of a per-device opt-in (`utils/previewFlags.ts`, all keys prefixed `mc-preview-`). While the flag is off the surface is not advertised **anywhere**. The safe list has a name: consumers read **`getAdvertisedSurfaces()`** (= `getBuiltinSurfaces()` minus gated entries) rather than filtering per call site, because a call site that reaches for the unfiltered list and forgets the filter leaks an unreleased surface silently. `useAppRailOrder` (`shell/nav/appRail.tsx`) derives `advertisedNavItems` once and feeds BOTH rail list paths (Main and the Apps group) from it; the Search Everywhere Pages provider reads the same accessor. The bottom-fixed rows are looked up by id (`settings`, `capabilities`) and are core surfaces that are never gated. Gated surfaces deliberately REMAIN in `getBuiltinSurfaces()` so registry-wide invariants (every surface carries a translatable `labelKey`) still cover them. Their route stays registered, which is what makes the surface reachable once the flag is on. The flags are listed as one card per feature on **Settings → Developer → Feature Previews** (the section is `pages/settings/FeaturePreviewsSection.tsx`, the first page of `DeveloperPanel`'s SubNav, above the internals pages. It keeps the registry's "surface" vocabulary in code while its copy says "features" and "pages". The old `/developer?tab=feature-previews` link is replace-redirected by `DeveloperPage` to `/settings/developer/feature-previews?highlight=key:feature-previews-section`, whose `key:` form rings the element carrying that `data-setting-key` — the section's wrapper, so the whole moved section is ringed rather than one card. Because the file lives under `pages/settings/`, its three toggles ARE indexed into Settings search via `PANEL_TAB_MAP` — the search hit reaches the labelled opt-in switch, not the page it holds, which stays un-advertised until the flag is on), which fires `mc-preview-flag-changed`; `usePreviewFlagRevision()` turns that into a revision number the rail uses both to re-render and as a memo dep, so the row appears without a reload. A cross-tab `storage` event on any `mc-preview-` key does the same. One occupant today: `/webhooks` (the endpoint is supported, the page is not finished). A `previewFlag` alone does not cover the **browser-tab attention count**: it reads the registry directly rather than `getAdvertisedSurfaces()`, so `selectAllSurfacesAttention` applies the predicate itself — the tab title is an advertisement too, and a gated surface that still contributed would show a `(1)` with no rail row to trace it to. `hiddenFromNav` is the deliberate opposite there: it keeps contributing, because it IS advertised, just on the topbar bell rather than the rail. The gate is on the INGRESS only: a gated route stays routable, so turning the flag off never orphans existing work. Retiring a gate is deleting the `previewFlag` and the feature's card. This is distinct from `hiddenFromNav`, which is permanent and means "rendered elsewhere" (the App Store's Explore link, the topbar notifications bell). +**Preview-gated surfaces** — a registry entry may carry `previewFlag`, the key of an opt-in switch (`utils/previewFlags.ts`, all keys prefixed `mc-preview-`). The switch is kept on the gateway under `dashboard.feature_previews.` (the key without its prefix, in snake_case), so every origin starts from the same stored value. localStorage under the `mc-preview-` key is a cache, which surfaces read synchronously; it can briefly differ from the gateway while a write is in flight, and a switch whose carry-up was refused stays on in that browser only. `usePreviewFlagServerSync` (mounted in `shell/appShell.tsx`) keeps the two in step: the gateway value wins over the cache except for a switch whose write is still in flight, each toggle is written through the owner-only config PATCH with one switch's writes sent in click order, a refused toggle puts the switch back to the value it had before the click (moved on by any write the gateway accepted since) with a notice naming it, and a switch set only in this browser before the gateway kept the switches is carried up with `if_unset`, once per page load until the gateway holds a value for it. A non-owner session reads the owner's switches but cannot change them; a switch it already had on in that browser stays on there only while the gateway holds no value for it. While the flag is off the surface is not advertised **anywhere**. The safe list has a name: consumers read **`getAdvertisedSurfaces()`** (= `getBuiltinSurfaces()` minus gated entries) rather than filtering per call site, because a call site that reaches for the unfiltered list and forgets the filter leaks an unreleased surface silently. `useAppRailOrder` (`shell/nav/appRail.tsx`) derives `advertisedNavItems` once and feeds BOTH rail list paths (Main and the Apps group) from it; the Search Everywhere Pages provider reads the same accessor. The bottom-fixed rows are looked up by id (`settings`, `capabilities`) and are core surfaces that are never gated. Gated surfaces deliberately REMAIN in `getBuiltinSurfaces()` so registry-wide invariants (every surface carries a translatable `labelKey`) still cover them. Their route stays registered, which is what makes the surface reachable once the flag is on. The flags are listed as one card per feature on **Settings → Developer → Feature Previews** (the section is `pages/settings/FeaturePreviewsSection.tsx`, the first page of `DeveloperPanel`'s SubNav, above the internals pages. It keeps the registry's "surface" vocabulary in code while its copy says "features" and "pages". The old `/developer?tab=feature-previews` link is replace-redirected by `DeveloperPage` to `/settings/developer/feature-previews?highlight=key:feature-previews-section`, whose `key:` form rings the element carrying that `data-setting-key` — the section's wrapper, so the whole moved section is ringed rather than one card. Because the file lives under `pages/settings/`, its three toggles ARE indexed into Settings search via `PANEL_TAB_MAP` — the search hit reaches the labelled opt-in switch, not the page it holds, which stays un-advertised until the flag is on), which fires `mc-preview-flag-changed`; `usePreviewFlagRevision()` turns that into a revision number the rail uses both to re-render and as a memo dep, so the row appears without a reload. A cross-tab `storage` event on any `mc-preview-` key does the same. One occupant today: `/webhooks` (the endpoint is supported, the page is not finished). A `previewFlag` alone does not cover the **browser-tab attention count**: it reads the registry directly rather than `getAdvertisedSurfaces()`, so `selectAllSurfacesAttention` applies the predicate itself — the tab title is an advertisement too, and a gated surface that still contributed would show a `(1)` with no rail row to trace it to. `hiddenFromNav` is the deliberate opposite there: it keeps contributing, because it IS advertised, just on the topbar bell rather than the rail. The gate is on the INGRESS only: a gated route stays routable, so turning the flag off never orphans existing work. Retiring a gate is deleting the `previewFlag` and the feature's card. This is distinct from `hiddenFromNav`, which is permanent and means "rendered elsewhere" (the App Store's Explore link, the topbar notifications bell). **Agent monitor — `Ctrl+G`** (`useKeyboardShortcuts.ts`, predicate `isAgentMonitorChord`): opens the **Subagents** activity tab (`openActivityToTab('subagents')`) and routes to `/chat`, since the activity panel is owned by the chat page. This is the one chord that is **literal Ctrl on every platform** rather than ⌘-on-Mac: the kiro-cli backend emits `Press ctrl+g to monitor progress.` into its crew-pipeline tool result, that string lives inside the backend binary and cannot be re-worded per OS, so the chord the user is told to press must be the chord that fires (on macOS find-next is ⌘G, leaving ⌃G free). It requires exactly one primary modifier and no Alt/Shift, and deliberately fires **inside text fields** — the hint is read while a crew is running and focus is normally in the composer, so an input bail-out would make it dead exactly when it is needed. It is skipped for `.xterm` targets, where Ctrl+G is BEL and belongs to the PTY. Because the branch requires `ctrlKey && !altKey`, `KeyG` is deliberately **not** added to `RESERVED_PANEL_CODES`: it cannot shadow a downstream Alt+G panel registration, so reserving it would over-claim the panel-navigation extension seam. diff --git a/src/kiro_crew/change_card_catalog.py b/src/kiro_crew/change_card_catalog.py index 1f673f2369ca..01d60479c4eb 100644 --- a/src/kiro_crew/change_card_catalog.py +++ b/src/kiro_crew/change_card_catalog.py @@ -829,6 +829,7 @@ def s(value: Any, limit: int = 60) -> str: from kiro_crew import mate_capability_catalog as _mate_catalog # noqa: F401 from kiro_crew.config.sections import ( # noqa: F401 DEFAULT_MODEL, + FEATURE_PREVIEW_FLAGS, MEMBER_APPROVAL_MODES, effective_pin_scope, normalize_agent_model, diff --git a/src/kiro_crew/change_card_catalog_kinds.py b/src/kiro_crew/change_card_catalog_kinds.py index 7d6061e48411..c7d7e0a6e3b4 100644 --- a/src/kiro_crew/change_card_catalog_kinds.py +++ b/src/kiro_crew/change_card_catalog_kinds.py @@ -26,7 +26,7 @@ from kiro_crew import mate_capability_catalog as _mate_catalog from kiro_crew import member_goals as _goals -from kiro_crew.config.sections import MEMBER_APPROVAL_MODES +from kiro_crew.config.sections import FEATURE_PREVIEW_FLAGS, MEMBER_APPROVAL_MODES from kiro_crew.terminal_safe import _is_invisible KIND_SETTING_CHANGE = "setting.change" @@ -219,6 +219,10 @@ "computer_use.screenshot_max_px", "dashboard.crewmate_threads", "dashboard.dynamic_dashboard_cards", + # A feature preview only decides whether the dashboard OFFERS an + # unreleased page or menu entry; the feature's own routes and checks + # are the same either way. + *(f"dashboard.feature_previews.{_name}" for _name in FEATURE_PREVIEW_FLAGS), "dashboard.folder_sort", "dashboard.mcp_probe_timeout_secs", "dashboard.prevent_sleep", diff --git a/src/kiro_crew/config/loader.py b/src/kiro_crew/config/loader.py index 8519659fcfee..c3c80dad9f73 100644 --- a/src/kiro_crew/config/loader.py +++ b/src/kiro_crew/config/loader.py @@ -725,6 +725,7 @@ def build_provider_factory(cfg: "KiroCrewConfig") -> Callable: _crew_mode_agent_or_default, _default_memory_mode_from, _default_session_folder_or_empty, + _feature_previews, _folder_sort_from, _jira_auth_entry, _load_idle_exempt_keys, diff --git a/src/kiro_crew/config/loader_builders.py b/src/kiro_crew/config/loader_builders.py index f8ab6e31832f..07fa83ddb781 100644 --- a/src/kiro_crew/config/loader_builders.py +++ b/src/kiro_crew/config/loader_builders.py @@ -1036,6 +1036,22 @@ def _default_session_folder_or_empty(value: object) -> str: return value.strip() if isinstance(value, str) else "" +def _feature_previews(value: object, default: dict) -> dict: + """``dashboard.feature_previews`` as ``{name: bool}`` over the known preview names. + + A non-object reads as *default* (nothing on). Inside it, a name this build does + not know and a value that is not a literal ``true``/``false`` are dropped, so a + hand-edited ``"yes"`` or ``1`` reads as absent (off) rather than as on. + """ + if not isinstance(value, dict): + return default + return { + name: flag + for name, flag in value.items() + if name in _sections.FEATURE_PREVIEW_FLAGS and isinstance(flag, bool) + } + + def _build_dashboard_config(_degraded: set[str], dashboard_data: dict) -> DashboardConfig: section = _sections.SectionReader(DashboardConfig, dashboard_data) gitlab_hosts = _coerce_gitlab_hosts(section.get("gitlab_hosts")) @@ -1058,6 +1074,7 @@ def _build_dashboard_config(_degraded: set[str], dashboard_data: dict) -> Dashbo restore_sessions=section.get("restore_sessions"), crewmate_threads=section.read("crewmate_threads", _safe_bool), crewmates_in_agent_picker=section.read("crewmates_in_agent_picker", _safe_bool), + feature_previews=section.read("feature_previews", _feature_previews), dynamic_dashboard_cards=section.read("dynamic_dashboard_cards", _safe_bool), qr_session_until_restart=section.read("qr_session_until_restart", _safe_bool), qr_session_persist_across_restart=section.read( diff --git a/src/kiro_crew/config/sections.py b/src/kiro_crew/config/sections.py index 9831df3e4806..31ea15561419 100644 --- a/src/kiro_crew/config/sections.py +++ b/src/kiro_crew/config/sections.py @@ -214,6 +214,7 @@ CHAT_ENTRY_CACHE_ENTRIES_MAX, CHAT_ENTRY_CACHE_ENTRIES_MIN, EXTERNAL_TERMINAL_APPS, + FEATURE_PREVIEW_FLAGS, LEGACY_VERBOSITY_ALIASES, LINK_PATTERN_PATTERN_MAX_LEN, LINK_PATTERN_URL_MAX_LEN, diff --git a/src/kiro_crew/config/sections_dashboard.py b/src/kiro_crew/config/sections_dashboard.py index 00b9ecc0dcc3..ac9a135954ab 100644 --- a/src/kiro_crew/config/sections_dashboard.py +++ b/src/kiro_crew/config/sections_dashboard.py @@ -27,6 +27,23 @@ "xfce4-terminal", ) +# The dashboard's feature-preview switches (Settings > Developer > Feature +# previews) stored under ``dashboard.feature_previews``, by name. Each name is a +# ``mc-preview-`` key in ``website/src/utils/previewFlags.ts`` with its +# hyphens written as underscores (config paths are snake_case); that file keeps +# the browser's copy as a cache of this section, and +# test_feature_previews_config.py pins the two lists equal. +FEATURE_PREVIEW_FLAGS: tuple[str, ...] = ( + "artifact_deploy", + "crew_mode", + "crewmate_harness", + "folder_conductor", + "layout_harness", + "remote_crew_chat", + "session_environments", + "webhooks", +) + @dataclass class JiraAuthEntry: @@ -217,6 +234,28 @@ class DashboardConfig: "reloaded; no gateway restart.", ), ) + feature_previews: dict = field( + default_factory=dict, + metadata=_meta( + "Feature previews", + "Which unreleased dashboard features are turned on under Settings > " + "Developer > Feature previews, by name, each true or false. Kept here " + "so a switch stays as set on every browser, device and dashboard " + "address of this gateway. A name that is absent reads as off. Takes " + "effect on the next dashboard read; no restart.", + properties={ + name: { + "type": "boolean", + "default": False, + "x-meta": { + "label": f"Feature preview: {name}", + "help": f"Turn on the '{name}' feature preview.", + }, + } + for name in FEATURE_PREVIEW_FLAGS + }, + ), + ) qr_session_until_restart: bool = field( default=True, metadata=_meta( diff --git a/src/kiro_crew/dashboard/handlers/core.py b/src/kiro_crew/dashboard/handlers/core.py index 7cbe92a3d346..97af76513129 100644 --- a/src/kiro_crew/dashboard/handlers/core.py +++ b/src/kiro_crew/dashboard/handlers/core.py @@ -679,6 +679,7 @@ async def pwa_file(request: web.Request) -> web.StreamResponse: _acp_backend_patch_values, _agent_values, _editable_config_spec, + _preview, _selectable_acp_backends, _tier, ) diff --git a/src/kiro_crew/dashboard/handlers/core_config_schema.py b/src/kiro_crew/dashboard/handlers/core_config_schema.py index 9d17117240f3..13a7d65cc55b 100644 --- a/src/kiro_crew/dashboard/handlers/core_config_schema.py +++ b/src/kiro_crew/dashboard/handlers/core_config_schema.py @@ -47,6 +47,7 @@ DECISION_BUCKET_MIN, DECISION_MODEL_ROUTE_TIERS, EXTERNAL_TERMINAL_APPS, + FEATURE_PREVIEW_FLAGS, FOLDER_SORT_MODES, JUDGE_PROVIDERS, SESSION_SORT_MODES, @@ -539,6 +540,15 @@ def _acp_backend_patch_values() -> list[str]: } +# The Feature previews switches (Settings > Developer > Feature previews), one +# boolean per known preview name. The dashboard keeps a browser copy of each as a +# cache and writes the switch here, so it holds on every browser and address of +# this gateway. Only the names in ``FEATURE_PREVIEW_FLAGS`` are writable, so the +# route cannot grow the section with arbitrary keys. +for _preview in FEATURE_PREVIEW_FLAGS: + _EDITABLE_CONFIG[f"dashboard.feature_previews.{_preview}"] = {"type": "bool"} + + # The wake judge's two per-point settings. In the editable set where # ``provider.*`` is not, and the difference is what each one decides: the endpoint # chooses WHERE collected state is sent and ``api_key`` is schema-sensitive, while diff --git a/src/kiro_crew/dashboard/server_runtime/config_watch.py b/src/kiro_crew/dashboard/server_runtime/config_watch.py index 1edf5c0856c7..465cfc926938 100644 --- a/src/kiro_crew/dashboard/server_runtime/config_watch.py +++ b/src/kiro_crew/dashboard/server_runtime/config_watch.py @@ -225,6 +225,14 @@ async def _apply_crew_mode_agent(change: Any) -> None: crew_mode_migration.schedule_on_config_change(state, getattr(change, "new", None)) state.push_refresh("agents") + def _push_feature_previews(change: ConfigChange) -> None: + # The Feature previews switches are read from the shared config query, + # which never goes stale on its own; a refresh frame is what makes every + # other open dashboard re-read it, so a switch flipped on one surface + # reaches the others without a reload. + if change.touched("dashboard.feature_previews"): + state.push_refresh("config") + # The workflow-run ceiling and the channel caps are not registered here: # WorkflowService and ChannelManager bind their own setters in their # constructors (``live.bind``), the rule for an applier a long-lived object owns. @@ -244,6 +252,11 @@ async def _apply_crew_mode_agent(change: Any) -> None: callback=_apply_crew_mode_agent, name="agent.crew_mode_agent", ), + live.subscribe( + "dashboard.feature_previews", + callback=_push_feature_previews, + name="dashboard.feature_previews", + ), ] # Closures are held strongly by the registry; keep the handles on the app so # the registrations are visible (and cancellable) from tests. diff --git a/src/kiro_crew/docs/configuration.md b/src/kiro_crew/docs/configuration.md index 961811eb5830..bf34dd6a8ab5 100644 --- a/src/kiro_crew/docs/configuration.md +++ b/src/kiro_crew/docs/configuration.md @@ -363,6 +363,7 @@ whether or not that preview is on. | `dashboard.link_patterns` | Rewrite matching plain text in transcripts into links at display time, through the same autolink rule engine editions register vocabulary on. Each rule pairs a JavaScript regex with an absolute http(s) URL template in which `{match}` inserts the matched text percent-encoded (no userinfo, placeholder outside the host), e.g. `{"pattern": "\\bPROJ-\\d+\\b", "url": "https://tracker.example.com/browse/{match}"}`. Code blocks and existing links are never rewritten; an inline code span whose whole text matches becomes a link chip. At most 50 rules with distinct patterns, each carrying at most one wide quantifier (`*`, `+`, `{n,}` or a wide `{n,m}`; narrow ranges may accompany it), scanning at most 2000 characters per text block | `[]` | | `dashboard.feature_videos_cache_max_mb` | Disk budget for downloaded clips. Whole release folders are removed oldest-first to fit; the release you are running is never removed. `0` = no cap | `500` | | `dashboard.crewmates_in_agent_picker` | List mates in the chat composer's agent picker beside the agent templates. Off: the picker lists templates plus any mate no listed template already covers; the default agent stays even when covered, unless a template shares its name. Takes effect when the dashboard is reloaded; no gateway restart | `false` | +| `dashboard.feature_previews` | Which unreleased dashboard features are on under Settings > Developer > Feature previews, as `{name: true/false}` (names: `artifact_deploy`, `crew_mode`, `crewmate_harness`, `folder_conductor`, `layout_harness`, `remote_crew_chat`, `session_environments`, `webhooks`). The dashboard keeps a browser copy as a cache and writes each switch here, so it stays set on every browser and dashboard address. An absent name, an unknown name, or a value that is not `true`/`false` reads as off | `{}` | | `dashboard.jira_auth` | Per-host Jira connection entries for the Issues panel, each `{"host": ..., "email": ...}`. `user` is accepted as an alias of `email` (`email` wins when both are set). The API token is not stored here: it is read from the secrets vault first, then from `.env` as `JIRA_API_TOKEN` (or a per-host token name when several hosts are configured). A Jira Cloud host (`*.atlassian.net`) with no `email`/`user` fails with `jira_config_error` before any request is sent | `[]` | ### Slack diff --git a/test/test_config_live_server_appliers.py b/test/test_config_live_server_appliers.py index 7f4d6e8fcc89..405146ef8f49 100644 --- a/test/test_config_live_server_appliers.py +++ b/test/test_config_live_server_appliers.py @@ -316,6 +316,29 @@ def test_log_level_applier_is_registered_on_its_own_path(self) -> None: assert sub.prefixes == ("agent.log_level",) assert sub.callback() is apply_log_level_from_config + def test_a_feature_preview_change_tells_every_dashboard_to_refresh(self) -> None: + """A switch saved from one dashboard reaches the other open ones. + + They read the switches from a config query that never goes stale on its + own, so only a refresh frame makes them re-read it. An unrelated write + pushes nothing. + """ + state = SimpleNamespace( + workflow_service=None, channel_manager=None, push_refresh=MagicMock() + ) + sub = self._register(state)["dashboard.feature_previews"] + assert sub.prefixes == ("dashboard.feature_previews",) + apply = sub.callback() + cfg = KiroCrewConfig() + apply(ConfigChange(old=cfg, new=cfg, changed=frozenset({"agent.log_level"}))) + state.push_refresh.assert_not_called() + apply( + ConfigChange( + old=cfg, new=cfg, changed=frozenset({"dashboard.feature_previews.crew_mode"}) + ) + ) + state.push_refresh.assert_called_once_with("config") + @pytest.mark.asyncio async def test_the_provider_switch_runs_off_the_watcher_cycle_exactly_once(self) -> None: """``reload_provider_factory`` clears the session registry and then shuts @@ -419,6 +442,7 @@ def test_every_applier_is_registered_and_scoped(self) -> None: "agent.role_models.background", "agent.log_level", "agent.crew_mode_agent", + "dashboard.feature_previews", } # None of them is a catch-all: an unrelated write must dispatch nothing. for sub in subs.values(): diff --git a/test/test_feature_previews_config.py b/test/test_feature_previews_config.py new file mode 100644 index 000000000000..47eaf84349f5 --- /dev/null +++ b/test/test_feature_previews_config.py @@ -0,0 +1,176 @@ +"""``dashboard.feature_previews``: the Feature previews switches, kept by the gateway. + +The dashboard holds a browser copy of each switch as a cache +(``website/src/utils/previewFlags.ts``) and writes it here through the owner-only +config PATCH, so a switch holds on every browser and dashboard address. +""" + +from __future__ import annotations + +import json +import re +from pathlib import Path +from unittest.mock import MagicMock, patch + +import pytest +from aiohttp import web +from aiohttp.test_utils import TestClient, TestServer + +from kiro_crew.config.loader import KiroCrewConfig +from kiro_crew.config.loader_builders import _feature_previews +from kiro_crew.config.sections import FEATURE_PREVIEW_FLAGS + +REPO = Path(__file__).resolve().parents[1] +PREVIEW_FLAGS_TS = REPO / "website/src/utils/previewFlags.ts" + + +@web.middleware +async def _owner_identity(request, handler): + request["user"] = "local-app" + request["app"] = "" + state = request.app.get("state") + if state is not None: + state.owner_id = "" + return await handler(request) + + +def _make_app() -> web.Application: + from kiro_crew.dashboard.handlers import api_kirocrew_config_patch + + app = web.Application(middlewares=[_owner_identity]) + app["state"] = MagicMock() + app.router.add_patch("/api/config/kirocrew", api_kirocrew_config_patch) + return app + + +@pytest.fixture +def tmp_config(tmp_path): + cfg_path = tmp_path / "config.json" + cfg_path.write_text(json.dumps({"dashboard": {"folder_sort": "name"}}), encoding="utf-8") + with patch("kiro_crew.config.loader.config_path", return_value=cfg_path): + yield cfg_path + + +def _frontend_flag_names() -> set[str]: + """The config names of the flags in ``previewFlags.ts``'s ``PREVIEW_FLAGS`` array.""" + text = PREVIEW_FLAGS_TS.read_text(encoding="utf-8") + consts = dict( + re.findall(r"export const (PREVIEW_[A-Z_]+) = `\$\{PREVIEW_FLAG_PREFIX\}([a-z-]+)`", text) + ) + body = re.search(r"export const PREVIEW_FLAGS: readonly string\[\] = \[(.*?)\]", text, re.S) + assert body, "PREVIEW_FLAGS array not found in previewFlags.ts" + members = re.findall(r"PREVIEW_[A-Z_]+", body.group(1)) + return {consts[m].replace("-", "_") for m in members} + + +def test_the_gateway_list_equals_the_dashboard_flags(): + names = _frontend_flag_names() + assert names, "no preview flag constants found in previewFlags.ts" + assert names == set(FEATURE_PREVIEW_FLAGS) + + +def test_nothing_is_on_by_default(): + assert KiroCrewConfig().dashboard.feature_previews == {} + + +@pytest.mark.parametrize( + "raw,expected", + [ + (None, {}), + ([], {}), + ("crew_mode", {}), + ({"crew_mode": True, "webhooks": False}, {"crew_mode": True, "webhooks": False}), + ({"crew_mode": "yes", "webhooks": 1, "layout_harness": None}, {}), + ({"layout-harness": True}, {}), + ({"crew_mode": True, "not_a_preview": True}, {"crew_mode": True}), + ], +) +def test_the_loader_keeps_only_known_names_with_boolean_values(raw, expected): + assert _feature_previews(raw, {}) == expected + + +def test_a_stored_switch_loads(tmp_config): + tmp_config.write_text( + json.dumps({"dashboard": {"feature_previews": {"crew_mode": True}}}), encoding="utf-8" + ) + assert KiroCrewConfig.load().dashboard.feature_previews == {"crew_mode": True} + assert KiroCrewConfig.load().to_dict()["dashboard"]["feature_previews"] == {"crew_mode": True} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("name", FEATURE_PREVIEW_FLAGS) +async def test_each_known_switch_is_writable(tmp_config, name): + async with TestClient(TestServer(_make_app())) as c: + resp = await c.patch( + "/api/config/kirocrew", + json={"path": f"dashboard.feature_previews.{name}", "value": True}, + ) + assert resp.status == 200, await resp.text() + stored = json.loads(tmp_config.read_text(encoding="utf-8")) + assert stored["dashboard"]["feature_previews"] == {name: True} + assert stored["dashboard"]["folder_sort"] == "name" + assert KiroCrewConfig.load().dashboard.feature_previews == {name: True} + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "path,value", + [ + ("dashboard.feature_previews.not_a_preview", True), + ("dashboard.feature_previews.layout-harness", True), + ("dashboard.feature_previews", {"crew_mode": True}), + ("dashboard.feature_previews.crew_mode", "true"), + ("dashboard.feature_previews.crew_mode", 1), + ], +) +async def test_an_unknown_name_or_non_boolean_writes_nothing(tmp_config, path, value): + before = tmp_config.read_bytes() + async with TestClient(TestServer(_make_app())) as c: + resp = await c.patch("/api/config/kirocrew", json={"path": path, "value": value}) + assert resp.status == 400, await resp.text() + assert tmp_config.read_bytes() == before + + +@pytest.mark.asyncio +async def test_the_one_time_carry_up_writes_a_switch_the_gateway_does_not_hold(tmp_config): + async with TestClient(TestServer(_make_app())) as c: + resp = await c.patch( + "/api/config/kirocrew", + json={"path": "dashboard.feature_previews.crew_mode", "value": True, "if_unset": True}, + ) + assert resp.status == 200, await resp.text() + stored = json.loads(tmp_config.read_text(encoding="utf-8")) + assert stored["dashboard"]["feature_previews"] == {"crew_mode": True} + assert KiroCrewConfig.load().dashboard.feature_previews == {"crew_mode": True} + + +@pytest.mark.asyncio +async def test_the_one_time_carry_up_never_replaces_a_stored_switch(tmp_config): + tmp_config.write_text( + json.dumps({"dashboard": {"feature_previews": {"crew_mode": False}}}), encoding="utf-8" + ) + before = tmp_config.read_bytes() + async with TestClient(TestServer(_make_app())) as c: + resp = await c.patch( + "/api/config/kirocrew", + json={"path": "dashboard.feature_previews.crew_mode", "value": True, "if_unset": True}, + ) + assert resp.status == 409, await resp.text() + assert (await resp.json())["code"] == "already_set" + assert tmp_config.read_bytes() == before + + +@pytest.mark.asyncio +async def test_a_non_owner_cannot_write_a_switch(tmp_config): + before = tmp_config.read_bytes() + with patch( + "kiro_crew.dashboard.handlers.source_providers.is_owner_dashboard_request", + return_value=False, + ): + async with TestClient(TestServer(_make_app())) as c: + resp = await c.patch( + "/api/config/kirocrew", + json={"path": "dashboard.feature_previews.crew_mode", "value": True}, + ) + assert resp.status in (401, 403), await resp.text() + assert tmp_config.read_bytes() == before diff --git a/website/src/hooks/usePreviewFlagServerSync.ts b/website/src/hooks/usePreviewFlagServerSync.ts new file mode 100644 index 000000000000..a8e76f19a80e --- /dev/null +++ b/website/src/hooks/usePreviewFlagServerSync.ts @@ -0,0 +1,326 @@ +import { useEffect, useSyncExternalStore } from 'react' +import { useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query' + +import { api } from '../api/client' +import { setConfigPathValue } from '../pages/settings/useOptimisticConfigPaths' +import { + PREVIEW_FLAGS, PREVIEW_INSTANCE_SESSIONS, PREVIEW_REMOTE_CREW_CHAT, cachePreviewFlag, + previewFlagConfigPath, previewFlagName, readPreviewFlag, setPreviewFlagPersister, +} from '../utils/previewFlags' +import { safeGetItem, safeSetItem } from '../utils/safeStorage' + +/** The slice of the `['kirocrewConfig']` body this sync reads. */ +export type PreviewFlagsConfigBody = { dashboard?: { feature_previews?: unknown } } + +const CONFIG_KEY = ['kirocrewConfig'] as const + +/** + * Toggles whose PATCH has not settled yet, counted per flag. While a flag has + * one in flight, a config body read before the write landed still carries the + * old value, and applying it would flip the switch back under the user's hand. + */ +const pending = new Map() + +/** + * The last queued PATCH per flag. Each write for a flag starts only after the + * one before it settled, so the gateway applies a flag's writes in click order + * and the last click is the value it keeps. + */ +const tails = new Map>() + +/** Per flag with toggles queued: the value a refusal of the last one puts back. */ +const baselines = new Map() + +/** + * Flags this document has already tried to carry up from the cache. A failed + * carry is not retried on every config refetch; the next document load tries + * again. + */ +const carried = new Set() + +/** Carries this document started that have not settled, and whether any failed. */ +let carriesInFlight = 0 +let carryFailed = false + +/** + * Set in this browser once its cache has been brought in line with a server + * copy, so every cache-only ON from then on is a value the server gave and + * later dropped, not one set before the server kept the switches. Outside the + * `mc-preview-` prefix, so it is never read as a flag. + */ +export const PREVIEW_FLAGS_SYNCED_KEY = 'kc-feature-previews-synced' + +/** + * The flags this browser has seen the server hold, or has saved to it, kept per + * flag as a JSON array of keys. A flag listed here that the server no longer + * holds was dropped there, so it reads as OFF even while the browser as a whole + * is not yet marked synced (a carry of another switch may have failed). Outside + * the `mc-preview-` prefix, so it is never read as a flag. + */ +export const PREVIEW_FLAGS_SERVER_BACKED_KEY = 'kc-feature-previews-server-backed' + +/** + * The last toggle the gateway refused, for the Feature previews section to say + * so. Without it a refused write would only flip the switch back, which reads + * as the switch not working. `denied` is a 403: the dashboard session is not + * the gateway owner, who alone may write config. + */ +export type PreviewFlagWriteError = { + flag: string + denied: boolean + /** + * The one-time carry-up of a switch set in this browser before the gateway + * kept it was refused (anything but the 409 that means the gateway already + * holds a value). The switch stays on here, so the notice says it is on in + * this browser only rather than that it was switched back. + */ + carry?: true +} + +let writeError: PreviewFlagWriteError | null = null +const writeErrorListeners = new Set<() => void>() + +function setWriteError(next: PreviewFlagWriteError | null): void { + if (writeError === next) return + writeError = next + for (const listener of writeErrorListeners) listener() +} + +/** Forget the last refused toggle (the notice's dismiss). */ +export function clearPreviewFlagWriteError(): void { + setWriteError(null) +} + +function subscribeWriteError(listener: () => void): () => void { + writeErrorListeners.add(listener) + return () => { writeErrorListeners.delete(listener) } +} + +/** The last toggle the gateway refused, or `null`; cleared by the next accepted toggle. */ +export function usePreviewFlagWriteError(): PreviewFlagWriteError | null { + return useSyncExternalStore(subscribeWriteError, () => writeError, () => null) +} + +/** Reset the module state between tests. */ +export function __resetPreviewFlagServerSyncForTests(): void { + setWriteError(null) + pending.clear() + tails.clear() + baselines.clear() + carried.clear() + documentBacked.clear() + carriesInFlight = 0 + carryFailed = false +} + +function markSynced(): void { + safeSetItem(PREVIEW_FLAGS_SYNCED_KEY, '1') +} + +/** + * The flags this document has seen the server hold, kept beside the stored + * record so a storage write that fails still counts for the rest of the page. + */ +const documentBacked = new Set() + +/** The flags this browser knows the server has held; an unreadable entry reads as none. */ +function serverBacked(): Set { + let stored: string[] = [] + try { + const raw: unknown = JSON.parse(safeGetItem(PREVIEW_FLAGS_SERVER_BACKED_KEY) ?? '[]') + if (Array.isArray(raw)) stored = raw.filter((v): v is string => typeof v === 'string') + } catch { + // Read as none; the document's own record still applies. + } + return new Set([...stored, ...documentBacked]) +} + +function markServerBacked(flag: string): void { + documentBacked.add(flag) + safeSetItem(PREVIEW_FLAGS_SERVER_BACKED_KEY, JSON.stringify([...serverBacked()])) +} + +/** The server's `{name: bool}` map, or `null` when the body has none to trust. */ +function serverFlags(body: PreviewFlagsConfigBody | undefined): Record | null { + const fp = body?.dashboard?.feature_previews + return fp !== null && typeof fp === 'object' && !Array.isArray(fp) ? fp as Record : null +} + +function settle(qc: QueryClient, flag: string): void { + const left = (pending.get(flag) ?? 1) - 1 + if (left > 0) pending.set(flag, left) + else { + pending.delete(flag) + baselines.delete(flag) + } + // Reconcile against the refetched body directly: one equal to the body already + // cached keeps its identity (structural sharing), so the hook's effect would not + // run again, and a refused write would leave the cache disagreeing with it. + void qc.invalidateQueries({ queryKey: CONFIG_KEY }) + .then(() => reconcilePreviewFlags(qc, qc.getQueryData(CONFIG_KEY))) +} + +/** + * Queue one write of *flag* to the gateway, after any earlier write of it. A + * refused write is put right by the refetch it ends with: the server's own + * value, when it has one, is what the cache then takes. A refused toggle is + * also kept for {@link usePreviewFlagWriteError}, so the switch moving back + * comes with a reason, and is put back to the value it had before the click. + * `ifUnset` makes the gateway refuse (409) when the key is already set. + * Resolves to whether the gateway accepted it (for a carry, a 409 counts: the + * gateway already holds a value for the flag). + */ +function persist(qc: QueryClient, flag: string, on: boolean, ifUnset = false): Promise { + // The value a refusal puts back: what the switch showed before the first of + // the clicks now queued, moved on by each one the gateway accepts. Reverting + // to `!on` instead would land on the previous click, not on a saved value. + // A carry still in flight does not count as a queued click, so the first + // click behind it records the value the switch showed before it. + if (!ifUnset && !baselines.has(flag)) baselines.set(flag, !on) + pending.set(flag, (pending.get(flag) ?? 0) + 1) + const write = (tails.get(flag) ?? Promise.resolve()) + .then(() => api.patchConfig(previewFlagConfigPath(flag), on, ifUnset ? { ifUnset: true } : undefined)) + .then(() => { + // Store the accepted value in the cached config body, so readers of it agree with the write. + qc.setQueryData(CONFIG_KEY, prev => + prev && setConfigPathValue(prev, previewFlagConfigPath(flag), on)) + markServerBacked(flag) + // An accepted carry is a saved value too, so a click queued behind it + // that is refused goes back to it. + if (baselines.has(flag)) baselines.set(flag, on) + // Clears only this switch's notice: another switch's refused write is + // still true after this one saved. + if (!ifUnset && writeError?.flag === flag) setWriteError(null) + return true + }, (e: unknown) => { + const status = (e as { status?: unknown } | null)?.status + // A carry the gateway answered 409 found the key already set: the server + // holds a choice for it, which is what the carry was there to make sure of. + // A 403 is owner-only unless the session itself no longer authenticates, + // which is a different cause to name. + const authRequired = (e as { authRequired?: unknown } | null)?.authRequired === true + const denied = status === 403 && !authRequired + if (ifUnset) { + if (status === 409) { + markServerBacked(flag) + return true + } + // A click queued behind the carry decides where the switch ends, so the + // carry's outcome is not reported over it. + if (pending.get(flag) === 1) setWriteError({ flag, denied, carry: true }) + return false + } + // In a browser that has not synced yet, a refused toggle leaves this + // browser's own value unsaved anywhere else, so it must not be marked + // synced: the next reconcile would then read the switch as off. + if (safeGetItem(PREVIEW_FLAGS_SYNCED_KEY) !== '1') carryFailed = true + // Only the last queued write reports and reverts: a later click still on + // its way decides where the switch ends, and a notice saying "switched + // back" under it would be wrong. The revert happens here rather than in + // the refetch: with no server value for the flag (or no body at all), + // reconcile would keep the cache, or carry it up. `carried` keeps + // reconcile from carrying the refused value up afterwards. + if (pending.get(flag) === 1) { + setWriteError({ flag, denied }) + carried.add(flag) + cachePreviewFlag(flag, baselines.get(flag) ?? !on) + } + return false + }) + const tail = write.then(() => settle(qc, flag)) + tails.set(flag, tail) + void tail.then(() => { if (tails.get(flag) === tail) tails.delete(flag) }) + return write +} + +/** + * Bring the browser cache in line with one config body. + * + * - A flag the server holds as `true`/`false` is written into the cache when the + * cache differs, unless a toggle of that flag is still in flight. + * - A flag the server does not hold reads as OFF, except in a browser that has + * never synced and has never seen the server hold that flag (tracked per + * flag, so one switch's failed carry cannot keep another dropped switch on): + * there a cache-only ON is carried up once with `if_unset`, so + * a value another surface wrote first is never replaced. This is the one-time + * migration of a switch set before the server kept it. + * - The retired "Remote crew sessions" key is never carried as itself: an ON is + * carried as "Chat on a crew", and the key is cleared once the server holds + * that switch, so it cannot keep the feature on behind a switch reading off. + * - A body with no `feature_previews` object (a failed read has none) leaves the + * cache as it is. + */ +export function reconcilePreviewFlags(qc: QueryClient, body: PreviewFlagsConfigBody | undefined): void { + const fp = serverFlags(body) + if (fp === null) return + const synced = safeGetItem(PREVIEW_FLAGS_SYNCED_KEY) === '1' + const backed = serverBacked() + const remote = fp[previewFlagName(PREVIEW_REMOTE_CREW_CHAT)] + if (readPreviewFlag(PREVIEW_INSTANCE_SESSIONS) + && (synced || backed.has(PREVIEW_REMOTE_CREW_CHAT) || typeof remote === 'boolean')) { + cachePreviewFlag(PREVIEW_INSTANCE_SESSIONS, false) + } + // A flag with a toggle in flight is not settled yet, so this pass cannot + // conclude the migration: its value may still have to be carried up. + let deferred = false + for (const flag of PREVIEW_FLAGS) { + if (pending.has(flag)) { + deferred = true + continue + } + const server = fp[previewFlagName(flag)] + if (typeof server === 'boolean') { + if (readPreviewFlag(flag) !== server) cachePreviewFlag(flag, server) + if (!backed.has(flag)) markServerBacked(flag) + // A refused carry said this switch was on in this browser only; now that + // the gateway holds a value for it, that notice no longer holds. + if (writeError?.flag === flag && writeError.carry) setWriteError(null) + continue + } + const cacheOn = readPreviewFlag(flag) + || (flag === PREVIEW_REMOTE_CREW_CHAT && readPreviewFlag(PREVIEW_INSTANCE_SESSIONS)) + if (!cacheOn) continue + // A flag the server held before and no longer does was dropped there, + // whatever became of another flag's carry. + if (synced || backed.has(flag)) { + cachePreviewFlag(flag, false) + continue + } + if (carried.has(flag)) continue + carried.add(flag) + carriesInFlight += 1 + void persist(qc, flag, true, true).then(ok => { + carriesInFlight -= 1 + if (!ok) carryFailed = true + if (carriesInFlight === 0 && !carryFailed && pending.size === 0) markSynced() + }) + } + if (!synced && !deferred && carriesInFlight === 0 && !carryFailed) markSynced() +} + +/** + * Keep the Feature previews switches on the gateway, with the browser copy as a + * cache (see `utils/previewFlags.ts`). Mount once, in the app shell. + * + * Reads the shared `['kirocrewConfig']` query, which a config `refresh` frame + * already invalidates, so a switch flipped on another surface reaches this one + * without a reload. Installs the persister `setPreviewFlag` hands each toggle to. + */ +export function usePreviewFlagServerSync(): void { + const qc = useQueryClient() + const { data } = useQuery({ + queryKey: CONFIG_KEY, + queryFn: () => api.kirocrewConfig(), + }) + useEffect(() => { + setPreviewFlagPersister((flag, on) => { + // The retired key has no server copy; `setRemoteCrewChat` clears it in the + // cache only. + if (PREVIEW_FLAGS.includes(flag)) void persist(qc, flag, on) + }) + return () => setPreviewFlagPersister(null) + }, [qc]) + useEffect(() => { + reconcilePreviewFlags(qc, data) + }, [qc, data]) +} diff --git a/website/src/i18n/locales/bn.json b/website/src/i18n/locales/bn.json index 782b8e34ce21..3c885014eca6 100644 --- a/website/src/i18n/locales/bn.json +++ b/website/src/i18n/locales/bn.json @@ -17148,11 +17148,15 @@ "developerPanel": { "developer_tools": "ডেভেলপার টুল", "feature_previews": "ফিচার প্রিভিউ", - "feature_previews_desc": "অপ্রকাশিত ফিচার ও পেজ। এখানে চালু না করা পর্যন্ত এই পেজগুলো সাইডবারে ও সর্বত্র সার্চ-এ দেখা যায় না; তবে নিচের সুইচগুলো সেটিংস অনুসন্ধানে খুঁজে পাওয়া যায়। এগুলো ইচ্ছাকৃতভাবেই অসম্পূর্ণ এবং শুধু এই ডিভাইসে প্রযোজ্য, যদি না কোনো কার্ডে অন্য কিছু লেখা থাকে।", + "feature_previews_desc": "অপ্রকাশিত ফিচার ও পেজ। এখানে তোমার বেছে নেওয়া সেটিং এই {{productName}}-এ সংরক্ষিত থাকে, তাই যেকোনো ব্রাউজারে বা ডেস্কটপ অ্যাপে ড্যাশবোর্ড খুললেই তা প্রযোজ্য হয়। এখানে চালু না করা পর্যন্ত এই পেজগুলো সাইডবারে ও সর্বত্র সার্চ-এ দেখা যায় না; তবে নিচের সুইচগুলো সেটিংস অনুসন্ধানে খুঁজে পাওয়া যায়। এগুলো ইচ্ছাকৃতভাবেই অসম্পূর্ণ।", "gateway": "গেটওয়ে", "how_to_set_up_an_ssh_tunnel": "কীভাবে SSH টানেল সেট আপ করবেন", "run_a_local_gateway": "লোকাল গেটওয়ে চালান", - "turn_it_off_only_when_a_gateway_already_answers": "এই মেশিনে একটি গেটওয়ে চালু করে। এই অ্যাপের পোর্ট যদি আগে থেকেই অন্য কোনো মেশিনের ক্রুতে না পৌঁছায়, তাহলে চালু রাখুন; নইলে পরের বার অ্যাপ খুললে (তখনই এটি প্রযোজ্য হয়) সংযোগ হবে না। এর জন্য Connection মেনুর “Set Remote Host…” দিয়ে এই পোর্টের জন্য ক্রু সংরক্ষণ করতে হবে, সঙ্গে একটি টানেল: সেখানে “Keep an SSH tunnel to this crew open” টিক দিন (macOS ও Linux) অথবা নিজের SSH টানেল চালু রাখুন। এটি বন্ধ থাকলে সেটিংস → রিমোট ক্রু সংযোগগুলো বন্ধ হয়ে যায়, তাই সেগুলো গণ্য নয়।" + "turn_it_off_only_when_a_gateway_already_answers": "এই মেশিনে একটি গেটওয়ে চালু করে। এই অ্যাপের পোর্ট যদি আগে থেকেই অন্য কোনো মেশিনের ক্রুতে না পৌঁছায়, তাহলে চালু রাখুন; নইলে পরের বার অ্যাপ খুললে (তখনই এটি প্রযোজ্য হয়) সংযোগ হবে না। এর জন্য Connection মেনুর “Set Remote Host…” দিয়ে এই পোর্টের জন্য ক্রু সংরক্ষণ করতে হবে, সঙ্গে একটি টানেল: সেখানে “Keep an SSH tunnel to this crew open” টিক দিন (macOS ও Linux) অথবা নিজের SSH টানেল চালু রাখুন। এটি বন্ধ থাকলে সেটিংস → রিমোট ক্রু সংযোগগুলো বন্ধ হয়ে যায়, তাই সেগুলো গণ্য নয়।", + "feature_previews_save_denied": "শুধু এই {{productName}}-এর মালিক ফিচার প্রিভিউ বদলাতে পারেন, তাই “{{name}}” আগের অবস্থায় ফিরিয়ে দেওয়া হয়েছে।", + "feature_previews_save_failed": "“{{name}}” সংরক্ষণ করা যায়নি, তাই এটি আগের অবস্থায় ফিরিয়ে দেওয়া হয়েছে। আবার চেষ্টা করো।", + "feature_previews_carry_failed": "“{{name}}” শুধু এই ব্রাউজারে চালু আছে: এটি এই {{productName}}-এ সংরক্ষণ করা যায়নি। আবার চেষ্টা করতে পেজটি রিলোড করো; ততক্ষণ এটি চালু থাকবে।", + "feature_previews_carry_denied": "“{{name}}” এখানে সংরক্ষণ হওয়ার আগেই এই ব্রাউজারে চালু করা হয়েছিল। শুধু এই {{productName}}-এর মালিক এটি সংরক্ষণ করতে পারেন, তাই এটি শুধু এই ব্রাউজারে চালু থাকবে।" }, "discordPanel": { "allowed_server_channel_ids": "অনুমোদিত সার্ভার চ্যানেল ID", diff --git a/website/src/i18n/locales/de.json b/website/src/i18n/locales/de.json index 8b73bfa48343..54e486330a7c 100644 --- a/website/src/i18n/locales/de.json +++ b/website/src/i18n/locales/de.json @@ -17148,11 +17148,15 @@ "developerPanel": { "developer_tools": "Entwicklerwerkzeuge", "feature_previews": "Funktionsvorschauen", - "feature_previews_desc": "Nicht veröffentlichte Funktionen und Seiten. Die Seiten erscheinen weder in der Seitenleiste noch in „Überall suchen“, bis du sie hier aktivierst; die Schalter selbst findet die Einstellungssuche aber. Sie sind absichtlich unfertig und gelten nur für dieses Gerät, sofern eine Karte nichts anderes sagt.", + "feature_previews_desc": "Nicht veröffentlichte Funktionen und Seiten. Deine Auswahl wird in dieser {{productName}} gespeichert und gilt überall, wo du das Dashboard öffnest, in jedem Browser und in der Desktop-App. Die Seiten erscheinen weder in der Seitenleiste noch in „Überall suchen“, bis du sie hier aktivierst; die Schalter selbst findet die Einstellungssuche aber. Sie sind absichtlich unfertig.", "gateway": "Gateway", "how_to_set_up_an_ssh_tunnel": "So richtest du einen SSH-Tunnel ein", "run_a_local_gateway": "Lokales Gateway ausführen", - "turn_it_off_only_when_a_gateway_already_answers": "Startet ein Gateway auf diesem Rechner. Lass es an, außer der Port dieser App erreicht bereits eine Crew auf einem anderen Rechner – sonst kann die App beim nächsten Öffnen, wenn dies wirksam wird, keine Verbindung herstellen. Dazu muss die Crew für diesen Port mit „Set Remote Host…“ im Menü Connection gespeichert sein, plus ein Tunnel: kreuz dort „Keep an SSH tunnel to this crew open“ an (macOS und Linux) oder lass einen eigenen SSH-Tunnel laufen. Verbindungen unter Einstellungen → Remote-Crew enden, wenn dies aus ist, und zählen daher nicht." + "turn_it_off_only_when_a_gateway_already_answers": "Startet ein Gateway auf diesem Rechner. Lass es an, außer der Port dieser App erreicht bereits eine Crew auf einem anderen Rechner – sonst kann die App beim nächsten Öffnen, wenn dies wirksam wird, keine Verbindung herstellen. Dazu muss die Crew für diesen Port mit „Set Remote Host…“ im Menü Connection gespeichert sein, plus ein Tunnel: kreuz dort „Keep an SSH tunnel to this crew open“ an (macOS und Linux) oder lass einen eigenen SSH-Tunnel laufen. Verbindungen unter Einstellungen → Remote-Crew enden, wenn dies aus ist, und zählen daher nicht.", + "feature_previews_save_denied": "Nur der Besitzer dieser {{productName}} kann Funktionsvorschauen ändern, daher wurde „{{name}}“ zurückgesetzt.", + "feature_previews_save_failed": "„{{name}}“ konnte nicht gespeichert werden und wurde zurückgesetzt. Versuch es noch einmal.", + "feature_previews_carry_failed": "„{{name}}“ ist nur in diesem Browser aktiv: Es konnte nicht in dieser {{productName}} gespeichert werden. Lade die Seite neu, um es noch einmal zu versuchen; bis dahin bleibt es aktiv.", + "feature_previews_carry_denied": "„{{name}}“ wurde in diesem Browser aktiviert, bevor es hier gespeichert werden konnte. Nur der Besitzer dieser {{productName}} kann es speichern, daher bleibt es nur in diesem Browser aktiv." }, "discordPanel": { "allowed_server_channel_ids": "Erlaubte Server-Kanal-IDs", diff --git a/website/src/i18n/locales/en-XA.json b/website/src/i18n/locales/en-XA.json index 1d8647cb8df5..a1af77fabce4 100644 --- a/website/src/i18n/locales/en-XA.json +++ b/website/src/i18n/locales/en-XA.json @@ -16869,7 +16869,11 @@ "run_a_local_gateway": "[Ŕùñ à ĺøçàĺ ğàţèẁàý ·················]", "turn_it_off_only_when_a_gateway_already_answers": "[Şţàŕţ à ğàţèẁàý øñ ţĥìş ɱàçĥìñè. Ĺèàṽè ìţ øñ ùñĺèşş ţĥìş àþþ'ş þøŕţ àĺŕèàðý ŕèàçĥèş à çŕèẁ øñ àñøţĥèŕ ɱàçĥìñè, øŕ ţĥè àþþ çàññøţ çøññèçţ ţĥè ñèẋţ ţìɱè ìţ øþèñş, ẁĥìçĥ ìş ẁĥèñ ţĥìş ţàķèş èƒƒèçţ. Ţĥàţ ñèèðş ţĥè çŕèẁ şàṽèð ƒøŕ ţĥìş þøŕţ ẁìţĥ “Şèţ Ŕèɱøţè Ĥøşţ…” ìñ ţĥè Çøññèçţìøñ ɱèñù, þĺùş à ţùññèĺ: ţìçķ “Ķèèþ àñ ŞŞĤ ţùññèĺ ţø ţĥìş çŕèẁ øþèñ” ţĥèŕè (ɱàçØŞ àñð Ĺìñùẋ) øŕ ķèèþ ýøùŕ øẁñ ŞŞĤ ţùññèĺ ŕùññìñğ. Şèţţìñğş → Ŕèɱøţè Çŕèẁ çøññèçţìøñş şţøþ ẁĥèñ ţĥìş ìş øƒƒ, şø ţĥèý ðø ñøţ çøùñţ. ················································································································································]", "feature_previews": "[Ƒèàţùŕè Þŕèṽìèẁş ··············]", - "feature_previews_desc": "[Ùñŕèĺèàşèð ƒèàţùŕèş àñð þàğèş. Ţĥè þàğèş şţàý ĥìððèñ ƒŕøɱ ţĥè şìðèƀàŕ àñð ƒŕøɱ Şèàŕçĥ Èṽèŕýẁĥèŕè ùñţìĺ ýøù ţùŕñ ţĥèɱ øñ ĥèŕè; ţĥè şẁìţçĥèş ţĥèɱşèĺṽèş ðø şĥøẁ ùþ ìñ Şèţţìñğş şèàŕçĥ. Ùñþøĺìşĥèð øñ þùŕþøşè, àñð þèŕ-ðèṽìçè ùñĺèşş à çàŕð şàýş øţĥèŕẁìşè. ··········································································]" + "feature_previews_desc": "[Ùñŕèĺèàşèð ƒèàţùŕèş àñð þàğèş. Ýøùŕ çĥøìçèş ĥèŕè àŕè şàṽèð øñ ţĥìş {{productName}}, şø ţĥèý àþþĺý ẁĥèŕèṽèŕ ýøù øþèñ ţĥè ðàşĥƀøàŕð, ìñ àñý ƀŕøẁşèŕ øŕ ìñ ţĥè ðèşķţøþ àþþ. Ţĥè þàğèş şţàý ĥìððèñ ƒŕøɱ ţĥè şìðèƀàŕ àñð ƒŕøɱ Şèàŕçĥ Èṽèŕýẁĥèŕè ùñţìĺ ýøù ţùŕñ ţĥèɱ øñ ĥèŕè; ţĥè şẁìţçĥèş ţĥèɱşèĺṽèş ðø şĥøẁ ùþ ìñ Şèţţìñğş şèàŕçĥ. Ùñþøĺìşĥèð øñ þùŕþøşè. ··································································································]", + "feature_previews_save_denied": "[Øñĺý ţĥè øẁñèŕ øƒ ţĥìş {{productName}} çàñ çĥàñğè ƒèàţùŕè þŕèṽìèẁş, şø “{{name}}” ẁàş şẁìţçĥèð ƀàçķ. ·······················]", + "feature_previews_save_failed": "[Çøùĺðñ’ţ şàṽè “{{name}}”, şø ìţ ẁàş şẁìţçĥèð ƀàçķ. Ţŕý àğàìñ. ···················]", + "feature_previews_carry_failed": "[“{{name}}” ìş øñ ìñ ţĥìş ƀŕøẁşèŕ øñĺý: ìţ çøùĺðñ’ţ ƀè şàṽèð øñ ţĥìş {{productName}}. Ŕèĺøàð ţĥè þàğè ţø ţŕý àğàìñ; ìţ şţàýş øñ ùñţìĺ ţĥèñ. ···································]", + "feature_previews_carry_denied": "[“{{name}}” ẁàş ţùŕñèð øñ ìñ ţĥìş ƀŕøẁşèŕ ƀèƒøŕè ìţ çøùĺð ƀè şàṽèð ĥèŕè. Øñĺý ţĥè øẁñèŕ øƒ ţĥìş {{productName}} çàñ şàṽè ìţ, şø ìţ şţàýş øñ ìñ ţĥìş ƀŕøẁşèŕ øñĺý. ·········································]" }, "displayPanel": { "applying": "[Àþþĺýìñğ… ··············]", diff --git a/website/src/i18n/locales/en.manual.json b/website/src/i18n/locales/en.manual.json index 540ed17794ad..fa110c8b3fc4 100644 --- a/website/src/i18n/locales/en.manual.json +++ b/website/src/i18n/locales/en.manual.json @@ -7882,7 +7882,11 @@ }, "developerPanel": { "feature_previews": "Feature Previews", - "feature_previews_desc": "Unreleased features and pages. The pages stay hidden from the sidebar and from Search Everywhere until you turn them on here; the switches themselves do show up in Settings search. Unpolished on purpose, and per-device unless a card says otherwise." + "feature_previews_desc": "Unreleased features and pages. Your choices here are saved on this {{productName}}, so they apply wherever you open the dashboard, in any browser or in the desktop app. The pages stay hidden from the sidebar and from Search Everywhere until you turn them on here; the switches themselves do show up in Settings search. Unpolished on purpose.", + "feature_previews_save_denied": "Only the owner of this {{productName}} can change feature previews, so “{{name}}” was switched back.", + "feature_previews_save_failed": "Couldn’t save “{{name}}”, so it was switched back. Try again.", + "feature_previews_carry_failed": "“{{name}}” is on in this browser only: it couldn’t be saved on this {{productName}}. Reload the page to try again; it stays on until then.", + "feature_previews_carry_denied": "“{{name}}” was turned on in this browser before it could be saved here. Only the owner of this {{productName}} can save it, so it stays on in this browser only." }, "computerUsePanel": { "computer_use_lets_the_agent_read_any_app_window": "Computer use lets the agent read any app window and send clicks and keystrokes into it. Most clicks are delivered straight to the app and leave your pointer alone, but the agent can ask to move the real pointer when a target needs it. Password fields are never read; nothing else limits which apps it may drive.", diff --git a/website/src/i18n/locales/es.json b/website/src/i18n/locales/es.json index 845359fbbbea..bde248807f85 100644 --- a/website/src/i18n/locales/es.json +++ b/website/src/i18n/locales/es.json @@ -17443,11 +17443,15 @@ "developerPanel": { "developer_tools": "Herramientas de desarrollo", "feature_previews": "Vistas previas de funciones", - "feature_previews_desc": "Funciones y páginas sin publicar. Las páginas siguen ocultas de la barra lateral y de Buscar en todo hasta que las actives aquí; los propios interruptores sí aparecen en la búsqueda de configuración. Sin terminar a propósito y solo para este dispositivo, salvo que una tarjeta indique lo contrario.", + "feature_previews_desc": "Funciones y páginas sin publicar. Lo que elijas aquí se guarda en este {{productName}} y se aplica dondequiera que abras el panel, en cualquier navegador o en la aplicación de escritorio. Las páginas siguen ocultas de la barra lateral y de Buscar en todo hasta que las actives aquí; los propios interruptores sí aparecen en la búsqueda de configuración. Sin terminar a propósito.", "gateway": "Gateway", "how_to_set_up_an_ssh_tunnel": "Cómo configurar un túnel SSH", "run_a_local_gateway": "Ejecutar un gateway local", - "turn_it_off_only_when_a_gateway_already_answers": "Inicia un gateway en este equipo. Déjalo activado salvo que el puerto de esta app ya llegue a un Crew en otro equipo; si no, la app no podrá conectarse la próxima vez que se abra, que es cuando se aplica este cambio. Para eso, el Crew debe estar guardado para este puerto con “Set Remote Host…” en el menú Connection, más un túnel: marca “Keep an SSH tunnel to this crew open” allí (macOS y Linux) o mantén tu propio túnel SSH en marcha. Las conexiones de Ajustes → Crew remoto se detienen cuando esto está desactivado, así que no cuentan." + "turn_it_off_only_when_a_gateway_already_answers": "Inicia un gateway en este equipo. Déjalo activado salvo que el puerto de esta app ya llegue a un Crew en otro equipo; si no, la app no podrá conectarse la próxima vez que se abra, que es cuando se aplica este cambio. Para eso, el Crew debe estar guardado para este puerto con “Set Remote Host…” en el menú Connection, más un túnel: marca “Keep an SSH tunnel to this crew open” allí (macOS y Linux) o mantén tu propio túnel SSH en marcha. Las conexiones de Ajustes → Crew remoto se detienen cuando esto está desactivado, así que no cuentan.", + "feature_previews_save_denied": "Solo el propietario de este {{productName}} puede cambiar las vistas previas de funciones, así que «{{name}}» se ha restablecido.", + "feature_previews_save_failed": "No se pudo guardar «{{name}}», así que se ha restablecido. Inténtalo de nuevo.", + "feature_previews_carry_failed": "«{{name}}» está activado solo en este navegador: no se pudo guardar en este {{productName}}. Vuelve a cargar la página para intentarlo de nuevo; hasta entonces sigue activado.", + "feature_previews_carry_denied": "«{{name}}» se activó en este navegador antes de que pudiera guardarse aquí. Solo el propietario de este {{productName}} puede guardarlo, así que sigue activado solo en este navegador." }, "discordPanel": { "allowed_server_channel_ids": "IDs de canales de servidor permitidos", diff --git a/website/src/i18n/locales/fr.json b/website/src/i18n/locales/fr.json index 0ae73de67584..129e1705de2f 100644 --- a/website/src/i18n/locales/fr.json +++ b/website/src/i18n/locales/fr.json @@ -17443,11 +17443,15 @@ "developerPanel": { "developer_tools": "Outils de développement", "feature_previews": "Aperçus de fonctionnalités", - "feature_previews_desc": "Fonctionnalités et pages non publiées. Les pages restent masquées dans la barre latérale et dans Rechercher partout jusqu’à ce que tu les actives ici ; les interrupteurs eux-mêmes apparaissent bien dans la recherche des paramètres. Inachevées à dessein, et valables pour cet appareil uniquement, sauf indication contraire sur une carte.", + "feature_previews_desc": "Fonctionnalités et pages non publiées. Tes choix sont enregistrés sur ce {{productName}} et s’appliquent partout où tu ouvres le tableau de bord, dans n’importe quel navigateur ou dans l’application de bureau. Les pages restent masquées dans la barre latérale et dans Rechercher partout jusqu’à ce que tu les actives ici ; les interrupteurs eux-mêmes apparaissent bien dans la recherche des paramètres. Inachevées à dessein.", "gateway": "Passerelle", "how_to_set_up_an_ssh_tunnel": "Configurer un tunnel SSH", "run_a_local_gateway": "Exécuter une passerelle locale", - "turn_it_off_only_when_a_gateway_already_answers": "Démarre une passerelle sur cette machine. Laisse-la activée sauf si le port de cette app atteint déjà une Crew sur une autre machine ; sinon l'app ne pourra pas se connecter à sa prochaine ouverture, moment où ce réglage prend effet. Il faut pour cela que la Crew soit enregistrée pour ce port avec « Set Remote Host… » dans le menu Connection, plus un tunnel : coche « Keep an SSH tunnel to this crew open » à cet endroit (macOS et Linux) ou garde ton propre tunnel SSH actif. Les connexions de Réglages → Crew distante s'arrêtent quand ce réglage est désactivé ; elles ne comptent donc pas." + "turn_it_off_only_when_a_gateway_already_answers": "Démarre une passerelle sur cette machine. Laisse-la activée sauf si le port de cette app atteint déjà une Crew sur une autre machine ; sinon l'app ne pourra pas se connecter à sa prochaine ouverture, moment où ce réglage prend effet. Il faut pour cela que la Crew soit enregistrée pour ce port avec « Set Remote Host… » dans le menu Connection, plus un tunnel : coche « Keep an SSH tunnel to this crew open » à cet endroit (macOS et Linux) ou garde ton propre tunnel SSH actif. Les connexions de Réglages → Crew distante s'arrêtent quand ce réglage est désactivé ; elles ne comptent donc pas.", + "feature_previews_save_denied": "Seul le propriétaire de ce {{productName}} peut modifier les aperçus de fonctionnalités, « {{name}} » a donc été rétabli.", + "feature_previews_save_failed": "Impossible d’enregistrer « {{name}} », il a donc été rétabli. Réessaie.", + "feature_previews_carry_failed": "« {{name}} » est activé dans ce navigateur uniquement : impossible de l’enregistrer sur ce {{productName}}. Recharge la page pour réessayer ; il reste activé d’ici là.", + "feature_previews_carry_denied": "« {{name}} » a été activé dans ce navigateur avant de pouvoir être enregistré ici. Seul le propriétaire de ce {{productName}} peut l’enregistrer, il reste donc activé dans ce navigateur uniquement." }, "discordPanel": { "allowed_server_channel_ids": "ID de canaux de serveur autorisés", diff --git a/website/src/i18n/locales/hi.json b/website/src/i18n/locales/hi.json index 677600a9e81f..1cbd423027af 100644 --- a/website/src/i18n/locales/hi.json +++ b/website/src/i18n/locales/hi.json @@ -17148,11 +17148,15 @@ "developerPanel": { "developer_tools": "डेवलपर टूल्स", "feature_previews": "फ़ीचर प्रीव्यू", - "feature_previews_desc": "अप्रकाशित फ़ीचर और पेज. जब तक तुम इन्हें यहाँ चालू नहीं करते, ये पेज साइडबार और हर जगह खोजें में नहीं दिखते; लेकिन नीचे के स्विच सेटिंग्स खोज में मिल जाते हैं. ये जान-बूझकर अपूर्ण हैं और इसी डिवाइस पर लागू होते हैं, बशर्ते किसी कार्ड में कुछ और न लिखा हो।", + "feature_previews_desc": "अप्रकाशित फ़ीचर और पेज. यहाँ तुम्हारी पसंद इस {{productName}} पर सहेजी जाती है, इसलिए तुम किसी भी ब्राउज़र या डेस्कटॉप ऐप में डैशबोर्ड खोलो, वह लागू रहती है. जब तक तुम इन्हें यहाँ चालू नहीं करते, ये पेज साइडबार और हर जगह खोजें में नहीं दिखते; लेकिन नीचे के स्विच सेटिंग्स खोज में मिल जाते हैं. ये जान-बूझकर अपूर्ण हैं।", "gateway": "गेटवे", "how_to_set_up_an_ssh_tunnel": "SSH टनल कैसे सेट अप करो", "run_a_local_gateway": "लोकल गेटवे चलाएँ", - "turn_it_off_only_when_a_gateway_already_answers": "इस मशीन पर गेटवे शुरू करता है। इसे चालू रखो, जब तक इस ऐप का पोर्ट पहले से किसी दूसरी मशीन के क्रू तक नहीं पहुँचता; वरना अगली बार ऐप खुलने पर (तभी यह लागू होता है) कनेक्शन नहीं हो पाएगा। इसके लिए Connection मेन्यू में “Set Remote Host…” से इस पोर्ट के लिए क्रू सहेजा होना चाहिए, साथ में एक टनल: वहाँ “Keep an SSH tunnel to this crew open” पर टिक करो (macOS और Linux) या अपना SSH टनल चालू रखो। इसके बंद होने पर सेटिंग्स → रिमोट क्रू कनेक्शन रुक जाते हैं, इसलिए वे गिने नहीं जाते।" + "turn_it_off_only_when_a_gateway_already_answers": "इस मशीन पर गेटवे शुरू करता है। इसे चालू रखो, जब तक इस ऐप का पोर्ट पहले से किसी दूसरी मशीन के क्रू तक नहीं पहुँचता; वरना अगली बार ऐप खुलने पर (तभी यह लागू होता है) कनेक्शन नहीं हो पाएगा। इसके लिए Connection मेन्यू में “Set Remote Host…” से इस पोर्ट के लिए क्रू सहेजा होना चाहिए, साथ में एक टनल: वहाँ “Keep an SSH tunnel to this crew open” पर टिक करो (macOS और Linux) या अपना SSH टनल चालू रखो। इसके बंद होने पर सेटिंग्स → रिमोट क्रू कनेक्शन रुक जाते हैं, इसलिए वे गिने नहीं जाते।", + "feature_previews_save_denied": "सिर्फ़ इस {{productName}} का मालिक फ़ीचर प्रीव्यू बदल सकता है, इसलिए “{{name}}” वापस पहले जैसा कर दिया गया।", + "feature_previews_save_failed": "“{{name}}” सहेजा नहीं जा सका, इसलिए उसे वापस पहले जैसा कर दिया गया. फिर से कोशिश करो।", + "feature_previews_carry_failed": "“{{name}}” सिर्फ़ इस ब्राउज़र में चालू है: इसे इस {{productName}} पर सहेजा नहीं जा सका. फिर से कोशिश करने के लिए पेज रीलोड करो; तब तक यह चालू रहेगा।", + "feature_previews_carry_denied": "“{{name}}” यहाँ सहेजे जाने से पहले ही इस ब्राउज़र में चालू किया गया था. सिर्फ़ इस {{productName}} का मालिक इसे सहेज सकता है, इसलिए यह सिर्फ़ इस ब्राउज़र में चालू रहेगा।" }, "discordPanel": { "allowed_server_channel_ids": "अनुमत सर्वर चैनल ID", diff --git a/website/src/i18n/locales/it.json b/website/src/i18n/locales/it.json index f184debaf340..5e72828553cd 100644 --- a/website/src/i18n/locales/it.json +++ b/website/src/i18n/locales/it.json @@ -17443,11 +17443,15 @@ "developerPanel": { "developer_tools": "Strumenti per sviluppatori", "feature_previews": "Anteprime delle funzionalità", - "feature_previews_desc": "Funzionalità e pagine non rilasciate. Le pagine restano nascoste dalla barra laterale e da Cerca in tutto finché non le attivi qui; gli interruttori stessi compaiono invece nella ricerca delle impostazioni. Sono incomplete di proposito e valgono solo per questo dispositivo, a meno che una scheda non dica il contrario.", + "feature_previews_desc": "Funzionalità e pagine non rilasciate. Le tue scelte vengono salvate su questo {{productName}} e valgono ovunque apri la dashboard, in qualsiasi browser o nell’app desktop. Le pagine restano nascoste dalla barra laterale e da Cerca in tutto finché non le attivi qui; gli interruttori stessi compaiono invece nella ricerca delle impostazioni. Sono incomplete di proposito.", "gateway": "Gateway", "how_to_set_up_an_ssh_tunnel": "Come configurare un tunnel SSH", "run_a_local_gateway": "Esegui un gateway locale", - "turn_it_off_only_when_a_gateway_already_answers": "Avvia un gateway su questa macchina. Lascialo attivo a meno che la porta di questa app non raggiunga già una Crew su un'altra macchina; altrimenti l'app non potrà connettersi alla prossima apertura, che è quando questa impostazione ha effetto. Serve che la Crew sia salvata per questa porta con “Set Remote Host…” nel menu Connection, più un tunnel: spunta “Keep an SSH tunnel to this crew open” lì (macOS e Linux) oppure mantieni attivo un tuo tunnel SSH. Le connessioni di Impostazioni → Crew remota si fermano quando questa opzione è disattivata, quindi non contano." + "turn_it_off_only_when_a_gateway_already_answers": "Avvia un gateway su questa macchina. Lascialo attivo a meno che la porta di questa app non raggiunga già una Crew su un'altra macchina; altrimenti l'app non potrà connettersi alla prossima apertura, che è quando questa impostazione ha effetto. Serve che la Crew sia salvata per questa porta con “Set Remote Host…” nel menu Connection, più un tunnel: spunta “Keep an SSH tunnel to this crew open” lì (macOS e Linux) oppure mantieni attivo un tuo tunnel SSH. Le connessioni di Impostazioni → Crew remota si fermano quando questa opzione è disattivata, quindi non contano.", + "feature_previews_save_denied": "Solo il proprietario di questo {{productName}} può modificare le anteprime delle funzionalità, quindi «{{name}}» è stato ripristinato.", + "feature_previews_save_failed": "Impossibile salvare «{{name}}», quindi è stato ripristinato. Riprova.", + "feature_previews_carry_failed": "«{{name}}» è attivo solo in questo browser: non è stato possibile salvarlo su questo {{productName}}. Ricarica la pagina per riprovare; fino ad allora resta attivo.", + "feature_previews_carry_denied": "«{{name}}» è stato attivato in questo browser prima che potesse essere salvato qui. Solo il proprietario di questo {{productName}} può salvarlo, quindi resta attivo solo in questo browser." }, "discordPanel": { "allowed_server_channel_ids": "ID dei canali del server consentiti", diff --git a/website/src/i18n/locales/ja.json b/website/src/i18n/locales/ja.json index 5a449d26387c..7b8226e11deb 100644 --- a/website/src/i18n/locales/ja.json +++ b/website/src/i18n/locales/ja.json @@ -16853,11 +16853,15 @@ "developerPanel": { "developer_tools": "開発者ツール", "feature_previews": "機能プレビュー", - "feature_previews_desc": "未リリースの機能とページです。ここでオンにするまで、ページ自体はサイドバーと「すべてから検索」には表示されませんが、下のスイッチは設定の検索で見つかります。内容は意図的に未完成のままです。カードに別の記載がない限り、設定はこのデバイスのみに適用されます。", + "feature_previews_desc": "未リリースの機能とページです。ここでの選択はこの {{productName}} に保存され、どのブラウザーやデスクトップアプリでダッシュボードを開いても同じように適用されます。ここでオンにするまで、ページ自体はサイドバーと「すべてから検索」には表示されませんが、下のスイッチは設定の検索で見つかります。内容は意図的に未完成のままです。", "gateway": "ゲートウェイ", "how_to_set_up_an_ssh_tunnel": "SSH トンネルの設定方法", "run_a_local_gateway": "ローカルゲートウェイを実行する", - "turn_it_off_only_when_a_gateway_already_answers": "このマシンでゲートウェイを起動します。このアプリのポートがすでに別のマシンのクルーにつながっている場合を除き、オンのままにしてください。そうでないと、次回アプリを開いたとき(この設定が反映されるとき)に接続できません。そのためには、Connection メニューの「Set Remote Host…」でこのポートのクルーを保存し、さらにトンネルが必要です:そこで「Keep an SSH tunnel to this crew open」にチェックを入れる(macOS と Linux)か、ご自身の SSH トンネルを維持してください。これがオフのときは 設定 → リモートクルー の接続は止まるため、条件を満たしません。" + "turn_it_off_only_when_a_gateway_already_answers": "このマシンでゲートウェイを起動します。このアプリのポートがすでに別のマシンのクルーにつながっている場合を除き、オンのままにしてください。そうでないと、次回アプリを開いたとき(この設定が反映されるとき)に接続できません。そのためには、Connection メニューの「Set Remote Host…」でこのポートのクルーを保存し、さらにトンネルが必要です:そこで「Keep an SSH tunnel to this crew open」にチェックを入れる(macOS と Linux)か、ご自身の SSH トンネルを維持してください。これがオフのときは 設定 → リモートクルー の接続は止まるため、条件を満たしません。", + "feature_previews_save_denied": "機能プレビューを変更できるのはこの {{productName}} の所有者だけのため、「{{name}}」は元に戻されました。", + "feature_previews_save_failed": "「{{name}}」を保存できなかったため、元に戻されました。もう一度お試しください。", + "feature_previews_carry_failed": "「{{name}}」はこのブラウザーでのみオンです。この {{productName}} に保存できませんでした。ページを再読み込みしてもう一度お試しください。それまではオンのままです。", + "feature_previews_carry_denied": "「{{name}}」はここに保存される前に、このブラウザーでオンにされました。保存できるのはこの {{productName}} の所有者だけのため、このブラウザーでのみオンのままになります。" }, "discordPanel": { "allowed_server_channel_ids": "許可されたサーバーチャネル ID", diff --git a/website/src/i18n/locales/ko.json b/website/src/i18n/locales/ko.json index 2ac9ab72aa78..12ac2d3522f3 100644 --- a/website/src/i18n/locales/ko.json +++ b/website/src/i18n/locales/ko.json @@ -16853,11 +16853,15 @@ "developerPanel": { "developer_tools": "개발자 도구", "feature_previews": "기능 미리 보기", - "feature_previews_desc": "아직 출시되지 않은 기능과 페이지입니다. 여기서 켜기 전에는 페이지가 사이드바와 전체 검색에 표시되지 않지만, 아래 스위치 자체는 설정 검색에서 찾을 수 있습니다. 의도적으로 미완성 상태이며, 카드에 다른 설명이 없으면 이 기기에만 적용됩니다.", + "feature_previews_desc": "아직 출시되지 않은 기능과 페이지입니다. 여기서 고른 설정은 이 {{productName}}에 저장되며, 어떤 브라우저나 데스크톱 앱에서 대시보드를 열어도 똑같이 적용됩니다. 여기서 켜기 전에는 페이지가 사이드바와 전체 검색에 표시되지 않지만, 아래 스위치 자체는 설정 검색에서 찾을 수 있습니다. 의도적으로 미완성 상태입니다.", "gateway": "게이트웨이", "how_to_set_up_an_ssh_tunnel": "SSH 터널 설정 방법", "run_a_local_gateway": "로컬 게이트웨이 실행", - "turn_it_off_only_when_a_gateway_already_answers": "이 컴퓨터에서 게이트웨이를 시작합니다. 이 앱의 포트가 이미 다른 컴퓨터의 크루에 연결되어 있지 않다면 켜 두세요. 그렇지 않으면 다음에 앱을 열 때(이 설정이 적용되는 때) 연결할 수 없습니다. 이를 위해서는 Connection 메뉴의 “Set Remote Host…”로 이 포트에 크루를 저장하고, 터널도 있어야 합니다: 그곳에서 “Keep an SSH tunnel to this crew open”를 체크하거나(macOS 및 Linux) 직접 SSH 터널을 유지하세요. 이 설정이 꺼지면 설정 → 원격 크루 연결도 멈추므로 해당되지 않습니다." + "turn_it_off_only_when_a_gateway_already_answers": "이 컴퓨터에서 게이트웨이를 시작합니다. 이 앱의 포트가 이미 다른 컴퓨터의 크루에 연결되어 있지 않다면 켜 두세요. 그렇지 않으면 다음에 앱을 열 때(이 설정이 적용되는 때) 연결할 수 없습니다. 이를 위해서는 Connection 메뉴의 “Set Remote Host…”로 이 포트에 크루를 저장하고, 터널도 있어야 합니다: 그곳에서 “Keep an SSH tunnel to this crew open”를 체크하거나(macOS 및 Linux) 직접 SSH 터널을 유지하세요. 이 설정이 꺼지면 설정 → 원격 크루 연결도 멈추므로 해당되지 않습니다.", + "feature_previews_save_denied": "기능 미리보기는 이 {{productName}}의 소유자만 변경할 수 있어서 ‘{{name}}’이(가) 원래대로 돌아갔습니다.", + "feature_previews_save_failed": "‘{{name}}’을(를) 저장하지 못해 원래대로 돌아갔습니다. 다시 시도하세요.", + "feature_previews_carry_failed": "‘{{name}}’은(는) 이 브라우저에서만 켜져 있습니다. 이 {{productName}}에 저장하지 못했습니다. 다시 시도하려면 페이지를 새로 고치세요. 그때까지는 켜진 상태로 유지됩니다.", + "feature_previews_carry_denied": "‘{{name}}’은(는) 여기에 저장되기 전에 이 브라우저에서 켜졌습니다. 이 {{productName}}의 소유자만 저장할 수 있어서 이 브라우저에서만 켜져 있습니다." }, "discordPanel": { "allowed_server_channel_ids": "허용된 서버 채널 ID", diff --git a/website/src/i18n/locales/pt.json b/website/src/i18n/locales/pt.json index 8e61cbbdb283..c40c0bb58dda 100644 --- a/website/src/i18n/locales/pt.json +++ b/website/src/i18n/locales/pt.json @@ -17443,11 +17443,15 @@ "developerPanel": { "developer_tools": "Ferramentas de desenvolvedor", "feature_previews": "Prévias de recursos", - "feature_previews_desc": "Recursos e páginas não lançados. As páginas ficam ocultas da barra lateral e da Pesquisar em tudo até você ativá-las aqui; os próprios interruptores, porém, aparecem na busca das configurações. Estão inacabados de propósito e valem só para este dispositivo, a menos que um cartão diga o contrário.", + "feature_previews_desc": "Recursos e páginas não lançados. Suas escolhas ficam salvas neste {{productName}} e valem onde quer que você abra o painel, em qualquer navegador ou no aplicativo para desktop. As páginas ficam ocultas da barra lateral e da Pesquisar em tudo até você ativá-las aqui; os próprios interruptores, porém, aparecem na busca das configurações. Estão inacabados de propósito.", "gateway": "Gateway", "how_to_set_up_an_ssh_tunnel": "Como configurar um túnel SSH", "run_a_local_gateway": "Executar um gateway local", - "turn_it_off_only_when_a_gateway_already_answers": "Inicia um gateway nesta máquina. Deixe ativado, a menos que a porta deste app já chegue a uma Crew em outra máquina; caso contrário, o app não conseguirá se conectar na próxima vez que abrir, que é quando isto entra em vigor. Para isso, a Crew precisa estar salva para esta porta com “Set Remote Host…” no menu Connection, mais um túnel: marque “Keep an SSH tunnel to this crew open” ali (macOS e Linux) ou mantenha seu próprio túnel SSH em execução. As conexões de Configurações → Crew remota param quando isto está desativado, então não contam." + "turn_it_off_only_when_a_gateway_already_answers": "Inicia um gateway nesta máquina. Deixe ativado, a menos que a porta deste app já chegue a uma Crew em outra máquina; caso contrário, o app não conseguirá se conectar na próxima vez que abrir, que é quando isto entra em vigor. Para isso, a Crew precisa estar salva para esta porta com “Set Remote Host…” no menu Connection, mais um túnel: marque “Keep an SSH tunnel to this crew open” ali (macOS e Linux) ou mantenha seu próprio túnel SSH em execução. As conexões de Configurações → Crew remota param quando isto está desativado, então não contam.", + "feature_previews_save_denied": "Só o proprietário deste {{productName}} pode alterar as prévias de recursos, então “{{name}}” voltou ao estado anterior.", + "feature_previews_save_failed": "Não foi possível salvar “{{name}}”, então ele voltou ao estado anterior. Tente de novo.", + "feature_previews_carry_failed": "“{{name}}” está ativado só neste navegador: não foi possível salvá-lo neste {{productName}}. Recarregue a página para tentar de novo; até lá ele continua ativado.", + "feature_previews_carry_denied": "“{{name}}” foi ativado neste navegador antes de poder ser salvo aqui. Só o proprietário deste {{productName}} pode salvá-lo, então ele continua ativado só neste navegador." }, "discordPanel": { "allowed_server_channel_ids": "IDs de canais de servidor permitidos", diff --git a/website/src/i18n/locales/ru.json b/website/src/i18n/locales/ru.json index fcaad2a48dac..845affb71006 100644 --- a/website/src/i18n/locales/ru.json +++ b/website/src/i18n/locales/ru.json @@ -17738,11 +17738,15 @@ "developerPanel": { "developer_tools": "Инструменты разработчика", "feature_previews": "Предпросмотр функций", - "feature_previews_desc": "Невыпущенные функции и страницы. Сами страницы не показываются в боковой панели и в поиске «Искать везде», пока ты не включишь их здесь; переключатели же находятся через поиск по настройкам. Они намеренно не доработаны и действуют только на этом устройстве, если в карточке не сказано иное.", + "feature_previews_desc": "Невыпущенные функции и страницы. Твой выбор сохраняется в этом {{productName}} и действует везде, где ты открываешь панель, в любом браузере и в настольном приложении. Сами страницы не показываются в боковой панели и в поиске «Искать везде», пока ты не включишь их здесь; переключатели же находятся через поиск по настройкам. Они намеренно не доработаны.", "gateway": "Шлюз", "how_to_set_up_an_ssh_tunnel": "Как настроить SSH-туннель", "run_a_local_gateway": "Запускать локальный шлюз", - "turn_it_off_only_when_a_gateway_already_answers": "Запускает шлюз на этом компьютере. Оставь включённым, если только порт этого приложения уже не ведёт к команде на другом компьютере, иначе приложение не сможет подключиться при следующем запуске, когда это изменение вступит в силу. Для этого команда должна быть сохранена для этого порта через «Set Remote Host…» в меню Connection, а также нужен туннель: отметь там «Keep an SSH tunnel to this crew open» (macOS и Linux) или держи собственный SSH-туннель. Подключения в «Настройки → Удалённая команда» останавливаются, когда это выключено, поэтому они не подходят." + "turn_it_off_only_when_a_gateway_already_answers": "Запускает шлюз на этом компьютере. Оставь включённым, если только порт этого приложения уже не ведёт к команде на другом компьютере, иначе приложение не сможет подключиться при следующем запуске, когда это изменение вступит в силу. Для этого команда должна быть сохранена для этого порта через «Set Remote Host…» в меню Connection, а также нужен туннель: отметь там «Keep an SSH tunnel to this crew open» (macOS и Linux) или держи собственный SSH-туннель. Подключения в «Настройки → Удалённая команда» останавливаются, когда это выключено, поэтому они не подходят.", + "feature_previews_save_denied": "Менять предварительные версии функций может только владелец этого {{productName}}, поэтому «{{name}}» возвращён обратно.", + "feature_previews_save_failed": "Не удалось сохранить «{{name}}», поэтому он возвращён обратно. Попробуй ещё раз.", + "feature_previews_carry_failed": "«{{name}}» включён только в этом браузере: его не удалось сохранить в этом {{productName}}. Перезагрузи страницу, чтобы попробовать ещё раз; до тех пор он остаётся включённым.", + "feature_previews_carry_denied": "«{{name}}» был включён в этом браузере до того, как его удалось сохранить здесь. Сохранить его может только владелец этого {{productName}}, поэтому он остаётся включённым только в этом браузере." }, "discordPanel": { "allowed_server_channel_ids": "Разрешённые ID каналов сервера", diff --git a/website/src/i18n/locales/zh-CN.json b/website/src/i18n/locales/zh-CN.json index a0daf0c27eb8..71dafc261ba8 100644 --- a/website/src/i18n/locales/zh-CN.json +++ b/website/src/i18n/locales/zh-CN.json @@ -16853,11 +16853,15 @@ "developerPanel": { "developer_tools": "开发者工具", "feature_previews": "功能预览", - "feature_previews_desc": "尚未发布的功能和页面。在此开启之前,这些页面不会出现在侧边栏和全局搜索中;下面的开关本身则可以通过设置搜索找到。这些内容有意保留未完善的状态;除卡片另有说明外,开关仅对本设备生效。", + "feature_previews_desc": "尚未发布的功能和页面。你在这里的选择保存在此 {{productName}} 上,无论在哪个浏览器或桌面应用中打开仪表板都会生效。在此开启之前,这些页面不会出现在侧边栏和全局搜索中;下面的开关本身则可以通过设置搜索找到。这些内容有意保留未完善的状态。", "gateway": "网关", "how_to_set_up_an_ssh_tunnel": "如何设置 SSH 隧道", "run_a_local_gateway": "运行本地网关", - "turn_it_off_only_when_a_gateway_already_answers": "在这台机器上启动网关。除非本应用的端口已经连到另一台机器上的 Crew,否则请保持开启;不然下次打开应用时(也就是此设置生效时)将无法连接。为此需要用 Connection 菜单中的“Set Remote Host…”为此端口保存该 Crew,并且要有隧道:在那里勾选“Keep an SSH tunnel to this crew open”(macOS 和 Linux),或自己保持 SSH 隧道运行。关闭此项后,设置 → 远程 Crew 中的连接会停止,所以不算数。" + "turn_it_off_only_when_a_gateway_already_answers": "在这台机器上启动网关。除非本应用的端口已经连到另一台机器上的 Crew,否则请保持开启;不然下次打开应用时(也就是此设置生效时)将无法连接。为此需要用 Connection 菜单中的“Set Remote Host…”为此端口保存该 Crew,并且要有隧道:在那里勾选“Keep an SSH tunnel to this crew open”(macOS 和 Linux),或自己保持 SSH 隧道运行。关闭此项后,设置 → 远程 Crew 中的连接会停止,所以不算数。", + "feature_previews_save_denied": "只有此 {{productName}} 的所有者可以更改功能预览,因此“{{name}}”已恢复原状。", + "feature_previews_save_failed": "无法保存“{{name}}”,因此已恢复原状。请重试。", + "feature_previews_carry_failed": "“{{name}}”仅在此浏览器中开启:无法保存到此 {{productName}}。请重新加载页面后重试;在此之前它会保持开启。", + "feature_previews_carry_denied": "“{{name}}”在保存到这里之前就已在此浏览器中开启。只有此 {{productName}} 的所有者可以保存它,因此它仅在此浏览器中保持开启。" }, "discordPanel": { "allowed_server_channel_ids": "允许的服务器频道 ID", diff --git a/website/src/pages/settings/FeaturePreviewsSection.tsx b/website/src/pages/settings/FeaturePreviewsSection.tsx index a6ff067e0a55..44c0580ede63 100644 --- a/website/src/pages/settings/FeaturePreviewsSection.tsx +++ b/website/src/pages/settings/FeaturePreviewsSection.tsx @@ -4,7 +4,9 @@ import { ArrowRight } from 'lucide-react' import { SettingsSection, SettingsCard, SettingsToggle } from '../../components/settings' import { FeaturePreviewIntroButton, type FeaturePreviewIntro } from '../../components/FeaturePreviewIntroDialog' import { usePreviewFlag, useRemoteCrewChat } from '../../hooks/usePreviewFlag' -import { PREVIEW_ARTIFACT_DEPLOY, PREVIEW_CREW_MODE, PREVIEW_CREWMATE_HARNESS, PREVIEW_FOLDER_CONDUCTOR, PREVIEW_LAYOUT_HARNESS, PREVIEW_SESSION_ENVIRONMENTS, PREVIEW_WEBHOOKS, setPreviewFlag, setRemoteCrewChat } from '../../utils/previewFlags' +import { clearPreviewFlagWriteError, usePreviewFlagWriteError } from '../../hooks/usePreviewFlagServerSync' +import ErrorNotice from '../../components/ErrorNotice' +import { PREVIEW_ARTIFACT_DEPLOY, PREVIEW_CREW_MODE, PREVIEW_CREWMATE_HARNESS, PREVIEW_FOLDER_CONDUCTOR, PREVIEW_LAYOUT_HARNESS, PREVIEW_REMOTE_CREW_CHAT, PREVIEW_SESSION_ENVIRONMENTS, PREVIEW_WEBHOOKS, setPreviewFlag, setRemoteCrewChat } from '../../utils/previewFlags' import ErrorBoundary from '../../components/ErrorBoundary' import { KasBundleCard } from '../developer/KasBundleCard' import { KIRO_SIGN_IN_BACKEND } from '../developer/kiroSignInLink' @@ -52,11 +54,14 @@ import { i18nT } from '../../i18n/t' * page it holds. The PAGE stays un-advertised: `getAdvertisedSurfaces()` and * the Search Everywhere Pages provider still filter it until the flag is on. * - * No `configKey` on the four `previewFlags.ts` toggles, deliberately: that prop - * is what makes a `` chip deep-link here and what feeds - * `settingsRegistry.gen.ts`, and a per-device localStorage flag has no config - * path to name at all. Search deep-links still reach every toggle through its - * registry id + `data-setting-label`, which need no configKey. + * No `configKey` on the `previewFlags.ts` toggles. That prop only feeds + * `settingsRegistry.gen.ts` and the `` deep link; it does not pick + * how a toggle saves (these write through `setPreviewFlag`: the browser cache, + * then `dashboard.feature_previews.`). Without it the + * `dashboard.feature_previews.*` paths are not in the registry, so a + * `` naming one falls back to its file/CLI hint. Search deep-links + * still reach every toggle through its registry id + `data-setting-label`, + * which need no configKey. * * The Decisions toggle (now in `DecisionsCard.tsx`) carries no `configKey` either, * for a different reason: it writes no config path. Its value is the KEYSTONE @@ -99,6 +104,25 @@ function webhooksIntro(): FeaturePreviewIntro { } } +/** + * The card label of *flag*, for the notice that names a switch the gateway + * refused. A `switch` of literal `i18nT` calls rather than a table, for the + * same `check-i18n-keys.mjs` reason the cards are not a loop. + */ +function previewFlagLabel(flag: string): string { + switch (flag) { + case PREVIEW_ARTIFACT_DEPLOY: return i18nT('pages.developer.featurePreviewsTab.artifact_deploy') + case PREVIEW_WEBHOOKS: return i18nT('pages.developer.featurePreviewsTab.webhooks') + case PREVIEW_CREW_MODE: return i18nT('pages.developer.featurePreviewsTab.crew_mode') + case PREVIEW_REMOTE_CREW_CHAT: return i18nT('pages.developer.featurePreviewsTab.chat_on_a_crew') + case PREVIEW_LAYOUT_HARNESS: return i18nT('pages.developer.featurePreviewsTab.layout_harness') + case PREVIEW_FOLDER_CONDUCTOR: return i18nT('pages.developer.featurePreviewsTab.folder_conductor') + case PREVIEW_CREWMATE_HARNESS: return i18nT('pages.developer.featurePreviewsTab.crewmate_harness') + case PREVIEW_SESSION_ENVIRONMENTS: return i18nT('sessionEnvironments.title') + default: return i18nT('pages.settings.developerPanel.feature_previews') + } +} + /** * `data-setting-key` anchor on the section wrapper, for * `?highlight=key:` — what the old `/developer?tab=feature-previews` @@ -120,6 +144,7 @@ export function FeaturePreviewsSection() { const crewmateHarness = usePreviewFlag(PREVIEW_CREWMATE_HARNESS) const sessionEnvironments = usePreviewFlag(PREVIEW_SESSION_ENVIRONMENTS) const crewMode = usePreviewFlag(PREVIEW_CREW_MODE) + const writeError = usePreviewFlagWriteError() // The KAS engine card is for a deployment that can select KAS at all: the same // gate its old mount used, read from the schema's `agent.acp_backend` enum. An // unanswered schema hides nothing, as on the harness tab. @@ -143,6 +168,29 @@ export function FeaturePreviewsSection() {

{i18nT('pages.settings.developerPanel.feature_previews_desc')}

+ {/* The gateway refused a toggle and the switch went back to its stored + value. Said once for the section, under the intro, and naming the + switch, so a refused click on a card further down still says which + switch moved back and why. */} + {writeError && ( + + )} {/* Artifact Deploy ships without a "See what it looks like" intro: the capture pipeline shoots a running pod, and the deploy surface's own screens need a registered AWS profile to show anything real. A card with @@ -242,7 +290,7 @@ export function FeaturePreviewsSection() { {/* Dev-only MECHANISM preview, not a shippable surface: the composable-layout mechanism (placement-driven renderer + scope + editor) being built beside the Members page. This card is the FLAG PLUMBING only — the switch exists so - the mechanism can be built and tested behind a per-device gate. + the mechanism can be built and tested behind a preview gate. NO ingress button, on purpose: unlike the webhooks card, this preview has no routable door in the bundle yet, so a link here would point at a route that @@ -294,9 +342,9 @@ export function FeaturePreviewsSection() { and the Install button for the pinned engine. It lives here, not on the KAS harness row, while the route is in shadow testing, so the one click that moves every new session onto an engine still being tested is not in - plain view of every KAS user. Unlike the cards above, the switch is a - server config value, not a per-device flag; the card writes it through - the same config PATCH it always did. Isolated so a throwing card cannot + plain view of every KAS user. Unlike the cards above, the switch is not + a preview flag but its own config value; the card writes it through the + same config PATCH it always did. Isolated so a throwing card cannot take the section down. */} {kasOffered && ( @@ -313,7 +361,7 @@ export function FeaturePreviewsSection() { onChange={value => setPreviewFlag(PREVIEW_SESSION_ENVIRONMENTS, value)} /> - {/* LAST, and the only card here whose switch is not a per-device flag: it + {/* LAST, and the only card here whose switch is not in gateway config: it writes the KEYSTONE `decisions_consent.json`, not a config path. It lives in `DecisionsCard.tsx` because it is a list and a detail rather than one row, and that file's own doc comment carries why. */} diff --git a/website/src/shell/appShell.tsx b/website/src/shell/appShell.tsx index 75af31d5cd5e..e820e6db225d 100644 --- a/website/src/shell/appShell.tsx +++ b/website/src/shell/appShell.tsx @@ -14,6 +14,7 @@ import { fetchNotifications, armBootNotificationsFallback } from '../store/notif import { useWebSocket } from '../hooks/useWebSocket' import { useDashboardHealthProbe } from '../hooks/useDashboardHealthProbe' import { useConfigAutolinkRules } from '../hooks/useConfigAutolinkRules' +import { usePreviewFlagServerSync } from '../hooks/usePreviewFlagServerSync' import { useTheme } from '../hooks/useTheme' import { useShellBranding } from './branding' import { useRumPageView } from '../hooks/useRumPageView' @@ -694,6 +695,9 @@ export function useAppShell() { }) const { kiroUsageOpen, setKiroUsageOpen, kiroUsageState, usageSegmentHidden, kiroAccountEntry } = useKiroUsageReadout() + // Feature previews live on the gateway; this keeps the browser cache of them in + // step. Called beside the credit readout, which already reads ['kirocrewConfig']. + usePreviewFlagServerSync() // Both forms use the side groups' container-query ladders. On desktop the // measured ladder (`.topbar.tb-measured`, index.css) adds folds when those // rungs still leave a group's contents overflowing; its level classes can diff --git a/website/src/test/featurePreviewsSectionNotice.test.tsx b/website/src/test/featurePreviewsSectionNotice.test.tsx new file mode 100644 index 000000000000..e7aa2997959d --- /dev/null +++ b/website/src/test/featurePreviewsSectionNotice.test.tsx @@ -0,0 +1,134 @@ +/** + * The Feature previews section with the gateway sync mounted, as the app shell + * mounts it: every card's switch hands its toggle to the gateway, a refused + * write shows one notice that names the switch that went back, and each + * ingress link opens its page. + */ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' +import { render, screen, act, waitFor, cleanup } from '@testing-library/react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom' + +import { api } from '../api/client' +import { + PREVIEW_FLAGS_SYNCED_KEY, __resetPreviewFlagServerSyncForTests, usePreviewFlagServerSync, +} from '../hooks/usePreviewFlagServerSync' +import { FeaturePreviewsSection } from '../pages/settings/FeaturePreviewsSection' +import { PREVIEW_ARTIFACT_DEPLOY, PREVIEW_WEBHOOKS } from '../utils/previewFlags' + +function Where() { + return
{useLocation().pathname}
+} + +function WithSync() { + usePreviewFlagServerSync() + return +} + +function renderSection() { + return render( + + + + } /> + } /> + + + , + ) +} + +const notice = () => screen.getByTestId('feature-previews-save-error').textContent ?? '' + +beforeEach(() => { + localStorage.clear() + // Synced, so no one-time carry runs and every PATCH below is a click. + localStorage.setItem(PREVIEW_FLAGS_SYNCED_KEY, '1') + __resetPreviewFlagServerSyncForTests() + vi.spyOn(api, 'dashboardConfig').mockResolvedValue({ decisions_enabled: true } as never) + vi.spyOn(api, 'kirocrewConfig').mockResolvedValue({ dashboard: { feature_previews: {} } } as never) + vi.spyOn(api, 'getDecisionsConsent').mockResolvedValue({ + enabled: false, endpoint: '', configured_endpoint: 'https://api.typesafe.ai/v1/systemone', permits: false, + }) +}) + +afterEach(() => { + cleanup() + act(() => { __resetPreviewFlagServerSyncForTests() }) + vi.restoreAllMocks() +}) + +describe('Feature previews section, refused toggles', () => { + it.each([ + [/artifact deploy/i, 'Artifact Deploy'], + [/webhooks/i, 'Webhooks'], + [/^ultra mode/i, 'Ultra Mode'], + [/chat on a crew/i, 'Chat on a crew'], + [/composable layout/i, 'Composable layout'], + [/folder conductor/i, 'Folder conductor'], + [/agent harness per mate/i, 'Agent harness per mate'], + [/session environments/i, 'Session Environments'], + ])('names the %s switch when the owner-only write is refused', async (name, label) => { + vi.spyOn(api, 'patchConfig').mockRejectedValue(Object.assign(new Error('owner only'), { status: 403 })) + renderSection() + await waitFor(() => expect(api.kirocrewConfig).toHaveBeenCalled()) + await act(async () => { screen.getAllByRole('switch', { name })[0].click() }) + await waitFor(() => expect(notice()).toContain(`“${label}” was switched back`)) + expect(notice()).toMatch(/only the owner of this Kiro Crew/i) + // The refetch the refused write ends with has landed, so nothing is still + // in flight when the next test resets the sync state. + await waitFor(() => expect(api.kirocrewConfig).toHaveBeenCalledTimes(2)) + }) + + it('says the save failed for any other refusal', async () => { + vi.spyOn(api, 'patchConfig').mockRejectedValue(Object.assign(new Error('boom'), { status: 500 })) + renderSection() + await waitFor(() => expect(api.kirocrewConfig).toHaveBeenCalled()) + await act(async () => { screen.getAllByRole('switch', { name: /^ultra mode/i })[0].click() }) + await waitFor(() => expect(notice()).toMatch(/couldn’t save “Ultra Mode”, so it was switched back/i)) + await waitFor(() => expect(api.kirocrewConfig).toHaveBeenCalledTimes(2)) + }) + + it('says a switch is on in this browser only when its one-time carry is refused', async () => { + localStorage.removeItem(PREVIEW_FLAGS_SYNCED_KEY) + localStorage.setItem(PREVIEW_WEBHOOKS, '1') + vi.spyOn(api, 'patchConfig').mockRejectedValue(Object.assign(new Error('boom'), { status: 500 })) + renderSection() + await waitFor(() => expect(notice()).toMatch(/“Webhooks” is on in this browser only/i)) + expect(notice()).toMatch(/it stays on until then/i) + expect(notice()).not.toMatch(/for everyone/i) + await waitFor(() => expect(api.kirocrewConfig).toHaveBeenCalledTimes(2)) + // And it really is still on here, as the notice says. + expect(localStorage.getItem(PREVIEW_WEBHOOKS)).toBe('1') + expect(screen.getAllByRole('switch', { name: /webhooks/i })[0].getAttribute('aria-checked')).toBe('true') + }) + + it('names the owner, not a reload, when a one-time carry is refused as owner-only', async () => { + localStorage.removeItem(PREVIEW_FLAGS_SYNCED_KEY) + localStorage.setItem(PREVIEW_WEBHOOKS, '1') + vi.spyOn(api, 'patchConfig').mockRejectedValue(Object.assign(new Error('owner only'), { status: 403 })) + renderSection() + await waitFor(() => expect(notice()).toMatch(/“Webhooks” was turned on in this browser before it could be saved here/i)) + expect(notice()).toMatch(/only the owner of this Kiro Crew can save it/i) + expect(notice()).toMatch(/stays on in this browser only/i) + expect(notice()).not.toMatch(/for everyone/i) + expect(notice()).not.toMatch(/reload/i) + await waitFor(() => expect(api.kirocrewConfig).toHaveBeenCalledTimes(2)) + expect(screen.getAllByRole('switch', { name: /webhooks/i })[0].getAttribute('aria-checked')).toBe('true') + }) +}) + +describe('Feature previews section, ingress links', () => { + it.each([ + [PREVIEW_ARTIFACT_DEPLOY, /open artifact deploy/i, '/deploy'], + [PREVIEW_WEBHOOKS, /open webhooks/i, '/webhooks'], + ])('opens the page %s reveals', async (flag, link, path) => { + localStorage.setItem(flag, '1') + vi.mocked(api.kirocrewConfig).mockResolvedValue( + { dashboard: { feature_previews: { artifact_deploy: true, webhooks: true } } } as never, + ) + renderSection() + await act(async () => { screen.getByRole('button', { name: link }).click() }) + expect(screen.getByTestId('where').textContent).toBe(path) + }) +}) diff --git a/website/src/test/previewFlagServerSync.test.tsx b/website/src/test/previewFlagServerSync.test.tsx new file mode 100644 index 000000000000..dcb75ae08a57 --- /dev/null +++ b/website/src/test/previewFlagServerSync.test.tsx @@ -0,0 +1,598 @@ +/** + * Feature previews are kept by the gateway (`dashboard.feature_previews.`) + * with localStorage as a cache. These tests pin the four parts of that contract: + * the server copy fills an empty cache, a toggle is written to the server, a + * failed config read leaves the cache in charge, and a switch set before the + * server kept it is carried up exactly once without replacing a stored value. + */ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' +import type { ReactNode } from 'react' +import { renderHook, act, waitFor, cleanup } from '@testing-library/react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' + +import { api } from '../api/client' +import { usePreviewFlag } from '../hooks/usePreviewFlag' +import { + PREVIEW_FLAGS_SERVER_BACKED_KEY, PREVIEW_FLAGS_SYNCED_KEY, __resetPreviewFlagServerSyncForTests, clearPreviewFlagWriteError, + usePreviewFlagServerSync, usePreviewFlagWriteError, +} from '../hooks/usePreviewFlagServerSync' +import * as previewFlags from '../utils/previewFlags' +import { + PREVIEW_ARTIFACT_DEPLOY, PREVIEW_CREW_MODE, PREVIEW_FLAGS, PREVIEW_FLAG_PREFIX, PREVIEW_INSTANCE_SESSIONS, + PREVIEW_REMOTE_CREW_CHAT, PREVIEW_WEBHOOKS, previewFlagConfigPath, readPreviewFlag, setPreviewFlag, + setRemoteCrewChat, +} from '../utils/previewFlags' + +type Body = { dashboard?: { feature_previews?: unknown } } + +function harness(qc: QueryClient) { + return ({ children }: { children: ReactNode }) => ( + {children} + ) +} + +function newClient(): QueryClient { + return new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } }) +} + +/** Mount the sync next to a reader of the Ultra Mode flag, as the app shell does. */ +function mountSync(qc: QueryClient) { + return renderHook(() => { + usePreviewFlagServerSync() + return usePreviewFlag(PREVIEW_CREW_MODE) + }, { wrapper: harness(qc) }) +} + +let server: Record +let patchSpy: ReturnType + +beforeEach(() => { + localStorage.clear() + __resetPreviewFlagServerSyncForTests() + server = {} + vi.spyOn(api, 'kirocrewConfig').mockImplementation( + async () => ({ dashboard: { feature_previews: { ...server } } }) as Body, + ) + patchSpy = vi.spyOn(api, 'patchConfig').mockImplementation(async (path: string, value: unknown, opts?: { ifUnset?: boolean }) => { + const name = path.replace('dashboard.feature_previews.', '') + if (opts?.ifUnset && name in server) throw Object.assign(new Error('already set'), { status: 409 }) + server[name] = value as boolean + return { ok: true } + }) +}) + +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +describe('preview flag config paths', () => { + it('names each flag by its snake_case config path', () => { + expect(previewFlagConfigPath(PREVIEW_CREW_MODE)).toBe('dashboard.feature_previews.crew_mode') + expect(previewFlagConfigPath(PREVIEW_ARTIFACT_DEPLOY)).toBe('dashboard.feature_previews.artifact_deploy') + expect(new Set(PREVIEW_FLAGS).size).toBe(PREVIEW_FLAGS.length) + }) + + it('keeps every declared flag on the gateway except the retired one', () => { + const declared = Object.entries(previewFlags) + .filter(([name, v]) => name.startsWith('PREVIEW_') && typeof v === 'string' && v.startsWith(PREVIEW_FLAG_PREFIX)) + .map(([, v]) => v as string) + .filter(v => v !== PREVIEW_INSTANCE_SESSIONS && v !== PREVIEW_FLAG_PREFIX && v !== previewFlags.PREVIEW_FLAG_EVENT) + expect([...PREVIEW_FLAGS].sort()).toEqual(declared.sort()) + }) +}) + +describe('usePreviewFlagServerSync', () => { + it('turns Ultra Mode on from the server when this browser has no copy', async () => { + server = { crew_mode: true } + const { result } = mountSync(newClient()) + await waitFor(() => expect(result.current).toBe(true)) + expect(localStorage.getItem(PREVIEW_CREW_MODE)).toBe('1') + expect(patchSpy).not.toHaveBeenCalled() + }) + + it('lets the server copy win over a stale browser copy', async () => { + server = { crew_mode: false } + localStorage.setItem(PREVIEW_CREW_MODE, '1') + localStorage.setItem(PREVIEW_FLAGS_SYNCED_KEY, '1') + const { result } = mountSync(newClient()) + await waitFor(() => expect(result.current).toBe(false)) + expect(readPreviewFlag(PREVIEW_CREW_MODE)).toBe(false) + expect(patchSpy).not.toHaveBeenCalled() + }) + + it('writes a toggle to the server', async () => { + const qc = newClient() + const { result } = mountSync(qc) + await waitFor(() => expect(api.kirocrewConfig).toHaveBeenCalled()) + act(() => { expect(setPreviewFlag(PREVIEW_CREW_MODE, true)).toBe(true) }) + expect(result.current).toBe(true) + await waitFor(() => expect(server).toEqual({ crew_mode: true })) + expect(patchSpy).toHaveBeenCalledWith('dashboard.feature_previews.crew_mode', true, undefined) + await waitFor(() => expect(qc.getQueryData(['kirocrewConfig'])?.dashboard?.feature_previews).toEqual({ crew_mode: true })) + expect(result.current).toBe(true) + }) + + it('does not flip a switch back while its write is still in flight', async () => { + let release: () => void = () => {} + patchSpy.mockImplementation(async (path: string, value: unknown) => { + await new Promise(r => { release = r }) + server[path.replace('dashboard.feature_previews.', '')] = value as boolean + return { ok: true } + }) + server = { crew_mode: false } + const qc = newClient() + const { result } = mountSync(qc) + await waitFor(() => expect(api.kirocrewConfig).toHaveBeenCalled()) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, true) }) + // A config body read before the write landed still says off. + await act(async () => { await qc.invalidateQueries({ queryKey: ['kirocrewConfig'] }) }) + expect(result.current).toBe(true) + await act(async () => { release() }) + await waitFor(() => expect(server.crew_mode).toBe(true)) + await waitFor(() => expect(qc.getQueryData(['kirocrewConfig'])?.dashboard?.feature_previews).toEqual({ crew_mode: true })) + expect(result.current).toBe(true) + }) + + it('puts a refused write right from the server copy', async () => { + server = { crew_mode: false } + patchSpy.mockRejectedValue(new Error('owner only')) + const { result } = mountSync(newClient()) + await waitFor(() => expect(api.kirocrewConfig).toHaveBeenCalled()) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, true) }) + expect(result.current).toBe(true) + await waitFor(() => expect(result.current).toBe(false)) + }) + + it('reports a toggle the gateway refused as owner-only on a 403', async () => { + server = { crew_mode: false } + patchSpy.mockRejectedValue(Object.assign(new Error('owner only'), { status: 403 })) + const qc = newClient() + const { result } = renderHook(() => { + usePreviewFlagServerSync() + return usePreviewFlagWriteError() + }, { wrapper: harness(qc) }) + await waitFor(() => expect(api.kirocrewConfig).toHaveBeenCalled()) + expect(result.current).toBeNull() + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, true) }) + await waitFor(() => expect(result.current).toEqual({ flag: PREVIEW_CREW_MODE, denied: true })) + act(() => { clearPreviewFlagWriteError() }) + expect(result.current).toBeNull() + }) + + it('reports any other refused toggle as a failed save, and clears it on the next accepted one', async () => { + server = { crew_mode: false } + patchSpy.mockRejectedValueOnce(Object.assign(new Error('boom'), { status: 500 })) + const qc = newClient() + const { result } = renderHook(() => { + usePreviewFlagServerSync() + return usePreviewFlagWriteError() + }, { wrapper: harness(qc) }) + await waitFor(() => expect(api.kirocrewConfig).toHaveBeenCalled()) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, true) }) + await waitFor(() => expect(result.current).toEqual({ flag: PREVIEW_CREW_MODE, denied: false })) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, true) }) + await waitFor(() => expect(result.current).toBeNull()) + expect(server.crew_mode).toBe(true) + }) + + it('does not report a carry the gateway refused', async () => { + server = { crew_mode: false } + localStorage.setItem(PREVIEW_WEBHOOKS, '1') + patchSpy.mockRejectedValue(Object.assign(new Error('already set'), { status: 409 })) + const qc = newClient() + const { result } = renderHook(() => { + usePreviewFlagServerSync() + return usePreviewFlagWriteError() + }, { wrapper: harness(qc) }) + await waitFor(() => expect(patchSpy).toHaveBeenCalledWith('dashboard.feature_previews.webhooks', true, { ifUnset: true })) + await act(async () => { await qc.invalidateQueries({ queryKey: ['kirocrewConfig'] }) }) + expect(result.current).toBeNull() + }) + + it('keeps the browser copy when the config cannot be read', async () => { + vi.mocked(api.kirocrewConfig).mockRejectedValue(new Error('offline')) + localStorage.setItem(PREVIEW_CREW_MODE, '1') + const qc = newClient() + const { result } = mountSync(qc) + await waitFor(() => expect(qc.getQueryState(['kirocrewConfig'])?.status).toBe('error')) + expect(result.current).toBe(true) + expect(patchSpy).not.toHaveBeenCalled() + }) + + it('carries a switch set before the server kept it up once, without replacing a stored one', async () => { + server = { webhooks: false } + localStorage.setItem(PREVIEW_CREW_MODE, '1') + localStorage.setItem(PREVIEW_WEBHOOKS, '1') + localStorage.setItem(PREVIEW_ARTIFACT_DEPLOY, '0') + const qc = newClient() + const { result } = mountSync(qc) + await waitFor(() => expect(server.crew_mode).toBe(true)) + expect(patchSpy).toHaveBeenCalledTimes(1) + expect(patchSpy).toHaveBeenCalledWith('dashboard.feature_previews.crew_mode', true, { ifUnset: true }) + // The stored webhooks value wins and an OFF copy is never carried. + await waitFor(() => expect(readPreviewFlag(PREVIEW_WEBHOOKS)).toBe(false)) + expect(server.artifact_deploy).toBeUndefined() + expect(result.current).toBe(true) + // Later reads do not carry it again. + await act(async () => { await qc.invalidateQueries({ queryKey: ['kirocrewConfig'] }) }) + expect(patchSpy).toHaveBeenCalledTimes(1) + }) + + it('does not retry a refused carry on every refetch', async () => { + patchSpy.mockRejectedValue(new Error('owner only')) + localStorage.setItem(PREVIEW_CREW_MODE, '1') + const qc = newClient() + const { result } = mountSync(qc) + await waitFor(() => expect(patchSpy).toHaveBeenCalledTimes(1)) + await act(async () => { await qc.invalidateQueries({ queryKey: ['kirocrewConfig'] }) }) + expect(patchSpy).toHaveBeenCalledTimes(1) + expect(result.current).toBe(true) + }) + + it('puts a refused toggle back in a browser that has never synced, where the server holds no value', async () => { + // Webhooks' carry is refused too, so this browser really stays unsynced. + localStorage.setItem(PREVIEW_WEBHOOKS, '1') + patchSpy.mockRejectedValue(Object.assign(new Error('owner only'), { status: 403 })) + const qc = newClient() + const { result } = mountSync(qc) + await waitFor(() => expect(patchSpy).toHaveBeenCalledWith('dashboard.feature_previews.webhooks', true, { ifUnset: true })) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, true) }) + await waitFor(() => expect(patchSpy).toHaveBeenCalledWith('dashboard.feature_previews.crew_mode', true, undefined)) + await waitFor(() => expect(result.current).toBe(false)) + expect(localStorage.getItem(PREVIEW_FLAGS_SYNCED_KEY)).toBeNull() + // Nor is the refused value carried up afterwards. + await act(async () => { await qc.invalidateQueries({ queryKey: ['kirocrewConfig'] }) }) + expect(result.current).toBe(false) + expect(patchSpy).not.toHaveBeenCalledWith('dashboard.feature_previews.crew_mode', true, { ifUnset: true }) + }) + + it('puts two refused clicks back to the value before the first, in an unsynced browser', async () => { + localStorage.setItem(PREVIEW_WEBHOOKS, '1') + patchSpy.mockRejectedValue(Object.assign(new Error('owner only'), { status: 403 })) + const qc = newClient() + const { result } = mountSync(qc) + await waitFor(() => expect(patchSpy).toHaveBeenCalledTimes(1)) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, true) }) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, false) }) + await waitFor(() => expect(patchSpy).toHaveBeenCalledTimes(3)) + await act(async () => { await qc.invalidateQueries({ queryKey: ['kirocrewConfig'] }) }) + expect(result.current).toBe(false) + }) + + it('puts two refused clicks back to the value before the first when the config cannot be read', async () => { + vi.mocked(api.kirocrewConfig).mockRejectedValue(new Error('offline')) + patchSpy.mockRejectedValue(Object.assign(new Error('boom'), { status: 500 })) + const qc = newClient() + const { result } = mountSync(qc) + await waitFor(() => expect(qc.getQueryState(['kirocrewConfig'])?.status).toBe('error')) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, true) }) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, false) }) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, true) }) + await waitFor(() => expect(patchSpy).toHaveBeenCalledTimes(3)) + await waitFor(() => expect(result.current).toBe(false)) + }) + + it('puts refused clicks queued behind a refused carry back to the browser value', async () => { + localStorage.setItem(PREVIEW_CREW_MODE, '1') + let refuseCarry!: () => void + patchSpy.mockImplementationOnce(() => new Promise((_, reject) => { + refuseCarry = () => reject(Object.assign(new Error('owner only'), { status: 403 })) + })) + let refuseFirstClick!: () => void + patchSpy.mockImplementationOnce(() => new Promise((_, reject) => { + refuseFirstClick = () => reject(Object.assign(new Error('owner only'), { status: 403 })) + })) + patchSpy.mockRejectedValue(Object.assign(new Error('owner only'), { status: 403 })) + const qc = newClient() + const { result } = renderHook(() => { + usePreviewFlagServerSync() + return [usePreviewFlagWriteError(), usePreviewFlag(PREVIEW_CREW_MODE)] as const + }, { wrapper: harness(qc) }) + await waitFor(() => expect(patchSpy).toHaveBeenCalledWith('dashboard.feature_previews.crew_mode', true, { ifUnset: true })) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, false) }) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, true) }) + await act(async () => { refuseCarry() }) + await waitFor(() => expect(patchSpy).toHaveBeenCalledTimes(2)) + // The carry's own outcome is not reported while the clicks behind it are queued. + expect(result.current[0]).toBeNull() + await act(async () => { refuseFirstClick() }) + await waitFor(() => expect(patchSpy).toHaveBeenCalledTimes(3)) + await waitFor(() => expect(result.current[0]).toEqual({ flag: PREVIEW_CREW_MODE, denied: true })) + expect(result.current[1]).toBe(true) + await act(async () => { await qc.invalidateQueries({ queryKey: ['kirocrewConfig'] }) }) + expect(result.current[1]).toBe(true) + }) + + it('does not mark the browser synced when a carry lands while a toggle of another switch is in flight', async () => { + localStorage.setItem(PREVIEW_WEBHOOKS, '1') + let releaseCarry!: () => void + const accept = patchSpy.getMockImplementation()! + patchSpy.mockImplementationOnce((...args: Parameters) => new Promise(resolve => { + releaseCarry = () => resolve(accept(...args)) + })) + let refuseToggle!: () => void + patchSpy.mockImplementationOnce(() => new Promise((_, reject) => { + refuseToggle = () => reject(Object.assign(new Error('owner only'), { status: 403 })) + })) + localStorage.setItem(PREVIEW_CREW_MODE, '0') + const qc = newClient() + const { result } = mountSync(qc) + await waitFor(() => expect(patchSpy).toHaveBeenCalledWith('dashboard.feature_previews.webhooks', true, { ifUnset: true })) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, true) }) + await waitFor(() => expect(patchSpy).toHaveBeenCalledTimes(2)) + await act(async () => { releaseCarry() }) + await waitFor(() => expect(server.webhooks).toBe(true)) + expect(localStorage.getItem(PREVIEW_FLAGS_SYNCED_KEY)).toBeNull() + await act(async () => { refuseToggle() }) + await waitFor(() => expect(result.current).toBe(false)) + await act(async () => { await qc.invalidateQueries({ queryKey: ['kirocrewConfig'] }) }) + expect(result.current).toBe(false) + }) + + it('keeps another switch\'s notice when a different switch saves', async () => { + server = { crew_mode: false, webhooks: false } + patchSpy.mockRejectedValueOnce(Object.assign(new Error('boom'), { status: 500 })) + const qc = newClient() + const { result } = renderHook(() => { + usePreviewFlagServerSync() + return usePreviewFlagWriteError() + }, { wrapper: harness(qc) }) + await waitFor(() => expect(api.kirocrewConfig).toHaveBeenCalled()) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, true) }) + await waitFor(() => expect(result.current).toEqual({ flag: PREVIEW_CREW_MODE, denied: false })) + act(() => { setPreviewFlag(PREVIEW_WEBHOOKS, true) }) + await waitFor(() => expect(server.webhooks).toBe(true)) + expect(result.current).toEqual({ flag: PREVIEW_CREW_MODE, denied: false }) + }) + + it('reports a refused click only once the last queued click of that switch has settled', async () => { + server = { crew_mode: false } + let refuseFirst!: () => void + let acceptSecond!: () => void + const accept = patchSpy.getMockImplementation()! + patchSpy.mockImplementationOnce(() => new Promise((_, reject) => { + refuseFirst = () => reject(Object.assign(new Error('boom'), { status: 500 })) + })) + patchSpy.mockImplementationOnce((...args: Parameters) => new Promise(resolve => { + acceptSecond = () => resolve(accept(...args)) + })) + const qc = newClient() + const { result } = renderHook(() => { + usePreviewFlagServerSync() + return [usePreviewFlagWriteError(), usePreviewFlag(PREVIEW_CREW_MODE)] as const + }, { wrapper: harness(qc) }) + await waitFor(() => expect(api.kirocrewConfig).toHaveBeenCalled()) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, true) }) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, false) }) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, true) }) + await waitFor(() => expect(patchSpy).toHaveBeenCalledTimes(1)) + await act(async () => { refuseFirst() }) + await waitFor(() => expect(patchSpy).toHaveBeenCalledTimes(2)) + expect(result.current[0]).toBeNull() + await act(async () => { acceptSecond() }) + await waitFor(() => expect(server.crew_mode).toBe(true)) + await waitFor(() => expect(result.current[1]).toBe(true)) + expect(result.current[0]).toBeNull() + }) + + it('reports a 403 from a session that no longer authenticates as a failed save, not owner-only', async () => { + server = { crew_mode: false } + patchSpy.mockRejectedValue(Object.assign(new Error('sign in'), { status: 403, authRequired: true })) + const qc = newClient() + const { result } = renderHook(() => { + usePreviewFlagServerSync() + return usePreviewFlagWriteError() + }, { wrapper: harness(qc) }) + await waitFor(() => expect(api.kirocrewConfig).toHaveBeenCalled()) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, true) }) + await waitFor(() => expect(result.current).toEqual({ flag: PREVIEW_CREW_MODE, denied: false })) + }) + + it('counts a carry the gateway answered 409 as synced', async () => { + patchSpy.mockRejectedValue(Object.assign(new Error('already set'), { status: 409 })) + localStorage.setItem(PREVIEW_CREW_MODE, '1') + mountSync(newClient()) + await waitFor(() => expect(patchSpy).toHaveBeenCalledTimes(1)) + await waitFor(() => expect(localStorage.getItem(PREVIEW_FLAGS_SYNCED_KEY)).toBe('1')) + }) + + it('keeps a switch set in this browser when a toggle of it is refused before the first read lands', async () => { + localStorage.setItem(PREVIEW_CREW_MODE, '1') + localStorage.setItem(PREVIEW_WEBHOOKS, '0') + let releaseRead!: () => void + vi.mocked(api.kirocrewConfig).mockImplementationOnce(() => new Promise(resolve => { + // Webhooks is held by the server and off in this browser, so the reconcile + // that reads this body has a visible effect the test can wait for. + releaseRead = () => resolve({ dashboard: { feature_previews: { webhooks: true } } } as Body) + })) + let refuse!: () => void + patchSpy.mockImplementationOnce(() => new Promise((_, reject) => { + refuse = () => reject(Object.assign(new Error('owner only'), { status: 403 })) + })) + const qc = newClient() + const { result } = mountSync(qc) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, false) }) + await waitFor(() => expect(patchSpy).toHaveBeenCalledTimes(1)) + await act(async () => { releaseRead() }) + // The reconcile of that read has run (it turned Webhooks on) before the + // refusal, so the read really landed while the toggle was in flight. + await waitFor(() => expect(readPreviewFlag(PREVIEW_WEBHOOKS)).toBe(true)) + await act(async () => { refuse() }) + await waitFor(() => expect(result.current).toBe(true)) + await act(async () => { await qc.invalidateQueries({ queryKey: ['kirocrewConfig'] }) }) + expect(result.current).toBe(true) + expect(localStorage.getItem(PREVIEW_FLAGS_SYNCED_KEY)).toBeNull() + }) + + it('reports a refused carry as on in this browser only, and keeps the switch on', async () => { + patchSpy.mockRejectedValue(Object.assign(new Error('boom'), { status: 500 })) + localStorage.setItem(PREVIEW_CREW_MODE, '1') + const qc = newClient() + const { result } = renderHook(() => { + usePreviewFlagServerSync() + return [usePreviewFlagWriteError(), usePreviewFlag(PREVIEW_CREW_MODE)] as const + }, { wrapper: harness(qc) }) + await waitFor(() => expect(result.current[0]).toEqual({ flag: PREVIEW_CREW_MODE, denied: false, carry: true })) + expect(result.current[1]).toBe(true) + expect(localStorage.getItem(PREVIEW_FLAGS_SYNCED_KEY)).toBeNull() + }) + + it('clears a refused carry notice once the server holds a value for that switch', async () => { + patchSpy.mockRejectedValue(Object.assign(new Error('owner only'), { status: 403 })) + localStorage.setItem(PREVIEW_CREW_MODE, '1') + const qc = newClient() + const { result } = renderHook(() => { + usePreviewFlagServerSync() + return [usePreviewFlagWriteError(), usePreviewFlag(PREVIEW_CREW_MODE)] as const + }, { wrapper: harness(qc) }) + await waitFor(() => expect(result.current[0]).toEqual({ flag: PREVIEW_CREW_MODE, denied: true, carry: true })) + // The owner saves the switch off on another surface; the refresh brings it here. + server = { crew_mode: false } + await act(async () => { await qc.invalidateQueries({ queryKey: ['kirocrewConfig'] }) }) + await waitFor(() => expect(result.current[1]).toBe(false)) + expect(result.current[0]).toBeNull() + }) + + it('keeps a refused toggle notice when the server value arrives', async () => { + server = { crew_mode: false } + const qc = newClient() + const { result } = renderHook(() => { + usePreviewFlagServerSync() + return [usePreviewFlagWriteError(), usePreviewFlag(PREVIEW_CREW_MODE)] as const + }, { wrapper: harness(qc) }) + await waitFor(() => expect(api.kirocrewConfig).toHaveBeenCalled()) + patchSpy.mockRejectedValue(Object.assign(new Error('owner only'), { status: 403 })) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, true) }) + await waitFor(() => expect(result.current[0]).toEqual({ flag: PREVIEW_CREW_MODE, denied: true })) + await act(async () => { await qc.invalidateQueries({ queryKey: ['kirocrewConfig'] }) }) + expect(result.current[0]).toEqual({ flag: PREVIEW_CREW_MODE, denied: true }) + expect(result.current[1]).toBe(false) + }) + + it('applies rapid toggles of one flag in click order', async () => { + const order: boolean[] = [] + const releases: Array<() => void> = [] + patchSpy.mockImplementation(async (path: string, value: unknown) => { + order.push(value as boolean) + await new Promise(r => { releases.push(r) }) + server[path.replace('dashboard.feature_previews.', '')] = value as boolean + return { ok: true } + }) + const { result } = mountSync(newClient()) + await waitFor(() => expect(api.kirocrewConfig).toHaveBeenCalled()) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, true) }) + act(() => { setPreviewFlag(PREVIEW_CREW_MODE, false) }) + // The second write waits for the first to settle. + await waitFor(() => expect(order).toEqual([true])) + await act(async () => { releases[0]() }) + await waitFor(() => expect(order).toEqual([true, false])) + await act(async () => { releases[1]() }) + await waitFor(() => expect(server.crew_mode).toBe(false)) + await waitFor(() => expect(result.current).toBe(false)) + }) + + it('reads a switch the server dropped as off once this browser has synced', async () => { + server = { crew_mode: true } + const qc = newClient() + const { result } = mountSync(qc) + await waitFor(() => expect(result.current).toBe(true)) + expect(localStorage.getItem(PREVIEW_FLAGS_SYNCED_KEY)).toBe('1') + server = {} + await act(async () => { await qc.invalidateQueries({ queryKey: ['kirocrewConfig'] }) }) + await waitFor(() => expect(result.current).toBe(false)) + expect(patchSpy).not.toHaveBeenCalled() + }) + + it('reads a switch the server dropped as off when another switch failed to carry up', async () => { + server = { crew_mode: true } + localStorage.setItem(PREVIEW_WEBHOOKS, '1') + patchSpy.mockRejectedValue(Object.assign(new Error('boom'), { status: 500 })) + const qc = newClient() + const { result } = mountSync(qc) + await waitFor(() => expect(result.current).toBe(true)) + await waitFor(() => expect(patchSpy).toHaveBeenCalledWith('dashboard.feature_previews.webhooks', true, { ifUnset: true })) + // The failed carry keeps the browser as a whole unsynced. + await waitFor(() => expect(readPreviewFlag(PREVIEW_WEBHOOKS)).toBe(true)) + expect(localStorage.getItem(PREVIEW_FLAGS_SYNCED_KEY)).toBeNull() + expect(JSON.parse(localStorage.getItem(PREVIEW_FLAGS_SERVER_BACKED_KEY) ?? '[]')).toContain(PREVIEW_CREW_MODE) + // The crew_mode key is deleted on the gateway. + server = {} + await act(async () => { await qc.invalidateQueries({ queryKey: ['kirocrewConfig'] }) }) + await waitFor(() => expect(result.current).toBe(false)) + expect(patchSpy).toHaveBeenCalledTimes(1) + expect(patchSpy).not.toHaveBeenCalledWith('dashboard.feature_previews.crew_mode', expect.anything(), expect.anything()) + expect(server.crew_mode).toBeUndefined() + // The switch whose carry failed is still on in this browser. + expect(readPreviewFlag(PREVIEW_WEBHOOKS)).toBe(true) + }) + + it('reads a dropped switch as off when the server-backed record cannot be stored', async () => { + const setItem = Storage.prototype.setItem + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(function (this: Storage, key: string, value: string) { + if (key === PREVIEW_FLAGS_SERVER_BACKED_KEY) throw new DOMException('full', 'QuotaExceededError') + setItem.call(this, key, value) + }) + server = { crew_mode: true } + localStorage.setItem(PREVIEW_WEBHOOKS, '1') + patchSpy.mockRejectedValue(Object.assign(new Error('boom'), { status: 500 })) + const qc = newClient() + const { result } = mountSync(qc) + await waitFor(() => expect(result.current).toBe(true)) + await waitFor(() => expect(patchSpy).toHaveBeenCalledWith('dashboard.feature_previews.webhooks', true, { ifUnset: true })) + expect(localStorage.getItem(PREVIEW_FLAGS_SERVER_BACKED_KEY)).toBeNull() + server = {} + await act(async () => { await qc.invalidateQueries({ queryKey: ['kirocrewConfig'] }) }) + await waitFor(() => expect(result.current).toBe(false)) + expect(patchSpy).toHaveBeenCalledTimes(1) + expect(server.crew_mode).toBeUndefined() + expect(readPreviewFlag(PREVIEW_WEBHOOKS)).toBe(true) + }) + + it('reads an unreadable server-backed record as none and still carries a browser switch up', async () => { + localStorage.setItem(PREVIEW_FLAGS_SERVER_BACKED_KEY, '{not json') + localStorage.setItem(PREVIEW_CREW_MODE, '1') + const { result } = mountSync(newClient()) + await waitFor(() => expect(server.crew_mode).toBe(true)) + expect(result.current).toBe(true) + await waitFor(() => expect(JSON.parse(localStorage.getItem(PREVIEW_FLAGS_SERVER_BACKED_KEY) ?? '[]')).toEqual([PREVIEW_CREW_MODE])) + }) + + it('carries the retired Remote crew sessions switch up as Chat on a crew', async () => { + localStorage.setItem(PREVIEW_INSTANCE_SESSIONS, '1') + mountSync(newClient()) + await waitFor(() => expect(server.remote_crew_chat).toBe(true)) + expect(patchSpy).toHaveBeenCalledTimes(1) + expect(patchSpy).toHaveBeenCalledWith('dashboard.feature_previews.remote_crew_chat', true, { ifUnset: true }) + await waitFor(() => expect(readPreviewFlag(PREVIEW_INSTANCE_SESSIONS)).toBe(false)) + expect(readPreviewFlag(PREVIEW_REMOTE_CREW_CHAT)).toBe(true) + }) + + it('never lets the retired key turn Chat on a crew back on after it was turned off', async () => { + server = { remote_crew_chat: false } + localStorage.setItem(PREVIEW_INSTANCE_SESSIONS, '1') + mountSync(newClient()) + await waitFor(() => expect(readPreviewFlag(PREVIEW_INSTANCE_SESSIONS)).toBe(false)) + expect(readPreviewFlag(PREVIEW_REMOTE_CREW_CHAT)).toBe(false) + expect(patchSpy).not.toHaveBeenCalled() + }) + + it('sends no write for the retired key when Chat on a crew is turned off', async () => { + server = { remote_crew_chat: true } + mountSync(newClient()) + await waitFor(() => expect(readPreviewFlag(PREVIEW_REMOTE_CREW_CHAT)).toBe(true)) + localStorage.setItem(PREVIEW_INSTANCE_SESSIONS, '1') + act(() => { setRemoteCrewChat(false) }) + await waitFor(() => expect(server.remote_crew_chat).toBe(false)) + expect(patchSpy).toHaveBeenCalledTimes(1) + expect(readPreviewFlag(PREVIEW_INSTANCE_SESSIONS)).toBe(false) + }) + + it('writes nothing to the server once the shell unmounts', async () => { + const { unmount } = mountSync(newClient()) + await waitFor(() => expect(api.kirocrewConfig).toHaveBeenCalled()) + unmount() + expect(setPreviewFlag(PREVIEW_CREW_MODE, true)).toBe(true) + expect(patchSpy).not.toHaveBeenCalled() + }) +}) diff --git a/website/src/test/previewSurfaces.test.tsx b/website/src/test/previewSurfaces.test.tsx index 284509341539..af30f317aeb3 100644 --- a/website/src/test/previewSurfaces.test.tsx +++ b/website/src/test/previewSurfaces.test.tsx @@ -57,6 +57,7 @@ import { usePreviewFlag, usePreviewFlagRevision } from '../hooks/usePreviewFlag' import { createPagesProvider } from '../components/commandPalette/providers/pagesProvider' import { api } from '../api/client' import { FeaturePreviewsSection, FEATURE_PREVIEWS_HIGHLIGHT_ANCHOR } from '../pages/settings/FeaturePreviewsSection' +import { __resetPreviewFlagServerSyncForTests, usePreviewFlagServerSync } from '../hooks/usePreviewFlagServerSync' import DeveloperPage from '../pages/DeveloperPage' const TEST_ICON: ReactElement = @@ -383,6 +384,27 @@ describe('Settings > Developer > Feature Previews', () => { expect(toggleState()).toBe('true') }) + it('says why a switch went back when the gateway refuses the write', async () => { + __resetPreviewFlagServerSyncForTests() + vi.spyOn(api, 'patchConfig').mockRejectedValue(Object.assign(new Error('owner only'), { status: 403 })) + function WithSync() { + usePreviewFlagServerSync() + return + } + render( + + + , + ) + expect(screen.queryByTestId('feature-previews-save-error')).toBeNull() + await act(async () => { + screen.getByRole('switch', { name: /webhooks/i }).click() + }) + await waitFor(() => expect(screen.getByTestId('feature-previews-save-error').textContent) + .toMatch(/only the owner of this Kiro Crew can change feature previews, so “Webhooks” was switched back/i)) + act(() => { __resetPreviewFlagServerSyncForTests() }) + }) + it('offers no ingress button besides the webhooks link', async () => { // `webhooks` is `hiddenFromNav`, so its card is that page's ONLY door and // carries a link once on. No other card here does. diff --git a/website/src/utils/previewFlags.ts b/website/src/utils/previewFlags.ts index c20641ddfa91..5c662f5beffd 100644 --- a/website/src/utils/previewFlags.ts +++ b/website/src/utils/previewFlags.ts @@ -1,5 +1,5 @@ /** - * Preview flags — local, per-device opt-ins for surfaces that ship in the + * Preview flags — opt-ins for surfaces that ship in the * bundle but are NOT ready to be released. * * The problem this solves: a surface can be code-complete enough to merge and @@ -9,11 +9,16 @@ * routable, and simply does not advertise the surface anywhere in the UI until * the operator turns it on from Settings > Developer > Feature Previews. * - * Deliberately localStorage, not backend config: this is a per-device "show me - * the unfinished thing" switch with no server behavior attached (the surface's - * own API is unaffected either way), which is exactly the shape of the existing - * other per-device switches in localStorage. Putting it in `config.json` would imply - * a fleet-wide setting and a backend contract that does not exist. + * Stored in the gateway config (`dashboard.feature_previews.`), with + * localStorage as a synchronous cache. A switch kept only in the browser is + * lost to every fresh origin: another browser or device, the desktop app beside + * a browser tab, a changed dashboard port, or cleared site data. Every reader + * below still reads the cache, so the nav rail and the registry stay + * synchronous; `usePreviewFlagServerSync` fills the cache from the server copy, + * carries a cache-only ON up to the server once, and sends each toggle to the + * server through the writer it registers with {@link setPreviewFlagPersister}. + * The flag still has no server behavior of its own: the surface's API is the + * same whichever way it is set. * * Retiring a flag is the goal, not an afterthought: when the surface is * polished, delete its `previewFlag` from the registry entry and its card from @@ -132,7 +137,7 @@ export const PREVIEW_LAYOUT_HARNESS = `${PREVIEW_FLAG_PREFIX}layout-harness` * them. The pin is not a new door that a reader can decline to walk through, so * the usual ingress-only argument for shipping a preview unflagged does not * apply here: there is nothing to decline. First Principles review asked for - * either a flag or an accepted RFC, and a per-device flag is the cheaper of the + * either a flag or an accepted RFC, and a preview flag is the cheaper of the * two to retire. * * Default OFF, and OFF is byte-for-byte the list on `main`: the folder's rows @@ -177,6 +182,55 @@ export const PREVIEW_CREWMATE_HARNESS = `${PREVIEW_FLAG_PREFIX}crewmate-harness` */ export const PREVIEW_CREW_MODE = `${PREVIEW_FLAG_PREFIX}crew-mode` +/** + * Every live preview-flag key, the ones the gateway keeps. Each one's name (see + * {@link previewFlagName}) is a writable `dashboard.feature_previews.` path + * in the gateway config; `test_feature_previews_config.py` pins this list equal + * to the gateway's `FEATURE_PREVIEW_FLAGS`, and `previewFlagServerSync.test.tsx` + * pins it to every flag constant declared here. The retired + * {@link PREVIEW_INSTANCE_SESSIONS} is left out: the gateway never keeps it, and + * its ON is carried up as {@link PREVIEW_REMOTE_CREW_CHAT}. + */ +export const PREVIEW_FLAGS: readonly string[] = [ + PREVIEW_WEBHOOKS, + PREVIEW_ARTIFACT_DEPLOY, + PREVIEW_REMOTE_CREW_CHAT, + PREVIEW_LAYOUT_HARNESS, + PREVIEW_FOLDER_CONDUCTOR, + PREVIEW_SESSION_ENVIRONMENTS, + PREVIEW_CREWMATE_HARNESS, + PREVIEW_CREW_MODE, +] + +/** + * *flag*'s name in the gateway config: the key without + * {@link PREVIEW_FLAG_PREFIX}, hyphens as underscores (config paths are + * snake_case). `mc-preview-artifact-deploy` -> `artifact_deploy`. + */ +export function previewFlagName(flag: string): string { + return flag.slice(PREVIEW_FLAG_PREFIX.length).replace(/-/g, '_') +} + +/** The gateway config path holding *flag*: `dashboard.feature_previews.`. */ +export function previewFlagConfigPath(flag: string): string { + return ['dashboard', 'feature_previews', previewFlagName(flag)].join('.') +} + +/** Sends a toggled flag to the gateway; see {@link setPreviewFlagPersister}. */ +export type PreviewFlagPersister = (flag: string, on: boolean) => void + +let persister: PreviewFlagPersister | null = null + +/** + * Install (or, with `null`, remove) the writer {@link setPreviewFlag} hands each + * toggle to after the cache write lands. Registered by the app shell's + * `usePreviewFlagServerSync`; with none installed a toggle changes only the + * cache, which is what a test that never mounts the shell gets. + */ +export function setPreviewFlagPersister(next: PreviewFlagPersister | null): void { + persister = next +} + /** * Read a preview flag. Absent, unparseable, or storage-denied all mean OFF — * the whole point of the gate is that a surface stays hidden unless someone @@ -197,9 +251,10 @@ export function setRemoteCrewChat(on: boolean): boolean { } /** - * Write a preview flag and announce it. + * Write a preview flag to the browser cache, announce it, and hand it to the + * installed persister so the gateway keeps it too. * - * Returns whether the write actually landed. The announcement is gated on that + * Returns whether the cache write actually landed. The announcement is gated on that * result, and the gating is load-bearing rather than tidiness: every READER of a * flag (`readPreviewFlag`, and so `surfacePreviewEnabled` and the nav rail) goes * to storage, while `usePreviewFlag` tracks the event. So dispatching after a @@ -210,9 +265,21 @@ export function setRemoteCrewChat(on: boolean): boolean { * exhausted quota survives `safeSetItem`'s reclaim attempts. * * On failure the toggle simply stays where it was, which is the truthful - * outcome: nothing was saved. + * outcome: nothing was saved, and nothing is sent to the gateway. */ export function setPreviewFlag(flag: string, on: boolean): boolean { + if (!cachePreviewFlag(flag, on)) return false + persister?.(flag, on) + return true +} + +/** + * Write a preview flag to the browser cache only, and announce it, without + * sending it to the gateway. For applying a value the gateway already holds; + * a user's toggle goes through {@link setPreviewFlag}. Returns whether the + * write landed, for the reason given there. + */ +export function cachePreviewFlag(flag: string, on: boolean): boolean { if (!safeSetItem(flag, on ? '1' : '0')) return false const detail: PreviewFlagChange = { key: flag, on } window.dispatchEvent(new CustomEvent(PREVIEW_FLAG_EVENT, { detail }))