From 531bf320db6414584d26534dc8a5fa8df3e49683 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 19:19:03 +0000 Subject: [PATCH 01/13] FIX-2429: task board changes reach open screens as board notices Every change a task collection makes (the onChange adapter in getOrCreateTaskCollection) also publishes a `board` notice on the topic of the session that filed the row, narrowed to the board, through a new engine seam on the block context. The board views in Shift Manager, the Teammates and claude-code-style labs, and a live BoardList read on those notices through client.subscribe / useSubscription, with today's pace as the fallback where push can miss a change. Goal check: goals/task-board/a-settled-task-reaches-the-board/. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn --- .changeset/board-notices.md | 16 + apps/docs/docs/api/client.md | 2 +- apps/docs/docs/api/react.md | 5 +- apps/docs/docs/client/react.md | 6 +- .../docs/docs/orchestration/task-substrate.md | 14 + apps/docs/docs/workforce/ui.md | 8 +- apps/docs/guides/realtime.md | 26 +- .../a-settled-task-reaches-the-board/goal.md | 36 ++ .../a-settled-task-reaches-the-board/run.mts | 578 ++++++++++++++++++ labs/claude-code-style/src/adapter.ts | 55 +- .../test/watch-tasks.test.ts | 68 +++ labs/teammates/src/adapter.ts | 96 ++- labs/teammates/test/run-link.test.ts | 112 +++- packages/contracts/src/types/change-notice.ts | 5 +- packages/core/src/types/block.ts | 8 + packages/core/src/types/board-notice.ts | 46 ++ packages/core/src/types/index.ts | 4 + packages/engine/src/bus/board-notice.ts | 28 + packages/engine/src/bus/publish-writes.ts | 12 + .../src/context/createExecutionContext.ts | 7 + .../engine/test/bus/board-notice-seam.test.ts | 91 +++ packages/orchestration/README.md | 7 +- .../src/tasks/collection/get-or-create.ts | 20 + .../test/tasks/board-notice.test.ts | 110 ++++ packages/react/README.md | 13 +- .../react/src/components/panels/BoardList.ts | 25 +- packages/react/src/components/panels/reads.ts | 73 +-- packages/react/src/hooks/useSubscription.ts | 14 +- packages/react/test/board-list.test.ts | 341 +++-------- packages/react/test/useSubscription.test.ts | 13 + .../src/components/TaskBoardMeta.tsx | 59 +- .../src/components/TasksPanel.tsx | 82 +-- .../src/lib/conversation-tasks.ts | 21 +- .../test/conversation-tasks-panel.test.tsx | 75 ++- .../test/task-card-in-feed.test.tsx | 55 +- 35 files changed, 1641 insertions(+), 490 deletions(-) create mode 100644 .changeset/board-notices.md create mode 100644 goals/task-board/a-settled-task-reaches-the-board/goal.md create mode 100644 goals/task-board/a-settled-task-reaches-the-board/run.mts create mode 100644 labs/claude-code-style/test/watch-tasks.test.ts create mode 100644 packages/core/src/types/board-notice.ts create mode 100644 packages/engine/src/bus/board-notice.ts create mode 100644 packages/engine/test/bus/board-notice-seam.test.ts create mode 100644 packages/orchestration/test/tasks/board-notice.test.ts diff --git a/.changeset/board-notices.md b/.changeset/board-notices.md new file mode 100644 index 0000000000..4941a33609 --- /dev/null +++ b/.changeset/board-notices.md @@ -0,0 +1,16 @@ +--- +"@flow-state-dev/orchestration": minor +"@flow-state-dev/engine": minor +"@flow-state-dev/react": minor +"@flow-state-dev/core": patch +"@flow-state-dev/contracts": patch +"@flow-state-dev/shift-manager": patch +--- + +A task board's change reaches every open view of the board, from whichever session or process settles the task (FIX-2429). + +- **orchestration:** every change to a board built by `getOrCreateTaskCollection` also publishes a `board` change notice on the topic of the session that filed the row (`Task.filer`, else the ledger's legacy filer, else the running session), narrowed to the board's `collectionId`. A screen subscribes `topic.session(conversationId, { resource: "tasks" })` and reads again. Nothing to wire: the `task-change` item is unchanged. +- **engine:** the block context carries the seam that publishes a board notice on the running request's bus, under its tenant, with the request as `origin`. +- **react:** **Breaking for a hand-built client slice:** a live `BoardList`'s `client` takes `subscribe` in place of `sessions.stream`. A client from `createClient` works as before. The list now hears a task that settles in another session or process, never wakes on a reply streaming in the session, and reads every 3 s where push can miss a change. `useSubscription` takes `client`, for an app that builds its own client. +- **core / contracts:** `ChangeKind` gains `"board"`; `publishBoardChange` and `BOARD_NOTICE_SEAM` (framework-facing) in `@flow-state-dev/core/types`. +- **shift-manager:** the conversation's task panel and task cards read on board notices; they keep their 3 s timer only while a task is open, and only where push can miss a change. diff --git a/apps/docs/docs/api/client.md b/apps/docs/docs/api/client.md index ec3dbaec98..a5cc2aa5bd 100644 --- a/apps/docs/docs/api/client.md +++ b/apps/docs/docs/api/client.md @@ -491,7 +491,7 @@ The topics come from `topic`, which `@flow-state-dev/client` and `@flow-state-de Each takes an optional `{ resource }` to watch one resource under the scope. A topic without one also hears changes narrowed to a resource under it. User and org topics name no id: the server fills them in from the signed-in caller, so a client can't ask for someone else's. -A notice's `kind` is `"items"`, `"request"`, `"run"` or `"resync"`; `origin.requestId` names the request that made the change, when a request did. +A notice's `kind` is `"items"`, `"request"`, `"run"`, `"board"` (a task on one of the session's boards changed, on a topic narrowed to the board) or `"resync"`; `origin.requestId` names the request that made the change, when a request did. **On a host with push** (`serve()` from `@flow-state-dev/node`, `fsdev dev` and `fsdev serve`), the client opens one WebSocket, shared by every `subscribe` call on that client. It asks the server for each topic first, through the client's own `fetcher`, so a bearer token your fetcher adds is what proves who the socket is. A topic the caller may not read is left out, the same way a session that doesn't exist is: `onChange` never hears about it, and with `pollIntervalMs` the client asks for it again at each tick, so access given back recovers without a remount. Each connect and reconnect calls `onChange(null)` once. The server closes a socket after an hour and the client reconnects, which checks every topic again. diff --git a/apps/docs/docs/api/react.md b/apps/docs/docs/api/react.md index 1b1bff6b46..0fa452e774 100644 --- a/apps/docs/docs/api/react.md +++ b/apps/docs/docs/api/react.md @@ -178,10 +178,10 @@ Use `source: { response }` to consume a pre-fetched POST stream (inline streamin ### `useSubscription(topics, read, options?)` -Runs `read` again when something under `topics` changes, through the provider's client and [`fsd.subscribe`](/docs/api/client#fsdsubscribetopics-options). +Runs `read` again when something under `topics` changes, through the provider's client (or `options.client`) and [`fsd.subscribe`](/docs/api/client#fsdsubscribetopics-options). ```ts -useSubscription([topic.session(sessionId)], refresh, { pollIntervalMs: 3000 }); +useSubscription([topic.session(sessionId, { resource: "tasks" })], refresh, { pollIntervalMs: 3000 }); ``` | Argument | Type | Notes | @@ -190,6 +190,7 @@ useSubscription([topic.session(sessionId)], refresh, { pollIntervalMs: 3000 }); | `read` | `(notice: WireNotice \| null) => unknown` | The screen's read. One runs at a time, and at most one more waits. Gets the notice that woke it, or `null` when the screen should read everything again: after a connect or a reconnect, on a timer tick, and when push starts or stops reaching every server process. It also gets `null` when several changes arrived during one read (one follow-up read covers them all). | | `options.pollIntervalMs` | `number` | Read at this pace wherever push can miss a change. Omitted, no timer. | | `options.enabled` | `boolean` | `false` subscribes nothing. Default `true`. | +| `options.client` | `Pick` | Your own client, when you build one with its own `fetcher`, so the socket signs in the same way. Pass a stable reference. Default: the provider's client. | Returns nothing. It doesn't read on mount. diff --git a/apps/docs/docs/client/react.md b/apps/docs/docs/client/react.md index b625ebad7e..23010b739a 100644 --- a/apps/docs/docs/client/react.md +++ b/apps/docs/docs/client/react.md @@ -160,12 +160,14 @@ const refresh = useCallback( [sessionId], ); -useSubscription([topic.session(sessionId)], refresh, { pollIntervalMs: 3000 }); +useSubscription([topic.session(sessionId, { resource: "tasks" })], refresh, { pollIntervalMs: 3000 }); ``` +The topic is narrowed to the `tasks` board, so a reply streaming in the session doesn't wake the read; a task that settles in another session still does (see [Task boards](/guides/realtime#task-boards)). + On the Node host the read runs as soon as the change is saved, over a WebSocket; on a host with no push it runs every `pollIntervalMs`. A burst of changes runs it once more after the read in flight finishes, not once per change. The read gets the notice that woke it (`{ topic, kind, origin? }`), or `null` when the screen should read everything again: after a connect or a reconnect, on a timer tick, and when push starts or stops reaching every server process. Act on `kind` when the screen only cares about some changes, and read everything on `null`. Leave `pollIntervalMs` out for no timer. `enabled: false` subscribes nothing. -The hook doesn't read on mount; keep the first read where the screen already makes it. It uses the provider's client, so the provider's `fetcher` signs the socket in. See [`fsd.subscribe`](/docs/api/client#fsdsubscribetopics-options) for which topics a caller hears. +The hook doesn't read on mount; keep the first read where the screen already makes it. It uses the provider's client, so the provider's `fetcher` signs the socket in. An app that builds its own client passes it as `client` instead. See [`fsd.subscribe`](/docs/api/client#fsdsubscribetopics-options) for which topics a caller hears. ### Background work diff --git a/apps/docs/docs/orchestration/task-substrate.md b/apps/docs/docs/orchestration/task-substrate.md index 92ecb620d9..adf1a2e7fc 100644 --- a/apps/docs/docs/orchestration/task-substrate.md +++ b/apps/docs/docs/orchestration/task-substrate.md @@ -545,6 +545,20 @@ The `task` snapshot is the post-mutation row minus the fields the substrate keep UIs stay in sync off that stream rather than by polling. The `` component and the DevTool subscribe to `task-change` items, filter by `collectionId`, and rebuild the board's state from them. You don't wire any of it up: every collection `getOrCreateTaskCollection` hands you emits these items itself. +### Board notices + +The item lands on the stream of the session that made the change. A task often settles somewhere else: in its own task session, or on another process. So every change also publishes a board notice. It goes on the topic of the session that filed the row (the row's filer, or the running session for a board that hands nothing out), narrowed to the board's `collectionId`, with kind `board`. It carries no rows. A screen subscribes `topic.session(conversationId, { resource: "tasks" })` with `client.subscribe` or `useSubscription`, and reads the board again when one arrives: + +```ts +useSubscription( + [topic.session(conversationId, { resource: "tasks" }), topic.session(conversationId, { resource: "plan" })], + refresh, // your board read, run again on each notice + { pollIntervalMs: 3000 }, +); +``` + +Subscribe each ledger your read returns. Workforce's `listTasks_tasks` read merges the conversation board with its planning worker's steps, so its screens subscribe `tasks` and `plan`. Because the topic is narrowed, a reply streaming in the conversation never wakes the screen. The session stream hears board notices on its topic and ignores them. As with any notice, `pollIntervalMs` is the fallback wherever push can't reach (see [Keeping a screen current](/guides/realtime#task-boards)). + ## Related pages - [Task board](./task-board.md) — the concurrent drain built on a TaskCollection. diff --git a/apps/docs/docs/workforce/ui.md b/apps/docs/docs/workforce/ui.md index d200621a1a..2b1a7746a8 100644 --- a/apps/docs/docs/workforce/ui.md +++ b/apps/docs/docs/workforce/ui.md @@ -114,15 +114,13 @@ import { BoardList } from "@flow-state-dev/react"; /> ``` -With `live`, the list follows the session you pass and reads the board again whenever that session records a change to it. A task filed in a conversation is recorded in that conversation's session, so pass the conversation's id, as above. Each new task then shows up in every tab that has the list open. +With `live`, the list reads the board again whenever a task on it changes, from whichever session or server process the change comes. Pass the id of the session that files the tasks, usually the conversation, as above. A task filed there, and the same task settling later in its delegate's own task session, both show up in every tab that has the list open. A reply streaming in the conversation doesn't make the list read. -The reads and the live stream both go through `client`, so the stream carries the same credential to the same server as the reads. A client that can only read (it has `resources.listCollectionItems` but no `sessions.stream`) can't take `live`, and TypeScript rejects that pair. +The reads and the live subscription both go through `client`, so the subscription carries the same credential to the same server as the reads. A client that can only read (it has `resources.listCollectionItems` but no `subscribe`) can't take `live`, and TypeScript rejects that pair. Rows already on screen stay there while the list reads again. -A change recorded in a different session does not reach a live list until something makes it read again: a remount, a reload, or the next change in the session it follows. A delegate working a task in its own task session is the usual example. So `live` suits watching tasks arrive as they're filed. To see where the work has got to, read the board on mount, as `BoardColumns` does. - -Each live list holds its own connection to its session's stream while it is mounted, the same kind [`useSession`'s `live`](../client/react.md#hearing-requests-you-didnt-send) opens. A page that also follows that session with `useSession(..., { live: true })` holds two connections to it. If the server doesn't offer the stream, or refuses it, the list reads once, as if you hadn't asked, with no error. +A live list shares its client's one connection with every other subscription on that client (see [Keeping a screen current](/guides/realtime)). On a host that can't push, or while the connection is down, it reads every few seconds instead, so it never goes stale for long. Each row shows the task's `title` (its `goal` if there is no title, its `id` if there is neither), its status word, and the assignee when there is one. The words are the ones the columns are headed with (`pending`, `in_progress`, and so on). A task in a status the list doesn't recognise shows with its own word. No row is hidden. A row without a `createdAt` follows the dated ones. diff --git a/apps/docs/guides/realtime.md b/apps/docs/guides/realtime.md index 10972839f4..7ff16b4b6b 100644 --- a/apps/docs/guides/realtime.md +++ b/apps/docs/guides/realtime.md @@ -29,17 +29,17 @@ function TaskList({ sessionId }: { sessionId: string }) { ); useEffect(() => void refresh(), [refresh]); // the first read - useSubscription([topic.session(sessionId)], refresh, { pollIntervalMs: 3000 }); + useSubscription([topic.session(sessionId, { resource: "tasks" })], refresh, { pollIntervalMs: 3000 }); return
    {tasks.map((task) =>
  • {task.title}
  • )}
; } ``` -On the Node host, `refresh` runs as soon as the change is saved: the server sends the notice once the change can be read, and no timer is involved, so the delay is the network and your read. A burst of changes runs it once more after the read in flight finishes, not once per change. The hook doesn't read on mount, so keep the first read where your screen already makes it. +On the Node host, `refresh` runs as soon as the change is saved: the server sends the notice once the change can be read, and no timer is involved, so the delay is the network and your read. A burst of changes runs it once more after the read in flight finishes, not once per change. The hook doesn't read on mount, so keep the first read where your screen already makes it. It subscribes through the provider's client; an app that builds its own client, with its own `fetcher`, passes it as `client` so the socket signs in the same way. | Topic | What changes it covers | |-------|------------------------| -| `topic.session(id)` | One session: its requests, their items, and runs started under it. | +| `topic.session(id)` | One session: its requests, their items, runs started under it, and changes to its task boards. | | `topic.user()` | The signed-in user's own scope. | | `topic.org()` | The signed-in user's organization. | @@ -56,7 +56,25 @@ useSubscription([topic.session(sessionId)], (notice) => { }); ``` -`kind` is `"items"`, `"request"`, `"run"` or `"resync"`. Read everything on `null` and on `"resync"`: the screen may have missed something. +`kind` is `"items"`, `"request"`, `"run"`, `"board"` or `"resync"`. Read everything on `null` and on `"resync"`: the screen may have missed something. + +Narrowing the topic does the same job with less code. A screen subscribed to `topic.session(id, { resource: "tasks" })` only hears changes to that board, so a long reply never wakes it. + +## Task boards + +A task board's change is announced on the session that filed the task, narrowed to the board, whichever session or process made the change. A conversation's delegate settles its task in a task session of its own, and the conversation's board screen still hears of it at once. Subscribe the conversation's topic narrowed to each board your read returns: + +```ts +useSubscription( + [topic.session(conversationId, { resource: "tasks" }), topic.session(conversationId, { resource: "plan" })], + refresh, + { pollIntervalMs: 3000 }, +); +``` + +Workforce's `listTasks_tasks` read returns the conversation's board and its planning worker's own steps, which sit on the `plan` board, so a screen of that read subscribes both. A flow with no planning worker never announces anything on `plan`, so the extra topic costs nothing. + +`BoardList` with `live` does this for you, for the one board it draws. Its `client` needs `subscribe` (see [A board as a list](/docs/workforce/ui#a-board-as-a-list)). ## Outside React diff --git a/goals/task-board/a-settled-task-reaches-the-board/goal.md b/goals/task-board/a-settled-task-reaches-the-board/goal.md new file mode 100644 index 0000000000..9ef957d781 --- /dev/null +++ b/goals/task-board/a-settled-task-reaches-the-board/goal.md @@ -0,0 +1,36 @@ +# task-board › a settled task reaches the board + +**Issue:** FIX-2429 (epic FIX-2367). Its spec's goal: `specs/issues/FIX-2429/SPEC.md` → "The goal, and how we'll know it's met". + +**Outcome:** On a long-lived host, a change to a conversation's task board, written by any session on any process, shows on every open view of that board within a second, and a view reads nothing between changes. Wherever push can miss a change, the same views keep a timer and miss nothing. + +**Input:** Real `serve()` hosts on bound ports, behind a bearer-token sign-in, and real WebSocket clients. One user's conversation on a Workforce session board (`desk`, worker `lead`), whose turn runs no model: it files tasks for a handler delegate (`eng.doer`, which takes 1.5 s), files a plan step for itself (a 1.5 s step turn), or streams a 3 s reply that touches no task. Three board views of the conversation, each on its own client: the Teammates lab adapter's `watchTasks`, the claude-code-style lab adapter's `watchTasks` (the merged `listTasks_tasks` read, with no session stream beside it), and a live `BoardList`'s read (`client.subscribe` on `topic.session(id, { resource: "tasks" })`, `listCollectionItems` on mount and on each wake, at its 3 s fallback pace). Legs a and c run in memory, leg a on FIX-2426's crossing double (`goals/lib/crossing-bus.mts`); leg b runs two registries over one real Postgres (`goals/lib/postgres.mts`), each with its own Postgres bus. Held out: a second conversation of the same user, whose task settles during leg a's idle window and must not read the first's board; every id is stamped per run. + +**Signal:** +- `a:within-1s` — each view shows the delegate's task `completed`, and the Teammates view its run's link, less than 1000 ms after the change can be read from the store (polled every 5 ms). The task settles in its own task session. +- `a:plan-step` — the claude-code-style view (the merged read) shows the conversation's plan step `completed` less than 1000 ms after the store. +- `a:0-reads` — over a 10 s window, starting after every view's socket said `crosses: true` and with a task held open, each view makes 0 board reads (`/reads/listTasks_tasks`, `/resources/tasks`), while a reply streams in the conversation and the second conversation files and settles a task. +- `b:within-1s` — as `a:within-1s`, the task released and settled on process 2 (graded: the delegate ran there and nowhere else); the views are on process 1. +- `b:0-reads` — as `a:0-reads`, over 10 s from each view's first `crosses: true` frame, which on the Postgres bus waits for its first ping. +- `c:within-a-poll` — on a host with `push: false`, each view shows the task `completed` within its own poll interval plus 1 s (Teammates 1.5 s, claude-code-style 2 s, `BoardList` 3 s). + +**Anti-game:** Not `publish` calls and not frames sent: every grade is what a view's own callback or read returned, timed against the store, or how many board reads its client's fetcher sent. The socket taps only time the start of the idle windows. Real sockets against bound ports, not an in-process fetch; two registries for leg b, not two clients of one. Each graded list is floored with `tell.over`. The `BoardList` view drives the call shape `BoardList` makes rather than rendering React in Node; that the component makes exactly that call (the narrowed topic, its pace, a read on mount and on each wake, coalesced) is proven by `packages/react/test/board-list.test.ts`. The plan step is graded on the claude-code-style view because the Teammates view also draws each `task-change` its conversation's own stream carries, which a step worked in the conversation's request would reach without any board notice. + +**Model:** n/a, model-free (handler turns settle every task). + +**Run:** `pnpm tsx goals/task-board/a-settled-task-reaches-the-board/run.mts`. `GOAL_LEGS=a,b,c` runs some legs. Leg b needs `initdb` and `pg_ctl`, or `FSD_DB_URL`. + +**Controls:** each runs leg a with a scratch patch applied as the process loads (`goals/lib/module-patch.mts`). +- `GOAL_CONTROL=running-session` — the board notice goes on the session that wrote, not the one that filed. Must FAIL `a:within-1s`. +- `GOAL_CONTROL=whole-topic` — the two lab views subscribe the conversation's whole topic. Must FAIL `a:0-reads`. +- `GOAL_CONTROL=tasks-only` — the merged read's views subscribe `tasks` alone. Must FAIL `a:plan-step`. +- Today's `main` (the parent of this change) has no board notice and no `client.subscribe` in the labs, so this script doesn't load there; on it the claude-code-style list reads every 2 s whatever happens, which is what `a:0-reads` would catch. The three controls stand in for its red state. + +## Verdict log +| Date | Commit | Model | Verdict | Notes | +|------|--------|-------|---------|-------| +| 2026-11-03 | fix/FIX-2429-board-notices (pre-commit) | n/a | FAIL | b: the Teammates view showed the run's link 2075 ms after the store. Its merge kept the conversation's own copy of a row over the board read's whenever the read named no `updatedAt`, which `listTasks` never does; leg a passed only because the read landed before the stream's copy. Fixed in the adapter (the read's fields win), with a regression test in `labs/teammates/test/run-link.test.ts` | +| 2026-11-03 | fix/FIX-2429-board-notices (pre-commit) | n/a | PASS | a: 0 reads in 10 s on 3 views (a reply streaming, another conversation's task settled); completed shown 96 / 44 / 16 ms, link 50 ms; plan step 48 ms · b (initdb): settled on p2, 0 reads in 10 s; shown 140 / 50 / 17 ms, link 31 ms · c: no push, shown 447 ms (bound 2500), 1966 ms (3000), 968 ms (4000) | +| 2026-11-03 | fix/FIX-2429-board-notices (pre-commit) | n/a | FAIL (expected) | `running-session`: `a:within-1s` only (Teammates showed the run's link 1661 ms after the store: the link is written in the run's session, so its notice went there; the ending still reached the conversation through the filer's own notice write) | +| 2026-11-03 | fix/FIX-2429-board-notices (pre-commit) | n/a | FAIL (expected) | `whole-topic`: `a:0-reads` only (Teammates 18 reads, claude-code-style 18 in 10 s) | +| 2026-11-03 | fix/FIX-2429-board-notices (pre-commit) | n/a | FAIL (expected) | `tasks-only`: `a:plan-step` only (the step never showed completed within 4 s) | diff --git a/goals/task-board/a-settled-task-reaches-the-board/run.mts b/goals/task-board/a-settled-task-reaches-the-board/run.mts new file mode 100644 index 0000000000..1e7c0ae29b --- /dev/null +++ b/goals/task-board/a-settled-task-reaches-the-board/run.mts @@ -0,0 +1,578 @@ +/** + * task-board › a settled task reaches the board (FIX-2429). + * + * Real `serve()` hosts on bound ports, real WebSocket clients, and the board + * views as the apps run them: the Teammates lab adapter's `watchTasks`, the + * claude-code-style lab adapter's `watchTasks` (a view of the merged + * `listTasks_tasks` read and nothing else), and a live `BoardList`'s read + * (`client.subscribe` on the board's narrowed topic, `listCollectionItems` on + * each wake). Every assertion reads what a view showed, timed against when the + * row's change could be read from the store, and counts the board reads each + * view made. + * + * a — on a bus that crosses (FIX-2426's crossing double): a conversation + * files a task its delegate runs in a task session, and a plan step for + * itself; each settles. Each view shows the task completed (and, for + * Teammates, its run's link) within 1 s of the store; the merged view + * shows the step completed within 1 s. Over a 10 s window with a task + * open, a reply streaming in the conversation, and a task filed and + * settled in a second conversation of the same user, each view makes + * 0 board reads. + * b — the same views on process 1, the task released and settled on a + * second registry over one real Postgres (the Postgres bus): within + * 1 s, and 0 reads over 10 s from each view's first `crosses: true`. + * c — the same views on a host with no push: each shows the task + * completed within its own poll interval plus 1 s. + * + * Controls (each runs this file again with a patch applied as it loads): + * GOAL_CONTROL=running-session publish on the session that wrote: a's 1 s signal must FAIL. + * GOAL_CONTROL=whole-topic the lab views subscribe the whole session topic: a's 0-reads must FAIL. + * GOAL_CONTROL=tasks-only the merged read's views subscribe `tasks` alone: a's plan-step signal must FAIL. + */ +import { spawnSync } from "node:child_process"; +import { rmSync } from "node:fs"; +import { join } from "node:path"; +import { z } from "zod"; +import { defineFlow, handler } from "@flow-state-dev/core"; +import type { BlockContext } from "@flow-state-dev/core/types"; +import { createClient, topic, type Client, type ClientFetch } from "@flow-state-dev/client"; +import { createFlowState, createInMemoryStores, type FlowState, type StoreAdapter } from "@flow-state-dev/engine"; +import { serve, type ServeHandle } from "@flow-state-dev/node"; +import { postgresStores } from "@flow-state-dev/store-postgres"; +import type { Task, TaskInit } from "@flow-state-dev/orchestration/tasks"; +import { + createWorkerInstallation, + defineSessionBoard, + hireWorkforce, + workerConfigSchema, + workerTaskEntry, + type WorkerManifest +} from "@flow-state-dev/workforce"; +import { crossingBus } from "../../lib/crossing-bus.mts"; +import { startPostgres } from "../../lib/postgres.mts"; +import { + REPO_ROOT, + RUN_STAMP, + actingAs, + assertPatched, + describePatches, + goalTmpDir, + modulePatchEnv, + runGoal, + silentLogger, + type ModulePatch +} from "../../lib/index.mts"; +import { createLabAdapter as teammatesLab } from "../../../labs/teammates/src/adapter.ts"; +import { createWiredLab as claudeCodeStyleLab } from "../../../labs/claude-code-style/src/adapter.ts"; + +const CONTROL = process.env.GOAL_CONTROL ?? ""; +const SCRATCH = process.env.GOAL_SCRATCH ?? goalTmpDir("a-settled-task-reaches-the-board"); +const USER = "alice"; +const TOKEN = "tok-alice"; +const ORG = "acme"; +const IDLE_WINDOW_MS = 10_000; +/** How long a delegate's run takes, so its link and its ending are two writes apart. */ +const DOER_MS = 1_500; +/** How long a plan step's turn takes. */ +const STEP_MS = 1_500; +/** Each view's pace where push can miss a change: today's. */ +const PACE = { teammates: 1_500, "claude-code-style": 2_000, "board-list": 3_000 } as const; +type ViewName = keyof typeof PACE; + +const TEAMMATES = "labs/teammates/src/adapter.ts"; +const CLAUDE_CODE_STYLE = "labs/claude-code-style/src/adapter.ts"; +const PATCHES: Record = { + // Publish on the session that wrote, not the one that filed. + "running-session": [ + { + module: "packages/orchestration/src/tasks/collection/get-or-create.ts", + from: String.raw`event\.task\.filer\?\.sessionId \?\? legacyFiler\?\.\(event\.task\) \?\? runningSession`, + to: "runningSession" + } + ], + // The lab views subscribe the conversation's whole topic. + "whole-topic": [ + { module: TEAMMATES, from: String.raw`BOARD_LEDGERS\.map\(\(resource\) => topic\.session\(sessionId, \{ resource \}\)\)`, to: "[topic.session(sessionId)]" }, + { module: CLAUDE_CODE_STYLE, from: String.raw`BOARD_LEDGERS\.map\(\(resource\) => topic\.session\(sessionId, \{ resource \}\)\)`, to: "[topic.session(sessionId)]" } + ], + // The merged read's views subscribe `tasks` alone. + "tasks-only": [ + { module: TEAMMATES, from: String.raw`const BOARD_LEDGERS = \["tasks", "plan"\] as const;`, to: 'const BOARD_LEDGERS = ["tasks"] as const;' }, + { module: CLAUDE_CODE_STYLE, from: String.raw`const BOARD_LEDGERS = \["tasks", "plan"\] as const;`, to: 'const BOARD_LEDGERS = ["tasks"] as const;' } + ] +}; + +if (CONTROL !== "" && PATCHES[CONTROL] === undefined) { + console.error(`unknown GOAL_CONTROL "${CONTROL}"; known: ${Object.keys(PATCHES).join(", ")}`); + process.exit(2); +} +if (PATCHES[CONTROL] !== undefined && process.env.GOAL_MODULE_PATCH === undefined) { + const mark = join(SCRATCH, `patch-mark-${RUN_STAMP}`); + rmSync(mark, { force: true }); + console.error(`control ${CONTROL}:\n${describePatches(PATCHES[CONTROL]!, REPO_ROOT)}`); + const child = spawnSync(process.execPath, [...process.execArgv, ...process.argv.slice(1)], { + stdio: "inherit", + env: { ...process.env, GOAL_SCRATCH: SCRATCH, GOAL_LEGS: process.env.GOAL_LEGS ?? "a", ...modulePatchEnv(PATCHES[CONTROL]!, REPO_ROOT, mark) } + }); + assertPatched(PATCHES[CONTROL]!, REPO_ROOT, mark); + process.exit(child.status ?? 1); +} +const legs = new Set((process.env.GOAL_LEGS ?? "a,b,c").split(",").map((s) => s.trim()).filter(Boolean)); + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); +const say = (s: string) => console.error(`[board-notices ${new Date().toISOString().slice(11, 19)}] ${s}`); + +// --------------------------------------------------------------------------- +// Observing the sockets (taps only: nothing here changes what a client does) +// --------------------------------------------------------------------------- + +type Tap = { frames: Array<{ type: string; crosses?: boolean }>; crossedAt?: number }; +const taps: Tap[] = []; +const NativeWebSocket = globalThis.WebSocket; +globalThis.WebSocket = class TappedWebSocket extends NativeWebSocket { + constructor(url: string | URL, protocols?: string | string[]) { + super(url, protocols); + const tap: Tap = { frames: [] }; + taps.push(tap); + this.addEventListener("message", (event) => { + const frame = JSON.parse(String(event.data)) as Tap["frames"][number]; + tap.frames.push(frame); + if (frame.type === "crossing" && frame.crosses === true) tap.crossedAt ??= Date.now(); + }); + } +} as typeof WebSocket; + +// --------------------------------------------------------------------------- +// The app: a conversation whose worker files a task for a handler delegate and +// a step for itself +// --------------------------------------------------------------------------- + +const worker = (id: string, declared: Record): WorkerManifest => ({ id, declared, body: "", skills: [] }); +const WORKERS: WorkerManifest[] = [worker("lead", { flow: "desk", delegates: ["eng.doer"] }), worker("eng.doer", { flow: "doer", delegates: [] })]; +const STEP = "You are working a step you filed for yourself"; +const ANSWER = "The steps you filed for yourself have ended"; + +type Script = { op: "file"; tasks: TaskInit[] } | { op: "step"; id: string; goal: string } | { op: "chat"; ms: number }; + +/** The doer's runs, by the host that ran them. */ +const ranOn: Array<{ host: string; goal: string }> = []; + +function buildHost(name: string, stores: StoreAdapter): FlowState { + let workerFlows: Record = {}; + const installation = createWorkerInstallation({ standardWorkers: WORKERS, workerFlows: () => workerFlows as never }); + const doorInput = z.object({ message: z.string() }); + const deskBoard = defineSessionBoard({ installation, flowKind: "desk" }); + const doerBoard = defineSessionBoard({ installation, flowKind: "doer" }); + + const deskTurn = handler({ + name: "board-notices-desk-turn", + inputSchema: doorInput, + outputSchema: z.unknown(), + resources: { ...installation.resources, ...deskBoard.resources }, + execute: async (input, rawCtx) => { + const ctx = rawCtx as unknown as BlockContext; + if (input.message.startsWith(STEP)) { + await sleep(STEP_MS); + return "step done"; + } + if (input.message.startsWith(ANSWER)) return "answered"; + if (input.message.startsWith('Task "')) return "heard"; + const script = JSON.parse(input.message) as Script; + if (script.op === "chat") { + // A reply streaming in the conversation: items kept, no task touched. + for (let n = 0; n * 200 < script.ms; n += 1) { + ctx.emit.message(`part ${n} of a long reply`); + await sleep(200); + } + return "chatted"; + } + if (script.op === "step") { + const ref = await deskBoard.board.turnResolver(ctx as never); + await ref!.createTask({ id: script.id, goal: script.goal, assignee: "lead" }); + return "planned"; + } + const ref = await deskBoard.board.resolver(ctx as never); + return { ids: (await ref!.createTasks(script.tasks)).map((t) => t.id) }; + } + }); + const planned = deskBoard.planned(deskTurn); + + const doerTurn = handler({ + name: "board-notices-doer-turn", + inputSchema: doorInput, + outputSchema: z.unknown(), + execute: async (input) => { + ranOn.push({ host: name, goal: input.message }); + await sleep(DOER_MS); + return `done: ${input.message}`; + } + }); + + const resolveWorker = (kind: string) => + handler({ + name: `board-notices-${kind}-resolve-worker`, + inputSchema: z.unknown(), + outputSchema: z.object({ worker: z.string() }), + resources: { ...installation.resources }, + execute: async (_input, ctx) => ({ worker: (await installation.resolveWorker(ctx, kind)).id }) + }); + const flowOf = (kind: string, board: ReturnType, turn: unknown) => + defineFlow({ + kind, + configSchema: workerConfigSchema(), + session: { ...installation.session(board.sessionStateShape), serverOwned: [...board.serverOwned] }, + resources: { ...installation.resources, ...board.resources }, + request: { onStarted: resolveWorker(kind) }, + actions: { respond: { inputSchema: doorInput.strict(), block: turn, userMessage: (i: { message: string }) => i.message }, ...board.actions }, + reads: { ...board.reads }, + internal: { actions: board.entries(turn as never) }, + task: { actions: { work: workerTaskEntry({ name: `board-notices-${kind}-task`, turn: turn as never }) } } + } as never); + workerFlows = { + desk: { flow: flowOf("desk", deskBoard, planned), roles: ["contributor", "manager"] }, + doer: { flow: flowOf("doer", doerBoard, doerTurn), roles: ["contributor", "manager"] } + }; + return createFlowState({ + flows: Object.fromEntries(hireWorkforce(installation).map((copy) => [copy.id, copy])), + stores: { default: { primary: stores } }, + logger: silentLogger, + resolvePrincipal: (context: any) => { + // A tab's bearer token, or `actingAs`'s in-process caller (process 2's person, leg b). + const header = context.request?.headers.get("authorization") ?? ""; + const inProcess = context.request?.headers.get("x-user"); + return header.replace(/^Bearer /, "") === TOKEN || inProcess === USER ? { userId: USER, orgId: ORG } : null; + } + } as never); +} + +/** A memory adapter for `createFlowState`, with `bus` when given. */ +function memory(bus?: ReturnType): StoreAdapter { + const registry = { ...createInMemoryStores(), ...(bus !== undefined ? { bus } : {}) }; + return { capabilities: ["primary", ...(bus !== undefined ? (["bus"] as const) : [])], resolve: async () => registry as never } as never; +} + +type Host = { name: string; state: FlowState; handle?: ServeHandle; base: string; rows(): Promise> }; + +async function host(name: string, stores: StoreAdapter, options: { serve: boolean; push?: boolean }): Promise { + const state = buildHost(name, stores); + const runtime = await state.getRuntime(); + const rows = async () => + new Map( + Object.values(await runtime.stores.resourceState.getByPrefix("user", `${USER}:~org:${ORG}`, "")) + .map((value) => value.state as Task) + .filter((row) => typeof row?.goal === "string" && typeof row?.status === "string") + .map((row) => [row.id, row]) + ); + if (!options.serve) return { name, state, base: "", rows }; + const handle = await serve(await state.getRouter(), { + port: 0, + host: "127.0.0.1", + handleSignals: false, + shutdownGraceMs: 200, + ...(options.push !== undefined ? { push: options.push } : {}) + }); + return { name, state, handle, base: `http://127.0.0.1:${handle.port}`, rows }; +} + +/** A tab on `on`: the one client, with the bearer token, counting the board reads it makes. */ +function tab(on: Host) { + const counted = { reads: 0 }; + const fetcher: ClientFetch = (input, init) => { + const url = String(input); + if (url.includes("/reads/listTasks_tasks") || /\/resources\/tasks(\?|$)/.test(url)) counted.reads += 1; + return fetch(input, { ...init, headers: { ...(init?.headers as Record), authorization: `Bearer ${TOKEN}` } }); + }; + return { client: createClient({ userId: USER, baseUrl: on.base, fetcher }), counted }; +} + +/** A person acting on a host in this process (`b`'s second registry), as the same verified user. */ +function personOn(state: FlowState) { + const inProcess = actingAs(state as never, USER); + return inProcess; +} + +// --------------------------------------------------------------------------- +// The views +// --------------------------------------------------------------------------- + +type Shown = { at: number; rows: Map }; +type View = { name: ViewName; shown: Shown[]; reads(): number; close(): void }; + +function viewsOn(on: Host, conversation: string): View[] { + const teammates = tab(on); + const tShown: Shown[] = []; + const stopTeammates = teammatesLab(teammates.client).watchTasks(conversation, (tasks) => + tShown.push({ + at: Date.now(), + rows: new Map(tasks.map((t) => [t.id, { status: t.status === "done" ? "completed" : t.status, ...(t.runSessionId !== undefined ? { run: t.runSessionId } : {}) }])) + }) + ); + + const ccs = tab(on); + const cShown: Shown[] = []; + const stopCcs = claudeCodeStyleLab(ccs.client).watchTasks(conversation, (rows) => + cShown.push({ at: Date.now(), rows: new Map(rows.map((r) => [r.id, { status: r.status }])) }) + ); + + // A live `BoardList`'s read: its board's narrowed topic, its pace, and the + // collection read on mount and on each wake, one read at a time. + const list = tab(on); + const lShown: Shown[] = []; + let running = false; + let queued = false; + const read = async (): Promise => { + if (running) { + queued = true; + return; + } + running = true; + try { + const page = await list.client.resources.listCollectionItems(conversation, "tasks", {}); + lShown.push({ at: Date.now(), rows: new Map(page.items.map((item) => [(item.clientData as Task).id, { status: (item.clientData as Task).status }])) }); + } catch { + // A failed read shows nothing new. + } finally { + running = false; + if (queued) { + queued = false; + void read(); + } + } + }; + const subscription = list.client.subscribe([topic.session(conversation, { resource: "tasks" })], { onChange: () => void read(), pollIntervalMs: PACE["board-list"] }); + void read(); + + return [ + { name: "teammates", shown: tShown, reads: () => teammates.counted.reads, close: stopTeammates }, + { name: "claude-code-style", shown: cShown, reads: () => ccs.counted.reads, close: stopCcs }, + { name: "board-list", shown: lShown, reads: () => list.counted.reads, close: () => subscription.close() } + ]; +} + +/** When `view` first showed a row matching `match`, waiting up to `withinMs`. */ +async function shownAt(view: View, id: string, match: (row: { status: string; run?: string }) => boolean, withinMs: number): Promise { + const deadline = Date.now() + withinMs; + for (;;) { + const hit = view.shown.find((s) => { + const row = s.rows.get(id); + return row !== undefined && match(row); + }); + if (hit !== undefined) return hit.at; + if (Date.now() > deadline) return undefined; + await sleep(10); + } +} + +/** + * Watch the store every 5 ms for when `id` first reads as `match`: the moment + * the change can be read, which every view's latency is measured from. + */ +function storeWatch(on: Host) { + const seen = new Map(); + let live = true; + const checks: Array<{ key: string; id: string; match: (row: Task) => boolean }> = []; + void (async () => { + while (live) { + const rows = await on.rows().catch(() => new Map()); + for (const check of checks) { + if (seen.has(check.key)) continue; + const row = rows.get(check.id); + if (row !== undefined && check.match(row)) seen.set(check.key, Date.now()); + } + await sleep(5); + } + })(); + return { + watch: (key: string, id: string, match: (row: Task) => boolean) => checks.push({ key, id, match }), + at: async (key: string, withinMs: number) => { + const deadline = Date.now() + withinMs; + while (!seen.has(key) && Date.now() < deadline) await sleep(5); + return seen.get(key); + }, + stop: () => void (live = false) + }; +} + +async function until(check: () => boolean | Promise, withinMs: number): Promise { + const deadline = Date.now() + withinMs; + while (!(await check())) { + if (Date.now() > deadline) return false; + await sleep(20); + } + return true; +} + +const script = (fsd: Client, session: string, s: Script) => fsd.flow("desk").send("respond", { message: JSON.stringify(s) }, { sessionId: session }); + +// --------------------------------------------------------------------------- +// The legs +// --------------------------------------------------------------------------- + +await runGoal(async (failures, tell) => { + const evidence: string[] = []; + const closers: Array<() => unknown> = []; + try { + if (legs.has("a")) { + const on = await host("a", memory(crossingBus()), { serve: true }); + closers.push(() => on.handle!.close()); + const person = tab(on).client; + const conversation = (await person.flow("desk").createSession({ state: { workerId: "lead" } })).id; + const other = (await person.flow("desk").createSession({ state: { workerId: "lead" } })).id; + const store = storeWatch(on); + closers.push(store.stop); + + const before = taps.length; + const views = viewsOn(on, conversation); + closers.push(() => views.forEach((v) => v.close())); + const crossed = await until(() => taps.slice(before).length >= 3 && taps.slice(before).every((t) => t.crossedAt !== undefined), 5_000); + if (!crossed) failures.push("a:crossing: the views' sockets never all said crosses: true within 5 s"); + + // A task held open: the window below has a task open. + const held = `held-${RUN_STAMP}`; + await script(person, conversation, { op: "file", tasks: [{ id: held, goal: "stays open", assignee: "eng.doer", held: true }] }); + for (const view of views) { + if ((await shownAt(view, held, () => true, 5_000)) === undefined) failures.push(`a:setup: ${view.name} never showed the held task`); + } + await sleep(1_500); + + // The window: a reply streams in the conversation, and the user's other + // conversation files a task its delegate settles. + const readsBefore = views.map((v) => v.reads()); + const otherTask = `other-${RUN_STAMP}`; + store.watch("other:completed", otherTask, (row) => row.status === "completed"); + await sleep(1_000); + await script(person, conversation, { op: "chat", ms: 3_000 }); + await script(person, other, { op: "file", tasks: [{ id: otherTask, goal: "in the other conversation", assignee: "eng.doer" }] }); + await sleep(IDLE_WINDOW_MS - 1_000); + const otherSettled = await store.at("other:completed", 5_000); + tell.over("a:0-reads · the other conversation's task settled during the window", otherSettled === undefined ? [] : [otherSettled]); + const idle = views.map((v, i) => ({ name: v.name, reads: v.reads() - readsBefore[i]! })); + tell.over("a:0-reads · the views' reads before the window", readsBefore.filter((n) => n > 0)); + const busy = idle.filter((v) => v.reads !== 0); + if (busy.length > 0) failures.push(`a:0-reads: ${busy.map((v) => `${v.name} made ${v.reads} board reads`).join(", ")} in ${IDLE_WINDOW_MS / 1000} s with no change to this board`); + else evidence.push(`a: 0 board reads in ${IDLE_WINDOW_MS / 1000} s on each of ${views.length} views (a reply streaming, another conversation's task settled)`); + + // A task settled in its own task session, with its run's link. + const task = `task-${RUN_STAMP}`; + store.watch("task:linked", task, (row) => row.run?.sessionId !== undefined); + store.watch("task:completed", task, (row) => row.status === "completed"); + await script(person, conversation, { op: "file", tasks: [{ id: task, goal: "settles in its own session", assignee: "eng.doer" }] }); + const linkedAt = await store.at("task:linked", 10_000); + const completedAt = await store.at("task:completed", 10_000); + tell.over("a:within-1s · the task's link and ending in the store", [linkedAt, completedAt].filter((t) => t !== undefined)); + const latencies: string[] = []; + for (const view of views) { + if (completedAt !== undefined) { + const shown = await shownAt(view, task, (row) => row.status === "completed", 4_000); + if (shown === undefined || shown - completedAt >= 1_000) failures.push(`a:within-1s: ${view.name} showed the task completed ${shown === undefined ? "never (4 s)" : `${shown - completedAt} ms`} after the store (bound 1000)`); + else latencies.push(`${view.name} ${shown - completedAt} ms`); + } + } + const teammates = views.find((v) => v.name === "teammates")!; + if (linkedAt !== undefined) { + const shown = await shownAt(teammates, task, (row) => row.run !== undefined, 4_000); + if (shown === undefined || shown - linkedAt >= 1_000) failures.push(`a:within-1s: teammates showed the run's link ${shown === undefined ? "never (4 s)" : `${shown - linkedAt} ms`} after the store (bound 1000)`); + else latencies.push(`teammates link ${shown - linkedAt} ms`); + } + if (latencies.length > 0) evidence.push(`a: task shown ${latencies.join(", ")}`); + + // A plan step the conversation's worker files for itself. + const step = `step-${RUN_STAMP}`; + store.watch("step:completed", step, (row) => row.status === "completed"); + await sleep(1_000); + await script(person, conversation, { op: "step", id: step, goal: "a step for itself" }); + const stepAt = await store.at("step:completed", 15_000); + tell.over("a:plan-step · the step's ending in the store", stepAt === undefined ? [] : [stepAt]); + const merged = views.find((v) => v.name === "claude-code-style")!; + if (stepAt !== undefined) { + const shown = await shownAt(merged, step, (row) => row.status === "completed", 4_000); + if (shown === undefined || shown - stepAt >= 1_000) failures.push(`a:plan-step: ${merged.name} showed the step completed ${shown === undefined ? "never (4 s)" : `${shown - stepAt} ms`} after the store (bound 1000)`); + else evidence.push(`a: plan step shown ${shown - stepAt} ms after the store`); + } + views.forEach((v) => v.close()); + } + + if (legs.has("b")) { + const db = await startPostgres({ slug: "board-notices" }); + closers.push(() => db.stop()); + const p1 = await host("p1", postgresStores({ connectionString: db.url }), { serve: true }); + closers.push(() => p1.handle!.close()); + const p2 = await host("p2", postgresStores({ connectionString: db.url }), { serve: false }); + closers.push(() => p2.state.dispose?.()); + const person = tab(p1).client; + const conversation = (await person.flow("desk").createSession({ state: { workerId: "lead" } })).id; + const store = storeWatch(p1); + closers.push(store.stop); + const task = `b-task-${RUN_STAMP}`; + await script(person, conversation, { op: "file", tasks: [{ id: task, goal: "settled on process 2", assignee: "eng.doer", held: true }] }); + + const before = taps.length; + const views = viewsOn(p1, conversation); + closers.push(() => views.forEach((v) => v.close())); + const crossed = await until(() => taps.slice(before).length >= 3 && taps.slice(before).every((t) => t.crossedAt !== undefined), 15_000); + if (!crossed) failures.push("b:crossing: the views' sockets never all said crosses: true within 15 s"); + for (const view of views) await shownAt(view, task, () => true, 5_000); + const readsBefore = views.map((v) => v.reads()); + await sleep(IDLE_WINDOW_MS); + const busy = views.map((v, i) => ({ name: v.name, reads: v.reads() - readsBefore[i]! })).filter((v) => v.reads !== 0); + tell.over("b:0-reads · the views' reads before the window", readsBefore.filter((n) => n > 0)); + if (busy.length > 0) failures.push(`b:0-reads: ${busy.map((v) => `${v.name} made ${v.reads} board reads`).join(", ")} in ${IDLE_WINDOW_MS / 1000} s idle`); + else evidence.push(`b: 0 board reads in ${IDLE_WINDOW_MS / 1000} s from each view's first crosses: true`); + + // Released on process 2: its pass hands the row out, its doer runs it. + store.watch("b:linked", task, (row) => row.run?.sessionId !== undefined); + store.watch("b:completed", task, (row) => row.status === "completed"); + const ran = ranOn.length; + await personOn(p2.state).act("desk", conversation, "updateTask_tasks", { id: task, status: "pending" }); + const linkedAt = await store.at("b:linked", 15_000); + const completedAt = await store.at("b:completed", 15_000); + const where = tell.over("b:within-1s · the hosts the doer ran on", ranOn.slice(ran)); + if (where.some((r) => r.host !== "p2")) failures.push(`b:setup: the task ran on ${where.map((r) => r.host).join(", ")}, not process 2 alone`); + tell.over("b:within-1s · the task's link and ending in the store", [linkedAt, completedAt].filter((t) => t !== undefined)); + const latencies: string[] = []; + for (const view of views) { + if (completedAt === undefined) continue; + const shown = await shownAt(view, task, (row) => row.status === "completed", 4_000); + if (shown === undefined || shown - completedAt >= 1_000) failures.push(`b:within-1s: ${view.name} showed the task completed ${shown === undefined ? "never (4 s)" : `${shown - completedAt} ms`} after the store (bound 1000)`); + else latencies.push(`${view.name} ${shown - completedAt} ms`); + } + if (linkedAt !== undefined) { + const shown = await shownAt(views[0]!, task, (row) => row.run !== undefined, 4_000); + if (shown === undefined || shown - linkedAt >= 1_000) failures.push(`b:within-1s: teammates showed the run's link ${shown === undefined ? "never (4 s)" : `${shown - linkedAt} ms`} after the store (bound 1000)`); + else latencies.push(`teammates link ${shown - linkedAt} ms`); + } + if (latencies.length > 0) evidence.push(`b: settled on p2 (${db.source}), shown ${latencies.join(", ")}`); + views.forEach((v) => v.close()); + } + + if (legs.has("c")) { + const on = await host("c", memory(), { serve: true, push: false }); + closers.push(() => on.handle!.close()); + const person = tab(on).client; + const conversation = (await person.flow("desk").createSession({ state: { workerId: "lead" } })).id; + const store = storeWatch(on); + closers.push(store.stop); + const views = viewsOn(on, conversation); + closers.push(() => views.forEach((v) => v.close())); + await sleep(500); + const task = `c-task-${RUN_STAMP}`; + store.watch("c:completed", task, (row) => row.status === "completed"); + await script(person, conversation, { op: "file", tasks: [{ id: task, goal: "settles with no push", assignee: "eng.doer" }] }); + const completedAt = await store.at("c:completed", 15_000); + tell.over("c:within-a-poll · the task's ending in the store", completedAt === undefined ? [] : [completedAt]); + const latencies: string[] = []; + for (const view of views) { + if (completedAt === undefined) continue; + const bound = PACE[view.name] + 1_000; + const shown = await shownAt(view, task, (row) => row.status === "completed", bound + 3_000); + if (shown === undefined || shown - completedAt >= bound) failures.push(`c:within-a-poll: ${view.name} showed the task completed ${shown === undefined ? "never" : `${shown - completedAt} ms`} after the store (bound ${bound})`); + else latencies.push(`${view.name} ${shown - completedAt} ms (bound ${bound})`); + } + if (latencies.length > 0) evidence.push(`c: no push, shown ${latencies.join(", ")}`); + views.forEach((v) => v.close()); + } + } finally { + for (const close of closers.reverse()) await Promise.resolve(close()).catch(() => undefined); + } + return { failures, evidence: evidence.join(" · ") }; +}); diff --git a/labs/claude-code-style/src/adapter.ts b/labs/claude-code-style/src/adapter.ts index 6b69235e22..235ff13de5 100644 --- a/labs/claude-code-style/src/adapter.ts +++ b/labs/claude-code-style/src/adapter.ts @@ -16,6 +16,7 @@ * | | and that feed's connection state, for the connection bar; `loadEarlier` | * | | is the feed's, for a thread longer than its first read | * | `watchTasks` | the conversation board's `listTasks_tasks` read, and the rows' open holds | + * | | again on each notice of the board, through `client.subscribe` | * | `watchTaskWork` | the items of a task's run session, followed through `sessionFeed`, with | * | | its `loadEarlier` too | * | `sayInThread` | the Inbox client's answer to the thread's open question, else `updateTask_tasks` with your line | @@ -23,7 +24,7 @@ * | `requestChanges`| the same answer with `{ verdict: "revise", words }` | * | `watchPins`, `pin`, `unpin` | the lab's `pins` flow, your own user state | */ -import { createClient, sessionFeed, type Client, type SessionConnectionState, type SessionFeed, type SessionSummary } from "@flow-state-dev/client"; +import { createClient, sessionFeed, topic, type Client, type SessionConnectionState, type SessionFeed, type SessionSummary } from "@flow-state-dev/client"; import { readBasePath, readBearerToken, readUserId, withBearerToken } from "@flow-state-dev/devtool/react"; import { createInboxClient, inboxItems, type InboxAnswer, type InboxHold, type InboxRow, type TaskHold } from "@flow-state-dev/orchestration/inbox"; import { parseNotice, type TaskSpendView } from "@flow-state-dev/orchestration/tasks"; @@ -240,6 +241,56 @@ function every(read: () => Promise, onChange: (value: T) => void, everyMs }; } +/** How often a session's task list reads on a timer, wherever push can miss a change. */ +const TASKS_EVERY_MS = 2_000; +/** The ledgers a session's `listTasks` read returns: its board and its planning worker's steps. */ +const BOARD_LEDGERS = ["tasks", "plan"] as const; + +/** + * Read `read` now, and again whenever a session's board changes (FIX-2429): + * the session's topic narrowed to each ledger, so a reply streaming in the + * session never wakes it. Reports a value only when it changed, as + * {@link every} does. One read at a time, and one waiting for any number of + * notices. Wherever push can miss a change, `client.subscribe` reads every + * `everyMs` instead. + */ +function onBoardChange(client: Client, sessionId: string, read: () => Promise, onChange: (value: T) => void, everyMs = TASKS_EVERY_MS): Unsubscribe { + let live = true; + let last: string | undefined; + let running = false; + let queued = false; + const tick = async (): Promise => { + if (!live) return; + if (running) { + queued = true; + return; + } + running = true; + try { + const value = await read(); + const key = JSON.stringify(value); + if (live && key !== last) { + last = key; + onChange(value); + } + } catch (error) { + console.warn("[claude-code-style]", error); + } + running = false; + if (queued) { + queued = false; + void tick(); + } + }; + const topics = BOARD_LEDGERS.map((resource) => topic.session(sessionId, { resource })); + const subscription = client.subscribe(topics, { onChange: () => void tick(), pollIntervalMs: everyMs }); + void tick(); + return () => { + live = false; + subscription.close(); + }; +} + /** * A run's latest review stop, read with harness-manager's browser reader, or * undefined before it makes one. The latest wins: a run sent back for changes @@ -723,7 +774,7 @@ export function createWiredLab(fsd: Client): LabAdapter { }; }, // The board is a read, so listing it every tick while the pane is open stores nothing. - watchTasks: (sessionId, onChange) => every(() => boardOf(sessionId), onChange, 2000), + watchTasks: (sessionId, onChange) => onBoardChange(fsd, sessionId, () => boardOf(sessionId), onChange), // Shown only inside the tasks pane or the threads board, whose watch keeps `runSessionOf` current. watchTaskWork: (_sessionId, taskId, onChange) => { // The task's run session is known once the board has listed it, and a re-run moves it: follow diff --git a/labs/claude-code-style/test/watch-tasks.test.ts b/labs/claude-code-style/test/watch-tasks.test.ts new file mode 100644 index 0000000000..1b4c5ade26 --- /dev/null +++ b/labs/claude-code-style/test/watch-tasks.test.ts @@ -0,0 +1,68 @@ +/** + * A session's task list reads when its board changes (FIX-2429), not every two + * seconds all day: the conversation's session topic narrowed to each ledger + * its `listTasks` read returns, so a reply streaming in the session never wakes + * it. Wherever push can miss a change, `client.subscribe` reads on its timer, + * at the list's old pace. + */ +import { describe, expect, it } from "vitest"; +import type { Client, SubscribeOptions, WireNotice, WireTopic } from "@flow-state-dev/client"; +import { createWiredLab, type TaskRow } from "../src/adapter"; + +function fakeClient() { + const reads: string[] = []; + const subscriptions: Array<{ topics: readonly WireTopic[]; options: SubscribeOptions; closed: boolean }> = []; + let status = "in_progress"; + const client = { + subscribe: (topics: readonly WireTopic[], options: SubscribeOptions) => { + const entry = { topics, options, closed: false }; + subscriptions.push(entry); + return { close: () => void (entry.closed = true) }; + }, + sessions: { get: async (id: string) => ({ id, flowKind: "agent" }) }, + flow: (flow: string) => ({ + read: async (action: string) => { + reads.push(`${flow}.${action}`); + return { ok: true, tasks: [{ id: "t1", goal: "Fix the typo", status, updatedAt: reads.length }] }; + }, + }), + } as unknown as Client; + const hear = (notice: WireNotice | null) => { + for (const s of subscriptions) if (!s.closed) s.options.onChange(notice); + }; + return { client, reads, subscriptions, hear, settle: (next: string) => void (status = next) }; +} + +const until = async (check: () => boolean) => { + for (let i = 0; i < 200 && !check(); i++) await new Promise((r) => setTimeout(r, 10)); + if (!check()) throw new Error("condition never held"); +}; + +describe("watchTasks", () => { + it("subscribes the session's board and plan ledgers, narrowed, at its old pace for where push can miss a change", async () => { + const lab = fakeClient(); + const stop = createWiredLab(lab.client).watchTasks("s1", () => {}); + await until(() => lab.subscriptions.length > 0); + stop(); + expect(lab.subscriptions[0]!.topics).toEqual([ + { scope: "session", id: "s1", resource: "tasks" }, + { scope: "session", id: "s1", resource: "plan" }, + ]); + expect(lab.subscriptions[0]!.options.pollIntervalMs).toBe(2_000); + expect(lab.subscriptions[0]!.closed).toBe(true); + }); + + it("reads once on open, again on a board notice, and keeps no timer of its own", async () => { + const lab = fakeClient(); + let rows: TaskRow[] = []; + const stop = createWiredLab(lab.client).watchTasks("s1", (next) => (rows = next)); + await until(() => rows.length === 1); + await new Promise((r) => setTimeout(r, 2_200)); + expect(lab.reads).toEqual(["agent.listTasks_tasks"]); + lab.settle("completed"); + lab.hear({ topic: { scope: "session", id: "s1", resource: "tasks" }, kind: "board" }); + await until(() => rows[0]?.status === "completed"); + stop(); + expect(lab.reads).toHaveLength(2); + }); +}); diff --git a/labs/teammates/src/adapter.ts b/labs/teammates/src/adapter.ts index f6ed61df9b..a2fd099900 100644 --- a/labs/teammates/src/adapter.ts +++ b/labs/teammates/src/adapter.ts @@ -18,7 +18,7 @@ * | `editInstructions` | the workforce client's `edit`, on one of the user's own workers | * | `fire` | the workforce client's `fire`, on one of the user's own workers | * | `watchTasks` | the board's rows, as the conversation's stream carries each one (`task-change`) | - * | | and, while a running row names no run, the board's `listTasks` read for its run | + * | | and the board's `listTasks` read, on each notice of the conversation's board | * | | and `taskSpendView` on a row, for the harness and model its run reported | * | | and each linked run's session, where the run writes its row (its holds) | * | | and `taskRowView` with the Inbox's holds (`inboxItems`), for what it waits on | @@ -36,7 +36,7 @@ * The page acts as the user `fsdev dev` hands it (the config's `devtool` * block), with the bearer token when there is one, on the server it came from. */ -import { createClient, readEveryCollectionPage, type Client, type SessionConnectionState, type SessionRequestSummary } from "@flow-state-dev/client"; +import { createClient, readEveryCollectionPage, topic, type Client, type SessionConnectionState, type SessionRequestSummary } from "@flow-state-dev/client"; import type { OutputItem } from "@flow-state-dev/core/items"; import { readBasePath, readBearerToken, readUserId, withBearerToken } from "@flow-state-dev/devtool/react"; import { @@ -251,6 +251,8 @@ const TASK_CHANGE = "task-change"; const CREATE_TASK = "createTask"; /** The board's read of its rows, on a conversation's flow. */ const LIST_TASKS = "listTasks_tasks"; +/** The ledgers that read returns: the conversation's board and its planning worker's steps. */ +const BOARD_LEDGERS = ["tasks", "plan"] as const; /** The board's action a question on a row is answered through, on the conversation that filed it. */ const UPDATE_TASK = "updateTask_tasks"; /** Requests that are a worker answering: everything but the board's own passes. */ @@ -364,6 +366,44 @@ function poll(read: () => Promise, onValue: (value: T) => void, everyMs = }; } +/** + * Run `read` now, and again on each notice of a conversation's board (FIX-2429): + * its session's topic narrowed to each ledger its `listTasks` read returns, so a + * reply streaming in the conversation never wakes it. One read at a time, and + * one waiting for any number of notices. Wherever push can miss a change, + * `client.subscribe` reads every `everyMs` instead. + */ +function onBoardChange(client: Client, sessionId: string, read: () => Promise, everyMs = POLL_MS): Unsubscribe { + let live = true; + let running = false; + let queued = false; + const run = async (): Promise => { + if (!live) return; + if (running) { + queued = true; + return; + } + running = true; + try { + await read(); + } catch (error) { + console.error("teammates: a read failed", error); + } + running = false; + if (queued) { + queued = false; + void run(); + } + }; + const topics = BOARD_LEDGERS.map((resource) => topic.session(sessionId, { resource })); + const subscription = client.subscribe(topics, { onChange: () => void run(), pollIntervalMs: everyMs }); + void run(); + return () => { + live = false; + subscription.close(); + }; +} + /** The latest copy of each board row in a conversation's items, oldest filing first. */ function boardRows(items: readonly Item[]): Map> { const rows = new Map>(); @@ -798,9 +838,12 @@ export function createLabAdapter(client: Client = connect()): LabAdapter { watchTasks(sessionId, onChange) { const show = stableList(onChange); let rows = new Map>(); - /** The run each running row's last board read named, by task id. */ - const runs = new Map(); - let stopRead: Unsubscribe | undefined; + /** + * Each row as the board's last read answered it. A task settles, and its run links itself, in + * the task's own session, which the conversation's stream doesn't carry; the board's notice + * does, and the read says what changed. The newer of the two copies is the row. + */ + let listed = new Map>(); /** * Each linked run's own copy of its row. A run writes its row on its own session (its link, its * questions, its review), so the conversation hears of those only when the task ends: the run's @@ -834,8 +877,15 @@ export function createLabAdapter(client: Client = connect()): LabAdapter { runFeeds.set(runSession, stop); } }; + // The board read's fields win: it names no time to compare, and a change after it sends a notice + // that reads again. The conversation's copy keeps what the read leaves out (a result's output). + const merged = (): Record[] => { + const all = new Map(rows); + for (const [id, row] of listed) all.set(id, { ...all.get(id), ...row }); + return [...all.values()]; + }; const publish = () => { - const current = [...rows.values()].map((row) => newer(row.run == null && runs.has(row.id) ? { ...row, run: runs.get(row.id) } : row)); + const current = merged().map(newer); const flowOf = (id: string) => (id === sessionId ? flowOfSession.get(sessionId) : runFlows.get(id)); const holds = holdsOfRows(sessionId, current, flowOf); openHolds.set(sessionId, holds); @@ -859,37 +909,21 @@ export function createLabAdapter(client: Client = connect()): LabAdapter { }), ).then(publish, (error) => console.error("teammates: a session's flow couldn't be read", error)); }; - // A run links itself on its own session, so the conversation hears of it only when the task ends: - // while a running row names no run, the board is read until it does, and the run's steps show as they happen. - const readWhileUnlinked = () => { - const unlinked = [...rows.values()].some((row) => row.status !== "completed" && row.status !== "errored" && row.status !== "cancelled" && row.run == null && !runs.has(row.id)); - if (!unlinked) { - stopRead?.(); - stopRead = undefined; - } else if (stopRead === undefined) { - stopRead = poll( - async () => { - const flow = flowOfSession.get(sessionId) ?? (await client.sessions.get(sessionId)).flowKind; - const listed = await client.flow(flow).read<{ ok: boolean; error?: string; tasks: Array> }>(LIST_TASKS, {}, { sessionId }); - if (!listed.ok) throw new Error(listed.error); - return listed.tasks.flatMap((task) => (task.run?.sessionId === undefined ? [] : [[task.id as string, task.run] as const])); - }, - (linked) => { - for (const [id, run] of linked) runs.set(id, run); - publish(); - readWhileUnlinked(); - }, - ); - } - }; + // A run links itself, and a task settles, on its own session: the board's notice says so. + const stopBoard = onBoardChange(client, sessionId, async () => { + const flow = flowOfSession.get(sessionId) ?? (await client.sessions.get(sessionId)).flowKind; + const read = await client.flow(flow).read<{ ok: boolean; error?: string; tasks: Array> }>(LIST_TASKS, {}, { sessionId }); + if (!read.ok) throw new Error(read.error); + listed = new Map(read.tasks.map((task) => [task.id as string, task])); + publish(); + }); const stopFeed = watchFeed(sessionId, boardRows, (read) => { rows = read; publish(); - readWhileUnlinked(); }); return () => { stopFeed(); - stopRead?.(); + stopBoard(); for (const stop of runFeeds.values()) stop(); }; }, diff --git a/labs/teammates/test/run-link.test.ts b/labs/teammates/test/run-link.test.ts index b96c72f5f6..cce0433813 100644 --- a/labs/teammates/test/run-link.test.ts +++ b/labs/teammates/test/run-link.test.ts @@ -1,14 +1,29 @@ /** * A coding task's run shows while it runs. The run links itself to its row on - * its own session, so the conversation that filed the task hears of the link - * only when the task ends; until then the popup would show nothing, and then - * every step at once. While a running row names no run, `watchTasks` reads the - * board until it does. + * its own session, so the conversation's own stream hears of the link only + * when the task ends; until then the popup would show nothing, and then every + * step at once. The link is a board change (FIX-2429): `watchTasks` reads the + * board on each notice of the conversation's board, and on a timer only where + * push can miss a change (`client.subscribe` owns that timer). */ import { describe, expect, it, vi } from "vitest"; -import type { Client } from "@flow-state-dev/client"; +import type { Client, SubscribeOptions, WireNotice, WireTopic } from "@flow-state-dev/client"; import { createLabAdapter, type BoardTask } from "../src/adapter"; +/** `client.subscribe`, faked: each subscription is kept so a case can deliver its notices. */ +function fakeSubscribe() { + const subscriptions: Array<{ topics: readonly WireTopic[]; options: SubscribeOptions; closed: boolean }> = []; + const subscribe = (topics: readonly WireTopic[], options: SubscribeOptions) => { + const entry = { topics, options, closed: false }; + subscriptions.push(entry); + return { close: () => void (entry.closed = true) }; + }; + const hear = (notice: WireNotice | null) => { + for (const s of subscriptions) if (!s.closed) s.options.onChange(notice); + }; + return { subscribe, subscriptions, hear }; +} + /** The conversation's one item: the board's row as filed, with no run yet. */ const filed = (status: string) => ({ id: "task-change:board/task_1", @@ -21,10 +36,12 @@ const filed = (status: string) => ({ data: { collectionId: "board", taskId: "task_1", kind: "added", task: { id: "task_1", title: "Fix the typo", status, assignee: "teammates.cursor" } }, }); -/** A client whose conversation holds `item`, and whose board read names the run once it has started. */ -function clientWith(item: ReturnType) { +/** A client whose conversation holds `item`, and whose board read names the run once `started`. */ +function clientWith(item: ReturnType, started = () => true) { const reads: string[] = []; + const push = fakeSubscribe(); const client = { + subscribe: push.subscribe, sessions: { state: async () => ({ at: 1, sessionCreatedAt: 1, items: [item], pagination: { hasMore: false, nextOffset: 1 } }), stream: () => ({ close() {} }), @@ -33,11 +50,11 @@ function clientWith(item: ReturnType) { flow: (flow: string) => ({ read: async (action: string) => { reads.push(`${flow}.${action}`); - return { ok: true, tasks: [{ ...item.data.task, run: { sessionId: "dsx_run", requestId: "req_run", attempt: 1 } }] }; + return { ok: true, tasks: [{ ...item.data.task, ...(started() ? { run: { sessionId: "dsx_run", requestId: "req_run", attempt: 1 } } : {}) }] }; }, }), } as unknown as Client; - return { client, reads }; + return { client, reads, push }; } const until = async (check: () => boolean) => { @@ -55,15 +72,84 @@ describe("a coding task's run, while it runs", () => { expect(reads).toContain("agent.listTasks_tasks"); }); - it("reads no board for a task that has ended: its row already says all there is", async () => { - const { client, reads } = clientWith(filed("completed")); + it("subscribes the conversation's board and plan ledgers, narrowed, with today's pace for where push can miss a change", async () => { + const { client, push } = clientWith(filed("in_progress")); + const stop = createLabAdapter(client).watchTasks("wks_1", () => {}); + await until(() => push.subscriptions.length > 0); + stop(); + expect(push.subscriptions[0]!.topics).toEqual([ + { scope: "session", id: "wks_1", resource: "tasks" }, + { scope: "session", id: "wks_1", resource: "plan" }, + ]); + expect(push.subscriptions[0]!.options.pollIntervalMs).toBe(1_500); + expect(push.subscriptions[0]!.closed).toBe(true); + }); + + it("names the run when its link's board notice arrives, and reads the board for nothing else", async () => { + let started = false; + const { client, reads, push } = clientWith(filed("in_progress"), () => started); + let tasks: BoardTask[] = []; + const stop = createLabAdapter(client).watchTasks("wks_1", (next) => (tasks = next)); + await until(() => reads.length === 1); + // No timer of its own: with no notice, the board is read once. + await new Promise((r) => setTimeout(r, 1_700)); + expect(reads).toHaveLength(1); + expect(tasks[0]?.runSessionId).toBeUndefined(); + started = true; + push.hear({ topic: { scope: "session", id: "wks_1", resource: "tasks" }, kind: "board" }); + await until(() => tasks[0]?.runSessionId !== undefined); + stop(); + expect(tasks[0]?.runSessionId).toBe("dsx_run"); + expect(reads).toHaveLength(2); + }); + + it("takes the board read's fields over the conversation's copy, which the read never names a time for", async () => { + // `listTasks` carries no `updatedAt`; the conversation's own copy does. + const item = filed("in_progress"); + const stamped = { ...item, data: { ...item.data, task: { ...item.data.task, updatedAt: 1 } } }; + const push = fakeSubscribe(); + let linked = false; + const client = { + subscribe: push.subscribe, + sessions: { + state: async () => ({ at: 1, sessionCreatedAt: 1, items: [stamped], pagination: { hasMore: false, nextOffset: 1 } }), + stream: () => ({ close() {} }), + get: async () => ({ id: "wks_1", flowKind: "agent" }), + }, + flow: () => ({ read: async () => ({ ok: true, tasks: [{ ...item.data.task, ...(linked ? { run: { sessionId: "dsx_run", requestId: "req_run", attempt: 1 } } : {}) }] }) }), + } as unknown as Client; let tasks: BoardTask[] = []; const stop = createLabAdapter(client).watchTasks("wks_1", (next) => (tasks = next)); await until(() => tasks.length > 0); await new Promise((r) => setTimeout(r, 50)); + linked = true; + push.hear({ topic: { scope: "session", id: "wks_1", resource: "tasks" }, kind: "board" }); + await until(() => tasks[0]?.runSessionId !== undefined); + stop(); + expect(tasks[0]?.runSessionId).toBe("dsx_run"); + }); + + it("shows a task that settled in its own session as the board reads it, newer than the conversation's copy", async () => { + const item = filed("in_progress"); + const push = fakeSubscribe(); + let status = "in_progress"; + const client = { + subscribe: push.subscribe, + sessions: { + state: async () => ({ at: 1, sessionCreatedAt: 1, items: [item], pagination: { hasMore: false, nextOffset: 1 } }), + stream: () => ({ close() {} }), + get: async () => ({ id: "wks_1", flowKind: "agent" }), + }, + flow: () => ({ read: async () => ({ ok: true, tasks: [{ ...item.data.task, status, updatedAt: status === "completed" ? 5 : 1 }] }) }), + } as unknown as Client; + let tasks: BoardTask[] = []; + const stop = createLabAdapter(client).watchTasks("wks_1", (next) => (tasks = next)); + await until(() => tasks.length > 0); + status = "completed"; + push.hear({ topic: { scope: "session", id: "wks_1", resource: "tasks" }, kind: "board" }); + await until(() => tasks[0]?.status === "done"); stop(); expect(tasks[0]?.status).toBe("done"); - expect(reads).toEqual([]); }); }); @@ -93,6 +179,7 @@ describe("a coding task's hold, while it runs", () => { }, }; return { + subscribe: fakeSubscribe().subscribe, sessions: { state: async (id: string) => ({ at: 1, sessionCreatedAt: 1, items: id === "dsx_run" ? [held] : [conversation], pagination: { hasMore: false, nextOffset: 1 } }), stream: () => ({ close() {} }), @@ -120,6 +207,7 @@ describe("a coding task's hold, while it runs", () => { const running = { ...conversation, data: { ...conversation.data, task: { ...conversation.data.task, run: { sessionId: "dsx_run", requestId: "req_run", attempt: 1 }, updatedAt: 1 } } }; const ended = { ...running, id: "task-change:board/task_1@end", ts: 3, itemIndex: 2, data: { ...running.data, kind: "completed", task: { ...running.data.task, status: "completed", updatedAt: 3 } } }; const client = { + subscribe: fakeSubscribe().subscribe, sessions: { state: async (id: string) => ({ at: 1, sessionCreatedAt: 1, items: id === "wks_1" ? [old, running] : [running], pagination: { hasMore: false, nextOffset: 1 } }), stream: (id: string, options: { onItem: (event: { item: unknown }) => void }) => { diff --git a/packages/contracts/src/types/change-notice.ts b/packages/contracts/src/types/change-notice.ts index c657577164..77b90906b9 100644 --- a/packages/contracts/src/types/change-notice.ts +++ b/packages/contracts/src/types/change-notice.ts @@ -18,10 +18,13 @@ * status moved, or deleted. * - `run` — a session record was written: the topic's own session, or a run * (a child session) under it. + * - `board` — a row on a task board changed (FIX-2429), on the topic of the + * session that filed it, narrowed to the board's id. The session stream + * ignores it: a board is read through its own read. * - `resync` — the bus may have missed notices (it reconnected). Every * subscriber reads once, whatever kinds it otherwise listens for. */ -export type ChangeKind = "items" | "request" | "run" | "resync"; +export type ChangeKind = "items" | "request" | "run" | "board" | "resync"; /** The scopes a topic can name. No other topic exists. */ export type TopicScope = "session" | "user" | "org"; diff --git a/packages/core/src/types/block.ts b/packages/core/src/types/block.ts index 0ad05ab03b..eec89ee214 100644 --- a/packages/core/src/types/block.ts +++ b/packages/core/src/types/block.ts @@ -17,6 +17,7 @@ import { DISPATCH_SEAM } from "./dispatch"; import type { RequestEndSeam, RequestSpendSeam } from "./request-end"; import { REQUEST_END_SEAM, REQUEST_SPEND_SEAM } from "./request-end"; import { REQUEST_RESUME_SEAM, type RequestResume } from "./request-resume"; +import { BOARD_NOTICE_SEAM, type BoardNoticeSeam } from "./board-notice"; import type { TracingLevel } from "../helpers/tracing-level"; import type { Content } from "../items/content"; import type { @@ -636,6 +637,13 @@ export interface BlockContext< */ [REQUEST_SPEND_SEAM]?: RequestSpendSeam; + /** + * @internal The running request's board-notice seam (FIX-2429), under a + * symbol key. Read only by `publishBoardChange`, which the task + * collection's change adapter calls. See `types/board-notice.ts`. + */ + [BOARD_NOTICE_SEAM]?: BoardNoticeSeam; + /** * @internal How the running request resumed (FIX-2129), under a symbol key. * Read only by `requestResumeOf`. See `types/request-resume.ts`. diff --git a/packages/core/src/types/board-notice.ts b/packages/core/src/types/board-notice.ts new file mode 100644 index 0000000000..338d894687 --- /dev/null +++ b/packages/core/src/types/board-notice.ts @@ -0,0 +1,46 @@ +/** + * The board-notice seam (FIX-2429): how a task board's change reaches the + * change bus, so every open view of the board reads again. + * + * Orchestration calls {@link publishBoardChange} where every board change + * already passes (the task collection's `onChange`), naming the session that + * filed the row and the board. The engine attaches the seam to every block + * context under {@link BOARD_NOTICE_SEAM}: it fills the tenant from the + * running request, names that request as the notice's origin, and publishes a + * `board` notice on that run's bus, on the session's topic narrowed to the + * board. The notice carries no rows: a view reads the board through its own + * checked read. + * + * Framework-facing, like the dispatch seam: a symbol key, not a public + * `ctx.publish`, so app code can't invent a topic. + */ + +/** What the engine's seam publishes: a board change, on a session's topic. */ +export interface BoardChange { + /** The bare session id whose board changed: the row's filer. */ + readonly sessionId: string; + /** The board's id (the ledger's `collectionId`), which narrows the topic. */ + readonly board: string; +} + +/** The seam the engine attaches under {@link BOARD_NOTICE_SEAM}. */ +export interface BoardNoticeSeam { + /** Publish a `board` notice for `change`. Never throws; a failed publish costs a view its wake. */ + publish(change: BoardChange): void; +} + +/** The context slot the engine attaches its board-notice seam under. */ +export const BOARD_NOTICE_SEAM: unique symbol = Symbol.for("@flow-state-dev/board-notice-seam"); + +/** + * Tell the open views of `change.board` on `change.sessionId` that it changed. + * + * @returns `false` when the context carries no seam (a hand-built test + * context): nothing is published. + */ +export function publishBoardChange(ctx: { readonly [BOARD_NOTICE_SEAM]?: BoardNoticeSeam }, change: BoardChange): boolean { + const seam = ctx[BOARD_NOTICE_SEAM]; + if (seam == null) return false; + seam.publish(change); + return true; +} diff --git a/packages/core/src/types/index.ts b/packages/core/src/types/index.ts index f557eef4e1..776ea87587 100644 --- a/packages/core/src/types/index.ts +++ b/packages/core/src/types/index.ts @@ -111,6 +111,10 @@ export type { RequestResume } from "./request-resume"; export { suspendForUserOn } from "./suspend-for-user"; export type { ApprovalAnswer, UserAnswer, SuspendForUser, SuspendForUserCancelled, SuspendForUserContext, SuspendForUserOptions } from "./suspend-for-user"; +/** The board-notice seam (FIX-2429): a task board's change reaches the change bus. */ +export { BOARD_NOTICE_SEAM, publishBoardChange } from "./board-notice"; +export type { BoardChange, BoardNoticeSeam } from "./board-notice"; + /** The request-end seam (FIX-2077): a framework package's hook after a request's last drain. */ export { REQUEST_END_SEAM, diff --git a/packages/engine/src/bus/board-notice.ts b/packages/engine/src/bus/board-notice.ts new file mode 100644 index 0000000000..5a7c208951 --- /dev/null +++ b/packages/engine/src/bus/board-notice.ts @@ -0,0 +1,28 @@ +/** + * The engine's half of the board-notice seam (FIX-2429): a task board's + * change, named by orchestration as a session and a board, published on the + * running request's bus. + * + * The seam fills what orchestration never names: the tenant, from the running + * request's verified identity, and the request itself as the notice's origin. + * The notice goes on the session's topic narrowed to the board, with kind + * `board`, through the same end-of-turn queue as the store writes' notices + * (`publish-writes.ts`), so a failed publish never fails the write it follows. + */ +import type { BoardNoticeSeam } from "@flow-state-dev/core/types"; +import { queueNotices } from "./publish-writes"; +import type { ChangeBus } from "./types"; + +/** The seam for one request: its bus, its tenant and its id. */ +export function createBoardNoticeSeam(bus: ChangeBus, request: { requestId: string; tenantId: string | undefined }): BoardNoticeSeam { + return { + publish: (change) => + queueNotices(bus, [ + { + topic: { scope: "session", id: change.sessionId, tenantId: request.tenantId ?? "", resource: change.board }, + kind: "board", + origin: { requestId: request.requestId } + } + ]) + }; +} diff --git a/packages/engine/src/bus/publish-writes.ts b/packages/engine/src/bus/publish-writes.ts index fb189fe916..92b28a6c1d 100644 --- a/packages/engine/src/bus/publish-writes.ts +++ b/packages/engine/src/bus/publish-writes.ts @@ -27,6 +27,9 @@ * | any other request write | `request` on its session, and `run` on that session's parent | * | any session write | `run` on the session, and on its parent | * + * A task board's change (`board`, narrowed to the board) is not a store write + * here: orchestration names it through the board-notice seam (`board-notice.ts`). + * * Not `persistEvents`, which feeds the request's own stream. A write that did * not land (a version conflict, a status predicate that failed) publishes * nothing. A failed publish never fails the write. Notices for one topic and @@ -116,6 +119,15 @@ function noticeKey(notice: ChangeNotice): string { return `${scope}\u0000${tenantId}\u0000${id}\u0000${resource ?? ""}\u0000${notice.kind}`; } +/** + * Queue `notices` for `bus`, to go out at the end of this microtask turn, + * folded as the store writes' notices are. Never throws. The board-notice + * seam (`board-notice.ts`) publishes through it. + */ +export function queueNotices(bus: ChangeBus, notices: readonly ChangeNotice[]): void { + publish(bus, notices); +} + /** Queue `notices` for `bus`, to go out at the end of this microtask turn. Never throws. */ function publish(bus: ChangeBus, notices: readonly ChangeNotice[]): void { let queued = pending.get(bus); diff --git a/packages/engine/src/context/createExecutionContext.ts b/packages/engine/src/context/createExecutionContext.ts index a6ddad4428..ea465008d0 100644 --- a/packages/engine/src/context/createExecutionContext.ts +++ b/packages/engine/src/context/createExecutionContext.ts @@ -1,6 +1,7 @@ import { WRITES_OUTLIVE_ABORT, attachRequestEndRegistry, createRequestEndRegistry, type WritesOutliveAbort } from "../execution/request-end-hooks"; import { createRequestSpendLedger, isInterruptedEndingHeld, loggedSpendOf, sumSpend } from "../execution/request-spend-ledger"; import { isOrgAttributed, UnattributedOrgError } from "./org-attribution"; +import { createBoardNoticeSeam } from "../bus/board-notice"; import { AsyncLocalStorage } from "node:async_hooks"; import type { AnyResourceRef, @@ -98,6 +99,7 @@ import { } from "../errors/error-capture"; import { SuspensionError, SuspensionRejectedError, SuspensionTimeoutError, resolveAllowedActions, type SuspendOptions } from "@flow-state-dev/core"; import { + BOARD_NOTICE_SEAM, DISPATCH_SEAM, REQUEST_RESUME_SEAM, REQUEST_SPEND_SEAM, @@ -1140,6 +1142,8 @@ export async function createExecutionContext< // `tenantMatches` is strict equality), so the option and the resolved value // cannot differ. Org is the one identity field whose check permits a // difference, which is why it is the one that had to change. + const boardNoticeSeam = + stores.bus !== undefined ? createBoardNoticeSeam(stores.bus, { requestId, tenantId: options.tenantId }) : undefined; const requestHostBuild = options.requestHost !== undefined ? createRequestHost({ @@ -3752,6 +3756,9 @@ export async function createExecutionContext< ...(requestHostBuild !== undefined ? { requestHost: requestHostBuild.host, [DISPATCH_SEAM]: requestHostBuild.seam } : {}), + // A task board's change reaches this run's bus (FIX-2429), under the + // request's tenant. No bus (a registry no entry wrapped): no seam. + ...(boardNoticeSeam !== undefined ? { [BOARD_NOTICE_SEAM]: boardNoticeSeam } : {}), settings: options.settings ?? {}, request: requestHandle, session: sessionHandle, diff --git a/packages/engine/test/bus/board-notice-seam.test.ts b/packages/engine/test/bus/board-notice-seam.test.ts new file mode 100644 index 0000000000..8958b659f0 --- /dev/null +++ b/packages/engine/test/bus/board-notice-seam.test.ts @@ -0,0 +1,91 @@ +/** + * The board-notice seam (FIX-2429): a task board's change reaches the bus of + * the run that made it, on the filing session's topic, narrowed to the board. + * + * Orchestration names the session and the board; the engine fills the tenant + * from the running request, stamps the request as `origin`, and publishes on + * that run's `stores.bus`. A view of another tenant or another board hears + * nothing. + */ +import { describe, expect, it } from "vitest"; +import { z } from "zod"; +import { DEFAULT_ORG_ID, defineFlow, handler } from "@flow-state-dev/core"; +import { publishBoardChange } from "@flow-state-dev/core/types"; +import { createInMemoryBus, createInMemoryStores, runAction, type ChangeNotice } from "../../src"; + +const inputSchema = z.object({ filer: z.string(), board: z.string() }); + +function boardFlow(published: boolean[]) { + return defineFlow({ + kind: "board-notices", + actions: { + settle: { + inputSchema, + block: handler({ + name: "settle", + inputSchema, + outputSchema: z.object({}), + execute: (input, ctx) => { + published.push(publishBoardChange(ctx, { sessionId: input.filer, board: input.board })); + return {}; + } + }) + } + } + })(); +} + +async function settle(options: { tenantId?: string; filer: string; board: string }) { + const bus = createInMemoryBus(); + const tenantId = options.tenantId ?? ""; + const narrowed: ChangeNotice[] = []; + bus.subscribe({ scope: "session", id: "conversation", tenantId, resource: "tasks" }, (n) => narrowed.push(n)); + const whole: ChangeNotice[] = []; + bus.subscribe({ scope: "session", id: "conversation", tenantId }, (n) => whole.push(n)); + const otherTenant: ChangeNotice[] = []; + bus.subscribe({ scope: "session", id: "conversation", tenantId: "other" }, (n) => otherTenant.push(n)); + const published: boolean[] = []; + const result = await runAction({ + orgId: DEFAULT_ORG_ID, + flow: boardFlow(published), + actionName: "settle", + input: { filer: options.filer, board: options.board }, + userId: "alice", + sessionId: "task-session", + ...(options.tenantId !== undefined ? { tenantId: options.tenantId } : {}), + stores: { ...createInMemoryStores(), bus }, + runtimeConfig: {} + }); + await new Promise((resolve) => setTimeout(resolve, 20)); + return { narrowed, whole, otherTenant, published, requestId: result.requestId }; +} + +describe("publishBoardChange · the engine's seam", () => { + it("publishes a board notice on the filer's session, narrowed to the board, with the request as origin", async () => { + const { narrowed, published, requestId } = await settle({ filer: "conversation", board: "tasks" }); + expect(published).toEqual([true]); + expect(narrowed).toEqual([ + { + topic: { scope: "session", id: "conversation", tenantId: "", resource: "tasks" }, + kind: "board", + origin: { requestId } + } + ]); + }); + + it("fills the tenant from the running request, so another tenant's view never hears it", async () => { + const { narrowed, otherTenant } = await settle({ tenantId: "acme", filer: "conversation", board: "tasks" }); + expect(narrowed.map((n) => n.topic.tenantId)).toEqual(["acme"]); + expect(otherTenant).toEqual([]); + }); + + it("reaches only that board's narrowed view", async () => { + const { narrowed, whole } = await settle({ filer: "conversation", board: "plan" }); + expect(narrowed).toEqual([]); + expect(whole.filter((n) => n.kind === "board").map((n) => n.topic.resource)).toEqual(["plan"]); + }); + + it("publishes nothing from a context with no seam", () => { + expect(publishBoardChange({}, { sessionId: "conversation", board: "tasks" })).toBe(false); + }); +}); diff --git a/packages/orchestration/README.md b/packages/orchestration/README.md index 75c858adfa..cad16cf961 100644 --- a/packages/orchestration/README.md +++ b/packages/orchestration/README.md @@ -91,7 +91,12 @@ denied. (the `taskBoard` default; survives block boundaries within a request), or on a state ref you pass, such as `ctx.sequencer` for one board invocation. `backing: "resource"` outlives the request: a user's queue, an org work pool, declared with `defineTaskCollection`. Every -mutation that changes a field emits a `task-change` component item. +mutation that changes a field emits a `task-change` component item on the writing session's +stream, and publishes a `board` change notice on the topic of the session that filed the row +(its `filer`, else the ledger's legacy filer, else the running session), narrowed to the +`collectionId`. A screen of the board subscribes that topic (`topic.session(id, { resource })`) +and reads again, whichever session or process settled the task. A context with no engine seam +(a hand-built test context) publishes nothing. **A ledger per partition.** A `user`-scoped collection can take a `partitionBy` function, keeping one set of rows per partition at the user's scope: diff --git a/packages/orchestration/src/tasks/collection/get-or-create.ts b/packages/orchestration/src/tasks/collection/get-or-create.ts index f928a95f44..ca5b5cea37 100644 --- a/packages/orchestration/src/tasks/collection/get-or-create.ts +++ b/packages/orchestration/src/tasks/collection/get-or-create.ts @@ -13,6 +13,7 @@ * these items, filter by `data.collectionId`, and render the board. */ import type { JsonObject } from "@flow-state-dev/core"; +import { publishBoardChange } from "@flow-state-dev/core/types"; import type { ItemVisibility, OutputItem } from "@flow-state-dev/core/items"; import type { BlockContext, @@ -165,7 +166,18 @@ export async function getOrCreateTaskCollection { + // A board notice beside the item: the item goes on the writing session's + // stream; the notice reaches every open view of the filer's board, from + // whichever session and process settles the row. Server-written (BP-031). + const filer = event.task.filer?.sessionId ?? legacyFiler?.(event.task) ?? runningSession; + if (filer !== undefined) publishBoardChange(options.ctx, { sessionId: filer, board: event.collectionId }); options.ctx.emit.component( TASK_CHANGE_COMPONENT_TYPE, { @@ -266,6 +278,14 @@ export async function getOrCreateTaskCollection string | undefined) | undefined { + if (options.backing !== "resource") return undefined; + const declared = options.collection.config; + const legacy = isDefinedTaskCollection(declared) ? declared.__taskCollection.delivery?.legacyFiler : undefined; + return legacy === undefined ? undefined : (row) => legacy(row, options.partition); +} + /** * The partition a resource-backed resolution reads, checked against the * ledger's declaration: a partitioned ledger is never read whole, and an diff --git a/packages/orchestration/test/tasks/board-notice.test.ts b/packages/orchestration/test/tasks/board-notice.test.ts new file mode 100644 index 0000000000..703aa5db60 --- /dev/null +++ b/packages/orchestration/test/tasks/board-notice.test.ts @@ -0,0 +1,110 @@ +/** + * A task board's change publishes a board notice (FIX-2429), from whichever + * session writes it, on the topic of the session that filed the row, narrowed + * to the board. + * + * Run through the real runtime, so the engine's seam is the one every block + * gets: a conversation files a row on a user-scoped ledger, and a task session + * (another session of the user) claims and settles it. The conversation's view + * of the board hears every write; the task session's own topic hears none, and + * a row with no filer (a board on request state) goes on the session that + * wrote it. + */ +import { describe, expect, it } from "vitest"; +import { DEFAULT_ORG_ID, defineFlow, handler } from "@flow-state-dev/core"; +import type { BlockContext } from "@flow-state-dev/core/types"; +import { createInMemoryBus, createInMemoryStores, runAction, type ChangeNotice } from "@flow-state-dev/engine"; +import { z } from "zod"; +import { defineTaskCollection, getOrCreateTaskCollection, resolveResourceCollection } from "../../src/tasks"; + +const BOARD = "desk"; + +async function desk(ctx: BlockContext) { + const collection = resolveResourceCollection(ctx, BOARD); + if (collection === undefined) throw new Error("the board is not declared"); + return getOrCreateTaskCollection({ ctx, backing: "resource", collectionId: BOARD, collection }); +} + +const flow = defineFlow({ + kind: "board-notice", + resources: { [BOARD]: defineTaskCollection({ id: BOARD, scope: "user", delivery: {} }) }, + actions: { + file: { + block: handler({ + name: "file", + outputSchema: z.object({ id: z.string() }), + execute: async (_input, ctx) => ({ id: (await (await desk(ctx)).createTask({ goal: "look it up", assignee: "researcher" })).id }) + }) + }, + settle: { + block: handler({ + name: "settle", + outputSchema: z.object({}), + execute: async (_input, ctx) => { + const board = await desk(ctx); + const claimed = await board.claim("researcher-worker"); + if (claimed === null) throw new Error("nothing to claim"); + await board.complete(claimed.id, { answer: 42 }); + return {}; + } + }) + }, + scratch: { + block: handler({ + name: "scratch", + outputSchema: z.object({}), + execute: async (_input, ctx) => { + const board = await getOrCreateTaskCollection({ ctx, backing: "state", collectionId: "scratch" }); + await board.createTask({ goal: "a step" }); + return {}; + } + }) + } + } +})(); + +function boot() { + const bus = createInMemoryBus(); + const stores = { ...createInMemoryStores(), bus }; + const heard = (id: string, resource?: string) => { + const notices: ChangeNotice[] = []; + bus.subscribe({ scope: "session", id, tenantId: "", ...(resource !== undefined ? { resource } : {}) }, (n) => { + if (n.kind === "board") notices.push(n); + }); + return notices; + }; + const run = async (actionName: "file" | "settle" | "scratch", sessionId: string) => { + const result = await runAction({ orgId: DEFAULT_ORG_ID, flow, actionName, input: {}, userId: "alice", sessionId, stores, runtimeConfig: {} }); + if (result.error !== undefined) throw new Error(`${actionName} failed: ${JSON.stringify(result.error)}`); + await new Promise((resolve) => setTimeout(resolve, 20)); + return result.requestId!; + }; + return { heard, run }; +} + +describe("a board change publishes a board notice", () => { + it("on the filer's session, narrowed to the board, for the filing and for a settle in another session", async () => { + const { heard, run } = boot(); + const conversationBoard = heard("conversation", BOARD); + const taskSession = heard("task-session"); + + const filed = await run("file", "conversation"); + expect(conversationBoard).toEqual([ + { topic: { scope: "session", id: "conversation", tenantId: "", resource: BOARD }, kind: "board", origin: { requestId: filed } } + ]); + + const settled = await run("settle", "task-session"); + // The claim and the completion, folded or not: each names the settling request. + expect(conversationBoard.length).toBeGreaterThan(1); + expect(conversationBoard.slice(1).every((n) => n.origin?.requestId === settled)).toBe(true); + // The session that wrote is not where the board's view listens. + expect(taskSession).toEqual([]); + }); + + it("on the running session for a row with no filer", async () => { + const { heard, run } = boot(); + const scratch = heard("worker", "scratch"); + await run("scratch", "worker"); + expect(scratch.map((n) => n.topic)).toEqual([{ scope: "session", id: "worker", tenantId: "", resource: "scratch" }]); + }); +}); diff --git a/packages/react/README.md b/packages/react/README.md index a5d983dd3b..2dbb7a1955 100644 --- a/packages/react/README.md +++ b/packages/react/README.md @@ -252,7 +252,7 @@ Low-level hook for direct action execution without session management. ### `useSubscription(topics, read, options?)` Runs `read` again when something under `topics` changes, through the provider's -client and `fsd.subscribe`. One read runs at a time and at most one more waits, +client (or `options.client`, a client you built yourself) and `fsd.subscribe`. One read runs at a time and at most one more waits, so a burst of changes is one more read. `read` gets the notice that woke it, or `null` when the screen should read everything again: after a connect or a reconnect, on a timer tick, and when push starts or stops reaching every server @@ -262,10 +262,11 @@ follow-up read covers them all). It doesn't read on mount. ```tsx import { topic } from "@flow-state-dev/client"; -useSubscription([topic.session(sessionId)], refresh, { pollIntervalMs: 3000 }); +useSubscription([topic.session(sessionId, { resource: "tasks" })], refresh, { pollIntervalMs: 3000 }); ``` -`pollIntervalMs` reads on a timer wherever push can miss a change (a host with +Narrow a session topic to the resource or task board the read shows, so a reply +streaming in the session doesn't wake it. `pollIntervalMs` reads on a timer wherever push can miss a change (a host with no push, a socket that is down); omit it for no timer. `enabled: false` subscribes nothing. For a session's own items, use `useSession({ live: true })`. @@ -681,11 +682,9 @@ import { BoardList } from "@flow-state-dev/react"; It reads the same rows `BoardColumns` does, through the same `sessionId`, `boardRef`, `client` and `limit`, and labels a row the same way, with the assignee beside it when there is one. Nothing is hidden: a finished or cancelled task stays in the list, and a status the component does not recognise shows as its own word. A row without a `createdAt` follows the dated ones, in read order. -`live` re-reads the board whenever the session named by `sessionId` records a change to it. Pass the id of the session whose runs write to the board. A change made in a different session shows after the list remounts, or the next time this session changes the board. With `live` off, the default, it reads on mount like the other panels. If the server doesn't offer the session stream, or refuses it, the list reads once and shows no error. +`live` re-reads the board whenever a task on it changes, in any session and on any server process: it subscribes `topic.session(sessionId, { resource: boardRef })`, where every board change is announced on the session that filed the task. Pass the id of the session that files the tasks, usually the conversation. A reply streaming in that session doesn't make it read. Where push can miss a change (a host with no push, a socket that is down) it reads every 3 s instead. With `live` off, the default, it reads on mount like the other panels. -Each live list opens its own connection to its session's stream while mounted, so a page that also calls `useSession(..., { live: true })` on that session holds two. - -The read and the live stream go through one `client`, so the stream carries the read's credential to the read's origin. Any client from `createClient` works. A client that can only read (it has `resources.listCollectionItems` but no `sessions.stream`) takes no `live`, and TypeScript rejects that pair. +The read and the live subscription go through one `client`, so the subscription carries the read's credential to the read's origin. Any client from `createClient` works, and every subscription on it shares one connection. A client that can only read (it has `resources.listCollectionItems` but no `subscribe`) takes no `live`, and TypeScript rejects that pair. The list renders the `
  • ` for every row and puts the task's id on it (`data-task-id`), so a `row` slot returns the body that goes inside one. diff --git a/packages/react/src/components/panels/BoardList.ts b/packages/react/src/components/panels/BoardList.ts index 3da1e576b4..4ab04c87e8 100644 --- a/packages/react/src/components/panels/BoardList.ts +++ b/packages/react/src/components/panels/BoardList.ts @@ -8,10 +8,10 @@ * status this version does not know still shows, as its own word, and no row * is hidden whatever its status. * - * With `live`, the list follows the session it reads through and reads the - * board again whenever that session keeps a change to it. A change kept in any - * other session shows on the list's next read. The rows drawn are always the - * read's, never a change's own payload. + * With `live`, the list reads the board again whenever it changes: a board + * notice on the session's topic, narrowed to the board, which a task settled + * in any session or process sends. Wherever push can miss a change it reads on + * a timer. The rows drawn are always the read's, never a notice's. * * Loading, empty and a failed read are three different renders. */ @@ -35,7 +35,7 @@ export type BoardListSlots = { }; type BoardListCommonProps = { - /** The session the read is addressed to, and, with `live`, the one the list follows. */ + /** The session the read is addressed to, and, with `live`, the one whose board notices it hears. */ readonly sessionId: string; /** * The key the session's flow declares this board's ledger under. One path @@ -53,17 +53,18 @@ type BoardListCommonProps = { }; /** - * What reads the board, and what the live stream is sent with: one client. + * What reads the board, and what the live subscription is sent with: one client. * - * - `client`: the host's own client, so the read and the live stream carry the - * host's transport and its credential. Pass a STABLE reference. Without + * - `client`: the host's own client, so the read and the subscription carry + * the host's transport and its credential. Pass a STABLE reference. Without * one, the panel uses the nearest `FlowProvider`'s user, `baseUrl` and * `fetcher`. - * - `live`: read the board again whenever the session keeps a change to it. + * - `live`: read the board again whenever it changes. * - * A live list's client must be able to stream (`sessions`): the stream goes - * through the same client as the read, so it carries the read's credential to - * the read's origin. A client that only reads takes no `live`. + * A live list's client must be able to subscribe (`subscribe`): the + * subscription goes through the same client as the read, so it carries the + * read's credential to the read's origin. A client that only reads takes no + * `live`. */ type BoardListTransportProps = | { readonly client?: PanelLiveSource; readonly live?: boolean } diff --git a/packages/react/src/components/panels/reads.ts b/packages/react/src/components/panels/reads.ts index c2d86d4de9..b29659ba2a 100644 --- a/packages/react/src/components/panels/reads.ts +++ b/packages/react/src/components/panels/reads.ts @@ -5,18 +5,11 @@ * reads one item. All go through the package's internal `useFencedRead` * (`internal/useFencedRead.ts`), which the flow navigator's reads share, so the * fence protocol lives there, once. A live `BoardList` reads its board again on - * the session's changes (`liveBoardDriver`). Internal on purpose — exporting a + * each board notice (`liveBoardDriver`). Internal on purpose — exporting a * read would let a host mount it twice. */ import { useMemo } from "react"; -import { - compareItemOrder, - readEveryCollectionPage, - type ResourcesApi, - type SessionsApi -} from "@flow-state-dev/client"; -import type { OutputItem } from "@flow-state-dev/core/items"; -import { followSession } from "@flow-state-dev/client/internal"; +import { readEveryCollectionPage, topic, type Client, type ResourcesApi } from "@flow-state-dev/client"; import { coalescedReads } from "../../internal/coalescedReads"; import { useFencedRead, type ReadDriver } from "../../internal/useFencedRead"; @@ -34,11 +27,11 @@ export type PanelRowSource = { readonly resources: Pick }; /** - * A live `BoardList`'s slice: the board read, and the session stream that says - * when to read it again. Both go through the one client, so the stream always - * carries the read's credential. + * A live `BoardList`'s slice: the board read, and the subscription that says + * when to read it again. Both go through the one client, so the subscription + * always carries the read's credential. */ -export type PanelLiveSource = PanelRowSource & { readonly sessions: Pick }; +export type PanelLiveSource = PanelRowSource & { readonly subscribe: Client["subscribe"] }; /** One row as a panel receives it: its topic, and the collection's projection of its state. */ export type PanelRow = { @@ -59,56 +52,38 @@ const EMPTY: PanelRow[] = []; /** - * Whether an item says a task on board `boardRef` changed. Two equality - * checks: the substrate's `task-change` component, naming this board. + * How often a live board reads on a timer wherever push can miss a change: a + * host with no push, a socket down, or a bus that doesn't cross processes. + * Where push covers the list it reads on a board notice, a connect and a + * reconnect only. */ -function namesBoard(item: OutputItem, boardRef: string): boolean { - if (item.type !== "component") return false; - const component = item as { component?: unknown; data?: { collectionId?: unknown } | null }; - return component.component === "task-change" && component.data?.collectionId === boardRef; -} +export const LIVE_BOARD_POLL_MS = 3_000; /** - * Read a board, and read it again whenever the session keeps a change to it. + * Read a board, and read it again whenever it changes (FIX-2429). * - * The stream opens before the board is read on mount, and its opening scan - * reaches back a minute on the server's own clock. So a change kept around - * the mount read, before it, during it or after it, is heard, and every change - * to this board heard for the first time reads it again, whichever scan finds - * it. A board with no change in the last minute costs one read on mount; a - * change the opening scan finds adds a read, coalesced with any others as - * below. Nothing here compares a server's clock with this page's. + * The list subscribes its session's topic narrowed to the board, through the + * client's `subscribe`, so a task settled in any session, on any process, + * reaches it as a board notice, and a streaming reply in the session (its + * `items` notices) never does. It reads on mount, on each notice, and on each + * connect, reconnect or timer tick (`null`), which may have missed a change. * * Reads are coalesced: one in flight, and one queued for any number of - * changes that arrive meanwhile. A copy the stream delivers again (the same - * request id and item id, stamped no later than one already heard), as a - * reconnect does, wakes nothing. What the item carries is never drawn: it says - * when to read, never what. A stream refused, missing or stopped leaves the - * rows as they are, with no error. + * notices that arrive meanwhile. A notice says when to read, never what: the + * rows drawn are always the read's. */ function liveBoardDriver(sessionId: string, boardRef: string, client: PanelLiveSource): ReadDriver { return (read) => { - const heard = new Map(); const reads = coalescedReads(read); - - const close = followSession({ - sessionId, - client, - itemTypes: ["component"], - onItem: ({ requestId, item }) => { - if (!namesBoard(item, boardRef)) return; - const key = `${requestId}\u0000${item.id}`; - const held = heard.get(key); - if (held !== undefined && compareItemOrder(item, held) <= 0) return; - heard.set(key, item); - reads.request(); - } + const subscription = client.subscribe([topic.session(sessionId, { resource: boardRef })], { + onChange: () => reads.request(), + pollIntervalMs: LIVE_BOARD_POLL_MS }); reads.request(); return () => { reads.close(); - close(); + subscription.close(); }; }; } @@ -130,7 +105,7 @@ function liveBoardDriver(sessionId: string, boardRef: string, client: PanelLiveS * so far (BR-19, BR-21). * * With `live`, `ref` is a task board, and the rows are read again whenever - * the session keeps a change to it (see `liveBoardDriver`). Without it they + * it changes (see `liveBoardDriver`). Without it they * are read once, on mount. */ export function usePanelRows( diff --git a/packages/react/src/hooks/useSubscription.ts b/packages/react/src/hooks/useSubscription.ts index 882206443d..4f3ea7b906 100644 --- a/packages/react/src/hooks/useSubscription.ts +++ b/packages/react/src/hooks/useSubscription.ts @@ -2,7 +2,8 @@ * `useSubscription(topics, read, options)` (FIX-2428): run a screen's read * again when something under `topics` changes. * - * It subscribes through the provider's client (`client.subscribe`), which + * It subscribes through the provider's client (`client.subscribe`), or the + * host's own when it passes `client`, which * owns the one socket and the timer: push on a host that has it, and a read * every `pollIntervalMs` wherever push can miss a change. The read goes * through the coalesced read, so a burst of notices is one read in flight @@ -14,7 +15,7 @@ * then. */ import { useEffect, useMemo, useRef } from "react"; -import type { WireNotice, WireTopic } from "@flow-state-dev/client"; +import type { Client, WireNotice, WireTopic } from "@flow-state-dev/client"; import { wireTopicKey } from "@flow-state-dev/contracts"; import { coalescedReads } from "../internal/coalescedReads"; import { useClient } from "../internal/useClient"; @@ -29,6 +30,12 @@ export type UseSubscriptionOptions = { pollIntervalMs?: number; /** `false` subscribes nothing. Default `true`. */ enabled?: boolean; + /** + * The client to subscribe through, for a host that holds its own (its own + * user, origin and `fetcher`, so the socket carries its credential). Pass a + * stable reference. Default: the provider's client. + */ + client?: Pick; }; /** One key per distinct topic list, so an equal list keeps the subscription. */ @@ -54,7 +61,8 @@ export function useSubscription( read: (notice: WireNotice | null) => unknown, options: UseSubscriptionOptions = {} ): void { - const client = useClient(); + const built = useClient(); + const client = options.client ?? built; const readRef = useRef(read); readRef.current = read; const key = topicsKey(topics); diff --git a/packages/react/test/board-list.test.ts b/packages/react/test/board-list.test.ts index 2685764b3e..c30fecd702 100644 --- a/packages/react/test/board-list.test.ts +++ b/packages/react/test/board-list.test.ts @@ -1,45 +1,42 @@ // @vitest-environment happy-dom /** * `BoardList`: one board as a list with each task's status (FIX-1622 V1), and - * its `live` re-read (V2, V3). + * its `live` re-read (V2, V3; on board notices since FIX-2429). * - * The stream is faked at the client seam, so each live case hands the list - * exactly the events it would get and counts the board reads it makes. Reads - * are counted rather than only the rows asserted, because a list that polls, - * or re-reads on every copy the stream repeats, draws the same rows. The - * transport cases run the real stream client against a host `fetch`, since - * "the stream carries the read's credential, to the read's origin" is the + * `client.subscribe` is faked at the client seam, so each live case hands the + * list exactly the notices it would hear and counts the board reads it makes. + * Reads are counted rather than only the rows asserted, because a list that + * polls, or re-reads on every notice of a burst, draws the same rows. The + * transport cases run the real client against a host `fetch`, since "the + * subscription carries the read's credential, to the read's origin" is the * list and the client together. * * Every read the list makes is held until the case releases it, so "a change - * that lands mid-read" is a change delivered while a read is still open. + * that lands mid-read" is a notice delivered while a read is still open. */ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { act, cleanup, render, screen, waitFor } from "@testing-library/react"; import { createElement } from "react"; -import type { OutputItem, SessionStreamEvent } from "@flow-state-dev/core/items"; -import { createClient, type SessionStreamOptions, type SessionsApi } from "@flow-state-dev/client"; +import { createClient, type Client, type SubscribeOptions, type WireNotice, type WireTopic } from "@flow-state-dev/client"; -const streams: Array<{ options: SessionStreamOptions & { sessionId: string }; closed: boolean }> = []; +const subscriptions: Array<{ topics: readonly WireTopic[]; options: SubscribeOptions; closed: boolean }> = []; -/** The session stream a host client opens, faked: captured so a case can drive it. */ -const fakeStream: SessionsApi["stream"] = (sessionId, options = {}) => { - const entry = { options: { sessionId, ...options }, closed: false }; - streams.push(entry); +/** `client.subscribe`, faked: captured so a case can deliver notices. */ +const fakeSubscribe: Client["subscribe"] = (topics, options) => { + const entry = { topics, options, closed: false }; + subscriptions.push(entry); return { close: () => { entry.closed = true; - }, - lastAt: undefined, - stopped: false + } }; }; -/** A host client: the board read the case controls, and the faked stream. */ +/** A host client: the board read the case controls, and the faked subscribe. */ function hostClient(resources: T) { - return { resources, sessions: { stream: fakeStream } } as unknown as { + return { resources, subscribe: fakeSubscribe } as unknown as { resources: T & import("@flow-state-dev/client").ResourcesApi; - sessions: Pick; + subscribe: Client["subscribe"]; }; } @@ -93,76 +90,31 @@ function fixedSource(items: Row[]) { return { listCollectionItems: vi.fn(async () => ({ items })) }; } -function openStream() { - const open = streams.filter((s) => !s.closed); +function openSubscription() { + const open = subscriptions.filter((s) => !s.closed); const last = open[open.length - 1]; - if (last === undefined) throw new Error("no open session stream"); - return last.options; -} - -function deliver(event: SessionStreamEvent): void { - const options = openStream(); - act(() => { - if (event.type === "session.item") options.onItem?.(event); - if (event.type === "session.runs") options.onRuns?.(event); - }); + if (last === undefined) throw new Error("no open subscription"); + return last; } -/** The notice every connection opens with; `at` is the point its first read reaches back to. */ -const opening = (at: number): SessionStreamEvent => ({ - stream: "session", - sessionId: SESSION, - at, - type: "session.runs", - runs: [] -}); - -function component( - requestId: string, - id: string, - name: string, - data: Record, - ts: number, - itemIndex = 0 -): OutputItem { - return { - id, - type: "component", - status: "completed", - requestId, - itemIndex, - ts, - provenance: { blockName: "b", blockInstanceId: "b_1", phase: "main" }, - component: name, - data - } as unknown as OutputItem; -} - -/** A `task-change` for `board`, carrying the whole row the way the session's item log does. */ -function taskChange(requestId: string, board: string, taskId: string, ts: number, task: Record = {}) { - return component( - requestId, - `tc_${taskId}`, - "task-change", - { collectionId: board, taskId, kind: "added", task: { id: taskId, status: "pending", ...task } }, - ts - ); +/** Hand the open subscription what `client.subscribe` would: a notice, or `null` for a connect, reconnect or tick. */ +function hear(notice: WireNotice | null): void { + const { options } = openSubscription(); + act(() => options.onChange(notice)); } -const itemEvent = (at: number, requestId: string, item: OutputItem): SessionStreamEvent => ({ - stream: "session", - sessionId: SESSION, - at, - type: "session.item", - requestId, - item +/** A board notice on the session's topic, narrowed to `board`. */ +const boardNotice = (board: string = BOARD): WireNotice => ({ + topic: { scope: "session", id: SESSION, resource: board }, + kind: "board", + origin: { requestId: "req_1" } }); const rowIds = () => [...document.querySelectorAll("li[data-task-id]")].map((li) => li.getAttribute("data-task-id")); const settle = () => act(async () => new Promise((resolve) => setTimeout(resolve, 20))); beforeEach(() => { - streams.length = 0; + subscriptions.length = 0; }); afterEach(() => { @@ -302,163 +254,64 @@ describe("BoardList · live (V2)", () => { ); } - /** - * Mount a live list, connect its stream with an opening scan that finds - * nothing for this board, and let the mount read land. Hands back the - * source at one read. - */ + /** Mount a live list and let its mount read land. Hands back the source at one read. */ async function mountLive(rows: Row[] = [card("t-1", "pending")]) { const source = heldSource(rows); const view = renderLive(source); - deliver(opening(100)); await source.release(); await waitFor(() => expect(rowIds()).toHaveLength(rows.length)); expect(source.listCollectionItems).toHaveBeenCalledTimes(1); return { source, view }; } - it("without live, opens no stream and reads once (BR-17)", async () => { + it("without live, subscribes nothing and reads once (BR-17)", async () => { const source = fixedSource([card("t-1", "pending")]); render(createElement(BoardList, { sessionId: SESSION, boardRef: BOARD, client: hostClient(source) })); await waitFor(() => expect(rowIds()).toEqual(["t-1"])); await settle(); - expect(streams).toHaveLength(0); + expect(subscriptions).toHaveLength(0); expect(source.listCollectionItems).toHaveBeenCalledTimes(1); }); - it("opens the session's stream, components only, before its first read", async () => { - const opened: string[] = []; + it("subscribes its session's topic narrowed to the board, with a timer for where push can miss a change, and reads on mount", async () => { const source = heldSource([]); - source.listCollectionItems.mockImplementationOnce(() => { - opened.push(streams.length === 1 ? "read after the stream" : "read before the stream"); - return new Promise(() => {}); - }); - renderLive(source); - expect(opened).toEqual(["read after the stream"]); - expect(streams[0]!.options).toMatchObject({ sessionId: SESSION, itemTypes: ["component"] }); - // No `since`: the first connection reaches back a minute. - expect(streams[0]!.options.since).toBeUndefined(); - }); - - it("reads once, on mount, when the opening scan finds nothing for this board", async () => { - const source = heldSource([card("t-1", "pending")]); renderLive(source); - deliver(opening(100)); - // The scan finds another board's change, and a component on this board - // that is not a task change. - deliver(itemEvent(100, "req_a", taskChange("req_a", "eng.feature.backlog", "t-9", Date.now()))); - deliver(itemEvent(100, "req_a", component("req_a", "cp_1", "note", { body: "hello", collectionId: BOARD }, Date.now()))); - await source.release(); - // A later notice on the same connection says the runs changed, not the board. - deliver(opening(1_100)); - await settle(); - expect(source.pending()).toBe(0); - expect(source.listCollectionItems).toHaveBeenCalledTimes(1); - }); - - it("reads once more when the opening scan finds changes to this board, however many", async () => { - const source = heldSource([card("t-1", "pending"), card("t-2", "pending")]); - renderLive(source); - deliver(opening(100)); - // Changes from 30 s ago and from just now, heard while the mount read is open. - deliver(itemEvent(100, "req_a", taskChange("req_a", BOARD, "t-1", Date.now() - 30_000))); - deliver(itemEvent(100, "req_b", taskChange("req_b", BOARD, "t-2", Date.now()))); - expect(source.pending()).toBe(1); - await source.release(); - expect(source.pending()).toBe(1); - await source.release(); - await settle(); - expect(source.pending()).toBe(0); - expect(source.listCollectionItems).toHaveBeenCalledTimes(2); - }); - - it("shows a change kept after the mount read that the stream delivers only in its opening scan", async () => { - const source = heldSource([]); - renderLive(source); - deliver(opening(100)); - // Every read the list has asked for so far lands before the change is kept. - while (source.pending() > 0) await source.release(); - source.setRows([card("t-new", "pending")]); - // The server named the runs, then began its first scan, which finds the - // change: it arrives as part of that opening scan and nowhere else. - deliver(itemEvent(100, "req_file", taskChange("req_file", BOARD, "t-new", Date.now()))); - await settle(); + expect(subscriptions).toHaveLength(1); + // Narrowed: a streaming reply's `items` notices on the session never wake it. + expect(subscriptions[0]!.topics).toEqual([{ scope: "session", id: SESSION, resource: BOARD }]); + expect(subscriptions[0]!.options.pollIntervalMs).toEqual(expect.any(Number)); + // The mount read: on a host with no push, nothing else reads before the first tick. expect(source.pending()).toBe(1); - await source.release(); - await waitFor(() => expect(rowIds()).toEqual(["t-new"])); }); - it("shows a change kept during its mount read with the page's clock 10 s ahead of the server's", async () => { - const source = heldSource([]); - renderLive(source); - // The stream connects while the mount read is still open. - deliver(opening(100)); - // The mount read reached the store just before the change was kept. - await source.release(); - source.setRows([card("t-new", "pending")]); - // The stream's first read finds the change, stamped by the server's clock, - // 10 s behind this page's. - deliver(itemEvent(100, "req_file", taskChange("req_file", BOARD, "t-new", Date.now() - 10_000))); - await settle(); + it("reads again on a connect or reconnect, which may have missed a change", async () => { + const { source } = await mountLive(); + hear(null); expect(source.pending()).toBe(1); await source.release(); - await waitFor(() => expect(rowIds()).toEqual(["t-new"])); - await settle(); expect(source.listCollectionItems).toHaveBeenCalledTimes(2); }); - it("reads nothing when a reconnect replays what the opening scan found (BR-12)", async () => { - const source = heldSource([card("t-1", "pending")]); - renderLive(source); - deliver(opening(100)); - const found = itemEvent(100, "req_a", taskChange("req_a", BOARD, "t-1", Date.now())); - deliver(found); - await source.release(); - await source.release(); - await settle(); - expect(source.listCollectionItems).toHaveBeenCalledTimes(2); - - // The connection drops; the next one's opening scan delivers the same change. - act(() => openStream().onReconnecting?.({ attempt: 1 })); - deliver(opening(1_100)); - deliver({ ...found, at: 1_100 }); + it("reads nothing until something under its topic changes", async () => { + const { source } = await mountLive(); await settle(); expect(source.pending()).toBe(0); - expect(source.listCollectionItems).toHaveBeenCalledTimes(2); + expect(source.listCollectionItems).toHaveBeenCalledTimes(1); }); - it("reads the board again on a change to it, and draws the read, never the change (BR-8, BR-9)", async () => { + it("reads the board again on a board notice, and draws the read, never anything the notice says (BR-8, BR-9)", async () => { const { source } = await mountLive([card("t-1", "pending", { title: "Charger fire" })]); - // The change says `completed` and carries fields the board withholds; the read says `pending`. - deliver(itemEvent(200, "req_1", taskChange("req_1", BOARD, "t-1", Date.now(), { status: "completed", metadata: { author: "x" } }))); + source.setRows([card("t-1", "completed", { title: "Charger fire" })]); + hear(boardNotice()); expect(source.pending()).toBe(1); await source.release(); - expect(source.listCollectionItems).toHaveBeenCalledTimes(2); - expect(document.querySelector('li[data-task-id="t-1"] [data-task-status]')?.textContent).toBe("pending"); - expect(document.body.textContent).not.toContain("completed"); - expect(document.body.textContent).not.toContain("author"); - }); - - it("reads nothing for another board's change, another kind of component, or an item that is not a component (BR-10)", async () => { - const { source } = await mountLive(); - deliver(itemEvent(200, "req_1", taskChange("req_1", "eng.feature.backlog", "t-9", Date.now()))); - deliver(itemEvent(200, "req_1", component("req_1", "cp_1", "note", { body: "hello", collectionId: BOARD }, Date.now()))); - deliver( - itemEvent(200, "req_1", { - ...(taskChange("req_1", BOARD, "t-8", Date.now()) as unknown as Record), - type: "message" - } as unknown as OutputItem) - ); - await settle(); - expect(source.listCollectionItems).toHaveBeenCalledTimes(1); + expect(document.querySelector('li[data-task-id="t-1"] [data-task-status]')?.textContent).toBe("completed"); }); it("reads at most once more for a burst, with one read in flight and one queued (BR-11)", async () => { const { source } = await mountLive(); - for (const n of [1, 2, 3, 4, 5]) { - deliver(itemEvent(200, `req_${n}`, taskChange(`req_${n}`, BOARD, `t-${n}`, Date.now()))); - } + for (let n = 0; n < 5; n += 1) hear(boardNotice()); // One in flight, and the other four queued as one. expect(source.pending()).toBe(1); await source.release(); @@ -472,10 +325,9 @@ describe("BoardList · live (V2)", () => { it("reads a change that lands while the mount read pages in exactly one read after it", async () => { const source = heldSource([]); renderLive(source); - deliver(opening(100)); - // Kept while the mount read is still open: that read may or may not hold it. - deliver(itemEvent(1_200, "req_file", taskChange("req_file", BOARD, "t-new", Date.now()))); - deliver(itemEvent(1_200, "req_more", taskChange("req_more", BOARD, "t-more", Date.now()))); + // Heard while the mount read is still open: that read may or may not hold it. + hear(boardNotice()); + hear(boardNotice()); source.setRows([card("t-new", "pending"), card("t-more", "pending")]); expect(source.pending()).toBe(1); await source.release(); @@ -487,87 +339,40 @@ describe("BoardList · live (V2)", () => { expect(source.listCollectionItems).toHaveBeenCalledTimes(2); }); - it("reads nothing for a copy the stream repeats across a reconnect, and reads a change kept during the drop (BR-12, BR-14)", async () => { - const { source } = await mountLive(); - const filed = taskChange("req_1", BOARD, "t-1", Date.now()); - deliver(itemEvent(1_100, "req_1", filed)); - await source.release(); - expect(source.listCollectionItems).toHaveBeenCalledTimes(2); - - // The connection drops; the next one resumes a little before where it - // left off, and its notice reads nothing. - act(() => openStream().onReconnecting?.({ attempt: 1 })); - deliver(opening(1_100)); - deliver(itemEvent(1_100, "req_1", filed)); - await settle(); - expect(source.listCollectionItems).toHaveBeenCalledTimes(2); - - // Kept while the stream was down: new to the list, so it reads. - deliver(itemEvent(1_100, "req_2", taskChange("req_2", BOARD, "t-2", Date.now() - 20_000))); - expect(source.pending()).toBe(1); - await source.release(); - expect(source.listCollectionItems).toHaveBeenCalledTimes(3); - }); - - it("reads for a later copy of the same keyed change, stamped after the one it heard", async () => { - const { source } = await mountLive(); - const ts = Date.now(); - deliver(itemEvent(1_100, "req_1", taskChange("req_1", BOARD, "t-1", ts))); - await source.release(); - deliver(itemEvent(2_100, "req_1", { ...(taskChange("req_1", BOARD, "t-1", ts + 5) as object), itemIndex: 3 } as OutputItem)); - expect(source.pending()).toBe(1); - }); - - it("keeps its rows and says nothing when the stream is refused, and reads nothing more (BR-15)", async () => { - for (const status of [401, 404, 501]) { - streams.length = 0; - const source = heldSource([card("t-1", "pending")]); - renderLive(source); - await source.release(); - await waitFor(() => expect(rowIds()).toEqual(["t-1"])); - act(() => openStream().onStop?.({ status })); - await settle(); - expect(rowIds()).toEqual(["t-1"]); - expect(document.querySelector('[role="alert"]')).toBeNull(); - expect(source.listCollectionItems).toHaveBeenCalledTimes(1); - cleanup(); - } - }); - it("does not show loading over its rows while it reads them again", async () => { - const { source } = await mountLive([card("t-1", "pending")]); - deliver(itemEvent(1_100, "req_1", taskChange("req_1", BOARD, "t-2", Date.now()))); - expect(source.pending()).toBe(1); + await mountLive([card("t-1", "pending")]); + hear(boardNotice()); expect(document.querySelector('[data-state="loading"]')).toBeNull(); expect(rowIds()).toEqual(["t-1"]); }); - it("closes its stream on unmount, and on a new board discards the old board's read (BR-18)", async () => { + it("closes its subscription on unmount, and on a new board discards the old board's read (BR-18)", async () => { const source = heldSource([card("t-1", "pending")]); const props = { sessionId: SESSION, client: hostClient(source), live: true } as const; const view = render(createElement(BoardList, { ...props, boardRef: BOARD })); - const first = streams[0]!; + const first = subscriptions[0]!; // The old board's read is still open when the board changes. view.rerender(createElement(BoardList, { ...props, boardRef: "eng.feature.backlog" })); expect(first.closed).toBe(true); - expect(streams.filter((s) => !s.closed)).toHaveLength(1); + const open = subscriptions.filter((s) => !s.closed); + expect(open.map((s) => s.topics)).toEqual([[{ scope: "session", id: SESSION, resource: "eng.feature.backlog" }]]); source.setRows([card("t-2", "pending")]); await source.release(); await source.release(); await waitFor(() => expect(rowIds()).toEqual(["t-2"])); view.unmount(); - expect(streams.every((s) => s.closed)).toBe(true); + expect(subscriptions.every((s) => s.closed)).toBe(true); }); }); // --------------------------------------------------------------------------- -// V3 · the stream's credential +// V3 · the subscription's credential // --------------------------------------------------------------------------- -describe("BoardList · the stream carries the read's credential, to the read's origin (V3, BR-16)", () => { +describe("BoardList · the subscription carries the read's credential, to the read's origin (V3, BR-16)", () => { // The real client, against a host `fetch`: one transport for the read and - // the stream is the client and the list together. + // the subscription is the client and the list together. function hostFetchAnswering(rows: Row[]) { const sent: Array<{ url: string; authorization: string | null }> = []; const fetcher = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { @@ -575,14 +380,14 @@ describe("BoardList · the stream carries the read's credential, to the read's o headers.set("authorization", "Bearer host-token"); const url = String(input); sent.push({ url, authorization: headers.get("authorization") }); - // A stream refused for good, so the client stops and the case ends quietly. - if (url.includes("/stream")) return new Response(null, { status: 404 }); + // A host with no push, so the client reads on its timer and the case ends quietly. + if (url.includes("/capabilities")) return new Response(JSON.stringify({ push: null }), { status: 200 }); return new Response(JSON.stringify({ items: rows }), { status: 200 }); }); return { fetcher, sent }; } - it("sends the read and the stream through the host's client, header and all", async () => { + it("sends the read and the subscription through the host's client, header and all", async () => { // The plain `fetch`: anything that reaches it went out without the host's header. const plain = vi.fn(async () => new Response(null, { status: 401 })); vi.stubGlobal("fetch", plain); @@ -591,12 +396,12 @@ describe("BoardList · the stream carries the read's credential, to the read's o render(createElement(BoardList, { sessionId: SESSION, boardRef: BOARD, client, live: true })); await waitFor(() => expect(rowIds()).toEqual(["t-1"])); - await waitFor(() => expect(host.sent.some((s) => s.url.includes(`/sessions/${SESSION}/stream`))).toBe(true)); + await waitFor(() => expect(host.sent.some((s) => s.url.includes("/capabilities"))).toBe(true)); expect(host.sent.every((s) => s.authorization === "Bearer host-token")).toBe(true); expect(plain).not.toHaveBeenCalled(); }); - it("reads and streams through the provider's fetch when the host passes no client", async () => { + it("reads and subscribes through the provider's fetch when the host passes no client", async () => { const plain = vi.fn(async () => new Response(null, { status: 401 })); vi.stubGlobal("fetch", plain); const host = hostFetchAnswering([card("t-1", "pending")]); @@ -610,13 +415,13 @@ describe("BoardList · the stream carries the read's credential, to the read's o await waitFor(() => expect(rowIds()).toEqual(["t-1"])); await waitFor(() => expect(host.sent.map((s) => new URL(s.url, window.location.href).pathname)).toEqual( - expect.arrayContaining([`/api/flows/sessions/${SESSION}/stream`, `/api/flows/sessions/${SESSION}/resources/${BOARD}`]) + expect.arrayContaining(["/api/flows/capabilities", `/api/flows/sessions/${SESSION}/resources/${BOARD}`]) ) ); expect(plain).not.toHaveBeenCalled(); }); - it("sends the stream to the origin the host's client reads, not the provider's", async () => { + it("subscribes at the origin the host's client reads, not the provider's", async () => { const plain = vi.fn(async () => new Response(null, { status: 401 })); vi.stubGlobal("fetch", plain); const host = hostFetchAnswering([card("t-1", "pending")]); @@ -628,7 +433,7 @@ describe("BoardList · the stream carries the read's credential, to the read's o children: createElement(BoardList, { sessionId: SESSION, boardRef: BOARD, client, live: true }) }) ); - await waitFor(() => expect(host.sent.some((s) => s.url.includes("/stream"))).toBe(true)); + await waitFor(() => expect(host.sent.some((s) => s.url.includes("/capabilities"))).toBe(true)); expect(new Set(host.sent.map((s) => new URL(s.url).origin))).toEqual(new Set(["https://boards.example"])); expect(plain).not.toHaveBeenCalled(); }); diff --git a/packages/react/test/useSubscription.test.ts b/packages/react/test/useSubscription.test.ts index 89ccc5192d..b35f5fb2f1 100644 --- a/packages/react/test/useSubscription.test.ts +++ b/packages/react/test/useSubscription.test.ts @@ -202,6 +202,19 @@ describe("useSubscription", () => { expect(subscriptions).toEqual([]); }); + it("subscribes through a host's own client when it passes one, so the socket carries that client's credential", () => { + const own: Array = []; + const client = { + subscribe: (topics: readonly WireTopic[]) => { + own.push(topics); + return { close() {} }; + } + }; + renderHook(() => useSubscription([S1], () => {}, { client })); + expect(own).toEqual([[S1]]); + expect(subscriptions).toEqual([]); + }); + it("drops a waiting read on unmount", async () => { const gate = gatedRead(); const { unmount } = renderHook(() => useSubscription([S1], gate.read)); diff --git a/packages/shift-manager/src/components/TaskBoardMeta.tsx b/packages/shift-manager/src/components/TaskBoardMeta.tsx index 2a9b020da7..25aaf1185c 100644 --- a/packages/shift-manager/src/components/TaskBoardMeta.tsx +++ b/packages/shift-manager/src/components/TaskBoardMeta.tsx @@ -4,7 +4,8 @@ * filed. Any other board is drawn by `TaskPlan` (`flow-state/task-plan.tsx`, * byte-equal to the registry, no router). */ -import { createContext, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; +import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; +import { useSubscription } from "@flow-state-dev/react"; import type { ComponentItem, OutputItem } from "@flow-state-dev/core/items"; import { ERROR_REPORTER_FLOW } from "@flow-state-dev/workforce/browser"; import { SessionItemsProvider, useSessionItems } from "./flow-state/session-items-context"; @@ -14,7 +15,7 @@ import { isOpen, TASKS_POLL_MS } from "./TasksPanel"; import { STATE_OF_COLUMN, StateSquare } from "./ui"; import { columnFor } from "../lib/columns"; import { useConversationSession } from "../lib/conversation"; -import { readConversationTasks, type ConversationTask } from "../lib/conversation-tasks"; +import { conversationBoardTopics, readConversationTasks, type ConversationTask } from "../lib/conversation-tasks"; import { workerLabel } from "../lib/derive"; import { useLab } from "../lib/lab-data"; import { CONVERSATION_BOARD_COLLECTION, conversationBoardRef } from "../lib/reads"; @@ -63,44 +64,48 @@ function isConversationTaskChange(item: OutputItem): boolean { } /** - * A failed read leaves the last one, or the feed's record, and is tried again while a task could be moving. - * A read that shows a task moved reloads the Lab, so what the snapshot counts agrees with the card. + * Reads on mount, when the Lab is read again, and on each board notice + * (FIX-2429). Wherever push can miss a change it reads on a timer, only while a + * task could be moving. A failed read leaves the last one, or the feed's + * record, and keeps the timer. A read that shows a task moved reloads the Lab, + * so what the snapshot counts agrees with the card. */ function LiveBoard({ flow, sessionId, boardRef, children }: { flow: string; sessionId: string; boardRef: string; children: ReactNode }) { const { client, snapshot, refresh } = useLab(); const readAt = snapshot !== undefined && "readAt" in snapshot ? snapshot.readAt : undefined; const [read, setRead] = useState<{ sessionId: string; tasks: ReadonlyMap } | undefined>(undefined); - const [polls, setPolls] = useState(0); // Whether the last read left a task that can still move; before any read lands, assume one can. - const moving = useRef(true); + const [moving, setMoving] = useState(true); // Each task and where it stood at the last read. const standing = useRef(undefined); + // Only the latest read started may land. + const latest = useRef(0); useEffect(() => { - moving.current = true; + setMoving(true); standing.current = undefined; }, [flow, sessionId]); + const readBoard = useCallback(async () => { + const mine = ++latest.current; + try { + const tasks = await readConversationTasks(client, flow, sessionId); + if (mine !== latest.current) return; + setRead({ sessionId, tasks: new Map(tasks.map((task) => [task.id, task])) }); + const now = tasks.map((task) => `${task.id}:${task.status}`).join(","); + if (standing.current !== undefined && standing.current !== now) void refresh(); + standing.current = now; + setMoving(tasks.some(isOpen)); + } catch { + // The last read stands; the timer, if any, stays on. + } + }, [client, refresh, flow, sessionId]); + useEffect(() => { - let closed = false; - let next: ReturnType | undefined; - readConversationTasks(client, flow, sessionId) - .then((tasks) => { - if (closed) return; - setRead({ sessionId, tasks: new Map(tasks.map((task) => [task.id, task])) }); - const now = tasks.map((task) => `${task.id}:${task.status}`).join(","); - if (standing.current !== undefined && standing.current !== now) void refresh(); - standing.current = now; - moving.current = tasks.some(isOpen); - if (moving.current) next = setTimeout(() => setPolls((n) => n + 1), TASKS_POLL_MS); - }) - .catch(() => { - if (!closed && moving.current) next = setTimeout(() => setPolls((n) => n + 1), TASKS_POLL_MS); - }); - return () => { - closed = true; - if (next !== undefined) clearTimeout(next); - }; - }, [client, refresh, flow, sessionId, readAt, polls]); + void readBoard(); + }, [readBoard, readAt]); + + const topics = useMemo(() => conversationBoardTopics(sessionId), [sessionId]); + useSubscription(topics, readBoard, { client, ...(moving ? { pollIntervalMs: TASKS_POLL_MS } : {}) }); const board = useMemo(() => ({ boardRef, read: read?.sessionId === sessionId ? read.tasks : undefined }), [boardRef, read, sessionId]); return {children}; diff --git a/packages/shift-manager/src/components/TasksPanel.tsx b/packages/shift-manager/src/components/TasksPanel.tsx index 829fe7da04..508d1b2ea6 100644 --- a/packages/shift-manager/src/components/TasksPanel.tsx +++ b/packages/shift-manager/src/components/TasksPanel.tsx @@ -5,21 +5,23 @@ * nothing, so a poll costs no request (FIX-2286). Each conversation * keeps a board of its own, so this reads that one board and nothing else. * - * It reads when it opens and again each time the Lab is read again - * (`readAt`), which is after each turn the user sends: a task filed or - * reassigned in that turn shows then. A task ends between those turns, and - * its ending wakes a coordinator turn of its own, so while a task is open the - * panel reads again every {@link TASKS_POLL_MS}; when a read shows a task - * moved, it reloads the Lab, and it keeps reading for a while after, so the - * turn that ending woke (a task filed again, say) shows too. Nothing here - * knows a tool's name. + * It reads when it opens, again each time the Lab is read again (`readAt`), + * which is after each turn the user sends, and on every board notice + * (FIX-2429): a task filed, moved or settled in any session, on any process, + * on the conversation's board or its plan ledger. Wherever push can miss a + * change (no push, the socket down, a bus that doesn't cross, as the SQLite + * store's) it reads every {@link TASKS_POLL_MS} instead, but only while a task + * is open or for a while after one moved, as it always has: its ending wakes a + * coordinator turn of its own, and the turn's follow-up shows too. When a read + * shows a task moved, it reloads the Lab. Nothing here knows a tool's name. */ -import { useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useSubscription } from "@flow-state-dev/react"; import { ChevronRightIcon } from "lucide-react"; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; import { columnFor, isDone } from "../lib/columns"; import { workerLabel } from "../lib/derive"; -import { readConversationTasks, type ConversationTask } from "../lib/conversation-tasks"; +import { conversationBoardTopics, readConversationTasks, type ConversationTask } from "../lib/conversation-tasks"; import { useLab } from "../lib/lab-data"; import { conversationBoardRef, describeFailure, type Worker } from "../lib/reads"; import { RouteLink } from "./RouteLink"; @@ -27,10 +29,10 @@ import { STATE_OF_COLUMN, StateSquare } from "./ui"; type Read = { tasks: ConversationTask[] } | { failure: string } | undefined; -/** How often the panel reads again while a task is open, or just moved. */ +/** How often the panel reads on a timer, where push can miss a change, while a task is open or just moved. */ export const TASKS_POLL_MS = 3_000; -/** How long the panel keeps reading after a task moved: the turn its ending woke runs in that time. */ -const AFTER_A_MOVE_MS = 30_000; +/** How long the panel keeps its timer after a task moved: the turn its ending woke runs in that time. */ +export const AFTER_A_MOVE_MS = 30_000; /** Whether a task can still move by itself. */ export const isOpen = (task: ConversationTask) => task.status === "pending" || task.status === "in_progress"; @@ -53,41 +55,47 @@ export function TasksPanel({ }) { const { client, refresh } = useLab(); const [read, setRead] = useState(undefined); - const [polls, setPolls] = useState(0); + // Whether the last read left a task open, or one just moved: the timer's gate. + const [timed, setTimed] = useState(false); // The last read's standing, and when a task last moved. const last = useRef<{ standing?: string; movedAt: number }>({ movedAt: 0 }); + // Only the latest read started may land: an older one finishing late would draw a board that moved on. + const latest = useRef(0); // Another conversation's tasks never show under this one. A read again of the // same conversation keeps its list up until the new answer lands. useEffect(() => { setRead(undefined); + setTimed(false); last.current = { movedAt: 0 }; }, [worker.kind, sessionId]); - useEffect(() => { + const readTasks = useCallback(async () => { if (sessionId === null || worker.kind === null) return; - let closed = false; - let next: ReturnType | undefined; - readConversationTasks(client, worker.kind, sessionId) - .then((tasks) => { - if (closed) return; - setRead({ tasks }); - const now = standing(tasks); - if (last.current.standing !== undefined && last.current.standing !== now) { - last.current.movedAt = Date.now(); - void refresh(); - } - last.current.standing = now; - if (tasks.some(isOpen) || Date.now() - last.current.movedAt < AFTER_A_MOVE_MS) { - next = setTimeout(() => setPolls((n) => n + 1), TASKS_POLL_MS); - } - }) - .catch((error: unknown) => !closed && setRead({ failure: describeFailure(error).message })); - return () => { - closed = true; - if (next !== undefined) clearTimeout(next); - }; - }, [client, refresh, worker.kind, sessionId, readAt, polls]); + const mine = ++latest.current; + try { + const tasks = await readConversationTasks(client, worker.kind, sessionId); + if (mine !== latest.current) return; + setRead({ tasks }); + const now = standing(tasks); + if (last.current.standing !== undefined && last.current.standing !== now) { + last.current.movedAt = Date.now(); + void refresh(); + } + last.current.standing = now; + setTimed(tasks.some(isOpen) || Date.now() - last.current.movedAt < AFTER_A_MOVE_MS); + } catch (error: unknown) { + if (mine === latest.current) setRead({ failure: describeFailure(error).message }); + } + }, [client, refresh, worker.kind, sessionId]); + + // On open, and after each turn the user sends. + useEffect(() => { + void readTasks(); + }, [readTasks, readAt]); + + const topics = useMemo(() => (sessionId === null || worker.kind === null ? [] : conversationBoardTopics(sessionId)), [sessionId, worker.kind]); + useSubscription(topics, readTasks, { client, ...(timed ? { pollIntervalMs: TASKS_POLL_MS } : {}) }); if (sessionId === null || worker.kind === null) { return ( diff --git a/packages/shift-manager/src/lib/conversation-tasks.ts b/packages/shift-manager/src/lib/conversation-tasks.ts index 9a3238e8b8..cb9b4c515a 100644 --- a/packages/shift-manager/src/lib/conversation-tasks.ts +++ b/packages/shift-manager/src/lib/conversation-tasks.ts @@ -5,9 +5,26 @@ * an action (FIX-2286), so a panel polling it stores no request per look; a * refusal comes back as an `ActionRefused` carrying its reason. */ -import { ClientHttpError, type Client } from "@flow-state-dev/client"; +import { ClientHttpError, topic, type Client, type WireTopic } from "@flow-state-dev/client"; import { ActionRefused } from "./action"; -import { describeFailure } from "./reads"; +import { CONVERSATION_BOARD_COLLECTION, describeFailure } from "./reads"; + +/** The plan ledger's id (Workforce's `PLAN_LEDGER_ID`, pinned): a planning worker's own steps. */ +const PLAN_COLLECTION = "plan"; + +/** + * The topics a view of the conversation's `listTasks` read subscribes + * (FIX-2429): the conversation's session, narrowed to each ledger the read + * returns. The read merges the board with the plan ledger, so its views hear + * both; a flow with no planning worker never publishes on `plan`. Narrowed, + * so a reply streaming in the conversation never wakes the view. + */ +export function conversationBoardTopics(sessionId: string): WireTopic[] { + return [ + topic.session(sessionId, { resource: CONVERSATION_BOARD_COLLECTION }), + topic.session(sessionId, { resource: PLAN_COLLECTION }), + ]; +} /** * The read a coordinator conversation lists its tasks by: the task tools' diff --git a/packages/shift-manager/test/conversation-tasks-panel.test.tsx b/packages/shift-manager/test/conversation-tasks-panel.test.tsx index 152f8774af..590d0e0071 100644 --- a/packages/shift-manager/test/conversation-tasks-panel.test.tsx +++ b/packages/shift-manager/test/conversation-tasks-panel.test.tsx @@ -10,6 +10,7 @@ */ import { act, cleanup, render, screen } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { SubscribeOptions, WireNotice, WireTopic } from "@flow-state-dev/client"; import { TASKS_POLL_MS, TasksPanel } from "../src/components/TasksPanel"; import { toWorker } from "../src/lib/reads"; @@ -19,11 +20,36 @@ let refusal: string | null = null; const calls: string[] = []; const refreshes: number[] = []; +const { subscriptions } = vi.hoisted(() => ({ + subscriptions: [] as Array<{ topics: readonly WireTopic[]; options: SubscribeOptions; closed: boolean }>, +})); vi.mock("../src/lib/lab-data", () => { - const lab = { client: { userId: "alice" }, refresh: async () => void refreshes.push(Date.now()) }; + // The Lab's one client, its `subscribe` faked so a case delivers the notices. + const subscribe = (topics: readonly WireTopic[], options: SubscribeOptions) => { + const entry = { topics, options, closed: false }; + subscriptions.push(entry); + return { close: () => void (entry.closed = true) }; + }; + const lab = { client: { userId: "alice", subscribe }, refresh: async () => void refreshes.push(Date.now()) }; return { useLab: () => lab }; }); -vi.mock("../src/lib/conversation-tasks", () => ({ + +/** The panel's open subscription. */ +function open() { + const live = subscriptions.filter((s) => !s.closed); + if (live.length === 0) throw new Error("no open subscription"); + return live[live.length - 1]!; +} + +/** Hand the open subscription a notice, or `null` for a connect, reconnect or tick. */ +async function hear(notice: WireNotice | null) { + await act(async () => { + open().options.onChange(notice); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); +} +vi.mock("../src/lib/conversation-tasks", async (importOriginal) => ({ + conversationBoardTopics: (await importOriginal()).conversationBoardTopics, readConversationTasks: async (_c: unknown, flow: string, sessionId: string) => { calls.push(`list ${flow} ${sessionId}`); if (refusal !== null) throw new Error(refusal); @@ -38,6 +64,7 @@ beforeEach(() => { refusal = null; calls.length = 0; refreshes.length = 0; + subscriptions.length = 0; }); afterEach(cleanup); @@ -164,32 +191,48 @@ describe("the tasks panel (S11)", () => { }); }); - describe("a task that ends between the user's lines", () => { - beforeEach(() => vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] })); - afterEach(() => vi.useRealTimers()); - const tick = (ms: number) => act(async () => void (await vi.advanceTimersByTimeAsync(ms))); + describe("a task that ends between the user's lines (board notices, FIX-2429)", () => { + it("subscribes the conversation's board and plan ledgers, narrowed, through the Lab's client", async () => { + render(); + await settle(); + expect(open().topics).toEqual([ + { scope: "session", id: "s1", resource: "tasks" }, + { scope: "session", id: "s1", resource: "plan" }, + ]); + }); - it("is read again while a task is open, and reloads the Lab when one ends, so the coordinator's turn on it shows", async () => { + it("reads again on a board notice, and reloads the Lab when a task moved, so the coordinator's turn on it shows", async () => { rows = [{ id: "t1", goal: "Audit the licenses", status: "in_progress", assignee: "licenses", attempts: 1 }]; render(); - await tick(0); + await settle(); expect(calls).toHaveLength(1); - await tick(TASKS_POLL_MS); - expect(calls).toHaveLength(2); - expect(refreshes).toHaveLength(0); rows = [{ id: "t1", goal: "Audit the licenses", status: "completed", assignee: "licenses", attempts: 1 }]; - await tick(TASKS_POLL_MS); + await hear({ topic: { scope: "session", id: "s1", resource: "tasks" }, kind: "board" }); + expect(calls).toHaveLength(2); expect(shown()).toEqual([{ id: "t1", status: "completed", text: expect.stringContaining("Audit the licenses") }]); expect(refreshes).toHaveLength(1); }); - it("reads nothing more while no task is open and none just ended", async () => { + it("keeps a timer for where push can miss a change only while a task is open or just moved", async () => { + rows = [{ id: "t1", goal: "Audit the licenses", status: "in_progress", assignee: "licenses", attempts: 1 }]; + render(); + await settle(); + expect(open().options.pollIntervalMs).toBe(TASKS_POLL_MS); + // It ends: the timer stays through the turn its ending wakes. + rows = [{ id: "t1", goal: "Audit the licenses", status: "completed", assignee: "licenses", attempts: 1 }]; + await hear(null); + expect(open().options.pollIntervalMs).toBe(TASKS_POLL_MS); + }); + + it("keeps no timer while no task is open and none just moved, and still hears every notice", async () => { rows = [{ id: "t1", goal: "Audit the licenses", status: "completed", assignee: "licenses", attempts: 1 }]; render(); - await tick(0); - await tick(TASKS_POLL_MS * 20); + await settle(); + expect(open().options.pollIntervalMs).toBeUndefined(); expect(calls).toEqual(["list coordinator s1"]); - expect(refreshes).toHaveLength(0); + rows = [...rows, { id: "t2", goal: "Write the release notes", status: "pending", attempts: 0 }]; + await hear({ topic: { scope: "session", id: "s1", resource: "tasks" }, kind: "board" }); + expect(shown().map((task) => task.id)).toEqual(["t1", "t2"]); }); }); }); diff --git a/packages/shift-manager/test/task-card-in-feed.test.tsx b/packages/shift-manager/test/task-card-in-feed.test.tsx index 2c9004e305..55e19f57d7 100644 --- a/packages/shift-manager/test/task-card-in-feed.test.tsx +++ b/packages/shift-manager/test/task-card-in-feed.test.tsx @@ -7,6 +7,7 @@ import { act, cleanup, fireEvent, render, screen } from "@testing-library/react" import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { OutputItem } from "@flow-state-dev/core/items"; import { SessionScope, TaskBoardMeta } from "../src/components/TaskBoardMeta"; +import type { SubscribeOptions, WireNotice, WireTopic } from "@flow-state-dev/client"; import { TASKS_POLL_MS } from "../src/components/TasksPanel"; type Row = { id: string; goal: string; title?: string; status: string; assignee?: string; attempts: number }; @@ -14,8 +15,15 @@ let rows: Row[] = []; let failing = false; const calls: string[] = []; let refreshes = 0; -const lab: { client: { userId: string }; snapshot: Record; refresh: () => Promise } = { - client: { userId: "alice" }, +const subscriptions: Array<{ topics: readonly WireTopic[]; options: SubscribeOptions; closed: boolean }> = []; +/** The Lab's one client, its `subscribe` faked so a case delivers the notices. */ +const subscribe = (topics: readonly WireTopic[], options: SubscribeOptions) => { + const entry = { topics, options, closed: false }; + subscriptions.push(entry); + return { close: () => void (entry.closed = true) }; +}; +const lab: { client: { userId: string; subscribe: typeof subscribe }; snapshot: Record; refresh: () => Promise } = { + client: { userId: "alice", subscribe }, snapshot: { readAt: 1 }, refresh: async () => void refreshes++, }; @@ -34,7 +42,8 @@ vi.mock("../src/lib/routes", async (importOriginal) => ({ ...(await importOriginal()), navigate: (route: unknown) => void navigated.push(route), })); -vi.mock("../src/lib/conversation-tasks", () => ({ +vi.mock("../src/lib/conversation-tasks", async (importOriginal) => ({ + conversationBoardTopics: (await importOriginal()).conversationBoardTopics, readConversationTasks: async (_c: unknown, flow: string, sessionId: string) => { calls.push(`list ${flow} ${sessionId}`); if (failing) throw new Error("network"); @@ -51,6 +60,7 @@ beforeEach(() => { reporterConversation = null; conversationsAskedFor.length = 0; navigated.length = 0; + subscriptions.length = 0; vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); }); afterEach(() => { @@ -59,6 +69,21 @@ afterEach(() => { }); const tick = (ms: number) => act(async () => void (await vi.advanceTimersByTimeAsync(ms))); +/** The board's open subscription. */ +function open() { + const live = subscriptions.filter((s) => !s.closed); + if (live.length === 0) throw new Error("no open subscription"); + return live[live.length - 1]!; +} + +/** Hand the open subscription a notice, or `null` for a connect, reconnect or tick. */ +async function hear(notice: WireNotice | null) { + act(() => open().options.onChange(notice)); + await tick(0); +} + +const boardNotice: WireNotice = { topic: { scope: "session", id: "s1", resource: "tasks" }, kind: "board" }; + const meta = (requestId: string) => ({ id: `m-${requestId}`, type: "component", component: "task-board-meta", requestId, status: "completed", data: { collectionId: "tasks", status: "active" } }) as never; @@ -111,16 +136,29 @@ describe("a delegated post's task in the feed", () => { expect(document.querySelector(".animate-spin")).toBeNull(); }); - it("follows the task as it moves, with no reload, and reads nothing more once it has ended", async () => { + it("subscribes the conversation's board and plan ledgers, narrowed, through the Lab's client", async () => { + rows = [{ id: "t1", goal: "g", title: "Post for eng.pm", status: "in_progress", assignee: "eng.pm", attempts: 1 }]; + render(scope([filed("r1", "t1", "Post for eng.pm", "eng.pm")], ["r1"])); + await tick(0); + expect(open().topics).toEqual([ + { scope: "session", id: "s1", resource: "tasks" }, + { scope: "session", id: "s1", resource: "plan" }, + ]); + }); + + it("follows the task as it moves on its board's notices, with no reload, and keeps no timer once it has ended", async () => { rows = [{ id: "t1", goal: "g", title: "Post for eng.pm", status: "in_progress", assignee: "eng.pm", attempts: 1 }]; render(scope([filed("r1", "t1", "Post for eng.pm", "eng.pm")], ["r1"])); await tick(0); expect(cards()[0]!.status).toBe("in_progress"); + // Where push can miss a change, a timer while the task can still move. + expect(open().options.pollIntervalMs).toBe(TASKS_POLL_MS); rows = [{ ...rows[0]!, status: "completed" }]; - await tick(TASKS_POLL_MS); + await hear(boardNotice); expect(cards()[0]).toMatchObject({ status: "completed", text: expect.stringContaining("completed") }); // The task moved: the Lab is read again, so what it counts agrees with the card. expect(refreshes).toBe(1); + expect(open().options.pollIntervalMs).toBeUndefined(); const read = calls.length; await tick(TASKS_POLL_MS * 20); expect(calls).toHaveLength(read); @@ -139,16 +177,17 @@ describe("a delegated post's task in the feed", () => { expect(cards()[0]!.status).toBe("in_progress"); }); - it("keeps reading through a failed read, so a task that ended while the read failed still shows ended", async () => { + it("keeps its timer through a failed read, so a task that ended while the read failed still shows ended", async () => { rows = [{ id: "t1", goal: "g", title: "Post for eng.pm", status: "in_progress", assignee: "eng.pm", attempts: 1 }]; render(scope([filed("r1", "t1", "Post for eng.pm", "eng.pm")], ["r1"])); await tick(0); failing = true; - await tick(TASKS_POLL_MS); + await hear(null); expect(cards()[0]!.status).toBe("in_progress"); + expect(open().options.pollIntervalMs).toBe(TASKS_POLL_MS); failing = false; rows = [{ ...rows[0]!, status: "errored" }]; - await tick(TASKS_POLL_MS); + await hear(null); expect(cards()[0]!.status).toBe("errored"); }); From 96d51ebf7bef4a433896e0b255c5181576202765 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 19:27:35 +0000 Subject: [PATCH 02/13] FIX-2429: start the goal's idle windows once the views go quiet Leg b's window could open on the last read of a view's opening burst (the filing's notice and the Postgres bus's resync landing after the sockets crossed). Both legs now wait until no view has sent a board read for 1 s. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn --- .../a-settled-task-reaches-the-board/goal.md | 7 ++++-- .../a-settled-task-reaches-the-board/run.mts | 22 +++++++++++++++++-- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/goals/task-board/a-settled-task-reaches-the-board/goal.md b/goals/task-board/a-settled-task-reaches-the-board/goal.md index 9ef957d781..015bd052c2 100644 --- a/goals/task-board/a-settled-task-reaches-the-board/goal.md +++ b/goals/task-board/a-settled-task-reaches-the-board/goal.md @@ -9,9 +9,9 @@ **Signal:** - `a:within-1s` — each view shows the delegate's task `completed`, and the Teammates view its run's link, less than 1000 ms after the change can be read from the store (polled every 5 ms). The task settles in its own task session. - `a:plan-step` — the claude-code-style view (the merged read) shows the conversation's plan step `completed` less than 1000 ms after the store. -- `a:0-reads` — over a 10 s window, starting after every view's socket said `crosses: true` and with a task held open, each view makes 0 board reads (`/reads/listTasks_tasks`, `/resources/tasks`), while a reply streams in the conversation and the second conversation files and settles a task. +- `a:0-reads` — over a 10 s window, starting once every view's socket said `crosses: true` and the views have sent no board read for 1 s (the reads their opening owed are done), with a task held open, each view makes 0 board reads (`/reads/listTasks_tasks`, `/resources/tasks`), while a reply streams in the conversation and the second conversation files and settles a task. - `b:within-1s` — as `a:within-1s`, the task released and settled on process 2 (graded: the delegate ran there and nowhere else); the views are on process 1. -- `b:0-reads` — as `a:0-reads`, over 10 s from each view's first `crosses: true` frame, which on the Postgres bus waits for its first ping. +- `b:0-reads` — as `a:0-reads`, over 10 s from each view's first `crosses: true` frame (which on the Postgres bus waits for its first ping) and the views going quiet. - `c:within-a-poll` — on a host with `push: false`, each view shows the task `completed` within its own poll interval plus 1 s (Teammates 1.5 s, claude-code-style 2 s, `BoardList` 3 s). **Anti-game:** Not `publish` calls and not frames sent: every grade is what a view's own callback or read returned, timed against the store, or how many board reads its client's fetcher sent. The socket taps only time the start of the idle windows. Real sockets against bound ports, not an in-process fetch; two registries for leg b, not two clients of one. Each graded list is floored with `tell.over`. The `BoardList` view drives the call shape `BoardList` makes rather than rendering React in Node; that the component makes exactly that call (the narrowed topic, its pace, a read on mount and on each wake, coalesced) is proven by `packages/react/test/board-list.test.ts`. The plan step is graded on the claude-code-style view because the Teammates view also draws each `task-change` its conversation's own stream carries, which a step worked in the conversation's request would reach without any board notice. @@ -34,3 +34,6 @@ | 2026-11-03 | fix/FIX-2429-board-notices (pre-commit) | n/a | FAIL (expected) | `running-session`: `a:within-1s` only (Teammates showed the run's link 1661 ms after the store: the link is written in the run's session, so its notice went there; the ending still reached the conversation through the filer's own notice write) | | 2026-11-03 | fix/FIX-2429-board-notices (pre-commit) | n/a | FAIL (expected) | `whole-topic`: `a:0-reads` only (Teammates 18 reads, claude-code-style 18 in 10 s) | | 2026-11-03 | fix/FIX-2429-board-notices (pre-commit) | n/a | FAIL (expected) | `tasks-only`: `a:plan-step` only (the step never showed completed within 4 s) | +| 2026-11-03 | 531bf320d | n/a | FAIL | `b:0-reads`: claude-code-style made 1 read in the window. The read was its opening burst's last (the filing's notice and the Postgres bus's resync arrived after the sockets crossed), started the same millisecond the window did. The window now starts once the views have sent no read for 1 s, in both legs; 3 runs of leg b after that, all PASS | +| 2026-11-03 | 531bf320d + the quiet window (uncommitted) | n/a | PASS | a: 0 reads in 10 s on 3 views; completed shown 98 / 45 / 17 ms, link 25 ms; plan step 53 ms · b (initdb): settled on p2, 0 reads in 10 s; shown 142 / 52 / 15 ms, link 32 ms · c: no push, shown 416 ms (bound 2500), 1932 ms (3000), 930 ms (4000) | +| 2026-11-03 | 531bf320d + the quiet window (uncommitted) | n/a | FAIL (expected) | `running-session`: `a:within-1s` only (link 1527 ms) · `whole-topic`: `a:0-reads` only (18 and 18 reads) · `tasks-only`: `a:plan-step` only (never within 4 s) | diff --git a/goals/task-board/a-settled-task-reaches-the-board/run.mts b/goals/task-board/a-settled-task-reaches-the-board/run.mts index 1e7c0ae29b..b87d1e65c8 100644 --- a/goals/task-board/a-settled-task-reaches-the-board/run.mts +++ b/goals/task-board/a-settled-task-reaches-the-board/run.mts @@ -402,6 +402,21 @@ async function until(check: () => boolean | Promise, withinMs: number): return true; } +/** Wait until no view has sent a board read for 1 s (at most 10 s): the reads its opening owed are done. */ +async function quiet(views: View[]): Promise { + const total = () => views.reduce((sum, v) => sum + v.reads(), 0); + const deadline = Date.now() + 10_000; + let last = total(); + let since = Date.now(); + while (Date.now() - since < 1_000 && Date.now() < deadline) { + await sleep(50); + if (total() !== last) { + last = total(); + since = Date.now(); + } + } +} + const script = (fsd: Client, session: string, s: Script) => fsd.flow("desk").send("respond", { message: JSON.stringify(s) }, { sessionId: session }); // --------------------------------------------------------------------------- @@ -433,7 +448,7 @@ await runGoal(async (failures, tell) => { for (const view of views) { if ((await shownAt(view, held, () => true, 5_000)) === undefined) failures.push(`a:setup: ${view.name} never showed the held task`); } - await sleep(1_500); + await quiet(views); // The window: a reply streams in the conversation, and the user's other // conversation files a task its delegate settles. @@ -512,12 +527,15 @@ await runGoal(async (failures, tell) => { const crossed = await until(() => taps.slice(before).length >= 3 && taps.slice(before).every((t) => t.crossedAt !== undefined), 15_000); if (!crossed) failures.push("b:crossing: the views' sockets never all said crosses: true within 15 s"); for (const view of views) await shownAt(view, task, () => true, 5_000); + // The window starts once the views have gone quiet: the opening burst (each connect's read, the + // filing's notice and the bus's resync) can still be finishing a read when the last socket crosses. + await quiet(views); const readsBefore = views.map((v) => v.reads()); await sleep(IDLE_WINDOW_MS); const busy = views.map((v, i) => ({ name: v.name, reads: v.reads() - readsBefore[i]! })).filter((v) => v.reads !== 0); tell.over("b:0-reads · the views' reads before the window", readsBefore.filter((n) => n > 0)); if (busy.length > 0) failures.push(`b:0-reads: ${busy.map((v) => `${v.name} made ${v.reads} board reads`).join(", ")} in ${IDLE_WINDOW_MS / 1000} s idle`); - else evidence.push(`b: 0 board reads in ${IDLE_WINDOW_MS / 1000} s from each view's first crosses: true`); + else evidence.push(`b: 0 board reads in ${IDLE_WINDOW_MS / 1000} s once quiet after each view's first crosses: true`); // Released on process 2: its pass hands the row out, its doer runs it. store.watch("b:linked", task, (row) => row.run?.sessionId !== undefined); From 6b0f245d424c796df614a42b69ca7fdcc5217595 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 19:36:49 +0000 Subject: [PATCH 03/13] FIX-2429: drop a board read that lands after watchTasks stops; review fixes - Teammates watchTasks: a read or lookup landing after the watch stopped shows nothing and follows no run (Codex r4459527555). - Keep LIVE_BOARD_POLL_MS and AFTER_A_MOVE_MS internal (Fallow). - Docs: listTasks_tasks screens subscribe both tasks and plan; editor wording. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn --- apps/docs/docs/client/react.md | 8 +++-- .../docs/docs/orchestration/task-substrate.md | 4 +-- apps/docs/docs/workforce/coordinators.md | 2 +- apps/docs/docs/workforce/ui.md | 2 +- apps/docs/guides/realtime.md | 8 +++-- labs/teammates/src/adapter.ts | 5 +++ labs/teammates/test/run-link.test.ts | 35 +++++++++++++++++++ packages/orchestration/README.md | 6 ++-- packages/react/src/components/panels/reads.ts | 2 +- .../src/components/TasksPanel.tsx | 2 +- 10 files changed, 61 insertions(+), 13 deletions(-) diff --git a/apps/docs/docs/client/react.md b/apps/docs/docs/client/react.md index 23010b739a..9fadaa0dba 100644 --- a/apps/docs/docs/client/react.md +++ b/apps/docs/docs/client/react.md @@ -160,10 +160,14 @@ const refresh = useCallback( [sessionId], ); -useSubscription([topic.session(sessionId, { resource: "tasks" })], refresh, { pollIntervalMs: 3000 }); +useSubscription( + [topic.session(sessionId, { resource: "tasks" }), topic.session(sessionId, { resource: "plan" })], + refresh, + { pollIntervalMs: 3000 }, +); ``` -The topic is narrowed to the `tasks` board, so a reply streaming in the session doesn't wake the read; a task that settles in another session still does (see [Task boards](/guides/realtime#task-boards)). +The topics are narrowed to the two boards `listTasks_tasks` returns (the conversation's tasks and its planning worker's steps), so a reply streaming in the session doesn't wake the read; a task that settles in another session still does (see [Task boards](/guides/realtime#task-boards)). On the Node host the read runs as soon as the change is saved, over a WebSocket; on a host with no push it runs every `pollIntervalMs`. A burst of changes runs it once more after the read in flight finishes, not once per change. The read gets the notice that woke it (`{ topic, kind, origin? }`), or `null` when the screen should read everything again: after a connect or a reconnect, on a timer tick, and when push starts or stops reaching every server process. Act on `kind` when the screen only cares about some changes, and read everything on `null`. Leave `pollIntervalMs` out for no timer. `enabled: false` subscribes nothing. diff --git a/apps/docs/docs/orchestration/task-substrate.md b/apps/docs/docs/orchestration/task-substrate.md index adf1a2e7fc..b9c41e3b8d 100644 --- a/apps/docs/docs/orchestration/task-substrate.md +++ b/apps/docs/docs/orchestration/task-substrate.md @@ -547,7 +547,7 @@ UIs stay in sync off that stream rather than by polling. The `` comp ### Board notices -The item lands on the stream of the session that made the change. A task often settles somewhere else: in its own task session, or on another process. So every change also publishes a board notice. It goes on the topic of the session that filed the row (the row's filer, or the running session for a board that hands nothing out), narrowed to the board's `collectionId`, with kind `board`. It carries no rows. A screen subscribes `topic.session(conversationId, { resource: "tasks" })` with `client.subscribe` or `useSubscription`, and reads the board again when one arrives: +The item lands on the stream of the session that made the change. A task often settles somewhere else: in its own task session, or on another process. So every change also publishes a board notice. It goes on the topic of the session that filed the row (the session that filed the row, or the running session when the row names no filer), narrowed to the board's `collectionId`, with kind `board`. It carries no rows. A screen subscribes `topic.session(conversationId, { resource: "tasks" })` with `client.subscribe` or `useSubscription`, and reads the board again when one arrives: ```ts useSubscription( @@ -557,7 +557,7 @@ useSubscription( ); ``` -Subscribe each ledger your read returns. Workforce's `listTasks_tasks` read merges the conversation board with its planning worker's steps, so its screens subscribe `tasks` and `plan`. Because the topic is narrowed, a reply streaming in the conversation never wakes the screen. The session stream hears board notices on its topic and ignores them. As with any notice, `pollIntervalMs` is the fallback wherever push can't reach (see [Keeping a screen current](/guides/realtime#task-boards)). +Subscribe each board your read returns. Workforce's `listTasks_tasks` read merges the conversation board with its planning worker's steps, so its screens subscribe `tasks` and `plan`. Because the topic is narrowed, a reply streaming in the conversation never wakes the screen. `useSession`'s live stream doesn't react to board notices. As with any notice, `pollIntervalMs` is the fallback wherever push can't reach (see [Keeping a screen current](/guides/realtime#task-boards)). ## Related pages diff --git a/apps/docs/docs/workforce/coordinators.md b/apps/docs/docs/workforce/coordinators.md index 8dceeefb39..49d356f0ce 100644 --- a/apps/docs/docs/workforce/coordinators.md +++ b/apps/docs/docs/workforce/coordinators.md @@ -475,7 +475,7 @@ It hears when a task completes, with what came back; when it fails for good, wit | Action | What it does | | --- | --- | -| `listTasks_tasks` | This conversation's tasks only, even when another conversation has the same coordinator and the same delegates | +| `listTasks_tasks` | This conversation's tasks, and the steps its coordinator filed for itself, only: never another conversation's, even with the same coordinator and the same delegates | | `getTask_tasks` | One task whole: its brief, its fields, how it stands, its delegate's status note, and its output | | `createTask_tasks` | Files a task: it starts at once, after its `deps`, or, with `held: true`, when you release it | | `updateTask_tasks` | Before the task starts: changes any of its fields, its delegate included, holds it (`status: "held"`) or releases it (`status: "pending"`). Until it finishes: sends it a `message`, or cancels it (`status: "cancelled"`), with nothing said in the conversation | diff --git a/apps/docs/docs/workforce/ui.md b/apps/docs/docs/workforce/ui.md index 2b1a7746a8..1422174a02 100644 --- a/apps/docs/docs/workforce/ui.md +++ b/apps/docs/docs/workforce/ui.md @@ -120,7 +120,7 @@ The reads and the live subscription both go through `client`, so the subscriptio Rows already on screen stay there while the list reads again. -A live list shares its client's one connection with every other subscription on that client (see [Keeping a screen current](/guides/realtime)). On a host that can't push, or while the connection is down, it reads every few seconds instead, so it never goes stale for long. +A live list shares its client's one connection with every other subscription on that client (see [Keeping a screen current](/guides/realtime)). On a host that can't push, or while the connection is down, it reads every 3 seconds instead. Each row shows the task's `title` (its `goal` if there is no title, its `id` if there is neither), its status word, and the assignee when there is one. The words are the ones the columns are headed with (`pending`, `in_progress`, and so on). A task in a status the list doesn't recognise shows with its own word. No row is hidden. A row without a `createdAt` follows the dated ones. diff --git a/apps/docs/guides/realtime.md b/apps/docs/guides/realtime.md index 7ff16b4b6b..11cb24d8f9 100644 --- a/apps/docs/guides/realtime.md +++ b/apps/docs/guides/realtime.md @@ -29,7 +29,11 @@ function TaskList({ sessionId }: { sessionId: string }) { ); useEffect(() => void refresh(), [refresh]); // the first read - useSubscription([topic.session(sessionId, { resource: "tasks" })], refresh, { pollIntervalMs: 3000 }); + useSubscription( + [topic.session(sessionId, { resource: "tasks" }), topic.session(sessionId, { resource: "plan" })], + refresh, + { pollIntervalMs: 3000 }, + ); return
      {tasks.map((task) =>
    • {task.title}
    • )}
    ; } @@ -72,7 +76,7 @@ useSubscription( ); ``` -Workforce's `listTasks_tasks` read returns the conversation's board and its planning worker's own steps, which sit on the `plan` board, so a screen of that read subscribes both. A flow with no planning worker never announces anything on `plan`, so the extra topic costs nothing. +Workforce's `listTasks_tasks` read returns the conversation's board and its planning worker's own steps, which sit on the `plan` board, so a screen of that read subscribes both. Subscribing `plan` is harmless when the flow has no planning worker. `BoardList` with `live` does this for you, for the one board it draws. Its `client` needs `subscribe` (see [A board as a list](/docs/workforce/ui#a-board-as-a-list)). diff --git a/labs/teammates/src/adapter.ts b/labs/teammates/src/adapter.ts index a2fd099900..55ba201351 100644 --- a/labs/teammates/src/adapter.ts +++ b/labs/teammates/src/adapter.ts @@ -884,7 +884,10 @@ export function createLabAdapter(client: Client = connect()): LabAdapter { for (const [id, row] of listed) all.set(id, { ...all.get(id), ...row }); return [...all.values()]; }; + // Set once the watch stops: a read or a flow lookup that lands after it shows nothing and follows no run. + let stopped = false; const publish = () => { + if (stopped) return; const current = merged().map(newer); const flowOf = (id: string) => (id === sessionId ? flowOfSession.get(sessionId) : runFlows.get(id)); const holds = holdsOfRows(sessionId, current, flowOf); @@ -914,6 +917,7 @@ export function createLabAdapter(client: Client = connect()): LabAdapter { const flow = flowOfSession.get(sessionId) ?? (await client.sessions.get(sessionId)).flowKind; const read = await client.flow(flow).read<{ ok: boolean; error?: string; tasks: Array> }>(LIST_TASKS, {}, { sessionId }); if (!read.ok) throw new Error(read.error); + if (stopped) return; listed = new Map(read.tasks.map((task) => [task.id as string, task])); publish(); }); @@ -922,6 +926,7 @@ export function createLabAdapter(client: Client = connect()): LabAdapter { publish(); }); return () => { + stopped = true; stopFeed(); stopBoard(); for (const stop of runFeeds.values()) stop(); diff --git a/labs/teammates/test/run-link.test.ts b/labs/teammates/test/run-link.test.ts index cce0433813..6f32f83971 100644 --- a/labs/teammates/test/run-link.test.ts +++ b/labs/teammates/test/run-link.test.ts @@ -153,6 +153,41 @@ describe("a coding task's run, while it runs", () => { }); }); +describe("a board read still in flight when the watch stops", () => { + it("shows nothing and follows no run once it lands", async () => { + const item = filed("in_progress"); + const push = fakeSubscribe(); + const opened: string[] = []; + let land!: () => void; + const client = { + subscribe: push.subscribe, + sessions: { + state: async () => ({ at: 1, sessionCreatedAt: 1, items: [item], pagination: { hasMore: false, nextOffset: 1 } }), + stream: (id: string) => { + opened.push(id); + return { close() {} }; + }, + get: async () => ({ id: "wks_1", flowKind: "agent" }), + }, + flow: () => ({ + read: () => + new Promise((resolve) => { + land = () => resolve({ ok: true, tasks: [{ ...item.data.task, run: { sessionId: "dsx_run", requestId: "req_run", attempt: 1 } }] }); + }), + }), + } as unknown as Client; + const calls: BoardTask[][] = []; + const stop = createLabAdapter(client).watchTasks("wks_1", (next) => calls.push(next)); + await until(() => land !== undefined && calls.length > 0); + const before = calls.length; + stop(); + land(); + await new Promise((r) => setTimeout(r, 50)); + expect(calls).toHaveLength(before); + expect(opened).not.toContain("dsx_run"); + }); +}); + describe("a coding task's hold, while it runs", () => { /** * The run writes its row on its own session: its link, and the review it stops for. The diff --git a/packages/orchestration/README.md b/packages/orchestration/README.md index cad16cf961..555cef8739 100644 --- a/packages/orchestration/README.md +++ b/packages/orchestration/README.md @@ -93,10 +93,10 @@ pass, such as `ctx.sequencer` for one board invocation. `backing: "resource"` ou request: a user's queue, an org work pool, declared with `defineTaskCollection`. Every mutation that changes a field emits a `task-change` component item on the writing session's stream, and publishes a `board` change notice on the topic of the session that filed the row -(its `filer`, else the ledger's legacy filer, else the running session), narrowed to the +(the row's `filer`, or the running session when the row has none), narrowed to the `collectionId`. A screen of the board subscribes that topic (`topic.session(id, { resource })`) -and reads again, whichever session or process settled the task. A context with no engine seam -(a hand-built test context) publishes nothing. +and reads again, whichever session or process settled the task. A test context you build by hand, +without the engine, publishes no notices. **A ledger per partition.** A `user`-scoped collection can take a `partitionBy` function, keeping one set of rows per partition at the user's scope: diff --git a/packages/react/src/components/panels/reads.ts b/packages/react/src/components/panels/reads.ts index b29659ba2a..5eb94bcd43 100644 --- a/packages/react/src/components/panels/reads.ts +++ b/packages/react/src/components/panels/reads.ts @@ -57,7 +57,7 @@ const EMPTY: PanelRow[] = []; * Where push covers the list it reads on a board notice, a connect and a * reconnect only. */ -export const LIVE_BOARD_POLL_MS = 3_000; +const LIVE_BOARD_POLL_MS = 3_000; /** * Read a board, and read it again whenever it changes (FIX-2429). diff --git a/packages/shift-manager/src/components/TasksPanel.tsx b/packages/shift-manager/src/components/TasksPanel.tsx index 508d1b2ea6..794dafa09d 100644 --- a/packages/shift-manager/src/components/TasksPanel.tsx +++ b/packages/shift-manager/src/components/TasksPanel.tsx @@ -32,7 +32,7 @@ type Read = { tasks: ConversationTask[] } | { failure: string } | undefined; /** How often the panel reads on a timer, where push can miss a change, while a task is open or just moved. */ export const TASKS_POLL_MS = 3_000; /** How long the panel keeps its timer after a task moved: the turn its ending woke runs in that time. */ -export const AFTER_A_MOVE_MS = 30_000; +const AFTER_A_MOVE_MS = 30_000; /** Whether a task can still move by itself. */ export const isOpen = (task: ConversationTask) => task.status === "pending" || task.status === "in_progress"; From edf30c596551a1fe0ce5396dec7c3ca96194817f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 19:44:44 +0000 Subject: [PATCH 04/13] FIX-2429: drop the goal check's unused say helper Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn --- goals/task-board/a-settled-task-reaches-the-board/run.mts | 1 - 1 file changed, 1 deletion(-) diff --git a/goals/task-board/a-settled-task-reaches-the-board/run.mts b/goals/task-board/a-settled-task-reaches-the-board/run.mts index b87d1e65c8..bd98d3cf1f 100644 --- a/goals/task-board/a-settled-task-reaches-the-board/run.mts +++ b/goals/task-board/a-settled-task-reaches-the-board/run.mts @@ -120,7 +120,6 @@ if (PATCHES[CONTROL] !== undefined && process.env.GOAL_MODULE_PATCH === undefine const legs = new Set((process.env.GOAL_LEGS ?? "a,b,c").split(",").map((s) => s.trim()).filter(Boolean)); const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); -const say = (s: string) => console.error(`[board-notices ${new Date().toISOString().slice(11, 19)}] ${s}`); // --------------------------------------------------------------------------- // Observing the sockets (taps only: nothing here changes what a client does) From 56a2872b58ac4897d93ed0ce94938bb9f970baa6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 19:52:41 +0000 Subject: [PATCH 05/13] chore(labs): mark the two lab adapters' shared LabAdapter shape as intended (FIX-2429) fallow audit counts LabAdapter, Unsubscribe and createLabAdapter as duplicate exports once a PR touches both adapters. Each lab is its own app with the same adapter shape on purpose, so suppress only that rule, per file. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn --- labs/claude-code-style/src/adapter.ts | 1 + labs/teammates/src/adapter.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/labs/claude-code-style/src/adapter.ts b/labs/claude-code-style/src/adapter.ts index 235ff13de5..2f1410e9c4 100644 --- a/labs/claude-code-style/src/adapter.ts +++ b/labs/claude-code-style/src/adapter.ts @@ -1,3 +1,4 @@ +// fallow-ignore-file duplicate-export -- each lab is its own app, and both expose the same LabAdapter shape on purpose. /** * The lab's one way in and out. Every read and write the screen makes goes * through `LabAdapter`, and nothing else in `src/` touches a package. diff --git a/labs/teammates/src/adapter.ts b/labs/teammates/src/adapter.ts index 55ba201351..d87ede30e1 100644 --- a/labs/teammates/src/adapter.ts +++ b/labs/teammates/src/adapter.ts @@ -1,3 +1,4 @@ +// fallow-ignore-file duplicate-export -- each lab is its own app, and both expose the same LabAdapter shape on purpose. /** * The lab's one way in and out. Every read and write the screen makes goes * through `LabAdapter`, and nothing else in `src/` touches a package. Each From 547ff60785671b2996fa014a2e0d0de2735d4a2f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 20:24:35 +0000 Subject: [PATCH 06/13] FIX-2429: useSubscription hands read an AbortSignal; Shift Manager drops reads that land after unmount A read already running when the subscription ends still finished and could set state or start a Lab refresh (Codex r4459947789). The hook now aborts a signal on cleanup; TasksPanel and LiveBoard check it after their await, and their own readAt effects pass one too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn --- .changeset/board-notices.md | 2 +- apps/docs/docs/api/react.md | 3 +- packages/react/README.md | 5 ++- packages/react/src/hooks/useSubscription.ts | 14 +++++++-- packages/react/test/useSubscription.test.ts | 31 ++++++++++++++++++- .../src/components/TaskBoardMeta.tsx | 10 ++++-- .../src/components/TasksPanel.tsx | 12 ++++--- .../test/conversation-tasks-panel.test.tsx | 27 +++++++++++++++- .../test/task-card-in-feed.test.tsx | 24 +++++++++++++- 9 files changed, 112 insertions(+), 16 deletions(-) diff --git a/.changeset/board-notices.md b/.changeset/board-notices.md index 4941a33609..25625e0f8f 100644 --- a/.changeset/board-notices.md +++ b/.changeset/board-notices.md @@ -11,6 +11,6 @@ A task board's change reaches every open view of the board, from whichever sessi - **orchestration:** every change to a board built by `getOrCreateTaskCollection` also publishes a `board` change notice on the topic of the session that filed the row (`Task.filer`, else the ledger's legacy filer, else the running session), narrowed to the board's `collectionId`. A screen subscribes `topic.session(conversationId, { resource: "tasks" })` and reads again. Nothing to wire: the `task-change` item is unchanged. - **engine:** the block context carries the seam that publishes a board notice on the running request's bus, under its tenant, with the request as `origin`. -- **react:** **Breaking for a hand-built client slice:** a live `BoardList`'s `client` takes `subscribe` in place of `sessions.stream`. A client from `createClient` works as before. The list now hears a task that settles in another session or process, never wakes on a reply streaming in the session, and reads every 3 s where push can miss a change. `useSubscription` takes `client`, for an app that builds its own client. +- **react:** **Breaking for a hand-built client slice:** a live `BoardList`'s `client` takes `subscribe` in place of `sessions.stream`. A client from `createClient` works as before. The list now hears a task that settles in another session or process, never wakes on a reply streaming in the session, and reads every 3 s where push can miss a change. `useSubscription` takes `client`, for an app that builds its own client, and hands `read` an `AbortSignal` that aborts when the subscription ends. - **core / contracts:** `ChangeKind` gains `"board"`; `publishBoardChange` and `BOARD_NOTICE_SEAM` (framework-facing) in `@flow-state-dev/core/types`. - **shift-manager:** the conversation's task panel and task cards read on board notices; they keep their 3 s timer only while a task is open, and only where push can miss a change. diff --git a/apps/docs/docs/api/react.md b/apps/docs/docs/api/react.md index 0fa452e774..0f66ecd7a7 100644 --- a/apps/docs/docs/api/react.md +++ b/apps/docs/docs/api/react.md @@ -187,7 +187,8 @@ useSubscription([topic.session(sessionId, { resource: "tasks" })], refresh, { po | Argument | Type | Notes | |----------|------|-------| | `topics` | `WireTopic[]` | From `topic.session(id)`, `topic.user()`, `topic.org()`. A new array with the same topics keeps the subscription. | -| `read` | `(notice: WireNotice \| null) => unknown` | The screen's read. One runs at a time, and at most one more waits. Gets the notice that woke it, or `null` when the screen should read everything again: after a connect or a reconnect, on a timer tick, and when push starts or stops reaching every server process. It also gets `null` when several changes arrived during one read (one follow-up read covers them all). | +| `read` | `(notice: WireNotice \| null, signal: AbortSignal) => unknown` | The screen's read. One runs at a time, and at most one more waits. Gets the notice that woke it, or `null` when the screen should read everything again: after a connect or a reconnect, on a timer tick, and when push starts or stops reaching every server process. It also gets `null` when several changes arrived during one read (one follow-up read covers them all). | +| `read`'s `signal` | `AbortSignal` | Aborted when the subscription ends: the screen unmounts, or its topics or options change. A read that awaits checks `signal.aborted` before it sets state or starts more work, since a read already running when the screen goes away still finishes. | | `options.pollIntervalMs` | `number` | Read at this pace wherever push can miss a change. Omitted, no timer. | | `options.enabled` | `boolean` | `false` subscribes nothing. Default `true`. | | `options.client` | `Pick` | Your own client, when you build one with its own `fetcher`, so the socket signs in the same way. Pass a stable reference. Default: the provider's client. | diff --git a/packages/react/README.md b/packages/react/README.md index 2dbb7a1955..60e2c2392a 100644 --- a/packages/react/README.md +++ b/packages/react/README.md @@ -257,7 +257,10 @@ so a burst of changes is one more read. `read` gets the notice that woke it, or `null` when the screen should read everything again: after a connect or a reconnect, on a timer tick, and when push starts or stops reaching every server process. It also gets `null` when several changes arrived during one read (one -follow-up read covers them all). It doesn't read on mount. +follow-up read covers them all). It doesn't read on mount. Its second argument is an +`AbortSignal`, aborted when the subscription ends (the screen unmounts, or its topics +or options change): a read that awaits checks `signal.aborted` before it sets state or +starts more work, since a read already running when the screen goes away still finishes. ```tsx import { topic } from "@flow-state-dev/client"; diff --git a/packages/react/src/hooks/useSubscription.ts b/packages/react/src/hooks/useSubscription.ts index 4f3ea7b906..681819ed40 100644 --- a/packages/react/src/hooks/useSubscription.ts +++ b/packages/react/src/hooks/useSubscription.ts @@ -13,6 +13,11 @@ * or a timer tick. A waiting read that stands for several different notices * gets `null` too, so a read that acts on a notice's kind reads everything * then. + * + * `read` also gets an `AbortSignal`, aborted when the subscription ends (the + * screen unmounts, or its topics or options change). A read that awaits + * checks it before it sets state or starts more work: a read already running + * when the screen goes away still finishes, and its result is for nobody. */ import { useEffect, useMemo, useRef } from "react"; import type { Client, WireNotice, WireTopic } from "@flow-state-dev/client"; @@ -54,11 +59,12 @@ function sameNotice(a: WireNotice | null, b: WireNotice | null): boolean { /** * Run `read` when something under `topics` changes. `read` may return a - * promise; the next read waits for it. + * promise; the next read waits for it. Its `signal` aborts when this + * subscription ends. */ export function useSubscription( topics: readonly WireTopic[], - read: (notice: WireNotice | null) => unknown, + read: (notice: WireNotice | null, signal: AbortSignal) => unknown, options: UseSubscriptionOptions = {} ): void { const built = useClient(); @@ -74,10 +80,11 @@ export function useSubscription( useEffect(() => { if (!enabled || stable.length === 0) return; let next: { notice: WireNotice | null } | undefined; + const ended = new AbortController(); const reads = coalescedReads(async () => { const notice = next?.notice ?? null; next = undefined; - await readRef.current(notice); + await readRef.current(notice, ended.signal); }); const subscription = client.subscribe(stable, { onChange: (notice) => { @@ -87,6 +94,7 @@ export function useSubscription( ...(pollIntervalMs !== undefined ? { pollIntervalMs } : {}) }); return () => { + ended.abort(); subscription.close(); reads.close(); }; diff --git a/packages/react/test/useSubscription.test.ts b/packages/react/test/useSubscription.test.ts index b35f5fb2f1..78bb413b10 100644 --- a/packages/react/test/useSubscription.test.ts +++ b/packages/react/test/useSubscription.test.ts @@ -182,7 +182,7 @@ describe("useSubscription", () => { await Promise.resolve(); }); expect(first).not.toHaveBeenCalled(); - expect(second).toHaveBeenCalledWith(null); + expect(second).toHaveBeenCalledWith(null, expect.any(AbortSignal)); }); it("subscribes again when the topics change, and closes the old one", () => { @@ -215,6 +215,35 @@ describe("useSubscription", () => { expect(subscriptions).toEqual([]); }); + it("aborts the signal a running read holds when the hook unmounts, so it can drop what it read", async () => { + const signals: AbortSignal[] = []; + let release: (() => void) | undefined; + const read = (_n: WireNotice | null, signal: AbortSignal) => { + signals.push(signal); + return new Promise((resolve) => (release = resolve)); + }; + const { unmount } = renderHook(() => useSubscription([S1], read)); + act(() => subscriptions[0]!.options.onChange(notice("items"))); + expect(signals).toHaveLength(1); + expect(signals[0]!.aborted).toBe(false); + unmount(); + // The read resumes after the hook is gone: its signal says so. + release?.(); + expect(signals[0]!.aborted).toBe(true); + }); + + it("aborts a running read's signal when the topics change", () => { + const signals: AbortSignal[] = []; + const read = (_n: WireNotice | null, signal: AbortSignal) => { + signals.push(signal); + return new Promise(() => {}); + }; + const { rerender } = renderHook(({ at }) => useSubscription([at], read), { initialProps: { at: S1 } }); + act(() => subscriptions[0]!.options.onChange(notice("items"))); + rerender({ at: topic.session("s2") }); + expect(signals[0]!.aborted).toBe(true); + }); + it("drops a waiting read on unmount", async () => { const gate = gatedRead(); const { unmount } = renderHook(() => useSubscription([S1], gate.read)); diff --git a/packages/shift-manager/src/components/TaskBoardMeta.tsx b/packages/shift-manager/src/components/TaskBoardMeta.tsx index 25aaf1185c..e4426aeb87 100644 --- a/packages/shift-manager/src/components/TaskBoardMeta.tsx +++ b/packages/shift-manager/src/components/TaskBoardMeta.tsx @@ -85,11 +85,13 @@ function LiveBoard({ flow, sessionId, boardRef, children }: { flow: string; sess standing.current = undefined; }, [flow, sessionId]); - const readBoard = useCallback(async () => { + // `signal` aborts once the read's subscription or effect is gone: a read that lands after the + // board unmounted sets nothing and reloads nothing. + const readBoard = useCallback(async (_notice?: unknown, signal?: AbortSignal) => { const mine = ++latest.current; try { const tasks = await readConversationTasks(client, flow, sessionId); - if (mine !== latest.current) return; + if (mine !== latest.current || signal?.aborted === true) return; setRead({ sessionId, tasks: new Map(tasks.map((task) => [task.id, task])) }); const now = tasks.map((task) => `${task.id}:${task.status}`).join(","); if (standing.current !== undefined && standing.current !== now) void refresh(); @@ -101,7 +103,9 @@ function LiveBoard({ flow, sessionId, boardRef, children }: { flow: string; sess }, [client, refresh, flow, sessionId]); useEffect(() => { - void readBoard(); + const ended = new AbortController(); + void readBoard(null, ended.signal); + return () => ended.abort(); }, [readBoard, readAt]); const topics = useMemo(() => conversationBoardTopics(sessionId), [sessionId]); diff --git a/packages/shift-manager/src/components/TasksPanel.tsx b/packages/shift-manager/src/components/TasksPanel.tsx index 794dafa09d..1043b9ac2e 100644 --- a/packages/shift-manager/src/components/TasksPanel.tsx +++ b/packages/shift-manager/src/components/TasksPanel.tsx @@ -70,12 +70,14 @@ export function TasksPanel({ last.current = { movedAt: 0 }; }, [worker.kind, sessionId]); - const readTasks = useCallback(async () => { + // `signal` aborts once the read's subscription or effect is gone: a read that lands after the + // panel unmounted, or moved to another conversation, sets nothing and reloads nothing. + const readTasks = useCallback(async (_notice?: unknown, signal?: AbortSignal) => { if (sessionId === null || worker.kind === null) return; const mine = ++latest.current; try { const tasks = await readConversationTasks(client, worker.kind, sessionId); - if (mine !== latest.current) return; + if (mine !== latest.current || signal?.aborted === true) return; setRead({ tasks }); const now = standing(tasks); if (last.current.standing !== undefined && last.current.standing !== now) { @@ -85,13 +87,15 @@ export function TasksPanel({ last.current.standing = now; setTimed(tasks.some(isOpen) || Date.now() - last.current.movedAt < AFTER_A_MOVE_MS); } catch (error: unknown) { - if (mine === latest.current) setRead({ failure: describeFailure(error).message }); + if (mine === latest.current && signal?.aborted !== true) setRead({ failure: describeFailure(error).message }); } }, [client, refresh, worker.kind, sessionId]); // On open, and after each turn the user sends. useEffect(() => { - void readTasks(); + const ended = new AbortController(); + void readTasks(null, ended.signal); + return () => ended.abort(); }, [readTasks, readAt]); const topics = useMemo(() => (sessionId === null || worker.kind === null ? [] : conversationBoardTopics(sessionId)), [sessionId, worker.kind]); diff --git a/packages/shift-manager/test/conversation-tasks-panel.test.tsx b/packages/shift-manager/test/conversation-tasks-panel.test.tsx index 590d0e0071..2e479491f9 100644 --- a/packages/shift-manager/test/conversation-tasks-panel.test.tsx +++ b/packages/shift-manager/test/conversation-tasks-panel.test.tsx @@ -53,13 +53,21 @@ vi.mock("../src/lib/conversation-tasks", async (importOriginal) => ({ readConversationTasks: async (_c: unknown, flow: string, sessionId: string) => { calls.push(`list ${flow} ${sessionId}`); if (refusal !== null) throw new Error(refusal); - return [...rows]; + const answer = [...rows]; + // A case holding reads open answers each when it releases it. + if (holdReads) return new Promise((resolve) => held.push(() => resolve(answer))); + return answer; }, })); +let holdReads = false; +const held: Array<() => void> = []; + const shiftCoordinator = toWorker({ id: "shift-coordinator", kind: "coordinator", door: "run" })!; beforeEach(() => { + holdReads = false; + held.length = 0; rows = []; refusal = null; calls.length = 0; @@ -234,6 +242,23 @@ describe("the tasks panel (S11)", () => { await hear({ topic: { scope: "session", id: "s1", resource: "tasks" }, kind: "board" }); expect(shown().map((task) => task.id)).toEqual(["t1", "t2"]); }); + + it("reloads nothing when it unmounts with a read still in flight", async () => { + rows = [{ id: "t1", goal: "Audit the licenses", status: "in_progress", assignee: "licenses", attempts: 1 }]; + const view = render(); + await settle(); + // A notice's read is in flight, and would show the task moved. + holdReads = true; + rows = [{ id: "t1", goal: "Audit the licenses", status: "completed", assignee: "licenses", attempts: 1 }]; + await hear({ topic: { scope: "session", id: "s1", resource: "tasks" }, kind: "board" }); + expect(held).toHaveLength(1); + view.unmount(); + await act(async () => { + held.forEach((release) => release()); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + expect(refreshes).toHaveLength(0); + }); }); }); diff --git a/packages/shift-manager/test/task-card-in-feed.test.tsx b/packages/shift-manager/test/task-card-in-feed.test.tsx index 55e19f57d7..c32472e887 100644 --- a/packages/shift-manager/test/task-card-in-feed.test.tsx +++ b/packages/shift-manager/test/task-card-in-feed.test.tsx @@ -47,11 +47,19 @@ vi.mock("../src/lib/conversation-tasks", async (importOriginal) => ({ readConversationTasks: async (_c: unknown, flow: string, sessionId: string) => { calls.push(`list ${flow} ${sessionId}`); if (failing) throw new Error("network"); - return rows.map((row) => ({ ...row })); + const answer = rows.map((row) => ({ ...row })); + // A case holding reads open answers each when it releases it. + if (holdReads) return new Promise((resolve) => held.push(() => resolve(answer))); + return answer; }, })); +let holdReads = false; +const held: Array<() => void> = []; + beforeEach(() => { + holdReads = false; + held.length = 0; rows = []; failing = false; refreshes = 0; @@ -191,6 +199,20 @@ describe("a delegated post's task in the feed", () => { expect(cards()[0]!.status).toBe("errored"); }); + it("reloads nothing when it unmounts with a read still in flight", async () => { + rows = [{ id: "t1", goal: "g", title: "Post for eng.pm", status: "in_progress", assignee: "eng.pm", attempts: 1 }]; + const view = render(scope([filed("r1", "t1", "Post for eng.pm", "eng.pm")], ["r1"])); + await tick(0); + holdReads = true; + rows = [{ ...rows[0]!, status: "completed" }]; + await hear(boardNotice); + expect(held).toHaveLength(1); + view.unmount(); + held.forEach((release) => release()); + await tick(0); + expect(refreshes).toBe(0); + }); + it("reads one board for every card in the feed", async () => { const items = [filed("r1", "t1", "Post for eng.pm", "eng.pm"), filed("r2", "t2", "Post for eng.qa", "eng.qa")]; rows = [ From 1cdac67bc6885496fc342471a3532f951c8c8e11 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 01:57:27 +0000 Subject: [PATCH 07/13] FIX-2429: Teammates cards keep the spend the board read already folded listTasks returns each row's spend as a folded TaskSpendView; after the board read's fields won the merge, spendOf folded it again and read nothing spent, wiping the card's harness and model (Codex r4462663901). spendOf now takes either shape. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn --- labs/teammates/src/adapter.ts | 13 ++++++++++--- labs/teammates/test/run-link.test.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/labs/teammates/src/adapter.ts b/labs/teammates/src/adapter.ts index d87ede30e1..ceca3d8951 100644 --- a/labs/teammates/src/adapter.ts +++ b/labs/teammates/src/adapter.ts @@ -50,7 +50,7 @@ import { type RosterEntry, type WorkforceClient, } from "@flow-state-dev/workforce/browser"; -import { isTerminalStatus, parseNotice, taskSpendView } from "@flow-state-dev/orchestration/tasks"; +import { isTerminalStatus, parseNotice, taskSpendView, taskSpendViewSchema } from "@flow-state-dev/orchestration/tasks"; import { createInboxClient, inboxItems, taskRowView, type InboxAnswer, type InboxHold, type InboxRow } from "@flow-state-dev/orchestration/inbox"; import { reviewDetail, type ReviewDetail } from "@flow-state-dev/harness-manager/browser"; import { CODER_FLOW } from "./lib/coder-flow"; @@ -414,10 +414,17 @@ function boardRows(items: readonly Item[]): Map> { return rows; } -/** What a row's spend says ran it: the harness and model its run reported, or nothing. */ +/** + * What a row's spend says ran it: the harness and model its run reported, or nothing. + * + * A row reaches here in one of two shapes: the stored ledger (`spend.requests`), as a + * `task-change` item carries it, or the view the board's `listTasks` read already folded + * (`taskSpendViewSchema`). Folding a view again would read as nothing spent. + */ function spendOf(row: Record): { harness?: string; model?: string } { try { - const view = taskSpendView(row as never); + const folded = taskSpendViewSchema.safeParse(row.spend); + const view = folded.success ? folded.data : taskSpendView(row as never); return { ...(view?.harness == null ? {} : { harness: view.harness }), ...(view?.model == null ? {} : { model: view.model }) }; } catch { return {}; diff --git a/labs/teammates/test/run-link.test.ts b/labs/teammates/test/run-link.test.ts index 6f32f83971..2e20c48fdf 100644 --- a/labs/teammates/test/run-link.test.ts +++ b/labs/teammates/test/run-link.test.ts @@ -153,6 +153,32 @@ describe("a coding task's run, while it runs", () => { }); }); +describe("what a task's runs spent, as the board read folds it", () => { + it("keeps the harness and model the read reports: its `spend` is already a folded view", async () => { + const item = filed("completed"); + const push = fakeSubscribe(); + const client = { + subscribe: push.subscribe, + sessions: { + state: async () => ({ at: 1, sessionCreatedAt: 1, items: [item], pagination: { hasMore: false, nextOffset: 1 } }), + stream: () => ({ close() {} }), + get: async () => ({ id: "wks_1", flowKind: "agent" }), + }, + flow: () => ({ + read: async () => ({ + ok: true, + tasks: [{ ...item.data.task, spend: { harness: "codex", model: "gpt-5.5-codex", inputTokens: 10, outputTokens: 5, costUsd: null, unreported: false, live: false } }], + }), + }), + } as unknown as Client; + let tasks: BoardTask[] = []; + const stop = createLabAdapter(client).watchTasks("wks_1", (next) => (tasks = next)); + await until(() => tasks[0]?.model !== undefined); + stop(); + expect(tasks[0]).toMatchObject({ harness: "Codex", model: "gpt-5.5-codex" }); + }); +}); + describe("a board read still in flight when the watch stops", () => { it("shows nothing and follows no run once it lands", async () => { const item = filed("in_progress"); From 24d3b3e8d00f7fd07cd4d4524051e97a314cfd1a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 02:00:02 +0000 Subject: [PATCH 08/13] shift-manager: port main's FIX-2393 registry drift into the byte copies #4621 updated packages/ui/registry/components/{tool.tsx,tool-grouping.ts, tool-naming.ts} without Shift Manager's copies, so static.test.ts fails on main. Copied byte-for-byte. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn --- .../components/flow-state/tool-grouping.ts | 67 +++++++- .../src/components/flow-state/tool-naming.ts | 149 +++++++++++++++++- .../src/components/flow-state/tool.tsx | 47 ++---- 3 files changed, 224 insertions(+), 39 deletions(-) diff --git a/packages/shift-manager/src/components/flow-state/tool-grouping.ts b/packages/shift-manager/src/components/flow-state/tool-grouping.ts index 39dd405940..ac960fc58f 100644 --- a/packages/shift-manager/src/components/flow-state/tool-grouping.ts +++ b/packages/shift-manager/src/components/flow-state/tool-grouping.ts @@ -5,9 +5,13 @@ * and reused from any UI layer. The grouping walk itself lives in * `@flow-state-dev/react`'s ItemsRenderer so framework filters (dedup, * sub-agent, container-owner suppression) run before grouping. This file - * is responsible for the verb-phrase vocabulary and label composition. + * is responsible for the verb-phrase vocabulary and label composition, and + * for where a run of steps stands: each step's state, the run's, the words + * that say it, and whether the run is open. */ +import { toolBaseName, toolOutcome } from "./tool-naming"; + /** * Verb-phrase entry for a tool. Two forms: a singular phrase used when a * group contains exactly one call of this tool, and a function that @@ -58,11 +62,26 @@ export const TOOL_VERB_MAP: Record = { grep: { singular: "searched the code", plural: (n) => `searched the code ${n} times` }, glob: { singular: "looked for files", plural: (n) => `looked for files ${n} times` }, load_tools: { singular: "loaded tools", plural: () => "loaded tools" }, + // Workforce's project reads, which merge with any other read, search or listing. + readProjectSource: { singular: "read a file", plural: (n) => `read ${n} files` }, + grepProjectSource: { singular: "searched the code", plural: (n) => `searched the code ${n} times` }, + globProjectSource: { singular: "looked for files", plural: (n) => `looked for files ${n} times` }, + // The task board's tools and a worker's own. + createTask: { singular: "started a task", plural: (n) => `started ${n} tasks` }, + getTask: { singular: "checked on a task", plural: (n) => `checked on tasks ${n} times` }, + updateTask: { singular: "updated a task", plural: (n) => `updated tasks ${n} times` }, + listTasks: { singular: "looked over the tasks", plural: (n) => `looked over the tasks ${n} times` }, + holdTaskForUser: { singular: "asked you a question", plural: (n) => `asked you ${n} questions` }, + suspendForUser: { singular: "asked for your answer", plural: (n) => `asked for your answer ${n} times` }, + sendMessage: { singular: "sent a message", plural: (n) => `sent ${n} messages` }, + reportProgress: { singular: "noted progress", plural: (n) => `noted progress ${n} times` }, + consultSessionHistory: { singular: "read a conversation", plural: (n) => `read ${n} conversations` }, }; /** Look up verbs for a tool name, in any case (Claude Code says `Bash`), falling back to a generic phrase. */ function verbsFor(toolName: string): ToolVerbs { - const entry = TOOL_VERB_MAP[toolName] ?? TOOL_VERB_MAP[toolName.toLowerCase()]; + const base = toolBaseName(toolName); + const entry = TOOL_VERB_MAP[base] ?? TOOL_VERB_MAP[base.toLowerCase()]; if (entry !== undefined) return entry; return { singular: `ran \`${toolName}\``, @@ -155,3 +174,47 @@ export function composeToolCallsLabel(calls: ToolCallLabelInput[]): string { const shown = phrases.slice(0, TOOL_GROUP_INTENT_CAP).join(" · "); return `${shown} · +${phrases.length - TOOL_GROUP_INTENT_CAP} more`; } + +/** Where one step, or a run of steps, stands. A state, never a colour: each app draws its own. */ +export type ToolStepState = "running" | "waiting" | "completed" | "error"; + +/** A call's own status, as a host reads it off its item, before its result is read. */ +export type ToolCallStatus = "running" | "waiting" | "failed" | "done"; + +/** + * One call's state: its status, and, once it is done, whether its result + * reports a failure ({@link toolOutcome}). A refused read is as failed as a + * thrown one. + */ +export function toolStepState(status: ToolCallStatus, toolName: string, output?: unknown): ToolStepState { + if (status === "failed") return "error"; + if (status === "waiting") return "waiting"; + if (status === "running") return "running"; + return toolOutcome(toolName, output) === "failed" ? "error" : "completed"; +} + +/** A run's state from its steps': failed over waiting over running over done. */ +export function toolRunState(states: readonly ToolStepState[]): ToolStepState { + if (states.includes("error")) return "error"; + if (states.includes("waiting")) return "waiting"; + if (states.includes("running")) return "running"; + return "completed"; +} + +/** + * A line with its state in words: "…" while running, "(failed)" or + * "(waiting)" after it, "(2 failed)" for `count` of a run of `total` steps. + */ +export function withToolState(label: string, state: ToolStepState, count = 1, total = 1): string { + if (state === "running") return `${label}…`; + if (state === "error" || state === "waiting") { + const word = state === "error" ? "failed" : "waiting"; + return total > 1 ? `${label} (${count} ${word})` : `${label} (${word})`; + } + return label; +} + +/** A run of steps shows open while it is running and folds once it isn't. */ +export function toolRunOpen(state: ToolStepState): boolean { + return state === "running"; +} diff --git a/packages/shift-manager/src/components/flow-state/tool-naming.ts b/packages/shift-manager/src/components/flow-state/tool-naming.ts index 4fb17557d6..e9c5884255 100644 --- a/packages/shift-manager/src/components/flow-state/tool-naming.ts +++ b/packages/shift-manager/src/components/flow-state/tool-naming.ts @@ -1,10 +1,12 @@ /** * Pure helpers that name a tool call: what it did in a few words. * - * `toolSubject` reads a call's name and args into one short line ("Read - * src/a.ts", "Calling MCP tool Linear Get Issue", the shell command it ran); - * `toolIntent` reads the description a call states about itself. Free of DOM - * and component imports, so any UI layer can use them. + * `toolSubject` reads a call's name and args, and its result once it has one, + * into one short line ("Read src/a.ts", `Search "x" · 3 matches`, "Calling MCP + * tool Linear Get Issue", the shell command it ran); `toolIntent` reads the + * description a call states about itself; `toolOutcome` says whether a call's + * result reports that it failed. Free of DOM and component imports, so any UI + * layer can use them. */ const SHELL_TOOLS = new Set(["shell", "bash", "command_execution", "run_command", "terminal"]); @@ -77,14 +79,149 @@ function clip(text: string): string { /** What one call acted on, read off its args. `code` marks a shell command, shown in mono. */ export type ToolSubject = { text: string; code: boolean }; +type Fields = Record; + +const asFields = (value: unknown): Fields => + value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Fields) : {}; + +/** A trimmed, non-blank string field, else undefined. */ +function textOf(record: Fields, key: string): string | undefined { + const value = record[key]; + return typeof value === "string" && value.trim() !== "" ? value.trim() : undefined; +} + +/** `1 match`, `3 matches`, `no matches`; `50+ matches` when the result was cut. */ +function counted(n: number, one: string, many: string, cut: boolean): string { + if (n === 0 && !cut) return `no ${many}`; + return `${n}${cut ? "+" : ""} ${n === 1 && !cut ? one : many}`; +} + +/** The lines a read asked for: `lines 3-9`, `line 3`, `from line 3`. */ +function lineRange(args: Fields): string | undefined { + const start = typeof args.startLine === "number" ? args.startLine : undefined; + const end = typeof args.endLine === "number" ? args.endLine : undefined; + if (end === undefined) return start === undefined ? undefined : `from line ${start}`; + if (start === end) return `line ${end}`; + return `lines ${start ?? 1}-${end}`; +} + +/** + * How a workforce or task tool says what it did, from its args and, once the + * call is done, its result. Never an id: a task or message id means nothing to + * the person reading, so a task is named by its title, else its goal. + */ +const WORK_TOOLS: Record string> = { + readProjectSource: (args, output) => { + const path = textOf(args, "path") ?? (output === undefined ? undefined : textOf(output, "path")); + if (path === undefined) return "Read a project file"; + const range = lineRange(args); + return `Read ${shortPath(path)}${range === undefined ? "" : `, ${range}`}`; + }, + grepProjectSource: (args, output) => { + const pattern = textOf(args, "pattern"); + const prefix = textOf(args, "prefix"); + let line = pattern === undefined ? "Search the project" : `Search "${pattern}"`; + if (prefix !== undefined) line += ` in ${shortPath(prefix)}`; + if (output?.kind === "grep" && Array.isArray(output.matches)) { + line += ` · ${counted(output.matches.length, "match", "matches", output.cut != null)}`; + } + return line; + }, + globProjectSource: (args, output) => { + const pattern = textOf(args, "pattern"); + let line = pattern === undefined ? "List the project's files" : `List ${pattern}`; + if (output?.kind === "glob" && Array.isArray(output.paths)) { + line += ` · ${counted(output.paths.length, "file", "files", output.cut != null)}`; + } + return line; + }, + createTask: (args) => { + const named = textOf(args, "title") ?? textOf(args, "goal"); + return named === undefined ? "Start a task" : `Start a task: ${named}`; + }, + getTask: (_args, output) => { + const task = asFields(output?.task); + const named = textOf(task, "title") ?? textOf(task, "goal"); + return named === undefined ? "Check on a task" : `Check on "${named}"`; + }, + updateTask: () => "Update a task", + listTasks: () => "Look over the tasks", + holdTaskForUser: () => "Ask you a question", + suspendForUser: (args) => { + const kind = textOf(args, "kind"); + const asks = kind === "approval" ? "Ask for your approval" : kind === "review" ? "Ask for your review" : "Ask for your answer"; + const title = textOf(args, "title"); + return title === undefined ? asks : `${asks}: ${title}`; + }, + sendMessage: (args) => { + const to = args.to; + if (typeof to === "string" && to.trim() !== "") return `Message ${to.trim()}`; + const target = asFields(to); + if (typeof target.task === "string") return "Message the worker on a task"; + if (typeof target.session === "string") return "Message a conversation"; + return "Send a message"; + }, + reportProgress: (args) => { + const note = textOf(args, "statusNote"); + return note === undefined ? "Note progress" : `Note progress: ${note}`; + }, + consultSessionHistory: () => "Read a conversation", +}; + +/** + * The tool a name stands for. A board-qualified task tool + * (`createTask_`, when two boards share a block) is its base tool. The + * suffix is orchestration's `taskToolSuffix`, the one place it is built; this + * file can't import orchestration, so it only strips it, and only when the + * base is a tool named here, so `read_file` stays `read_file`. + */ +export function toolBaseName(toolName: string): string { + if (Object.hasOwn(WORK_TOOLS, toolName)) return toolName; + const cut = toolName.indexOf("_"); + if (cut <= 0) return toolName; + const base = toolName.slice(0, cut); + return Object.hasOwn(WORK_TOOLS, base) ? base : toolName; +} + +/** Whether a call worked, as its result reports it. */ +export type ToolOutcome = "ok" | "failed"; + +/** + * Whether a call's result says it failed. A tool that refuses answers with a + * result, not a throw, in one of four shapes: `{ ok: false, error }`, + * `{ kind: "refused", reason, message }`, `{ status: "failed", error }` (a + * send that waited on a reply its message never got to give), and a project + * read whose `status` isn't `ok` (`missing`, `binary`, ...), the one rule tied + * to a tool. Any other `status` (a task filed `held`, a fetched task that + * failed) says nothing about the call, and a search that found nothing worked. + * A thrown call is its item's status, not this. + */ +export function toolOutcome(toolName: string, output: unknown): ToolOutcome { + const record = asFields(output); + if (record.ok === false) return "failed"; + if (record.kind === "refused") return "failed"; + if (record.status === "failed" && record.error !== undefined) return "failed"; + if (toolBaseName(toolName) === "readProjectSource" && record.kind === "read" && record.status !== "ok") return "failed"; + return "ok"; +} + /** * Names what a call did, so a run of calls to one tool reads as distinct steps: * the command a shell ran, the file a read opened, the pattern a grep sought. * The verb is the tool's name, title-cased; the subject is the first of a * short list of common args the call carries. Undefined when it carries none, - * which keeps the tool's name. + * which keeps the tool's name. A workforce or task tool has words of its own, + * and says more once `output`, the call's result, is given: a search's match + * count, a task's title. Without one (a call still running) it says what its + * args say. */ -export function toolSubject(toolName: string, args: unknown): ToolSubject | undefined { +export function toolSubject(toolName: string, args: unknown, output?: unknown): ToolSubject | undefined { + const base = toolBaseName(toolName); + const work = Object.hasOwn(WORK_TOOLS, base) ? WORK_TOOLS[base] : undefined; + if (work !== undefined) { + const result = output === undefined || output === null ? undefined : asFields(output); + return { text: clip(work(asFields(args), result)), code: false }; + } if (args === null || typeof args !== "object") return undefined; const record = args as Record; const lower = toolName.toLowerCase(); diff --git a/packages/shift-manager/src/components/flow-state/tool.tsx b/packages/shift-manager/src/components/flow-state/tool.tsx index 4acee12993..14b745c813 100644 --- a/packages/shift-manager/src/components/flow-state/tool.tsx +++ b/packages/shift-manager/src/components/flow-state/tool.tsx @@ -7,6 +7,7 @@ * each call's stated intent, or the name-based phrase when none stated one. * Running ends in "…", waiting says "(waiting)", failure says "(failed)" in * words and stays muted: a failed call is routine, not an alarm on the run. + * A call fails when it throws or when its result says it was refused. * No status badge on the line. * * An agent's working, the tool calls and the thinking between the things it @@ -35,7 +36,7 @@ import { } from "lucide-react"; import { CodeBlock } from "./code-block"; -import { composeToolCallsLabel } from "./tool-grouping"; +import { composeToolCallsLabel, toolRunState, toolStepState, withToolState, type ToolStepState } from "./tool-grouping"; import { toolIntent, toolSubject } from "./tool-naming"; export { @@ -220,35 +221,28 @@ function getToolErrorText(item: ToolItem): string | undefined { return raw === undefined ? undefined : String(raw); } -type LineState = "running" | "waiting" | "completed" | "error"; - -function lineState(item: ToolItem): LineState { +/** A call's state is its status, then whether its result reports a failure (a refused read). */ +function lineState(item: ToolItem): ToolStepState { // A thought that ended unfinished (a stream that dropped mid-thought) is over, not still going. if (isThought(item)) return item.status === "in_progress" ? "running" : "completed"; const state = mapToolStatus(item); - if (state === "error") return "error"; - if (state === "awaiting") return "waiting"; - if (state === "completed") return "completed"; - return "running"; + const status = state === "error" ? "failed" : state === "awaiting" ? "waiting" : state === "completed" ? "done" : "running"; + return toolStepState(status, getToolName(item), getToolOutput(item)); } -function runState(items: readonly ToolItem[]): LineState { - const states = items.map(lineState); - if (states.includes("error")) return "error"; - if (states.includes("waiting")) return "waiting"; - if (states.includes("running")) return "running"; - return "completed"; +function runState(items: readonly ToolItem[]): ToolStepState { + return toolRunState(items.map(lineState)); } function labelInput(item: Exclude) { const name = getToolName(item); const args = getToolArgs(item); - const subject = toolSubject(name, args); + const subject = toolSubject(name, args, getToolOutput(item)); return { name, intent: toolIntent(name, args), subject }; } /** "Thinking" while it goes on, "Thought" once it has. */ -const thoughtWord = (state: LineState) => (state === "running" ? "Thinking" : "Thought"); +const thoughtWord = (state: ToolStepState) => (state === "running" ? "Thinking" : "Thought"); function ToolCallDetails({ item }: { item: ToolItem }) { if (isThought(item)) { @@ -286,7 +280,7 @@ function ToolCallDetails({ item }: { item: ToolItem }) { type ToolLineProps = { label: string; - state: LineState; + state: ToolStepState; nested?: boolean; mono?: boolean; defaultOpen?: boolean; @@ -319,15 +313,6 @@ function ToolLine({ label, state, nested = false, mono = false, defaultOpen = fa ); } -function withState(label: string, state: LineState, count = 1, total = 1): string { - if (state === "running") return `${label}…`; - if (state === "error" || state === "waiting") { - const word = state === "error" ? "failed" : "waiting"; - return total > 1 ? `${label} (${count} ${word})` : `${label} (${word})`; - } - return label; -} - /** One call. A missing tool call renders nothing. */ export function Tool({ item }: { item: BlockTraceItem | ToolOutputItem }) { if (!item.toolCall) return null; @@ -389,13 +374,13 @@ export function ToolGroup({ items, defaultOpen = false, live = false, className const nowState = now === undefined ? state : lineState(now); label = now === undefined - ? withState(summary, state) + ? withToolState(summary, state) : isThought(now) - ? withState(thoughtLine(now) ?? thoughtWord(nowState), nowState) - : withState(nowLabel(labelInput(now)), nowState); + ? withToolState(thoughtLine(now) ?? thoughtWord(nowState), nowState) + : withToolState(nowLabel(labelInput(now)), nowState); } else { const count = one ? 1 : items.filter((item) => lineState(item) === state).length; - label = withState(summary, state, count, items.length); + label = withToolState(summary, state, count, items.length); } return ( @@ -429,7 +414,7 @@ export function ToolRow({ item, defaultOpen = false, className }: ToolRowProps) : labelInput(item); return ( Date: Wed, 4 Nov 2026 02:12:25 +0000 Subject: [PATCH 09/13] FIX-2429: every committed row write publishes a board notice, task-change or not A write with no lifecycle kind (a run's spend tick, a cleared marker, steers taken) skipped onChange, so it published no board notice and a view of the board's read (its model, tokens and cost) stayed frozen (Codex r4462717502). The backings' one emitter now hands a kind-null write to onWrite, and getOrCreateTaskCollection publishes the board notice from there. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn --- .../src/tasks/collection/change-event.ts | 21 ++++++++---- .../src/tasks/collection/get-or-create.ts | 16 ++++++--- .../src/tasks/collection/resource-backed.ts | 15 +++++--- .../src/tasks/collection/state-backed.ts | 17 ++++++---- .../test/tasks/board-notice.test.ts | 34 +++++++++++++++++-- 5 files changed, 78 insertions(+), 25 deletions(-) diff --git a/packages/orchestration/src/tasks/collection/change-event.ts b/packages/orchestration/src/tasks/collection/change-event.ts index ec14d502fe..d591b01e53 100644 --- a/packages/orchestration/src/tasks/collection/change-event.ts +++ b/packages/orchestration/src/tasks/collection/change-event.ts @@ -74,17 +74,26 @@ export interface TaskChangeEvent { } /** - * Build the `emit` a collection backing calls after every successful mutation. + * Build the `emit` a collection backing calls after every committed write of a + * row, whatever it changed. * - * Both backings publish the identical envelope; only how they resolve the task - * differs. A no-op when the caller supplied no `onChange`, so call sites stay - * unconditional. + * A write with a `kind` is a lifecycle change: `onChange` gets the event (the + * `task-change` item). A write with kind `null` changes the row without being + * one (a run's spend, a cleared marker, steers taken): only `onWrite` hears of + * it (FIX-2429), so a view of the board still reads again. Both backings + * publish the identical envelope; only how they resolve the task differs. + * Absent callbacks are no-ops, so call sites stay unconditional. */ export function createTaskChangeEmitter( collectionId: string, - onChange: ((event: TaskChangeEvent) => void) | undefined -): (kind: TaskChangeKind, task: Task, prevStatus?: TaskStatus) => void { + onChange: ((event: TaskChangeEvent) => void) | undefined, + onWrite?: (task: Task) => void +): (kind: TaskChangeKind | null, task: Task, prevStatus?: TaskStatus) => void { return (kind, task, prevStatus) => { + if (kind === null) { + onWrite?.(task as Task); + return; + } if (onChange === undefined) return; onChange({ collectionId, diff --git a/packages/orchestration/src/tasks/collection/get-or-create.ts b/packages/orchestration/src/tasks/collection/get-or-create.ts index ca5b5cea37..fa2778aeab 100644 --- a/packages/orchestration/src/tasks/collection/get-or-create.ts +++ b/packages/orchestration/src/tasks/collection/get-or-create.ts @@ -172,12 +172,16 @@ export async function getOrCreateTaskCollection { + const filer = task.filer?.sessionId ?? legacyFiler?.(task) ?? runningSession; + if (filer !== undefined) publishBoardChange(options.ctx, { sessionId: filer, board: options.collectionId }); + }; const onChange = (event: TaskChangeEvent): void => { - // A board notice beside the item: the item goes on the writing session's - // stream; the notice reaches every open view of the filer's board, from - // whichever session and process settles the row. Server-written (BP-031). - const filer = event.task.filer?.sessionId ?? legacyFiler?.(event.task) ?? runningSession; - if (filer !== undefined) publishBoardChange(options.ctx, { sessionId: filer, board: event.collectionId }); + // The notice beside the item: the item goes on the writing session's stream. + onWrite(event.task); options.ctx.emit.component( TASK_CHANGE_COMPONENT_TYPE, { @@ -208,6 +212,7 @@ export async function getOrCreateTaskCollection void; + /** + * Fired after a committed write that is no lifecycle change, so emits no + * `task-change` (a run's spend, a cleared marker): with `onChange`, every + * write that changes a row reaches one of the two (FIX-2429). + */ + onWrite?: (task: Task) => void; /** * Item-log accessor for `TaskHandle.items()` (FIX-480). Reads the * response's persistent item buffer at call time so synthesizer @@ -529,7 +535,8 @@ export async function createResourceBackedTaskCollection( options.collectionId, - onChange + onChange, + options.onWrite ); function listAll(): Task[] { @@ -633,7 +640,7 @@ export async function createResourceBackedTaskCollection void; + /** + * Fired after a committed write that is no lifecycle change, so emits no + * `task-change` (a run's spend, a cleared marker): with `onChange`, every + * write that changes a row reaches one of the two (FIX-2429). + */ + onWrite?: (task: Task) => void; /** * Item-log accessor for `TaskHandle.items()` (FIX-480). Reads the * response's persistent item buffer at call time so synthesizer @@ -201,7 +207,8 @@ export function createStateBackedTaskCollection( options.collectionId, - onChange + onChange, + options.onWrite ); /** @@ -407,9 +414,7 @@ export function createStateBackedTaskCollection { + // A request of its own, on a row claimed earlier: only the spend write happens here. + const board = await desk(ctx); + const row = board.list()[0]; + if (row === undefined) throw new Error("nothing filed"); + await board.recordSpend!( + row.id, + { requestId: ctx.request.identity.id, part: "live", spend: { byModel: { "openai/gpt-6-luna": { prompt: 10, completion: 5, total: 15, cacheReadTokens: 0, cacheCreationTokens: 0 } }, harnessRuns: [] } }, + { claim: ticketForClaim(BOARD, row) } + ); + return {}; + } + }) + }, scratch: { block: handler({ name: "scratch", @@ -73,7 +93,7 @@ function boot() { }); return notices; }; - const run = async (actionName: "file" | "settle" | "scratch", sessionId: string) => { + const run = async (actionName: "file" | "settle" | "scratch" | "spend", sessionId: string) => { const result = await runAction({ orgId: DEFAULT_ORG_ID, flow, actionName, input: {}, userId: "alice", sessionId, stores, runtimeConfig: {} }); if (result.error !== undefined) throw new Error(`${actionName} failed: ${JSON.stringify(result.error)}`); await new Promise((resolve) => setTimeout(resolve, 20)); @@ -107,4 +127,14 @@ describe("a board change publishes a board notice", () => { await run("scratch", "worker"); expect(scratch.map((n) => n.topic)).toEqual([{ scope: "session", id: "worker", tenantId: "", resource: "scratch" }]); }); + + it("for a write that emits no task-change item: a run's spend, which the board read shows", async () => { + const { heard, run } = boot(); + const conversationBoard = heard("conversation", BOARD); + await run("file", "conversation"); + const spent = await run("spend", "task-session"); + expect(conversationBoard.filter((n) => n.origin?.requestId === spent)).toEqual([ + { topic: { scope: "session", id: "conversation", tenantId: "", resource: BOARD }, kind: "board", origin: { requestId: spent } } + ]); + }); }); From 8d73ed4aa0e49851a856f2bfb93872e805d47655 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 02:17:24 +0000 Subject: [PATCH 10/13] fallow: ignore toolRunOpen in Shift Manager's registry copy, as #4654 does The ported FIX-2393 copy carries an export nothing in Shift Manager calls; the same ignore line #4654 adds, so whichever merges second merges cleanly. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn --- .fallowrc.json | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/.fallowrc.json b/.fallowrc.json index 8e150af19d..44cb5276ea 100644 --- a/.fallowrc.json +++ b/.fallowrc.json @@ -136,12 +136,13 @@ "packages/shift-manager/src/components/flow-state/spend.tsx" ], - // One named export, not a whole file. Kitchen Sink's byte copy of the registry's - // tool-grouping carries `toolRunOpen`, the open-while-running rule the labs follow - // (specs/issues/FIX-2393/SPEC.md, "One step-run state"); the registry's own - // ToolGroup keeps its `defaultOpen` prop, so nothing in Kitchen Sink calls it. + // One named export, not a whole file. Kitchen Sink's and Shift Manager's byte + // copies of the registry's tool-grouping carry `toolRunOpen`, the open-while-running + // rule the labs follow (specs/issues/FIX-2393/SPEC.md, "One step-run state"); the + // registry's own ToolGroup keeps its `defaultOpen` prop, so neither app calls it. "ignoreExports": [ - { "file": "apps/kitchen-sink/components/flow-state/tool-grouping.ts", "exports": ["toolRunOpen"] } + { "file": "apps/kitchen-sink/components/flow-state/tool-grouping.ts", "exports": ["toolRunOpen"] }, + { "file": "packages/shift-manager/src/components/flow-state/tool-grouping.ts", "exports": ["toolRunOpen"] } ], // Dead code fails `fallow audit` at its default severity. Complexity reports From 36f6e39a7bd25d5fb6887be27d237ca45fac0818 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 02:27:43 +0000 Subject: [PATCH 11/13] registry: say user in tool-naming's copies, as #4654 does The retired-terms check counts "the person reading" in Shift Manager's copy. The same one-word change #4654 makes, in the registry and both byte copies, so whichever merges second merges cleanly. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn --- apps/kitchen-sink/components/flow-state/tool-naming.ts | 2 +- packages/shift-manager/src/components/flow-state/tool-naming.ts | 2 +- packages/ui/registry/components/tool-naming.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/kitchen-sink/components/flow-state/tool-naming.ts b/apps/kitchen-sink/components/flow-state/tool-naming.ts index e9c5884255..6e982d7f5f 100644 --- a/apps/kitchen-sink/components/flow-state/tool-naming.ts +++ b/apps/kitchen-sink/components/flow-state/tool-naming.ts @@ -108,7 +108,7 @@ function lineRange(args: Fields): string | undefined { /** * How a workforce or task tool says what it did, from its args and, once the * call is done, its result. Never an id: a task or message id means nothing to - * the person reading, so a task is named by its title, else its goal. + * the user reading, so a task is named by its title, else its goal. */ const WORK_TOOLS: Record string> = { readProjectSource: (args, output) => { diff --git a/packages/shift-manager/src/components/flow-state/tool-naming.ts b/packages/shift-manager/src/components/flow-state/tool-naming.ts index e9c5884255..6e982d7f5f 100644 --- a/packages/shift-manager/src/components/flow-state/tool-naming.ts +++ b/packages/shift-manager/src/components/flow-state/tool-naming.ts @@ -108,7 +108,7 @@ function lineRange(args: Fields): string | undefined { /** * How a workforce or task tool says what it did, from its args and, once the * call is done, its result. Never an id: a task or message id means nothing to - * the person reading, so a task is named by its title, else its goal. + * the user reading, so a task is named by its title, else its goal. */ const WORK_TOOLS: Record string> = { readProjectSource: (args, output) => { diff --git a/packages/ui/registry/components/tool-naming.ts b/packages/ui/registry/components/tool-naming.ts index e9c5884255..6e982d7f5f 100644 --- a/packages/ui/registry/components/tool-naming.ts +++ b/packages/ui/registry/components/tool-naming.ts @@ -108,7 +108,7 @@ function lineRange(args: Fields): string | undefined { /** * How a workforce or task tool says what it did, from its args and, once the * call is done, its result. Never an id: a task or message id means nothing to - * the person reading, so a task is named by its title, else its goal. + * the user reading, so a task is named by its title, else its goal. */ const WORK_TOOLS: Record string> = { readProjectSource: (args, output) => { From 4453c0a9c18651361796e68cc7d9b68e5d163667 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 02:48:01 +0000 Subject: [PATCH 12/13] FIX-2429: one precedence rule for a Teammates row's copies: newest updatedAt wins listTasks answered no updatedAt, so once a run's feed supplied a row, the run's copy always looked newer and every later board read was thrown away: a spend-only change never showed, and a completion through the board could stay hidden (Codex r4462900231). The board's listTasks action now answers updatedAt (additive, not on the model's tool), and watchTasks picks the newest of its three copies, ties to the board read. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn --- .changeset/board-notices.md | 2 +- labs/teammates/src/adapter.ts | 28 ++++----- labs/teammates/test/run-link.test.ts | 57 ++++++++++++++++++- .../src/skills/task-tools-capability.ts | 9 ++- .../test/skills/list-tasks-spend.test.ts | 17 ++++++ 5 files changed, 95 insertions(+), 18 deletions(-) diff --git a/.changeset/board-notices.md b/.changeset/board-notices.md index 25625e0f8f..5374f1008e 100644 --- a/.changeset/board-notices.md +++ b/.changeset/board-notices.md @@ -9,7 +9,7 @@ A task board's change reaches every open view of the board, from whichever session or process settles the task (FIX-2429). -- **orchestration:** every change to a board built by `getOrCreateTaskCollection` also publishes a `board` change notice on the topic of the session that filed the row (`Task.filer`, else the ledger's legacy filer, else the running session), narrowed to the board's `collectionId`. A screen subscribes `topic.session(conversationId, { resource: "tasks" })` and reads again. Nothing to wire: the `task-change` item is unchanged. +- **orchestration:** every change to a board built by `getOrCreateTaskCollection` also publishes a `board` change notice on the topic of the session that filed the row (`Task.filer`, else the ledger's legacy filer, else the running session), narrowed to the board's `collectionId`. A screen subscribes `topic.session(conversationId, { resource: "tasks" })` and reads again. Nothing to wire: the `task-change` item is unchanged. The board's `listTasks` action (a client's read, not the model's tool) also answers each row's `updatedAt`, so a client holding a row from two sources keeps the newer. - **engine:** the block context carries the seam that publishes a board notice on the running request's bus, under its tenant, with the request as `origin`. - **react:** **Breaking for a hand-built client slice:** a live `BoardList`'s `client` takes `subscribe` in place of `sessions.stream`. A client from `createClient` works as before. The list now hears a task that settles in another session or process, never wakes on a reply streaming in the session, and reads every 3 s where push can miss a change. `useSubscription` takes `client`, for an app that builds its own client, and hands `read` an `AbortSignal` that aborts when the subscription ends. - **core / contracts:** `ChangeKind` gains `"board"`; `publishBoardChange` and `BOARD_NOTICE_SEAM` (framework-facing) in `@flow-state-dev/core/types`. diff --git a/labs/teammates/src/adapter.ts b/labs/teammates/src/adapter.ts index 815572e1de..3a11779a54 100644 --- a/labs/teammates/src/adapter.ts +++ b/labs/teammates/src/adapter.ts @@ -934,19 +934,26 @@ export function createLabAdapter(client: Client = connect()): LabAdapter { /** * Each row as the board's last read answered it. A task settles, and its run links itself, in * the task's own session, which the conversation's stream doesn't carry; the board's notice - * does, and the read says what changed. The newer of the two copies is the row. + * does, and the read says what changed. */ let listed = new Map>(); /** * Each linked run's own copy of its row. A run writes its row on its own session (its link, its * questions, its review), so the conversation hears of those only when the task ends: the run's - * session is followed too, and the newer of the two copies is the row. + * session is followed too. */ const runRows = new Map>(); const runFeeds = new Map(); - const newer = (row: Record) => { - const fromRun = runRows.get(row.id); - return fromRun !== undefined && (fromRun.updatedAt ?? 0) > (row.updatedAt ?? 0) ? fromRun : row; + /** + * The one rule for a row's three copies (the board read, the run's, the conversation's): the + * newest by the `updatedAt` each copy carries as the row recorded it; on a tie, the board read, + * then the run's. What the newest copy leaves out (the board read carries no output) comes from + * the conversation's copy. + */ + const rowOf = (id: string): Record => { + const copies = [listed.get(id), runRows.get(id), rows.get(id)].filter((c): c is Record => c !== undefined); + const newest = copies.reduce((best, copy) => ((copy.updatedAt ?? 0) > (best.updatedAt ?? 0) ? copy : best)); + return { ...rows.get(id), ...newest }; }; const followRuns = (current: readonly Record[]) => { for (const row of current) { @@ -970,18 +977,13 @@ export function createLabAdapter(client: Client = connect()): LabAdapter { runFeeds.set(runSession, stop); } }; - // The board read's fields win: it names no time to compare, and a change after it sends a notice - // that reads again. The conversation's copy keeps what the read leaves out (a result's output). - const merged = (): Record[] => { - const all = new Map(rows); - for (const [id, row] of listed) all.set(id, { ...all.get(id), ...row }); - return [...all.values()]; - }; + /** Every row, the conversation's order first, each as {@link rowOf} settles it. */ + const merged = (): Record[] => [...new Set([...rows.keys(), ...listed.keys()])].map(rowOf); // Set once the watch stops: a read or a flow lookup that lands after it shows nothing and follows no run. let stopped = false; const publish = () => { if (stopped) return; - const current = merged().map(newer); + const current = merged(); const flowOf = (id: string) => (id === sessionId ? flowOfSession.get(sessionId) : runFlows.get(id)); const holds = holdsOfRows(sessionId, current, flowOf); openHolds.set(sessionId, holds); diff --git a/labs/teammates/test/run-link.test.ts b/labs/teammates/test/run-link.test.ts index 2e20c48fdf..4c2ab2595e 100644 --- a/labs/teammates/test/run-link.test.ts +++ b/labs/teammates/test/run-link.test.ts @@ -103,8 +103,8 @@ describe("a coding task's run, while it runs", () => { expect(reads).toHaveLength(2); }); - it("takes the board read's fields over the conversation's copy, which the read never names a time for", async () => { - // `listTasks` carries no `updatedAt`; the conversation's own copy does. + it("takes the board read over the conversation's copy when the read is as new or newer", async () => { + // The read names when the row was last written, as the conversation's copy does: the newer copy wins, a tie the read. const item = filed("in_progress"); const stamped = { ...item, data: { ...item.data, task: { ...item.data.task, updatedAt: 1 } } }; const push = fakeSubscribe(); @@ -116,7 +116,7 @@ describe("a coding task's run, while it runs", () => { stream: () => ({ close() {} }), get: async () => ({ id: "wks_1", flowKind: "agent" }), }, - flow: () => ({ read: async () => ({ ok: true, tasks: [{ ...item.data.task, ...(linked ? { run: { sessionId: "dsx_run", requestId: "req_run", attempt: 1 } } : {}) }] }) }), + flow: () => ({ read: async () => ({ ok: true, tasks: [{ ...item.data.task, updatedAt: linked ? 3 : 1, ...(linked ? { run: { sessionId: "dsx_run", requestId: "req_run", attempt: 1 } } : {}) }] }) }), } as unknown as Client; let tasks: BoardTask[] = []; const stop = createLabAdapter(client).watchTasks("wks_1", (next) => (tasks = next)); @@ -179,6 +179,57 @@ describe("what a task's runs spent, as the board read folds it", () => { }); }); +describe("a row the run's feed and the board read both carry", () => { + /** + * The conversation's copy names the run, so the run's own session is followed and supplies a + * copy of the row (updatedAt 5). The board read is whatever `board()` answers then. + */ + function twoSources(board: () => Record) { + const run = { sessionId: "dsx_run", requestId: "req_run", attempt: 1 }; + const conversation = filed("in_progress"); + const linked = { ...conversation, data: { ...conversation.data, task: { ...conversation.data.task, run, updatedAt: 2 } } }; + const fromRun = { ...linked, id: "task-change:board/task_1@run", requestId: "req_run", ts: 5, data: { ...linked.data, kind: "progress_reported", task: { ...linked.data.task, updatedAt: 5 } } }; + const push = fakeSubscribe(); + const client = { + subscribe: push.subscribe, + sessions: { + state: async (id: string) => ({ at: 1, sessionCreatedAt: 1, items: id === "dsx_run" ? [fromRun] : [linked], pagination: { hasMore: false, nextOffset: 1 } }), + stream: () => ({ close() {} }), + get: async (id: string) => ({ id, flowKind: "agent" }), + }, + flow: () => ({ read: async () => ({ ok: true, tasks: [{ ...linked.data.task, ...board() }] }) }), + } as unknown as Client; + return { client, push }; + } + const notice = { topic: { scope: "session" as const, id: "wks_1", resource: "tasks" }, kind: "board" as const }; + + it("shows a spend the board read reports after the run's copy arrived", async () => { + let spend: unknown = null; + const { client, push } = twoSources(() => ({ updatedAt: 5, spend })); + let tasks: BoardTask[] = []; + const stop = createLabAdapter(client).watchTasks("wks_1", (next) => (tasks = next)); + await new Promise((r) => setTimeout(r, 100)); + spend = { harness: "codex", model: "gpt-5.5-codex", inputTokens: 10, outputTokens: 5, costUsd: null, unreported: false, live: true }; + push.hear(notice); + await until(() => tasks[0]?.model !== undefined); + stop(); + expect(tasks[0]).toMatchObject({ harness: "Codex", model: "gpt-5.5-codex" }); + }); + + it("shows a completion the board read reports while the run's copy still says running", async () => { + let done = false; + const { client, push } = twoSources(() => (done ? { status: "completed", updatedAt: 9 } : { updatedAt: 5 })); + let tasks: BoardTask[] = []; + const stop = createLabAdapter(client).watchTasks("wks_1", (next) => (tasks = next)); + await new Promise((r) => setTimeout(r, 100)); + done = true; + push.hear(notice); + await until(() => tasks[0]?.status === "done"); + stop(); + expect(tasks[0]?.status).toBe("done"); + }); +}); + describe("a board read still in flight when the watch stops", () => { it("shows nothing and follows no run once it lands", async () => { const item = filed("in_progress"); diff --git a/packages/orchestration/src/skills/task-tools-capability.ts b/packages/orchestration/src/skills/task-tools-capability.ts index 4d5a65b18f..7764447215 100644 --- a/packages/orchestration/src/skills/task-tools-capability.ts +++ b/packages/orchestration/src/skills/task-tools-capability.ts @@ -1793,6 +1793,13 @@ function buildTaskTools(resolve: TaskCollectionResolver, options: BuildTaskTools * of its own. On the board's action only: a model's tool reads none. */ spend: taskSpendViewSchema.nullable().optional(), + /** + * When the row was last written (epoch ms), as the row records it + * (FIX-2429), so a client that holds the row from another source + * too (a run's own session) keeps the newer copy. On the board's + * action only, like `spend`. + */ + updatedAt: z.number().optional(), /** A request is waiting on this task's ending (`getTask` with `wait`). */ waitedOn: z.literal(true).optional(), ...waitingShape, @@ -1827,7 +1834,7 @@ function buildTaskTools(resolve: TaskCollectionResolver, options: BuildTaskTools ...(t.filedByTask !== undefined ? { filedByTask: t.filedByTask } : {}), ...(t.run != null ? { run: t.run } : {}), // A client's read, never a model's (FIX-2288): the action carries it, the tool doesn't. - ...(claimless ? { spend: taskSpendView(t) } : {}), + ...(claimless ? { spend: taskSpendView(t), updatedAt: t.updatedAt } : {}), ...(t.wait != null && t.wait.lapsed !== true && !isTerminalStatus(t.status) ? { waitedOn: true as const } : {}), ...waitingOf(t), ...withCurrentId(currentFor(t, latest.get(t.followUpOf ?? t.id))), diff --git a/packages/orchestration/test/skills/list-tasks-spend.test.ts b/packages/orchestration/test/skills/list-tasks-spend.test.ts index 08275beef7..589650458a 100644 --- a/packages/orchestration/test/skills/list-tasks-spend.test.ts +++ b/packages/orchestration/test/skills/list-tasks-spend.test.ts @@ -48,4 +48,21 @@ describe("listTasks and a task's spend", () => { expect(told.tasks).toHaveLength(2); for (const row of told.tasks) expect("spend" in row).toBe(false); }); + + // A client that also holds a row from another source (a run's own session) compares the two + // by version (FIX-2429): the action names when the row was last written, as the row records it. + it("answers each row's updatedAt on the action, and leaves it off the tool", async () => { + const { ctx } = buildDelegationCtx({ self: false }); + const ref = (await ownStateResolver(ctx as never))!; + await ref.createTask({ id: "t_one", goal: "Fix the login form" }); + const stored = ref.get("t_one")!; + + const actions = taskToolActions("desk", ownStateResolver); + const caller = { ...(ctx as object), user: { identity: { userId: "u1" } } }; + const acted = (await runForTest(actions["listTasks_desk"]!.block as never, {} as never, caller as never)) as { tasks: Array> }; + expect(acted.tasks[0]!.updatedAt).toBe(stored.updatedAt); + + const told = (await runForTest(toolNamed(buildTaskToolsList(ownStateResolver), "listTasks"), {} as never, ctx)) as { tasks: Array> }; + for (const row of told.tasks) expect("updatedAt" in row).toBe(false); + }); }); From a600d3a7cbbbd39f03cf3c184ee6c56eb369b214 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 02:58:23 +0000 Subject: [PATCH 13/13] FIX-2429: a Teammates row is the board read's; other copies only fill output and error Merging three copies field by field let an answered hold survive from the conversation's older copy (Codex r4463036356). Every committed row write now sends a board notice, so the board read is the row: a field it leaves out is cleared. The conversation's (else the run's) copy stands in only before the first read; an ended row takes output and error, which listTasks never carries, from the other copies. A run is let go once its own copy ends. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn --- labs/teammates/src/adapter.ts | 28 ++++++++++++------- labs/teammates/test/run-link.test.ts | 40 +++++++++++++++++++++++++--- 2 files changed, 55 insertions(+), 13 deletions(-) diff --git a/labs/teammates/src/adapter.ts b/labs/teammates/src/adapter.ts index 3a11779a54..2a4dba4009 100644 --- a/labs/teammates/src/adapter.ts +++ b/labs/teammates/src/adapter.ts @@ -263,6 +263,8 @@ const POLL_MS = 1_500; const TASK_CHANGE = "task-change"; /** The tool a worker files a task with. */ const CREATE_TASK = "createTask"; +/** What a board row's `listTasks` read never carries: an ended task's output and error, read from the row's other copies. */ +const UNPROJECTED = ["output", "error"] as const; /** The board's read of its rows, on a conversation's flow. */ const LIST_TASKS = "listTasks_tasks"; /** The ledgers that read returns: the conversation's board and its planning worker's steps. */ @@ -945,22 +947,30 @@ export function createLabAdapter(client: Client = connect()): LabAdapter { const runRows = new Map>(); const runFeeds = new Map(); /** - * The one rule for a row's three copies (the board read, the run's, the conversation's): the - * newest by the `updatedAt` each copy carries as the row recorded it; on a tie, the board read, - * then the run's. What the newest copy leaves out (the board read carries no output) comes from - * the conversation's copy. + * A row is the board read's (FIX-2429): every committed write of a row sends a board notice, so + * the read is never more than one notice behind, and a field it leaves out is cleared (an + * answered hold). Until the first read lands, the conversation's copy, else the run's, stands in. + * The run's and the conversation's copies give only what the read never carries: an ended + * task's output and error ({@link UNPROJECTED}). */ const rowOf = (id: string): Record => { - const copies = [listed.get(id), runRows.get(id), rows.get(id)].filter((c): c is Record => c !== undefined); - const newest = copies.reduce((best, copy) => ((copy.updatedAt ?? 0) > (best.updatedAt ?? 0) ? copy : best)); - return { ...rows.get(id), ...newest }; + const board = listed.get(id); + if (board === undefined) return rows.get(id) ?? runRows.get(id)!; + if (!isTerminalStatus(board.status)) return board; + const ended: Record = {}; + for (const field of UNPROJECTED) { + const value = runRows.get(id)?.[field] ?? rows.get(id)?.[field]; + if (value !== undefined) ended[field] = value; + } + return { ...board, ...ended }; }; const followRuns = (current: readonly Record[]) => { for (const row of current) { const runSession = row.run?.sessionId; if (typeof runSession !== "string") continue; - // An ended task's row already says all there is: its run is let go, or never followed. - if (isTerminalStatus(row.status)) { + // An ended task's run is let go once the run's own copy says it ended (it carries the output + // the board read doesn't), or never followed when no copy of it was ever read. + if (isTerminalStatus((runRows.get(row.id) ?? row).status)) { runFeeds.get(runSession)?.(); runFeeds.set(runSession, () => {}); continue; diff --git a/labs/teammates/test/run-link.test.ts b/labs/teammates/test/run-link.test.ts index 4c2ab2595e..73af2cb22d 100644 --- a/labs/teammates/test/run-link.test.ts +++ b/labs/teammates/test/run-link.test.ts @@ -179,6 +179,36 @@ describe("what a task's runs spent, as the board read folds it", () => { }); }); +describe("a hold answered in the run's session", () => { + it("leaves the card once the board read stops listing it, though the conversation's older copy still holds it", async () => { + const run = { sessionId: "dsx_run", requestId: "req_run", attempt: 1 }; + const hold = { id: "susp-1", actor: "user", openedAt: 2, source: { kind: "suspension", requestId: "req_run", suspensionId: "susp-1" }, ask: { kind: "review", prompt: "1 commit on b" } }; + const conversation = filed("in_progress"); + // The conversation's copy caught the row while the review was open. + const held = { ...conversation, data: { ...conversation.data, task: { ...conversation.data.task, run, updatedAt: 2, holds: [hold] } } }; + const push = fakeSubscribe(); + let answered = false; + const client = { + subscribe: push.subscribe, + sessions: { + state: async (id: string) => ({ at: 1, sessionCreatedAt: 1, items: id === "dsx_run" ? [] : [held], pagination: { hasMore: false, nextOffset: 1 } }), + stream: () => ({ close() {} }), + get: async (id: string) => (id === "dsx_run" ? { id, flowKind: "teammates-coder" } : { id, flowKind: "agent" }), + }, + // `listTasks` lists a row's open holds, and leaves `holds` out once none is open. + flow: () => ({ read: async () => ({ ok: true, tasks: [{ ...conversation.data.task, run, updatedAt: answered ? 3 : 2, ...(answered ? {} : { holds: [hold] }) }] }) }), + } as unknown as Client; + let tasks: BoardTask[] = []; + const stop = createLabAdapter(client).watchTasks("wks_1", (next) => (tasks = next)); + await until(() => tasks[0]?.waiting !== undefined); + answered = true; + push.hear({ topic: { scope: "session", id: "wks_1", resource: "tasks" }, kind: "board" }); + await until(() => tasks[0]?.waiting === undefined); + stop(); + expect(tasks[0]?.waiting).toBeUndefined(); + }); +}); + describe("a row the run's feed and the board read both carry", () => { /** * The conversation's copy names the run, so the run's own session is followed and supplies a @@ -268,8 +298,8 @@ describe("a board read still in flight when the watch stops", () => { describe("a coding task's hold, while it runs", () => { /** * The run writes its row on its own session: its link, and the review it stops for. The - * conversation's copy still says only that the task is running, so read alone, nothing waits - * on you and the popup has no review to answer. + * conversation's copy still says only that the task is running. The write sends a board notice, + * and the board's read lists the open hold, as `listTasks` does. */ function clientWithRunRow() { const conversation = filed("in_progress"); @@ -297,11 +327,11 @@ describe("a coding task's hold, while it runs", () => { stream: () => ({ close() {} }), get: async (id: string) => (id === "dsx_run" ? { id, flowKind: "teammates-coder" } : { id, flowKind: "agent" }), }, - flow: () => ({ read: async () => ({ ok: true, tasks: [{ ...conversation.data.task, run }] }) }), + flow: () => ({ read: async () => ({ ok: true, tasks: [{ ...held.data.task }] }) }), } as unknown as Client; } - it("is read from the run's own session, where the run writes it", async () => { + it("is read from the board, which the run's write reaches from its own session", async () => { let tasks: BoardTask[] = []; const stop = createLabAdapter(clientWithRunRow()).watchTasks("wks_1", (next) => (tasks = next)); await until(() => tasks[0]?.waiting !== undefined); @@ -336,6 +366,8 @@ describe("a coding task's hold, while it runs", () => { await until(() => opened.includes("dsx_run") && pushTo.has("wks_1")); expect(opened).not.toContain("dsx_old"); expect(closed).not.toContain("dsx_run"); + // The run writes its ending in its own session; the conversation hears of it too. + pushTo.get("dsx_run")!({ item: ended }); pushTo.get("wks_1")!({ item: ended }); await until(() => tasks.find((t) => t.id === "task_1")?.status === "done"); expect(tasks.find((t) => t.id === "task_1")?.status).toBe("done");