diff --git a/.changeset/shift-manager-directory-follows-changes.md b/.changeset/shift-manager-directory-follows-changes.md
new file mode 100644
index 0000000000..22937375f1
--- /dev/null
+++ b/.changeset/shift-manager-directory-follows-changes.md
@@ -0,0 +1,7 @@
+---
+"@flow-state-dev/shift-manager": patch
+---
+
+Shift Manager's directory screens follow changes made elsewhere (FIX-2775). Roster, the sidebar's TEAMS, PROJECTS and counts, Jump to, a project, Messages, Routines, Usage and Settings read the Lab's views and collections directly and stay current on their own: a hire, a new project, a paused routine or a new message from another tab or a worker's turn shows when its read hears it, not on the next whole-Lab read. A worker's on-shift status moves in the same update as the Inbox, so the two always agree. Lists show every row past 200, Retry and R read again what the screen shows, and a Lab that refuses Shift Manager or can't be reached gets the same page and words as before.
+
+Docs: packages/shift-manager/README.md (the directory screens read live; R reads what the page holds again)
diff --git a/goals/conversation-scroll/sent-line-rises-reply-stays/pages/shift-manager/fakes/lab-data.ts b/goals/conversation-scroll/sent-line-rises-reply-stays/pages/shift-manager/fakes/lab-data.ts
index ca9c1c2451..a7fd06657f 100644
--- a/goals/conversation-scroll/sent-line-rises-reply-stays/pages/shift-manager/fakes/lab-data.ts
+++ b/goals/conversation-scroll/sent-line-rises-reply-stays/pages/shift-manager/fakes/lab-data.ts
@@ -1,4 +1,4 @@
/** The Lab, scripted: no client calls, no snapshot. See `../shared.ts`. */
export * from "../../../lib/lab-data";
-const lab = { client: { userId: "alice" }, refresh: async () => undefined, answered: undefined, snapshot: undefined };
+const lab = { client: { userId: "alice" }, refresh: async () => undefined, snapshot: undefined };
export const useLab = () => lab as never;
diff --git a/goals/conversation-scroll/sent-line-rises-reply-stays/pages/shift-manager/main.tsx b/goals/conversation-scroll/sent-line-rises-reply-stays/pages/shift-manager/main.tsx
index b544280d10..6e82159007 100644
--- a/goals/conversation-scroll/sent-line-rises-reply-stays/pages/shift-manager/main.tsx
+++ b/goals/conversation-scroll/sent-line-rises-reply-stays/pages/shift-manager/main.tsx
@@ -11,7 +11,7 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { Conversation } from "../../components/Conversation";
-import { toWorker } from "../../lib/reads";
+import { toWorker } from "../../lib/workers";
import { TaskSession } from "../../surfaces/TaskSession";
import "../../styles.css";
import { exposeGoal, script } from "../script";
diff --git a/goals/harness-manager/a-runs-changes-wait-for-review/run.mts b/goals/harness-manager/a-runs-changes-wait-for-review/run.mts
index 54557aea54..d7879c9c59 100644
--- a/goals/harness-manager/a-runs-changes-wait-for-review/run.mts
+++ b/goals/harness-manager/a-runs-changes-wait-for-review/run.mts
@@ -53,7 +53,8 @@ import { LAB_ORG_ID, LAB_USER_ID, openLab, type Lab } from "../../../packages/sh
import { commitAll, createBareRemote } from "../../../packages/shift-manager/teams/devteam/scratch-repo.mts";
import { LIST_TASKS_ACTION } from "../../../packages/shift-manager/src/lib/conversation-tasks.ts";
import { connect } from "../../../packages/shift-manager/src/lib/connection.ts";
-import { CONVERSATION_BOARD_COLLECTION, createLabReader } from "../../../packages/shift-manager/src/lib/reads.ts";
+import { createLabReader } from "../../../packages/shift-manager/src/lib/reads.ts";
+import { CONVERSATION_BOARD_COLLECTION } from "../../../packages/shift-manager/src/lib/boards.ts";
stripIntentOverrides();
diff --git a/goals/realtime/app-views-read-on-notice/goal.md b/goals/realtime/app-views-read-on-notice/goal.md
index 4e9468b469..44236dc660 100644
--- a/goals/realtime/app-views-read-on-notice/goal.md
+++ b/goals/realtime/app-views-read-on-notice/goal.md
@@ -6,7 +6,7 @@
**Signal:**
- `a:within-1s` — after another client sends a slow turn into the watched session, the claude-code-style thread and the Teammates conversation report it running, Shift Manager's conversation shows its reply; after a pin the pins view shows it; after a message is logged the Talk panel and Shift Manager's message log show it; and after a workstream entry is written the project view lists it; each less than 1000 ms after the write.
- `a:within-1s` (task screen) — the task screen shows the run the board links less than 1000 ms after the link's write.
-- `a:lab-read` — a Lab read (Shift Manager's Refresh) reads the message log and the project's entries again, each within 1000 ms.
+- `a:lab-read` — a Lab read (Shift Manager's R, which reads again what the page holds; its snapshot Refresh before FIX-2775) reads the message log and the project's entries again, each within 1000 ms.
- `a:idle-0-reads` — over a 10 s idle window, each of the eight views makes 0 reads; and over 10 s waiting on its run's link, the task screen makes 0 board reads.
- `b:as-short` — during a 200-item reply each request view (thread running turn, Teammates answering, divider) makes the same number of reads as during a 2-item reply that takes as long, and Shift Manager's conversation makes none. The two replies last the same time so they differ only in items: how a request's own notices coalesce depends on how far apart they land.
- `c:within-poll` — with no crossing bus, the pins view shows a pin within 3 s + 1 s, the Teammates conversation a turn and the Talk panel a message within 1.5 s + 1 s, Shift Manager's message log a message and its project view an entry within 5 s + 1 s, and the task screen its run link within 2 s + 1 s.
@@ -53,3 +53,5 @@
| 2026-11-19 | fix/FIX-2846-fallback-read (pre-push) | n/a | FAIL (red) | Scratch edit: the task-list view given `pollIntervalMs: null`, so the waiting screen has no timer. `c:fallback-reads`: task run link made no read over 6 s |
| 2026-11-19 | fix/FIX-2846-fallback-read (pre-push) | n/a | FAIL (expected) | `timer`: `a:idle-0-reads` (task run link 3 board reads while waiting; 4, 4, 7, 14, Talk 7, entries 2, log 2 idle) |
| 2026-11-19 | fix/FIX-2846-fallback-read (pre-push) | n/a | FAIL (expected) | `every-kind`: `b:as-short` (102/105/106 reads for 200 items against 5/5/8 for 2) |
+| 2026-11-20 | fix-2775-screen-migration on 8ee63f43e0 (FIX-2775 PR 3) | n/a | FAIL | Before R read the screens' own reads: *"a:lab-read: Shift Manager message log read never after a Lab read (bound 1000)"*, and the same for the project entries. The log and the entries no longer re-read on the snapshot's `readAt`, and R read only the directory and the Inbox |
+| 2026-11-20 | fix-2775-screen-migration on 25b6080c9f | n/a | PASS | `a:lab-read` now presses Shift Manager's R (`useReadPageAgain`): *"a: read again after a Lab read: Shift Manager message log 0 ms, Shift Manager project entries 0 ms · a: 0 reads over 10 s idle in each of 8 views"* |
diff --git a/goals/realtime/app-views-read-on-notice/run.mts b/goals/realtime/app-views-read-on-notice/run.mts
index 20d9712b61..2e661939bd 100644
--- a/goals/realtime/app-views-read-on-notice/run.mts
+++ b/goals/realtime/app-views-read-on-notice/run.mts
@@ -12,7 +12,7 @@
* id), both read by the conversation's follower, and its Talk lines (`useTalk`,
* workforce's worker messages view), under its `AppProvider`, and Shift Manager's worker
* conversation (the client's `sessionFeed`, which its shared session feed holds), its message log
- * (`useMessages`), a project's entries (`useProjectRead`) and a task screen
+ * (`useMessages`), a project's entries (`useProjectWorkstreams`) and a task screen
* waiting on its run's link (`TaskProvider`), the last three under the real
* `LabProvider`, rendered by react-dom over happy-dom. Each view has its own
* client, whose fetcher counts the reads it makes.
@@ -68,9 +68,10 @@ import type { ConversationView } from "../../../labs/teammates/src/lib/conversat
import { useTalk } from "../../../labs/teammates/src/lib/talk.ts";
import { kitchenSinkWorkforce } from "../../../apps/kitchen-sink/lib/workforce-kit.ts";
import { LabProvider, useLab } from "../../../packages/shift-manager/src/lib/lab-data.tsx";
-import { useProjectRead } from "../../../packages/shift-manager/src/lib/projects.ts";
+import { useProjectWorkstreams } from "../../../packages/shift-manager/src/lib/projects.ts";
import { useMessages } from "../../../packages/shift-manager/src/lib/messages.ts";
-import { conversationBoardRef } from "../../../packages/shift-manager/src/lib/reads.ts";
+import { PageReadsProvider, useReadPageAgain } from "../../../packages/shift-manager/src/lib/page-reads.tsx";
+import { conversationBoardRef } from "../../../packages/shift-manager/src/lib/boards.ts";
import { TaskProvider, useTask } from "../../../packages/shift-manager/src/lib/task.tsx";
const CONTROL = process.env.GOAL_CONTROL ?? "";
@@ -377,23 +378,25 @@ function mountViews(on: Host, sessionId: string) {
pageReads.set(smToken, smReads);
const smProject = record();
const smMessages = record();
- let labRead: () => Promise = async () => {};
+ let labRead: () => void = () => {};
function ProjectProbe() {
- const { snapshot, refresh } = useLab();
- labRead = refresh;
+ const { snapshot } = useLab();
+ // FIX-2775: R reads again what the page holds, each screen's own reads included.
+ labRead = useReadPageAgain();
const loaded = snapshot !== undefined && snapshot.refused === undefined && snapshot.unreachable === undefined ? snapshot : undefined;
- const { read } = useProjectRead({ visibility: "shared", id: PROJECT }, loaded !== undefined, loaded?.readAt ?? 0);
- const entries = read !== undefined && "value" in read && read.value !== null ? read.value.entries.map((e) => e.id) : undefined;
+ // FIX-2775: the entries are read on their own, by the project's prefix, from the moment the view draws them.
+ const { value } = useProjectWorkstreams({ visibility: "shared", id: PROJECT });
+ const entries = value === undefined ? undefined : value.entries.map((e) => e.id);
const key = entries === undefined ? null : entries.join(",");
useEffect(() => {
if (entries !== undefined) smProject.push({ at: Date.now(), value: { entries } });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key]);
- // The Messages view reads the log once the snapshot has landed, on its `readAt`.
- return loaded === undefined ? null : createElement(MessagesProbe, { readAt: loaded.readAt });
+ // The Messages view reads the log once the Lab has let Shift Manager in.
+ return loaded === undefined ? null : createElement(MessagesProbe);
}
- function MessagesProbe({ readAt }: { readAt: number }) {
- const { rows } = useMessages(readAt);
+ function MessagesProbe() {
+ const { rows } = useMessages();
const ids = rows == null ? undefined : rows.map((m) => m.id);
const key = ids === undefined ? null : ids.join(",");
useEffect(() => {
@@ -403,7 +406,7 @@ function mountViews(on: Host, sessionId: string) {
return null;
}
const smRoot: Root = createRoot(happy.document.createElement("div") as unknown as Element);
- smRoot.render(createElement(LabProvider, { connection: { userId: "alice", bearerToken: smToken, baseUrl: on.base }, children: createElement(ProjectProbe) }));
+ smRoot.render(createElement(LabProvider, { connection: { userId: "alice", bearerToken: smToken, baseUrl: on.base }, children: createElement(PageReadsProvider, { children: createElement(ProjectProbe) }) }));
const stops = [
() => ccRoot.unmount(),
() => tmRoot.unmount(),
@@ -432,7 +435,7 @@ function mountViews(on: Host, sessionId: string) {
const logReads = () => smReads.filter((r) => r.url.includes("workforce/messages"));
return {
shown: { ccThread, ccPins, tmConversation, smItems, tmTalk, smProject, smMessages },
- labRead: () => labRead(),
+ labRead: async () => labRead(),
reads: {
"claude-code-style thread (running turn)": () => turnReads(cc.reads),
"claude-code-style pins": () => pinsClient.reads,
@@ -618,7 +621,7 @@ await runGoal(async (failures, tell) => {
else if (waitReads === 0) evidence.push(`a: task screen read its board 0 times over ${IDLE_MS / 1000} s waiting, and showed the run link ${linkShown} ms after its write`);
task.close();
- // A Lab read (the snapshot read again, here as the user's Refresh) reads the log and the entries again, as it did before.
+ // A Lab read (Shift Manager's R, which reads again what the page holds) reads the log and the entries again, as it did before.
await quiet(views.all);
const onLabRead = ["Shift Manager message log", "Shift Manager project entries"];
const readsBefore = new Map(onLabRead.map((name) => [name, views.reads[name]!().length]));
diff --git a/goals/routines/sessions-in-the-labs-manage-their-routines/run.mts b/goals/routines/sessions-in-the-labs-manage-their-routines/run.mts
index d24a844c27..d8c586db50 100644
--- a/goals/routines/sessions-in-the-labs-manage-their-routines/run.mts
+++ b/goals/routines/sessions-in-the-labs-manage-their-routines/run.mts
@@ -13,7 +13,7 @@ import { REPO_ROOT, goalTmpDir, loadFixture, runGoal, silentLogger, sleep } from
import { assertPatched, describePatches, modulePatchEnv, type ModulePatch } from "../../lib/module-patch.mts";
import * as contract from "../../../labs/test-support/contract.ts";
import type { ScriptedCall, ScriptedStep } from "../../../labs/test-support/contract.ts";
-import type { Routine } from "../../../packages/shift-manager/src/lib/routines.ts";
+import type { ListedRoutine as Routine } from "@flow-state-dev/workforce/browser";
import { build } from "esbuild";
import { openTeammates } from "../../../labs/teammates/host.mts";
import { openClaudeCodeStyle } from "../../../labs/claude-code-style/host.mts";
diff --git a/goals/shift-manager/a-coding-runs-question-is-answered-in-the-inbox/run.mts b/goals/shift-manager/a-coding-runs-question-is-answered-in-the-inbox/run.mts
index 8b3683430a..62499e004f 100644
--- a/goals/shift-manager/a-coding-runs-question-is-answered-in-the-inbox/run.mts
+++ b/goals/shift-manager/a-coding-runs-question-is-answered-in-the-inbox/run.mts
@@ -60,7 +60,7 @@ import { LAB_ORG_ID, LAB_USER_ID, openLab, type Lab } from "../../../packages/sh
import { commitAll, createBareRemote } from "../../../packages/shift-manager/teams/devteam/scratch-repo.mts";
import { LIST_TASKS_ACTION } from "../../../packages/shift-manager/src/lib/conversation-tasks.ts";
import { connect } from "../../../packages/shift-manager/src/lib/connection.ts";
-import { CONVERSATION_BOARD_COLLECTION } from "../../../packages/shift-manager/src/lib/reads.ts";
+import { CONVERSATION_BOARD_COLLECTION } from "../../../packages/shift-manager/src/lib/boards.ts";
import { inboxViewRef } from "@flow-state-dev/workforce/browser";
stripIntentOverrides();
diff --git a/goals/shift-manager/it-briefs-and-talks-with-the-shift-coordinator/controls/optimistic-reply.ts b/goals/shift-manager/it-briefs-and-talks-with-the-shift-coordinator/controls/optimistic-reply.ts
index 51d33cd13c..539ce1f8d4 100644
--- a/goals/shift-manager/it-briefs-and-talks-with-the-shift-coordinator/controls/optimistic-reply.ts
+++ b/goals/shift-manager/it-briefs-and-talks-with-the-shift-coordinator/controls/optimistic-reply.ts
@@ -19,7 +19,7 @@
import type { SessionSummary } from "@flow-state-dev/client";
import type { OutputItem } from "@flow-state-dev/core/items";
import { useWorkerConversation as useStoredConversation, type WorkerConversation } from "../../../../packages/shift-manager/src/lib/conversation.ts";
-import type { Worker } from "../../../../packages/shift-manager/src/lib/reads.ts";
+import type { Worker } from "../../../../packages/shift-manager/src/lib/workers.ts";
export * from "../../../../packages/shift-manager/src/lib/conversation.ts";
export * from "../../../../packages/shift-manager/src/lib/deliver.ts";
diff --git a/goals/shift-manager/it-groups-workstreams-under-their-projects/controls/gap-tabs.tsx b/goals/shift-manager/it-groups-workstreams-under-their-projects/controls/gap-tabs.tsx
index bac3903549..6c2281c746 100644
--- a/goals/shift-manager/it-groups-workstreams-under-their-projects/controls/gap-tabs.tsx
+++ b/goals/shift-manager/it-groups-workstreams-under-their-projects/controls/gap-tabs.tsx
@@ -6,7 +6,6 @@
* Lab holds. The goal must fail at "a project's four tabs".
*/
import { EmptyState, Tabs } from "../../../../packages/shift-manager/src/components/ui";
-import type { LoadedSnapshot } from "../../../../packages/shift-manager/src/lib/derive";
import { navigate, PROJECT_TABS, type ProjectTab, type Route } from "../../../../packages/shift-manager/src/lib/routes";
import type { Gaps } from "../../../../packages/shift-manager/src/gaps";
@@ -24,7 +23,7 @@ const GAP_COPY: Record = {
brief: { title: "No project brief yet", body: "A project's brief arrives with FIX-1650." },
};
-export function ProjectView({ route }: { snapshot: LoadedSnapshot; route: Extract; gaps: Gaps }) {
+export function ProjectView({ route }: { route: Extract; gaps: Gaps }) {
const { projectId, tab } = route;
const gap = GAP_COPY[tab];
return (
diff --git a/goals/shift-manager/it-groups-workstreams-under-their-projects/controls/unread.ts b/goals/shift-manager/it-groups-workstreams-under-their-projects/controls/unread.ts
index 134773717a..43eed477a8 100644
--- a/goals/shift-manager/it-groups-workstreams-under-their-projects/controls/unread.ts
+++ b/goals/shift-manager/it-groups-workstreams-under-their-projects/controls/unread.ts
@@ -1,17 +1,17 @@
/**
* Control `unread`: Shift Manager that never groups by the Lab's projects.
*
- * Built into the control page in place of `src/lib/derive.ts`. Everything is
- * the real module except `projectsOf`, which ignores the project rows.
- * `ProjectsView` is the project list alone, so the control returns none of
- * them. The goal must fail at "PROJECTS equals the store's rows".
+ * Built into the control page in place of `src/lib/directory.tsx`. Everything
+ * is the real module except `useProjects`, which ignores the project rows: a
+ * projects read that landed holds none of them. The goal must fail at
+ * "PROJECTS equals the store's rows".
*/
-import { projectsOf as groupedAsWritten, type LoadedSnapshot } from "../../../../packages/shift-manager/src/lib/derive.ts";
+import { useProjects as readAsWritten } from "../../../../packages/shift-manager/src/lib/directory.tsx";
-export * from "../../../../packages/shift-manager/src/lib/derive.ts";
+export * from "../../../../packages/shift-manager/src/lib/directory.tsx";
/** No projects: the stored rows are never read into the grouping. */
-export function projectsOf(snapshot: LoadedSnapshot): ReturnType {
- if (!snapshot.projects.ok) return snapshot.projects;
- return { ok: true, value: { projects: [] } };
+export function useProjects(): ReturnType {
+ const read = readAsWritten();
+ return read.section?.ok === true ? { ...read, section: { ok: true, value: [] } } : read;
}
diff --git a/goals/shift-manager/it-groups-workstreams-under-their-projects/goal.md b/goals/shift-manager/it-groups-workstreams-under-their-projects/goal.md
index bbf8236f0a..da346326e4 100644
--- a/goals/shift-manager/it-groups-workstreams-under-their-projects/goal.md
+++ b/goals/shift-manager/it-groups-workstreams-under-their-projects/goal.md
@@ -28,7 +28,7 @@
**Controls:** the page controls rebuild Shift Manager with one source module swapped for one under `controls/`, as `it-opens-a-lab` does; the build fails if the swap never fired. The server controls load the Lab with a Node module hook (`controls/swap-hook.mjs`) that swaps one source module, and the run fails if no import was swapped.
-- `GOAL_CONTROL=unread`: `projectsOf` ignores the stored project rows and returns none. Must fail at **PROJECTS equals the store's rows** (the sidebar draws no project against the stored rows). With no project grouped, every project's page is "No such project", so the four tabs and the entries leg fail with it. `ProjectsView` is only `{ projects }`, so this control no longer draws a flat `:unassigned` workstream list. Verdict rows before 2026-10-11 that say `PROJECTS draws :unassigned[...]` are that older shape.
+- `GOAL_CONTROL=unread`: `useProjects` (`src/lib/directory.tsx`; `projectsOf` in `derive.ts` before FIX-2775) ignores the stored project rows and returns none. Must fail at **PROJECTS equals the store's rows** (the sidebar draws no project against the stored rows). With no project grouped, every project's page is "No such project", so the four tabs and the entries leg fail with it. `ProjectsView` is only `{ projects }`, so this control no longer draws a flat `:unassigned` workstream list. Verdict rows before 2026-10-11 that say `PROJECTS draws :unassigned[...]` are that older shape.
- `GOAL_CONTROL=gap-tabs`: the project level as it was before projects, every tab a FIX-1650 empty state. Must fail at **a project's four tabs**; with no Stream to ask in, the entries leg fails with it.
- `GOAL_CONTROL=no-gate`: `membership-gate.ts` answers yes for everyone. Must fail at **the outsider's open is refused**, and only there.
- `GOAL_CONTROL=no-tool`: the Lab's `host.mts` is swapped for one whose `openLab` leaves the project tools out of the catalog the Shift Coordinator's turn is built with and out of every worker's `tools:`, as before the Shift Coordinator had them. The Lab boots as before. Must fail at **shift-coordinator**.
diff --git a/goals/shift-manager/it-groups-workstreams-under-their-projects/run.mts b/goals/shift-manager/it-groups-workstreams-under-their-projects/run.mts
index 8161af3da0..620bcad2c0 100644
--- a/goals/shift-manager/it-groups-workstreams-under-their-projects/run.mts
+++ b/goals/shift-manager/it-groups-workstreams-under-their-projects/run.mts
@@ -57,7 +57,7 @@
*
* Controls (each must fail; the run fails if a swap never fired):
*
- * unread projectsOf returns no projects (Vite swap of derive.ts).
+ * unread useProjects answers no projects (Vite swap of directory.tsx).
* Must fail at "PROJECTS equals the store's rows".
* gap-tabs the project level as it was before projects (Vite swap of
* Project.tsx). Must fail at "a project's four tabs".
@@ -158,7 +158,7 @@ const diff = (want: Iterable, got: Iterable) => {
/** The page control's module swap: which Shift Manager source, for which module under `controls/`. */
function pageSwapFor(control: string): { target: string; with: string } | undefined {
- if (control === "unread") return { target: join(SHIFT_MANAGER, "src", "lib", "derive.ts"), with: join(HERE, "controls", "unread.ts") };
+ if (control === "unread") return { target: join(SHIFT_MANAGER, "src", "lib", "directory.tsx"), with: join(HERE, "controls", "unread.ts") };
if (control === "gap-tabs") {
return { target: join(SHIFT_MANAGER, "src", "surfaces", "Project.tsx"), with: join(HERE, "controls", "gap-tabs.tsx") };
}
diff --git a/goals/shift-manager/it-opens-a-lab/controls/static-names.ts b/goals/shift-manager/it-opens-a-lab/controls/static-names.ts
index 69d23680dd..f58c2c4f3a 100644
--- a/goals/shift-manager/it-opens-a-lab/controls/static-names.ts
+++ b/goals/shift-manager/it-opens-a-lab/controls/static-names.ts
@@ -2,37 +2,36 @@
* Control `static-names`: Shift Manager with its seat list written in rather than
* read from the Lab.
*
- * Built into the control page in place of `src/lib/reads.ts`. Everything is
- * the real module except `createLabReader`, whose snapshot has its seats
- * replaced by one Lab's seat list fixed at build time (`__STATIC_SEATS__`,
- * the DevTeam tree's seats). Opened over DevTeam it looks right; opened over
- * any other Lab, TEAMS lists seats that Lab doesn't have. The goal must fail
- * at "TEAMS equals the store's seats", naming the missing seats.
+ * Built into the control page in place of `src/lib/directory-reads.ts`.
+ * Everything is the real module except `useDirectoryReads`, whose inventory
+ * rows are replaced by one Lab's seat list fixed at build time
+ * (`__STATIC_SEATS__`, the DevTeam tree's seats). Opened over DevTeam it looks
+ * right; opened over any other Lab, TEAMS lists seats that Lab doesn't have.
+ * The goal must fail at "TEAMS equals the store's seats", naming the missing
+ * seats.
*
* Only the names are written in. A written-in seat the store also holds keeps
* that stored row's `door`, the action that takes a person's message, so the
* control removes the tree reading and nothing else: a composer turn to a
* seat that exists still goes through.
*/
-import { createLabReader as readerAsWritten, toWorker, type LabReader, type Worker } from "../../../../packages/shift-manager/src/lib/reads.ts";
+import { useMemo } from "react";
+import { useDirectoryReads as readsAsWritten, type DirectoryReads } from "../../../../packages/shift-manager/src/lib/directory-reads.ts";
+import { toWorker, type Worker } from "../../../../packages/shift-manager/src/lib/workers.ts";
-export * from "../../../../packages/shift-manager/src/lib/reads.ts";
+export * from "../../../../packages/shift-manager/src/lib/directory-reads.ts";
declare const __STATIC_SEATS__: Array<{ id: string; kind: string }>;
-/** The real reader, with the seat list swapped for the one written in. */
-export function createLabReader(clients: Parameters[0]): LabReader {
- const reader = readerAsWritten(clients);
- return {
- ...reader,
- read: async () => {
- const snapshot = await reader.read();
- if (snapshot.refused !== undefined || snapshot.unreachable !== undefined || !snapshot.inventory.ok) return snapshot;
- const stored = new Map(snapshot.inventory.value.workers.map((seat) => [seat.id, seat]));
- const seats = __STATIC_SEATS__
- .map((row) => toWorker({ ...row, door: stored.get(row.id)?.door ?? null }))
- .filter((s): s is Worker => s !== undefined);
- return { ...snapshot, inventory: { ok: true, value: { ...snapshot.inventory.value, workers: seats } } };
- },
- };
+/** The real reads, with the inventory's seats swapped for the ones written in. */
+export function useDirectoryReads(): DirectoryReads {
+ const reads = readsAsWritten();
+ const stored = reads.inventory.values;
+ const rows = useMemo(() => {
+ if (stored === undefined) return undefined;
+ const doors = new Map(stored.map((seat) => [seat.id, seat]));
+ return __STATIC_SEATS__.map((row) => toWorker({ ...row, door: doors.get(row.id)?.door ?? null })).filter((s): s is Worker => s !== undefined);
+ }, [stored]);
+ const inventory = useMemo(() => ({ ...reads.inventory, rows }), [reads.inventory, rows]);
+ return { ...reads, inventory };
}
diff --git a/goals/shift-manager/it-opens-a-lab/goal.md b/goals/shift-manager/it-opens-a-lab/goal.md
index 332c7dca3a..faec69c8b8 100644
--- a/goals/shift-manager/it-opens-a-lab/goal.md
+++ b/goals/shift-manager/it-opens-a-lab/goal.md
@@ -104,3 +104,5 @@ The empty Inbox's running count has no control of its own. No Lab reaches an emp
| 2026-11-13 | claude/fix-2627-impl-e-b2 (the workforce kit) | n/a | FAIL (expected) | `queued-shown`: **Tasks equals the store's open rows** (*"the Queued toggle says 0, the store holds 1 queued row(s)"*). |
| 2026-11-13 | claude/fix-2627-impl-e-b2 (the workforce kit) | n/a | FAIL (expected) | `static-names`: beside the line above, **TEAMS equals the store's seats** on multi-worker-collab (*"missing [eng.builder, eng.planner, eng.queue], extra [error-reporter, …]"*). |
| 2026-11-13 | claude/fix-2627-impl-e-b2 (the workforce kit) | n/a | FAIL (not shown failing on its leg) | `unanswerable-asks`: only the clean run's line above. **an answer lands in the store** never failed. That leg passes when no ask is pending, and a red run doesn't print its evidence, so this run can't say whether one was. |
+| 2026-11-20 | fix-2775-screen-migration on a449098bf0 (FIX-2775 PR 3), twice | n/a | FAIL | *"[devteam] Tasks equals the store's open rows: the task frame titles task_… \"task_…\", stored \"Add a release notes page that lists the last three tags.\""*, and the same on multi-worker-collab. The check read the title as the frame drew, before its row landed: the frame titles a task by its id until the row is read |
+| 2026-11-20 | same, the title graded once the row lands (`reachTaskFrame` waits for a title other than the id, at most 20 s) | n/a | PASS | The row landed 14 ms and 22 ms after the frame drew. *"Shift Manager built with Vite and served by its command over both goal Labs; every level walked in Chromium and graded against each tree on disk and each store read through the Lab's routes."* |
diff --git a/goals/shift-manager/it-opens-a-lab/run.mts b/goals/shift-manager/it-opens-a-lab/run.mts
index 1e86edb5c7..60f6e972fa 100644
--- a/goals/shift-manager/it-opens-a-lab/run.mts
+++ b/goals/shift-manager/it-opens-a-lab/run.mts
@@ -135,7 +135,7 @@ const diff = (want: Iterable, got: Iterable) => {
function swapFor(control: string): { targets: string[]; with: string } | undefined {
const lib = (file: string) => join(SHIFT_MANAGER, "src", "lib", file);
if (control === "static-names") {
- return { targets: [lib("reads.ts")], with: join(HERE, "controls", "static-names.ts") };
+ return { targets: [lib("directory-reads.ts")], with: join(HERE, "controls", "static-names.ts") };
}
if (control === "optimistic-post") {
return { targets: [lib("deliver.ts")], with: join(HERE, "controls", "optimistic-post.ts") };
@@ -437,6 +437,9 @@ async function checkLab(name: LabName, pages: string, failures: string[], eviden
/** The task frame a click just opened: titled as stored, with a panel slot, and every tab drawing. */
const reachTaskFrame = async (row: Store["rows"][string][number], titleLeg: string) => {
await page.getByTestId("task-frame").waitFor();
+ // The frame draws as the click lands and titles the task by its id until its row is read (one
+ // session read and the board's view): grade the title once the row has landed, or after 20 s.
+ await page.waitForFunction((id) => document.querySelector("[data-testid=task-title]")?.textContent !== id, row.id, { timeout: 20_000 }).catch(() => undefined);
const title = await page.getByTestId("task-title").textContent();
if (title !== row.title) fail(titleLeg, `the task frame titles ${row.id} "${title}", stored "${row.title}"`);
if (!(await visible(page, "task-panel-slot"))) fail("reach", `the task frame for ${row.id} has no panel slot`);
diff --git a/goals/shift-manager/it-shows-who-is-on-shift/controls/count-queued.ts b/goals/shift-manager/it-shows-who-is-on-shift/controls/count-queued.ts
index e9024245b1..5efac7ebd2 100644
--- a/goals/shift-manager/it-shows-who-is-on-shift/controls/count-queued.ts
+++ b/goals/shift-manager/it-shows-who-is-on-shift/controls/count-queued.ts
@@ -1,37 +1,24 @@
/**
- * Control `count-queued`: a queued row counts as a slot in use.
+ * Control `count-queued`: a queued task counts as a slot in use.
*
- * Built into the control page in place of `src/lib/derive.ts`. Everything is
+ * Built into the control page in place of `src/lib/shift.ts`. Everything is
* the real module except `workerStates`, whose `held` also takes each worker's
- * queued rows (`pending`, `held`). Statuses are left as the real rule gives
- * them. The goal must fail at "slots equal held rows" on the worker with a
- * queued row.
+ * queued tasks (`pending`, `held`) off the Inbox view's tasks. Statuses are
+ * left as the real rule gives them. The goal must fail at "slots equal held
+ * rows" on the worker with a queued task.
*/
-import {
- allTasks,
- rosterOf,
- workerFor,
- workerStates as asWritten,
- type LoadedSnapshot,
- type WorkerStates,
-} from "../../../../packages/shift-manager/src/lib/derive.ts";
+import { workerFor, workerStates as asWritten, type WorkerStates } from "../../../../packages/shift-manager/src/lib/shift.ts";
-export * from "../../../../packages/shift-manager/src/lib/derive.ts";
+export * from "../../../../packages/shift-manager/src/lib/shift.ts";
-const computed = new WeakMap();
-
-export function workerStates(snapshot: LoadedSnapshot): WorkerStates {
- const cached = computed.get(snapshot);
- if (cached !== undefined) return cached;
- const real = asWritten(snapshot);
- const roster = rosterOf(snapshot);
+export function workerStates(...args: Parameters): WorkerStates {
+ const [workers, view] = args;
+ const real = asWritten(...args);
const seats = new Map([...real.workers].map(([id, state]) => [id, { ...state, held: [...state.held] }]));
- for (const row of allTasks(snapshot)) {
- if (row.status !== "pending" && row.status !== "held") continue;
- const owner = workerFor(roster, row);
- if (owner !== undefined) seats.get(owner.id)?.held.push(row);
+ for (const task of view?.tasks ?? []) {
+ if (task.status !== "pending" && task.status !== "held") continue;
+ const owner = workerFor(workers, task);
+ if (owner !== undefined) seats.get(owner.id)?.held.push(task);
}
- const result = { ...real, workers: seats };
- computed.set(snapshot, result);
- return result;
+ return { ...real, workers: seats };
}
diff --git a/goals/shift-manager/it-shows-who-is-on-shift/controls/ignore-asks.ts b/goals/shift-manager/it-shows-who-is-on-shift/controls/ignore-asks.ts
index ea2fe0e042..0fbe4ae9aa 100644
--- a/goals/shift-manager/it-shows-who-is-on-shift/controls/ignore-asks.ts
+++ b/goals/shift-manager/it-shows-who-is-on-shift/controls/ignore-asks.ts
@@ -1,22 +1,18 @@
/**
- * Control `ignore-asks`: a worker's status read from its board rows only.
+ * Control `ignore-asks`: a worker's status read from its held tasks only.
*
- * Built into the control page in place of `src/lib/derive.ts`. Everything is
+ * Built into the control page in place of `src/lib/shift.ts`. Everything is
* the real module except `workerStates`, whose statuses ignore pending asks: a
* worker waiting on you only through an ask reads off shift. Its asks are still
* listed. The goal must fail at "status equals the store's" on the asking
* worker.
*/
-import { workerStates as asWritten, type LoadedSnapshot, type WorkerStates } from "../../../../packages/shift-manager/src/lib/derive.ts";
+import { workerStates as asWritten, type WorkerStates } from "../../../../packages/shift-manager/src/lib/shift.ts";
-export * from "../../../../packages/shift-manager/src/lib/derive.ts";
+export * from "../../../../packages/shift-manager/src/lib/shift.ts";
-const computed = new WeakMap();
-
-export function workerStates(snapshot: LoadedSnapshot): WorkerStates {
- const cached = computed.get(snapshot);
- if (cached !== undefined) return cached;
- const real = asWritten(snapshot);
+export function workerStates(...args: Parameters): WorkerStates {
+ const real = asWritten(...args);
const seats = new Map(
[...real.workers].map(([id, state]) => [
id,
@@ -26,7 +22,5 @@ export function workerStates(snapshot: LoadedSnapshot): WorkerStates {
},
]),
);
- const result = { ...real, workers: seats };
- computed.set(snapshot, result);
- return result;
+ return { ...real, workers: seats };
}
diff --git a/goals/shift-manager/it-shows-who-is-on-shift/controls/status-from-snapshot.ts b/goals/shift-manager/it-shows-who-is-on-shift/controls/status-from-snapshot.ts
new file mode 100644
index 0000000000..65acafee67
--- /dev/null
+++ b/goals/shift-manager/it-shows-who-is-on-shift/controls/status-from-snapshot.ts
@@ -0,0 +1,28 @@
+/**
+ * Control `status-from-snapshot`: a worker's asks read from the snapshot's
+ * walked asks, as before the status moved onto the Inbox view.
+ *
+ * Built into the control page in place of `src/lib/shift.ts`. Everything is
+ * the real module except `workerStates`, whose status counts the page's
+ * snapshot's asks, read through its provider, while the Inbox lists the
+ * view's (and the waits-on entries stay the view's). The two are separate reads, so a new ask is listed in one update and
+ * the worker reads on shift in another. The goal must fail at "one answer".
+ */
+import { useLab } from "../../../../packages/shift-manager/src/lib/lab-data.tsx";
+import { workerStates as asWritten, type WorkerStates } from "../../../../packages/shift-manager/src/lib/shift.ts";
+
+export * from "../../../../packages/shift-manager/src/lib/shift.ts";
+
+export function workerStates(...args: Parameters): WorkerStates {
+ const real = asWritten(...args);
+ // Every caller computes states while it renders, so the provider is in reach (a production build).
+ const { snapshot } = useLab();
+ const asks = snapshot !== undefined && "asks" in snapshot && snapshot.asks.ok ? snapshot.asks.value : [];
+ const seats = new Map(
+ [...real.workers].map(([id, state]) => {
+ const mine = asks.filter((ask) => ask.workerId === id);
+ return [id, { ...state, status:state.held.length > 0 || mine.length > 0 ? ("on shift" as const) : ("off shift" as const) }];
+ }),
+ );
+ return { ...real, workers: seats };
+}
diff --git a/goals/shift-manager/it-shows-who-is-on-shift/goal.md b/goals/shift-manager/it-shows-who-is-on-shift/goal.md
index 51dbc24cd9..a7bb15139b 100644
--- a/goals/shift-manager/it-shows-who-is-on-shift/goal.md
+++ b/goals/shift-manager/it-shows-who-is-on-shift/goal.md
@@ -1,6 +1,6 @@
# shift-manager › it shows who is on shift
-**Issue:** FIX-1723
+**Issue:** FIX-1723; the **one answer** leg by FIX-2775 (epic FIX-2683), whose spec's goal is `specs/issues/FIX-2775/SPEC.md` → "The goal, and how we'll know it's met".
**Outcome:** A person running a Lab in Shift Manager opens Roster and sees every worker the Lab has, each on shift or off shift as the Lab's own records say, with the tasks it holds and what it waits on, for all teams or one. The sidebar's Roster entry, its footer and its TEAMS rows agree with the page.
@@ -18,6 +18,7 @@
- **sidebar**: the Roster entry's on-shift count and the footer's equal the store's, and the sidebar never says on call.
- **TEAMS**: one row per group, Staff first, each with a square per seat carrying the store's status, and its on-shift count over its seats.
- **filter**: each TEAMS row opens Roster for exactly that team, names it in the title, and is marked current.
+- **one answer** (spread 1, after the legs above): a worker on the seat flow that is off shift stops for an approval, opened by this script through the Lab's routes; then the person approves it from Inbox. In every state the page draws, the Inbox lists the ask exactly when the worker's TEAMS square reads on shift, so the two move in one update, both when it is asked and when it is answered. Each state is read by a `MutationObserver` in the page, whose callback runs once per committed change, so no state is skipped and none is read half-drawn.
**Anti-game:**
- No assertion reads Shift Manager's modules. The oracle is the store, read by this script through the Lab's HTTP routes (the inventory, the person's conversation ledger, each seat session's suspensions). A row's board is the conversation whose partition keeps it, `.tasks`, by the script's own match against the listed sessions, so a HOLDING chip is graded against the real board ref.
@@ -28,9 +29,10 @@
**Run:** `PLAYWRIGHT_BROWSERS_PATH=/opt/pw-browsers pnpm tsx goals/shift-manager/it-shows-who-is-on-shift/run.mts`
-**Controls:** each rebuilds Shift Manager with `src/lib/derive.ts` swapped for a module under `controls/`.
+**Controls:** each rebuilds Shift Manager with `src/lib/shift.ts` swapped for a module under `controls/` (`src/lib/derive.ts` before FIX-2775, when status read the snapshot).
- `GOAL_CONTROL=ignore-asks`: status reads board rows only. Must fail at **status** on the worker whose only wait is an ask.
- `GOAL_CONTROL=count-queued`: queued rows count as slots. Must fail at **slots** on the worker holding a queued row.
+- `GOAL_CONTROL=status-from-snapshot`: status counts the snapshot's walked asks, read through the page's provider, while the Inbox lists the view's. Must fail at **one answer**.
## Verdict log
| Date | Commit | Model | Verdict | Notes |
@@ -53,3 +55,7 @@
| 2026-11-13 | claude/fix-2627-impl-e-b2 (the workforce kit) | n/a | PASS | The shift-lab installs the workforce kit with `lead`, `seat` and `coordinator` in its slot. *"Shift Manager built with Vite and served by its command over the shift-lab under 2 spreads; Roster, each team and the sidebar graded in Chromium against the store read through the Lab's routes."* |
| 2026-11-13 | claude/fix-2627-impl-e-b2 (the workforce kit) | n/a | FAIL (control broken, not from this change) | `count-queued` never reaches a leg: the control's build fails, *"controls/count-queued.ts (10:9): \"readStatus\" is not exported by \"packages/shift-manager/src/lib/columns.ts\""*. Neither file is touched here. |
| 2026-11-13 | claude/fix-2627-impl-e-b2 (the workforce kit) | n/a | FAIL (expected) | `ignore-asks`: **status**, *"[spread 1] status: All: ops.asker is drawn under \"off shift\" (row says \"off shift\"), the store says \"on shift\""*, with the sidebar and TEAMS counts that follow. |
+| 2026-11-20 | fix-2775-screen-migration on b8d86d908c (FIX-2775 PR 3) | n/a | PASS | Status and counts read the Inbox view's `workerId` (`src/lib/shift.ts`). Both spreads as before, 9 workers in [_general, eng, ops]. *"one answer: eng.spare's approval listed and its square on shift in one update, over 3 drawn states; after Approve both cleared together, over 6"* |
+| 2026-11-20 | same | n/a | FAIL (expected) | `status-from-snapshot`: *"[spread 1] one answer: eng.spare's approval: 1 of 3 drawn states disagree, the first {"count":"3","status":"off shift","listed":true}"* and *"after Approve: 1 of 8 drawn states disagree, the first {"count":"2","status":"on shift","listed":false}"*, with the sidebar's on-shift count that follows |
+| 2026-11-20 | same | n/a | FAIL (expected) | `ignore-asks`: **status** on eng.spare (spread 2) and ops.asker (spread 1), drawn off shift where the store says on shift, with the summary and TEAMS counts that follow |
+| 2026-11-20 | same | n/a | FAIL (expected) | `count-queued` (its build fixed by the retarget onto `shift.ts`): **slots** and **holding** on eng.coder and ops.asker (spread 2), *"shows \"1 in use\" … it holds 0 row(s) (and 1 queued)"* |
diff --git a/goals/shift-manager/it-shows-who-is-on-shift/run.mts b/goals/shift-manager/it-shows-who-is-on-shift/run.mts
index c35dee698d..9f2fdb446d 100644
--- a/goals/shift-manager/it-shows-who-is-on-shift/run.mts
+++ b/goals/shift-manager/it-shows-who-is-on-shift/run.mts
@@ -26,8 +26,11 @@
* sidebar the Roster entry's and the footer's counts equal the store's
* TEAMS one row per team, General first, a square per worker with its status
* filter a TEAMS row opens Roster for exactly that team
+ * one answer (spread 1) a worker off shift stops for an approval, then it is
+ * approved from Inbox: in every state the page draws, the Inbox
+ * lists the ask exactly when the worker's TEAMS square is on shift
*
- * Controls rebuild Shift Manager with `src/lib/derive.ts` swapped for a module
+ * Controls rebuild Shift Manager with `src/lib/shift.ts` swapped for a module
* under `controls/` (a Vite `resolveId` plugin; the build fails if the swap
* never fired):
*
@@ -35,6 +38,8 @@
* worker whose only wait is an ask.
* count-queued queued rows count as slots. Must fail at "slots" on the
* worker with a queued row.
+ * status-from-snapshot status counts the snapshot's walked asks, while the
+ * Inbox lists the view's. Must fail at "one answer".
*
* Run: PLAYWRIGHT_BROWSERS_PATH= pnpm tsx goals/shift-manager/it-shows-who-is-on-shift/run.mts
* Control: GOAL_CONTROL=ignore-asks pnpm tsx goals/shift-manager/it-shows-who-is-on-shift/run.mts
@@ -49,9 +54,11 @@ import type { Browser, Page } from "playwright";
import { REPO_ROOT, goalTmpDir, intentFreeEnv, loadFixture, runGoal } from "../../lib/index.mts";
import { SHIFT_MANAGER_COMMAND, pendingSeatAsks, servedAddresses } from "../../lib/shift-manager.mts";
import { launchChromium } from "../../lib/playwright.mts";
+import { createClient } from "@flow-state-dev/client";
+import { WORKER_ID_STATE_KEY } from "@flow-state-dev/workforce/browser";
const CONTROL = process.env.GOAL_CONTROL ?? "";
-const CONTROLS = ["ignore-asks", "count-queued"] as const;
+const CONTROLS = ["ignore-asks", "count-queued", "status-from-snapshot"] as const;
if (CONTROL === "list") {
console.log(`controls: ${CONTROLS.join(", ")}`);
process.exit(0);
@@ -93,7 +100,7 @@ async function buildShiftManager(control: string): Promise {
const outDir = join(SCRATCH, `pages-${control === "" ? "as-written" : control}`);
const viteEntry = createRequire(join(SHIFT_MANAGER, "package.json")).resolve("vite");
const vite = (await import(pathToFileURL(viteEntry).href)) as { build(config: Record): Promise };
- const swap = control === "" ? undefined : { target: join(SHIFT_MANAGER, "src", "lib", "derive.ts"), with: join(HERE, "controls", `${control}.ts`) };
+ const swap = control === "" ? undefined : { target: join(SHIFT_MANAGER, "src", "lib", "shift.ts"), with: join(HERE, "controls", `${control}.ts`) };
let swapped = 0;
await vite.build({
root: SHIFT_MANAGER,
@@ -197,6 +204,8 @@ type LabApi = ReturnType;
/** One worker, as the store says. */
type Worker = {
id: string;
+ /** The flow its inventory entry names. */
+ kind: string | null;
team: string;
status: Status;
/** `/` of each row it holds that is running, held on a question included. */
@@ -274,6 +283,7 @@ async function readStore(api: LabApi, userId: string): Promise a.seat === id);
return {
id,
+ kind: workerRows.find((s) => s.id === id)?.kind ?? null,
team: id.includes(".") ? id.slice(0, id.indexOf(".")) : GENERAL,
status: running.length > 0 || asked.length > 0 || myAsks.length > 0 ? "on shift" : "off shift",
held: [...running, ...asked].map((r) => r.key),
@@ -345,6 +355,75 @@ async function gradeRoster(page: Page, store: Store, team: string | null, fail:
}
}
+// ---- one answer ----------------------------------------------------------------
+
+/** One state of the page, read after each change React committed to it. */
+type Frame = { count: string | null; status: string | null; listed: boolean };
+
+/**
+ * A worker off shift stops for an approval, then the person approves it from
+ * Inbox. In every state the page draws, the Inbox lists the ask exactly when
+ * the worker's TEAMS square reads on shift: they move in one update, both ways.
+ * The page's states are read by a MutationObserver, whose callback runs once
+ * per committed change, so no state is skipped and none is read half-drawn.
+ */
+async function oneAnswer(page: Page, origin: string, userId: string, store: Store, fail: (leg: string, why: string) => void, evidence: string[]) {
+ const asker = store.workers.find((w) => w.status === "off shift" && w.kind === "seat");
+ if (asker === undefined) return fail("one answer", "setup: no worker on the seat flow is off shift to ask");
+ await open(page, origin, "/inbox");
+ const client = createClient({ userId, baseUrl: origin });
+ const sessionId = (await client.flow("seat").createSession({ state: { [WORKER_ID_STATE_KEY]: asker.id } })).id;
+ // A string, not a function: tsx names this file's functions with a helper the page doesn't have.
+ await page.evaluate(`(() => {
+ const workerId = ${JSON.stringify(asker.id)};
+ const sessionId = ${JSON.stringify(sessionId)};
+ window.__frames = [];
+ function read() {
+ return {
+ count: document.querySelector("[data-testid=nav-inbox-count]")?.textContent ?? null,
+ status: document.querySelector('[data-testid=team] [data-testid=worker][data-worker-id="' + workerId + '"]')?.getAttribute("data-status") ?? null,
+ listed: [...document.querySelectorAll("[data-testid=inbox-item]")].some((e) => e.getAttribute("data-session-id") === sessionId),
+ };
+ }
+ window.__frames.push(read());
+ new MutationObserver(() => window.__frames.push(read())).observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true });
+ })()`);
+ const frames = async () => (await page.evaluate(() => (window as unknown as { __frames: Frame[] }).__frames)) as Frame[];
+ const until = async (done: (all: Frame[]) => boolean) => {
+ for (let waited = 0; waited < 20_000; waited += 100) {
+ if (done(await frames())) return true;
+ await sleep(100);
+ }
+ return false;
+ };
+ /** Every drawn state where the list and the square disagree. */
+ const split = (all: Frame[]) => all.filter((f) => f.listed !== (f.status === "on shift"));
+
+ await client.flow("seat").send("ask", { what: `${asker.id} wants to go ahead` }, { sessionId });
+ if (!(await until((all) => all.some((f) => f.listed)))) return fail("one answer", `the Inbox never listed ${asker.id}'s approval`);
+ const asked = await frames();
+ const askedSplit = split(asked);
+ if (askedSplit.length > 0) {
+ fail("one answer", `${asker.id}'s approval: ${askedSplit.length} of ${asked.length} drawn states disagree, the first ${JSON.stringify(askedSplit[0])}`);
+ }
+
+ const item = page.locator(`[data-testid=inbox-item][data-session-id="${sessionId}"]`);
+ await item.click();
+ await page.getByTestId("inbox-detail").getByRole("button", { name: "Approve" }).first().click();
+ const from = asked.length;
+ if (!(await until((all) => all.slice(from).some((f) => !f.listed && f.status === "off shift")))) {
+ return fail("one answer", `after Approve, ${asker.id}'s approval never left the Inbox with its square off shift: last state ${JSON.stringify((await frames()).at(-1))}`);
+ }
+ const answered = (await frames()).slice(from);
+ const answeredSplit = split(answered);
+ if (answeredSplit.length > 0) {
+ fail("one answer", `after Approve: ${answeredSplit.length} of ${answered.length} drawn states disagree, the first ${JSON.stringify(answeredSplit[0])}`);
+ }
+ if (askedSplit.length === 0 && answeredSplit.length === 0) {
+ evidence.push(`one answer: ${asker.id}'s approval listed and its square on shift in one update, over ${asked.length} drawn states; after Approve both cleared together, over ${answered.length}`);
+ }
+}
+
// ---- one spread --------------------------------------------------------------
async function checkSpread(n: number, spread: Record, pages: string, failures: string[], evidence: string[]) {
@@ -428,6 +507,7 @@ async function checkSpread(n: number, spread: Record, page
.map((w) => `${w.id} ${w.status} ${w.held.length} held ${w.waits.length} waits${w.queued > 0 ? ` ${w.queued} queued` : ""}`)
.join("; ")}`,
);
+ if (n === 1) await oneAnswer(page, served.origin, userId, store, fail, evidence);
} finally {
await browser?.close();
served.child.kill("SIGTERM");
diff --git a/goals/shift-manager/its-summary-changes-on-its-own/run.mts b/goals/shift-manager/its-summary-changes-on-its-own/run.mts
index daa5e15583..fb5b95aa86 100644
--- a/goals/shift-manager/its-summary-changes-on-its-own/run.mts
+++ b/goals/shift-manager/its-summary-changes-on-its-own/run.mts
@@ -59,7 +59,7 @@ import { crossingBus } from "../../lib/crossing-bus.mts";
import { REPO_ROOT, RUN_STAMP, assertPatched, describePatches, goalTmpDir, installWorkers, modulePatchEnv, runGoal, silentLogger, sleep, workforceTree, type ModulePatch } from "../../lib/index.mts";
import { LabProvider, useLab } from "../../../packages/shift-manager/src/lib/lab-data.tsx";
import { useInbox } from "../../../packages/shift-manager/src/lib/inbox.ts";
-import { readHarnessUsageView } from "../../../packages/shift-manager/src/lib/usage.ts";
+import { recheckHarnessUsage } from "@flow-state-dev/harness-manager/browser";
import { Inbox } from "../../../packages/shift-manager/src/surfaces/Inbox.tsx";
import { GAPS } from "../../../packages/shift-manager/src/gaps.ts";
@@ -321,7 +321,8 @@ function mountProvider(on: Host) {
if (inbox.section === undefined) return;
shown.push({ at: Date.now(), needsYou: inbox.section.ok ? inbox.section.value.items.length : undefined, failure: inbox.section.ok ? undefined : inbox.section.failure.message });
void client.view(routinesView, {}).catch(() => {});
- void readHarnessUsageView(client).catch(() => {});
+ // Usage's Re-check, as the screen sends it when it opens (FIX-2775: the rows are then the view's).
+ void recheckHarnessUsage(client).catch(() => {});
}, [inbox.section, client]);
return loaded === undefined ? null : createElement(Inbox, { snapshot: loaded, itemId: null, gaps: GAPS } as never);
}
diff --git a/goals/standing-rules/the-rules-page-edits-what-the-worker-follows/run.mts b/goals/standing-rules/the-rules-page-edits-what-the-worker-follows/run.mts
index 6bc48cc67c..0932cc2d75 100644
--- a/goals/standing-rules/the-rules-page-edits-what-the-worker-follows/run.mts
+++ b/goals/standing-rules/the-rules-page-edits-what-the-worker-follows/run.mts
@@ -4,8 +4,8 @@ import { join } from "node:path";
import type { Page } from "playwright";
import { createClient } from "@flow-state-dev/client";
import { WORKER_ID_STATE_KEY, createWorkforceClient } from "@flow-state-dev/workforce/browser";
-import { shiftCoordinatorOf } from "../../../packages/shift-manager/src/lib/derive.ts";
-import type { Worker } from "../../../packages/shift-manager/src/lib/reads.ts";
+import { shiftCoordinatorOf } from "../../../packages/shift-manager/src/lib/shift.ts";
+import type { Worker } from "../../../packages/shift-manager/src/lib/workers.ts";
import { REPO_ROOT, goalTmpDir, runGoal } from "../../lib/index.mts";
import { launchChromium } from "../../lib/playwright.mts";
import {
diff --git a/packages/react/src/hooks/useResource.ts b/packages/react/src/hooks/useResource.ts
index c0e202fbf3..5e6f0a0ca5 100644
--- a/packages/react/src/hooks/useResource.ts
+++ b/packages/react/src/hooks/useResource.ts
@@ -273,11 +273,13 @@ export function useResource(
// A collection's entries as last read, for this handle read this way, while no other
// read is out: a notice that names entries re-reads just those over them (FIX-2625).
const how = useMemo(() => ({ all, topicPrefix }), [all, topicPrefix]);
- const held = useRef<{ handle: unknown; how: CollectionRead; entries: ScopeEntry[] } | undefined>(undefined);
+ // Held entries are a baseline only for the same read mode, named by value so the match never rests on `how`'s identity.
+ const mode = all ? `all:${topicPrefix ?? ""}` : "page";
+ const held = useRef<{ handle: unknown; mode: string; entries: ScopeEntry[] } | undefined>(undefined);
const reading = useRef(0);
const { data, error, cause, refresh } = useFencedRead[] | null>(
// `client` too: by `sessionId` there is no handle, and a value one client read is never shown under another.
- [handle, scope, key, sessionId, client, how],
+ [handle, scope, key, sessionId, client, mode],
null,
`Failed to read "${key}"`,
async (stillCurrent, notice) => {
@@ -287,7 +289,7 @@ export function useResource(
}
if (handle === undefined) return null;
if (!("list" in handle)) return (await handle.read()).value;
- const last = held.current?.handle === handle && held.current.how === how && reading.current === 0 ? held.current.entries : undefined;
+ const last = held.current?.handle === handle && held.current.mode === mode && reading.current === 0 ? held.current.entries : undefined;
reading.current += 1;
try {
const entries =
@@ -296,7 +298,7 @@ export function useResource(
? await handle.listAll({ limit: ENTRY_PAGE, ...(topicPrefix === undefined ? {} : { topicPrefix }) })
: (await handle.list({ limit: ENTRY_PAGE })).items);
// Only the read in play is a baseline: one a newer read superseded is older than what's shown.
- if (stillCurrent()) held.current = { handle, how, entries };
+ if (stillCurrent()) held.current = { handle, mode, entries };
return entries;
} catch (error) {
if (stillCurrent()) held.current = undefined;
diff --git a/packages/react/src/internal.ts b/packages/react/src/internal.ts
index e8cd9f9327..9288a5ecf3 100644
--- a/packages/react/src/internal.ts
+++ b/packages/react/src/internal.ts
@@ -1,6 +1,7 @@
/**
* `@flow-state-dev/react/internal`: seams the framework's own packages share,
- * such as the DevTool's read fence and Shift Manager's suspension reduction.
+ * such as the DevTool's read fence, Shift Manager's suspension reduction, and
+ * the words a failed read is shown in.
* Not a public API, and no app should import it: an app reads through the
* documented hooks.
*
@@ -11,3 +12,5 @@ export { deriveSuspensions } from "./hooks/useSuspensions";
// FIX-2627: what workforce's components (`@flow-state-dev/workforce/react`) read through.
export { useClient } from "./internal/useClient";
export { useFencedRead, type ReadDriver } from "./internal/useFencedRead";
+// FIX-2775: the one rule for a failed read's words, so a write's refusal reads as `useView`'s and `useResource`'s `failure` does.
+export { failureOf, type ViewReadFailure } from "./internal/readFailure";
diff --git a/packages/react/test/internal-subpath.test.ts b/packages/react/test/internal-subpath.test.ts
index 0bf9ab6393..9417a4a1d5 100644
--- a/packages/react/test/internal-subpath.test.ts
+++ b/packages/react/test/internal-subpath.test.ts
@@ -19,8 +19,8 @@ const manifest = JSON.parse(readFileSync(fileURLToPath(new URL("../package.json"
};
describe("@flow-state-dev/react/internal", () => {
- it("carries the read fence, the suspension reduction, and the client and fenced read workforce's components use", () => {
- expect(Object.keys(internal).sort()).toEqual(["deriveSuspensions", "useClient", "useFencedRead", "useReadFence"]);
+ it("carries the read fence, the suspension reduction, the client and fenced read workforce's components use, and the words a failed read is shown in", () => {
+ expect(Object.keys(internal).sort()).toEqual(["deriveSuspensions", "failureOf", "useClient", "useFencedRead", "useReadFence"]);
});
it("is gone from the root, with no alias", () => {
diff --git a/packages/react/test/useResource-all.test.ts b/packages/react/test/useResource-all.test.ts
index 89bc436e06..3ab9ce601a 100644
--- a/packages/react/test/useResource-all.test.ts
+++ b/packages/react/test/useResource-all.test.ts
@@ -198,6 +198,42 @@ describe("useResource(def, { all: true, topicPrefix })", () => {
expect(entryReads).toEqual(["projects/p1/c"]);
expect(lists).toHaveLength(listed);
});
+
+ // The live read's path filter is the client's (`liveRead`'s `paths`), not the subscription's, so
+ // the narrowed root is pinned by which notice with no ids reads the list again.
+ it("narrows its live paths to the prefix's whole segments: its own project's notice re-reads, the next project's doesn't", async () => {
+ const stored = new Map([
+ ["projects/p1/a", entry("p1a")],
+ ["projects/p2/a", entry("p2a")]
+ ]);
+ const { client, lists, hear } = lab(stored);
+ const { result } = renderHook(() => useResource(projects, { all: true, topicPrefix: "projects/p1/", client }));
+ await waitFor(() => expect(keys(result.current.value)).toEqual(["projects/p1/a"]));
+ const listed = lists.length;
+
+ await hear({ topic: { scope: "org", resource: "projects/p2" }, kind: "resource" });
+ expect(lists).toHaveLength(listed);
+ stored.set("projects/p1/b", entry("p1b"));
+ await hear({ topic: { scope: "org", resource: "projects/p1" }, kind: "resource" });
+ await waitFor(() => expect(keys(result.current.value)).toEqual(["projects/p1/a", "projects/p1/b"]));
+ expect(lists).toHaveLength(listed + 1);
+ });
+
+ it("narrows a prefix that ends mid-segment to the segment above it, so a sibling project's notice is still heard", async () => {
+ // `projects/p1` (no slash) also matches `projects/p10/...`: the path rule matches by segment, so the root is `projects`.
+ const stored = new Map([
+ ["projects/p1/a", entry("p1a")],
+ ["projects/p10/a", entry("p10a")],
+ ["projects/p2/a", entry("p2a")]
+ ]);
+ const { client, lists, hear } = lab(stored);
+ const { result } = renderHook(() => useResource(projects, { all: true, topicPrefix: "projects/p1", client }));
+ await waitFor(() => expect(keys(result.current.value)).toEqual(["projects/p1/a", "projects/p10/a"]));
+ const listed = lists.length;
+
+ await hear({ topic: { scope: "org", resource: "projects/p2" }, kind: "resource" });
+ await waitFor(() => expect(lists).toHaveLength(listed + 1));
+ });
});
describe("useResource's failure and refresh()", () => {
diff --git a/packages/shift-manager/src/App.tsx b/packages/shift-manager/src/App.tsx
index f2ec0ac6fc..f0a290ad5b 100644
--- a/packages/shift-manager/src/App.tsx
+++ b/packages/shift-manager/src/App.tsx
@@ -8,19 +8,21 @@
* from a control on the panel or with `[` and `]`, and the centre takes the
* width they give up.
*
- * A Lab that refuses the first read for want of a verified organization, or
- * that names no organization for the user, gets the refusal screen and
- * nothing else: the sidebar, the tree and every other read wait behind
- * it. A first read that can't reach the Lab gets the couldn't-reach screen,
- * which reads again on its own. Once a read has landed, a later failure keeps
- * the shell and draws the connection bar above it instead.
+ * A Lab that refuses the organization read for want of a verified
+ * organization, or that names no organization for the user, gets the refusal
+ * screen and nothing else: the sidebar, the tree and every other read wait
+ * behind it (`lib/gate.ts`). An organization read that can't reach the Lab
+ * gets the couldn't-reach screen, whose Retry reads it again. Once in, a later
+ * failure keeps the shell and draws the connection bar above it instead.
*/
-import { useEffect, useState, type ReactNode } from "react";
+import { useLayoutEffect, useState, type ReactNode } from "react";
import { GAPS, type Gaps } from "./gaps";
import type { ThemeLook } from "./lib/theme";
import type { Connection } from "./lib/connection";
-import type { LoadedSnapshot } from "./lib/derive";
import { LabProvider, useLab } from "./lib/lab-data";
+import { DirectoryProvider, useDirectoryLanded, useProjects, useSessions, useWorkers } from "./lib/directory";
+import { useGate } from "./lib/gate";
+import { PageReadsProvider, useReadPageAgain } from "./lib/page-reads";
import { ConnectionBanner } from "./components/flow-state/connection-banner";
import { ConnectionScreen } from "./components/flow-state/connection-screen";
import { ResourceView } from "./surfaces/Resource";
@@ -68,11 +70,73 @@ function LabSessionFeeds({ children }: { children: ReactNode }) {
return {children};
}
+/** What the page draws while the Lab is first read. */
+const READING = (
+
+ Reading the Lab…
+
+);
+
function Shell({ gaps, devtoolUrl, look }: { gaps: Gaps; devtoolUrl: string | undefined; look: ThemeLook | undefined }) {
- const { snapshot, refresh, client, health } = useLab();
- // FIX-2774: the Inbox, Tasks and a task's asks read the inbox view, once the Lab let Shift Manager in; R reads it again too.
- const inbox = useInbox(snapshot !== undefined && snapshot.refused === undefined && snapshot.unreachable === undefined);
+ const { gate, retry } = useGate();
+ if (gate.state === "reading") return READING;
+ if (gate.state === "refused") {
+ return (
+
+ {gate.failure.httpStatus === undefined
+ ? "Shift Manager opens a Lab only under an organization, and this Lab doesn't say which one you're in. Shift Manager shows nothing from the Lab until it does."
+ : "The Lab's server refused the first read because the request carried no verified organization. Shift Manager shows nothing from the Lab until it does. Check that the Lab's config hands Shift Manager a credential (its devtool block) and that Shift Manager is opened on the address its start script printed."}
+
+ );
+ }
+ if (gate.state === "unreachable") {
+ return (
+
+ The first read failed before the Lab said who you are. Check that the Lab's server is running, then retry.
+
+ );
+ }
+ // Every read but the gate's waits behind it: the directory, the Inbox view and the screens' own.
+ return (
+
+
+
+
+
+
+
+ );
+}
+
+/**
+ * The frame, once the directory's first reads have landed; until then, the
+ * page is still reading the Lab. A session list whose first read failed is the
+ * couldn't-reach page, as a failed first whole-Lab read was: every screen
+ * draws its workers' sessions, and none may draw that as no sessions.
+ */
+function Landed({ children }: { children: ReactNode }) {
+ const landed = useDirectoryLanded();
+ const sessions = useSessions();
+ if (!landed) return READING;
+ if (sessions.list === undefined && sessions.failure !== undefined) {
+ return (
+
+ The Lab let you in, but listing your sessions failed. Check that the Lab's server is running, then retry.
+
+ );
+ }
+ return children;
+}
+
+/** The frame, once the Lab let Shift Manager in. */
+function Frame({ gaps, devtoolUrl, look }: { gaps: Gaps; devtoolUrl: string | undefined; look: ThemeLook | undefined }) {
+ const { client, health } = useLab();
+ // FIX-2774: the Inbox, Tasks and a task's asks read the inbox view; R reads it again too.
+ const inbox = useInbox();
const refreshInbox = inbox.refresh;
+ const refreshWorkers = useWorkers().refresh;
+ const refreshProjects = useProjects().refresh;
+ const readPageAgain = useReadPageAgain();
const route = useRoute();
// Null is closed; "" opens Jump to, MESSAGE_PREFIX opens it already in message mode.
const [jumping, setJumping] = useState(null);
@@ -82,7 +146,8 @@ function Shell({ gaps, devtoolUrl, look }: { gaps: Gaps; devtoolUrl: string | un
const { toggleNav, togglePanel } = panels;
const hasPanel = PANEL_NAMES[route.level] !== undefined;
- useEffect(() => {
+ // Bound as the frame commits, not after paint: a key pressed the moment the page draws is heard.
+ useLayoutEffect(() => {
const onKey = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
e.preventDefault();
@@ -90,49 +155,31 @@ function Shell({ gaps, devtoolUrl, look }: { gaps: Gaps; devtoolUrl: string | un
setJumping((j) => (j === null ? (e.shiftKey ? MESSAGE_PREFIX : "") : null));
return;
}
- // `[` and `]` toggle the sidebar and the right panel, and R reads the Lab
- // again, except while typing, and `]` only where there is a panel. AltGr,
- // which types `[` on some layouts, reports Ctrl and Alt held.
+ // `[` and `]` toggle the sidebar and the right panel, and R reads again
+ // what the page holds, except while typing, and `]` only where there is
+ // a panel. AltGr, which types `[` on some layouts, reports Ctrl and Alt held.
const altGraph = typeof e.getModifierState === "function" && e.getModifierState("AltGraph");
if (e.repeat || e.metaKey || ((e.ctrlKey || e.altKey) && !altGraph) || isTypingTarget(e.target)) return;
if (e.key === "[") toggleNav();
else if (e.key === "]" && hasPanel) togglePanel();
else if (e.key === "r" || e.key === "R") {
- // Both reads: the inbox view for the Inbox, its count, Tasks and a task's asks; the snapshot for the screens still on it.
+ // The page's reads: the Inbox view, the worker directory and the sessions, the projects, and each screen's own.
refreshInbox();
- void refresh();
+ refreshWorkers();
+ refreshProjects();
+ readPageAgain();
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
- }, [toggleNav, togglePanel, hasPanel, refresh, refreshInbox]);
-
- if (snapshot === undefined) {
- return
Reading the Lab…
;
- }
- if (snapshot.refused !== undefined) {
- return (
-
- {snapshot.refused.httpStatus === undefined
- ? "Shift Manager opens a Lab only under an organization, and this Lab doesn't say which one you're in. Shift Manager shows nothing from the Lab until it does."
- : "The Lab's server refused the first read because the request carried no verified organization. Shift Manager shows nothing from the Lab until it does. Check that the Lab's config hands Shift Manager a credential (its devtool block) and that Shift Manager is opened on the address its start script printed."}
-
- );
- }
- if (snapshot.unreachable !== undefined) {
- return (
-
- The first read failed before the Lab said who you are. Check that the Lab's server is running, then retry.
-
- );
- }
+ }, [toggleNav, togglePanel, hasPanel, refreshInbox, refreshWorkers, refreshProjects, readPageAgain]);
const levels = (
<>
-
+
-
+
>
);
return (
@@ -153,38 +200,38 @@ function Shell({ gaps, devtoolUrl, look }: { gaps: Gaps; devtoolUrl: string | un
) : (
levels
)}
- {jumping !== null ? setJumping(null)} /> : null}
+ {jumping !== null ? setJumping(null)} /> : null}
);
}
-function Centre({ snapshot, route, gaps, look, devtoolUrl }: { snapshot: LoadedSnapshot; route: Route; gaps: Gaps; look: ThemeLook | undefined; devtoolUrl: string | undefined }) {
+function Centre({ route, gaps, look, devtoolUrl }: { route: Route; gaps: Gaps; look: ThemeLook | undefined; devtoolUrl: string | undefined }) {
switch (route.level) {
case "shift-coordinator":
- return ;
+ return ;
case "roster":
- return ;
+ return ;
case "inbox":
- return ;
+ return ;
case "tasks":
- return ;
+ return ;
case "task":
return ;
case "messages":
- return ;
+ return ;
case "routines":
- return ;
+ return ;
case "usage":
- return ;
+ return ;
case "session":
- return ;
+ return ;
case "resource":
return ;
case "project":
- return ;
+ return ;
case "worker-settings":
- return ;
+ return ;
case "settings":
return ;
}
@@ -208,14 +255,12 @@ const PANEL_NAMES: Partial> = { "shift-coordinato
* has animated down, so it slides shut the way it slides open.
*/
function Panel({
- snapshot,
route,
gaps,
open,
overlay,
onToggle,
}: {
- snapshot: LoadedSnapshot;
route: Route;
gaps: Gaps;
open: boolean;
@@ -224,9 +269,9 @@ function Panel({
}) {
let content = null;
if (route.level === "shift-coordinator") {
- content = ;
+ content = ;
} else if (route.level === "task") {
- content = ;
+ content = ;
}
// Adjusted during render, not in an effect, so the frame after the click already has the panel kept.
const [wasOpen, setWasOpen] = useState(open);
diff --git a/packages/shift-manager/src/components/Conversation.tsx b/packages/shift-manager/src/components/Conversation.tsx
index ea62ea497f..5e9a9ad86e 100644
--- a/packages/shift-manager/src/components/Conversation.tsx
+++ b/packages/shift-manager/src/components/Conversation.tsx
@@ -2,7 +2,7 @@
* A conversation with a worker, as one component any view can draw: the worker's
* session as a feed, and a composer under it that sends into that session.
*
- *
+ *
*
* That is the whole of it: the read, the feed (the registry's renderers, with
* tool calls as quiet lines), the jump to the latest turn, the working line, the
@@ -19,7 +19,7 @@
* under it. It is exported for a screen that shows a named state in the same
* column; split the feed or the composer out when a second view needs them apart.
*/
-import { useEffect, useMemo, useState, type ReactNode } from "react";
+import { useMemo, useState, type ReactNode } from "react";
import type { OutputItem } from "@flow-state-dev/core/items";
import { RECEIVED_MESSAGE_DATA_TYPE, type ProjectAddressRef } from "@flow-state-dev/workforce/browser";
import type { SessionSummary } from "@flow-state-dev/client";
@@ -31,12 +31,13 @@ import { ConversationScrollButton } from "./flow-state/conversation";
import { LoadEarlierButton, SectionFailure } from "./ui";
import { TurnComposer } from "./TurnComposer";
import { knownWorkers, senderOf, useWorkerConversation } from "../lib/conversation";
-import { workerLabel } from "../lib/derive";
+import { workerLabel } from "../lib/shift";
import { SessionScope } from "./TaskBoardMeta";
import { useLab } from "../lib/lab-data";
import { cn } from "../lib/utils";
import { STALE_CLASS } from "./flow-state/connection-banner";
-import type { Worker } from "../lib/reads";
+import type { Worker } from "../lib/workers";
+import { useWorkers } from "../lib/directory";
import { useDeliverLine } from "../lib/deliver";
import { useWorkforce } from "../lib/workforce";
import { clockTime } from "../lib/shell";
@@ -129,12 +130,12 @@ export function Conversation({
/** Why nothing can be sent here, whatever the worker: the session is read, never written to. */
readOnly?: string;
}) {
- const { refresh, answered, snapshot, stale } = useLab();
+ const { stale } = useLab();
const workforce = useWorkforce();
const deliver = useDeliverLine();
const conversation = useWorkerConversation(worker, sessions, session, project);
- const inventory = snapshot !== undefined && "inventory" in snapshot && snapshot.inventory?.ok ? snapshot.inventory.value.workers : undefined;
- const known = useMemo(() => knownWorkers(inventory ?? [], sessions), [inventory, sessions]);
+ const { workers } = useWorkers();
+ const known = useMemo(() => knownWorkers(workers, sessions), [workers, sessions]);
// The feed opens where it starts; with `startAtEnd`, on the latest turn, and again on each
// conversation it is shown. What arrives after stays below the arrow, except the user's own line.
const feed = useJumpToLatest({ startAtEnd, resetKey: conversation.sessionId });
@@ -142,12 +143,6 @@ export function Conversation({
// A starter line picked before a first line: the composer's draft takes it.
const [seed, setSeed] = useState<{ text: string; at: number }>();
- // An ask in this conversation answered in Inbox or the summary: read the conversation back.
- const answeredHere = answered !== undefined && answered.sessionId === sessionId ? answered.count : undefined;
- useEffect(() => {
- if (answeredHere !== undefined) reread();
- }, [answeredHere, reread]);
-
// A run of tool calls stays one segment: the feed draws it as one quiet line. Items that draw no
// line are left out by the model, so a session holding only those (a standing-rules read writes a
// state change into it before any line is sent) counts as empty.
@@ -193,10 +188,8 @@ export function Conversation({
// The session's feed draws the line as it lands; `held` says the worker is on it.
return await deliver({ sessionId: target }, message, { onHeld: held, attachments });
} finally {
- // Read the Lab again however it ended. Stopped short, it may have raised an ask Inbox
- // should list; finished, it may have changed the organization, such as a project it
- // created; failed, the Lab may have opened the session anyway, and the listing says so.
- void refresh();
+ // What the turn changed elsewhere (an ask, a project it created, a worker it hired, the
+ // session a failed send opened anyway) reaches each screen through that read's own notices.
settled?.();
reread();
}
diff --git a/packages/shift-manager/src/components/CoordinatorRoute.tsx b/packages/shift-manager/src/components/CoordinatorRoute.tsx
index 9d5ca0b93f..02e7e3f40e 100644
--- a/packages/shift-manager/src/components/CoordinatorRoute.tsx
+++ b/packages/shift-manager/src/components/CoordinatorRoute.tsx
@@ -6,7 +6,7 @@
* no note.
*/
import type { DataItem } from "@flow-state-dev/core/items";
-import { workerLabel } from "../lib/derive";
+import { workerLabel } from "../lib/shift";
type RoutedDelegate = { worker: string; target?: string; outcome: "delivered" | "skipped" | "failed"; reason?: string };
type RouteRecord = { by?: string; delegates?: RoutedDelegate[]; none?: string; answeredItself?: boolean };
diff --git a/packages/shift-manager/src/components/DelegatesPanel.tsx b/packages/shift-manager/src/components/DelegatesPanel.tsx
index bb45f47dc4..740267c05e 100644
--- a/packages/shift-manager/src/components/DelegatesPanel.tsx
+++ b/packages/shift-manager/src/components/DelegatesPanel.tsx
@@ -6,7 +6,7 @@
* so an add or a remove from anywhere, the coordinator's own tool's included,
* shows as it lands; reading it writes nothing. A change goes through
* workforce's `addDelegate` and `removeDelegate`. The roster it picks from is
- * the connection's one roster watch (`useRoster`), so a worker hired
+ * the page's one roster watch (the directory's), so a worker hired
* meanwhile is offered without a remount. What it shows is what the session
* holds, never a guess: a refused add shows its reason and leaves the list
* as it was.
@@ -17,16 +17,17 @@
import { useMemo, useState } from "react";
import { useView } from "@flow-state-dev/react";
import { delegatesViewRef } from "@flow-state-dev/workforce/browser";
-import { workerLabel } from "../lib/derive";
+import { workerLabel } from "../lib/shift";
import { useLab } from "../lib/lab-data";
-import { describeFailure, type Worker } from "../lib/reads";
-import { useRoster } from "../lib/roster";
+import { describeFailure } from "../lib/failure";
+import type { Worker } from "../lib/workers";
+import { useWorkers } from "../lib/directory";
import { useWorkforce } from "../lib/workforce";
export function DelegatesPanel({ worker, sessionId }: { worker: Worker; sessionId: string | null }) {
const { client } = useLab();
const workforce = useWorkforce();
- const rosterRead = useRoster();
+ const rosterRead = useWorkers().roster;
const roster = rosterRead !== undefined && "entries" in rosterRead ? rosterRead.entries : [];
const [picked, setPicked] = useState("");
const [refusal, setRefusal] = useState(null);
diff --git a/packages/shift-manager/src/components/ReceivedMessage.tsx b/packages/shift-manager/src/components/ReceivedMessage.tsx
index b524d7864c..dfe4666f83 100644
--- a/packages/shift-manager/src/components/ReceivedMessage.tsx
+++ b/packages/shift-manager/src/components/ReceivedMessage.tsx
@@ -9,7 +9,7 @@
* only and never reaches the page.
*/
import type { DataItem } from "@flow-state-dev/core/items";
-import { workerLabel } from "../lib/derive";
+import { workerLabel } from "../lib/shift";
import { RouteLink } from "./RouteLink";
import { clockTime } from "../lib/shell";
import { MarkdownText } from "./flow-state/message-response";
diff --git a/packages/shift-manager/src/components/TaskBoardMeta.tsx b/packages/shift-manager/src/components/TaskBoardMeta.tsx
index af43bbe169..6f96a47b73 100644
--- a/packages/shift-manager/src/components/TaskBoardMeta.tsx
+++ b/packages/shift-manager/src/components/TaskBoardMeta.tsx
@@ -14,9 +14,11 @@ import { STATE_OF_COLUMN, StateSquare } from "./ui";
import { columnFor } from "../lib/columns";
import { useConversationSession } from "../lib/conversation";
import { useConversationTasks, type ConversationTask } from "../lib/conversation-tasks";
-import { workerLabel } from "../lib/derive";
+import { workerLabel } from "../lib/shift";
import { useLab } from "../lib/lab-data";
-import { CONVERSATION_BOARD_COLLECTION, conversationBoardRef } from "../lib/reads";
+import type { SessionSummary } from "@flow-state-dev/client";
+import { CONVERSATION_BOARD_COLLECTION, conversationBoardRef } from "../lib/boards";
+import { useSessions, useWorkers } from "../lib/directory";
import { RouteLink } from "./RouteLink";
/** The board the surrounding feed's session keeps, and its tasks as last read; `{}` outside a {@link SessionScope}. */
@@ -64,8 +66,8 @@ function isConversationTaskChange(item: OutputItem): boolean {
/**
* Watches the conversation's task-list view (`useConversationTasks`): current
* on each board change, with the view's own timer where push can miss one. A
- * failed read leaves the last answer, or the feed's record. The snapshot hears
- * the same moves on its own (`lab-data.tsx`), so what it counts agrees with
+ * failed read leaves the last answer, or the feed's record. The Inbox view
+ * hears the same moves on its own (`inbox.ts`), so what it counts agrees with
* the card.
*/
function LiveBoard({ flow, sessionId, boardRef, children }: { flow: string; sessionId: string; boardRef: string; children: ReactNode }) {
@@ -128,16 +130,19 @@ function TaskCard({ task, boardRef }: { task: Pick worker.kind === ERROR_REPORTER_FLOW) : undefined;
- const sessionId = useConversationSession(reporter, loaded?.sessions ?? []);
+ const { workers } = useWorkers();
+ const sessions = useSessions().list;
+ const reporter = workers.find((worker) => worker.kind === ERROR_REPORTER_FLOW);
+ const sessionId = useConversationSession(reporter, sessions ?? NO_SESSIONS);
if (reporter === undefined) return null;
const name = reporter.name || "the Error Reporter";
return (
diff --git a/packages/shift-manager/src/components/TasksPanel.tsx b/packages/shift-manager/src/components/TasksPanel.tsx
index 2dc25184af..bd4e2f7317 100644
--- a/packages/shift-manager/src/components/TasksPanel.tsx
+++ b/packages/shift-manager/src/components/TasksPanel.tsx
@@ -15,7 +15,7 @@ import { useEffect, useState } from "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 { workerLabel } from "../lib/shift";
import {
pullRequestsWaitedOn,
readPullRequestLinks,
@@ -23,7 +23,8 @@ import {
type ConversationTask,
} from "../lib/conversation-tasks";
import { useLab } from "../lib/lab-data";
-import { conversationBoardRef, type Worker } from "../lib/reads";
+import { conversationBoardRef } from "../lib/boards";
+import type { Worker } from "../lib/workers";
import { RouteLink } from "./RouteLink";
import { STATE_OF_COLUMN, StateSquare } from "./ui";
diff --git a/packages/shift-manager/src/components/ui.tsx b/packages/shift-manager/src/components/ui.tsx
index ed6fcd6c0c..378cbbd81a 100644
--- a/packages/shift-manager/src/components/ui.tsx
+++ b/packages/shift-manager/src/components/ui.tsx
@@ -2,16 +2,16 @@
* Shift Manager's small shared pieces: the named empty state, a failed section with
* Retry, tabs whose selection lives in the URL, a worker's status mark, a feed's
* Load earlier, and the parts of design v2's look every screen draws with: a screen's title,
- * mono meta text, a task's state square, and the snapshot's *as of* line with
- * the dimming its counts take while a read the user asked for runs.
+ * mono meta text, a task's state square, and the *as of* line that says when
+ * a screen's reads last landed.
*
* Every piece is square (v2 draws no rounded corner) and paints only tokens.
*/
import { useState, type ReactNode } from "react";
import type { Column } from "../lib/columns";
-import type { ShiftStatus } from "../lib/derive";
+import type { ShiftStatus } from "../lib/shift";
import { clockTime } from "../lib/shell";
-import type { Failure } from "../lib/reads";
+import type { Failure } from "../lib/failure";
import { cn } from "../lib/utils";
/**
@@ -195,14 +195,8 @@ export function Meta({
}
/**
- * Classes for counts while a read the user asked for runs (`useLab().asking`):
- * dimmed until it lands. A read nobody asked for gives no sign.
- */
-export const ASKING_CLASS = "opacity-60 transition-opacity";
-
-/**
- * When the snapshot was last read, *as of 14:02 · refresh*, never that it is
- * live. *refresh* reads the Lab now, as R does.
+ * When a screen's reads last landed, *as of 14:02 · refresh*, never that they
+ * are live. *refresh* reads them again now, as R does.
*/
export function AsOf({ readAt, onRefresh, testId }: { readAt: number; onRefresh: () => void; testId?: string }) {
return (
@@ -250,16 +244,6 @@ export function ShiftMark({ status, className = "size-2" }: { status: ShiftStatu
return ;
}
-/** A worker's status, as its mark and its word. */
-export function StatusWord({ status }: { status: ShiftStatus }) {
- return (
-
-
- {status}
-
- );
-}
-
/**
* The mark every screen that draws a status or a count shows when the status
* result is partial (asks did not load). The words are the caller's.
diff --git a/packages/shift-manager/src/lib/boards.ts b/packages/shift-manager/src/lib/boards.ts
new file mode 100644
index 0000000000..0ed8061fef
--- /dev/null
+++ b/packages/shift-manager/src/lib/boards.ts
@@ -0,0 +1,30 @@
+/**
+ * A conversation's board: where its rows live, and how a task route and a
+ * row name it. A row's shape is workforce's own (`BoardTask`), the one mapper
+ * the Inbox view reads tasks through too.
+ */
+export type { BoardTask as BoardTaskView } from "@flow-state-dev/workforce/browser";
+
+/**
+ * The collection every conversation's board keeps its rows in: Workforce's
+ * conversation ledger (`CONVERSATION_LEDGER_ID`), which its browser entry
+ * doesn't export. `static.test.ts` pins the two together.
+ */
+export const CONVERSATION_BOARD_COLLECTION = "tasks";
+
+/**
+ * A conversation board's ref: `.tasks`, so a task route and a row
+ * name their board one way.
+ */
+export function conversationBoardRef(sessionId: string): string {
+ return `${sessionId}.${CONVERSATION_BOARD_COLLECTION}`;
+}
+
+/**
+ * The collection a board's tasks are stamped with on their runs' items (the
+ * `collectionId` of each `task-change`): for a conversation's board, the one
+ * collection every conversation shares; any other ref names its own.
+ */
+export function collectionOfBoard(boardRef: string): string {
+ return boardRef.endsWith(`.${CONVERSATION_BOARD_COLLECTION}`) ? CONVERSATION_BOARD_COLLECTION : boardRef;
+}
diff --git a/packages/shift-manager/src/lib/conversation.ts b/packages/shift-manager/src/lib/conversation.ts
index 51703a4672..6aea69c9cb 100644
--- a/packages/shift-manager/src/lib/conversation.ts
+++ b/packages/shift-manager/src/lib/conversation.ts
@@ -8,18 +8,19 @@
* `ensureWorkerSession({ worker, projectId })` opens, on its first line. Items are read when the view opens and then
* followed on the session stream, through the page's one feed for the session (`useSharedSessionFeed`): a line sent here,
* a reply, another worker's message, each shows as it is stored, from any
- * process, and nothing is read on a clock or on the snapshot's refresh.
+ * process, and nothing is read on a clock.
* Nothing is sent until the first read has landed, and a session
* a line opened here holds nothing the user hasn't seen. A lapse after the
* first read keeps it on screen; only a failed first read shows.
*/
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { SessionSummary } from "@flow-state-dev/client";
import type { OutputItem } from "@flow-state-dev/core/items";
import { COORDINATOR_FLOW, deriveWorkerSessionId, type ProjectAddressRef } from "@flow-state-dev/workforce/browser";
import { useLab } from "./lab-data";
import { useReportFeedState } from "./feed-health";
-import { describeFailure, workerOf, type Failure, type Worker } from "./reads";
+import { describeFailure, type Failure } from "./failure";
+import { workerOf, type Worker } from "./workers";
import { useRetrySessionFeed, useSharedSessionFeed } from "./session-feeds";
import { useWorkforce } from "./workforce";
@@ -72,35 +73,43 @@ interface Derived {
}
/**
- * The worker's derived conversation id for the signed-in user.
+ * The worker's derived conversation id for the signed-in user, under the
+ * organization workforce's `organization()` reads (once per page: the gate
+ * already read it).
*/
function useDerivedId(worker: Pick | undefined): Derived {
- const { client, snapshot } = useLab();
- const orgId = snapshot !== undefined && "orgId" in snapshot ? snapshot.orgId : undefined;
+ const { client } = useLab();
+ // The connection decides the organization; its workforce client is the one built over it.
+ const current = useWorkforce();
+ const workforce = useRef(current);
+ workforce.current = current;
const flow = worker?.kind ?? null;
const id = worker?.id;
const [derived, setDerived] = useState<{ key: string; id: string | null; failure?: Failure } | null>(null);
- const key = orgId === undefined || flow === null || id === undefined ? null : `${client.userId}\n${orgId}\n${flow}\n${id}`;
+ const key = flow === null || id === undefined ? null : `${client.userId}\n${flow}\n${id}`;
useEffect(() => {
- if (key === null || orgId === undefined || flow === null || id === undefined) return;
+ if (key === null || flow === null || id === undefined) return;
let closed = false;
- derivedIdOf(key, { userId: client.userId, orgId, flow, criteria: { worker: id } }).then(
- (sessionId) => {
- if (!closed) setDerived({ key, id: sessionId });
- },
- (error: unknown) => {
- if (!closed) setDerived({ key, id: null, failure: describeFailure(error) });
- }
- );
+ workforce.current
+ .organization()
+ .then((orgId) => derivedIdOf(`${key}\n${orgId}`, { userId: client.userId, orgId, flow, criteria: { worker: id } }))
+ .then(
+ (sessionId) => {
+ if (!closed) setDerived({ key, id: sessionId });
+ },
+ (error: unknown) => {
+ if (!closed) setDerived({ key, id: null, failure: describeFailure(error) });
+ },
+ );
return () => {
closed = true;
};
- }, [key, client.userId, orgId, flow, id]);
+ }, [key, client.userId, flow, id]);
if (key === null) return { id: null, failure: undefined };
return derived !== null && derived.key === key ? { id: derived.id, failure: derived.failure } : { id: undefined, failure: undefined };
}
-/** The derived session once the snapshot lists it, for a view that reads the session without drawing it. */
+/** The derived session once the session list holds it, for a view that reads the session without drawing it. */
export function useConversationSession(worker: Pick | undefined, sessions: readonly SessionSummary[]): string | null {
return conversationAt(sessions, useDerivedId(worker).id ?? null, null);
}
@@ -108,7 +117,7 @@ export function useConversationSession(worker: Pick | und
export interface WorkerConversation {
/** The conversation's session, or `null` before a first line. */
sessionId: string | null;
- /** The session a first line opened here, until the snapshot lists it. */
+ /** The session a first line opened here, until the session list holds it. */
opened: string | null;
/**
* What the session stores, once read, for the session shown: its newest
@@ -126,7 +135,7 @@ export interface WorkerConversation {
}
/**
- * `pinned` is the session the view found: that one, whatever the snapshot lists.
+ * `pinned` is the session the view found: that one, whatever the session list holds.
* `project`, with nothing pinned, is the project a view's conversation is linked to (a
* project's Stream): it has no session until the first line opens one linked to it,
* and the worker's own conversation is never read in its place.
diff --git a/packages/shift-manager/src/lib/deliver.ts b/packages/shift-manager/src/lib/deliver.ts
index ec80f58a7e..7158088a18 100644
--- a/packages/shift-manager/src/lib/deliver.ts
+++ b/packages/shift-manager/src/lib/deliver.ts
@@ -49,7 +49,7 @@ import { deriveSuspensions } from "@flow-state-dev/react/internal";
import { sessionTurnsViewRef, type ListedTurn } from "@flow-state-dev/workforce/browser";
import type { Client } from "@flow-state-dev/client";
import { useLab } from "./lab-data";
-import { describeFailure } from "./reads";
+import { describeFailure } from "./failure";
import { useSharedSessionFeed } from "./session-feeds";
import { useWorkforce } from "./workforce";
diff --git a/packages/shift-manager/src/lib/derive.ts b/packages/shift-manager/src/lib/derive.ts
index e2fd283918..81c826a218 100644
--- a/packages/shift-manager/src/lib/derive.ts
+++ b/packages/shift-manager/src/lib/derive.ts
@@ -1,21 +1,15 @@
/**
- * What the screens compute from one snapshot, kept out of the components so
- * every surface computes it the same way.
+ * What the snapshot's reads compute from one snapshot. No screen reads the
+ * snapshot any more: the screens compute from their own reads (`shift.ts`,
+ * `inbox.ts`), and the helpers both share live there.
*/
import type { InboxItem } from "@flow-state-dev/orchestration/inbox";
import { isDone } from "./columns";
-import {
- GENERAL_TEAM,
- type Ask,
- type BoardTaskView,
- type Failure,
- type LabSnapshot,
- type Project,
- type Section,
- type Worker,
- workerOf,
- workstreamOf,
-} from "./reads";
+import type { Ask, LabSnapshot } from "./reads";
+import type { BoardTaskView } from "./boards";
+import type { Failure, Section } from "./failure";
+import type { Project } from "./project";
+import { workerOf, workstreamOf } from "./workers";
/** A loaded snapshot (not a refusal, not an unreachable Lab). */
export type LoadedSnapshot = Exclude;
@@ -47,108 +41,6 @@ export function openTasks(snapshot: LoadedSnapshot): BoardTaskView[] {
return allTasks(snapshot).filter((row) => !isDone(row.status));
}
-/** The workers a row's assignee is resolved against. */
-export type Roster = { workers: readonly Worker[] };
-
-// FIX-1672.
-/**
- * The worker a row is held by, or `undefined` when no single worker is.
- *
- * A row names an `assignee`, which is a routing key a board's workers answer
- * to, not a worker address: a board may name `` for the worker
- * `.`. So, in order:
- *
- * 1. the worker whose id is the assignee;
- * 2. the one worker whose own name is the assignee.
- *
- * A name more than one worker carries, or none, is no worker: a row is never shown against
- * several workers, or against a guess. Which worker actually claimed the row is
- * not published to a browser, and a declared assignee-to-worker map
- * arrives in a later release.
- */
-export function workerFor(roster: Roster, row: Pick): Worker | undefined {
- if (row.assignee === null) return undefined;
- const exact = roster.workers.find((worker) => worker.id === row.assignee);
- if (exact !== undefined) return exact;
- const named = roster.workers.filter((worker) => worker.name === row.assignee);
- return named.length === 1 ? named[0] : undefined;
-}
-
-/** A worker's shift status, the one word Roster and the sidebar draw. */
-export type ShiftStatus = "on shift" | "off shift";
-
-/** The two statuses, in the order Roster groups them. */
-export const SHIFT_STATUSES: readonly ShiftStatus[] = ["on shift", "off shift"];
-
-/** One worker's state: its status, the tasks it holds, and the asks it waits on you with. */
-export type WorkerState = {
- worker: Worker;
- status: ShiftStatus;
- /** Its rows that are running, waiting on you included, in board order: its slots in use. */
- held: BoardTaskView[];
- /** Of `held`, the rows held on a question or confirm for you (their Inbox item's board holds). */
- waitsOnYou: BoardTaskView[];
- /** Its pending asks, in Inbox's order. */
- asks: Ask[];
-};
-
-/** Every worker's state, and whether the result is partial. */
-export type WorkerStates = {
- /** Keyed by worker id, in inventory order. */
- workers: Map;
- /** Asks did not load: a worker waiting on you only through an ask reads off shift. */
- partial: boolean;
-};
-
-const computed = new WeakMap();
-
-/**
- * Every worker's status, worked out once per snapshot from what the Lab records:
- * its rows (each resolved by {@link workerFor}) and its pending asks.
- *
- * - **on shift**: it holds a running row (one waiting on you included) or a
- * pending ask;
- * - **off shift**: none of those. Queued, blocked, errored and finished rows
- * hold no slot.
- *
- * A row no single worker resolves to, and an ask whose session names no worker in
- * the inventory, count for nobody. Asks that did not load leave every status
- * as the boards give it and mark the result `partial`.
- *
- * Every screen that draws a status or a count reads this result, and the same
- * snapshot always gets the same object.
- */
-export function workerStates(snapshot: LoadedSnapshot): WorkerStates {
- const cached = computed.get(snapshot);
- if (cached !== undefined) return cached;
- const roster = rosterOf(snapshot);
- const workers = new Map(
- roster.workers.map((worker) => [worker.id, { worker, status: "off shift", held: [], waitsOnYou: [], asks: [] }]),
- );
- for (const row of allTasks(snapshot)) {
- if (row.status !== "in_progress") continue;
- const owner = workerFor(roster, row);
- if (owner === undefined) continue;
- const state = workers.get(owner.id);
- state?.held.push(row);
- if (waitsOnYou(snapshot, row)) state?.waitsOnYou.push(row);
- }
- for (const ask of snapshot.asks.ok ? snapshot.asks.value : []) {
- if (ask.workerId !== null) workers.get(ask.workerId)?.asks.push(ask);
- }
- for (const state of workers.values()) {
- state.status = state.held.length > 0 || state.asks.length > 0 ? "on shift" : "off shift";
- }
- const result = { workers, partial: !snapshot.asks.ok };
- computed.set(snapshot, result);
- return result;
-}
-
-/** The workers of a snapshot whose inventory loaded; empty otherwise. */
-export function rosterOf(snapshot: LoadedSnapshot): Roster {
- return snapshot.inventory.ok ? snapshot.inventory.value : { workers: [] };
-}
-
/**
* The Inbox item that shows suspension `suspensionId`: a task's item when its
* task holds it, else the ask's own. Its id when the Inbox didn't load or
@@ -200,39 +92,6 @@ export function asksOfTask(snapshot: LabSnapshot | undefined, row: Pick worker.kind === flowId)?.door ?? null;
-}
-
-/**
- * Whether the door of the flow that owns a session takes a task id, read the
- * same way as {@link doorOf}. `false` when no worker entry is on the flow.
- */
-export function doorTakesTaskOf(workers: readonly Worker[], flowId: string): boolean {
- return workers.find((worker) => worker.kind === flowId)?.doorTakesTask ?? false;
-}
-
-/**
- * The teams in the worker inventory, each with its display name and its
- * workers, in first-seen order, with the org workers' General group first.
- */
-export function teamsOf(workers: readonly Worker[]): Array<{ team: string; name: string; workers: Worker[] }> {
- const teams = new Map();
- for (const worker of workers) {
- const team = teams.get(worker.team);
- if (team === undefined) teams.set(worker.team, [worker]);
- else team.push(worker);
- }
- const all = [...teams].map(([team, workers]) => ({ team, name: workers[0]!.teamName, workers }));
- return [...all.filter((t) => t.team === GENERAL_TEAM), ...all.filter((t) => t.team !== GENERAL_TEAM)];
-}
-
/** PROJECTS: every project the user reads. */
export type ProjectsView = { projects: Project[] };
@@ -247,57 +106,6 @@ export function projectsOf(snapshot: LoadedSnapshot): Section {
return { ok: true, value: { projects: snapshot.projects.value.rows } };
}
-
-/** How many workers are in each status, and how many waits-on entries they have. */
-export type ShiftCounts = Record & {
- /** Each held task holding on a question for you plus each pending ask, across the workers counted. */
- waiting: number;
-};
-
-/** The counts over every worker in `states`, or over one team's. */
-export function shiftCounts(states: WorkerStates, team?: string): ShiftCounts {
- const counts: ShiftCounts = { "on shift": 0, "off shift": 0, waiting: 0 };
- for (const { worker, status, waitsOnYou, asks } of states.workers.values()) {
- if (team !== undefined && worker.team !== team) continue;
- counts[status] += 1;
- counts.waiting += waitsOnYou.length + asks.length;
- }
- return counts;
-}
-
-/** The team a Roster address picks, or `null` (All) when the inventory has no such team. */
-export function pickedTeam(workers: readonly Worker[], team: string | null): string | null {
- return team !== null && workers.some((worker) => worker.team === team) ? team : null;
-}
-
-/**
- * The name a worker must carry to be the Shift Coordinator: an org worker's id, or a
- * team worker's name. The only place Shift Manager names a worker (D2).
- */
-const SHIFT_COORDINATOR = "shift-coordinator";
-
-const isShiftCoordinator = (idOrName: string) => idOrName.slice(idOrName.indexOf(".") + 1) === SHIFT_COORDINATOR;
-
-/** How the screens name a worker: `shift-coordinator` is the Shift Coordinator. */
-export function workerLabel(idOrName: string): string {
- return isShiftCoordinator(idOrName) ? "Shift Coordinator" : idOrName;
-}
-
-/** Which worker Shift Manager talks to as the Shift Coordinator, if exactly one is. */
-export type ShiftCoordinator = { kind: "one"; worker: Worker } | { kind: "none" } | { kind: "several"; workers: Worker[] };
-
-/**
- * The Shift Coordinator among the inventory's workers (D2): the workers whose name is
- * exactly `shift-coordinator`. That is an org worker (`shift-coordinator`) or a
- * team's worker (`.shift-coordinator`). One is the Shift Coordinator; two or
- * more are a state, never a guess.
- */
-export function shiftCoordinatorOf(workers: readonly Worker[]): ShiftCoordinator {
- const found = workers.filter((worker) => isShiftCoordinator(worker.id));
- if (found.length === 0) return { kind: "none" };
- return found.length === 1 ? { kind: "one", worker: found[0]! } : { kind: "several", workers: found };
-}
-
/** Whether a row is running. */
const isRunning = (row: BoardTaskView) => row.status === "in_progress";
@@ -332,14 +140,3 @@ export function shiftSummary(snapshot: LoadedSnapshot): {
: { ok: false, failure: failed },
};
}
-
-/** How long ago `since` was, in a short human form. */
-export function waited(since: number, now: number): string {
- const seconds = Math.max(0, Math.round((now - since) / 1000));
- if (seconds < 60) return `${seconds}s`;
- const minutes = Math.round(seconds / 60);
- if (minutes < 60) return `${minutes}m`;
- const hours = Math.round(minutes / 60);
- if (hours < 48) return `${hours}h`;
- return `${Math.round(hours / 24)}d`;
-}
diff --git a/packages/shift-manager/src/lib/directory-reads.ts b/packages/shift-manager/src/lib/directory-reads.ts
new file mode 100644
index 0000000000..e4e726b38c
--- /dev/null
+++ b/packages/shift-manager/src/lib/directory-reads.ts
@@ -0,0 +1,82 @@
+/**
+ * The reads the directory holds, one of each per page (`directory.tsx`):
+ * the organization's worker inventory and the user's two projects
+ * collections, each read whole and kept current by `react`'s `useResource`;
+ * the user's roster, followed through workforce's client (`roster.ts`); and
+ * the user's sessions, dispatch runs included, by `react`'s `useSessionList`.
+ * Every one is kept current by its own notices, so nothing here re-reads on
+ * a whole-Lab clock.
+ */
+import { useMemo, useRef } from "react";
+import type { SessionSummary } from "@flow-state-dev/client";
+import { useResource, useSessionList } from "@flow-state-dev/react";
+import { privateProjectsResource, projectsResource, workerInventoryResource } from "@flow-state-dev/workforce/browser";
+import { useLab } from "./lab-data";
+import type { Failure } from "./failure";
+import { toProject, type Project } from "./project";
+import { useRoster, type RosterRead } from "./roster";
+import { toWorker, type Worker } from "./workers";
+
+/** One whole-collection read: its entries' parsed values once read (`undefined` before), why the last read failed, and a read on demand. */
+export type CollectionRead = { values: T[] | undefined; failure: Failure | undefined; refresh: () => void };
+
+/** The user's listed sessions: `undefined` until a list lands, why the last list failed, and a list on demand. */
+export type Sessions = { list: readonly SessionSummary[] | undefined; failure: Failure | undefined; refresh: () => void };
+
+/** What the directory reads. */
+export type DirectoryReads = {
+ /** The inventory's workers, as its rows publish them. */
+ inventory: CollectionRead;
+ /** The user's roster. */
+ roster: RosterRead;
+ /** The user's listed sessions, dispatch runs included: `undefined` until listed, and why the last list failed. */
+ sessions: Sessions;
+ /** The organization's projects, then the user's private ones. */
+ projects: { shared: CollectionRead; own: CollectionRead };
+};
+
+/** A failure, held by what it says: a hook words a failure afresh each render. */
+function useSameFailure(failure: Failure | undefined): Failure | undefined {
+ const message = failure?.message;
+ const status = failure?.httpStatus;
+ return useMemo(
+ () => (message === undefined ? undefined : { message, ...(status === undefined ? {} : { httpStatus: status }) }),
+ [message, status],
+ );
+}
+
+/** A whole-collection read's entries, each parsed by `parse` (one that doesn't parse is left out), held while the read's value is. */
+function useParsed(
+ read: { value: readonly { value: unknown }[] | null; failure?: Failure; refresh(): void },
+ parse: (value: unknown) => T | undefined,
+): CollectionRead {
+ const value = read.value;
+ // `parse` is a module-level function per call site.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ const values = useMemo(() => value?.map((entry) => parse(entry.value)).filter((parsed): parsed is T => parsed !== undefined), [value]);
+ const failure = useSameFailure(read.failure);
+ const refresh = read.refresh;
+ return useMemo(() => ({ values, failure, refresh }), [values, failure, refresh]);
+}
+
+const sharedProject = (value: unknown) => toProject(value, "shared");
+const privateProject = (value: unknown) => toProject(value, "private");
+
+/** The directory's reads, once per page: only the directory provider calls this. */
+export function useDirectoryReads(): DirectoryReads {
+ const { client } = useLab();
+ const inventory = useParsed(useResource(workerInventoryResource, { client, all: true }), toWorker);
+ const shared = useParsed(useResource(projectsResource, { client, all: true }), sharedProject);
+ const own = useParsed(useResource(privateProjectsResource, { client, all: true }), privateProject);
+ const roster = useRoster();
+ const listing = useSessionList({ client, includeDispatchRuns: true, includeStatus: false });
+ // The last list that landed: undefined until one has. A failed read is its failure, never an empty
+ // list, and a failed read again keeps the list already drawn beside it.
+ const good = useRef(undefined);
+ if (listing.error === null && (!listing.isLoading || listing.sessions.length > 0)) good.current = listing.sessions;
+ const listed = good.current;
+ const failure = useSameFailure(listing.error === null ? undefined : { message: listing.error });
+ const sessions = useMemo(() => ({ list: listed, failure, refresh: listing.refresh }), [listed, failure, listing.refresh]);
+ const projects = useMemo(() => ({ shared, own }), [shared, own]);
+ return { inventory, roster, sessions, projects };
+}
diff --git a/packages/shift-manager/src/lib/directory.tsx b/packages/shift-manager/src/lib/directory.tsx
new file mode 100644
index 0000000000..160b9d6eaa
--- /dev/null
+++ b/packages/shift-manager/src/lib/directory.tsx
@@ -0,0 +1,162 @@
+// FIX-2775 D1.
+/**
+ * The worker directory, the user's sessions and the projects they read: one
+ * read of each per page, held by {@link DirectoryProvider} and drawn by every
+ * screen through {@link useWorkers}, {@link useSessions} and
+ * {@link useProjects}. N screens drawing workers is still one inventory read
+ * and one roster watch, so one org notice is one read, not N.
+ *
+ * The workers are the inventory joined with the roster (`workers.ts`);
+ * who is on shift reads the Inbox view against them (`shift.ts`).
+ */
+import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from "react";
+import { useDirectoryReads, type CollectionRead, type Sessions } from "./directory-reads";
+import type { Failure, Section } from "./failure";
+import type { Project } from "./project";
+import type { RosterRead } from "./roster";
+import { joinWorkers, type Worker } from "./workers";
+
+/** The organization's worker inventory, by its published key pattern: named in the no-inventory failure. */
+const WORKER_INVENTORY_PATTERN = "inventory/workers/*";
+
+/** What a read the Lab answered with no inventory says: none of its flows declares one, or none holds a worker. */
+const NO_INVENTORY: Failure = {
+ message: `No inventory to read: none of this Lab's flows declares the organization's worker inventory (${WORKER_INVENTORY_PATTERN}) with a worker in it. Either the Lab booted without opening its inventory, or these pages are an older build than the Lab and look for keys it no longer uses: rebuild them (pnpm --filter @flow-state-dev/shift-manager build) and reload.`,
+};
+
+/** The worker directory, as a screen draws it. */
+export type Workers = {
+ /**
+ * The inventory's workers, or why there are none: a Lab whose flows declare
+ * no inventory, or one with no worker in it, is a failure that says which.
+ * `undefined` until the first read lands or fails.
+ */
+ inventory: Section | undefined;
+ /** Every worker: the inventory's, joined with the roster, the user's own after them. */
+ workers: Worker[];
+ /** The user's own workers, among {@link Workers.workers}. */
+ own: Worker[];
+ /** The roster read the join drew on. */
+ roster: RosterRead;
+ /** When the directory's reads last landed, epoch ms; `undefined` before. */
+ readAt: number | undefined;
+ /** Read the inventory and the sessions again: a section's Retry, R. */
+ refresh: () => void;
+};
+
+/** The directory: the workers, the sessions and the projects. */
+type Directory = {
+ workers: Workers;
+ sessions: Sessions;
+ projects: { section: Section | undefined; refresh: () => void };
+};
+
+const nothing = () => {};
+
+/**
+ * The directory with nothing read: what a component drawn outside a
+ * {@link DirectoryProvider} sees (a component under test on its own), the
+ * same as a page whose reads haven't landed.
+ */
+const UNREAD: Directory = {
+ workers: { inventory: undefined, workers: [], own: [], roster: undefined, readAt: undefined, refresh: nothing },
+ sessions: { list: undefined, failure: undefined, refresh: nothing },
+ projects: { section: undefined, refresh: nothing },
+};
+
+const DirectoryContext = createContext(UNREAD);
+
+/** The inventory's section: its workers, or why there are none. */
+function inventorySection(read: CollectionRead): Section | undefined {
+ if (read.values !== undefined && read.values.length > 0) return { ok: true, value: read.values };
+ if (read.values !== undefined || read.failure?.httpStatus === 404) return { ok: false, failure: NO_INVENTORY };
+ return read.failure === undefined ? undefined : { ok: false, failure: read.failure };
+}
+
+/**
+ * The projects the user reads: the shared ones in the collection's order,
+ * then their private ones. A scope no flow declares (a 404) has none, which is
+ * not a failure; any other failure says why, and is never drawn as an empty
+ * list. A read that fails after one landed keeps the rows it read.
+ */
+function projectsSection(shared: CollectionRead, own: CollectionRead): Section | undefined {
+ const valuesOf = (read: CollectionRead): Section | undefined =>
+ read.values !== undefined
+ ? { ok: true, value: read.values }
+ : read.failure === undefined
+ ? undefined
+ : read.failure.httpStatus === 404
+ ? { ok: true, value: [] }
+ : { ok: false, failure: read.failure };
+ const [a, b] = [valuesOf(shared), valuesOf(own)];
+ if (a?.ok === false) return a;
+ if (b?.ok === false) return b;
+ return a === undefined || b === undefined ? undefined : { ok: true, value: [...a.value, ...b.value] };
+}
+
+/** Hold the page's one read of each directory read, for every screen under it. */
+export function DirectoryProvider({ children }: { children: ReactNode }) {
+ const { inventory, roster, sessions, projects } = useDirectoryReads();
+ const section = useMemo(() => inventorySection(inventory), [inventory]);
+ const entries = roster !== undefined && "entries" in roster ? roster.entries : undefined;
+ const joined = useMemo(() => joinWorkers(section?.ok === true ? section.value : undefined, entries ?? []), [section, entries]);
+ // When the directory's reads last landed: what Roster's *read* line says.
+ const [readAt, setReadAt] = useState(undefined);
+ useEffect(() => {
+ if (inventory.values !== undefined || entries !== undefined) setReadAt(Date.now());
+ }, [inventory.values, entries]);
+ const refreshInventory = inventory.refresh;
+ const refreshSessions = sessions.refresh;
+ const refresh = useCallback(() => {
+ refreshInventory();
+ refreshSessions();
+ }, [refreshInventory, refreshSessions]);
+ const workers = useMemo(
+ () => ({ inventory: section, workers: joined.workers, own: joined.own, roster, readAt, refresh }),
+ [section, joined, roster, readAt, refresh],
+ );
+ const projectList = useMemo(() => projectsSection(projects.shared, projects.own), [projects]);
+ const refreshShared = projects.shared.refresh;
+ const refreshOwn = projects.own.refresh;
+ const refreshProjects = useCallback(() => {
+ refreshShared();
+ refreshOwn();
+ }, [refreshShared, refreshOwn]);
+ const value = useMemo(
+ () => ({ workers, sessions, projects: { section: projectList, refresh: refreshProjects } }),
+ [workers, sessions, projectList, refreshProjects],
+ );
+ return {children};
+}
+
+function useDirectory(): Directory {
+ return useContext(DirectoryContext);
+}
+
+/** The worker directory every screen that draws a worker reads. */
+export function useWorkers(): Workers {
+ return useDirectory().workers;
+}
+
+/** The user's listed sessions, dispatch runs included: `list` is `undefined` until listed. */
+export function useSessions(): Directory["sessions"] {
+ return useDirectory().sessions;
+}
+
+/** The projects the user reads, shared then private: `undefined` until both reads land. */
+export function useProjects(): Directory["projects"] {
+ return useDirectory().projects;
+}
+
+/**
+ * Whether the directory's first reads have landed, or failed: the inventory,
+ * the roster, the session list and the projects. The frame waits for it, as
+ * it waited for the whole-Lab read before, so no screen draws half a
+ * directory: not the inventory's workers before the user's own join them, and
+ * not a failed session list as no sessions (the frame draws that failure).
+ */
+export function useDirectoryLanded(): boolean {
+ const { workers, sessions, projects } = useDirectory();
+ const listed = sessions.list !== undefined || sessions.failure !== undefined;
+ return workers.inventory !== undefined && workers.roster !== undefined && listed && projects.section !== undefined;
+}
diff --git a/packages/shift-manager/src/lib/documents.ts b/packages/shift-manager/src/lib/documents.ts
new file mode 100644
index 0000000000..acaaeee6c8
--- /dev/null
+++ b/packages/shift-manager/src/lib/documents.ts
@@ -0,0 +1,78 @@
+// BR-10.
+/**
+ * The declared documents a browser may read, for Jump to: each listed flow's
+ * manifest, read once per flow through the first listed session of it, and
+ * cached by flow for the page, since a manifest is a property of the flow and
+ * static per flow. The session is only its address. A document no flow
+ * serves, or a flow no listed session runs, is not found.
+ */
+import { useEffect, useState } from "react";
+import type { Client, ResourceManifest, SessionSummary } from "@flow-state-dev/client";
+import { useLab } from "./lab-data";
+import { useSessions } from "./directory";
+import { describeFailure, type Section } from "./failure";
+
+/** A declared document the Lab serves to a browser, and a listed session whose flow serves it, to read it through. */
+type DeclaredDocument = { ref: string; sessionId: string };
+
+/** Manifests read, per connection and flow; a failed read is not kept, so the next open reads it again. */
+const manifests = new WeakMap
diff --git a/packages/shift-manager/src/surfaces/Messages.tsx b/packages/shift-manager/src/surfaces/Messages.tsx
index b39fd29d13..dac8a4e575 100644
--- a/packages/shift-manager/src/surfaces/Messages.tsx
+++ b/packages/shift-manager/src/surfaces/Messages.tsx
@@ -9,7 +9,7 @@
*/
import { useMemo } from "react";
import { EmptyState, Meta, ScreenTitle, SectionFailure } from "../components/ui";
-import { workerLabel, type LoadedSnapshot } from "../lib/derive";
+import { workerLabel } from "../lib/shift";
import { firstLine, exchangesOf, useMessages, type WorkerMessageResourceState } from "../lib/messages";
import { RouteLink } from "../components/RouteLink";
import { clockTime } from "../lib/shell";
@@ -81,8 +81,8 @@ function MessageLine({ row }: { row: WorkerMessageResourceState }) {
);
}
-export function Messages({ snapshot }: { snapshot: LoadedSnapshot }) {
- const { rows, failure, reread } = useMessages(snapshot.readAt);
+export function Messages() {
+ const { rows, failure, reread } = useMessages();
const exchanges = useMemo(() => (rows == null ? [] : exchangesOf(rows)), [rows]);
return (
diff --git a/packages/shift-manager/src/surfaces/Project.tsx b/packages/shift-manager/src/surfaces/Project.tsx
index e7c7becb1e..b8b10f16c2 100644
--- a/packages/shift-manager/src/surfaces/Project.tsx
+++ b/packages/shift-manager/src/surfaces/Project.tsx
@@ -7,8 +7,7 @@
* a session of the standard coordinator worker the Lab's project setup
* names, linked to this project, found when the tab opens and started by
* the user's first line there, so opening the tab starts nothing. It
- * hands a line to the user's own workstreams in the project. A finished
- * turn reads the Lab again, as every conversation does.
+ * hands a line to the user's own workstreams in the project.
* - **Board** draws the tasks of the user's own workstream sessions in the
* project, one panel per session, each read from that session alone. Another
* user's workstream sessions, and the Lab-wide inventory of boards, are
@@ -23,10 +22,10 @@
* - **Brief** is the row's brief, under the repository its code lives in, or
* a line saying it has none and its coding work runs on its files.
*
- * **What a project view reads**: the row and the entries, by one
- * prefix, when it opens, each time the Lab is read again, and every few
- * seconds while Board or Workstreams is on screen; never a read of
- * the whole Lab of its own. The title comes from the snapshot every level shares.
+ * **What a project view reads**: the row from the projects the page holds
+ * (`directory.tsx`), and the entries by the project's one prefix while Board
+ * or Workstreams is on screen, each kept current by its own notices; never a
+ * read of the whole Lab.
*
* Above the tabs, the team strip from the worker inventory, as design v2 draws
* it (v2:513-519): each team's name in spaced mono caps and how many of its
@@ -37,19 +36,24 @@ import type { RosterEntry } from "@flow-state-dev/workforce/browser";
import { Conversation } from "../components/Conversation";
import { TasksPanel } from "../components/TasksPanel";
import { EmptyState, Meta, PartialMark, ScreenTitle, SectionFailure, Tabs } from "../components/ui";
-import { projectsOf, workerStates, shiftCounts, teamsOf, type LoadedSnapshot } from "../lib/derive";
+import type { SessionSummary } from "@flow-state-dev/client";
+import type { ProjectSetup } from "@flow-state-dev/workforce/browser";
+import { workerStates, shiftCounts, teamsOf } from "../lib/shift";
import { useLab } from "../lib/lab-data";
+import { useProjects, useSessions, useWorkers } from "../lib/directory";
+import { useInbox } from "../lib/inbox";
import {
- readEntryReport,
- readProjectSetup,
- useProjectRead,
+ useEntryReport,
+ useProjectSetup,
+ useProjectWorkstreams,
type ProjectAddress,
- type ProjectRead,
- type ProjectSetup,
+ type ProjectWorkstreams,
+ type ScreenRead,
type WorkstreamEntry,
} from "../lib/projects";
-import { describeFailure, workerOf, type Failure, type Worker } from "../lib/reads";
-import { useRoster, withRoster } from "../lib/roster";
+import { describeFailure, type Failure } from "../lib/failure";
+import type { RosterRead } from "../lib/roster";
+import { workerOf, type Worker } from "../lib/workers";
import { navigate, PROJECT_TABS, type ProjectTab, type Route } from "../lib/routes";
import { RouteLink } from "../components/RouteLink";
import { useWorkforce } from "../lib/workforce";
@@ -60,6 +64,14 @@ type ProjectRoute = Extract;
/** A read in flight, landed, or failed. */
type Read = { value: T } | { failure: Failure } | undefined;
+/** A hook's read as one of those three: a value drawn wins over a later failure beside it. */
+function readOf(read: ScreenRead): Read {
+ return read.value !== undefined ? { value: read.value } : read.failure !== undefined ? { failure: read.failure } : undefined;
+}
+
+/** No sessions, while the list is read. */
+const NO_SESSIONS: readonly SessionSummary[] = [];
+
/** The same project at `tab`, on one of its workstreams or on none. */
function at(route: ProjectRoute, tab: ProjectTab, entry?: { owner: string; id: string }): ProjectRoute {
return {
@@ -71,24 +83,27 @@ function at(route: ProjectRoute, tab: ProjectTab, entry?: { owner: string; id: s
};
}
-export function ProjectView({ snapshot, route, gaps }: { snapshot: LoadedSnapshot; route: ProjectRoute; gaps: Gaps }) {
- const { refresh } = useLab();
+export function ProjectView({ route, gaps }: { route: ProjectRoute; gaps: Gaps }) {
const { projectId, tab } = route;
- const teams = snapshot.inventory.ok ? teamsOf(snapshot.inventory.value.workers) : [];
- const states = workerStates(snapshot);
- const view = projectsOf(snapshot);
+ const { inventory, workers } = useWorkers();
+ const inbox = useInbox().section;
+ const teams = inventory?.ok === true ? teamsOf(inventory.value) : [];
+ const states = workerStates(workers, inbox?.ok === true ? inbox.value : undefined);
+ const { section: view, refresh } = useProjects();
const address: ProjectAddress = { visibility: route.visibility ?? "shared", id: projectId };
let title = projectId;
let body: ReactNode;
- if (!view.ok) {
+ if (view === undefined) {
+ body =
- ) : read !== undefined && read.value === null ? (
-
- The Lab has no project here you can read. It may have been removed since the Lab was last read.{" "}
-
-
- ) : null;
- const reading =
+ );
+ }}
+
);
- }
}
}
+/** A project's workstreams, read while this is mounted, drawn by `children` once they land. */
+function Entries({ address, children }: { address: ProjectAddress; children: (read: ProjectWorkstreams) => ReactNode }) {
+ const { value, failure, refresh } = useProjectWorkstreams(address);
+ if (value === undefined && failure !== undefined) {
+ return (
+
+
+
+ );
+ }
+ if (value === undefined) return
Reading the project…
;
+ return <>{children(value)}>;
+}
+
/**
* The user's conversation with their project coordinator (S5): found for this
* project when the tab opens, then the shared conversation component pinned to
@@ -264,14 +254,12 @@ function ProjectBody({
* session, linked to the project: reading the tab starts no session.
*/
function CoordinatorStream({
- snapshot,
address,
setup,
retrySetup,
workers,
gaps,
}: {
- snapshot: LoadedSnapshot;
address: ProjectAddress;
setup: Read;
retrySetup: () => void;
@@ -279,6 +267,7 @@ function CoordinatorStream({
gaps: Gaps;
}) {
const workforce = useWorkforce();
+ const sessions = useSessions().list ?? NO_SESSIONS;
const coordinatorId = setup !== undefined && "value" in setup ? (setup.value?.projectCoordinator ?? null) : undefined;
// `null`: the user has no session with it for this project yet.
const [session, setSession] = useState>(undefined);
@@ -299,7 +288,7 @@ function CoordinatorStream({
// Found none: look again whenever the Lab lists a new session of the coordinator, such as one
// another tab started, so this tab follows it. Still a lookup only; nothing is started here.
const unopened = session !== undefined && "value" in session && session.value === null;
- const listed = snapshot.sessions
+ const listed = sessions
.filter((s) => workerOf(s) === coordinatorId)
.map((s) => s.id)
.join("\n");
@@ -351,7 +340,7 @@ function CoordinatorStream({
worker={worker}
session={session.value ?? undefined}
project={address}
- sessions={snapshot.sessions}
+ sessions={sessions}
gaps={gaps}
name="Project coordinator"
emptyText="Ask about this project, or hand work to one of your workstreams in it."
@@ -361,7 +350,7 @@ function CoordinatorStream({
// BR-18, BR-19.
/** The project's progress, worked out from its entries. */
-function Progress({ read }: { read: ProjectRead }) {
+function Progress({ read }: { read: ProjectWorkstreams }) {
const { progress } = read;
const statuses = Object.entries(progress.byStatus);
return (
@@ -423,7 +412,6 @@ function EntryList({ entries, route }: { entries: readonly WorkstreamEntry[]; ro
* anyone else reads the entry and its latest report, and never its session.
*/
function EntryView({
- snapshot,
address,
route,
entry,
@@ -431,15 +419,15 @@ function EntryView({
workers,
gaps,
}: {
- snapshot: LoadedSnapshot;
address: ProjectAddress;
route: ProjectRoute;
entry: WorkstreamEntry | undefined;
- roster: ReturnType;
+ roster: RosterRead;
workers: readonly Worker[];
gaps: Gaps;
}) {
const { client } = useLab();
+ const sessions = useSessions().list ?? NO_SESSIONS;
const back = (
}
@@ -510,18 +498,7 @@ function EntryDetails({
leadName: string;
back: ReactNode;
}) {
- const { client } = useLab();
- const [report, setReport] = useState>(undefined);
- useEffect(() => {
- let closed = false;
- readEntryReport(client, address, entry)
- .then((value) => !closed && setReport({ value }))
- .catch((error: unknown) => !closed && setReport({ failure: describeFailure(error) }));
- return () => {
- closed = true;
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [client, entry.key]);
+ const report = readOf(useEntryReport(address, entry));
return (
{back}
@@ -564,7 +541,7 @@ function Objectives({ objectives }: { objectives: WorkstreamEntry["objectives"]
}
/** The worker a workstream's lead talks through: its worker on the user's roster, on the flow the roster names. */
-function leadWorker(entry: WorkstreamEntry, roster: ReturnType, workers: readonly Worker[]): Worker | undefined {
+function leadWorker(entry: WorkstreamEntry, roster: RosterRead, workers: readonly Worker[]): Worker | undefined {
const onRoster = roster !== undefined && "entries" in roster ? roster.entries.find((r: RosterEntry) => r.id === entry.lead) : undefined;
if (onRoster === undefined) return undefined;
return workers.find((worker) => worker.id === entry.lead && worker.kind === onRoster.flow);
@@ -580,7 +557,7 @@ function OwnBoards({
workers,
}: {
entries: readonly WorkstreamEntry[];
- roster: ReturnType;
+ roster: RosterRead;
workers: readonly Worker[];
}) {
const { client } = useLab();
diff --git a/packages/shift-manager/src/surfaces/Resource.tsx b/packages/shift-manager/src/surfaces/Resource.tsx
index 02c3cbc60c..fa423e5d8e 100644
--- a/packages/shift-manager/src/surfaces/Resource.tsx
+++ b/packages/shift-manager/src/surfaces/Resource.tsx
@@ -7,7 +7,7 @@
import { useEffect, useState } from "react";
import { EmptyState, SectionFailure } from "../components/ui";
import { useLab } from "../lib/lab-data";
-import { describeFailure, type Failure } from "../lib/reads";
+import { describeFailure, type Failure } from "../lib/failure";
export function ResourceView({ sessionId, resourceRef }: { sessionId: string; resourceRef: string }) {
const { client } = useLab();
diff --git a/packages/shift-manager/src/surfaces/Roster.tsx b/packages/shift-manager/src/surfaces/Roster.tsx
index 5f7c9bb8a1..ca9ae5a705 100644
--- a/packages/shift-manager/src/surfaces/Roster.tsx
+++ b/packages/shift-manager/src/surfaces/Roster.tsx
@@ -2,13 +2,13 @@
* Roster: every worker the user has, grouped on shift and off shift, for
* all teams or one (`/roster[?team=]`). The workers are the user's roster,
* read through Workforce's client: their own workers and the standard ones, each on the flow it names. A standard worker's row is the
- * worker inventory's. The roster is read again with every snapshot, so a worker
- * hired or fired on a turn shows on the next read.
+ * worker inventory's. Both are followed (`directory.tsx`), so a worker hired
+ * or fired on a turn shows when the roster hears it.
*
* Every status, slot and count is read from the one `workerStates` result over
- * the snapshot, the same one the sidebar and Shift Coordinator draw, so a
- * worker reads the same everywhere. Nothing is polled: Roster draws the
- * snapshot and says when it was read.
+ * the directory and the Inbox view, the same one the sidebar and Shift
+ * Coordinator draw, so a worker reads the same everywhere, and its status
+ * moves when the Inbox does. Roster says when the directory was read.
*
* In design v2's form (v2:693-725): a column header, each group's heading
* with what its status means, and WAITING ON YOU as boxed tags, a task or an
@@ -16,10 +16,10 @@
*/
import { useSyncExternalStore } from "react";
import { PartialMark, ScreenTitle, SectionFailure, ShiftMark } from "../components/ui";
-import { shiftCoordinatorOf, pickedTeam, workerLabel, workerStates, SHIFT_STATUSES, shiftCounts, teamsOf, type LoadedSnapshot, type WorkerState, type ShiftStatus } from "../lib/derive";
+import { shiftCoordinatorOf, pickedTeam, workerLabel, workerStates, SHIFT_STATUSES, shiftCounts, teamsOf, type WorkerState, type ShiftStatus } from "../lib/shift";
import { themeLabel, type ThemeLook } from "../lib/theme";
-import { useLab } from "../lib/lab-data";
-import { useRoster, withRoster } from "../lib/roster";
+import { useWorkers } from "../lib/directory";
+import { askWord, useInbox } from "../lib/inbox";
import { navigate } from "../lib/routes";
import { RouteLink } from "../components/RouteLink";
import type { Gaps } from "../gaps";
@@ -150,39 +150,31 @@ function WorkerRow({ state, gaps, own }: { state: WorkerState; gaps: Gaps; own:
{waitsOnYou.map((row) => (
))}
- {asks.map((ask) => (
-
+ {asks.map((hold) => (
+
))}
);
}
-export function RosterView({
- snapshot,
- team: asked,
- gaps,
- look,
-}: {
- snapshot: LoadedSnapshot;
- team: string | null;
- gaps: Gaps;
- look?: ThemeLook;
-}) {
- const { refresh } = useLab();
+export function RosterView({ team: asked, gaps, look }: { team: string | null; gaps: Gaps; look?: ThemeLook }) {
const lookName = useLookName(look);
- const roster = useRoster();
- const { snapshot: withOwn, workers, own } = withRoster(snapshot, roster);
- if (!snapshot.inventory.ok && workers.length === 0) {
+ const { inventory, workers, own, roster, readAt, refresh } = useWorkers();
+ const inbox = useInbox();
+ if (inventory === undefined) {
+ return
- ))}
{SHIFT_STATUSES.map((status) => {
const group = shown.filter((s) => s.status === status);
if (group.length === 0) return null;
diff --git a/packages/shift-manager/src/surfaces/Routines.tsx b/packages/shift-manager/src/surfaces/Routines.tsx
index 138891403f..c213e76603 100644
--- a/packages/shift-manager/src/surfaces/Routines.tsx
+++ b/packages/shift-manager/src/surfaces/Routines.tsx
@@ -9,8 +9,9 @@
*/
import { useState } from "react";
import { EmptyState, Meta, ScreenTitle, SectionFailure } from "../components/ui";
-import { workerLabel, type LoadedSnapshot } from "../lib/derive";
-import { useRoutines, type Routine, type RoutineChange } from "../lib/routines";
+import type { ListedRoutine } from "@flow-state-dev/workforce/browser";
+import { workerLabel } from "../lib/shift";
+import { clockOf, eventOf, taskOf, useRoutines, type RoutineChange } from "../lib/routines";
/** When a clock routine is next due, in the page's time zone: weekday, date and 24-hour time. */
export function nextRunLabel(nextRunAt: string | null, paused: boolean): string {
@@ -27,14 +28,17 @@ export function nextRunLabel(nextRunAt: string | null, paused: boolean): string
}
/** Who made a routine, as the list says it. */
-export function madeByLabel(madeBy: Routine["madeBy"]): string {
- if (madeBy === null) return "";
+export function madeByLabel(madeBy: ListedRoutine["madeBy"]): string {
+ if (madeBy === undefined) return "";
if (madeBy.by === "user") return "made by you";
if (madeBy.by === "worker") return `made by ${workerLabel(madeBy.worker)}`;
return "the app's";
}
-function RoutineLine({ routine, change }: { routine: Routine; change: RoutineChange }) {
+function RoutineLine({ routine, change }: { routine: ListedRoutine; change: RoutineChange }) {
+ const clock = clockOf(routine);
+ const event = eventOf(routine);
+ const { goal, assignee } = taskOf(routine);
const [busy, setBusy] = useState(false);
const [problem, setProblem] = useState(undefined);
const run = (wanted: Parameters[0]) => {
@@ -45,12 +49,13 @@ function RoutineLine({ routine, change }: { routine: Routine; change: RoutineCha
setProblem(why);
});
};
- const when = routine.clock !== null ? nextRunLabel(routine.clock.nextRunAt, routine.paused) : routine.paused ? "paused" : "on each event";
- const title = routine.description ?? (routine.clock !== null ? (routine.goal ?? routine.name) : (routine.event?.interest ?? routine.name));
+ const when = clock !== null ? nextRunLabel(clock.nextRunAt, routine.paused) : routine.paused ? "paused" : "on each event";
+ // An empty description is none, as the list has always read it.
+ const title = (routine.description || null) ?? (clock !== null ? (goal ?? routine.name) : (event?.interest ?? routine.name));
const detail =
- routine.clock !== null
- ? `${workerLabel(routine.worker)}'s board${routine.assignee === null ? "" : ` → ${workerLabel(routine.assignee)}`} · ${routine.clock.cron} · ${routine.clock.timezone}`
- : `${routine.event!.thread}${routine.event!.kinds === null ? "" : ` · ${routine.event!.kinds.join(", ")}`} · heard by ${workerLabel(routine.worker)}`;
+ clock !== null
+ ? `${workerLabel(routine.worker)}'s board${assignee === null ? "" : ` → ${workerLabel(assignee)}`} · ${clock.cron} · ${clock.timezone}`
+ : `${event!.thread}${event!.kinds === null ? "" : ` · ${event!.kinds.join(", ")}`} · heard by ${workerLabel(routine.worker)}`;
const maker = madeByLabel(routine.madeBy);
const declared = routine.madeBy?.by === "app";
return (
@@ -58,8 +63,8 @@ function RoutineLine({ routine, change }: { routine: Routine; change: RoutineCha
className="grid grid-cols-[minmax(9rem,max-content)_1fr_max-content] items-baseline gap-x-4 border-b border-foreground/10 py-2"
data-testid="routine"
data-id={routine.id}
- data-trigger={routine.clock !== null ? "clock" : "event"}
- data-next-run={routine.clock?.nextRunAt ?? ""}
+ data-trigger={clock !== null ? "clock" : "event"}
+ data-next-run={clock?.nextRunAt ?? ""}
data-paused={routine.paused}
>
@@ -99,8 +104,8 @@ function RoutineLine({ routine, change }: { routine: Routine; change: RoutineCha
);
}
-export function Routines({ snapshot }: { snapshot: LoadedSnapshot }) {
- const { routines, failure, reread, change } = useRoutines(snapshot.readAt);
+export function Routines() {
+ const { routines, failure, reread, change } = useRoutines();
return (
diff --git a/packages/shift-manager/src/surfaces/SessionView.tsx b/packages/shift-manager/src/surfaces/SessionView.tsx
index 800bc0e4f1..d8efc92ef6 100644
--- a/packages/shift-manager/src/surfaces/SessionView.tsx
+++ b/packages/shift-manager/src/surfaces/SessionView.tsx
@@ -3,8 +3,8 @@
* typed here stays in it. A worker the inventory doesn't register is drawn
* read-only: its door isn't known. So is a task's session or a delegate's session for another conversation,
* whatever the worker: a line typed there would be task input.
- * A session the snapshot doesn't list yet (one a message opened after the
- * last Lab read) is looked up in a fresh listing first.
+ * A session the page's session list doesn't hold yet (one a message opened
+ * a moment ago) is looked up in a fresh listing first.
*/
import { useEffect, useState } from "react";
import type { SessionSummary } from "@flow-state-dev/client";
@@ -12,9 +12,10 @@ import { FILING_SESSION_STATE_KEY, TASK_ID_STATE_KEY } from "@flow-state-dev/wor
import { Conversation } from "../components/Conversation";
import { EmptyState } from "../components/ui";
import type { Gaps } from "../gaps";
-import { workerLabel, type LoadedSnapshot } from "../lib/derive";
+import { workerLabel } from "../lib/shift";
import { useLab } from "../lib/lab-data";
-import { workerOf, type Worker } from "../lib/reads";
+import { useSessions, useWorkers } from "../lib/directory";
+import { workerOf, type Worker } from "../lib/workers";
/** Why a line can't go to `session`, or `undefined` when it can: a task's session and a delegate's session for another conversation take task input only. */
function readOnlyReason(session: SessionSummary): string | undefined {
@@ -24,13 +25,15 @@ function readOnlyReason(session: SessionSummary): string | undefined {
return undefined;
}
-export function SessionView({ snapshot, sessionId, gaps }: { snapshot: LoadedSnapshot; sessionId: string; gaps: Gaps }) {
+export function SessionView({ sessionId, gaps }: { sessionId: string; gaps: Gaps }) {
const { client } = useLab();
- const listed = snapshot.sessions.find((s) => s.id === sessionId);
+ const { workers } = useWorkers();
+ const sessions = useSessions().list;
+ const listed = sessions?.find((s) => s.id === sessionId);
// `undefined` while the fresh listing is read; `null` when it doesn't hold the session either.
const [fresh, setFresh] = useState<{ sessionId: string; session: SessionSummary | null } | undefined>(undefined);
useEffect(() => {
- if (listed !== undefined) return;
+ if (sessions === undefined || listed !== undefined) return;
let closed = false;
client.sessions
.list({ userId: client.userId, include: "dispatch-runs" })
@@ -41,10 +44,10 @@ export function SessionView({ snapshot, sessionId, gaps }: { snapshot: LoadedSna
return () => {
closed = true;
};
- }, [client, sessionId, listed]);
+ }, [client, sessionId, sessions, listed]);
const looked = fresh?.sessionId === sessionId ? fresh.session : undefined;
const session = listed ?? looked ?? undefined;
- if (session === undefined && looked === undefined) {
+ if (sessions === undefined || (session === undefined && looked === undefined)) {
return (
Looking for this session…
@@ -59,7 +62,7 @@ export function SessionView({ snapshot, sessionId, gaps }: { snapshot: LoadedSna
);
}
- const registered = snapshot.inventory.ok ? snapshot.inventory.value.workers.find((w) => w.id === workerId) : undefined;
+ const registered = workers.find((w) => w.id === workerId);
const worker: Worker =
registered !== undefined && registered.kind === session.flowKind
? registered
@@ -70,7 +73,7 @@ export function SessionView({ snapshot, sessionId, gaps }: { snapshot: LoadedSna
testId="session"
worker={worker}
session={sessionId}
- sessions={listed === undefined ? [...snapshot.sessions, session] : snapshot.sessions}
+ sessions={listed === undefined ? [...sessions, session] : sessions}
gaps={gaps}
name={workerLabel(workerId)}
readOnly={readOnlyReason(session)}
diff --git a/packages/shift-manager/src/surfaces/Settings.tsx b/packages/shift-manager/src/surfaces/Settings.tsx
index dfae62c20b..bcc992f43b 100644
--- a/packages/shift-manager/src/surfaces/Settings.tsx
+++ b/packages/shift-manager/src/surfaces/Settings.tsx
@@ -7,19 +7,15 @@
* Lab has taken it. A key is the user's alone. A coding run on a project that
* names the server reaches it with the key of the user the run works for.
*/
-import { useCallback, useEffect, useState } from "react";
+import { useState } from "react";
+import type { ConnectorKeyStatus } from "@flow-state-dev/workforce/browser";
import { EmptyState, SectionFailure } from "../components/ui";
import { useLab } from "../lib/lab-data";
-import { readMcpKeys, writeMcpKey, type McpKeysRead, type McpServerKey } from "../lib/mcp-credentials";
-import type { Failure } from "../lib/reads";
+import { useMcpKeys, writeMcpKey } from "../lib/mcp-credentials";
+import type { Failure } from "../lib/failure";
export function SettingsView() {
- const { connection } = useLab();
- const [read, setRead] = useState(undefined);
- const reread = useCallback(() => {
- void readMcpKeys(connection).then(setRead);
- }, [connection]);
- useEffect(reread, [reread]);
+ const { read, reread } = useMcpKeys();
return (
@@ -53,7 +49,7 @@ export function SettingsView() {
}
/** One server: whether the key is set, a field to set or replace it, and Clear. */
-function ServerKey({ server, onChanged }: { server: McpServerKey; onChanged: () => void }) {
+function ServerKey({ server, onChanged }: { server: ConnectorKeyStatus; onChanged: () => void }) {
const { connection } = useLab();
const [draft, setDraft] = useState("");
const [busy, setBusy] = useState(false);
diff --git a/packages/shift-manager/src/surfaces/ShiftCoordinator.tsx b/packages/shift-manager/src/surfaces/ShiftCoordinator.tsx
index cd06896580..f8ca747fd9 100644
--- a/packages/shift-manager/src/surfaces/ShiftCoordinator.tsx
+++ b/packages/shift-manager/src/surfaces/ShiftCoordinator.tsx
@@ -5,7 +5,7 @@
* panel lists its delegates and tasks.
*
* **The summary is Shift Manager's, not the worker's (D1).** It is drawn from
- * the one snapshot, with the helpers Inbox and Tasks use, so its numbers are
+ * the Inbox view, with the helpers Inbox and Tasks use, so its numbers are
* theirs. Each ask is drawn by Inbox's card and answered through Inbox's path,
* so answering it in either place clears both.
*
@@ -13,8 +13,7 @@
* the Shift Coordinator is one rule, `shiftCoordinatorOf`. A line goes in through the
* worker's door by the one send path, and shows *delivered* only once the
* session holds it. What is drawn below it is what the session stores, read
- * back when the view opens and after each line, never on the snapshot's
- * refresh. Nothing is drawn in the worker's voice that its session doesn't hold.
+ * back when the view opens and after each line, then followed live. Nothing is drawn in the worker's voice that its session doesn't hold.
*
* **Drawn in design v2's form (v2:120-180).** A 720px feed under v2's header,
* the summary as unboxed prose with its asks in one bordered list, each
@@ -33,37 +32,39 @@ import { TasksPanel } from "../components/TasksPanel";
import { COORDINATOR_FLOW, useConversationSession } from "../lib/conversation";
import { useSessionItems } from "../components/flow-state/session-items-context";
import { ItemRenderer } from "@flow-state-dev/react";
-import { AsOf, ASKING_CLASS, Meta, PartialMark, ScreenTitle, SectionFailure, ShiftMark } from "../components/ui";
-import { cn } from "../lib/utils";
+import { AsOf, Meta, ScreenTitle, SectionFailure } from "../components/ui";
import { clearHandedLine, useHandedLine } from "../lib/outbox";
import { delegatesViewRef } from "@flow-state-dev/workforce/browser";
import { useView } from "@flow-state-dev/react";
import { starterLines, type StarterDelegate } from "../lib/first-run";
-import { useRoster } from "../lib/roster";
-import { shiftCoordinatorOf, workerLabel, workerStates, type LoadedSnapshot } from "../lib/derive";
+import { shiftCoordinatorOf, workerLabel, workerStates } from "../lib/shift";
import { everyAsk, itemIdHolding, openBoardTasks, useInbox } from "../lib/inbox";
import { workerOfHold } from "../lib/inbox-list";
import { useLab } from "../lib/lab-data";
+import { useSessions, useWorkers } from "../lib/directory";
import type { SessionSummary } from "@flow-state-dev/client";
-import type { Worker } from "../lib/reads";
+import type { Worker } from "../lib/workers";
import { RouteLink } from "../components/RouteLink";
import { startShiftCoordinatorWork, useShiftCoordinatorWorking } from "../lib/working";
import type { Gaps } from "../gaps";
const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
+/** No sessions, while the list is read. */
+const NO_SESSIONS: readonly SessionSummary[] = [];
+
// FIX-1747.
/** What Shift Manager calls the `shift-coordinator` worker. */
const NAME = "Shift Coordinator";
-export function ShiftCoordinatorView({ snapshot, gaps }: { snapshot: LoadedSnapshot; gaps: Gaps }) {
+export function ShiftCoordinatorView({ gaps }: { gaps: Gaps }) {
const lead = (
<>
-
-
+
+
>
);
- return ;
+ return ;
}
/**
@@ -72,16 +73,17 @@ export function ShiftCoordinatorView({ snapshot, gaps }: { snapshot: LoadedSnaps
* a line from this page (v2:1424). When there is one Shift Coordinator, a gear at
* the end opens that worker's settings, on any flow.
*/
-function Header({ snapshot }: { snapshot: LoadedSnapshot }) {
+function Header() {
const working = useShiftCoordinatorWorking();
+ const { inventory, workers } = useWorkers();
+ const inbox = useInbox().section;
let status: string | undefined;
let watching: string | null = null;
let workerId: string | undefined;
- if (snapshot.inventory.ok) {
- const { workers } = snapshot.inventory.value;
+ if (inventory?.ok === true) {
const shiftCoordinator = shiftCoordinatorOf(workers);
workerId = shiftCoordinator.kind === "one" ? shiftCoordinator.worker.id : undefined;
- status = workerId === undefined ? undefined : workerStates(snapshot).workers.get(workerId)?.status;
+ status = workerId === undefined ? undefined : workerStates(workers, inbox?.ok === true ? inbox.value : undefined).workers.get(workerId)?.status;
watching = `watching ${plural(workers.length, "worker", "workers")}`;
}
return (
@@ -139,14 +141,10 @@ function NeedsYouTag() {
* (v2:135-136), with the asks as v2's one bordered list (v2:138-153). The
* label says whose summary it is: Shift Manager's, not the worker's.
*/
-function ShiftSummary({ snapshot }: { snapshot: LoadedSnapshot }) {
- const { refresh, asking } = useLab();
- // FIX-2774: what needs the user, the asks and the runs are the inbox view's; *refresh* reads it and the Lab again.
+function ShiftSummary() {
+ // FIX-2774: what needs the user, the asks and the runs are the inbox view's; *refresh* reads it again.
const view = useInbox();
- const retry = () => {
- view.refresh();
- void refresh();
- };
+ const retry = view.refresh;
if (view.section === undefined) {
return (
@@ -168,7 +166,7 @@ function ShiftSummary({ snapshot }: { snapshot: LoadedSnapshot }) {
-
+ {view.readAt === undefined ? null : }
{inbox.ok && asks.length > 0 ? (
{asks.map((ask, i) => (
@@ -224,17 +222,28 @@ function ShiftSummary({ snapshot }: { snapshot: LoadedSnapshot }) {
// BR-10 to BR-12.
/** The conversation, or the named state in its place, under `lead`. */
-function ShiftCoordinatorConversation({ snapshot, gaps, lead }: { snapshot: LoadedSnapshot; gaps: Gaps; lead: ReactNode }) {
- const { refresh } = useLab();
- if (!snapshot.inventory.ok) {
+function ShiftCoordinatorConversation({ gaps, lead }: { gaps: Gaps; lead: ReactNode }) {
+ const { inventory, workers, refresh } = useWorkers();
+ const sessions = useSessions().list;
+ if (inventory === undefined || sessions === undefined) {
+ return (
+
+ {lead}
+
+ Reading your workers…
+
+
+ );
+ }
+ if (!inventory.ok) {
return (
{lead}
- void refresh()} testId="shift-coordinator-worker-failure" />
+
);
}
- const shiftCoordinator = shiftCoordinatorOf(snapshot.inventory.value.workers);
+ const shiftCoordinator = shiftCoordinatorOf(workers);
if (shiftCoordinator.kind === "none") {
return (
@@ -262,7 +271,7 @@ function ShiftCoordinatorConversation({ snapshot, gaps, lead }: { snapshot: Load
);
}
return (
-
+
);
}
@@ -346,7 +355,7 @@ function Talk({
function useStarterLines(worker: Worker, sessions: readonly SessionSummary[]): string[] {
const { client } = useLab();
const sessionId = useConversationSession(worker, sessions);
- const rosterRead = useRoster();
+ const rosterRead = useWorkers().roster;
const coordinator = sessionId !== null && worker.kind === COORDINATOR_FLOW;
const ref = useMemo(() => delegatesViewRef(COORDINATOR_FLOW), []);
const { value: list } = useView(ref, {}, { client, enabled: coordinator, ...(sessionId !== null ? { sessionId } : {}) });
@@ -363,11 +372,13 @@ function useStarterLines(worker: Worker, sessions: readonly SessionSummary[]): s
* The right panel at Shift Coordinator: the delegates and tasks of a Shift Coordinator on the coordinator flow.
* Its standing rules are on its settings page, behind the header's gear.
*/
-export function ShiftCoordinatorPanel({ snapshot }: { snapshot: LoadedSnapshot }) {
- const found = snapshot.inventory.ok ? shiftCoordinatorOf(snapshot.inventory.value.workers) : undefined;
+export function ShiftCoordinatorPanel() {
+ const { inventory, workers } = useWorkers();
+ const sessions = useSessions().list;
+ const found = inventory?.ok === true ? shiftCoordinatorOf(workers) : undefined;
const one = found?.kind === "one" ? found.worker : undefined;
const shiftCoordinator = one?.kind === COORDINATOR_FLOW ? one : undefined;
- const conversation = useConversationSession(shiftCoordinator, snapshot.sessions);
+ const conversation = useConversationSession(shiftCoordinator, sessions ?? NO_SESSIONS);
return (
{shiftCoordinator !== undefined ? (
diff --git a/packages/shift-manager/src/surfaces/Sidebar.tsx b/packages/shift-manager/src/surfaces/Sidebar.tsx
index aa9ba3a320..a204047133 100644
--- a/packages/shift-manager/src/surfaces/Sidebar.tsx
+++ b/packages/shift-manager/src/surfaces/Sidebar.tsx
@@ -5,9 +5,10 @@
* with the ⌘K tip and the on-shift count. A header above them all carries
* the mark, which changes the theme with a click, and names the theme.
*
- * Every entry is drawn from the one snapshot, so a count and the screen it
- * opens always agree; every status and status count from its one
- * `workerStates` result, so they agree with Roster. PROJECTS lists each project,
+ * Every count is drawn from the read its screen draws, so a count and the
+ * screen it opens always agree; every status and status count from its one
+ * `workerStates` result over the directory and the Inbox view, so they agree
+ * with Roster. PROJECTS lists each project,
* its workstreams beneath it while it is open, read as its view reads them;
* TEAMS is one row per
* team with a status square per worker, the user's own workers included,
@@ -31,14 +32,14 @@ import { useState, useSyncExternalStore, type ReactNode } from "react";
import { themeLabel, type ThemeLook } from "../lib/theme";
import type { Route } from "../lib/routes";
import { useLab } from "../lib/lab-data";
-import { useRoster, withRoster } from "../lib/roster";
-import { projectsOf, workerLabel, workerStates, shiftCounts, teamsOf, type LoadedSnapshot } from "../lib/derive";
+import { useProjects, useWorkers } from "../lib/directory";
+import { workerLabel, workerStates, shiftCounts, teamsOf } from "../lib/shift";
import { openBoardTasks, useInbox } from "../lib/inbox";
-import { useProjectRead, type WorkstreamEntry } from "../lib/projects";
-import type { Project } from "../lib/reads";
+import { useProjectWorkstreams, type WorkstreamEntry } from "../lib/projects";
+import type { Project } from "../lib/project";
import { initialsOf } from "../lib/shell";
import { useShiftCoordinatorWorking } from "../lib/working";
-import { ASKING_CLASS, Meta, PartialMark, SectionFailure, ShiftMark } from "../components/ui";
+import { Meta, PartialMark, SectionFailure, ShiftMark } from "../components/ui";
import { ShiftManagerMark } from "../components/ShiftManagerMark";
import { RouteLink } from "../components/RouteLink";
import type { Gaps } from "../gaps";
@@ -279,24 +280,14 @@ function SidebarRail({
* Only an open project's entries are read, by its one prefix, as its view
* reads them; a closed one costs nothing.
*/
-function ProjectGroup({
- project,
- route,
- readAt,
-}: {
- project: Project;
- route: Route;
- readAt: number;
-}) {
+function ProjectGroup({ project, route }: { project: Project; route: Route }) {
// `null` follows the route; a toggle overrides it.
const [toggled, setToggled] = useState(null);
const { id, title, visibility } = project;
// A project's address is its visibility and its id: a private project and a shared one can share an id.
const here = route.level === "project" && route.projectId === id && (route.visibility ?? "shared") === visibility;
const open = toggled ?? here;
- const { read, reread } = useProjectRead({ visibility, id }, open, readAt);
const testId = visibility === "private" ? `nav-project-private-${id}` : `nav-project-${id}`;
- const entries = read !== undefined && "value" in read && read.value !== null ? read.value.entries : undefined;
const to = (entry?: { owner: string; id: string }): Route => ({
level: "project",
projectId: id,
@@ -326,30 +317,38 @@ function ProjectGroup({
/>