`@effect/ui` (Effect-TS/ui): warn in development when a Command's own optimistic patch unmounts the instance that issued it

Abierto
#11,044 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
48/100
Tipo de issue
Nueva funcionalidad
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
typescript

Línea de trabajo

Start with packages/ui/src/Command.ts for run lifetimes, Query.ts for optimistic patch behavior, and MessageLog.ts for interruption reasons and causedBy. Reproduce the case with the provided test in packages/ui/test and inspect its timeline. Done means a development-only warning identifies an issuing instance unmounted by its own update, while ordinary unmount interruptions stay quiet; the issue does not name the relevant test file.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Written with Claude Code for @magoz, from an app we're building on Effect UI.

What is the problem this feature would solve?

A list row that deletes itself with an optimistic patch cancels its own delete. The patch removes the row from the query's value as the Command is issued, the list renders without the row, the row unmounts, and the run, owned by the row, is interrupted before its body starts. The interrupt drops the patch, so the row comes back, and the server was never asked. Nothing is logged to the console.

This is the documented lifetime: "Every run is owned by the instance that issued it and ends with it, whatever its kind or mode" (Command.ts#L1316-L1319), and "A failure, an interrupt or a defect drops it at once" for a patch (Query.ts#L1473-L1482). So this isn't a bug report. But the self-removing row follows naturally from writing a Command and its patch beside the row's button, and what the user sees, a row that flickers and stays, doesn't point at the lifetime rule. It took us a while to find, and we moved the Command up to the list. The MessageLog has the cause (CommandInterrupted with reason: "unmount", MessageLog.ts#L707-L733), and DevTools shows it, if you already know to look there.

Reproduced on Effect-TS/ui main at dec1ca9 with this test in its packages/ui/test (effect 4.1.6). It was item 4 of Effect-TS/ui#532, filed here as Effect-TS/ui#593 asks:

import { Command, Component, Query, UiSchema } from "@effect/ui"
import { Locator, TestHost } from "@effect/ui/testing"
import { assert, describe, it } from "@effect/vitest"
import { Effect, Layer, Schema } from "effect"
import { AsyncResult } from "effect/reactivity"
import { TestClock } from "effect/testing"

const Todo = Schema.Struct({ id: Schema.String, title: Schema.String })
const db = { todos: [{ id: "a", title: "A" }, { id: "b", title: "B" }] }

class GetTodos extends Query.Service<GetTodos>()("todos/GetTodos", {
  success: Schema.Array(Todo),
  staleTime: "1 minute"
}) {
  static readonly layer = this.toLayer(() => Effect.sync(() => db.todos))
}

class DeleteTodo extends Command.Service<DeleteTodo>()("todos/DeleteTodo", {
  args: { id: Schema.String },
  optimistic: ({ id }) => [GetTodos.patch({}, (todos) => todos.filter((todo) => todo.id !== id))]
}) {
  static readonly layer = this.toLayer(({ id }) =>
    Effect.sleep("50 millis").pipe(
      Effect.andThen(() => (db.todos = db.todos.filter((todo) => todo.id !== id)))
    )
  )
}

const RowMessage = UiSchema.TaggedEnum({ ClickedDelete: {} })
const Row = Component.define({
  name: "Row",
  props: Schema.Struct({ id: Schema.String, title: Schema.String }),
  model: Schema.Struct({}),
  message: RowMessage
}).make({
  init: () => ({}),
  update: ($, message) =>
    RowMessage.match(message, {
      ClickedDelete: () => $.run(DeleteTodo.make({ id: $.props.id }))
    }),
  view: (h) => h.el("li").on("click", RowMessage.ClickedDelete()).children(h.props.title)
})

const List = Component.define({
  name: "List",
  model: Schema.Struct({}),
  message: UiSchema.TaggedEnum({}),
  queries: { todos: { query: GetTodos, args: () => ({}) } }
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    h.el(
      "ul",
      AsyncResult.match(h.queries.todos, {
        onInitial: () => [],
        onFailure: () => [],
        onSuccess: ({ value }) => value.map((todo) => Row(h, { key: todo.id, props: todo }))
      })
    )
})

describe("a row whose optimistic patch removes it", () => {
  it.effect("cancels its own delete", () =>
    Effect.gen(function*() {
      const root = yield* TestHost.mount(List, {})
      yield* TestHost.settle
      Locator.fire(root.get(Locator.text("A", { exact: true })), "click")
      yield* TestHost.settle
      yield* TestClock.adjust("1 second")
      yield* TestHost.settle
      console.log(TestHost.formatTimeline(root.log()))
      assert.deepStrictEqual(db.todos.map((todo) => todo.id), ["b"])
    }).pipe(
      Effect.provide(DeleteTodo.layer.pipe(Layer.provideMerge(GetTodos.layer))),
      Effect.scoped,
      Effect.provide(TestHost.layer())
    ))
})
#7 /List/Row[a] Update ClickedDelete (dom click) -> todos/DeleteTodo
    #8 /List QueryChanged
#9 /List/Row[a] Unmounted
#10 /List QueryChanged
#11 /List/Row[a] CommandInterrupted todos/DeleteTodo (unmount)
#12 /List/Row[a] Mounted

AssertionError: expected [ 'a', 'b' ] to deeply equal [ 'b' ]

There's no CommandStarted: the body never ran, and nothing reached the console.

What is the feature you are proposing to solve the problem?

A development-only warning when a run is interrupted with reason: "unmount" and its own optimistic patch is what removed its instance, or, more broadly, when the unmount comes from the render of the update that issued the run. Something like:

Command "todos/DeleteTodo" was interrupted before it started: its instance /List/Row[a] unmounted in the render of the update that issued it (its optimistic patch removed it). A run ends with the instance that issued it; issue it from a component that outlives the change, such as the list.

Keeping it to these cases leaves out the ordinary ones, such as navigating away from a page whose save is still running, which the lifetime rule is for.

A smaller, related note: in this repro Unmounted (#9) and CommandInterrupted (#11) have no causedBy, while the patch's QueryChanged (#8) has causedBy: 7. InterruptReason's doc says causedBy is set for every reason but "self" (MessageLog.ts#L721-L722). With it, the warning could follow the chain back to the issuing update.

What alternatives have you considered?
  • Moving the Command to the list, as we did. It's the fix, but the warning is about finding it.
  • A line in LLMS.md's Commands sections. The rule is in Command.Service's JSDoc, but the guide doesn't state it, so an agent reading only the guide writes this row. It helps, but a warning also covers code written without reading either.
  • A lint rule. It can't see that a patch removes its own row.
Lenguaje dominante
TypeScript
Estrellas
16.7k
Forks
808
Merge medio
21 h 22 min
PR fusionados (30 d)
486

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de Effect-TS/effect

Todos los issues de Effect-TS/effect

Issues similares

Más issues de TypeScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.