// The state of the UI and its rules. `step` is pure: it gives the next model and the
// effects. `update` makes a Rabbita command of each effect.

///|
/// The path of a new project.
#derive(Eq, Debug)
pub(all) enum AddState {
  /// The user types it.
  Typing
  /// The server refused it, or the folder dialog did not open. The text is for the user.
  Refused(String)
  /// The folder dialog of the system is open. Only a desktop window has one.
  Browsing
  /// The server has it and did not answer.
  Sending
}

///|
pub extend AddState with Eq::{equal, not_equal}

///|
pub extend AddState with @debug.Debug::{to_repr}

///|
/// The dialog that is open. Two dialogs are never open at the same time.
#derive(Eq, Debug)
pub(all) enum Dialog {
  NoDialog
  /// The field for the path of a new project. `path` is the text of the user, and
  /// only the server knows its rules.
  AddDialog(path~ : String, state~ : AddState)
  /// The question before Mission Control stops.
  ConfirmStop
  /// The command palette, with the text of the user and the selected action. `step`
  /// keeps the selection in the results. Without a result it is `None`.
  Palette(query~ : String, selected~ : ActionId?)
}

///|
pub extend Dialog with Eq::{equal, not_equal}

///|
pub extend Dialog with @debug.Debug::{to_repr}

///|
/// The dialog that adds a project, with an empty field.
pub fn Dialog::add() -> Dialog {
  AddDialog(path="", state=Typing)
}

///|
/// An element of the page that shows a dialog.
#derive(Eq, Debug)
pub(all) enum DialogElement {
  AddElement
  StopElement
  PaletteElement
}

///|
pub extend DialogElement with Eq::{equal, not_equal}

///|
pub extend DialogElement with @debug.Debug::{to_repr}

///|
/// The ID of the element.
fn DialogElement::id(self : DialogElement) -> String {
  match self {
    AddElement => "add-project-dialog"
    StopElement => "stop-dialog"
    PaletteElement => "palette"
  }
}

///|
/// The ID of the field for the path in the dialog that adds a project.
let add_path_id : String = "add-path"

///|
/// The ID of the title of the main area. Each state of the view has one.
let main_title_id : String = "main-title"

///|
/// The element that shows the dialog.
fn Dialog::element(self : Dialog) -> DialogElement? {
  match self {
    NoDialog => None
    AddDialog(..) => Some(AddElement)
    ConfirmStop => Some(StopElement)
    Palette(..) => Some(PaletteElement)
  }
}

///|
/// The state of the primary sidebar, which is at the left of a wide window.
#derive(Eq, Debug)
pub(all) enum PrimarySidebar {
  Shown
  Hidden
}

///|
pub extend PrimarySidebar with Eq::{equal, not_equal}

///|
pub extend PrimarySidebar with @debug.Debug::{to_repr}

///|
/// The state from the text that the browser kept. Each text that the UI does not write
/// gives `Shown`, also the empty one of a browser that kept nothing.
fn PrimarySidebar::of_stored(text : String) -> PrimarySidebar {
  match text {
    "hidden" => Hidden
    _ => Shown
  }
}

///|
/// The text that the browser keeps.
fn PrimarySidebar::stored(self : PrimarySidebar) -> String {
  match self {
    Shown => "shown"
    Hidden => "hidden"
  }
}

///|
fn PrimarySidebar::other(self : PrimarySidebar) -> PrimarySidebar {
  match self {
    Shown => Hidden
    Hidden => Shown
  }
}

///|
/// The ID of the control that the user sees in this state. It gives the other state.
fn PrimarySidebar::control_id(self : PrimarySidebar) -> String {
  match self {
    Shown => "hide-primary-sidebar"
    Hidden => "show-primary-sidebar"
  }
}

///|
/// The key of the state in the storage of the browser.
let primary_sidebar_key : String = "mission-control-primary-sidebar"

///|
/// The size of the window. A small one has no space for the primary sidebar, and shows
/// the same content in a sheet.
#derive(Eq, Debug)
pub(all) enum WindowSize {
  Wide
  Small
}

///|
pub extend WindowSize with Eq::{equal, not_equal}

///|
pub extend WindowSize with @debug.Debug::{to_repr}

///|
/// Live workspace loading state for one project.
#derive(Eq, Debug)
pub(all) enum WorkspaceLoad {
  Loading
  Ready(@app.ProjectWorkspaces)
  Failed(String)
}

///|
pub extend WorkspaceLoad with Eq::{equal, not_equal}

///|
pub extend WorkspaceLoad with @debug.Debug::{to_repr}

///|
/// Live composed workspace sources loading state for one workspace.
#derive(Eq, Debug)
pub(all) enum SourcesLoad {
  Idle
  Loading
  Ready(@app.WorkspaceSources)
  Failed(String)
}

///|
pub extend SourcesLoad with Eq::{equal, not_equal}

///|
pub extend SourcesLoad with @debug.Debug::{to_repr}

///|
/// Live canonical OpenSpec intent loading state for one workspace.
#derive(Eq, Debug)
pub(all) enum IntentLoad {
  Idle
  Loading
  Ready(@app.WorkspaceIntent)
  Failed(String)
}

///|
pub extend IntentLoad with Eq::{equal, not_equal}

///|
pub extend IntentLoad with @debug.Debug::{to_repr}

///|
/// Live RDF/SKOS Data Dictionary loading state for one workspace.
#derive(Eq, Debug)
pub(all) enum DictionaryLoad {
  Idle
  Loading
  Ready(@app.WorkspaceDictionary)
  Failed(String)
}

///|
pub extend DictionaryLoad with Eq::{equal, not_equal}

///|
pub extend DictionaryLoad with @debug.Debug::{to_repr}

///|
/// Live DocumentScorer and Rego SDLC gate evaluation state for one workspace.
#derive(Eq, Debug)
pub(all) enum SdlcLoad {
  Idle
  Loading
  Ready(@app.WorkspaceSdlc)
  Failed(String)
}

///|
pub extend SdlcLoad with Eq::{equal, not_equal}

///|
pub extend SdlcLoad with @debug.Debug::{to_repr}

///|
/// The typed location parsed from the URL hash fragment.
#derive(Eq, Debug)
pub(all) enum Route {
  NoRoute
  ProjectRoute(@app.ProjectId)
  WorkspaceRoute(@app.ProjectId, @app.WorkspaceId)
}

///|
pub extend Route with Eq::{equal, not_equal}

///|
pub extend Route with @debug.Debug::{to_repr}

///|
/// The project ID of a route, if any.
pub fn Route::project(self : Route) -> @app.ProjectId? {
  match self {
    NoRoute => None
    ProjectRoute(id) | WorkspaceRoute(id, _) => Some(id)
  }
}

///|
/// The workspace ID of a route, if any.
pub fn Route::workspace(self : Route) -> @app.WorkspaceId? {
  match self {
    WorkspaceRoute(_, id) => Some(id)
    NoRoute | ProjectRoute(_) => None
  }
}

///|
/// The state of one view.
#derive(Eq, Debug)
pub struct Model {
  connection : ConnectionState
  surface : @app.Surface
  /// The instance whose server gave the page.
  instance : @app.InstanceName
  /// What the server tells about itself, after the first connection.
  info : @app.AppInfo?
  /// The list of the server, or `None` before the first one. It stays while the
  /// connection is lost.
  projects : ReadOnlyArray[@app.Project]?
  /// The active route (home, project, or project + workspace).
  /// The list can be without the project: see `Model::open_project`.
  route : Route
  /// Live workspace loading state per project ID.
  workspaces : ReadOnlyArray[(@app.ProjectId, WorkspaceLoad)]
  /// Live composed source loading state per workspace ID.
  sources : ReadOnlyArray[(@app.WorkspaceId, SourcesLoad)]
  /// Live canonical intent loading state per workspace ID.
  intents : ReadOnlyArray[(@app.WorkspaceId, IntentLoad)]
  /// Currently focused live intent item ID (when live OpenSpec items are loaded).
  selected_live_intent : String?
  /// Currently selected 0-based document index inside the focused live reading packet.
  selected_live_doc : Int32
  /// Live RDF/SKOS Data Dictionary loading state per workspace ID.
  dictionaries : ReadOnlyArray[(@app.WorkspaceId, DictionaryLoad)]
  /// Currently selected live dictionary concept IRI.
  selected_live_concept : String?
  /// Active live dictionary named graph ID filter (`None` = All graphs).
  selected_live_dict_graph : String?
  /// Live DocumentScorer & Rego SDLC gate evaluation per workspace ID.
  sdlc : ReadOnlyArray[(@app.WorkspaceId, SdlcLoad)]
  /// Multi-workspace projects whose nested workspace list is collapsed in the sidebar.
  collapsed_projects : ReadOnlyArray[@app.ProjectId]
  dialog : Dialog
  /// The choice of the user for a wide window. It stays while the window is small.
  primary_sidebar : PrimarySidebar
  /// Resized width of the desktop primary sidebar in pixels.
  sidebar_width : SidebarWidth
  /// Open/collapsed state of the secondary left sidebar in Review and Knowledge.
  secondary_sidebar : SecondarySidebar
  /// Resized width of the secondary left sidebar in pixels.
  secondary_sidebar_width : SecondarySidebarWidth
  /// Open/collapsed state of the right companion panel in Review and Knowledge.
  companion_panel : CompanionPanel
  window : WindowSize
  /// A failure that has no other place, as text for the user.
  notice : String?
  /// Active activity perspective over the open project.
  perspective : Perspective
  /// Active view inside the Plan perspective.
  plan_view : PlanView
  /// Active document reading mode inside the Review perspective.
  read_mode : ReadMode
  /// Active document ID inside the Review reading packet.
  review_doc : ReviewDocId
  /// Active view inside the Knowledge perspective (`Dictionary` or `KnowledgeBase`).
  knowledge_view : KnowledgeView
  /// Active named graph filter in Data Dictionary.
  dict_graph : NamedGraphFilter
  /// Active serialization display format in Data Dictionary.
  dict_format : DictFormat
  /// Search query in Data Dictionary.
  dict_query : String
  /// Draft label for adding a local SKOS concept.
  dict_draft_label : String
  /// Draft definition for adding a local SKOS concept.
  dict_draft_def : String
  /// Validation message for the local concept form, if any.
  dict_draft_error : String?
  /// Active source filter in Knowledge Base.
  kb_source : KbSourceFilter
  /// Search query in Knowledge Base.
  kb_query : String
  /// Selected document in Knowledge Base.
  kb_doc : KbDocId
  /// Reading mode in Knowledge Base (`KbPreview` or `KbSource`).
  kb_read_mode : KbReadMode
  /// Persisted color scheme.
  color_scheme : ColorScheme
  /// Persisted light/dark/system appearance override.
  appearance : Appearance
  /// Persisted configurable brand mark and display title.
  brand : BrandConfig
  /// Validation feedback from custom brand inputs or uploads.
  brand_error : String?
  /// Full-page Settings overlay state.
  settings : SettingsSurface
  /// Immutable Back/Forward shell navigation history.
  history : NavHistory
  /// Isolated local preview state per project ID.
  mockups : ReadOnlyArray[(@app.ProjectId, MockupWorkspace)]
}

///|
pub extend Model with Eq::{equal, not_equal}

///|
pub extend Model with @debug.Debug::{to_repr}

///|
/// The state of a view before its first connection.
pub fn Model::Model(
  surface~ : @app.Surface,
  instance~ : @app.InstanceName,
  primary_sidebar~ : PrimarySidebar,
  sidebar_width~ : SidebarWidth = SidebarWidth::default(),
  secondary_sidebar~ : SecondarySidebar = SecondaryShown,
  secondary_sidebar_width~ : SecondarySidebarWidth = SecondarySidebarWidth::default(),
  companion_panel~ : CompanionPanel = CompanionShown,
  window~ : WindowSize,
  color_scheme~ : ColorScheme = Moonrockz,
  appearance~ : Appearance = System,
  brand~ : BrandConfig = BrandConfig::default(),
) -> Model {
  let initial_target = NavTarget(
    route=NoRoute,
    perspective=Plan,
    plan_view=Board,
    review_doc=Spec,
  )
  {
    connection: Connecting,
    surface,
    instance,
    info: None,
    projects: None,
    route: NoRoute,
    workspaces: [],
    sources: [],
    intents: [],
    selected_live_intent: None,
    selected_live_doc: 0,
    dictionaries: [],
    selected_live_concept: None,
    selected_live_dict_graph: None,
    sdlc: [],
    collapsed_projects: [],
    dialog: NoDialog,
    primary_sidebar,
    sidebar_width,
    secondary_sidebar,
    secondary_sidebar_width,
    companion_panel,
    window,
    notice: None,
    perspective: Plan,
    plan_view: Board,
    read_mode: Structured,
    review_doc: Spec,
    knowledge_view: Dictionary,
    dict_graph: AllGraphs,
    dict_format: DictStructured,
    dict_query: "",
    dict_draft_label: "",
    dict_draft_def: "",
    dict_draft_error: None,
    kb_source: AllKbSources,
    kb_query: "",
    kb_doc: KbPciRunbook,
    kb_read_mode: KbPreview,
    color_scheme,
    appearance,
    brand,
    brand_error: None,
    settings: Closed,
    history: NavHistory(initial_target),
    mockups: [],
  }
}

///|
/// The project ID in the current route, if any.
pub fn Model::open_id(self : Model) -> @app.ProjectId? {
  self.route.project()
}

///|
/// The active workspace ID in the current route, if any.
pub fn Model::active_workspace_id(self : Model) -> @app.WorkspaceId? {
  self.route.workspace()
}

///|
/// The current shell location captured as a `NavTarget`.
fn Model::nav_target(self : Model) -> NavTarget {
  NavTarget(
    route=self.route,
    perspective=self.perspective,
    plan_view=self.plan_view,
    review_doc=self.review_doc,
    knowledge_view=self.knowledge_view,
  )
}

///|
/// Returns true when the project's nested workspace tree is collapsed in the sidebar.
pub fn Model::is_project_collapsed(self : Model, id : @app.ProjectId) -> Bool {
  self.collapsed_projects.contains(id)
}

///|
/// Returns a new model with the project's sidebar collapse state flipped.
fn Model::toggle_project_collapsed(self : Model, id : @app.ProjectId) -> Model {
  let next : Array[@app.ProjectId] = []
  let mut removed = false
  for item in self.collapsed_projects {
    if item == id {
      removed = true
    } else {
      next.push(item)
    }
  }
  if !removed {
    next.push(id)
  }
  { ..self, collapsed_projects: ReadOnlyArray::from_array(next), }
}

///|
/// Returns true when the given project is currently open and has more than one
/// loaded workspace.
fn Model::is_open_multi_workspace(self : Model, id : @app.ProjectId) -> Bool {
  self.open_id() == Some(id) &&
  self.workspace_load(id) is Some(Ready(Populated(set))) &&
  set.length() > 1
}

///|
/// Returns the live workspace loading state for a project, if loaded or loading.
pub fn Model::workspace_load(
  self : Model,
  id : @app.ProjectId,
) -> WorkspaceLoad? {
  match self.workspaces.iter().find_first(pair => pair.0 == id) {
    Some((_, load)) => Some(load)
    None => None
  }
}

///|
/// Returns the live workspace loading state for the open project, if any.
pub fn Model::open_workspaces(self : Model) -> WorkspaceLoad? {
  self.open_id().bind(id => self.workspace_load(id))
}

///|
/// Returns the active `@app.Workspace` of the open project when populated.
pub fn Model::active_workspace_value(self : Model) -> @app.Workspace? {
  match self.open_workspaces() {
    Some(Ready(Populated(set))) =>
      match self.active_workspace_id().bind(id => set.get(id)) {
        Some(ws) => Some(ws)
        None => Some(set.default_workspace())
      }
    _ => None
  }
}

///|
/// Reports whether perspective tabs should be shown and enabled for the open project.
/// Hidden when no project is open or when the open project has zero or unavailable
/// workspaces.
pub fn Model::has_perspectives(self : Model) -> Bool {
  guard self.open_project() is Some(_) else { return false }
  match self.open_workspaces() {
    Some(Ready(Empty)) | Some(Ready(Unavailable(..))) | Some(Failed(_)) => false
    None | Some(Loading) | Some(Ready(Populated(_))) => true
  }
}

///|
/// Updates or inserts the workspace loading state for one project purely.
fn Model::with_workspace_load(
  self : Model,
  id : @app.ProjectId,
  load : WorkspaceLoad,
) -> Model {
  let mut replaced = false
  let next : Array[(@app.ProjectId, WorkspaceLoad)] = []
  for pair in self.workspaces {
    if pair.0 == id {
      next.push((id, load))
      replaced = true
    } else {
      next.push(pair)
    }
  }
  if !replaced {
    next.push((id, load))
  }
  { ..self, workspaces: ReadOnlyArray::from_array(next), }
}

///|
/// Returns the live composed source loading state for one workspace ID.
pub fn Model::sources_load(self : Model, id : @app.WorkspaceId) -> SourcesLoad {
  match self.sources.iter().find_first(pair => pair.0 == id) {
    Some((_, load)) => load
    None => Idle
  }
}

///|
/// Returns the live composed source loading state for the active workspace, or
/// `Idle` when no populated workspace is active.
pub fn Model::active_sources_load(self : Model) -> SourcesLoad {
  match self.active_workspace_value() {
    Some(ws) => self.sources_load(ws.id)
    None => Idle
  }
}

///|
/// Updates or inserts the composed source loading state for one workspace purely.
fn Model::with_sources_load(
  self : Model,
  id : @app.WorkspaceId,
  load : SourcesLoad,
) -> Model {
  let mut replaced = false
  let next : Array[(@app.WorkspaceId, SourcesLoad)] = []
  for pair in self.sources {
    if pair.0 == id {
      next.push((id, load))
      replaced = true
    } else {
      next.push(pair)
    }
  }
  if !replaced {
    next.push((id, load))
  }
  { ..self, sources: ReadOnlyArray::from_array(next), }
}

///|
/// Returns the live canonical intent loading state for one workspace ID.
pub fn Model::intent_load(self : Model, id : @app.WorkspaceId) -> IntentLoad {
  match self.intents.iter().find_first(pair => pair.0 == id) {
    Some((_, load)) => load
    None => Idle
  }
}

///|
/// Returns the live canonical intent loading state for the active workspace.
pub fn Model::active_intent_load(self : Model) -> IntentLoad {
  match self.active_workspace_value() {
    Some(ws) => self.intent_load(ws.id)
    None => Idle
  }
}

///|
/// Returns the live `WorkspaceIntent` of the active workspace when it has at
/// least one real intent item.
pub fn Model::active_live_intent(self : Model) -> @app.WorkspaceIntent? {
  match self.active_intent_load() {
    Ready(intent) if !intent.items.is_empty() => Some(intent)
    _ => None
  }
}

///|
/// Returns the selected live `WireIntentItem`, falling back to the first item.
pub fn Model::selected_live_intent_item(
  self : Model,
  intent : @app.WorkspaceIntent,
) -> @app.WireIntentItem? {
  match self.selected_live_intent {
    Some(id) =>
      match intent.items.iter().find_first(item => item.id == id) {
        Some(found) => Some(found)
        None => intent.items.get(0)
      }
    None => intent.items.get(0)
  }
}

///|
/// Updates or inserts the canonical intent loading state for one workspace purely.
fn Model::with_intent_load(
  self : Model,
  id : @app.WorkspaceId,
  load : IntentLoad,
) -> Model {
  let mut replaced = false
  let next : Array[(@app.WorkspaceId, IntentLoad)] = []
  for pair in self.intents {
    if pair.0 == id {
      next.push((id, load))
      replaced = true
    } else {
      next.push(pair)
    }
  }
  if !replaced {
    next.push((id, load))
  }
  { ..self, intents: ReadOnlyArray::from_array(next), }
}

///|
/// Returns the live RDF Data Dictionary loading state for one workspace ID.
pub fn Model::dictionary_load(
  self : Model,
  id : @app.WorkspaceId,
) -> DictionaryLoad {
  match self.dictionaries.iter().find_first(pair => pair.0 == id) {
    Some((_, load)) => load
    None => Idle
  }
}

///|
/// Returns the live RDF Data Dictionary loading state for the active workspace.
pub fn Model::active_dictionary_load(self : Model) -> DictionaryLoad {
  match self.active_workspace_value() {
    Some(ws) => self.dictionary_load(ws.id)
    None => Idle
  }
}

///|
/// Returns the live `WorkspaceDictionary` of the active workspace when it has
/// at least one real graph or concept on disk.
pub fn Model::active_live_dictionary(self : Model) -> @app.WorkspaceDictionary? {
  match self.active_dictionary_load() {
    Ready(dict) if !dict.graphs.is_empty() || !dict.concepts.is_empty() =>
      Some(dict)
    _ => None
  }
}

///|
/// Updates or inserts the live RDF Data Dictionary loading state purely.
fn Model::with_dictionary_load(
  self : Model,
  id : @app.WorkspaceId,
  load : DictionaryLoad,
) -> Model {
  let mut replaced = false
  let next : Array[(@app.WorkspaceId, DictionaryLoad)] = []
  for pair in self.dictionaries {
    if pair.0 == id {
      next.push((id, load))
      replaced = true
    } else {
      next.push(pair)
    }
  }
  if !replaced {
    next.push((id, load))
  }
  { ..self, dictionaries: ReadOnlyArray::from_array(next), }
}

///|
/// Returns the live SDLC evaluation loading state for one workspace ID.
pub fn Model::sdlc_load(self : Model, id : @app.WorkspaceId) -> SdlcLoad {
  match self.sdlc.iter().find_first(pair => pair.0 == id) {
    Some((_, load)) => load
    None => Idle
  }
}

///|
/// Returns the live SDLC evaluation loading state for the active workspace.
pub fn Model::active_sdlc_load(self : Model) -> SdlcLoad {
  match self.active_workspace_value() {
    Some(ws) => self.sdlc_load(ws.id)
    None => Idle
  }
}

///|
/// Returns the live `WorkspaceSdlc` of the active workspace when loaded.
pub fn Model::active_live_sdlc(self : Model) -> @app.WorkspaceSdlc? {
  match self.active_sdlc_load() {
    Ready(eval) => Some(eval)
    _ => None
  }
}

///|
/// Builds a `PersistWorkspaceWorkflow` server call when connected with an active
/// populated workspace so Settings workflow changes save to `.mission-control/workflow.toml`.
fn Model::persist_workflow_effect(self : Model) -> Array[Effect] {
  guard self.connection is Connected else { return [] }
  match (self.open_id(), self.active_workspace_value()) {
    (Some(project_id), Some(active_ws)) => {
      let ws = self.active_mockup()
      [
        Call(
          PersistWorkspaceWorkflow({
            workspace: { project: project_id, workspace: active_ws.id, },
            preset: ws.preset().id(),
            min_scorecard: ws.min_scorecard().value(),
            require_security_gate: ws.has_security_gate(),
          }),
        ),
      ]
    }
    _ => []
  }
}

///|
/// Updates or inserts the live SDLC loading state purely.
fn Model::with_sdlc_load(
  self : Model,
  id : @app.WorkspaceId,
  load : SdlcLoad,
) -> Model {
  let mut replaced = false
  let next : Array[(@app.WorkspaceId, SdlcLoad)] = []
  for pair in self.sdlc {
    if pair.0 == id {
      next.push((id, load))
      replaced = true
    } else {
      next.push(pair)
    }
  }
  if !replaced {
    next.push((id, load))
  }
  { ..self, sdlc: ReadOnlyArray::from_array(next), }
}

///|
/// Returns the isolated mockup workspace for the currently open project, or the
/// default seed when no project-specific edits exist yet.
pub fn Model::active_mockup(self : Model) -> MockupWorkspace {
  match self.open_project() {
    Some(project) =>
      match self.mockups.iter().find_first(pair => pair.0 == project.id) {
        Some((_, ws)) => ws
        None => MockupWorkspace::seed()
      }
    None => MockupWorkspace::seed()
  }
}

///|
/// Updates the isolated mockup workspace for the currently open project purely.
fn Model::update_active_mockup(
  self : Model,
  f : (MockupWorkspace) -> MockupWorkspace,
) -> Model {
  guard self.open_project() is Some(project) else { self }
  let pid = project.id
  let current = self.active_mockup()
  let updated = f(current)
  let mut replaced = false
  let next_entries : Array[(@app.ProjectId, MockupWorkspace)] = []
  for pair in self.mockups {
    if pair.0 == pid {
      next_entries.push((pid, updated))
      replaced = true
    } else {
      next_entries.push(pair)
    }
  }
  if !replaced {
    next_entries.push((pid, updated))
  }
  { ..self, mockups: ReadOnlyArray::from_array(next_entries), }
}

///|
/// The details of a project, or `None` when the list does not have it.
fn Model::find(self : Model, id : @app.ProjectId) -> @app.Project? {
  self.projects.bind(projects => {
    projects.iter().find_first(project => project.id == id)
  })
}

///|
/// The open project, or `None` when no project is open or the list does not have it.
pub fn Model::open_project(self : Model) -> @app.Project? {
  self.open_id().bind(id => self.find(id))
}

///|
/// The name of the instance, if it is not `stable`.
pub fn Model::other_instance(self : Model) -> String? {
  guard self.instance != @app.InstanceName::of_channel(Stable) else { None }
  Some(self.instance.to_string())
}

///|
/// The view ended: it does not connect again, and its state does not change.
pub fn Model::is_over(self : Model) -> Bool {
  self.connection is (Restarted | Stopped)
}

///|
/// The part of an address before the ID of a project.
let project_hash : String = "#/projects/"

///|
/// Decodes percent-encoded colons (`%3A` / `%3a`) in a URN hash segment.
fn decode_urn_segment(text : String) -> String {
  text.replace_all(old="%3A", new=":").replace_all(old="%3a", new=":")
}

///|
/// Parses a URL hash fragment into a typed `Route`:
/// - `#/projects/` -> `ProjectRoute`
/// - `#/projects//workspaces/` -> `WorkspaceRoute`
/// - anything else -> `NoRoute`
pub fn parse_route(hash : String) -> Route {
  guard hash.strip_prefix(project_hash) is Some(rest) else { return NoRoute }
  match rest.split_once("/workspaces/") {
    Some((proj_part, ws_part)) => {
      if proj_part.contains("/") || ws_part.contains("/") {
        return NoRoute
      }
      let proj_text = decode_urn_segment(proj_part.to_owned())
      let ws_text = decode_urn_segment(ws_part.to_owned())
      let proj = @app.ProjectId(proj_text) catch { _ => return NoRoute }
      let ws = @app.WorkspaceId(ws_text) catch { _ => return NoRoute }
      WorkspaceRoute(proj, ws)
    }
    None => {
      if rest.contains("/") {
        return NoRoute
      }
      let proj_text = decode_urn_segment(rest.to_owned())
      let proj = @app.ProjectId(proj_text) catch { _ => return NoRoute }
      ProjectRoute(proj)
    }
  }
}

///|
/// Formats a typed `Route` as its canonical URL hash fragment.
pub fn Route::to_hash(self : Route) -> String {
  match self {
    NoRoute => "#/"
    ProjectRoute(id) => "\{project_hash}\{id}"
    WorkspaceRoute(proj, ws) => "\{project_hash}\{proj}/workspaces/\{ws}"
  }
}

///|
/// The project in the fragment of an address, such as `#/projects/urn:mc:proj:docs-01234567`.
pub fn project_of_hash(hash : String) -> @app.ProjectId? {
  parse_route(hash).project()
}

///|
/// The fragment of the address of a project, or of no project.
pub fn hash_of_project(project : @app.ProjectId?) -> String {
  match project {
    Some(id) => Route::ProjectRoute(id).to_hash()
    None => Route::NoRoute.to_hash()
  }
}

///|
/// What happens to a view.
pub(all) enum Msg {
  ConnectionChanged(ConnectionState)
  /// The view cannot try to connect. The text is for the user.
  ConnectionFailed(String)
  InfoRead(@app.AppInfo)
  /// The server gave its list, as a reply or as an event.
  ProjectsListed(ReadOnlyArray[@app.Project])
  /// The server returned live workspaces for one project.
  WorkspacesListed(@app.ProjectId, @app.ProjectWorkspaces)
  /// Live workspaces for one project changed on the server.
  WorkspacesChanged(@app.WorkspacesChanged)
  /// Loading workspaces for one project failed.
  WorkspacesFailed(@app.ProjectId, @proton_client.ClientFailure)
  /// The server returned live composed sources for one workspace.
  SourcesListed(@app.WorkspaceId, @app.WorkspaceSources)
  /// Loading composed sources for one workspace failed.
  SourcesFailed(@app.WorkspaceId, @proton_client.ClientFailure)
  /// The server returned live canonical intent for one workspace.
  IntentListed(@app.WorkspaceId, @app.WorkspaceIntent)
  /// Loading canonical intent for one workspace failed.
  IntentFailed(@app.WorkspaceId, @proton_client.ClientFailure)
  /// Selects one live OpenSpec intent item by ID.
  LiveIntentSelected(String)
  /// Selects a 0-based document index inside the active live reading packet.
  LiveDocSelected(Int32)
  /// The server returned live RDF Data Dictionary state for one workspace.
  DictionaryListed(@app.WorkspaceId, @app.WorkspaceDictionary)
  /// Loading the live RDF Data Dictionary failed.
  DictionaryFailed(@app.WorkspaceId, @proton_client.ClientFailure)
  /// Adding a local concept to `.mission-control/dictionary/local.ttl` succeeded.
  LiveConceptAdded(@app.WorkspaceId, String, @app.WorkspaceDictionary)
  /// Adding a local concept failed on the server.
  LiveConceptAddFailed(@proton_client.ClientFailure)
  /// Selects one live dictionary concept by IRI.
  LiveConceptSelected(String)
  /// Filters live dictionary concepts by named graph ID (`None` = All).
  LiveDictGraphSelected(String?)
  /// The server returned live DocumentScorer & Rego SDLC evaluation for one workspace.
  SdlcEvaluated(@app.WorkspaceId, @app.WorkspaceSdlc)
  /// Evaluating workspace SDLC failed on the server.
  SdlcFailed(@app.WorkspaceId, @proton_client.ClientFailure)
  /// A program asks the views of one kind to show a project.
  ProjectShown(@app.ShownProject)
  /// The server stops.
  AppStopping
  /// The address of the page changed, also because the view changed it.
  HashChanged(Route)
  /// The window has a new size, which can be of the same kind.
  WindowResized(WindowSize)
  /// The user selects an action, with a control on the screen, in the palette or with
  /// its shortcut.
  ActionChosen(Action)
  /// Toggles the expanded/collapsed state of an open multi-workspace project's
  /// sidebar tree without closing the mobile project sheet.
  ProjectTreeToggled(@app.ProjectId)
  /// The user presses a shortcut of the palette, or its control.
  PaletteOpened
  /// The user changed the text in the palette.
  PaletteTyped(String)
  /// The user selects the next result or the one before it.
  PaletteMoved(Direction)
  /// The user moved the pointer over an action of the palette.
  PalettePointed(ActionId)
  /// The user presses Enter in the palette. `seen` has the actions of the page at that
  /// moment.
  PaletteEntered(seen~ : ReadOnlyArray[Action])
  /// The user cancels the dialog that is open.
  CloseDialog
  /// The browser closed the element, because the user pressed Escape or because the
  /// view closed it. The browser tells it late: another dialog can be open.
  DialogClosed(DialogElement)
  /// The user changed the text of the path.
  PathTyped(String)
  /// The user asks for the folder dialog of the system.
  BrowseChosen
  /// The folder dialog of the system closed.
  FolderChosen(@app.ChosenFolder)
  /// The folder dialog of the system did not open.
  BrowseFailed(@proton_client.ClientFailure)
  /// The user sends the path to the server.
  AddSubmitted
  /// The server has the project of this path.
  ProjectAdded(path~ : String, @app.AddedProject)
  /// The server did not add this path.
  AddFailed(path~ : String, @proton_client.ClientFailure)
  ProjectRemoved(@app.ProjectId)
  RemoveFailed(@app.ProjectId, @proton_client.ClientFailure)
  /// The user confirms in the dialog `ConfirmStop`.
  StopConfirmed
  /// A call or an event failed, and the user did not wait for it.
  CallFailed(@proton_client.ClientFailure)
  /// The user closes the notice.
  NoticeDismissed
  /// Switches perspective via tablist keyboard navigation and moves focus to the chosen tab.
  PerspectiveTabMoved(Perspective)
  /// Switches the view inside the Plan perspective.
  PlanViewChosen(PlanView)
  /// Switches document reading mode inside Review.
  ReadModeChosen(ReadMode)
  /// Selects a document in the Review reading packet.
  ReviewDocChosen(ReviewDocId)
  /// Switches between Data Dictionary and Knowledge Base inside Knowledge.
  KnowledgeViewChosen(KnowledgeView)
  /// Filters Data Dictionary concepts by named graph.
  DictGraphChosen(NamedGraphFilter)
  /// Switches Data Dictionary reader format (`Structured`, `Turtle`, `JSON-LD`).
  DictFormatChosen(DictFormat)
  /// Updates the Data Dictionary concept search filter.
  DictQueryChanged(String)
  /// Updates the local concept draft label input.
  DictDraftLabelChanged(String)
  /// Updates the local concept draft definition input.
  DictDraftDefChanged(String)
  /// Validates and creates a new local SKOS concept in preview state.
  DictConceptSubmitted
  /// Resolves a Prose Term Audit item (normalizing `CC#` or accepting an unlinked term).
  TermAuditResolved(TermAuditId)
  /// Jumps straight to `Knowledge -> Data Dictionary` focused on one concept.
  OpenConceptInDictionary(ConceptId)
  /// Jumps from a Dictionary backlink straight to the workflow item and document in Review.
  OpenBacklinkInReview(WorkflowItemId, ReviewDocId)
  /// Filters Knowledge Base documents by source (`All`, `Local OKF`, `Mounted RO`).
  KbSourceChosen(KbSourceFilter)
  /// Updates the Knowledge Base search query.
  KbQueryChanged(String)
  /// Selects a Knowledge Base document.
  KbDocChosen(KbDocId)
  /// Switches Knowledge Base document reading mode (`Preview` or `Source`).
  KbReadModeChosen(KbReadMode)
  /// Toggles the read marker on a Review reading packet document.
  ToggleDocRead(ReviewDocId)
  /// Switches the right Reading Companion tab in Review.
  ReviewTabChosen(ReviewTab)
  /// Selects an inline dictionary concept to peek in Review.
  ConceptSelected(ConceptId)
  /// Normalizes the deprecated `CC#` term in the preview workspace.
  NormalizeDeprecatedTerm
  /// Approves the active Review packet and advances it when unblocked.
  ReviewApproved
  /// Requests changes on the active Review packet, sending it back.
  ReviewRequestedChanges
  /// Selects a workflow item and opens the on-demand gate inspector.
  ItemSelected(WorkflowItemId)
  /// Dismisses the on-demand gate inspector.
  CloseInspector
  /// Resolves open preview gates on one workflow item.
  ResolveOpenGates(WorkflowItemId)
  /// Advances one workflow item when its gates pass.
  AdvanceWorkflowItem(WorkflowItemId)
  /// Sends one workflow item back along its rework transition.
  SendBackWorkflowItem(WorkflowItemId)
  /// Opens full-page Settings directly on a chosen section tab.
  OpenSettingsTab(SettingsTab)
  /// Switches the active tab inside full-page Settings.
  SettingsTabChosen(SettingsTab)
  /// Closes the full-page Settings overlay.
  CloseSettings
  /// Cycles appearance (`System -> Light -> Dark`) from the top-bar quick toggle.
  AppearanceCycled
  /// Updates the configurable brand display title when valid.
  BrandTitleChanged(String)
  /// Selects a brand mark (`Moonrockz`, `Monogram`, `Emoji`, or `CustomImage`).
  BrandMarkChosen(BrandMark)
  /// Updates the monogram letters when valid.
  BrandMonogramChanged(String)
  /// Updates the emoji mark when valid.
  BrandEmojiChanged(String)
  /// Validates and applies an uploaded custom raster `data:image/` URL.
  BrandImageSelected(String)
  /// Resets brand mark and display title back to Mission Control defaults.
  BrandReset
  /// Picks a canned workflow preset for the active project preview.
  PresetChosen(WorkflowPreset)
  /// Updates the Verify Gate minimum scorecard floor.
  MinScorecardChosen(Score)
  /// Switches Mermaid vs BPMN rendering inside Workflow Studio.
  StudioDiagramChosen(StudioDiagramKind)
  /// Switches Mermaid/BPMN/YAML source tab inside Workflow Studio.
  StudioFormatChosen(StudioFormat)
  /// Selects a stage node inside Workflow Studio to inspect its contract.
  StudioStageChosen(StageId)
  /// Toggles an optional input artifact requirement on a Workflow Studio stage.
  StudioExtraInputToggled(StageId, ExtraArtifactInput)
  /// Updates the editable Workflow Studio diagram source draft.
  StudioSourceEdited(String)
  /// Toggles the Security Gate stage inside Workflow Studio.
  ToggleSecurityGate
  /// Selects a color scheme and persists it in browser storage.
  ColorSchemeChosen(ColorScheme)
  /// Selects a light/dark/system appearance override and persists it.
  AppearanceChosen(Appearance)
  /// Resizes the desktop primary sidebar and persists its pixel width.
  SidebarResized(SidebarWidth)
  /// Collapses or expands the secondary left sidebar in Review and Knowledge.
  SecondarySidebarToggled
  /// Resizes the secondary left sidebar and persists its pixel width.
  SecondarySidebarResized(SecondarySidebarWidth)
  /// Collapses or expands the right companion panel in Review and Knowledge.
  CompanionPanelToggled
}

///|
/// A call of the server.
#derive(Eq, Debug)
priv enum ServerCall {
  ReadInfo
  ReadProjects
  ReadWorkspaces(@app.ProjectId)
  ReadWorkspaceSources(@app.WorkspaceRef)
  ReadWorkspaceIntent(@app.WorkspaceRef)
  ReadWorkspaceDictionary(@app.WorkspaceRef)
  CreateDictionaryConcept(@app.AddDictionaryConcept)
  EvaluateWorkspaceSdlc(@app.WorkspaceRef)
  PersistWorkspaceWorkflow(@app.SaveWorkspaceWorkflow)
  Add(String)
  /// Records that the user opens the project.
  RecordOpen(@app.ProjectId)
  /// Records that the user opens a specific peer workspace.
  RecordOpenWorkspace(@app.WorkspaceRef)
  Remove(@app.ProjectId)
  Stop
}

///|
/// Closed set of page controls that receive explicit focus after render.
#derive(Eq, Debug)
priv enum FocusTarget {
  PerspectiveTab(Perspective)
  WorkflowItemTrigger(Perspective, PlanView, WorkflowItemId)
}

///|
fn FocusTarget::id(self : FocusTarget) -> String {
  match self {
    PerspectiveTab(perspective) => perspective.tab_id()
    WorkflowItemTrigger(perspective, plan_view, item_id) =>
      workflow_item_trigger_id(perspective, plan_view, item_id)
  }
}

///|
/// What a step asks of the server and of the page.
// Only the tests compare effects and write them as text.
#warnings("-unused_value")
#derive(Eq, Debug)
priv enum Effect {
  Call(ServerCall)
  /// Opens the folder dialog of the system, with the desktop app and not the server.
  ChooseFolder
  ShowDialog(DialogElement)
  HideDialog(DialogElement)
  /// Scrolls the list of the palette, so that the user sees the action.
  ShowEntry(ActionId)
  /// Sets the address. The browser can go back to the old one.
  PushHash(Route)
  /// Sets the address. The browser cannot go back to the old one.
  ReplaceHash(Route)
  /// Puts the focus in the field for the path of a new project.
  FocusPath
  /// Puts the focus in the Back to Workspace button when Settings opens.
  FocusSettingsBack
  /// Moves focus to a typed control target after render, falling back to `main_title_id`.
  Focus(FocusTarget)
  /// Puts the focus in the title of the main area, if the control that had it is gone.
  KeepFocus
  /// Puts the focus in the control that the user sees in this state of the primary
  /// sidebar, if the control that had it is gone.
  FocusPrimarySidebarControl(PrimarySidebar)
  /// Keeps the state for the next page of the same browser.
  StorePrimarySidebar(PrimarySidebar)
  /// Keeps the resized primary sidebar width for the next page of the same browser.
  StoreSidebarWidth(SidebarWidth)
  /// Keeps the secondary left sidebar open/collapsed state.
  StoreSecondarySidebar(SecondarySidebar)
  /// Keeps the resized secondary left sidebar width.
  StoreSecondarySidebarWidth(SecondarySidebarWidth)
  /// Keeps the right companion panel open/collapsed state.
  StoreCompanionPanel(CompanionPanel)
  /// Keeps the color scheme for the next page of the same browser.
  StoreColorScheme(ColorScheme)
  /// Keeps the appearance choice for the next page of the same browser.
  StoreAppearance(Appearance)
  /// Keeps the configurable brand identity for the next page of the same browser.
  StoreBrand(BrandConfig)
  /// Ends the connection for good. It does not know why the server went away.
  EndConnection
}

///|
/// Sends the call, and gives its answer as a message.
fn ServerCall::start(
  self : ServerCall,
  client : @proton_client.Client,
  send : (Msg) -> Unit,
) -> Unit {
  let failed = error => send(CallFailed(error))
  // The view never takes a call back, so it does not need the function that does.
  let _ = match self {
    ReadInfo =>
      client.invoke_with_callbacks(
        @app.app_info,
        @proton_contract.EmptyRequest::{ },
        info => send(InfoRead(info)),
        failed,
      )
    ReadProjects =>
      client.invoke_with_callbacks(
        @app.list_projects,
        @proton_contract.EmptyRequest::{ },
        projects => send(ProjectsListed(ReadOnlyArray::from_array(projects))),
        failed,
      )
    ReadWorkspaces(project) =>
      client.invoke_with_callbacks(
        @app.list_workspaces,
        project,
        workspaces => send(WorkspacesListed(project, workspaces)),
        error => send(WorkspacesFailed(project, error)),
      )
    ReadWorkspaceSources(ws_ref) =>
      client.invoke_with_callbacks(
        @app.list_workspace_sources,
        ws_ref,
        sources => send(SourcesListed(ws_ref.workspace, sources)),
        error => send(SourcesFailed(ws_ref.workspace, error)),
      )
    ReadWorkspaceIntent(ws_ref) =>
      client.invoke_with_callbacks(
        @app.list_workspace_intent,
        ws_ref,
        intent => send(IntentListed(ws_ref.workspace, intent)),
        error => send(IntentFailed(ws_ref.workspace, error)),
      )
    ReadWorkspaceDictionary(ws_ref) =>
      client.invoke_with_callbacks(
        @app.list_workspace_dictionary,
        ws_ref,
        dict => send(DictionaryListed(ws_ref.workspace, dict)),
        error => send(DictionaryFailed(ws_ref.workspace, error)),
      )
    CreateDictionaryConcept(req) =>
      client.invoke_with_callbacks(
        @app.add_dictionary_concept,
        req,
        dict => {
          send(LiveConceptAdded(req.workspace.workspace, req.pref_label, dict))
        },
        error => send(LiveConceptAddFailed(error)),
      )
    EvaluateWorkspaceSdlc(ws_ref) =>
      client.invoke_with_callbacks(
        @app.evaluate_workspace_sdlc,
        ws_ref,
        eval => send(SdlcEvaluated(ws_ref.workspace, eval)),
        error => send(SdlcFailed(ws_ref.workspace, error)),
      )
    PersistWorkspaceWorkflow(req) =>
      client.invoke_with_callbacks(
        @app.save_workspace_workflow,
        req,
        eval => send(SdlcEvaluated(req.workspace.workspace, eval)),
        error => send(SdlcFailed(req.workspace.workspace, error)),
      )
    Add(path) =>
      client.invoke_with_callbacks(
        @app.add_project,
        { path, title: None, caption: None, },
        added => send(ProjectAdded(path~, added)),
        error => send(AddFailed(path~, error)),
      )
    RecordOpen(id) =>
      client.invoke_with_callbacks(
        @app.open_project,
        id,
        // The event `projects_changed` has the new details.
        _ => (),
        failed,
      )
    RecordOpenWorkspace(ws_ref) =>
      client.invoke_with_callbacks(
        @app.open_workspace,
        ws_ref,
        // The event `workspaces_changed` has the updated state.
        _ => (),
        failed,
      )
    Remove(id) =>
      client.invoke_with_callbacks(
        @app.remove_project,
        id,
        _ => send(ProjectRemoved(id)),
        error => send(RemoveFailed(id, error)),
      )
    Stop =>
      client.invoke_with_callbacks(
        @app.stop_app,
        @proton_contract.EmptyRequest::{ },
        _ => send(AppStopping),
        failed,
      )
  }
}

///|
/// Asks the desktop app for a folder, and gives its answer as a message.
fn ask_folder(
  desktop_app : @proton_client.Client,
  send : (Msg) -> Unit,
) -> Unit {
  // The view never takes the call back, because the user closes the folder dialog.
  let _ = desktop_app.invoke_with_callbacks(
    @app.choose_folder,
    @proton_contract.EmptyRequest::{ },
    chosen => send(FolderChosen(chosen)),
    error => send(BrowseFailed(error)),
  )
}

///|
/// The text of a failure for the user. The server writes the text of a refusal.
fn failure_text(failure : @proton_client.ClientFailure) -> String {
  match failure {
    RemoteFailure(message~, ..) => message
    TransportFailure(message~) => "No answer from Mission Control: \{message}"
    InvalidContract(message~)
    | ResponseDecode(message~)
    | EventDecode(message~) =>
      "Mission Control sent data that this page does not know: \{message}"
    BridgeUnavailable | RequestCancelled as other => other.message()
  }
}

///|
/// Ensures workspaces for `id` are requested when connected and the project is listed.
/// Marks `Loading` only when no `Ready` snapshot is cached yet.
fn Model::ensure_workspaces(
  self : Model,
  id : @app.ProjectId,
  force~ : Bool = false,
) -> (Model, Array[Effect]) {
  guard self.connection is Connected && self.find(id) is Some(_) else {
    return (self, [])
  }
  match self.workspace_load(id) {
    Some(Ready(_)) if !force => (self, [])
    Some(Ready(_)) => (self, [Call(ReadWorkspaces(id))])
    Some(Loading) if !force => (self, [])
    _ => (self.with_workspace_load(id, Loading), [Call(ReadWorkspaces(id))])
  }
}

///|
fn Model::ensure_intent(
  self : Model,
  project_id : @app.ProjectId,
  workspace_id : @app.WorkspaceId,
  force~ : Bool = false,
) -> (Model, Array[Effect]) {
  guard self.connection is Connected && self.find(project_id) is Some(_) else {
    return (self, [])
  }
  let call : Effect = Call(
    ReadWorkspaceIntent({ project: project_id, workspace: workspace_id, }),
  )
  match self.intent_load(workspace_id) {
    Ready(_) if !force => (self, [])
    Ready(_) => (self, [call])
    Loading if !force => (self, [])
    _ => (self.with_intent_load(workspace_id, Loading), [call])
  }
}

///|
fn Model::ensure_dictionary(
  self : Model,
  project_id : @app.ProjectId,
  workspace_id : @app.WorkspaceId,
  force~ : Bool = false,
) -> (Model, Array[Effect]) {
  guard self.connection is Connected && self.find(project_id) is Some(_) else {
    return (self, [])
  }
  let call : Effect = Call(
    ReadWorkspaceDictionary({ project: project_id, workspace: workspace_id, }),
  )
  match self.dictionary_load(workspace_id) {
    Ready(_) if !force => (self, [])
    Ready(_) => (self, [call])
    Loading if !force => (self, [])
    _ => (self.with_dictionary_load(workspace_id, Loading), [call])
  }
}

///|
fn Model::ensure_sdlc(
  self : Model,
  project_id : @app.ProjectId,
  workspace_id : @app.WorkspaceId,
  force~ : Bool = false,
) -> (Model, Array[Effect]) {
  guard self.connection is Connected && self.find(project_id) is Some(_) else {
    return (self, [])
  }
  let call : Effect = Call(
    EvaluateWorkspaceSdlc({ project: project_id, workspace: workspace_id, }),
  )
  match self.sdlc_load(workspace_id) {
    Ready(_) if !force => (self, [])
    Ready(_) => (self, [call])
    Loading if !force => (self, [])
    _ => (self.with_sdlc_load(workspace_id, Loading), [call])
  }
}

///|
/// Ensures composed sources, live canonical intent, live RDF dictionary, and
/// live SDLC scorecards/Rego gates are requested for `(project_id, workspace_id)`.
fn Model::ensure_sources(
  self : Model,
  project_id : @app.ProjectId,
  workspace_id : @app.WorkspaceId,
  force~ : Bool = false,
) -> (Model, Array[Effect]) {
  guard self.connection is Connected && self.find(project_id) is Some(_) else {
    return (self, [])
  }
  let call : Effect = Call(
    ReadWorkspaceSources({ project: project_id, workspace: workspace_id, }),
  )
  let (after_src, effects) : (Model, Array[Effect]) = match
    self.sources_load(workspace_id) {
    Ready(_) if !force => (self, [])
    Ready(_) => (self, [call])
    Loading if !force => (self, [])
    _ => (self.with_sources_load(workspace_id, Loading), [call])
  }
  let (after_intent, intent_effects) = after_src.ensure_intent(
    project_id,
    workspace_id,
    force~,
  )
  effects.append(intent_effects)
  let (after_dict, dict_effects) = after_intent.ensure_dictionary(
    project_id,
    workspace_id,
    force~,
  )
  effects.append(dict_effects)
  let (after_sdlc, sdlc_effects) = after_dict.ensure_sdlc(
    project_id,
    workspace_id,
    force~,
  )
  effects.append(sdlc_effects)
  (after_sdlc, effects)
}

///|
/// Requests composed sources for the currently active populated workspace.
fn Model::ensure_active_sources(
  self : Model,
  force~ : Bool = false,
) -> (Model, Array[Effect]) {
  match (self.open_id(), self.active_workspace_value()) {
    (Some(project_id), Some(ws)) =>
      self.ensure_sources(project_id, ws.id, force~)
    _ => (self, [])
  }
}

///|
/// Applies a fresh workspace state for `id`, reconciling the active workspace and URL hash
/// when `id` is the open project.
fn Model::apply_workspaces(
  self : Model,
  id : @app.ProjectId,
  result : @app.ProjectWorkspaces,
) -> (Model, Array[Effect]) {
  let updated = self.with_workspace_load(id, Ready(result))
  guard updated.open_id() == Some(id) else { return (updated, []) }
  match result {
    Populated(set) =>
      match updated.active_workspace_id() {
        Some(ws_id) if set.get(ws_id) is Some(_) =>
          updated.ensure_sources(id, ws_id)
        Some(_) => {
          // Hash named a workspace that no longer exists: fall back to the default
          // workspace and update the URL hash.
          let fallback = set.default_id()
          let next_route = Route::WorkspaceRoute(id, fallback)
          let target : NavTarget = {
            ..updated.nav_target(),
            route: next_route,
          }
          let history = updated.history.replace_current(target)
          let next = { ..updated, route: next_route, history, }
          let (next, src_effects) = next.ensure_sources(id, fallback)
          (next, [ReplaceHash(next_route), ..src_effects])
        }
        None => {
          let def = set.default_id()
          let next_route = Route::WorkspaceRoute(id, def)
          let target : NavTarget = {
            ..updated.nav_target(),
            route: next_route,
          }
          let history = updated.history.replace_current(target)
          let next = { ..updated, route: next_route, history, }
          next.ensure_sources(id, def)
        }
      }
    Empty | Unavailable(..) =>
      if updated.active_workspace_id() is Some(_) {
        let next_route = Route::ProjectRoute(id)
        let target : NavTarget = { ..updated.nav_target(), route: next_route, }
        let history = updated.history.replace_current(target)
        ({ ..updated, route: next_route, history, }, [ReplaceHash(next_route)])
      } else {
        (updated, [])
      }
  }
}

///|
/// Opens a project and sets the address of the page.
fn Model::show(
  self : Model,
  id : @app.ProjectId,
  workspace~ : @app.WorkspaceId? = None,
  record~ : Bool,
) -> (Model, Array[Effect]) {
  guard self.open_id() != Some(id) ||
    (workspace is Some(w) && Some(w) != self.active_workspace_id()) else {
    if self.settings is Open(_) {
      ({ ..self, settings: Closed, }, [])
    } else {
      (self, [])
    }
  }
  let resolved_route : Route = match workspace {
    Some(w) => WorkspaceRoute(id, w)
    None =>
      match self.workspace_load(id) {
        Some(Ready(Populated(set))) => WorkspaceRoute(id, set.default_id())
        _ => ProjectRoute(id)
      }
  }
  let target : NavTarget = { ..self.nav_target(), route: resolved_route, }
  let history = match self.open_id() {
    Some(_) => self.history.push(target)
    None => self.history.replace_current(target)
  }
  let next = { ..self, route: resolved_route, settings: Closed, history, }
  let (next, ws_effects) = next.ensure_workspaces(id, force=true)
  let hash_route : Route = match workspace {
    Some(w) => WorkspaceRoute(id, w)
    None => ProjectRoute(id)
  }
  let effects : Array[Effect] = [PushHash(hash_route)]
  if record {
    match workspace {
      Some(ws_id) =>
        if self.connection is Connected && self.find(id) is Some(_) {
          effects.push(
            Call(RecordOpenWorkspace({ project: id, workspace: ws_id, })),
          )
        }
      None => effects.append(self.record_open(id))
    }
  }
  effects.append(ws_effects)
  if self.loses_control(next) {
    effects.push(KeepFocus)
  }
  (next, effects)
}

///|
/// Switches to a specific peer workspace of a project, updating the URL hash and
/// recording the workspace open on the server when connected.
fn Model::show_workspace(
  self : Model,
  project_id : @app.ProjectId,
  workspace_id : @app.WorkspaceId,
  record~ : Bool,
) -> (Model, Array[Effect]) {
  let next_route = Route::WorkspaceRoute(project_id, workspace_id)
  guard self.route != next_route else {
    if self.settings is Open(_) {
      ({ ..self, settings: Closed, }, [])
    } else {
      (self, [])
    }
  }
  let target : NavTarget = { ..self.nav_target(), route: next_route, }
  let history = match self.open_id() {
    Some(_) => self.history.push(target)
    None => self.history.replace_current(target)
  }
  let next = { ..self, route: next_route, settings: Closed, history, }
  let (next, ws_effects) = if self.open_id() != Some(project_id) {
    next.ensure_workspaces(project_id, force=true)
  } else {
    (next, [])
  }
  let (next, src_effects) = next.ensure_sources(
    project_id,
    workspace_id,
    force=true,
  )
  let effects : Array[Effect] = [PushHash(next_route)]
  if record && self.connection is Connected && self.find(project_id) is Some(_) {
    effects.push(
      Call(
        RecordOpenWorkspace({ project: project_id, workspace: workspace_id, }),
      ),
    )
  }
  effects.append(ws_effects)
  effects.append(src_effects)
  if self.loses_control(next) {
    effects.push(KeepFocus)
  }
  (next, effects)
}

///|
/// Reconciles `route` against cached workspaces so a disappeared workspace URN
/// falls back to the project's default workspace (or `ProjectRoute` if empty or
/// unavailable). Returns `(resolved_route, changed)`.
fn Model::reconcile_route(self : Model, route : Route) -> (Route, Bool) {
  match route {
    NoRoute => (NoRoute, false)
    ProjectRoute(pid) =>
      match self.workspace_load(pid) {
        Some(Ready(Populated(set))) =>
          (WorkspaceRoute(pid, set.default_id()), true)
        _ => (ProjectRoute(pid), false)
      }
    WorkspaceRoute(pid, wid) =>
      match self.workspace_load(pid) {
        Some(Ready(Populated(set))) =>
          match set.get(wid) {
            Some(_) => (route, false)
            None => (WorkspaceRoute(pid, set.default_id()), true)
          }
        Some(Ready(Empty | Unavailable(..))) => (ProjectRoute(pid), true)
        _ => (route, false)
      }
  }
}

///|
/// Applies a `NavTarget` popped from `NavHistory` (via Back or Forward),
/// reconciling stale workspace URNs against cached project workspaces.
fn Model::apply_history(
  self : Model,
  history : NavHistory,
  target : NavTarget,
) -> (Model, Array[Effect]) {
  let (resolved_route, reconciled) = self.reconcile_route(target.route)
  let next_history = if reconciled {
    history.replace_current({ ..target, route: resolved_route, })
  } else {
    history
  }
  let route_changed = resolved_route != self.route
  let next = {
    ..self,
    route: resolved_route,
    perspective: target.perspective,
    plan_view: target.plan_view,
    review_doc: target.review_doc,
    knowledge_view: target.knowledge_view,
    settings: Closed,
    history: next_history,
  }
  let effects : Array[Effect] = []
  let mut final_model = next
  if route_changed {
    effects.push(
      if reconciled {
        ReplaceHash(resolved_route)
      } else {
        PushHash(resolved_route)
      },
    )
    match resolved_route {
      WorkspaceRoute(pid, wid) => {
        if self.connection is Connected && self.find(pid) is Some(_) {
          effects.push(
            Call(RecordOpenWorkspace({ project: pid, workspace: wid, })),
          )
        }
        let (loaded, ws_effects) = final_model.ensure_workspaces(pid)
        final_model = loaded
        effects.append(ws_effects)
        let (loaded, src_effects) = final_model.ensure_sources(pid, wid)
        final_model = loaded
        effects.append(src_effects)
      }
      ProjectRoute(pid) => {
        effects.append(self.record_open(pid))
        let (loaded, ws_effects) = final_model.ensure_workspaces(pid)
        final_model = loaded
        effects.append(ws_effects)
      }
      NoRoute => ()
    }
    if self.loses_control(final_model) {
      effects.push(KeepFocus)
    }
  }
  (final_model, effects)
}

///|
/// Records the open of a project, if the server can do it now.
fn Model::record_open(self : Model, id : @app.ProjectId) -> Array[Effect] {
  if self.connection is Connected && self.find(id) is Some(_) {
    [Call(RecordOpen(id))]
  } else {
    []
  }
}

///|
/// The model with this dialog, if no other dialog is open.
fn Model::open_dialog(self : Model, dialog : Dialog) -> (Model, Array[Effect]) {
  guard self.dialog is NoDialog && dialog.element() is Some(element) else {
    (self, [])
  }
  ({ ..self, dialog, }, [ShowDialog(element)])
}

///|
/// The model with no notice. The button that closes the notice can have the focus.
fn Model::dismiss_notice(self : Model) -> (Model, Array[Effect]) {
  guard self.notice is Some(_) else { (self, []) }
  ({ ..self, notice: None, }, [KeepFocus])
}

///|
/// The model with no dialog. The browser gives the focus back to the control that had
/// it before the dialog, but that control can be gone.
fn Model::close_dialog(self : Model) -> (Model, Array[Effect]) {
  match self.dialog.element() {
    Some(element) =>
      ({ ..self, dialog: NoDialog, }, [HideDialog(element), KeepFocus])
    None => (self, [])
  }
}

///|
/// The model of a view that ended.
fn Model::end(
  self : Model,
  connection : ConnectionState,
) -> (Model, Array[Effect]) {
  let (model, effects) = self.close_dialog()
  // The controls of the page go away, also without a dialog.
  let effects = if effects.is_empty() { [KeepFocus] } else { effects }
  ({ ..model, connection, notice: None, }, effects)
}

///|
/// The change of the list or of the open project removes a control from the page, or
/// moves it. Both take the focus from the control. An open project and an empty list
/// have a button in the main area, and each project has its own one.
fn Model::loses_control(self : Model, next : Model) -> Bool {
  guard self.projects is Some(projects) else { false }
  let rows = next.projects.unwrap_or([])
  if self.open_project() is Some(project) &&
    !(next.open_project() is Some(other) && other.id == project.id) {
    true
  } else if projects.is_empty() {
    !rows.is_empty()
  } else {
    // New projects after the old ones move no row.
    projects.length() > rows.length() ||
    !projects.iter().zip(rows.iter()).all(pair => pair.0.id == pair.1.id)
  }
}

///|
/// The model that shows a failure. The status bar shows a lost connection, so a
/// failure that comes from the loss has no text.
fn Model::show_failure(
  self : Model,
  failure : @proton_client.ClientFailure,
) -> Model {
  guard self.connection is Connected else { self }
  { ..self, notice: Some(failure_text(failure)), }
}

///|
/// Does an action that is enabled, with no open dialog.
fn Model::do_action(self : Model, action : Action) -> (Model, Array[Effect]) {
  match action {
    OpenProject(project) => self.show(project.id, record=true)
    OpenWorkspace(project, workspace) =>
      self.show_workspace(project.id, workspace.id, record=true)
    AddProject => self.open_dialog(Dialog::add())
    RemoveProject(project) => {
      let (model, effects) = self.dismiss_notice()
      (model, [Call(Remove(project.id)), ..effects])
    }
    SetPerspective(perspective) => {
      let base = self.update_active_mockup(ws => ws.close_inspector())
      let target : NavTarget = { ..base.nav_target(), perspective, }
      let history = base.history.push(target)
      ({ ..base, perspective, settings: Closed, history, }, [])
    }
    NavigateBack =>
      match self.history.go_back() {
        Some((history, target)) => self.apply_history(history, target)
        None => (self, [])
      }
    NavigateForward =>
      match self.history.go_forward() {
        Some((history, target)) => self.apply_history(history, target)
        None => (self, [])
      }
    OpenSettings => {
      let initial_tab = match self.open_project() {
        Some(_) => Workflow
        None => Appearance
      }
      ({ ..self, settings: Open(initial_tab), }, [FocusSettingsBack])
    }
    SetPrimarySidebar(state) => {
      guard state != self.primary_sidebar else { (self, []) }
      (
        { ..self, primary_sidebar: state, },
        [StorePrimarySidebar(state), FocusPrimarySidebarControl(state)],
      )
    }
    StopApp => self.open_dialog(ConfirmStop)
  }
}

///|
/// Does an action that the user selected with a control or in the palette.
fn Model::choose(self : Model, action : Action) -> (Model, Array[Effect]) {
  guard action.enabled(self) else { (self, []) }
  match self.dialog {
    NoDialog => self.do_action(action)
    Palette(..) => {
      // The palette closes first, so it gives the focus back before a dialog takes it.
      // The title gets the focus last, only if the action has no better place for it.
      let closed = { ..self, dialog: NoDialog, }
      let (next, effects) = closed.do_action(action)
      (next, [HideDialog(PaletteElement), ..effects, KeepFocus])
    }
    // These dialogs are over each control.
    AddDialog(..) | ConfirmStop => (self, [])
  }
}

///|
/// The model after a message, and what the step asks of the server and the page.
fn step(model : Model, msg : Msg) -> (Model, Array[Effect]) {
  guard !model.is_over() else { (model, []) }
  let (next, effects) = step_alone(model, msg)
  let (next, show) = next.keep_selection(before=model)
  (next, [..effects, ..show])
}

///|
/// The step without its result for the selection in the palette.
fn step_alone(model : Model, msg : Msg) -> (Model, Array[Effect]) {
  match msg {
    ConnectionChanged(Connected) => {
      let next = { ..model, connection: Connected, }
      let (next, ws_effects) = match next.open_id() {
        Some(id) => next.ensure_workspaces(id, force=true)
        None => (next, [])
      }
      (next, [Call(ReadInfo), Call(ReadProjects), ..ws_effects])
    }
    ConnectionChanged(Restarted | Stopped as state) => model.end(state)
    ConnectionChanged(Connecting | Reconnecting as connection) =>
      ({ ..model, connection, }, [])
    ConnectionFailed(text) => ({ ..model, notice: Some(text), }, [])
    AppStopping => {
      let (model, effects) = model.end(Stopped)
      (model, [EndConnection, ..effects])
    }
    InfoRead(info) => ({ ..model, info: Some(info), }, [])
    ProjectsListed(projects) => {
      let history = model.history.retain_projects(projects)
      let mockups = model.mockups.filter(pair => {
        projects.iter().any(project => project.id == pair.0)
      })
      let workspaces = model.workspaces.filter(pair => {
        projects.iter().any(project => project.id == pair.0)
      })
      let sources = prune_removed_sources(
        model.workspaces,
        workspaces,
        model.sources,
      )
      let collapsed_projects = model.collapsed_projects.filter(id => {
        projects.iter().any(project => project.id == id)
      })
      let next = {
        ..model,
        projects: Some(projects),
        history,
        mockups,
        workspaces,
        sources,
        collapsed_projects,
      }
      let (next, ws_effects) = match next.open_id() {
        Some(id) => next.ensure_workspaces(id)
        None => (next, [])
      }
      let effects : Array[Effect] = ws_effects
      if model.loses_control(next) {
        effects.push(KeepFocus)
      }
      (next, effects)
    }
    WorkspacesListed(project, result) => model.apply_workspaces(project, result)
    WorkspacesChanged({ project, workspaces, }) =>
      model.apply_workspaces(project, workspaces)
    WorkspacesFailed(project, failure) =>
      if model.connection is Connected && model.find(project) is Some(_) {
        (model.with_workspace_load(project, Failed(failure_text(failure))), [])
      } else {
        (model, [])
      }
    SourcesListed(workspace, sources) =>
      (model.with_sources_load(workspace, Ready(sources)), [])
    SourcesFailed(workspace, failure) =>
      if model.connection is Connected {
        (model.with_sources_load(workspace, Failed(failure_text(failure))), [])
      } else {
        (model, [])
      }
    IntentListed(workspace, intent) =>
      (model.with_intent_load(workspace, Ready(intent)), [])
    IntentFailed(workspace, failure) =>
      if model.connection is Connected {
        (model.with_intent_load(workspace, Failed(failure_text(failure))), [])
      } else {
        (model, [])
      }
    LiveIntentSelected(item_id) =>
      (
        { ..model, selected_live_intent: Some(item_id), selected_live_doc: 0, },
        [],
      )
    LiveDocSelected(doc_idx) => ({ ..model, selected_live_doc: doc_idx, }, [])
    DictionaryListed(workspace, dict) =>
      (model.with_dictionary_load(workspace, Ready(dict)), [])
    DictionaryFailed(workspace, failure) =>
      if model.connection is Connected {
        (
          model.with_dictionary_load(workspace, Failed(failure_text(failure))),
          [],
        )
      } else {
        (model, [])
      }
    LiveConceptAdded(workspace, pref_label, dict) => {
      let chosen_iri = dict.concepts
        .iter()
        .find_first(c => c.pref_label == pref_label)
        .map(c => c.iri)
      let next = model.with_dictionary_load(workspace, Ready(dict))
      (
        {
          ..next,
          selected_live_concept: chosen_iri,
          selected_live_dict_graph: None,
          dict_query: "",
          dict_draft_label: "",
          dict_draft_def: "",
          dict_draft_error: None,
        },
        [],
      )
    }
    LiveConceptAddFailed(failure) =>
      ({ ..model, dict_draft_error: Some(failure_text(failure)), }, [])
    LiveConceptSelected(iri) =>
      ({ ..model, selected_live_concept: Some(iri), }, [])
    LiveDictGraphSelected(graph_id) =>
      ({ ..model, selected_live_dict_graph: graph_id, }, [])
    SdlcEvaluated(workspace, eval) => {
      let updated = model.with_sdlc_load(workspace, Ready(eval))
      let hydrated = if eval.workflow.source_origin != "default" &&
        updated.active_workspace_value().map(w => w.id) == Some(workspace) {
        let preset : WorkflowPreset = match eval.workflow.preset {
          "regulated-bpmn-v1" => RegulatedBpmnV1
          "lightweight-rfc-v1" => LightweightRfcV1
          "custom-file" => CustomProjectFile
          _ => OpenSpecSdlcV1
        }
        let score = Score::clamped(eval.workflow.min_scorecard)
        updated.update_active_mockup(ws => {
          let w1 = ws.with_preset(preset).with_min_scorecard(score)
          if w1.has_security_gate() != eval.workflow.require_security_gate {
            w1.toggle_security_gate()
          } else {
            w1
          }
        })
      } else {
        updated
      }
      (hydrated, [])
    }
    SdlcFailed(workspace, failure) =>
      if model.connection is Connected {
        (model.with_sdlc_load(workspace, Failed(failure_text(failure))), [])
      } else {
        (model, [])
      }
    ProjectShown({ project, surface, }) =>
      if surface == model.surface {
        // The program that asks for it also records it.
        model.show(project, record=false)
      } else {
        (model, [])
      }
    HashChanged(route) => {
      let open = route.project()
      let ws = route.workspace()
      let unchanged = open == model.open_id() &&
        (ws is None || ws == model.active_workspace_id())
      guard !unchanged else { (model, []) }
      let (resolved_route, reconciled) = model.reconcile_route(route)
      let target : NavTarget = { ..model.nav_target(), route: resolved_route, }
      let history = match model.open_id() {
        Some(_) => model.history.push(target)
        None => model.history.replace_current(target)
      }
      let next = { ..model, route: resolved_route, settings: Closed, history, }
      let effects : Array[Effect] = []
      let mut final_model = next
      if reconciled && route is WorkspaceRoute(_, _) {
        effects.push(ReplaceHash(resolved_route))
      }
      match resolved_route {
        WorkspaceRoute(pid, wid) =>
          match final_model.workspace_load(pid) {
            Some(Ready(Populated(_))) => {
              if model.connection is Connected && model.find(pid) is Some(_) {
                effects.push(
                  Call(RecordOpenWorkspace({ project: pid, workspace: wid, })),
                )
              }
              let (loaded, src_effects) = final_model.ensure_sources(pid, wid)
              final_model = loaded
              effects.append(src_effects)
            }
            _ => {
              if Some(pid) != model.open_id() {
                effects.append(model.record_open(pid))
              }
              let (loaded, ws_effects) = final_model.ensure_workspaces(pid)
              final_model = loaded
              effects.append(ws_effects)
            }
          }
        ProjectRoute(pid) => {
          if Some(pid) != model.open_id() {
            effects.append(model.record_open(pid))
          }
          let (loaded, ws_effects) = final_model.ensure_workspaces(pid)
          final_model = loaded
          effects.append(ws_effects)
        }
        NoRoute => ()
      }
      if model.loses_control(final_model) {
        effects.push(KeepFocus)
      }
      (final_model, effects)
    }
    WindowResized(window) => ({ ..model, window, }, [])
    ActionChosen(action) => model.choose(action)
    ProjectTreeToggled(id) =>
      if model.is_open_multi_workspace(id) {
        (model.toggle_project_collapsed(id), [])
      } else {
        (model, [])
      }
    PaletteOpened => model.open_palette()
    PaletteTyped(query) => model.search(query)
    PaletteMoved(direction) => model.move_selection(direction)
    PalettePointed(id) => model.point_at(id)
    PaletteEntered(seen~) => model.run_selection(seen)
    CloseDialog => model.close_dialog()
    DialogClosed(element) =>
      if model.dialog.element() == Some(element) {
        model.close_dialog()
      } else {
        (model, [])
      }
    PathTyped(path) =>
      match model.dialog {
        AddDialog(state=Typing | Refused(_), ..) =>
          ({ ..model, dialog: AddDialog(path~, state=Typing), }, [])
        _ => (model, [])
      }
    BrowseChosen =>
      match model.dialog {
        AddDialog(path~, state=Typing | Refused(_)) if model.surface is Desktop =>
          (
            { ..model, dialog: AddDialog(path~, state=Browsing), },
            [ChooseFolder],
          )
        _ => (model, [])
      }
    FolderChosen({ path: chosen, }) =>
      match model.dialog {
        AddDialog(path~, state=Browsing) => {
          let path = chosen.unwrap_or(path)
          ({ ..model, dialog: AddDialog(path~, state=Typing), }, [FocusPath])
        }
        // The user closed the dialog before the answer.
        _ => (model, [])
      }
    BrowseFailed(failure) =>
      match model.dialog {
        AddDialog(path~, state=Browsing) => {
          let state = Refused(failure_text(failure))
          ({ ..model, dialog: AddDialog(path~, state~), }, [FocusPath])
        }
        _ => (model, [])
      }
    AddSubmitted =>
      match model.dialog {
        AddDialog(path~, state=Typing | Refused(_)) if AddProject.enabled(model) &&
          !path.trim().is_empty() =>
          (
            { ..model, dialog: AddDialog(path~, state=Sending), },
            [Call(Add(path))],
          )
        _ => (model, [])
      }
    ProjectAdded(path~, added) =>
      if model.waits_for(path) {
        let { project, target, .. } = added
        let target_ws = match target {
          WorkspaceRoot(ws_id) => Some(ws_id)
          RepositoryOnly => None
        }
        let (closed, hide) = { ..model, notice: None, }.close_dialog()
        let (shown, show) = closed
          .with_project(project)
          .show(project.id, workspace=target_ws, record=true)
        (shown, [..hide, ..show])
      } else {
        // The user closed the dialog. The event `projects_changed` has the project.
        (model, [])
      }
    AddFailed(path~, failure) =>
      if model.waits_for(path) {
        let state = Refused(failure_text(failure))
        ({ ..model, dialog: AddDialog(path~, state~), }, [FocusPath])
      } else {
        (model, [])
      }
    ProjectRemoved(id) => {
      let projects = model.projects.map(projects => {
        projects.filter(project => project.id != id)
      })
      let history = model.history.prune_project(id)
      let mockups = model.mockups.filter(pair => pair.0 != id)
      let workspaces = model.workspaces.filter(pair => pair.0 != id)
      let sources = prune_removed_sources(
        model.workspaces,
        workspaces,
        model.sources,
      )
      let collapsed_projects = model.collapsed_projects.filter(pid => pid != id)
      if model.open_id() == Some(id) {
        (
          {
            ..model,
            projects,
            route: NoRoute,
            settings: Closed,
            history,
            mockups,
            workspaces,
            sources,
            collapsed_projects,
          },
          [ReplaceHash(NoRoute), KeepFocus],
        )
      } else {
        (
          {
            ..model,
            projects,
            history,
            mockups,
            workspaces,
            sources,
            collapsed_projects,
          },
          [KeepFocus],
        )
      }
    }
    RemoveFailed(id, failure) =>
      // Without the project, another call or another view removed it.
      if model.find(id) is Some(_) {
        (model.show_failure(failure), [])
      } else {
        (model, [])
      }
    StopConfirmed =>
      if model.dialog is ConfirmStop && StopApp.enabled(model) {
        let (model, effects) = model.close_dialog()
        ({ ..model, notice: None, }, [..effects, Call(Stop)])
      } else {
        (model, [])
      }
    CallFailed(failure) => (model.show_failure(failure), [])
    NoticeDismissed => model.dismiss_notice()
    PerspectiveTabMoved(perspective) => {
      let action = SetPerspective(perspective)
      guard action.enabled(model) else { (model, []) }
      let (next, effects) = model.do_action(action)
      (next, [..effects, Focus(PerspectiveTab(perspective))])
    }
    PlanViewChosen(plan_view) => {
      let target : NavTarget = { ..model.nav_target(), plan_view, }
      let history = model.history.push(target)
      ({ ..model, plan_view, history, }, [])
    }
    ReadModeChosen(read_mode) => ({ ..model, read_mode, }, [])
    ReviewDocChosen(review_doc) => {
      let target : NavTarget = { ..model.nav_target(), review_doc, }
      let history = model.history.push(target)
      ({ ..model, review_doc, history, }, [])
    }
    KnowledgeViewChosen(knowledge_view) => {
      let target : NavTarget = { ..model.nav_target(), knowledge_view, }
      let history = model.history.push(target)
      ({ ..model, knowledge_view, history, }, [])
    }
    DictGraphChosen(dict_graph) => ({ ..model, dict_graph, }, [])
    DictFormatChosen(dict_format) => ({ ..model, dict_format, }, [])
    DictQueryChanged(dict_query) => ({ ..model, dict_query, }, [])
    DictDraftLabelChanged(dict_draft_label) =>
      ({ ..model, dict_draft_label, dict_draft_error: None, }, [])
    DictDraftDefChanged(dict_draft_def) =>
      ({ ..model, dict_draft_def, dict_draft_error: None, }, [])
    DictConceptSubmitted => {
      let label_res : Result[ConceptLabel, String] = Ok(
        ConceptLabel(model.dict_draft_label),
      ) catch {
        Empty => Err("Enter a concept label.")
        TooLong(len) => Err("Concept label is too long (\{len}/60 characters).")
        ContainsControlChar(_) =>
          Err("Concept label cannot contain control characters.")
      }
      let def_res : Result[ConceptDefinition, String] = Ok(
        ConceptDefinition(model.dict_draft_def),
      ) catch {
        Empty => Err("Enter a concept definition.")
        TooLong(len) =>
          Err("Concept definition is too long (\{len}/240 characters).")
        ContainsControlChar(_) =>
          Err("Concept definition cannot contain control characters.")
      }
      match (label_res, def_res) {
        (Ok(label), Ok(definition)) =>
          match
            (model.connection, model.open_id(), model.active_workspace_value()) {
            (Connected, Some(project_id), Some(active_ws)) =>
              (
                { ..model, dict_draft_error: None, },
                [
                  Call(
                    CreateDictionaryConcept({
                      workspace: {
                        project: project_id,
                        workspace: active_ws.id,
                      },
                      pref_label: label.as_str(),
                      definition: definition.as_str(),
                      alt_labels: [],
                    }),
                  ),
                ],
              )
            _ => {
              let next = model.update_active_mockup(ws => {
                ws.add_local_concept(label, definition)
              })
              let next_graph = if next.dict_graph.matches(LocalPayments) {
                next.dict_graph
              } else {
                AllGraphs
              }
              (
                {
                  ..next,
                  dict_graph: next_graph,
                  dict_query: "",
                  dict_draft_label: "",
                  dict_draft_def: "",
                  dict_draft_error: None,
                },
                [],
              )
            }
          }
        (Err(msg), _) => ({ ..model, dict_draft_error: Some(msg), }, [])
        (_, Err(msg)) => ({ ..model, dict_draft_error: Some(msg), }, [])
      }
    }
    TermAuditResolved(audit_id) =>
      (model.update_active_mockup(ws => ws.resolve_term_audit(audit_id)), [])
    OpenConceptInDictionary(concept_id) => {
      let base = model.update_active_mockup(ws => {
        ws.close_inspector().select_concept(concept_id)
      })
      let target : NavTarget = {
        ..base.nav_target(),
        perspective: Knowledge,
        knowledge_view: Dictionary,
      }
      let history = base.history.push(target)
      (
        {
          ..base,
          perspective: Knowledge,
          knowledge_view: Dictionary,
          dict_graph: AllGraphs,
          dict_query: "",
          settings: Closed,
          history,
        },
        [],
      )
    }
    OpenBacklinkInReview(item_id, review_doc) => {
      let base = model.update_active_mockup(ws => {
        ws.close_inspector().select_item(item_id)
      })
      let target : NavTarget = {
        ..base.nav_target(),
        perspective: Review,
        review_doc,
      }
      let history = base.history.push(target)
      (
        { ..base, perspective: Review, review_doc, settings: Closed, history, },
        [],
      )
    }
    KbSourceChosen(kb_source) => ({ ..model, kb_source, }, [])
    KbQueryChanged(kb_query) => ({ ..model, kb_query, }, [])
    KbDocChosen(kb_doc) => {
      let doc = kb_document(kb_doc)
      if kb_doc_matches_filter(doc, model.kb_source, model.kb_query) {
        ({ ..model, kb_doc, }, [])
      } else {
        ({ ..model, kb_doc, kb_source: AllKbSources, kb_query: "", }, [])
      }
    }
    KbReadModeChosen(kb_read_mode) => ({ ..model, kb_read_mode, }, [])
    ToggleDocRead(doc_id) =>
      (model.update_active_mockup(ws => ws.toggle_doc_read(doc_id)), [])
    ReviewTabChosen(review_tab) =>
      (model.update_active_mockup(ws => ws.with_review_tab(review_tab)), [])
    ConceptSelected(active_concept) => {
      let next = model.update_active_mockup(ws => {
        ws.select_concept(active_concept)
      })
      let visible = match next.active_mockup().concept(active_concept) {
        Some(card) =>
          concept_matches_filter(card, next.dict_graph, next.dict_query)
        None => true
      }
      if visible {
        (next, [])
      } else {
        ({ ..next, dict_graph: AllGraphs, dict_query: "", }, [])
      }
    }
    NormalizeDeprecatedTerm =>
      (model.update_active_mockup(ws => ws.normalize_deprecated_term()), [])
    ReviewApproved =>
      (model.update_active_mockup(ws => ws.approve_selected_review()), [])
    ReviewRequestedChanges =>
      (
        model.update_active_mockup(ws => ws.request_changes_selected_review()),
        [],
      )
    ItemSelected(item_id) =>
      (model.update_active_mockup(ws => ws.open_inspector(item_id)), [])
    CloseInspector => {
      let ws = model.active_mockup()
      guard ws.inspector_open() else { (model, []) }
      let target = WorkflowItemTrigger(
        model.perspective,
        model.plan_view,
        ws.selected_item(),
      )
      (model.update_active_mockup(ws => ws.close_inspector()), [Focus(target)])
    }
    ResolveOpenGates(item_id) =>
      (model.update_active_mockup(ws => ws.resolve_open_gates(item_id)), [])
    AdvanceWorkflowItem(item_id) =>
      (model.update_active_mockup(ws => ws.advance_item(item_id)), [])
    SendBackWorkflowItem(item_id) =>
      (model.update_active_mockup(ws => ws.send_back_item(item_id)), [])
    OpenSettingsTab(tab) => {
      let base = { ..model, settings: Open(tab), brand_error: None, }
      if tab == Mounts {
        let (next, src_effects) = base.ensure_active_sources(force=true)
        (next, [FocusSettingsBack, ..src_effects])
      } else {
        (base, [FocusSettingsBack])
      }
    }
    SettingsTabChosen(tab) => {
      let base = { ..model, settings: Open(tab), brand_error: None, }
      if tab == Mounts {
        base.ensure_active_sources(force=true)
      } else {
        (base, [])
      }
    }
    CloseSettings =>
      ({ ..model, settings: Closed, brand_error: None, }, [KeepFocus])
    AppearanceCycled => {
      let appearance = model.appearance.next()
      ({ ..model, appearance, }, [StoreAppearance(appearance)])
    }
    BrandTitleChanged(raw) =>
      match BrandTitle::parse(raw) {
        Some(title) => {
          let brand : BrandConfig = { ..model.brand, title, }
          ({ ..model, brand, brand_error: None, }, [StoreBrand(brand)])
        }
        None =>
          (
            {
              ..model,
              brand_error: Some(
                "Enter a single-line title between 1 and 40 characters.",
              ),
            },
            [],
          )
      }
    BrandMarkChosen(mark) => {
      let brand : BrandConfig = { ..model.brand, mark, }
      ({ ..model, brand, brand_error: None, }, [StoreBrand(brand)])
    }
    BrandMonogramChanged(raw) =>
      match BrandMonogram::parse(raw) {
        Some(mono) => {
          let brand : BrandConfig = { ..model.brand, mark: Monogram(mono), }
          ({ ..model, brand, brand_error: None, }, [StoreBrand(brand)])
        }
        None =>
          (
            {
              ..model,
              brand_error: Some("Monogram must be 1 to 3 letters or digits."),
            },
            [],
          )
      }
    BrandEmojiChanged(raw) =>
      match BrandEmoji::parse(raw) {
        Some(emoji) => {
          let brand : BrandConfig = { ..model.brand, mark: Emoji(emoji), }
          ({ ..model, brand, brand_error: None, }, [StoreBrand(brand)])
        }
        None =>
          (
            {
              ..model,
              brand_error: Some(
                "Enter an emoji or short symbol (1 to 8 chars).",
              ),
            },
            [],
          )
      }
    BrandImageSelected(raw) =>
      match BrandImageUrl::parse(raw) {
        Some(img) => {
          let brand : BrandConfig = { ..model.brand, mark: CustomImage(img), }
          ({ ..model, brand, brand_error: None, }, [StoreBrand(brand)])
        }
        None =>
          (
            {
              ..model,
              brand_error: Some(
                "Choose a PNG, JPEG, WebP, or GIF image up to 96 KB.",
              ),
            },
            [],
          )
      }
    BrandReset => {
      let brand = BrandConfig::default()
      ({ ..model, brand, brand_error: None, }, [StoreBrand(brand)])
    }
    PresetChosen(preset) => {
      let next = model.update_active_mockup(ws => ws.with_preset(preset))
      let effects = next.persist_workflow_effect()
      (next, effects)
    }
    MinScorecardChosen(score) => {
      let next = model.update_active_mockup(ws => ws.with_min_scorecard(score))
      let effects = next.persist_workflow_effect()
      (next, effects)
    }
    StudioDiagramChosen(studio_diagram) =>
      (
        model.update_active_mockup(ws => ws.with_studio_diagram(studio_diagram)),
        [],
      )
    StudioFormatChosen(studio_format) =>
      (
        model.update_active_mockup(ws => ws.with_studio_format(studio_format)),
        [],
      )
    StudioStageChosen(studio_stage) =>
      (model.update_active_mockup(ws => ws.with_studio_stage(studio_stage)), [])
    StudioExtraInputToggled(stage, extra) =>
      (
        model.update_active_mockup(ws => ws.toggle_extra_input(stage, extra)),
        [],
      )
    StudioSourceEdited(source) =>
      (model.update_active_mockup(ws => ws.with_studio_source(source)), [])
    ToggleSecurityGate => {
      let next = model.update_active_mockup(ws => ws.toggle_security_gate())
      let effects = next.persist_workflow_effect()
      (next, effects)
    }
    ColorSchemeChosen(color_scheme) =>
      ({ ..model, color_scheme, }, [StoreColorScheme(color_scheme)])
    AppearanceChosen(appearance) =>
      ({ ..model, appearance, }, [StoreAppearance(appearance)])
    SidebarResized(sidebar_width) =>
      if sidebar_width == model.sidebar_width {
        (model, [])
      } else {
        ({ ..model, sidebar_width, }, [StoreSidebarWidth(sidebar_width)])
      }
    SecondarySidebarToggled => {
      let secondary_sidebar = model.secondary_sidebar.other()
      (
        { ..model, secondary_sidebar, },
        [StoreSecondarySidebar(secondary_sidebar)],
      )
    }
    SecondarySidebarResized(secondary_sidebar_width) =>
      if secondary_sidebar_width == model.secondary_sidebar_width {
        (model, [])
      } else {
        (
          { ..model, secondary_sidebar_width, },
          [StoreSecondarySidebarWidth(secondary_sidebar_width)],
        )
      }
    CompanionPanelToggled => {
      let companion_panel = model.companion_panel.other()
      ({ ..model, companion_panel, }, [StoreCompanionPanel(companion_panel)])
    }
  }
}

///|
/// Drops cached `SourcesLoad` entries whose owning project was removed from `workspaces`.
fn prune_removed_sources(
  before : ReadOnlyArray[(@app.ProjectId, WorkspaceLoad)],
  after : ReadOnlyArray[(@app.ProjectId, WorkspaceLoad)],
  sources : ReadOnlyArray[(@app.WorkspaceId, SourcesLoad)],
) -> ReadOnlyArray[(@app.WorkspaceId, SourcesLoad)] {
  let dropped : Array[@app.WorkspaceId] = []
  for pair in before {
    if !after.iter().any(kept => kept.0 == pair.0) {
      if pair.1 is Ready(Populated(set)) {
        for ws in set.workspaces() {
          dropped.push(ws.id)
        }
      }
    }
  }
  if dropped.is_empty() {
    sources
  } else {
    sources.filter(pair => !dropped.contains(pair.0))
  }
}

///|
/// The dialog waits for the answer of the server for this path.
fn Model::waits_for(self : Model, path : String) -> Bool {
  self.dialog is AddDialog(path=sent, state=Sending) && sent == path
}

///|
/// The model with these details of a project. A new project is the last one, as in the
/// list of the server.
fn Model::with_project(self : Model, project : @app.Project) -> Model {
  let projects = self.projects.unwrap_or([])
  let projects = if self.find(project.id) is Some(_) {
    projects.map(other => if other.id == project.id { project } else { other })
  } else {
    ReadOnlyArray::from_array([..projects, project])
  }
  { ..self, projects: Some(projects), }
}

///|
/// The command that does an effect.
fn Effect::command(
  self : Effect,
  emit : @cmd.Emit[Msg],
  connection : Connection,
) -> @cmd.Cmd {
  match self {
    Call(call) =>
      @cmd.custom_cmd(scheduler => {
        call.start(connection.client, msg => scheduler.add(emit(msg)))
      })
    ChooseFolder =>
      @cmd.custom_cmd(scheduler => {
        ask_folder(@proton_client.desktop, msg => scheduler.add(emit(msg)))
      })
    ShowDialog(element) => @dialog.show(element.id())
    HideDialog(element) => @dialog.close(element.id())
    ShowEntry(id) =>
      @cmd.custom_cmd(_ => show_element(id.element()), kind=@cmd.after_render)
    PushHash(route) => @nav.push_url(route.to_hash())
    ReplaceHash(route) => @nav.replace_url(route.to_hash())
    FocusPath =>
      @cmd.custom_cmd(_ => focus_element(add_path_id), kind=@cmd.after_render)
    FocusSettingsBack =>
      @cmd.custom_cmd(
        _ => focus_element(settings_back_id),
        kind=@cmd.after_render,
      )
    Focus(target) =>
      @cmd.custom_cmd(
        _ => focus_element_or_fallback(target.id(), main_title_id),
        kind=@cmd.after_render,
      )
    KeepFocus => keep_focus(main_title_id)
    FocusPrimarySidebarControl(state) => keep_focus(state.control_id())
    StorePrimarySidebar(state) =>
      @cmd.custom_cmd(_ => store_text(primary_sidebar_key, state.stored()))
    StoreSidebarWidth(width) =>
      @cmd.custom_cmd(_ => store_text(sidebar_width_key, width.stored()))
    StoreSecondarySidebar(state) =>
      @cmd.custom_cmd(_ => store_text(secondary_sidebar_key, state.stored()))
    StoreSecondarySidebarWidth(width) =>
      @cmd.custom_cmd(_ => {
        store_text(secondary_sidebar_width_key, width.stored())
      })
    StoreCompanionPanel(state) =>
      @cmd.custom_cmd(_ => store_text(companion_panel_key, state.stored()))
    StoreColorScheme(scheme) =>
      @cmd.custom_cmd(_ => store_text(color_scheme_key, scheme.stored()))
    StoreAppearance(appearance) =>
      @cmd.custom_cmd(_ => store_text(appearance_key, appearance.stored()))
    StoreBrand(brand) =>
      @cmd.custom_cmd(_ => store_text(brand_key, brand.stored()))
    EndConnection => @cmd.custom_cmd(_ => (connection.stopped)())
  }
}

///|
extern "js" fn focus_element(id : String) -> Unit =
  #| (id) => { document.getElementById(id)?.focus(); }

///|
extern "js" fn focus_element_or_fallback(
  id : String,
  fallback : String,
) -> Unit =
  #| (id, fallback) => {
  #|   const target = document.getElementById(id) ?? document.getElementById(fallback);
  #|   target?.focus({ preventScroll: true });
  #| }

///|
/// Scrolls the list around the element, and only if a part of it is not visible.
extern "js" fn show_element(id : String) -> Unit =
  #| (id) => { document.getElementById(id)?.scrollIntoView({ block: "nearest" }); }

///|
/// The text that the browser kept for this key, or an empty text. A browser that blocks
/// the storage throws.
extern "js" fn stored_text(key : String) -> String =
  #| (key) => {
  #|   try { return localStorage.getItem(key) ?? ""; }
  #|   catch { return ""; }
  #| }

///|
/// Keeps the text for the next page. With a browser that keeps nothing, the next page
/// starts without it.
extern "js" fn store_text(key : String, text : String) -> Unit =
  #| (key, text) => { try { localStorage.setItem(key, text); } catch {} }

///|
/// Puts the focus in the element with this ID, if no control has it after the next
/// change of the page.
fn keep_focus(id : String) -> @cmd.Cmd {
  @cmd.custom_cmd(_ => keep_focus_in(id), kind=@cmd.after_render)
}

///|
/// A control of a sheet that closes still has the focus, but it is inert.
extern "js" fn keep_focus_in(id : String) -> Unit =
  #| (id) => {
  #|   const at = document.activeElement;
  #|   if (!at || at === document.body || at.closest("[inert]")) {
  #|     document.getElementById(id)?.focus({ preventScroll: true });
  #|   }
  #| }

///|
/// The model after a message, and the command that does the rest, with the connection
/// to the server.
pub fn update(
  model : Model,
  msg : Msg,
  emit : @cmd.Emit[Msg],
  connection : Connection,
) -> (Model, @cmd.Cmd) {
  let (next, effects) = step(model, msg)
  let cmds = effects.map(effect => effect.command(emit, connection))
  cmds.push(sync_studio_editor_cmd(next, emit))
  cmds.push(sync_sidebar_splitter_cmd(emit))
  (next, @cmd.batch(cmds))
}