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

Đang mở
#11,044 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức phù hợp với người mới
48/100
Loại issue
Tính năng
Độ rõ ràng
Khá rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
typescript
Lĩnh vực
developer-experience

Hướng nghiên cứu

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.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

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.
Ngôn ngữ chính
TypeScript
Star
16.7k
Fork
808
Merge trung bình
21 giờ 22 phút
Pull request đã merge (30 ngày)
486

Chuẩn bị môi trường

Dự án này không cung cấp dev container, Dockerfile hay hướng dẫn đóng góp, nên bạn cần tự thiết lập môi trường: hãy bắt đầu từ README và xem hướng dẫn đóng góp lần đầu của chúng tôi để biết các bước chung.

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của Effect-TS/effect

Tất cả issue của Effect-TS/effect

Issue tương tự

Thêm issue về TypeScript

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.