`@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 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
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分
マージ済み PR(30日)
486

環境構築

このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

Effect-TS/effect のほかの issue

Effect-TS/effect の issue をすべて見る

似ている issue

TypeScript の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。