Coverage for custom_components/ha_repl_server/config_flow.py: 100%

60 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-17 19:05 +0000

1"""Config flow for Home Assistant REPL: a single entry, added from the UI 

2(gated behind explicit risk acknowledgment - see _ACK_FIELDS below, the same 

3"are you sure you know what you're doing" pattern Marketplace's own config flow 

4uses) or imported from YAML (`ha_repl_server:` in configuration.yaml, left 

5as a no-form, always-on path for backward compatibility with existing 

6installs that predate this gate). 

7 

8What's exposed (`expose_hass`/`expose_sql`) is deliberately not on that 

9initial form: it's an ongoing setting, not a one-time risk acknowledgment, 

10so it lives in the entry's *options* - editable any time from Settings > 

11Devices & services > Home Assistant REPL > Configure - rather than data 

12fixed at creation. 

13 

14Either can be given a time limit there, in minutes, after which it is 

15switched off again (see __init__.py's _expire). The entry keeps the time 

16that falls at, as `expose_<name>_until`, not the minutes, so the limit 

17survives a restart. With no limit entered, it stays on. 

18""" 

19 

20from __future__ import annotations 

21 

22import math 

23from datetime import datetime, timedelta 

24from typing import Any, cast 

25 

26import voluptuous as vol 

27from homeassistant.config_entries import ( 

28 ConfigEntry, 

29 ConfigFlow, 

30 ConfigFlowResult, 

31 OptionsFlowWithReload, 

32) 

33from homeassistant.data_entry_flow import section 

34from homeassistant.util import dt as dt_util 

35 

36from .const import ( 

37 CAPABILITIES, 

38 DEFAULT_COMPLETE_BUDGET_MS, 

39 DEFAULT_COMPLETE_LIMIT, 

40 DOMAIN, 

41) 

42 

43TITLE = "Home Assistant REPL Live Server" 

44 

45# Both default on - matches the always-on behaviour of every version before 

46# this option existed, so an entry that predates it (or was never 

47# reconfigured) keeps working the same way. 

48_DEFAULT_OPTIONS = {"expose_hass": True, "expose_sql": True} 

49 

50# Every one of these must be truthy in user_input before the entry is 

51# created (see async_step_user) - each is its own field (rather than one 

52# "I agree" checkbox) so the form, and this module's own code, name the 

53# specific thing being acknowledged. 

54_ACK_FIELDS = ( 

55 "ack_stability", 

56 "ack_sql_not_guaranteed", 

57 "ack_secrets", 

58 "ack_token", 

59) 

60 

61_ACK_SCHEMA = vol.Schema({ 

62 vol.Required(field, default=False): bool for field in _ACK_FIELDS 

63}) 

64 

65 

66class HaReplServerConfigFlow(ConfigFlow, domain=DOMAIN): 

67 VERSION = 1 

68 

69 @staticmethod 

70 def async_get_options_flow(config_entry: ConfigEntry) -> HaReplServerOptionsFlow: 

71 return HaReplServerOptionsFlow() 

72 

73 async def async_step_user( 

74 self, user_input: dict[str, Any] | None = None 

75 ) -> ConfigFlowResult: 

76 errors: dict[str, str] = {} 

77 if user_input is not None: 

78 if all(user_input.get(field) for field in _ACK_FIELDS): 

79 return self.async_create_entry( 

80 title=TITLE, data={}, options=_DEFAULT_OPTIONS 

81 ) 

82 errors["base"] = "ack_required" 

83 return self.async_show_form( 

84 step_id="user", 

85 data_schema=_ACK_SCHEMA, # type: ignore[arg-type] #ty: ignore[invalid-argument-type] 

86 errors=errors, 

87 ) 

88 

89 async def async_step_import(self, import_data: dict[str, Any]) -> ConfigFlowResult: 

90 return self.async_create_entry(title=TITLE, data={}, options=_DEFAULT_OPTIONS) 

91 

92 

93def _minutes_left(options: Any, name: str, now: datetime) -> int | None: 

94 """Whole minutes, rounded up, until `expose_<name>` is switched off - 

95 None if it has no time limit, or is past it.""" 

96 until = dt_util.parse_datetime(options.get(f"expose_{name}_until") or "") 

97 if until is None or until <= now: 

98 return None 

99 return math.ceil((until - now) / timedelta(minutes=1)) 

100 

101 

102# Completion's limits: how many items one answer has at most, and how long 

103# it's given to find them. 

104_COMPLETE_FIELDS = { 

105 "complete_limit": (DEFAULT_COMPLETE_LIMIT, 10, 10_000), 

106 "complete_budget_ms": (DEFAULT_COMPLETE_BUDGET_MS, 50, 10_000), 

107} 

108 

109 

110class HaReplServerOptionsFlow(OptionsFlowWithReload): 

111 """`expose_hass`/`expose_sql`, a time limit for each, and completion's 

112 limits - editable 

113 after setup; changing any reloads the entry automatically 

114 (OptionsFlowWithReload's own job) so async_setup_entry re-reads them 

115 immediately, no manual listener needed. 

116 """ 

117 

118 async def async_step_init( 

119 self, user_input: dict[str, Any] | None = None 

120 ) -> ConfigFlowResult: 

121 options = self.config_entry.options 

122 now = dt_util.utcnow() 

123 if user_input is not None: 

124 data: dict[str, Any] = {} 

125 for name in CAPABILITIES: 

126 data[f"expose_{name}"] = user_input[f"expose_{name}"] 

127 minutes = user_input.get(f"expose_{name}_minutes") 

128 if not data[f"expose_{name}"] or minutes is None: 

129 continue # off, or on with no limit: nothing to run out 

130 if minutes == _minutes_left(options, name, now): 

131 # the limit already running, as the form showed it 

132 data[f"expose_{name}_until"] = options[f"expose_{name}_until"] 

133 else: 

134 until = now + timedelta(minutes=minutes) 

135 data[f"expose_{name}_until"] = until.isoformat() 

136 limits = user_input.get("limits", {}) 

137 for field, (default, _, _) in _COMPLETE_FIELDS.items(): 

138 data[field] = limits.get(field, options.get(field, default)) 

139 return self.async_create_entry(title="", data=data) 

140 fields: dict[Any, Any] = {} 

141 for name in CAPABILITIES: 

142 exposed = options.get(f"expose_{name}", True) 

143 fields[vol.Required(f"expose_{name}", default=exposed)] = bool 

144 # A suggested value, not a default: clearing the field has to 

145 # be a way of saying "no limit". 

146 left = _minutes_left(options, name, now) if exposed else None 

147 fields[ 

148 vol.Optional( 

149 f"expose_{name}_minutes", description={"suggested_value": left} 

150 ) 

151 ] = vol.All(vol.Coerce(int), vol.Range(min=1)) 

152 # In a section of their own, folded away: rarely changed. Defaulting 

153 # to {} fills in each limit's own default when it's left out. The 

154 # cast as websocket_api.py's: section() is typed for probatio. 

155 fields[vol.Required("limits", default={})] = section( 

156 cast(Any, vol.Schema)({ 

157 vol.Required(field, default=options.get(field, default)): vol.All( 

158 vol.Coerce(int), vol.Range(min=low, max=high) 

159 ) 

160 for field, (default, low, high) in _COMPLETE_FIELDS.items() 

161 }), 

162 {"collapsed": True}, 

163 ) 

164 return self.async_show_form(step_id="init", data_schema=vol.Schema(fields)) # type: ignore[arg-type] # ty: ignore[invalid-argument-type]