Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(auth): let editors see and save messaging ASR (#1415)

Call Whiteeec0e447e23e
diff --git a/config/v2_config.py b/config/v2_config.py
index 2a0b14c29..ddc048cc3 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -2,6 +2,7 @@ import copy
import ipaddress
import json
import logging
+import math
import os
import re
import shutil
@@ -847,6 +848,162 @@ def _migrate_config_payload_on_load(payload: dict) -> tuple[dict, bool, tuple[st
return migrated, changed, warnings
+# The spellings a hand-edited config may use for a boolean, both sides in one
+# place. ``""`` reads as off because ``test_show_agent_activity_defaults_off_and
+# _round_trips`` states it; anything absent from here names no side at all.
+_BOOL_SPELLINGS = {
+ "1": True,
+ "true": True,
+ "yes": True,
+ "on": True,
+ "0": False,
+ "false": False,
+ "no": False,
+ "off": False,
+ "": False,
+}
+
+
+def _named_bool(path: str, value: object) -> bool:
+ """The side a switch's value names, or a refusal.
+
+ ``true``/``1``/``"yes"``/``"off"`` all name a side the caller meant, and
+ ``_BOOL_SPELLINGS`` is the whole vocabulary in one place rather than a
+ truthy list plus an implicit else. A value outside it names no side at all
+ — ``"garbage"``, ``5``, ``[]`` — and is refused rather than read as false,
+ which on a write path would answer 200 having stored the side the caller
+ never asked for.
+ """
+
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, str):
+ spelled = _BOOL_SPELLINGS.get(value.strip().lower())
+ if spelled is not None:
+ return spelled
+ elif isinstance(value, int) and value in (0, 1):
+ return bool(value)
+ raise ValueError(f"Config '{path}' must be a boolean")
+
+
+def _named_value(path: str, declared: object, value: object) -> object:
+ """The value a field's declared kind names, or a refusal.
+
+ One vocabulary for every field this reaches, because the alternative is
+ what the review found twice: each field open-coding its own ``int(...)`` /
+ ``str(...)`` / truthy test, and each one deciding on its own whether a
+ value it cannot read is an error or something to repair in place. Repair
+ belongs to ``V2Config.load``, behind a backup and a warning; this states
+ only what a value must name to be readable at all.
+
+ A switch reads the spellings above. A number reads any spelling that names
+ one, so a hand-edited ``"14"`` still means 14, and otherwise reads only a
+ number it can store unchanged: a ``bool`` is refused because Python makes it
+ an ``int`` and ``int(True)`` is a legal ``1``, an infinity and a NaN are
+ refused because neither names a setting any field here can hold, and a
+ fractional value posted to an integer field is refused because ``int(14.9)``
+ is ``14`` — every one of them otherwise answers 200 having stored a setting
+ the caller never sent. A string reads only a string: no
+ number names a URL or a credential, and silently emptying one logs the
+ operator out or unpairs the instance. Kinds outside this vocabulary —
+ containers, nested sections — are left to the code that already
+ understands them.
+ """
+
+ if isinstance(declared, str):
+ text = declared
+ elif isinstance(declared, type):
+ text = declared.__name__
+ else:
+ # ``Optional[int]`` and friends are not classes, and their ``__name__``
+ # is the bare ``"Optional"``, which would drop the kind being wrapped.
+ text = str(declared)
+ optional = re.fullmatch(r"(?:typing\.)?Optional\[(?:typing\.)?(.+)\]", text)
+ if optional:
+ if value is None:
+ return None
+ text = optional.group(1)
+ if text == "bool":
+ return _named_bool(path, value)
+ if text in ("int", "float"):
+ if isinstance(value, bool):
+ raise ValueError(f"Config '{path}' must be a number")
+ try:
+ number = int(value) if text == "int" else float(value)
+ except (TypeError, ValueError, OverflowError) as exc:
+ # ``OverflowError`` is how Python spells "this float names no
+ # integer": ``int(float("inf"))`` raises it rather than
+ # ``ValueError``, and JSON turns both a hand-edited ``1e309`` and
+ # the ``Infinity`` an older release serialized back into that
+ # float. Left uncaught it escapes recovery on the disk path and
+ # answers 500 on the write path, so it is spelled here as what it
+ # is — a value naming no number — instead of being caught wider.
+ raise ValueError(f"Config '{path}' must be a number") from exc
+ if isinstance(number, float) and not math.isfinite(number):
+ # An infinity or a NaN survives ``float(...)`` and then behaves as
+ # a setting: an infinite ASR timeout never expires, and a NaN loses
+ # every range comparison so it clamps to whichever bound is written
+ # first. Refused for the same reason as the rest — it names no
+ # setting — rather than clamped, which would answer 200 having
+ # stored a bound the caller never asked for. Only floats are
+ # checked: an ``int`` is always finite, and asking ``math`` about a
+ # large one would raise the overflow just caught above.
+ raise ValueError(f"Config '{path}' must be a number")
+ if isinstance(value, (int, float)) and number != value:
+ # The conversion succeeded and changed the number. ``int(14.9)`` is
+ # ``14``, so a posted font size of 14.9 answered 200 having stored a
+ # size nobody asked for, and ``float`` of an integer past 2**53 lands
+ # on its neighbour the same way. Both are the defect this whole
+ # vocabulary exists to refuse — a value coerced into a legal setting
+ # instead of refused — so the rule is stated as what it is: a number
+ # this reads is the number it was given. Only a numeric input is
+ # held to it. A string is a spelling, not a number, and reading
+ # ``"14"`` as 14 is the normalization this deliberately keeps; a
+ # fractional spelling has no route here anyway, because ``int`` of
+ # ``"14.9"`` already raises above.
+ raise ValueError(f"Config '{path}' must be a number")
+ return number
+ if text == "str":
+ if not isinstance(value, str):
+ raise ValueError(f"Config '{path}' must be a string")
+ return value
+
+
+def _refuse_values_naming_nothing(section: str, instance: object) -> None:
+ """Hold every field of ``instance`` to the kind it declares.
+
+ Stated over the declared fields rather than over the ones some reviewer
+ reached, so a field added to the dataclass is held to its own declaration
+ without editing this call site — which is the difference between closing
+ this class and paying for it one review round per field.
+
+ Raised one field at a time, in the ``Config '<section>.<field>'`` shape
+ every other message on this path uses, because that is what lets a disk
+ load recover the unreadable field alone instead of discarding the section.
+ A second unreadable field simply raises on the next pass of the recovery
+ loop.
+ """
+
+ for info in fields(instance):
+ setattr(
+ instance,
+ info.name,
+ _named_value(f"{section}.{info.name}", info.type, getattr(instance, info.name)),
+ )
+
+
+# Sections whose fields are independent of one another, so a single unreadable
+# field is recovered on its own instead of discarding its siblings — and whose
+# switches recover to off rather than to the fresh-install default. See
+# ``_reset_recoverable_config_section``.
+_FIELD_SCOPED_RECOVERY_SECTIONS = ("ui", "audio_asr")
+
+# The switch that decides whether an optional feature runs at all. Named once
+# because recovery has to tell it apart from every other switch in a section:
+# the rest describe how a feature behaves, this one decides whether it happens.
+_FEATURE_SWITCH_FIELD = "enabled"
+
+
def _recovery_section_for_error(error: BaseException) -> Optional[str]:
message = str(error)
match = re.search(r"Config '([^']+)'", message)
@@ -900,7 +1057,79 @@ def _recovery_section_for_error(error: BaseException) -> Optional[str]:
return None
-def _reset_recoverable_config_section(payload: dict, section: str) -> bool:
+def _recovery_field_for_error(section: Optional[str], error: BaseException) -> Optional[str]:
+ """The single field an error names, for the field-scoped sections only.
+
+ Restricted to those sections so every other section keeps recovering — and
+ de-duplicating — as a whole, which is what stops the recovery loop.
+ """
+
+ if section not in _FIELD_SCOPED_RECOVERY_SECTIONS:
+ return None
+ match = re.search(r"Config '([^']+)'", str(error))
+ if not match:
+ return None
+ path = match.group(1).split(".", 1)
+ if len(path) != 2 or path[0] != section:
+ return None
+ return path[1]
+
+
+def _recover_switch_section_field(
+ payload: dict, section: str, field_name: Optional[str]
+) -> bool:
+ """Keep what the file still says, and leave a recovered feature switched off.
+
+ Two questions, answered separately, because answering both the same way is
+ what produced this function's two review rounds.
+
+ *How much of what the operator wrote is discarded?* As little as possible.
+ Replacing the whole section answers an unreadable font size by hiding the
+ tool-call rows and an unreadable model name by forgetting the endpoint, so
+ the unreadable field is recovered alone: a field declared ``bool`` resolves
+ to ``False`` because a value naming no side is no evidence the feature was
+ on, and any other field is dropped so its declared default applies.
+
+ *Does an optional feature still run afterwards?* No. ``AGENTS.md`` states it
+ — "a broken optional-feature section disables that feature and warns" — and
+ the two directions are not the symmetric pair the previous round argued they
+ were. Leaving ``audio_asr.enabled`` on runs transcription under a
+ configuration nobody wrote, shipping user audio off-machine against
+ substituted settings, and that cannot be taken back. Leaving it off costs a
+ warning the operator reads before turning it back on. Only one of those is
+ reversible, so any repair here clears the section's ``enabled`` switch.
+
+ Both answers are stated over the section's declared fields rather than over
+ the sections that exist today: a section with no ``enabled`` is presentation
+ and keeps its siblings untouched, and one that declares it inherits the
+ disable without editing this function.
+ """
+
+ declared = V2Config.__dataclass_fields__[section].default_factory
+ declared_fields = {info.name for info in fields(declared)}
+ switches = {info.name for info in fields(declared) if info.type in (bool, "bool")}
+ stored = payload.get(section)
+ if not isinstance(stored, dict):
+ # Nothing readable to keep, so every switch resolves off.
+ stored = {name: False for name in switches}
+ payload[section] = stored
+ elif field_name is None:
+ stored.update({name: False for name in switches})
+ elif field_name in switches:
+ stored[field_name] = False
+ elif field_name in declared_fields:
+ stored.pop(field_name, None)
+ else:
+ return False
+ if _FEATURE_SWITCH_FIELD in switches:
+ stored[_FEATURE_SWITCH_FIELD] = False
+ return True
+ return False
+
+
+def _reset_recoverable_config_section(
+ payload: dict, section: str, field_name: Optional[str] = None
+) -> bool:
"""Replace one independently recoverable section with its safe default.
This is deliberately outside ``V2Config.from_payload``. Direct callers and
@@ -908,6 +1137,8 @@ def _reset_recoverable_config_section(payload: dict, section: str) -> bool:
loss-avoiding recovery path, and the original file is backed up first.
"""
+ if section in _FIELD_SCOPED_RECOVERY_SECTIONS:
+ return _recover_switch_section_field(payload, section, field_name)
if section == "memory.rerank":
memory = payload.get("memory")
processing = memory.get("processing") if isinstance(memory, dict) else None
@@ -924,9 +1155,7 @@ def _reset_recoverable_config_section(payload: dict, section: str) -> bool:
if section in {
"model_hub",
"memory",
- "ui",
"remote_access",
- "audio_asr",
"update",
}:
payload[section] = {}
@@ -1395,6 +1624,22 @@ class AudioAsrConfig:
model: str = "qwen3-asr-flash"
max_file_bytes: Optional[int] = None
+ def __post_init__(self) -> None:
+ """Refuse a value that is not the kind this class declares.
+
+ ``from_payload`` copies this section verbatim, and an Editor may now
+ persist it, so a stale client or a hand-edited config can put ``[]``
+ where a switch belongs. Nothing further down coerces it: the Settings
+ pages read ``value !== false`` as on while ``AudioAsrService`` reads the
+ same value for truth, so ASR renders as enabled while transcription is
+ off. A ``true`` where ``timeout_seconds`` belongs is the same defect one
+ kind over — ``float(True)`` is a legal one-second timeout.
+
+ Enforced here rather than in ``from_payload`` so every construction path
+ holds the invariant the field types already claim.
+ """
+ _refuse_values_naming_nothing("audio_asr", self)
+
_MEMORY_MAX_URL_BYTES = 2048
_MEMORY_MAX_MODEL_BYTES = 512
@@ -2481,6 +2726,23 @@ class UiConfig:
# otherwise the machine's system hostname).
instance_name: str = ""
+ def __post_init__(self) -> None:
+ """Refuse a value that is not the kind this class declares.
+
+ ``from_payload`` copies this section verbatim and an Editor may now
+ persist part of it, so every field here is reachable from a stale
+ client or a hand-edited file. Held to the declared kinds rather than to
+ the two switches that had call-site checks, which is what closes
+ ``open_browser`` and ``setup_port`` — a declared switch and a declared
+ port that nothing on this path validated at all.
+
+ The switches keep reading the spellings a hand-edited config may use
+ (``"yes"``, ``"0"``, ``1``), which ``test_show_agent_activity_defaults_
+ off_and_round_trips`` states; that is why the normalisation happens here
+ rather than in a check that runs before it.
+ """
+ _refuse_values_naming_nothing("ui", self)
+
@dataclass
class VibeCloudRemoteAccessConfig:
@@ -2506,6 +2768,62 @@ class VibeCloudRemoteAccessConfig:
edge_bind_address: str = ""
dev_login_hint: str = ""
+ def __post_init__(self) -> None:
+ """Refuse a value that is not the kind this class declares.
+
+ ``from_payload`` copies this section's free-form fields verbatim, so a
+ hand-edited, migrated, or stale-client payload can hold a number where
+ a URL or credential belongs. Stated over the declared fields rather
+ than over the three the pairing predicate happens to read: any of them
+ can reach code that does string work, and ``is_runtime_paired`` is now
+ consulted on every ``/api/config`` response, which would turn one
+ malformed field into a 500 on every configuration read.
+
+ Refused rather than emptied. Emptying is a repair, and a repair here
+ writes a credential the operator never stored: clearing
+ ``session_secret`` logs every remote session out, and clearing
+ ``instance_secret`` unpairs the instance — answered ``200``, on a route
+ an Editor can now reach. Refusing sends a disk load through
+ ``V2Config.load``'s recovery instead, which backs the file up, restores
+ this section, and warns; the "degrade to not paired" outcome is
+ unchanged and now leaves evidence. Enforced here rather than in
+ ``from_payload`` so every construction path holds the invariant.
+
+ ``instance_kind`` is the one field exempt from that, because for it
+ "unreadable" and "unknown" are the same answer and ``""`` already means
+ unknown — the value a pairing this build does not recognise is meant to
+ carry. It is server-set at pairing and absent from every write surface,
+ so nothing an operator types reaches it.
+ """
+ if self.instance_kind not in ("personal", "organization"):
+ self.instance_kind = ""
+ _refuse_values_naming_nothing("remote_access.vibe_cloud", self)
+
+ def runtime_credentials(self) -> tuple[str, str, str] | None:
+ """Return ``(backend_url, instance_id, instance_secret)``, or ``None``.
+
+ The single definition of "this pairing can actually reach Avibe
+ Cloud". A recovered, migrated, or partially configured instance can
+ carry ``enabled`` and an ``instance_id`` while the secret every cloud
+ call needs is gone, so identifiers alone are not a readiness signal.
+ Runtime services call this to build their client; config projections
+ call ``is_runtime_paired`` to decide whether to offer the matching
+ control. One predicate, so a surface cannot promise what the runtime
+ will refuse.
+ """
+ if not self.enabled:
+ return None
+ backend_url = (self.backend_url or "").strip().rstrip("/")
+ instance_id = (self.instance_id or "").strip()
+ instance_secret = (self.instance_secret or "").strip()
+ if not backend_url or not instance_id or not instance_secret:
+ return None
+ return backend_url, instance_id, instance_secret
+
+ def is_runtime_paired(self) -> bool:
+ """Whether cloud-backed features can run against this pairing."""
+ return self.runtime_credentials() is not None
+
@dataclass
class RemoteAccessConfig:
@@ -2694,20 +3012,26 @@ class V2Config:
break
except (TypeError, ValueError) as exc:
section = _recovery_section_for_error(exc)
- if section is None or section in recovered_sections:
+ field_name = _recovery_field_for_error(section, exc)
+ # Keyed by whatever this pass will actually repair, so the
+ # dedupe that stops the loop cannot mistake a second unreadable
+ # field of a field-scoped section for no progress and discard
+ # the whole file.
+ recovered = section if field_name is None else f"{section}.{field_name}"
+ if section is None or recovered in recovered_sections:
warning = f"Config could not be loaded; using recovery defaults: {exc}"
logger.error("%s", warning)
config = cls.default()
recovery_warnings.append(warning)
break
- if not _reset_recoverable_config_section(candidate, section):
+ if not _reset_recoverable_config_section(candidate, section, field_name):
warning = f"Config section '{section}' could not be recovered; using recovery defaults: {exc}"
logger.error("%s", warning)
config = cls.default()
recovery_warnings.append(warning)
break
- recovered_sections.add(section)
- recovery_warnings.append(f"Recovered invalid config section '{section}': {exc}")
+ recovered_sections.add(recovered)
+ recovery_warnings.append(f"Recovered invalid config section '{recovered}': {exc}")
all_warnings = tuple(dict.fromkeys((*migration_warnings, *recovery_warnings)))
if migrated and not migration_warnings and not recovery_warnings:
@@ -2897,28 +3221,13 @@ class V2Config:
if not isinstance(ui_payload, dict):
raise ValueError("Config 'ui' must be an object")
ui = UiConfig(**_filter_dataclass_fields(UiConfig, ui_payload))
- try:
- ui.chat_message_font_size = max(
- MIN_CHAT_MESSAGE_FONT_SIZE_PX,
- min(MAX_CHAT_MESSAGE_FONT_SIZE_PX, int(ui.chat_message_font_size)),
- )
- except (TypeError, ValueError):
- ui.chat_message_font_size = DEFAULT_CHAT_MESSAGE_FONT_SIZE_PX
- # Accept real booleans; parse known string forms explicitly (a config file
- # or API client may supply "false"/"0", and ``bool("false")`` is True).
- raw_show_activity = ui.show_agent_activity
- if isinstance(raw_show_activity, str):
- ui.show_agent_activity = raw_show_activity.strip().lower() in ("1", "true", "yes", "on")
- else:
- ui.show_agent_activity = bool(raw_show_activity)
- # ``show_tool_calls`` defaults true; a string "false"/"0" must coerce to False
- # (``bool("false")`` is True) — same parse as above, applied when a string form
- # is supplied; a missing key keeps the ``UiConfig`` default (True).
- raw_show_tools = ui.show_tool_calls
- if isinstance(raw_show_tools, str):
- ui.show_tool_calls = raw_show_tools.strip().lower() in ("1", "true", "yes", "on")
- else:
- ui.show_tool_calls = bool(raw_show_tools)
+ # ``UiConfig.__post_init__`` has already held every field to its declared
+ # kind, so this is only the range policy: clamping an out-of-range size
+ # still honours what the caller asked for.
+ ui.chat_message_font_size = max(
+ MIN_CHAT_MESSAGE_FONT_SIZE_PX,
+ min(MAX_CHAT_MESSAGE_FONT_SIZE_PX, ui.chat_message_font_size),
+ )
remote_access_payload = payload.get("remote_access") or {}
if not isinstance(remote_access_payload, dict):
@@ -2935,10 +3244,6 @@ class V2Config:
**_filter_dataclass_fields(VibeCloudRemoteAccessConfig, vibe_cloud_payload)
),
)
- if not isinstance(remote_access.vibe_cloud.instance_kind, str) or (
- remote_access.vibe_cloud.instance_kind not in {"personal", "organization"}
- ):
- remote_access.vibe_cloud.instance_kind = ""
remote_access.vibe_cloud.transport_protocol = str(
remote_access.vibe_cloud.transport_protocol or "auto"
).strip().lower()
@@ -2946,16 +3251,10 @@ class V2Config:
raise ValueError(
"Config 'remote_access.vibe_cloud.transport_protocol' must be 'auto', 'quic', or 'http2'"
)
- raw_auto_recovery = remote_access.vibe_cloud.auto_recovery
- if isinstance(raw_auto_recovery, str):
- remote_access.vibe_cloud.auto_recovery = raw_auto_recovery.strip().lower() in (
- "1",
- "true",
- "yes",
- "on",
- )
- else:
- remote_access.vibe_cloud.auto_recovery = bool(raw_auto_recovery)
+ # ``auto_recovery`` reads the same spellings every other switch does;
+ # ``VibeCloudRemoteAccessConfig.__post_init__`` has already resolved it,
+ # where the truthy/else it used to have would have read ``"garbage"`` as
+ # off and a stale client's ``[1]`` as on.
remote_access.vibe_cloud.optimization_profile = str(
remote_access.vibe_cloud.optimization_profile or "balanced"
).strip().lower()
@@ -2995,19 +3294,16 @@ class V2Config:
audio_asr = AudioAsrConfig(**_filter_dataclass_fields(AudioAsrConfig, audio_asr_payload))
if audio_asr_enabled_present and audio_asr.enabled is False and not audio_asr.enabled_configured:
audio_asr.enabled_configured = True
- try:
- audio_asr.timeout_seconds = max(0.1, float(audio_asr.timeout_seconds))
- except (TypeError, ValueError):
- audio_asr.timeout_seconds = 60.0
+ # ``AudioAsrConfig.__post_init__`` has already held every field to its
+ # declared kind, so what is left here is range and format policy: a
+ # value that names a legal setting is clamped to the nearest legal one.
+ audio_asr.timeout_seconds = max(0.1, audio_asr.timeout_seconds)
if audio_asr.max_file_bytes is not None:
- try:
- audio_asr.max_file_bytes = max(1, int(audio_asr.max_file_bytes))
- except (TypeError, ValueError):
- audio_asr.max_file_bytes = None
- if not isinstance(audio_asr.endpoint_path, str) or not audio_asr.endpoint_path.startswith("/"):
- audio_asr.endpoint_path = "/v1/audio/transcriptions"
- if not isinstance(audio_asr.model, str) or not audio_asr.model.strip():
- audio_asr.model = "qwen3-asr-flash"
+ audio_asr.max_file_bytes = max(1, audio_asr.max_file_bytes)
+ if not audio_asr.endpoint_path.startswith("/"):
+ raise ValueError("Config 'audio_asr.endpoint_path' must be a path starting with '/'")
+ if not audio_asr.model.strip():
+ raise ValueError("Config 'audio_asr.model' must be a non-empty string")
update_payload = payload.get("update") or {}
if not isinstance(update_payload, dict):
@@ -3021,31 +3317,32 @@ class V2Config:
if not isinstance(ack_mode, str) or ack_mode not in {"reaction", "message", "typing"}:
raise ValueError("Config 'ack_mode' must be 'reaction', 'message', or 'typing'")
- show_duration = payload.get("show_duration", False)
- if not isinstance(show_duration, bool):
- show_duration = False
-
- include_user_info = payload.get("include_user_info", True)
- if not isinstance(include_user_info, bool):
- include_user_info = True
-
- include_time_info = payload.get("include_time_info", True)
- if not isinstance(include_time_info, bool):
- include_time_info = True
-
- reply_enhancements = payload.get("reply_enhancements", True)
- if not isinstance(reply_enhancements, bool):
- reply_enhancements = True
+ # Every preference below answers a wrong-typed value the way
+ # ``ack_mode`` above already does — by raising. This module's split is
+ # that ``from_payload`` validates and only disk loading recovers (see
+ # ``_reset_recoverable_config_section``), so a preference that quietly
+ # substituted its default broke the split in both directions: over HTTP
+ # the route answered 200 having stored a value the caller never sent
+ # (turning an enabled preference off on a request that asked to turn it
+ # on), and on disk the recovery entries written for these very fields
+ # were unreachable, so a hand-edit degraded with no warning.
+ def _declared_bool(name: str, default: bool) -> bool:
+ value = payload.get(name, default)
+ if not isinstance(value, bool):
+ raise ValueError(f"Config '{name}' must be a boolean")
+ return value
- show_pages_prompt = payload.get("show_pages_prompt", True)
- if not isinstance(show_pages_prompt, bool):
- show_pages_prompt = True
+ show_duration = _declared_bool("show_duration", False)
+ include_user_info = _declared_bool("include_user_info", True)
+ include_time_info = _declared_bool("include_time_info", True)
+ reply_enhancements = _declared_bool("reply_enhancements", True)
+ show_pages_prompt = _declared_bool("show_pages_prompt", True)
language = normalize_language(payload.get("language"), default="en")
agent_progress_style = payload.get("agent_progress_style", DEFAULT_AGENT_PROGRESS_STYLE)
if agent_progress_style not in ("concise", "verbose", "off"):
- agent_progress_style = DEFAULT_AGENT_PROGRESS_STYLE
+ raise ValueError("Config 'agent_progress_style' must be 'concise', 'verbose', or 'off'")
def _positive_int(value, default, maximum):
if isinstance(value, bool) or not isinstance(value, int) or value <= 0 or value > maximum:
@@ -3054,6 +3351,9 @@ class V2Config:
# Cap to sane upper bounds so a fat-fingered value can't silence the
# heartbeat (heartbeat ≤ 1h, no-output hint ≤ 24h); out-of-range → default.
+ # These two keep the fallback the settings above give up: they are not on
+ # the Settings write surface, and ``test_status_bubble_settings`` states
+ # the tolerance as a contract rather than as an accident.
agent_status_heartbeat_ms = _positive_int(payload.get("agent_status_heartbeat_ms"), 8000, 3_600_000)
agent_status_no_output_ms = _positive_int(payload.get("agent_status_no_output_ms"), 180000, 86_400_000)
@@ -3061,8 +3361,9 @@ class V2Config:
# when present; otherwise leave it ``None`` here and derive it below
# from the legacy "setup done" heuristic so installs configured before
# this flag existed are not bounced back into the wizard.
- setup_completed_raw = payload.get("setup_completed")
- setup_completed = setup_completed_raw if isinstance(setup_completed_raw, bool) else None
+ setup_completed = payload.get("setup_completed")
+ if setup_completed is not None and not isinstance(setup_completed, bool):
+ raise ValueError("Config 'setup_completed' must be a boolean")
config = cls(
platform=platform,
diff --git a/core/audio_asr.py b/core/audio_asr.py
index d9ec6ccef..3aaac3426 100644
--- a/core/audio_asr.py
+++ b/core/audio_asr.py
@@ -117,16 +117,14 @@ class AudioAsrService:
return getattr(self.config, "audio_asr", None) or AudioAsrConfig()
def _runtime_config(self) -> AudioAsrRuntimeConfig | None:
+ # Readiness is decided by ``VibeCloudRemoteAccessConfig`` so this
+ # service and the config projections that gate the ASR controls can
+ # never disagree about whether the pairing is usable.
cloud = getattr(getattr(self.config, "remote_access", None), "vibe_cloud", None)
- if not cloud:
- return None
- if not getattr(cloud, "enabled", False):
- return None
- base_url = (getattr(cloud, "backend_url", "") or "").strip().rstrip("/")
- instance_id = (getattr(cloud, "instance_id", "") or "").strip()
- device_secret = (getattr(cloud, "instance_secret", "") or "").strip()
- if not base_url or not instance_id or not device_secret:
+ credentials = cloud.runtime_credentials() if cloud is not None else None
+ if credentials is None:
return None
+ base_url, instance_id, device_secret = credentials
return AudioAsrRuntimeConfig(base_url=base_url, instance_id=instance_id, device_secret=device_secret)
def _endpoint_url(self, runtime: AudioAsrRuntimeConfig) -> str:
diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.py
index 4b23bcab7..78a62e2d0 100644
--- a/tests/test_api_save_config_merge.py
+++ b/tests/test_api_save_config_merge.py
@@ -1,6 +1,9 @@
from __future__ import annotations
import ast
+import copy
+import json
+import re
import sys
from dataclasses import fields
from pathlib import Path
@@ -9,7 +12,14 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from config.v2_config import UiConfig, V2Config
+from config.v2_config import (
+ _FIELD_SCOPED_RECOVERY_SECTIONS,
+ AudioAsrConfig,
+ UiConfig,
+ V2Config,
+ VibeCloudRemoteAccessConfig,
+)
+from core.audio_asr import AudioAsrService
from vibe import api, remote_access
@@ -1077,3 +1087,567 @@ def test_full_config_serializers_cover_every_config_field(monkeypatch, tmp_path)
from config import paths
_assert_complete("V2Config.save", json.loads(paths.get_config_path().read_text(encoding="utf-8")))
+
+
+def test_non_owner_config_keeps_asr_and_pairing_without_host_secrets(tmp_path, monkeypatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = V2Config.from_payload(_full_config_payload())
+ config.remote_access.vibe_cloud.enabled = True
+ config.remote_access.vibe_cloud.instance_id = "inst_123"
+ config.remote_access.vibe_cloud.backend_url = "https://avibe.bot"
+ config.remote_access.vibe_cloud.instance_secret = "instance-secret"
+ config.remote_access.vibe_cloud.tunnel_token = "tunnel-secret"
+ config.remote_access.vibe_cloud.session_secret = "session-secret"
+ config.audio_asr.enabled = True
+ config.audio_asr.echo_transcript = False
+ config.audio_asr.model = "secret-model"
+
+ payload = api.non_owner_config_payload(config)
+
+ assert payload["audio_asr"] == {
+ "enabled": True,
+ "echo_transcript": False,
+ "enabled_configured": False,
+ }
+ assert payload["remote_access"] == {"vibe_cloud": {"paired": True}}
+ assert payload["platforms"]["enabled"]
+ assert payload["platform_catalog"]
+ serialized = str(payload)
+ assert "tunnel-secret" not in serialized
+ assert "session-secret" not in serialized
+ assert "instance-secret" not in serialized
+ assert "secret-model" not in serialized
+ assert "runtime" not in payload
+ assert "agents" not in payload
+
+
+def test_non_owner_config_projects_exactly_the_declared_surface(tmp_path, monkeypatch):
+ """The projection is the writable surface plus the context that renders it.
+
+ An equality, not a list of forbidden keys: a field added to either
+ declaration but not projected fails here, and so does any key that starts
+ leaking into non-owner responses. That is the same intent the older
+ ``"remote_access" not in payload`` check carried, stated so that it also
+ covers the keys nobody has thought of yet.
+ """
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = V2Config.from_payload(_full_config_payload())
+
+ payload = api.non_owner_config_payload(config)
+
+ assert set(payload) == set(api._EDITOR_CONFIG_WRITE_FIELDS) | set(
+ api._NON_OWNER_CONFIG_CONTEXT_FIELDS
+ )
+ assert set(api._EDITOR_CONFIG_UI_WRITE_FIELDS) <= set(payload["ui"])
+ assert set(api._EDITOR_AUDIO_ASR_WRITE_FIELDS) <= set(payload["audio_asr"])
+
+
+ "missing_field",
+ ["backend_url", "instance_id", "instance_secret"],
+)
+def test_non_owner_config_pairing_requires_runtime_ready_cloud(tmp_path, monkeypatch, missing_field):
+ """Every credential the ASR runtime needs also gates the projected flag.
+
+ One case per member of the runtime requirement, so a recovered or
+ partially migrated instance can never advertise a pairing the runtime
+ refuses to use.
+ """
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = V2Config.from_payload(_full_config_payload())
+ config.remote_access.vibe_cloud.enabled = True
+ config.remote_access.vibe_cloud.backend_url = "https://avibe.bot"
+ config.remote_access.vibe_cloud.instance_id = "inst_123"
+ config.remote_access.vibe_cloud.instance_secret = "instance-secret"
+ assert api.non_owner_config_payload(config)["remote_access"] == {"vibe_cloud": {"paired": True}}
+
+ setattr(config.remote_access.vibe_cloud, missing_field, "")
+
+ assert api.non_owner_config_payload(config)["remote_access"] == {"vibe_cloud": {"paired": False}}
+ assert AudioAsrService(config)._runtime_config() is None
+
+
+def test_malformed_cloud_section_is_refused_on_writes_and_recovered_on_disk(tmp_path, monkeypatch):
+ """A non-string cloud value is refused; a persisted one degrades, never 500s.
+
+ Two boundaries, two answers, from one rule. ``V2Config.from_payload`` is
+ where an API write is validated, so a number where a credential belongs is
+ refused rather than emptied — emptying is a repair, and this repair clears
+ a credential the caller never asked to clear, then answers 200. Disk
+ loading is the one path allowed to repair, so the same file recovers the
+ section behind a backup and a warning, which keeps the malformed shape a
+ disabled cloud feature rather than a 500 on every ``/api/config`` read.
+
+ Seeded over every field the dataclass declares as ``str`` rather than over
+ the three the pairing predicate reads, because the section is copied
+ verbatim out of the stored config and any of them can reach code that does
+ string work. Seeding is complete by construction, so a field added later
+ is covered without editing this test.
+ """
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config_path = tmp_path / "config.json"
+
+ def _payload(vibe_cloud: dict) -> dict:
+ payload = _full_config_payload()
+ payload["remote_access"] = {"provider": "vibe_cloud", "vibe_cloud": vibe_cloud}
+ return payload
+
+ def _load_from_disk(vibe_cloud: dict) -> V2Config:
+ config_path.write_text(json.dumps(_payload(vibe_cloud)), encoding="utf-8")
+ return V2Config.load(config_path)
+
+ def _assert_degrades(config: V2Config) -> None:
+ assert config.remote_access.vibe_cloud.is_runtime_paired() is False
+ assert AudioAsrService(config)._runtime_config() is None
+ assert api.non_owner_config_payload(config)["remote_access"] == {
+ "vibe_cloud": {"paired": False}
+ }
+ assert api.client_config_payload(config)["remote_access"]["vibe_cloud"]["paired"] is False
+
+ string_fields = [
+ info.name
+ for info in fields(VibeCloudRemoteAccessConfig)
+ # ``instance_kind`` is server-set at pairing and means "unknown" when it
+ # is not one of the kinds this build knows, so for it an unreadable
+ # value and an unrecognised one are the same answer.
+ if info.type in (str, "str") and info.name != "instance_kind"
+ ]
+ assert string_fields
+
+ paired = {
+ "enabled": True,
+ "backend_url": "https://avibe.bot",
+ "instance_id": "inst_123",
+ "instance_secret": "instance-secret",
+ }
+ assert V2Config.from_payload(_payload(paired)).remote_access.vibe_cloud.is_runtime_paired()
+
+ for name in string_fields:
+ # The write path names the field it refused, so the Settings page can
+ # say which one, and the disk path recovers rather than failing.
+ with pytest.raises(ValueError, match=re.escape(f"remote_access.vibe_cloud.{name}")):
+ V2Config.from_payload(_payload({**paired, name: 12345}))
+ config = _load_from_disk({**paired, name: 12345})
+ assert any("remote_access" in warning for warning in config.load_warnings), name
+ _assert_degrades(config)
+
+ # Every field at once, so recovery is not being carried by one lucky field.
+ config = _load_from_disk({"enabled": True, **{name: 12345 for name in string_fields}})
+ assert config.load_warnings
+ _assert_degrades(config)
+
+
+def _settings_write_paths() -> list[tuple[str, ...]]:
+ """Every preference path the shared Settings pages may write.
+
+ Read out of the route's own allowlists instead of restated here, so a
+ preference added to them is covered by the tests below without editing
+ them.
+ """
+ paths: list[tuple[str, ...]] = []
+ for key in sorted(api._EDITOR_CONFIG_WRITE_FIELDS):
+ if key == "ui":
+ paths += [("ui", sub) for sub in sorted(api._EDITOR_CONFIG_UI_WRITE_FIELDS)]
+ elif key == "audio_asr":
+ paths += [("audio_asr", sub) for sub in sorted(api._EDITOR_AUDIO_ASR_WRITE_FIELDS)]
+ else:
+ paths.append((key,))
+ # ``show_pages_prompt`` is Owner-only, so it is absent from the Editor
+ # allowlist while sharing the same validation block.
+ return [*paths, ("show_pages_prompt",)]
+
+
+def _nested_patch(path: tuple[str, ...], value: object) -> dict:
+ patch: object = value
+ for key in reversed(path):
+ patch = {key: patch}
+ return patch # type: ignore[return-value]
+
+
+def _walk(root: object, path: tuple[str, ...], *, attr: bool) -> object:
+ for key in path:
+ root = getattr(root, key) if attr else root[key] # type: ignore[index]
+ return root
+
+
+def test_wrong_typed_settings_writes_are_refused_instead_of_silently_defaulted(
+ tmp_path, monkeypatch
+):
+ """``/api/config`` stores what the caller sent, or it refuses the write.
+
+ Seeded over the whole Settings write surface and driven through both roles,
+ rather than over the preferences a review happened to name: the paths come
+ from the allowlists the route itself uses, so the field nobody enumerated
+ is covered too.
+
+ The defect being pinned is silent success, not a bad stored value. A stale
+ or non-browser client posting ``{"show_duration": "true"}`` was answered
+ 200 while the stored value became ``False`` — a request to switch a
+ preference on switched it off, and nothing said so. ``ack_mode``, three
+ lines above the same block, already raised; this asserts the whole surface
+ answers alike.
+ """
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ api.save_config(_full_config_payload())
+
+ def _stored() -> dict:
+ return api.config_to_payload(api.load_config(), include_secrets=True, include_internal=True)
+
+ baseline = _stored()
+ paths = _settings_write_paths()
+ assert paths
+
+ for path in paths:
+ for value in ([], {}, None):
+ label = (".".join(path), value)
+ with pytest.raises(ValueError):
+ api.save_config(_nested_patch(path, value))
+ if path[0] in api._EDITOR_CONFIG_WRITE_FIELDS:
+ with pytest.raises(ValueError):
+ api.save_config(api.editor_config_write_payload(_nested_patch(path, value)))
+ assert _stored() == baseline, label
+
+ # Posting each stored value back still succeeds, so the refusals above
+ # cannot be produced by a route that refuses every write.
+ for path in paths:
+ api.save_config(_nested_patch(path, _walk(baseline, path, attr=False)))
+ assert _stored() == baseline
+
+ # The review's own payload: asking to switch a preference on must never be
+ # answered 200 with the preference switched off.
+ api.save_config({"show_duration": True})
+ with pytest.raises(ValueError, match="show_duration"):
+ api.save_config({"show_duration": "true"})
+ assert api.load_config().show_duration is True
+
+
+def test_wrong_typed_settings_on_disk_degrade_instead_of_failing_the_load(tmp_path, monkeypatch):
+ """Refusing over HTTP must not turn a hand-edited config into a dead start.
+
+ ``from_payload`` is the strict boundary and ``load`` is the recovering one
+ (``_reset_recoverable_config_section`` says so in as many words), so every
+ refusal added above has to come back out of the recovery table rather than
+ reaching the caller. Seeded over the same surface as the write test, which
+ is what makes the two halves one statement instead of two lists.
+
+ Recovery is also held to what it may not decide on the config's behalf. It
+ may not answer for a field other than the one it repaired, so a sibling the
+ file still spells out survives; and it may not leave an optional feature
+ running, so a section declaring ``enabled`` comes back with it off no matter
+ which of its fields was unreadable.
+ """
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config_path = tmp_path / "config.json"
+ healthy = api.config_to_payload(
+ V2Config.from_payload(_full_config_payload()), include_secrets=True, include_internal=True
+ )
+ config_path.write_text(json.dumps(healthy), encoding="utf-8")
+ assert V2Config.load(config_path).load_warnings == ()
+
+ for path in _settings_write_paths():
+ label = ".".join(path)
+ payload = copy.deepcopy(healthy)
+ _walk(payload, path[:-1], attr=False)[path[-1]] = [] # type: ignore[index]
+ config_path.write_text(json.dumps(payload), encoding="utf-8")
+
+ config = V2Config.load(config_path)
+
+ assert any(path[0] in warning for warning in config.load_warnings), label
+ declared = _walk(V2Config.default(), path, attr=True)
+ expected = (
+ False
+ if path[0] in _FIELD_SCOPED_RECOVERY_SECTIONS and isinstance(declared, bool)
+ else declared
+ )
+ repaired = copy.deepcopy(healthy)
+ _walk(repaired, path[:-1], attr=False)[path[-1]] = expected # type: ignore[index]
+ if len(path) > 1:
+ section = _walk(repaired, path[:-1], attr=False)
+ if isinstance(section, dict) and "enabled" in section:
+ # An optional feature that needed recovering does not come back
+ # running, whichever of its fields was the unreadable one.
+ section["enabled"] = False
+ # The load must equal the parse of the file with that one field written
+ # as its recovered value. Stated against the parser rather than against
+ # the constant above because some of these fields are derived — the
+ # recovered ``audio_asr.enabled: false`` is what makes
+ # ``enabled_configured`` true — and a constant would assert the raw
+ # value the parser is contracted to move off.
+ reparsed = V2Config.from_payload(copy.deepcopy(repaired))
+ assert _walk(config, path, attr=True) == _walk(reparsed, path, attr=True), label
+ recovered = api.config_to_payload(config, include_secrets=True, include_internal=True)
+ if len(path) > 1:
+ # The recovered section must be exactly what that file would have
+ # parsed to — so every sibling survives, including the ones derived
+ # from it. Asserting sibling-by-sibling would instead pass for a
+ # recovery that quietly re-derived a flag nobody listed.
+ assert (
+ recovered[path[0]]
+ == api.config_to_payload(reparsed, include_secrets=True, include_internal=True)[
+ path[0]
+ ]
+ ), label
+
+ # A number that names no setting reaches the file by a route none of the
+ # shapes above take. ``json`` reads a hand-edited ``1e309`` and the
+ # ``Infinity`` an older release serialized into the same float, and on an
+ # ``int`` field converting it raises ``OverflowError`` — not the
+ # ``ValueError`` this recovery is built on, so it escaped ``load`` and took
+ # startup down with it, which is the one outcome this test exists to rule
+ # out. Asserted as "recovers like any other unreadable value" rather than
+ # against a hand-written expectation, so it cannot drift from the sweep
+ # above, and seeded from the declared numeric fields of the held sections,
+ # so a number added to one of them is covered without editing this.
+ assert json.loads("1e309") == float("inf")
+ assert json.loads(json.dumps(float("inf"))) == float("inf")
+ numeric_paths = [
+ (section, info.name)
+ for section in _FIELD_SCOPED_RECOVERY_SECTIONS
+ for info in fields(V2Config.__dataclass_fields__[section].default_factory)
+ if any(kind in str(info.type) for kind in ("int", "float"))
+ ]
+ assert len(numeric_paths) >= 3, numeric_paths
+ for path in numeric_paths:
+ label = ".".join(path)
+ unreadable = copy.deepcopy(healthy)
+ _walk(unreadable, path[:-1], attr=False)[path[-1]] = [] # type: ignore[index]
+ config_path.write_text(json.dumps(unreadable), encoding="utf-8")
+ like_any_other = api.config_to_payload(
+ V2Config.load(config_path), include_secrets=True, include_internal=True
+ )
+ for number in (float("inf"), float("-inf"), float("nan")):
+ payload = copy.deepcopy(healthy)
+ _walk(payload, path[:-1], attr=False)[path[-1]] = number # type: ignore[index]
+ config_path.write_text(json.dumps(payload), encoding="utf-8")
+
+ config = V2Config.load(config_path)
+
+ assert any(path[0] in warning for warning in config.load_warnings), (label, number)
+ assert (
+ api.config_to_payload(config, include_secrets=True, include_internal=True)
+ == like_any_other
+ ), (label, number)
+ # Everything outside the corrupted section survives. Without this the
+ # test would pass just as well for a recovery that threw the whole file
+ # away, which for a scalar looks identical to repairing that scalar.
+ assert {key: value for key, value in recovered.items() if key != path[0]} == {
+ key: value for key, value in healthy.items() if key != path[0]
+ }, label
+
+
+def test_unreadable_optional_feature_fields_never_load_the_feature_back_on(tmp_path, monkeypatch):
+ """Recovery keeps the siblings it can read, and never leaves a feature on.
+
+ Two properties from two questions that must not share an answer. *How much
+ is discarded* — replacing a section wholesale answers an unreadable font
+ size by hiding the tool-call rows and an unreadable model name by
+ forgetting the endpoint, so the unreadable field is repaired alone and its
+ siblings stay as written. *Whether the feature still runs* — it does not:
+ a section that declares ``enabled`` comes back disabled, whichever of its
+ fields was unreadable, which is what ``AGENTS.md`` means by "a broken
+ optional-feature section disables that feature and warns".
+
+ The second property reverses an earlier round of this PR, which argued the
+ two directions were symmetric. They are not: leaving ASR on ships user
+ audio off-machine under settings nobody wrote and cannot be undone, while
+ leaving it off costs a warning the operator reads before re-enabling.
+
+ Stated over the declared fields of every field-scoped section rather than
+ over the fields either review named, so a field or a whole section added to
+ ``_FIELD_SCOPED_RECOVERY_SECTIONS`` is covered without editing this test.
+ """
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config_path = tmp_path / "config.json"
+ base = api.config_to_payload(
+ V2Config.from_payload(_full_config_payload()), include_secrets=True, include_internal=True
+ )
+
+ def _load(payload: dict) -> V2Config:
+ config_path.write_text(json.dumps(payload), encoding="utf-8")
+ return V2Config.load(config_path)
+
+ def _section_payload(config: V2Config, section: str) -> dict:
+ return api.config_to_payload(config, include_secrets=True, include_internal=True)[section]
+
+ recovered_fields: set[tuple[str, str]] = set()
+ every_switch: set[tuple[str, str]] = set()
+ for section in _FIELD_SCOPED_RECOVERY_SECTIONS:
+ declared = fields(V2Config.__dataclass_fields__[section].default_factory)
+ switches = [info.name for info in declared if info.type in (bool, "bool")]
+ assert switches, section
+ every_switch |= {(section, name) for name in switches}
+ # Both sides, so "keeps the sibling as written" is a real statement
+ # rather than one that happens to match the declared defaults.
+ for side in (False, True):
+ seed = copy.deepcopy(base)
+ seed[section].update({name: side for name in switches})
+ assert _load(seed).load_warnings == (), (section, side)
+
+ for info in declared:
+ for unreadable in ([], "garbage", {"nope": 1}):
+ corrupted = copy.deepcopy(seed)
+ corrupted[section][info.name] = unreadable
+ try:
+ V2Config.from_payload(corrupted)
+ except (TypeError, ValueError):
+ pass
+ else:
+ # This field reads that value, so there is nothing to
+ # recover. Driving the sweep off the parser rather than
+ # off a table of types keeps a newly validated field
+ # covered without editing this test.
+ continue
+ recovered_fields.add((section, info.name))
+
+ config = _load(corrupted)
+ assert config.load_warnings, (section, side, info.name, unreadable)
+
+ # A declared switch resolves off; anything else falls back
+ # to its own default; and a section that declares a feature
+ # switch comes back with it off. Either way the section must
+ # be exactly what the file would have parsed to had it been
+ # written that way — which is how every sibling, including a
+ # flag derived from the repaired field, is held in a single
+ # assertion.
+ repaired = copy.deepcopy(seed)
+ repaired[section][info.name] = (
+ False
+ if info.name in switches
+ else getattr(getattr(V2Config.default(), section), info.name)
+ )
+ if "enabled" in switches:
+ repaired[section]["enabled"] = False
+ assert _section_payload(config, section) == _section_payload(
+ V2Config.from_payload(repaired), section
+ ), (section, side, info.name, unreadable)
+
+ # An unreadable section keeps no sibling, so every switch resolves off
+ # — stated the same way, as the parse of a section written that way.
+ broken = copy.deepcopy(base)
+ broken[section] = 5
+ config = _load(broken)
+ assert config.load_warnings, section
+ all_off = copy.deepcopy(base)
+ all_off[section] = {name: False for name in switches}
+ assert _section_payload(config, section) == _section_payload(
+ V2Config.from_payload(all_off), section
+ ), section
+
+ # The sweep skips any field the parser reads happily, so state that no
+ # switch was skipped: a switch that stopped being validated would make the
+ # property above vacuous exactly where it matters.
+ assert every_switch <= recovered_fields, every_switch - recovered_fields
+
+ # Both reviews' own cases: the switch itself, then the siblings. Whichever
+ # field was unreadable, and whichever side the file had asked for, an
+ # ``audio_asr`` that needed recovering comes back not transcribing.
+ assert "enabled" in {
+ info.name
+ for info in fields(V2Config.__dataclass_fields__["audio_asr"].default_factory)
+ if info.type in (bool, "bool")
+ }
+ for side in (False, True):
+ stored = copy.deepcopy(base)
+ stored["audio_asr"].update({"enabled": side, "enabled_configured": True})
+ for corrupt_field in (
+ "enabled",
+ "model",
+ "timeout_seconds",
+ "echo_transcript",
+ "enabled_configured",
+ ):
+ payload = copy.deepcopy(stored)
+ payload["audio_asr"][corrupt_field] = []
+ recovered = _load(payload)
+ assert recovered.load_warnings, (side, corrupt_field)
+ assert recovered.audio_asr.enabled is False, (side, corrupt_field)
+
+ # Disabled, not discarded: the siblings the file could still be read for
+ # survive, so this is not the whole-section wipe in a new costume.
+ kept = copy.deepcopy(base)
+ kept["audio_asr"].update(
+ {"enabled": True, "endpoint_path": "/v1/custom/transcriptions", "model": []}
+ )
+ recovered = _load(kept)
+ assert recovered.audio_asr.enabled is False
+ assert recovered.audio_asr.endpoint_path == "/v1/custom/transcriptions"
+ assert recovered.audio_asr.model == V2Config.default().audio_asr.model
+
+ # A section with no feature switch is presentation, not an optional feature:
+ # it keeps every sibling and disables nothing beyond the unreadable field.
+ hidden_rows = copy.deepcopy(base)
+ hidden_rows["ui"].update({"show_tool_calls": False, "instance_name": "kept"})
+ hidden_rows["ui"]["chat_message_font_size"] = "garbage"
+ recovered = _load(hidden_rows)
+ assert recovered.ui.show_tool_calls is False
+ assert recovered.ui.instance_name == "kept"
+ assert recovered.ui.instance_name == "kept"
+ assert recovered.ui.chat_message_font_size == V2Config.default().ui.chat_message_font_size
+
+ # Two unreadable fields of one section are two repairs, not a reason to
+ # discard the file: the recovery loop dedupes per field, not per section.
+ both = copy.deepcopy(base)
+ both["ui"].update(
+ {"show_agent_activity": "garbage", "show_tool_calls": 5, "instance_name": "kept"}
+ )
+ recovered = _load(both)
+ assert recovered.ui.show_agent_activity is False
+ assert recovered.ui.show_tool_calls is False
+ assert recovered.ui.instance_name == "kept"
+
+
+def test_editor_config_write_payload_keeps_messaging_fields_only():
+ projected = api.editor_config_write_payload(
+ {
+ "audio_asr": {"enabled": False, "enabled_configured": True, "echo_transcript": False},
+ "ack_mode": "message",
+ "ui": {"chat_message_font_size": 16, "show_agent_activity": True},
+ }
+ )
+
+ assert projected == {
+ "audio_asr": {"enabled": False, "enabled_configured": True, "echo_transcript": False},
+ "ack_mode": "message",
+ "ui": {"chat_message_font_size": 16, "show_agent_activity": True},
+ }
+
+
+ "payload",
+ [
+ {"runtime": {"default_cwd": "/tmp/owned"}},
+ {"audio_asr": {"enabled": False, "model": "owned-model"}},
+ {"ui": {"setup_host": "0.0.0.0"}},
+ {"ui": {"instance_name": "renamed"}},
+ {"ui": {"default_instance_name": "owned"}},
+ {"show_pages_prompt": False},
+ ],
+)
+def test_editor_config_write_payload_rejects_owner_fields(payload):
+ with pytest.raises(ValueError, match="editor_config_write_forbidden"):
+ api.editor_config_write_payload(payload)
+
+
[email protected]("payload", [[1], "ack_mode", 1, None])
+def test_editor_config_write_payload_rejects_non_object_with_stable_code(payload):
+ with pytest.raises(ValueError, match="editor_config_write_invalid"):
+ api.editor_config_write_payload(payload)
+
+
+def test_editor_config_write_error_code_keeps_every_failure_localizable():
+ """Any failure on an Editor write answers with a code the client can render.
+
+ The codes this module raises pass through; everything else — the English
+ sentences raised much later by ``V2Config.from_payload`` — collapses to the
+ generic invalid code, so no message can reach a non-English client
+ unlocalized just because nobody enumerated it here.
+ """
+ for code in api._EDITOR_CONFIG_WRITE_ERROR_CODES:
+ assert api.editor_config_write_error_code(ValueError(code)) == code
+
+ for exc in (
+ ValueError("Config 'ack_mode' must be one of typing, reaction, message"),
+ ValueError("Config 'agent_progress_style' must be 'off', 'concise', or 'verbose'"),
+ ValueError(""),
+ ):
+ assert api.editor_config_write_error_code(exc) == "editor_config_write_invalid"
diff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.py
index e691da1db..d742ec15c 100644
--- a/tests/test_instance_authorization.py
+++ b/tests/test_instance_authorization.py
@@ -155,6 +155,7 @@ def test_advertised_capability_namespaces_cover_current_and_future_routes() -> N
("GET", "/api/asr/status"),
("POST", "/api/asr/transcribe"),
("POST", "/api/asr/telemetry"),
+ ("POST", "/api/config"),
("POST", "/api/sessions/session-1/messages"),
("POST", "/api/sessions/session-1/attachments"),
("POST", "/api/sessions/session-1/cancel"),
diff --git a/tests/test_status_bubble_settings.py b/tests/test_status_bubble_settings.py
index 3ab0fcd7c..501a2debb 100644
--- a/tests/test_status_bubble_settings.py
+++ b/tests/test_status_bubble_settings.py
@@ -44,18 +44,22 @@ class ConfigParsingTests(unittest.TestCase):
self.assertEqual(cfg.agent_status_heartbeat_ms, 12000)
self.assertEqual(cfg.agent_status_no_output_ms, 60000)
- def test_invalid_values_fall_back_to_defaults(self):
+ def test_invalid_timings_fall_back_to_defaults(self):
+ # These two are internal tuning knobs, absent from the Settings write
+ # surface, so a bad value has no caller to answer and keeps degrading.
cfg = V2Config.from_payload(
- _payload(
- agent_progress_style="bogus",
- agent_status_heartbeat_ms=-5,
- agent_status_no_output_ms="nope",
- )
+ _payload(agent_status_heartbeat_ms=-5, agent_status_no_output_ms="nope")
)
- self.assertEqual(cfg.agent_progress_style, "off")
self.assertEqual(cfg.agent_status_heartbeat_ms, 8000)
self.assertEqual(cfg.agent_status_no_output_ms, 180000)
+ def test_invalid_progress_style_is_refused(self):
+ # ``agent_progress_style`` is written from the Settings page, where
+ # answering a rejected value with a default silently changes a
+ # preference the caller asked to set.
+ with self.assertRaises(ValueError):
+ V2Config.from_payload(_payload(agent_progress_style="bogus"))
+
def test_bool_is_not_accepted_as_int(self):
cfg = V2Config.from_payload(_payload(agent_status_heartbeat_ms=True))
self.assertEqual(cfg.agent_status_heartbeat_ms, 8000)
diff --git a/tests/test_ui_project_access.py b/tests/test_ui_project_access.py
index 3436663a4..92a0adaf2 100644
--- a/tests/test_ui_project_access.py
+++ b/tests/test_ui_project_access.py
@@ -382,8 +382,15 @@ def test_session_bootstrap_uses_effective_project_chat_role(monkeypatch, tmp_pat
assert editor_payload["draft"] == expected_draft
# Editors receive the non-sensitive runtime UI projection used by ChatPage;
# Owner-only management data remains available only to the Owner payload.
+ # Asserted as the declared key set rather than as named exclusions: any
+ # block that starts reaching non-owners fails here even if nobody thought
+ # to forbid it, and cloud pairing appears only as a readiness boolean —
+ # never as an endpoint, identifier, or secret.
assert editor_payload["config"]["ui"]["chat_message_font_size"]
- assert "remote_access" not in editor_payload["config"]
+ assert set(editor_payload["config"]) == set(api._EDITOR_CONFIG_WRITE_FIELDS) | set(
+ api._NON_OWNER_CONFIG_CONTEXT_FIELDS
+ )
+ assert editor_payload["config"]["remote_access"] == {"vibe_cloud": {"paired": False}}
owner = _remote_client(config, role="owner", email="[email protected]")
owner_payload = _get(owner, f"/api/sessions/{ids['session_a']}/bootstrap").get_json()
@@ -418,6 +425,105 @@ def test_session_bootstrap_uses_effective_project_chat_role(monkeypatch, tmp_pat
assert editor_project["capabilities"] == {"can_chat": True, "has_folder": True}
+def test_editor_config_write_always_answers_with_a_renderable_code(monkeypatch, tmp_path) -> None:
+ """Every rejected Editor config write leaves the API as a client-renderable code.
+
+ Stated over the ways an Editor write can fail rather than over the one
+ message a review happened to name: a field outside the write allowlist is
+ refused up front, and an allowlisted field carrying a bad value is refused
+ much later inside ``V2Config.from_payload``. Both leave through the same
+ chokepoint, so a non-English client never has to render a raw English
+ validation sentence. The accepted write is asserted alongside them so the
+ codes cannot be produced by an endpoint that refuses everything.
+ """
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config, _ids = _setup_state(tmp_path)
+ client = _remote_client(config, role="editor", email="[email protected]")
+
+ def _post(payload: dict):
+ return client.post(
+ "/api/config",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=csrf_headers(client, REMOTE_ORIGIN),
+ json=payload,
+ )
+
+ forbidden = _post({"runtime": {"default_cwd": "/tmp/editor-should-not-write"}})
+ assert forbidden.status_code == 400
+ assert forbidden.get_json()["error"] == {
+ "code": "editor_config_write_forbidden",
+ "message": "editor_config_write_forbidden",
+ }
+
+ invalid = _post({"ack_mode": "not-a-mode"})
+ assert invalid.status_code == 400
+ assert invalid.get_json()["error"] == {
+ "code": "editor_config_write_invalid",
+ "message": "editor_config_write_invalid",
+ }
+
+ accepted = _post({"ack_mode": "reaction"})
+ assert accepted.status_code == 200
+ assert V2Config.load().ack_mode == "reaction"
+ assert V2Config.load().runtime.default_cwd == "."
+
+
+def test_config_write_requires_an_object_body_whatever_the_role(monkeypatch, tmp_path) -> None:
+ """A config write is a patch object, and a body that is not one is refused.
+
+ Stated over the JSON value space rather than over the shapes a review
+ happened to name: the route decoded the body with the usual ``request.json
+ or {}``, which turned every falsy value — including a missing body — into
+ an empty patch, so a malformed write persisted nothing and still answered
+ 200. Truthy non-objects were refused only because they survived that
+ coercion, which is why an enumeration would have missed exactly the half
+ that was broken. Both roles are asserted because the rule belongs to the
+ route, not to the Editor allowlist that happened to cover one side of it.
+ """
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config, _ids = _setup_state(tmp_path)
+ editor = _remote_client(config, role="editor", email="[email protected]")
+ owner = app.test_client()
+ editor_headers = {**csrf_headers(editor, REMOTE_ORIGIN), "Content-Type": "application/json"}
+ owner_headers = {**csrf_headers(owner, "http://localhost"), "Content-Type": "application/json"}
+
+ def _post_body(body):
+ return (
+ editor.post(
+ "/api/config",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=editor_headers,
+ content=json.dumps(body),
+ ),
+ owner.post(
+ "/api/config",
+ base_url="http://localhost",
+ headers=owner_headers,
+ content=json.dumps(body),
+ ),
+ )
+
+ for body in (None, [], [1], "", "text", 0, 1, False, True):
+ editor_response, owner_response = _post_body(body)
+ assert editor_response.status_code == 400, body
+ assert editor_response.get_json()["error"] == {
+ "code": "editor_config_write_invalid",
+ "message": "editor_config_write_invalid",
+ }, body
+ # The Owner keeps the descriptive message its Settings pages render.
+ assert owner_response.status_code == 400, body
+ assert owner_response.get_json()["error"] == "Config payload must be an object", body
+
+ # An empty object is a valid no-op patch, so the refusals above cannot be
+ # produced by a route that has started refusing every body.
+ editor_response, owner_response = _post_body({})
+ assert editor_response.status_code == 200
+ assert owner_response.status_code == 200
+ assert V2Config.load().ack_mode == "typing"
+
+
def test_archived_project_invalidates_retained_remote_urls(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config, ids = _setup_state(tmp_path)
diff --git a/tests/test_v2_config_platform_registry.py b/tests/test_v2_config_platform_registry.py
index 904576b02..5b196f1f6 100644
--- a/tests/test_v2_config_platform_registry.py
+++ b/tests/test_v2_config_platform_registry.py
@@ -1,9 +1,16 @@
from __future__ import annotations
+import copy
+import re
+from dataclasses import fields
+
import pytest
from config.v2_config import (
+ _BOOL_SPELLINGS,
+ _named_value,
AgentsConfig,
+ AudioAsrConfig,
DiscordConfig,
LarkConfig,
PlatformsConfig,
@@ -13,6 +20,7 @@ from config.v2_config import (
UiConfig,
UpdateConfig,
V2Config,
+ VibeCloudRemoteAccessConfig,
WeChatConfig,
)
from vibe import api
@@ -264,10 +272,13 @@ def test_chat_message_font_size_is_clamped() -> None:
assert config.ui.chat_message_font_size == 20
+ # A size out of range still names a size, so it is clamped. One that names
+ # no size is refused rather than answered with the default: this is the
+ # write path for /api/config, where substituting a default would return 200
+ # holding a value the caller never sent.
payload["ui"]["chat_message_font_size"] = "bad"
- config = V2Config.from_payload(payload)
-
- assert config.ui.chat_message_font_size == 14
+ with pytest.raises(ValueError, match="chat_message_font_size"):
+ V2Config.from_payload(payload)
def test_show_agent_activity_defaults_off_and_round_trips() -> None:
@@ -306,6 +317,42 @@ def test_show_tool_calls_defaults_on_and_round_trips() -> None:
assert config.ui.show_tool_calls is False
assert api.config_to_payload(config)["ui"]["show_tool_calls"] is False
+
+def test_ui_switches_resolve_the_side_a_spelling_names_or_refuse_the_value() -> None:
+ """A switch stores the side its value names; a value naming none is refused.
+
+ ``/api/config`` validates through this same parser, so a value read as a
+ side it never named is answered 200 holding the opposite of what the caller
+ sent. Seeded from ``_BOOL_SPELLINGS`` and from the switches ``UiConfig``
+ declares rather than from lists repeated here, so a spelling added to the
+ vocabulary or a switch added to the section is covered without editing it.
+ """
+ payload = api.config_to_payload(_base_config())
+ switches = [info.name for info in fields(UiConfig) if info.type in (bool, "bool")]
+ assert len(switches) > 1
+
+ for name in switches:
+ for spelling, side in _BOOL_SPELLINGS.items():
+ for written in (spelling, spelling.upper(), f" {spelling} "):
+ payload["ui"][name] = written
+ parsed = getattr(V2Config.from_payload(payload).ui, name)
+ assert parsed is side, (name, written)
+ for literal in (True, False, 1, 0):
+ payload["ui"][name] = literal
+ assert getattr(V2Config.from_payload(payload).ui, name) is bool(literal), (
+ name,
+ literal,
+ )
+
+ # Outside the vocabulary the value names no side at all. Reading it as
+ # off — which is what a truthy-list-plus-else does — is the defect:
+ # ``5`` was read as on and ``"garbage"`` as off, both silently.
+ for unspellable in ("garbage", "maybe", "true-ish", 5, -1, 2.0, [], {}, None):
+ payload["ui"][name] = unspellable
+ with pytest.raises(ValueError, match=name):
+ V2Config.from_payload(payload)
+ payload["ui"][name] = getattr(_base_config().ui, name)
+
# String forms parse explicitly — ``bool("false")`` would be True, which must NOT
# keep tool rows visible when the user hid them.
for truthy in ("true", "True", "1", "yes", "on"):
@@ -316,6 +363,217 @@ def test_show_tool_calls_defaults_on_and_round_trips() -> None:
assert V2Config.from_payload(payload).ui.show_tool_calls is False, falsey
+# The sections this PR makes writable, and how to reach each one in a payload.
+# ``instance_kind`` is server-set at pairing and means "unknown" whenever it is
+# not a kind this build knows, so for it an unreadable value and an
+# unrecognised one are the same answer; it is exempt by name in the dataclass.
+_KIND_HELD_SECTIONS = (
+ ("ui", UiConfig, ("ui",)),
+ ("audio_asr", AudioAsrConfig, ("audio_asr",)),
+ (
+ "remote_access.vibe_cloud",
+ VibeCloudRemoteAccessConfig,
+ ("remote_access", "vibe_cloud"),
+ ),
+)
+_KIND_EXEMPT_FIELDS = {("remote_access.vibe_cloud", "instance_kind")}
+
+# What each declared kind must refuse. ``True`` appears under the numbers on
+# purpose: Python makes ``bool`` an ``int``, so ``int(True)`` is a legal ``1``
+# and a switch posted where a size or a timeout belongs would be stored as one.
+# The infinities and the NaN are there because they are numbers that name no
+# setting: ``json`` produces them from a hand-edited ``1e309`` as readily as
+# from the literal ``Infinity``, ``int(inf)`` raises ``OverflowError`` rather
+# than the ``ValueError`` every other refusal here raises, and a ``float`` field
+# accepted them outright — an ASR timeout of infinity never expires.
+_NAMING_NO_NUMBER = (True, False, "garbage", [], {}, None, float("inf"), float("-inf"), float("nan"))
+# A fractional value is a legal ``float`` and names no ``int``, so this is the
+# one row the two numeric kinds cannot share: ``int(14.9)`` is ``14``, and a
+# font size posted as 14.9 was answered 200 and stored as 14.
+_VALUES_NAMING_NO = {
+ "bool": ("garbage", 5, -1, 2.0, [], {}, None),
+ "int": _NAMING_NO_NUMBER + (14.9, -0.5, 0.1),
+ "float": _NAMING_NO_NUMBER,
+ "str": (5, True, 2.0, [], {}, None),
+}
+
+
+def _declared_kind(info) -> tuple[str, bool]:
+ """The kind a field declares, and whether it also names ``None``.
+
+ ``Optional[int]`` reports its ``__name__`` as the bare ``"Optional"``, which
+ dropped the kind being wrapped and quietly excused every optional field from
+ the rule below — ``audio_asr.max_file_bytes`` was skipped while this test's
+ docstring claimed every declared field was covered.
+ """
+
+ text = info.type if isinstance(info.type, str) else getattr(info.type, "__name__", "")
+ if text.startswith("Optional"):
+ text = str(info.type)
+ optional = re.fullmatch(r"(?:typing\.)?Optional\[(?:typing\.)?(.+)\]", text)
+ return (optional.group(1), True) if optional else (text, False)
+
+
+def test_config_fields_are_held_to_the_kind_they_declare() -> None:
+ """Every field of a writable section refuses a value naming another kind.
+
+ ``/api/config`` validates through this same parser, so a value coerced into
+ a legal one is answered 200 having stored something the caller never sent:
+ ``{"chat_message_font_size": true}`` became the minimum font size,
+ ``{"timeout_seconds": true}`` a one-second ASR timeout, and a number where
+ a credential belongs emptied the credential. Each was a separate finding
+ because each field open-coded its own coercion; the property is stated once
+ here instead.
+
+ "Another kind" includes a number of the right type that still names no
+ setting. An infinity is a ``float`` and a NaN loses every comparison it is
+ given, so both slip past a type check and then behave as settings — an ASR
+ timeout that never expires, a size that clamps to whichever bound is written
+ first — and on an ``int`` field the conversion raises ``OverflowError``
+ instead, which is not the exception the disk path recovers from.
+
+ Seeded from the declared fields of each section rather than from the ones a
+ review reached, and closed with a non-vacuity assertion, so a field added to
+ any of these dataclasses is covered without editing this test.
+ """
+ healthy = api.config_to_payload(
+ V2Config.from_payload(
+ {
+ **api.config_to_payload(_base_config(), include_secrets=True),
+ "remote_access": {"provider": "vibe_cloud", "vibe_cloud": {"enabled": True}},
+ "audio_asr": {"enabled": True},
+ }
+ ),
+ include_secrets=True,
+ include_internal=True,
+ )
+
+ def _seed(section_path: tuple[str, ...], name: str, value: object) -> dict:
+ payload = copy.deepcopy(healthy)
+ cursor = payload
+ for key in section_path:
+ cursor = cursor[key]
+ cursor[name] = value
+ return payload
+
+ held: set[tuple[str, str]] = set()
+ declared_kinds: set[tuple[str, str]] = set()
+ for section, dataclass_type, section_path in _KIND_HELD_SECTIONS:
+ assert V2Config.from_payload(copy.deepcopy(healthy)), section
+ for info in fields(dataclass_type):
+ kind, optional = _declared_kind(info)
+ if kind not in _VALUES_NAMING_NO:
+ # Containers and nested sections are held by the code that
+ # already understands them, not by the declared-kind rule.
+ continue
+ if (section, info.name) in _KIND_EXEMPT_FIELDS:
+ continue
+ declared_kinds.add((section, info.name))
+ for value in _VALUES_NAMING_NO[kind]:
+ if value is None and optional:
+ # A field that declares ``Optional`` names ``None`` as one of
+ # its own values, so refusing it would be the mirror defect.
+ assert V2Config.from_payload(_seed(section_path, info.name, None))
+ continue
+ with pytest.raises(ValueError, match=re.escape(f"{section}.{info.name}")):
+ V2Config.from_payload(_seed(section_path, info.name, value))
+ held.add((section, info.name))
+
+ assert declared_kinds <= held, declared_kinds - held
+ assert len(held) > 10, held
+
+ # An optional scalar is a declared kind like any other, and it existing is
+ # what stops the line above from being satisfied by a resolver that quietly
+ # drops every ``Optional`` field out of ``declared_kinds`` as well as out of
+ # ``held`` — which is how ``audio_asr.max_file_bytes`` went uncovered.
+ optional_scalars = {
+ (section, info.name)
+ for section, dataclass_type, _ in _KIND_HELD_SECTIONS
+ for info in fields(dataclass_type)
+ if _declared_kind(info)[1] and _declared_kind(info)[0] in _VALUES_NAMING_NO
+ }
+ assert optional_scalars, "no optional scalar field left to hold to its declared kind"
+ assert optional_scalars <= held, optional_scalars - held
+
+ # A value that *names* the declared kind is still read, so the rule refuses
+ # wrong kinds rather than everything that is not already the right type.
+ assert V2Config.from_payload(_seed(("ui",), "chat_message_font_size", "15")).ui.chat_message_font_size == 15
+ assert V2Config.from_payload(_seed(("audio_asr",), "timeout_seconds", "2.5")).audio_asr.timeout_seconds == 2.5
+ assert (
+ V2Config.from_payload(
+ _seed(("remote_access", "vibe_cloud"), "auto_recovery", "off")
+ ).remote_access.vibe_cloud.auto_recovery
+ is False
+ )
+
+
+# Numbers to offer the numeric vocabulary: whole and fractional, negative, the
+# first integer a ``float`` cannot hold, one too large for a ``float`` at all,
+# and the three that are numbers without naming a quantity.
+_NUMBERS_GIVEN = (
+ 0,
+ 1,
+ -3,
+ 14,
+ 14.0,
+ -2.0,
+ 0.5,
+ 2.5,
+ 14.9,
+ -0.5,
+ 10**19,
+ 2**53 + 1,
+ 10**309,
+ float("inf"),
+ float("-inf"),
+ float("nan"),
+)
+
+
+def test_a_number_this_parser_accepts_is_the_number_it_was_given() -> None:
+ """Whatever the numeric vocabulary accepts, it stores unchanged.
+
+ Three review rounds each found one coercion — a switch read as ``1``, an
+ infinity read as an ASR timeout, a font size of 14.9 truncated to ``14`` —
+ and they are one defect wearing three faces: a conversion that succeeds
+ while changing the number, so the write is answered 200 having stored a
+ setting the caller never sent. Listing the three known faces would leave the
+ fourth to a fourth review round, so the property is stated over inputs
+ instead of over forbidden cases: offer this vocabulary a number, and either
+ it refuses or it hands back exactly what it was given. A conversion added
+ later that rounds, truncates, or saturates fails here rather than in review.
+
+ A spelling is deliberately not held to the rule — reading ``"14"`` as 14 is
+ the normalization this keeps, asserted at the bottom — because a spelling
+ names a number without being one, and no fractional spelling reaches the
+ conversion anyway: ``int("14.9")`` raises.
+ """
+
+ read: dict[str, list[object]] = {"int": [], "float": []}
+ for kind in read:
+ for value in _NUMBERS_GIVEN:
+ try:
+ number = _named_value(f"probe.{kind}", kind, value)
+ except ValueError:
+ continue
+ assert number == value, (kind, value, number)
+ read[kind].append(value)
+
+ # Non-vacuity, and the half of the contract the rule must not eat: refusing
+ # every number satisfies the loop above, so the values that must still be
+ # read are named. They are asserted by calling rather than by looking for
+ # them in what was accepted, because ``14.0 in [14]`` is true in Python —
+ # membership would report the float as read on the strength of the int it
+ # equals, and a rule that refused every float would pass.
+ assert _named_value("probe.int", "int", 14.0) == 14
+ assert _named_value("probe.float", "float", 14.9) == 14.9
+ assert _named_value("probe.int", "int", 2**53 + 1) == 2**53 + 1
+ assert len(read["int"]) >= 6 and len(read["float"]) >= 6, read
+
+ assert _named_value("probe.int", "int", "14") == 14
+ assert _named_value("probe.float", "float", "2.5") == 2.5
+
+
def test_config_payload_includes_vibe_cloud_remote_access() -> None:
config = _base_config()
config.remote_access.vibe_cloud.enabled = True
diff --git a/ui/src/components/settings/SettingsMessagingPage.test.tsx b/ui/src/components/settings/SettingsMessagingPage.test.tsx
index 044666963..00ebb5725 100644
--- a/ui/src/components/settings/SettingsMessagingPage.test.tsx
+++ b/ui/src/components/settings/SettingsMessagingPage.test.tsx
@@ -2,6 +2,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
import { SettingsMessagingPage } from './SettingsMessagingPage';
@@ -40,6 +41,8 @@ const baseConfig = {
reply_enhancements: true,
show_pages_prompt: true,
agent_progress_style: 'off',
+ audio_asr: { enabled: true, echo_transcript: true, enabled_configured: true },
+ remote_access: { vibe_cloud: { paired: true } },
ui: { chat_message_font_size: 14, show_agent_activity: false, show_tool_calls: true },
slack: { disable_link_unfurl: false },
agents: {
@@ -68,10 +71,51 @@ const remoteOwner: InstanceAuthorizationValue = {
};
const remoteEditor: InstanceAuthorizationValue = {
- ...remoteOwner,
+ remote: true,
+ instanceKind: null,
instanceRole: 'editor',
+ capabilities: {
+ ...OWNER_INSTANCE_CAPABILITIES,
+ can_manage_instance: false,
+ can_use_system: false,
+ can_manage_projects: false,
+ can_manage_agents: false,
+ },
+};
+
+const remoteViewer: InstanceAuthorizationValue = {
+ remote: true,
+ instanceKind: null,
+ instanceRole: 'viewer',
+ capabilities: {
+ ...OWNER_INSTANCE_CAPABILITIES,
+ can_chat: false,
+ can_manage_instance: false,
+ can_use_system: false,
+ can_manage_projects: false,
+ can_manage_agents: false,
+ can_use_agents: false,
+ can_use_skills: false,
+ can_use_vault_secrets: false,
+ can_use_show_pages: false,
+ can_use_terminal_files: false,
+ can_use_terminal: false,
+ can_use_files: false,
+ },
};
+function asrToggle() {
+ const title = screen.getByText('dashboard.audioTranscription');
+ const row = title.closest('.flex.flex-col.gap-3') ?? title.parentElement?.parentElement;
+ return row?.querySelector('[role="switch"]') as HTMLButtonElement | null;
+}
+
+// Identifies a control by its SettingsRow label so coverage survives re-renders.
+function controlLabel(control: Element): string {
+ const row = control.closest('div.flex.flex-col.gap-3');
+ return row?.querySelector('div.flex.min-w-0')?.textContent ?? '';
+}
+
function renderPage(context: InstanceAuthorizationValue) {
return render(
<InstanceAuthorizationContext.Provider value={context}>
@@ -120,4 +164,142 @@ describe('SettingsMessagingPage locality gating', () => {
expect(screen.queryByText('dashboard.opencodeActiveTurnTimeout')).toBeNull();
expect(screen.queryByText('dashboard.showPagesPrompt')).toBeNull();
});
+
+ it('shows a paired Editor the live ASR preference instead of a forced-off toggle', async () => {
+ renderPage(remoteEditor);
+
+ await screen.findByText('dashboard.audioTranscription');
+ const toggle = asrToggle();
+ expect(toggle).toBeTruthy();
+ expect(toggle?.getAttribute('aria-checked')).toBe('true');
+ expect(toggle?.disabled).toBe(false);
+ expect(screen.queryByText('dashboard.audioTranscriptionRequiresVibeCloud')).toBeNull();
+ });
+
+ it('keeps a paired Editor able to turn ASR off', async () => {
+ api.getConfig.mockResolvedValue({
+ ...baseConfig,
+ audio_asr: { enabled: false, echo_transcript: true, enabled_configured: true },
+ });
+ renderPage(remoteEditor);
+
+ await screen.findByText('dashboard.audioTranscription');
+ const toggle = asrToggle();
+ expect(toggle?.getAttribute('aria-checked')).toBe('false');
+ expect(toggle?.disabled).toBe(false);
+ });
+
+ it('shows a paired Viewer the live ASR state without making it clickable', async () => {
+ renderPage(remoteViewer);
+
+ await screen.findByText('dashboard.audioTranscription');
+ const toggle = asrToggle();
+ expect(toggle?.getAttribute('aria-checked')).toBe('true');
+ expect(toggle?.disabled).toBe(true);
+ });
+
+ it('sends only the changed ASR field when an Editor toggles transcription', async () => {
+ const user = userEvent.setup();
+ renderPage(remoteEditor);
+
+ await screen.findByText('dashboard.audioTranscription');
+ const toggle = asrToggle();
+ expect(toggle).toBeTruthy();
+ await user.click(toggle!);
+
+ expect(api.saveConfig).toHaveBeenCalledWith({
+ audio_asr: { enabled: false, enabled_configured: true },
+ });
+ });
+
+ it('sends only the changed acknowledgement field when an Editor changes ack mode', async () => {
+ const user = userEvent.setup();
+ renderPage(remoteEditor);
+
+ const select = await screen.findByDisplayValue('dashboard.ackTyping');
+ await user.selectOptions(select, 'message');
+
+ expect(api.saveConfig).toHaveBeenCalledWith({ ack_mode: 'message' });
+ });
+
+ it('hides Slack preview controls from Editors when they cannot manage the instance', async () => {
+ api.getConfig.mockResolvedValue({
+ ...baseConfig,
+ platforms: { enabled: ['slack'] },
+ platform_catalog: [{ id: 'slack', capabilities: { supports_reaction_indicator: true, supports_typing_indicator: true } }],
+ });
+ renderPage(remoteEditor);
+
+ await screen.findByText('dashboard.ackMode');
+ expect(screen.queryByText('dashboard.slackLinkPreviews')).toBeNull();
+ });
+
+ it('keeps the Slack preview control for a remote Owner and sends its own field patch', async () => {
+ // A remote Owner also saves field-specifically, so gating this control on
+ // "can use the local system" would have hidden it from a role allowed to
+ // write ``slack.*``. It is gated on instance management and carries a patch.
+ const user = userEvent.setup();
+ renderPage(remoteOwner);
+
+ await screen.findByText('dashboard.slackLinkPreviews');
+ const row = screen.getByText('dashboard.slackLinkPreviews').closest('div.flex.flex-col.gap-3');
+ await user.click(row?.querySelector('[role="switch"]') as HTMLButtonElement);
+
+ expect(api.saveConfig).toHaveBeenCalledWith({ slack: { disable_link_unfurl: true } });
+ });
+
+ it('never posts an empty patch from any control an Editor is offered', async () => {
+ // The property, not today's control list: a field-specific save carries only
+ // the control's own patch, so any control rendered without one posts ``{}``
+ // — a save that reports success and loses the change on reload. Sweeping
+ // whatever is rendered catches the next control added without a patch; an
+ // enumeration of the current controls never would.
+ const user = userEvent.setup();
+ renderPage(remoteEditor);
+ await screen.findByText('dashboard.ackMode');
+
+ const switches = () => screen.queryAllByRole('switch') as HTMLButtonElement[];
+ const selects = () => screen.queryAllByRole('combobox') as HTMLSelectElement[];
+ const exercised = new Set<string>();
+ const unsaved: string[] = [];
+ // Checked per interaction against the call the interaction itself produced:
+ // a control without a field patch either posts ``{}`` or trips the guard in
+ // ``persist`` and posts nothing, and both look identical at the end of a
+ // sweep once a later control's successful save has cleared the state.
+ const recordInteraction = async (label: string, act: () => Promise<void>) => {
+ const before = api.saveConfig.mock.calls.length;
+ exercised.add(label);
+ await act();
+ const patch = api.saveConfig.mock.calls[before]?.[0] as Record<string, unknown> | undefined;
+ if (!patch || Object.keys(patch).length === 0) unsaved.push(label);
+ };
+
+ // Two rounds, re-querying every step: toggling a parent reveals a child
+ // control (show_tool_calls) and toggling ASR off disables its echo child, so
+ // one pass can neither see nor reach the whole surface.
+ for (let round = 0; round < 2; round += 1) {
+ for (let index = 0; index < switches().length; index += 1) {
+ const control = switches()[index];
+ if (control.disabled) continue;
+ await recordInteraction(controlLabel(control), () => user.click(control));
+ }
+ for (let index = 0; index < selects().length; index += 1) {
+ const select = selects()[index];
+ const option = Array.from(select.options).find(
+ (each) => !each.disabled && each.value !== select.value,
+ );
+ if (!option) continue;
+ await recordInteraction(controlLabel(select), () =>
+ user.selectOptions(select, option.value),
+ );
+ }
+ }
+
+ const offered = [...switches(), ...selects()].filter(
+ (control) => !(control as HTMLButtonElement).disabled,
+ );
+ expect(offered.length).toBeGreaterThan(0);
+ expect(offered.map(controlLabel).filter((label) => !exercised.has(label))).toEqual([]);
+ expect(unsaved).toEqual([]);
+ });
});
diff --git a/ui/src/components/settings/SettingsMessagingPage.tsx b/ui/src/components/settings/SettingsMessagingPage.tsx
index 6249b562d..f193e6f2c 100644
--- a/ui/src/components/settings/SettingsMessagingPage.tsx
+++ b/ui/src/components/settings/SettingsMessagingPage.tsx
@@ -26,7 +26,7 @@ import {
normalizeChatMessageFontSize,
} from '@/lib/chatDisplay';
-const SAVE_KEYS = [
+const OWNER_SAVE_KEYS = [
'platforms',
'ack_mode',
'show_duration',
@@ -44,16 +44,21 @@ const SAVE_KEYS = [
'agents',
] as const;
-function buildMessagePatch(config: any, extraPatch: Record<string, unknown> = {}) {
- // ``save_config`` merges onto the stored config and the backend derives the
- // internal default platform from ``platforms.enabled``, so this messaging
- // save no longer sends a ``platform``/primary field.
+function buildMessagePatch(
+ config: any,
+ extraPatch: Record<string, unknown> = {},
+ { fieldSpecific }: { fieldSpecific: boolean },
+) {
+ // Owners still send the existing messaging snapshot so a first-time save of
+ // an older page does not drop sibling fields. Editors send only the changed
+ // field so an unrelated autosave cannot overwrite a newer ASR value.
+ if (fieldSpecific) {
+ return extraPatch;
+ }
const patch: Record<string, unknown> = {};
-
- for (const key of SAVE_KEYS) {
+ for (const key of OWNER_SAVE_KEYS) {
patch[key] = config?.[key];
}
-
return { ...patch, ...extraPatch };
}
@@ -73,6 +78,8 @@ export const SettingsMessagingPage: React.FC = () => {
const api = useApi();
const { capabilities } = useInstanceAuthorization();
const canUseSystem = capabilities.can_use_system;
+ const canManageInstance = capabilities.can_manage_instance;
+ const canEditMessaging = capabilities.can_chat || canUseSystem;
const [config, setConfig] = useState<any>(null);
const [saveError, setSaveError] = useState<string | null>(null);
const [savedAt, setSavedAt] = useState<number | null>(null);
@@ -97,10 +104,20 @@ export const SettingsMessagingPage: React.FC = () => {
);
const persist = async (nextConfig: any, extraPatch?: Record<string, unknown>) => {
+ const fieldSpecific = !canUseSystem;
+ // A field-specific save carries only what the control passes, so a control
+ // without an explicit patch would post ``{}``: a silent success that drops
+ // the change on reload. Controls that write owner-only fields have no
+ // Editor patch by design and must be gated out below; reaching here means
+ // one was rendered anyway, so fail visibly instead of pretending to save.
+ if (fieldSpecific && !extraPatch) {
+ setSaveError(t('common.saveFailed'));
+ return;
+ }
setConfig(nextConfig);
setSaveError(null);
try {
- await api.saveConfig(buildMessagePatch(nextConfig, extraPatch));
+ await api.saveConfig(buildMessagePatch(nextConfig, extraPatch, { fieldSpecific }));
setSavedAt(Date.now());
} catch (error) {
setSaveError(error instanceof Error ? error.message : t('common.saveFailed'));
@@ -134,8 +151,9 @@ export const SettingsMessagingPage: React.FC = () => {
const includeTimeInfoEnabled = config.include_time_info !== false;
const audioAsr = config.audio_asr || {};
const audioEchoEnabled = audioAsr.echo_transcript !== false;
- const vibeCloud = config.remote_access?.vibe_cloud || {};
- const vibeCloudPaired = Boolean(vibeCloud.enabled && vibeCloud.instance_id);
+ // Server-computed readiness: the identifiers alone cannot answer this, since
+ // the secret the ASR runtime needs is redacted from every config response.
+ const vibeCloudPaired = Boolean(config.remote_access?.vibe_cloud?.paired);
const audioAsrEnabled = vibeCloudPaired && audioAsr.enabled !== false;
const chatMessageFontSize = normalizeChatMessageFontSize(config.ui?.chat_message_font_size);
const saveChatMessageFontSize = (fontSize: number) => {
@@ -237,7 +255,7 @@ export const SettingsMessagingPage: React.FC = () => {
control={
<ToggleSwitch
enabled={audioAsrEnabled}
- disabled={!vibeCloudPaired}
+ disabled={!canEditMessaging || !vibeCloudPaired}
onClick={() =>
void persist({
...config,
@@ -246,6 +264,11 @@ export const SettingsMessagingPage: React.FC = () => {
enabled: !audioAsrEnabled,
enabled_configured: true,
},
+ }, {
+ audio_asr: {
+ enabled: !audioAsrEnabled,
+ enabled_configured: true,
+ },
})
}
/>
@@ -258,7 +281,7 @@ export const SettingsMessagingPage: React.FC = () => {
control={
<ToggleSwitch
enabled={audioEchoEnabled}
- disabled={!audioAsrEnabled}
+ disabled={!canEditMessaging || !audioAsrEnabled}
onClick={() =>
void persist({
...config,
@@ -266,6 +289,8 @@ export const SettingsMessagingPage: React.FC = () => {
...audioAsr,
echo_transcript: !audioEchoEnabled,
},
+ }, {
+ audio_asr: { echo_transcript: !audioEchoEnabled },
})
}
/>
@@ -289,7 +314,10 @@ export const SettingsMessagingPage: React.FC = () => {
<ToggleSwitch
enabled={includeTimeInfoEnabled}
onClick={() =>
- void persist({ ...config, include_time_info: !includeTimeInfoEnabled })
+ void persist(
+ { ...config, include_time_info: !includeTimeInfoEnabled },
+ { include_time_info: !includeTimeInfoEnabled },
+ )
}
/>
}
@@ -302,7 +330,10 @@ export const SettingsMessagingPage: React.FC = () => {
<ToggleSwitch
enabled={Boolean(config.include_user_info)}
onClick={() =>
- void persist({ ...config, include_user_info: !config.include_user_info })
+ void persist(
+ { ...config, include_user_info: !config.include_user_info },
+ { include_user_info: !config.include_user_info },
+ )
}
/>
}
@@ -325,7 +356,10 @@ export const SettingsMessagingPage: React.FC = () => {
<CompactSelect
value={config.ack_mode || 'typing'}
onChange={(event) =>
- void persist({ ...config, ack_mode: event.target.value || 'typing' })
+ void persist(
+ { ...config, ack_mode: event.target.value || 'typing' },
+ { ack_mode: event.target.value || 'typing' },
+ )
}
className="w-40"
>
@@ -345,10 +379,13 @@ export const SettingsMessagingPage: React.FC = () => {
<CompactSelect
value={config.agent_progress_style || 'off'}
onChange={(event) =>
- void persist({
- ...config,
- agent_progress_style: event.target.value || 'off',
- })
+ void persist(
+ {
+ ...config,
+ agent_progress_style: event.target.value || 'off',
+ },
+ { agent_progress_style: event.target.value || 'off' },
+ )
}
className="w-40"
>
@@ -430,7 +467,10 @@ export const SettingsMessagingPage: React.FC = () => {
control={
<ToggleSwitch
enabled={config.show_duration !== false}
- onClick={() => void persist({ ...config, show_duration: !config.show_duration })}
+ onClick={() => void persist(
+ { ...config, show_duration: !config.show_duration },
+ { show_duration: !config.show_duration },
+ )}
/>
}
/>
@@ -452,7 +492,10 @@ export const SettingsMessagingPage: React.FC = () => {
<ToggleSwitch
enabled={config.reply_enhancements !== false}
onClick={() =>
- void persist({ ...config, reply_enhancements: !config.reply_enhancements })
+ void persist(
+ { ...config, reply_enhancements: !config.reply_enhancements },
+ { reply_enhancements: !config.reply_enhancements },
+ )
}
/>
}
@@ -474,22 +517,26 @@ export const SettingsMessagingPage: React.FC = () => {
}
/>
)}
- {slackSupportsLinkUnfurl && (
+ {/* ``slack.*`` is outside the Editor write allowlist, so this control
+ is only offered to roles that may manage the instance — a remote
+ Owner included, which is why it carries its own field patch. */}
+ {canManageInstance && slackSupportsLinkUnfurl && (
<SettingsRow
title={t('dashboard.slackLinkPreviews')}
description={t('dashboard.slackLinkPreviewsHint')}
control={
<ToggleSwitch
enabled={Boolean(config.slack?.disable_link_unfurl)}
- onClick={() =>
- void persist({
- ...config,
- slack: {
- ...(config.slack || {}),
- disable_link_unfurl: !config.slack?.disable_link_unfurl,
+ onClick={() => {
+ const next = !config.slack?.disable_link_unfurl;
+ void persist(
+ {
+ ...config,
+ slack: { ...(config.slack || {}), disable_link_unfurl: next },
},
- })
- }
+ { slack: { disable_link_unfurl: next } },
+ );
+ }}
/>
}
/>
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 3c41962c3..f5a71131b 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1560,6 +1560,8 @@
"remote_access_public_url_invalid": "Remote access is misconfigured (the public URL is invalid). Re-pair this device or fix the remote-access settings.",
"remote_access_session_secret_missing": "Remote access is misconfigured (missing session secret). Re-pair this device to restore access.",
"remote_access_unknown": "The operation did not finish. Refresh the status and try again; if it still fails, check the remote access runtime logs.",
+ "editor_config_write_forbidden": "Only messaging preferences can be saved from this role.",
+ "editor_config_write_invalid": "That messaging setting could not be saved.",
"show_page_email_access_transient": "Email access is temporarily unavailable. Try again.",
"invalid_pairing_key": "This pairing key is invalid or expired. Create a new key at avibe.bot, then paste it here.",
"missing_pairing_key": "Paste the pairing key first.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index e2931d406..547e3f23c 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1560,6 +1560,8 @@
"remote_access_public_url_invalid": "远程访问配置有误(公网地址无效)。请重新配对此设备或修正远程访问设置。",
"remote_access_session_secret_missing": "远程访问配置有误(缺少会话密钥)。请重新配对此设备以恢复访问。",
"remote_access_unknown": "操作没有完成。请刷新状态后再试一次;如果仍然失败,请查看远程访问运行日志。",
+ "editor_config_write_forbidden": "当前角色只能保存消息偏好。",
+ "editor_config_write_invalid": "这条消息设置无法保存。",
"show_page_email_access_transient": "邮箱权限暂时不可用,请重试。",
"invalid_pairing_key": "这个 pairing key 无效或已过期。请回到 avibe.bot 重新生成一个 key,然后粘贴到这里。",
"missing_pairing_key": "请先粘贴 pairing key。",
diff --git a/vibe/api.py b/vibe/api.py
index 627587557..50804e6f8 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1076,7 +1076,15 @@ def save_memory_config(
def _vibe_cloud_payload(config: V2Config, include_secrets: bool) -> dict:
- payload = config.remote_access.vibe_cloud.__dict__.copy()
+ vibe_cloud = config.remote_access.vibe_cloud
+ payload = vibe_cloud.__dict__.copy()
+ # Derived, never stored: whether cloud-backed features can actually run.
+ # Clients must not re-derive it from whichever identifiers survived
+ # redaction — the secret the runtime needs is stripped from every
+ # non-wizard response, so ``enabled`` plus ``instance_id`` reads as paired
+ # on an instance the runtime refuses to serve. ``from_payload`` filters
+ # unknown keys, so this cannot round-trip into the stored config.
+ payload["paired"] = vibe_cloud.is_runtime_paired()
if not include_secrets:
for key in ("tunnel_token", "instance_secret", "session_secret"):
payload.pop(key, None)
@@ -1294,6 +1302,146 @@ _NON_OWNER_CONFIG_UI_FIELDS = (
)
+_NON_OWNER_AUDIO_ASR_FIELDS = (
+ "enabled",
+ "echo_transcript",
+ "enabled_configured",
+)
+
+_EDITOR_CONFIG_WRITE_FIELDS = frozenset(
+ {
+ "ack_mode",
+ "show_duration",
+ "include_time_info",
+ "include_user_info",
+ "reply_enhancements",
+ "agent_progress_style",
+ "audio_asr",
+ "ui",
+ }
+)
+
+_EDITOR_CONFIG_UI_WRITE_FIELDS = frozenset(
+ {
+ "chat_message_font_size",
+ "show_agent_activity",
+ "show_tool_calls",
+ }
+)
+_EDITOR_AUDIO_ASR_WRITE_FIELDS = frozenset(_NON_OWNER_AUDIO_ASR_FIELDS)
+
+# Read-only context the shared Settings pages need in order to render the
+# writable fields above the way an Owner sees them: platform capabilities
+# decide which acknowledgement modes are offered, and cloud pairing decides
+# whether the transcription control is live. Without them a non-owner client
+# falls back to guesses (``getEnabledPlatforms`` assumes Slack) and offers
+# settings the instance does not support.
+#
+# Together with ``_EDITOR_CONFIG_WRITE_FIELDS`` this is the complete set of
+# keys a non-owner may see; ``test_non_owner_config_projects_exactly_the_declared_surface``
+# holds the projection to it, so a field added to either half fails a test
+# rather than leaking or going missing.
+_NON_OWNER_CONFIG_CONTEXT_FIELDS = frozenset(
+ {
+ "mode",
+ "version",
+ "setup_state",
+ "language",
+ "platforms",
+ "platform_catalog",
+ "remote_access",
+ }
+)
+
+_EDITOR_CONFIG_WRITE_ERROR_CODES = frozenset(
+ {
+ "editor_config_write_forbidden",
+ "editor_config_write_invalid",
+ }
+)
+
+
+def _remote_access_pairing_projection(payload: dict) -> dict:
+ """Project cloud pairing for a non-owner as the readiness boolean alone.
+
+ Below the Owner role no pairing identifier or endpoint is exposed at all —
+ only whether cloud-backed controls can work, which ``_vibe_cloud_payload``
+ already decided from the stored config.
+ """
+ remote_access = payload.get("remote_access")
+ vibe_cloud = remote_access.get("vibe_cloud") if isinstance(remote_access, dict) else None
+ paired = bool(vibe_cloud.get("paired")) if isinstance(vibe_cloud, dict) else False
+ return {"vibe_cloud": {"paired": paired}}
+
+
+def _audio_asr_preference_projection(payload: dict) -> dict:
+ audio_asr = payload.get("audio_asr")
+ if not isinstance(audio_asr, dict):
+ return {}
+ return {
+ key: audio_asr[key]
+ for key in _NON_OWNER_AUDIO_ASR_FIELDS
+ if key in audio_asr
+ }
+
+
+def editor_config_write_payload(payload: dict) -> dict:
+ """Keep only the messaging preferences an Editor may persist."""
+
+ if not isinstance(payload, dict):
+ raise ValueError("editor_config_write_invalid")
+ unknown = set(payload) - _EDITOR_CONFIG_WRITE_FIELDS
+ if unknown:
+ raise ValueError("editor_config_write_forbidden")
+
+ projected: dict = {}
+ for key in payload:
+ if key == "audio_asr":
+ audio_asr = payload.get("audio_asr")
+ if not isinstance(audio_asr, dict):
+ raise ValueError("editor_config_write_invalid")
+ extra = set(audio_asr) - _EDITOR_AUDIO_ASR_WRITE_FIELDS
+ if extra:
+ raise ValueError("editor_config_write_forbidden")
+ projected["audio_asr"] = {
+ field: audio_asr[field]
+ for field in _EDITOR_AUDIO_ASR_WRITE_FIELDS
+ if field in audio_asr
+ }
+ continue
+ if key == "ui":
+ ui_payload = payload.get("ui")
+ if not isinstance(ui_payload, dict):
+ raise ValueError("editor_config_write_invalid")
+ extra = set(ui_payload) - _EDITOR_CONFIG_UI_WRITE_FIELDS
+ if extra:
+ raise ValueError("editor_config_write_forbidden")
+ projected["ui"] = {
+ field: ui_payload[field]
+ for field in _EDITOR_CONFIG_UI_WRITE_FIELDS
+ if field in ui_payload
+ }
+ continue
+ projected[key] = payload[key]
+ return projected
+
+
+def editor_config_write_error_code(exc: Exception) -> str:
+ """Return the stable client code for any failure on an Editor config write.
+
+ Stated as a property rather than as a list of recognised messages: every
+ validation failure reached while applying an Editor write is an Editor
+ write error, whichever layer raised it. Only the codes this module raises
+ survive; anything else — including value validation raised much later by
+ ``V2Config.from_payload`` — collapses to the generic invalid code, so a
+ non-English client never renders a raw English sentence.
+ """
+ message = str(exc)
+ if message in _EDITOR_CONFIG_WRITE_ERROR_CODES:
+ return message
+ return "editor_config_write_invalid"
+
+
def non_owner_config_payload(config: V2Config) -> dict:
"""Return the configuration projection available below the Owner role.
@@ -1301,6 +1449,13 @@ def non_owner_config_payload(config: V2Config) -> dict:
runtime and control-plane fields out of Viewer and Editor responses while
leaving ordinary messaging and UI preferences available to both local and
remote callers.
+
+ Its key set is exactly ``_EDITOR_CONFIG_WRITE_FIELDS`` (what an Editor may
+ change) plus ``_NON_OWNER_CONFIG_CONTEXT_FIELDS`` (the read-only context
+ needed to render those controls correctly). Keeping the two halves in step
+ is the invariant: a writable field that is not projected leaves the client
+ guessing, and an unprojected context field makes the shared Settings pages
+ fall back to defaults that do not match the instance.
"""
payload = client_config_payload(config)
@@ -1316,6 +1471,10 @@ def non_owner_config_payload(config: V2Config) -> dict:
"include_user_info": payload.get("include_user_info"),
"reply_enhancements": payload.get("reply_enhancements"),
"agent_progress_style": payload.get("agent_progress_style"),
+ "audio_asr": _audio_asr_preference_projection(payload),
+ "remote_access": _remote_access_pairing_projection(payload),
+ "platforms": payload.get("platforms"),
+ "platform_catalog": payload.get("platform_catalog"),
"ui": {
key: ui_payload[key]
for key in _NON_OWNER_CONFIG_UI_FIELDS
diff --git a/vibe/authorization.py b/vibe/authorization.py
index 554a7b757..c8b8066ff 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -401,6 +401,7 @@ _EDITOR_HTTP_RULES = tuple(
("PUT", r"^/api/sessions/[^/]+/draft$"),
("POST", r"^/api/asr/transcribe$"),
("POST", r"^/api/asr/telemetry$"),
+ ("POST", r"^/api/config$"),
("POST", r"^/api/show/sessions/[^/]+/events$"),
("POST", r"^/api/show/sessions/[^/]+/prewarm$"),
("POST", r"^/api/show-pages/[^/]+/icon$"),
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 7ce268e7a..e280f6225 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -5871,7 +5871,23 @@ async def config_post():
from vibe import internal_client
from vibe import remote_access
- payload = request.json or {}
+ # The decoded body, not the usual ``request.json or {}``: this route's two
+ # validators already require a JSON object — ``editor_config_write_payload``
+ # for an Editor, ``api.save_config`` for everyone — and that coercion turns
+ # every falsy body (``null``, ``[]``, ``false``, ``0``, ``""``, or none at
+ # all) into an empty patch before either of them sees it, so a malformed
+ # write saved nothing and answered 200. Passing the value through keeps one
+ # property — a config write is an object — instead of an enumeration of the
+ # falsy shapes that happen to exist today.
+ payload = request.json
+ authorization_context = getattr(g, "authorization_context", None)
+ editor_write = authorization_context is not None and not authorization_context.can_manage_instance
+ if editor_write:
+ try:
+ payload = api.editor_config_write_payload(payload)
+ except ValueError as exc:
+ code = api.editor_config_write_error_code(exc)
+ return jsonify({"ok": False, "error": {"code": code, "message": code}}), 400
remote_access_runtime = None
try:
(
@@ -5884,6 +5900,13 @@ async def config_post():
payload,
)
except ValueError as exc:
+ # Same chokepoint as the allowlist rejection above: an Editor write
+ # answers with a stable code whichever layer refused it, including
+ # value validation raised deep inside ``V2Config.from_payload``. Owner
+ # saves keep the descriptive message the Settings pages already show.
+ if editor_write:
+ code = api.editor_config_write_error_code(exc)
+ return jsonify({"ok": False, "error": {"code": code, "message": code}}), 400
message = str(exc)
return jsonify({"ok": False, "error": message, "message": message}), 400
if should_reconcile_remote_access: