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

未关闭
#11,044 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
48/100
Issue 类型
功能
描述清晰度
基本清楚
活跃度
活跃
技术栈
typescript

调研方向

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.

由索引模型根据 Issue 内容生成。

描述

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.
主要语言
TypeScript
星标
16.7k
派生
808
平均合并
21 小时 22 分钟
30 天内合并 PR
486

环境准备

这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

Effect-TS/effect 的其他 Issue

查看 Effect-TS/effect 的全部 Issue

相似的 Issue

更多 TypeScript Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。