From fe485fcdf6e02dfd5ba5c9e5a46473ef6481518b Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 00:02:58 +0000
Subject: [PATCH 01/24] wip(shift-manager): FIX-2775 screens off the snapshot
---
packages/react/src/internal.ts | 5 +-
packages/shift-manager/src/App.tsx | 120 +++---
.../src/components/Conversation.tsx | 27 +-
.../src/components/CoordinatorRoute.tsx | 2 +-
.../src/components/DelegatesPanel.tsx | 11 +-
.../src/components/ReceivedMessage.tsx | 2 +-
.../src/components/TaskBoardMeta.tsx | 17 +-
.../src/components/TasksPanel.tsx | 5 +-
packages/shift-manager/src/components/ui.tsx | 4 +-
packages/shift-manager/src/lib/boards.ts | 30 ++
.../shift-manager/src/lib/conversation.ts | 30 +-
packages/shift-manager/src/lib/deliver.ts | 2 +-
.../shift-manager/src/lib/directory-reads.ts | 74 ++++
packages/shift-manager/src/lib/directory.tsx | 150 ++++++++
packages/shift-manager/src/lib/documents.ts | 77 ++++
packages/shift-manager/src/lib/failure.ts | 18 +
packages/shift-manager/src/lib/gate.ts | 67 ++++
packages/shift-manager/src/lib/inbox.ts | 45 ++-
.../shift-manager/src/lib/mcp-credentials.ts | 28 +-
packages/shift-manager/src/lib/messages.ts | 84 ++---
packages/shift-manager/src/lib/projects.ts | 357 +++++++++---------
packages/shift-manager/src/lib/roster.ts | 140 ++-----
packages/shift-manager/src/lib/routines.ts | 111 ++----
packages/shift-manager/src/lib/rules.ts | 2 +-
packages/shift-manager/src/lib/shift.ts | 198 ++++++++++
packages/shift-manager/src/lib/task.tsx | 2 +-
packages/shift-manager/src/lib/tasks.ts | 14 +-
packages/shift-manager/src/lib/usage.ts | 226 ++++-------
packages/shift-manager/src/lib/workers.ts | 160 ++++++++
packages/shift-manager/src/lib/workforce.ts | 18 +-
packages/shift-manager/src/surfaces/Inbox.tsx | 22 +-
.../shift-manager/src/surfaces/JumpTo.tsx | 35 +-
.../shift-manager/src/surfaces/Messages.tsx | 6 +-
.../shift-manager/src/surfaces/Project.tsx | 211 +++++------
.../shift-manager/src/surfaces/Resource.tsx | 2 +-
.../shift-manager/src/surfaces/Roster.tsx | 62 ++-
.../shift-manager/src/surfaces/Routines.tsx | 33 +-
.../src/surfaces/SessionView.tsx | 25 +-
.../shift-manager/src/surfaces/Settings.tsx | 16 +-
.../src/surfaces/ShiftCoordinator.tsx | 81 ++--
.../shift-manager/src/surfaces/Sidebar.tsx | 125 +++---
.../shift-manager/src/surfaces/TaskFrame.tsx | 40 +-
.../src/surfaces/TaskInspector.tsx | 11 +-
.../src/surfaces/TaskSession.tsx | 3 +-
packages/shift-manager/src/surfaces/Tasks.tsx | 21 +-
packages/shift-manager/src/surfaces/Usage.tsx | 11 +-
.../src/surfaces/WorkerSettings.tsx | 9 +-
47 files changed, 1634 insertions(+), 1105 deletions(-)
create mode 100644 packages/shift-manager/src/lib/boards.ts
create mode 100644 packages/shift-manager/src/lib/directory-reads.ts
create mode 100644 packages/shift-manager/src/lib/directory.tsx
create mode 100644 packages/shift-manager/src/lib/documents.ts
create mode 100644 packages/shift-manager/src/lib/failure.ts
create mode 100644 packages/shift-manager/src/lib/gate.ts
create mode 100644 packages/shift-manager/src/lib/shift.ts
create mode 100644 packages/shift-manager/src/lib/workers.ts
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/shift-manager/src/App.tsx b/packages/shift-manager/src/App.tsx
index f2ec0ac6fc..884344073d 100644
--- a/packages/shift-manager/src/App.tsx
+++ b/packages/shift-manager/src/App.tsx
@@ -8,19 +8,20 @@
* 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 { 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, useProjects, useWorkers } from "./lib/directory";
+import { useGate } from "./lib/gate";
import { ConnectionBanner } from "./components/flow-state/connection-banner";
import { ConnectionScreen } from "./components/flow-state/connection-screen";
import { ResourceView } from "./surfaces/Resource";
@@ -69,10 +70,42 @@ function LabSessionFeeds({ children }: { children: ReactNode }) {
}
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 the Lab…
;
+ }
+ 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 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 route = useRoute();
// Null is closed; "" opens Jump to, MESSAGE_PREFIX opens it already in message mode.
const [jumping, setJumping] = useState(null);
@@ -90,49 +123,30 @@ 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.
refreshInbox();
- void refresh();
+ refreshWorkers();
+ refreshProjects();
}
};
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]);
const levels = (
<>
-
+
-
+
>
);
return (
@@ -153,38 +167,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 +222,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 +236,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 a615529b1e..67be74e443 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";
@@ -135,12 +136,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 });
@@ -148,12 +149,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 it never draws
// are left out, so a session holding only those (a standing-rules read writes a state change into
// it before any line is sent) counts as empty.
@@ -211,10 +206,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..0aaf8f8808 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}. */
@@ -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..9d7736672d 100644
--- a/packages/shift-manager/src/components/ui.tsx
+++ b/packages/shift-manager/src/components/ui.tsx
@@ -9,9 +9,9 @@
*/
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";
/**
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..97afbc2a9d 100644
--- a/packages/shift-manager/src/lib/conversation.ts
+++ b/packages/shift-manager/src/lib/conversation.ts
@@ -8,7 +8,7 @@
* `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.
@@ -19,7 +19,8 @@ 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,19 +73,24 @@ 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();
+ const workforce = useWorkforce();
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(
+ workforce
+ .organization()
+ .then((orgId) => derivedIdOf(`${key}\n${orgId}`, { userId: client.userId, orgId, flow, criteria: { worker: id } }))
+ .then(
(sessionId) => {
if (!closed) setDerived({ key, id: sessionId });
},
@@ -95,12 +101,12 @@ function useDerivedId(worker: Pick | undefined): Derived
return () => {
closed = true;
};
- }, [key, client.userId, orgId, flow, id]);
+ }, [key, workforce, 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 +114,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 +132,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/directory-reads.ts b/packages/shift-manager/src/lib/directory-reads.ts
new file mode 100644
index 0000000000..957a694f62
--- /dev/null
+++ b/packages/shift-manager/src/lib/directory-reads.ts
@@ -0,0 +1,74 @@
+/**
+ * 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 } 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 "./projects";
+import { useRoster, type RosterRead } from "./roster";
+import { toWorker, type Worker } from "./workers";
+
+/** One whole-collection read: its rows once read (`undefined` before), why the last read failed, and a read on demand. */
+export type CollectionRead = { rows: T[] | 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. */
+ sessions: { list: readonly SessionSummary[] | undefined; refresh: () => void };
+ /** 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 rows, each parsed by `parse` (one that doesn't parse is left out), held while the read's value is. */
+function useRows(
+ 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 rows = useMemo(() => value?.map((entry) => parse(entry.value)).filter((row): row is T => row !== undefined), [value]);
+ const failure = useSameFailure(read.failure);
+ const refresh = read.refresh;
+ return useMemo(() => ({ rows, failure, refresh }), [rows, 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 = useRows(useResource(workerInventoryResource, { client, all: true }), toWorker);
+ const shared = useRows(useResource(projectsResource, { client, all: true }), sharedProject);
+ const own = useRows(useResource(privateProjectsResource, { client, all: true }), privateProject);
+ const roster = useRoster();
+ const listing = useSessionList({ client, includeDispatchRuns: true, includeStatus: false });
+ const listed = listing.isLoading && listing.sessions.length === 0 && listing.error === null ? undefined : listing.sessions;
+ const sessions = useMemo(() => ({ list: listed, refresh: listing.refresh }), [listed, 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..a57d4f5235
--- /dev/null
+++ b/packages/shift-manager/src/lib/directory.tsx
@@ -0,0 +1,150 @@
+// 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 worker rows 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 type { SessionSummary } from "@flow-state-dev/client";
+import { useDirectoryReads, type CollectionRead } from "./directory-reads";
+import type { Failure, Section } from "./failure";
+import type { Project } from "./projects";
+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 worker rows, the sessions and the projects. */
+type Directory = {
+ workers: Workers;
+ sessions: { list: readonly SessionSummary[] | undefined; refresh: () => void };
+ 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, 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.rows !== undefined && read.rows.length > 0) return { ok: true, value: read.rows };
+ if (read.rows !== 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 rowsOf = (read: CollectionRead): Section | undefined =>
+ read.rows !== undefined
+ ? { ok: true, value: read.rows }
+ : read.failure === undefined
+ ? undefined
+ : read.failure.httpStatus === 404
+ ? { ok: true, value: [] }
+ : { ok: false, failure: read.failure };
+ const [a, b] = [rowsOf(shared), rowsOf(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.rows !== undefined || entries !== undefined) setReadAt(Date.now());
+ }, [inventory.rows, 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 projectRows = 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: projectRows, refresh: refreshProjects } }),
+ [workers, sessions, projectRows, 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;
+}
diff --git a/packages/shift-manager/src/lib/documents.ts b/packages/shift-manager/src/lib/documents.ts
new file mode 100644
index 0000000000..f11b7f2c00
--- /dev/null
+++ b/packages/shift-manager/src/lib/documents.ts
@@ -0,0 +1,77 @@
+// 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..8a64b051c6 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, PartialMark, ScreenTitle, SectionFailure, ShiftMark } 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..43965d496c 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,13 @@ 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 Project, type WorkstreamEntry } from "../lib/projects";
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 +279,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,31 +316,39 @@ function ProjectGroup({
/>
);
}
diff --git a/packages/shift-manager/test/ask-card-review-detail.test.tsx b/packages/shift-manager/test/ask-card-review-detail.test.tsx
index 57fe372516..e93998c229 100644
--- a/packages/shift-manager/test/ask-card-review-detail.test.tsx
+++ b/packages/shift-manager/test/ask-card-review-detail.test.tsx
@@ -11,7 +11,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { fakeLabClient, reviewHold } from "./helpers/ask-hold";
let lab = fakeLabClient(undefined);
-vi.mock("../src/lib/lab-data", () => ({ useLab: () => ({ client: lab.client, noteAnswered: () => {} }) }));
+vi.mock("../src/lib/lab-data", () => ({ useLab: () => ({ client: lab.client }) }));
// The card reads the stop's data from the page's feed for the ask's session; its first read is the session's state.
vi.mock("../src/lib/session-feeds", async () => (await import("./helpers/fake-feed")).fakeFeeds([], () => lab.client.sessions.state()));
const { AskCard } = await import("../src/components/AskCard");
diff --git a/packages/shift-manager/test/ask-card-review-read.test.tsx b/packages/shift-manager/test/ask-card-review-read.test.tsx
index 93d36e130e..d26800beb0 100644
--- a/packages/shift-manager/test/ask-card-review-read.test.tsx
+++ b/packages/shift-manager/test/ask-card-review-read.test.tsx
@@ -26,7 +26,7 @@ const client = {
},
flow: () => ({ request: () => ({ answer: async (body: unknown) => void answers.push(body) }) }),
};
-vi.mock("../src/lib/lab-data", () => ({ useLab: () => ({ client, noteAnswered: () => {} }) }));
+vi.mock("../src/lib/lab-data", () => ({ useLab: () => ({ client }) }));
// The card reads the stop's data from the page's feed for the ask's session; its first read is the session's state.
vi.mock("../src/lib/session-feeds", async () => (await import("./helpers/fake-feed")).fakeFeeds([], () => client.sessions.state()));
const { AskCard } = await import("../src/components/AskCard");
diff --git a/packages/shift-manager/test/project-workstreams.test.tsx b/packages/shift-manager/test/project-workstreams.test.tsx
index 8bb5045633..1596d03f6b 100644
--- a/packages/shift-manager/test/project-workstreams.test.tsx
+++ b/packages/shift-manager/test/project-workstreams.test.tsx
@@ -451,14 +451,14 @@ describe("a project view (V8: BR-12, BR-18)", () => {
[BOB.userId, "search"],
].sort(),
);
- // The view's reads: the row by its key, and the entries by the project's one prefix. No other entry read.
- // Each read is one of each, so they come in pairs: the view's, and the sidebar's for the project on screen.
- // The Lab's own read never lists entries.
+ // The view's reads: the entries by the project's one prefix, the view's and the sidebar's for the project
+ // on screen, so they come in pairs. No other entry read. The row is the projects read the page holds
+ // (FIX-2775), so nothing reads it by its key; the Lab's own read never lists entries.
const workstreamReads = seen.filter((r) => /\/resources\/(org|user)\/workstreams\//.test(r.path));
const rowReads = seen.filter((r) => /\/resources\/(org|user)\/projects\/\*\/entries\/projects\/apollo\b/.test(r.path));
- expect(workstreamReads.length).toBeGreaterThan(0);
+ expect(workstreamReads).toHaveLength(2);
expect(workstreamReads.map((r) => r.path.replace(/^.*\?(userId=[^&]*&)?/, "?"))).toEqual(workstreamReads.map(() => "?limit=200&topicPrefix=workstreams/apollo/"));
- expect(rowReads).toHaveLength(workstreamReads.length);
+ expect(rowReads).toEqual([]);
// The Board: one lane per workstream of hers, each read from its own session; Bob's is never read.
const boardFrom = seen.length;
diff --git a/packages/shift-manager/test/shell.test.tsx b/packages/shift-manager/test/shell.test.tsx
index a382c4c736..1946378ba9 100644
--- a/packages/shift-manager/test/shell.test.tsx
+++ b/packages/shift-manager/test/shell.test.tsx
@@ -149,11 +149,15 @@ describe("the refusal (V2, BR-3)", () => {
});
await openApp("/w/ops.desk/stream", { bearer: "secret" });
await screen.findByTestId("refusal");
- expect(screen.getByTestId("refusal-message").textContent).toMatch(/401.*verified organization/);
+ // The gate is the organization read (FIX-2775): the server's answer to it, under today's words for a refusal.
+ expect(screen.getByTestId("refusal-message").textContent).toMatch(/^401 · /);
+ expect(screen.getByTestId("refusal").textContent).toContain("the request carried no verified organization");
expect(screen.queryByTestId("sidebar")).toBeNull();
expect(document.body.textContent).not.toMatch(/ops\./);
await new Promise((r) => setTimeout(r, 300));
- expect(seen).toEqual(["/api/flows/sessions"]);
+ // Nothing from the tree is read behind the refusal: the gate's identity read, and the snapshot's own
+ // first read, which nothing draws (FIX-2777 deletes it), each refused once.
+ expect([...seen].sort()).toEqual(["/api/flows/sessions", "/api/flows/workforce-roster/identity"]);
});
it("a Lab that names no organization for the user gets the refusal, never an unknown one", async () => {
diff --git a/packages/shift-manager/test/teams-roster.test.ts b/packages/shift-manager/test/teams-roster.test.ts
index 3fab4da23d..6cd0e36cb5 100644
--- a/packages/shift-manager/test/teams-roster.test.ts
+++ b/packages/shift-manager/test/teams-roster.test.ts
@@ -31,14 +31,14 @@ function clientsFor(lab: Lab): Client {
userId: "u1",
// The organization is the identity read's; the inventory is read by org scope (FIX-2624).
flow: () => ({ identity: async () => ({ userId: "u1", orgId: ORG }), createSession: async () => ({ id: "s1" }) }),
- resource: (def: { scope: string; pattern?: string }) => ({
- list: async () => ({
- items:
- def.scope === "org" && def.pattern === "inventory/workers/*"
- ? lab.workers.map((data, i) => ({ topic: `workers-${i}`, storageKey: `inventory/workers/${data.id}`, value: data, version: 1 }))
- : [],
- }),
- }),
+ resource: (def: { scope: string; pattern?: string }) => {
+ const items = () =>
+ def.scope === "org" && def.pattern === "inventory/workers/*"
+ ? lab.workers.map((data, i) => ({ topic: `workers-${i}`, storageKey: `inventory/workers/${data.id}`, value: data, version: 1 }))
+ : [];
+ // Every page is one page here: `listAll()` is what the inventory is read whole by.
+ return { list: async () => ({ items: items() }), listAll: async () => items() };
+ },
sessions: {
list: async () => [{ id: "s1", flowKind: "workforce-roster", parentSessionId: null, updatedAt: 0 }],
get: async () => ({ orgId: ORG }),
From 90017e8e595edecbecd43973587b19106489b54d Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 00:35:27 +0000
Subject: [PATCH 07/24] wip: unexport what only its module uses
---
packages/shift-manager/src/lib/gate.ts | 2 +-
packages/shift-manager/src/lib/shift.ts | 8 --------
packages/shift-manager/src/lib/workers.ts | 4 ++--
packages/shift-manager/test/helpers/directory.ts | 2 +-
4 files changed, 4 insertions(+), 12 deletions(-)
diff --git a/packages/shift-manager/src/lib/gate.ts b/packages/shift-manager/src/lib/gate.ts
index 708004492c..d11de81dff 100644
--- a/packages/shift-manager/src/lib/gate.ts
+++ b/packages/shift-manager/src/lib/gate.ts
@@ -31,7 +31,7 @@ function noOrganization(userId: string, why = "it serves no roster flow to ask i
}
/** The gate for `userId`, from one organization read's outcome. */
-export function gateOf(userId: string, read: { orgId: unknown } | { error: unknown }): Exclude {
+function gateOf(userId: string, read: { orgId: unknown } | { error: unknown }): Exclude {
if ("error" in read) {
const failure = describeFailure(read.error);
if (failure.httpStatus === 404 && failure.message === NO_ROSTER_FLOW) return { state: "refused", failure: { message: noOrganization(userId) } };
diff --git a/packages/shift-manager/src/lib/shift.ts b/packages/shift-manager/src/lib/shift.ts
index 1f7115f294..fb7ead5af0 100644
--- a/packages/shift-manager/src/lib/shift.ts
+++ b/packages/shift-manager/src/lib/shift.ts
@@ -131,14 +131,6 @@ export function doorOf(workers: readonly Worker[], flowId: string): string | nul
return workers.find((worker) => 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 is on the flow.
- */
-export function doorTakesTaskOf(workers: readonly Worker[], flowId: string): boolean {
- return workers.find((worker) => worker.kind === flowId)?.doorTakesTask ?? false;
-}
-
/**
* The teams of the directory, each with its display name and its workers, in
* first-seen order, with the org workers' General group first.
diff --git a/packages/shift-manager/src/lib/workers.ts b/packages/shift-manager/src/lib/workers.ts
index c517ad035a..1883f8bc02 100644
--- a/packages/shift-manager/src/lib/workers.ts
+++ b/packages/shift-manager/src/lib/workers.ts
@@ -76,7 +76,7 @@ export function workstreamOf(session: SessionSummary): string | null {
export const GENERAL_TEAM = "_general";
/** {@link GENERAL_TEAM}'s display name. */
-export const GENERAL_TEAM_NAME = "General";
+const GENERAL_TEAM_NAME = "General";
/**
* A worker's team and names, from its id and the display names its row
@@ -86,7 +86,7 @@ export const GENERAL_TEAM_NAME = "General";
* is everything before the first one;
* - an id with no dot is an org worker, and sits in {@link GENERAL_TEAM}.
*/
-export function workerNames(
+function workerNames(
id: string,
displayName: string | null,
teamName: string | null,
diff --git a/packages/shift-manager/test/helpers/directory.ts b/packages/shift-manager/test/helpers/directory.ts
index 476d4afed1..600eb6b968 100644
--- a/packages/shift-manager/test/helpers/directory.ts
+++ b/packages/shift-manager/test/helpers/directory.ts
@@ -20,7 +20,7 @@ type Fixed = Omit;
const held = new WeakMap();
/** The reads `snapshot` stands for; `undefined` (not yet read), a refusal or an unreachable Lab read as nothing landed. */
-export function readsOfSnapshot(snapshot: LabSnapshot | undefined, refresh: () => void): Fixed {
+function readsOfSnapshot(snapshot: LabSnapshot | undefined, refresh: () => void): Fixed {
const key = snapshot ?? held;
const found = held.get(key);
if (found !== undefined) return found;
From b06ef9911db3966110ced3b25dcd44ef41903a9d Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 00:54:18 +0000
Subject: [PATCH 08/24] wip: directory test, goal controls retargeted, shell
test waits for the page's reads
---
.../controls/gap-tabs.tsx | 3 +-
.../controls/unread.ts | 18 ++--
.../goal.md | 2 +-
.../run.mts | 4 +-
.../controls/count-queued.ts | 43 +++-----
.../controls/ignore-asks.ts | 20 ++--
.../it-shows-who-is-on-shift/goal.md | 2 +-
.../it-shows-who-is-on-shift/run.mts | 4 +-
.../shift-manager/test/directory.test.tsx | 99 +++++++++++++++++++
packages/shift-manager/test/shell.test.tsx | 3 +
10 files changed, 140 insertions(+), 58 deletions(-)
create mode 100644 packages/shift-manager/test/directory.test.tsx
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-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/goal.md b/goals/shift-manager/it-shows-who-is-on-shift/goal.md
index 51dbc24cd9..f61e911419 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
@@ -28,7 +28,7 @@
**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.
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..abe00d0034 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
@@ -27,7 +27,7 @@
* TEAMS one row per team, General first, a square per worker with its status
* filter a TEAMS row opens Roster for exactly that team
*
- * 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):
*
@@ -93,7 +93,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,
diff --git a/packages/shift-manager/test/directory.test.tsx b/packages/shift-manager/test/directory.test.tsx
new file mode 100644
index 0000000000..6090f329f0
--- /dev/null
+++ b/packages/shift-manager/test/directory.test.tsx
@@ -0,0 +1,99 @@
+// @vitest-environment happy-dom
+/**
+ * The worker directory is one read of each per page (FIX-2775 D1): however
+ * many screens draw a worker, the inventory is listed once and the roster
+ * watched once, and one change notice on the organization's topic is one read,
+ * not one per screen. The rows are the inventory joined with the roster: the
+ * user's own workers after the inventory's, a standard worker's harness off its
+ * roster entry.
+ *
+ * The client's direct read, its subscription and the roster watch are the
+ * test's; the directory's hooks and join are the app's.
+ */
+import { act, cleanup, render, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { WireNotice, WireTopic } from "@flow-state-dev/client";
+
+type Opened = { topics: readonly WireTopic[]; onChange: (notice: WireNotice | null) => void; closed: boolean };
+const opened: Opened[] = [];
+const hear = (notice: WireNotice) => opened.filter((o) => !o.closed).forEach((o) => o.onChange(notice));
+
+/** Each collection's rows, by pattern. */
+const rows: Record> = {};
+/** Every whole read made, by `:`. */
+const lists: string[] = [];
+const client = {
+ userId: "u_1",
+ resource: ({ scope, pattern }: { scope: string; pattern: string }) => ({
+ scope,
+ key: pattern,
+ list: async () => ({ items: [] }),
+ listAll: async () => {
+ lists.push(`${scope}:${pattern}`);
+ return (rows[pattern] ?? []).map((row) => ({ topic: row.storageKey, ...row, version: 1 }));
+ },
+ entry: (storageKey: string) => ({ read: async () => ({ value: (rows[pattern] ?? []).find((row) => row.storageKey === storageKey)?.value ?? null, version: 1 }) }),
+ }),
+ subscribe: (topics: readonly WireTopic[], options: { onChange: (notice: WireNotice | null) => void }) => {
+ const entry: Opened = { topics, onChange: options.onChange, closed: false };
+ opened.push(entry);
+ return { close: () => void (entry.closed = true) };
+ },
+ sessions: { list: async () => [] },
+};
+vi.mock("../src/lib/lab-data", () => ({ useLab: () => ({ client }) }));
+
+let rosterWatches = 0;
+const workforce = {
+ watchRoster: (onRoster: (entries: unknown[]) => void) => {
+ rosterWatches += 1;
+ void Promise.resolve().then(() =>
+ onRoster([
+ { id: "eng.coder", flow: "coder", standard: true, description: null, name: null, teamName: null, settings: { harness: "codex" } },
+ { id: "amber", flow: "coder", standard: false, description: null, name: "Amber", teamName: null },
+ ]),
+ );
+ return () => {};
+ },
+};
+vi.mock("../src/lib/workforce", () => ({ useWorkforce: () => workforce }));
+
+import { DirectoryProvider, useWorkers } from "../src/lib/directory";
+
+const INVENTORY = "inventory/workers/*";
+const drawn: Array = [];
+/** A screen drawing the directory's workers, as Roster, TEAMS and Jump to each do. */
+function Screen() {
+ drawn.push(useWorkers().workers.map((worker) => `${worker.id}:${worker.kind}:${worker.harness ?? "-"}`));
+ return null;
+}
+
+beforeEach(() => {
+ opened.splice(0);
+ lists.splice(0);
+ drawn.splice(0);
+ rosterWatches = 0;
+ rows[INVENTORY] = [{ storageKey: "inventory/workers/eng.coder", value: { id: "eng.coder", kind: "coder", door: "run" } }];
+});
+afterEach(cleanup);
+
+describe("the worker directory", () => {
+ it("is one inventory read and one roster watch for every screen on the page, and one read per org notice", async () => {
+ render(
+
+
+
+
+ ,
+ );
+ await waitFor(() => expect(drawn.at(-1)).toEqual(["eng.coder:coder:codex", "amber:coder:-"]));
+ expect(lists.filter((list) => list === `org:${INVENTORY}`)).toHaveLength(1);
+ expect(rosterWatches).toBe(1);
+
+ // A hire registers a worker: one notice, one read, every screen redrawn from it.
+ rows[INVENTORY] = [...rows[INVENTORY]!, { storageKey: "inventory/workers/eng.reviewer", value: { id: "eng.reviewer", kind: "agent" } }];
+ await act(async () => hear({ topic: { scope: "org", resource: "inventory/workers" }, kind: "resource" }));
+ await waitFor(() => expect(drawn.at(-1)).toEqual(["eng.coder:coder:codex", "eng.reviewer:agent:-", "amber:coder:-"]));
+ expect(lists.filter((list) => list === `org:${INVENTORY}`)).toHaveLength(2);
+ });
+});
diff --git a/packages/shift-manager/test/shell.test.tsx b/packages/shift-manager/test/shell.test.tsx
index 1946378ba9..aed91c8102 100644
--- a/packages/shift-manager/test/shell.test.tsx
+++ b/packages/shift-manager/test/shell.test.tsx
@@ -453,6 +453,9 @@ describe("Shift Coordinator (FIX-1722)", () => {
setURL(`${lab.baseUrl}${path}`);
render();
await screen.findByTestId("shift-coordinator");
+ // The screen draws before the page's reads land (FIX-2775): wait for the directory and the session list,
+ // so a case acts on the page as drawn, not on one still reading.
+ await waitFor(() => expect(screen.queryByTestId("shift-coordinator-reading")).toBeNull(), { timeout: 10_000 });
return { lab, client };
}
From 02a24f220119ae000bc136560835abf6e61ef2ec Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 01:06:22 +0000
Subject: [PATCH 09/24] wip: frame waits for the directory's first reads; keys
bound at commit; goals compile
---
.../a-runs-changes-wait-for-review/run.mts | 3 +-
.../realtime/app-views-read-on-notice/run.mts | 19 ++++----
.../run.mts | 2 +-
.../run.mts | 2 +-
.../it-opens-a-lab/controls/static-names.ts | 45 +++++++++----------
goals/shift-manager/it-opens-a-lab/run.mts | 2 +-
.../its-summary-changes-on-its-own/run.mts | 5 ++-
.../run.mts | 4 +-
packages/shift-manager/src/App.tsx | 27 ++++++++---
.../shift-manager/src/lib/directory-reads.ts | 7 ++-
packages/shift-manager/src/lib/directory.tsx | 11 +++++
.../test/snapshot-subscribe.test.tsx | 5 ++-
12 files changed, 82 insertions(+), 50 deletions(-)
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/run.mts b/goals/realtime/app-views-read-on-notice/run.mts
index 20d9712b61..9d4c0e0c65 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,9 @@ 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 { 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 ?? "";
@@ -382,18 +382,19 @@ function mountViews(on: Host, sessionId: string) {
const { snapshot, refresh } = useLab();
labRead = refresh;
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(() => {
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-opens-a-lab/controls/static-names.ts b/goals/shift-manager/it-opens-a-lab/controls/static-names.ts
index 69d23680dd..b56f2f519f 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.rows;
+ 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/run.mts b/goals/shift-manager/it-opens-a-lab/run.mts
index 1e86edb5c7..7ecae12fc4 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") };
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/shift-manager/src/App.tsx b/packages/shift-manager/src/App.tsx
index 884344073d..d7d7958bef 100644
--- a/packages/shift-manager/src/App.tsx
+++ b/packages/shift-manager/src/App.tsx
@@ -15,12 +15,12 @@
* 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 { LabProvider, useLab } from "./lib/lab-data";
-import { DirectoryProvider, useProjects, useWorkers } from "./lib/directory";
+import { DirectoryProvider, useDirectoryLanded, useProjects, useWorkers } from "./lib/directory";
import { useGate } from "./lib/gate";
import { ConnectionBanner } from "./components/flow-state/connection-banner";
import { ConnectionScreen } from "./components/flow-state/connection-screen";
@@ -69,11 +69,16 @@ function LabSessionFeeds({ children }: { children: ReactNode }) {
return {children};
}
+/** What the page draws while the Lab is first read. */
+const READING = (
+
;
- }
+ if (gate.state === "reading") return READING;
if (gate.state === "refused") {
return (
@@ -93,11 +98,18 @@ function Shell({ gaps, devtoolUrl, look }: { gaps: Gaps; devtoolUrl: string | un
// 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. */
+function Landed({ children }: { children: ReactNode }) {
+ return useDirectoryLanded() ? children : READING;
+}
+
/** 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();
@@ -115,7 +127,8 @@ function Frame({ 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();
diff --git a/packages/shift-manager/src/lib/directory-reads.ts b/packages/shift-manager/src/lib/directory-reads.ts
index 957a694f62..93e221be62 100644
--- a/packages/shift-manager/src/lib/directory-reads.ts
+++ b/packages/shift-manager/src/lib/directory-reads.ts
@@ -7,7 +7,7 @@
* Every one is kept current by its own notices, so nothing here re-reads on
* a whole-Lab clock.
*/
-import { useMemo } from "react";
+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";
@@ -67,7 +67,10 @@ export function useDirectoryReads(): DirectoryReads {
const own = useRows(useResource(privateProjectsResource, { client, all: true }), privateProject);
const roster = useRoster();
const listing = useSessionList({ client, includeDispatchRuns: true, includeStatus: false });
- const listed = listing.isLoading && listing.sessions.length === 0 && listing.error === null ? undefined : listing.sessions;
+ // Undefined only before the first list lands: a later read of an empty list is still a list.
+ const landed = useRef(false);
+ if (!listing.isLoading || listing.sessions.length > 0 || listing.error !== null) landed.current = true;
+ const listed = landed.current ? listing.sessions : undefined;
const sessions = useMemo(() => ({ list: listed, refresh: listing.refresh }), [listed, 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
index a57d4f5235..5c8be25816 100644
--- a/packages/shift-manager/src/lib/directory.tsx
+++ b/packages/shift-manager/src/lib/directory.tsx
@@ -148,3 +148,14 @@ export function useSessions(): Directory["sessions"] {
export function useProjects(): Directory["projects"] {
return useDirectory().projects;
}
+
+/**
+ * Whether the directory's first reads have landed, or failed: the inventory,
+ * 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. The roster
+ * isn't waited for: a screen says when it hasn't loaded.
+ */
+export function useDirectoryLanded(): boolean {
+ const { workers, sessions, projects } = useDirectory();
+ return workers.inventory !== undefined && sessions.list !== undefined && projects.section !== undefined;
+}
diff --git a/packages/shift-manager/test/snapshot-subscribe.test.tsx b/packages/shift-manager/test/snapshot-subscribe.test.tsx
index d254c64791..e118f42de5 100644
--- a/packages/shift-manager/test/snapshot-subscribe.test.tsx
+++ b/packages/shift-manager/test/snapshot-subscribe.test.tsx
@@ -55,6 +55,8 @@ vi.mock("../src/lib/workforce", () => ({ useWorkforce: () => workforce }));
// FIX-2774: the summary's needs-you numbers read the inbox view, whose own subscription isn't this test's.
/** When the view's answer last landed, as `useInbox` says it, and its refresh. */
let viewReadAt = Date.UTC(2026, 10, 4, 14, 2);
+/** The directory the page draws: one good read, as one landed. */
+let directoryShown: LabSnapshot | undefined;
const viewRefresh = vi.fn();
vi.mock("../src/lib/inbox", async (importOriginal) => {
const real = await importOriginal();
@@ -64,7 +66,7 @@ vi.mock("../src/lib/inbox", async (importOriginal) => {
// FIX-2775: the directory's reads, whose own subscriptions aren't this test's either.
vi.mock("../src/lib/directory-reads", async () => {
const { useFixedReads } = await import("./helpers/directory");
- return { useDirectoryReads: () => useFixedReads(() => undefined) };
+ return { useDirectoryReads: () => useFixedReads(() => directoryShown) };
});
let sessions: SessionSummary[] = [];
@@ -123,6 +125,7 @@ beforeEach(() => {
holdNext = false;
viewReadAt = Date.UTC(2026, 10, 4, 14, 2);
viewRefresh.mockClear();
+ directoryShown = snapshotOf();
});
afterEach(() => cleanup());
From 1c5a7fdab29174883ce09415293379688e4141da Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 01:10:10 +0000
Subject: [PATCH 10/24] wip: shell test (FIX-2775)
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiGfuuX5mPxVeUwVXfa
---
packages/shift-manager/test/shell.test.tsx | 3 ---
1 file changed, 3 deletions(-)
diff --git a/packages/shift-manager/test/shell.test.tsx b/packages/shift-manager/test/shell.test.tsx
index aed91c8102..1946378ba9 100644
--- a/packages/shift-manager/test/shell.test.tsx
+++ b/packages/shift-manager/test/shell.test.tsx
@@ -453,9 +453,6 @@ describe("Shift Coordinator (FIX-1722)", () => {
setURL(`${lab.baseUrl}${path}`);
render();
await screen.findByTestId("shift-coordinator");
- // The screen draws before the page's reads land (FIX-2775): wait for the directory and the session list,
- // so a case acts on the page as drawn, not on one still reading.
- await waitFor(() => expect(screen.queryByTestId("shift-coordinator-reading")).toBeNull(), { timeout: 10_000 });
return { lab, client };
}
From baa400f7f1d1841fcae853288c7641385eb8067e Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 01:19:31 +0000
Subject: [PATCH 11/24] test(shift-manager): usage reads wait for both answers,
not 20 ms (FIX-2775)
harnessRead slept 20 ms for whichever of Re-check and the view landed second.
The fake now counts each answer as it settles, and the helper waits for both,
then flushes the hook's update.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiGfuuX5mPxVeUwVXfa
---
packages/shift-manager/test/usage.test.ts | 18 ++++++++++++------
1 file changed, 12 insertions(+), 6 deletions(-)
diff --git a/packages/shift-manager/test/usage.test.ts b/packages/shift-manager/test/usage.test.ts
index 65472c3d2f..4bfb25e13a 100644
--- a/packages/shift-manager/test/usage.test.ts
+++ b/packages/shift-manager/test/usage.test.ts
@@ -4,7 +4,7 @@
* The rows themselves are the Lab's; these only name them. And the usage
* reads (FIX-2775): the two views, through `useView`, with Re-check first.
*/
-import { renderHook, waitFor } from "@testing-library/react";
+import { act, renderHook, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { ClientHttpError } from "@flow-state-dev/client";
import {
@@ -134,12 +134,18 @@ const STORED: HarnessUsage = {
let lab: { client: unknown };
vi.mock("../src/lib/lab-data", () => ({ useLab: () => lab }));
+/** How many Re-checks and view reads the fake has answered, resolved or refused. */
+let answered = { recheck: 0, view: 0 };
+
function fakeLab(answers: { recheck?: () => Promise; view?: () => Promise }) {
+ answered = { recheck: 0, view: 0 };
+ // Counted before the hook's own handlers run: they are chained on the promise this returns.
+ const counted = (which: keyof typeof answered, answer: () => Promise) => answer().finally(() => (answered[which] += 1));
lab = {
client: {
userId: "alice",
- resource: () => ({ send: answers.recheck ?? (async () => ({ asked: [] })) }),
- view: async () => ({ value: await (answers.view ?? (async () => ({ harnesses: [STORED], workers: [] })))(), topics: [] }),
+ resource: () => ({ send: () => counted("recheck", answers.recheck ?? (async () => ({ asked: [] }))) }),
+ view: () => counted("view", async () => ({ value: await (answers.view ?? (async () => ({ harnesses: [STORED], workers: [] })))(), topics: [] })),
// The views are kept current by their notices; none arrive here.
subscribe: () => ({ close: () => {} }),
},
@@ -154,9 +160,9 @@ const refused = (status: number, error: string) => async () => {
async function harnessRead(answers: Parameters[0]) {
fakeLab(answers);
const { result } = renderHook(() => useHarnessUsage());
- await waitFor(() => expect(result.current.rows !== undefined || result.current.failure !== undefined).toBe(true));
- // Re-check and the view settle on their own; give the other one its turn.
- await new Promise((resolve) => setTimeout(resolve, 20));
+ // Re-check and the view settle on their own: wait for both answers, then let the hook take them.
+ await waitFor(() => expect(answered.recheck > 0 && answered.view > 0).toBe(true));
+ await act(async () => {});
return result.current;
}
From d7896113c14da6ea079644b0cc75d9f7e2f021eb Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 01:22:26 +0000
Subject: [PATCH 12/24] refactor(shift-manager): the directory's reads name
entries and values, not rows (FIX-2775)
The pre-push retired-terms check reads 21 new row names on this branch: the
whole-collection read's parsed values, the parsers' arguments and the test
fixtures. Renamed to values, entries or the thing itself (a task, the stored
entries); no behaviour changes.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiGfuuX5mPxVeUwVXfa
---
.../it-opens-a-lab/controls/static-names.ts | 2 +-
.../shift-manager/src/lib/directory-reads.ts | 18 +++++------
packages/shift-manager/src/lib/directory.tsx | 22 ++++++-------
packages/shift-manager/src/lib/projects.ts | 32 +++++++++----------
packages/shift-manager/src/lib/shift.ts | 8 ++---
packages/shift-manager/src/lib/workers.ts | 18 +++++------
.../shift-manager/test/directory.test.tsx | 12 +++----
.../shift-manager/test/helpers/directory.ts | 14 ++++----
.../shift-manager/test/inventory-settings.ts | 2 +-
.../shift-manager/test/messages-view.test.tsx | 4 +--
packages/shift-manager/test/roster.test.ts | 4 +--
11 files changed, 68 insertions(+), 68 deletions(-)
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 b56f2f519f..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
@@ -26,7 +26,7 @@ declare const __STATIC_SEATS__: Array<{ id: string; kind: string }>;
/** 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.rows;
+ const stored = reads.inventory.values;
const rows = useMemo(() => {
if (stored === undefined) return undefined;
const doors = new Map(stored.map((seat) => [seat.id, seat]));
diff --git a/packages/shift-manager/src/lib/directory-reads.ts b/packages/shift-manager/src/lib/directory-reads.ts
index 93e221be62..40b8131005 100644
--- a/packages/shift-manager/src/lib/directory-reads.ts
+++ b/packages/shift-manager/src/lib/directory-reads.ts
@@ -17,8 +17,8 @@ import { toProject, type Project } from "./projects";
import { useRoster, type RosterRead } from "./roster";
import { toWorker, type Worker } from "./workers";
-/** One whole-collection read: its rows once read (`undefined` before), why the last read failed, and a read on demand. */
-export type CollectionRead = { rows: T[] | undefined; failure: Failure | undefined; refresh: () => void };
+/** 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 };
/** What the directory reads. */
export type DirectoryReads = {
@@ -42,18 +42,18 @@ function useSameFailure(failure: Failure | undefined): Failure | undefined {
);
}
-/** A whole-collection read's rows, each parsed by `parse` (one that doesn't parse is left out), held while the read's value is. */
-function useRows(
+/** 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 rows = useMemo(() => value?.map((entry) => parse(entry.value)).filter((row): row is T => row !== undefined), [value]);
+ 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(() => ({ rows, failure, refresh }), [rows, failure, refresh]);
+ return useMemo(() => ({ values, failure, refresh }), [values, failure, refresh]);
}
const sharedProject = (value: unknown) => toProject(value, "shared");
@@ -62,9 +62,9 @@ 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 = useRows(useResource(workerInventoryResource, { client, all: true }), toWorker);
- const shared = useRows(useResource(projectsResource, { client, all: true }), sharedProject);
- const own = useRows(useResource(privateProjectsResource, { client, all: true }), privateProject);
+ 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 });
// Undefined only before the first list lands: a later read of an empty list is still a list.
diff --git a/packages/shift-manager/src/lib/directory.tsx b/packages/shift-manager/src/lib/directory.tsx
index 5c8be25816..1450ecb872 100644
--- a/packages/shift-manager/src/lib/directory.tsx
+++ b/packages/shift-manager/src/lib/directory.tsx
@@ -69,8 +69,8 @@ const DirectoryContext = createContext(UNREAD);
/** The inventory's section: its workers, or why there are none. */
function inventorySection(read: CollectionRead): Section | undefined {
- if (read.rows !== undefined && read.rows.length > 0) return { ok: true, value: read.rows };
- if (read.rows !== undefined || read.failure?.httpStatus === 404) return { ok: false, failure: NO_INVENTORY };
+ 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 };
}
@@ -81,15 +81,15 @@ function inventorySection(read: CollectionRead): Section | und
* list. A read that fails after one landed keeps the rows it read.
*/
function projectsSection(shared: CollectionRead, own: CollectionRead): Section | undefined {
- const rowsOf = (read: CollectionRead): Section | undefined =>
- read.rows !== undefined
- ? { ok: true, value: read.rows }
+ 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] = [rowsOf(shared), rowsOf(own)];
+ 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] };
@@ -104,8 +104,8 @@ export function DirectoryProvider({ children }: { children: ReactNode }) {
// When the directory's reads last landed: what Roster's *read* line says.
const [readAt, setReadAt] = useState(undefined);
useEffect(() => {
- if (inventory.rows !== undefined || entries !== undefined) setReadAt(Date.now());
- }, [inventory.rows, entries]);
+ if (inventory.values !== undefined || entries !== undefined) setReadAt(Date.now());
+ }, [inventory.values, entries]);
const refreshInventory = inventory.refresh;
const refreshSessions = sessions.refresh;
const refresh = useCallback(() => {
@@ -116,7 +116,7 @@ export function DirectoryProvider({ children }: { children: ReactNode }) {
() => ({ inventory: section, workers: joined.workers, own: joined.own, roster, readAt, refresh }),
[section, joined, roster, readAt, refresh],
);
- const projectRows = useMemo(() => projectsSection(projects.shared, projects.own), [projects]);
+ const projectList = useMemo(() => projectsSection(projects.shared, projects.own), [projects]);
const refreshShared = projects.shared.refresh;
const refreshOwn = projects.own.refresh;
const refreshProjects = useCallback(() => {
@@ -124,8 +124,8 @@ export function DirectoryProvider({ children }: { children: ReactNode }) {
refreshOwn();
}, [refreshShared, refreshOwn]);
const value = useMemo(
- () => ({ workers, sessions, projects: { section: projectRows, refresh: refreshProjects } }),
- [workers, sessions, projectRows, refreshProjects],
+ () => ({ workers, sessions, projects: { section: projectList, refresh: refreshProjects } }),
+ [workers, sessions, projectList, refreshProjects],
);
return {children};
}
diff --git a/packages/shift-manager/src/lib/projects.ts b/packages/shift-manager/src/lib/projects.ts
index 7db3832dae..348426c294 100644
--- a/packages/shift-manager/src/lib/projects.ts
+++ b/packages/shift-manager/src/lib/projects.ts
@@ -68,8 +68,8 @@ export type Project = {
repository: string | null;
};
-function field(row: unknown, key: string): unknown {
- return typeof row === "object" && row !== null ? (row as Record)[key] : undefined;
+function field(value: unknown, key: string): unknown {
+ return typeof value === "object" && value !== null ? (value as Record)[key] : undefined;
}
function text(value: unknown): string | null {
return typeof value === "string" && value.length > 0 ? value : null;
@@ -85,21 +85,21 @@ function strings(value: unknown): string[] {
* and is left out; every other field reads as empty when absent, so a row an
* earlier version wrote still reads.
*/
-export function toProject(row: unknown, visibility: ProjectVisibility = "shared"): Project | undefined {
- const id = text(field(row, "id"));
- const title = text(field(row, "title"));
- const ownerUserId = text(field(row, "ownerUserId"));
+export function toProject(value: unknown, visibility: ProjectVisibility = "shared"): Project | undefined {
+ const id = text(field(value, "id"));
+ const title = text(field(value, "title"));
+ const ownerUserId = text(field(value, "ownerUserId"));
if (id === null || title === null || ownerUserId === null) return undefined;
return {
id,
visibility,
title,
// An empty brief is still the brief the row was given; only a missing or non-string one is none.
- brief: typeof field(row, "brief") === "string" ? (field(row, "brief") as string) : null,
- status: text(field(row, "status")) ?? "active",
+ brief: typeof field(value, "brief") === "string" ? (field(value, "brief") as string) : null,
+ status: text(field(value, "status")) ?? "active",
ownerUserId,
- members: strings(field(row, "members")),
- repository: text(field(row, "repository")),
+ members: strings(field(value, "members")),
+ repository: text(field(value, "repository")),
};
}
@@ -131,8 +131,8 @@ function toEntry(storageKey: string, data: unknown): Omit[] {
- return rows.map((row) => toEntry(row.storageKey, row.value)).filter((entry): entry is Omit => entry !== undefined);
+function entriesOf(stored: readonly { storageKey: string; value: unknown }[]): Omit[] {
+ return stored.map((each) => toEntry(each.storageKey, each.value)).filter((entry): entry is Omit => entry !== undefined);
}
/**
@@ -170,12 +170,12 @@ export async function readProject(
now = Date.now(),
): Promise<({ project: Project } & ProjectWorkstreams) | null> {
const scope = scopeOf(address.visibility);
- const [stored, rows] = await Promise.all([
+ const [stored, listed] = await Promise.all([
client.resource({ scope, pattern: PROJECTS_PATTERN }).entry(`projects/${address.id}`).read(),
client.resource({ scope, pattern: WORKSTREAMS_PATTERN }).listAll({ topicPrefix: entriesPrefix(address.id) }),
]);
const project = stored.value === null ? undefined : toProject(stored.value, address.visibility);
- return project === undefined ? null : { project, ...withProgress(entriesOf(rows), now) };
+ return project === undefined ? null : { project, ...withProgress(entriesOf(listed), now) };
}
/** The longest delay `setTimeout` keeps; a longer one fires at once. */
@@ -214,11 +214,11 @@ export type ScreenRead = { value: T | undefined; failure: Failure | undefined
export function useProjectWorkstreams(address: ProjectAddress): ScreenRead {
const { client } = useLab();
const read = useResource(WORKSTREAMS[scopeOf(address.visibility)], { client, all: true, topicPrefix: entriesPrefix(address.id) });
- const rows = read.value;
+ const listed = read.value;
// Going quiet is the absence of writes, so the page's own clock says when:
// one recompute at the next entry's threshold, with no read, then the next.
const [now, setNow] = useState(() => Date.now());
- const value = useMemo(() => (rows === null ? undefined : withProgress(entriesOf(rows), now)), [rows, now]);
+ const value = useMemo(() => (listed === null ? undefined : withProgress(entriesOf(listed), now)), [listed, now]);
useEffect(() => {
if (value === undefined) return;
const at = nextQuietAt(value.entries);
diff --git a/packages/shift-manager/src/lib/shift.ts b/packages/shift-manager/src/lib/shift.ts
index fb7ead5af0..84b3d03dec 100644
--- a/packages/shift-manager/src/lib/shift.ts
+++ b/packages/shift-manager/src/lib/shift.ts
@@ -30,11 +30,11 @@ type ViewHold = InboxHold;
* A name more than one worker carries, or none, is no worker: a row is never
* shown against several workers, or against a guess.
*/
-export function workerFor(workers: readonly Worker[], row: { assignee: string | null }): Worker | undefined {
- if (row.assignee === null) return undefined;
- const exact = workers.find((worker) => worker.id === row.assignee);
+export function workerFor(workers: readonly Worker[], task: { assignee: string | null }): Worker | undefined {
+ if (task.assignee === null) return undefined;
+ const exact = workers.find((worker) => worker.id === task.assignee);
if (exact !== undefined) return exact;
- const named = workers.filter((worker) => worker.name === row.assignee);
+ const named = workers.filter((worker) => worker.name === task.assignee);
return named.length === 1 ? named[0] : undefined;
}
diff --git a/packages/shift-manager/src/lib/workers.ts b/packages/shift-manager/src/lib/workers.ts
index 1883f8bc02..c88875c9fe 100644
--- a/packages/shift-manager/src/lib/workers.ts
+++ b/packages/shift-manager/src/lib/workers.ts
@@ -42,8 +42,8 @@ export type Worker = {
harness?: string;
};
-function field(row: unknown, key: string): unknown {
- return typeof row === "object" && row !== null ? (row as Record)[key] : undefined;
+function field(value: unknown, key: string): unknown {
+ return typeof value === "object" && value !== null ? (value as Record)[key] : undefined;
}
function text(value: unknown): string | null {
return typeof value === "string" && value.length > 0 ? value : null;
@@ -102,16 +102,16 @@ function workerNames(
}
/** A worker inventory row, as its browser read publishes it, grouped and named by {@link workerNames}. */
-export function toWorker(row: unknown): Worker | undefined {
- const id = text(field(row, "id"));
+export function toWorker(value: unknown): Worker | undefined {
+ const id = text(field(value, "id"));
if (id === null) return undefined;
return {
id,
- kind: text(field(row, "kind")),
- door: text(field(row, "door")),
- rules: field(row, "rules") === true,
- doorTakesTask: field(row, "doorTakesTask") === true,
- ...workerNames(id, text(field(row, "name")), text(field(row, "teamName"))),
+ kind: text(field(value, "kind")),
+ door: text(field(value, "door")),
+ rules: field(value, "rules") === true,
+ doorTakesTask: field(value, "doorTakesTask") === true,
+ ...workerNames(id, text(field(value, "name")), text(field(value, "teamName"))),
};
}
diff --git a/packages/shift-manager/test/directory.test.tsx b/packages/shift-manager/test/directory.test.tsx
index 6090f329f0..74f755008c 100644
--- a/packages/shift-manager/test/directory.test.tsx
+++ b/packages/shift-manager/test/directory.test.tsx
@@ -18,8 +18,8 @@ type Opened = { topics: readonly WireTopic[]; onChange: (notice: WireNotice | nu
const opened: Opened[] = [];
const hear = (notice: WireNotice) => opened.filter((o) => !o.closed).forEach((o) => o.onChange(notice));
-/** Each collection's rows, by pattern. */
-const rows: Record> = {};
+/** each collection's entries, by pattern. */
+const stored: Record> = {};
/** Every whole read made, by `:`. */
const lists: string[] = [];
const client = {
@@ -30,9 +30,9 @@ const client = {
list: async () => ({ items: [] }),
listAll: async () => {
lists.push(`${scope}:${pattern}`);
- return (rows[pattern] ?? []).map((row) => ({ topic: row.storageKey, ...row, version: 1 }));
+ return (stored[pattern] ?? []).map((each) => ({ topic: each.storageKey, ...each, version: 1 }));
},
- entry: (storageKey: string) => ({ read: async () => ({ value: (rows[pattern] ?? []).find((row) => row.storageKey === storageKey)?.value ?? null, version: 1 }) }),
+ entry: (storageKey: string) => ({ read: async () => ({ value: (stored[pattern] ?? []).find((each) => each.storageKey === storageKey)?.value ?? null, version: 1 }) }),
}),
subscribe: (topics: readonly WireTopic[], options: { onChange: (notice: WireNotice | null) => void }) => {
const entry: Opened = { topics, onChange: options.onChange, closed: false };
@@ -73,7 +73,7 @@ beforeEach(() => {
lists.splice(0);
drawn.splice(0);
rosterWatches = 0;
- rows[INVENTORY] = [{ storageKey: "inventory/workers/eng.coder", value: { id: "eng.coder", kind: "coder", door: "run" } }];
+ stored[INVENTORY] = [{ storageKey: "inventory/workers/eng.coder", value: { id: "eng.coder", kind: "coder", door: "run" } }];
});
afterEach(cleanup);
@@ -91,7 +91,7 @@ describe("the worker directory", () => {
expect(rosterWatches).toBe(1);
// A hire registers a worker: one notice, one read, every screen redrawn from it.
- rows[INVENTORY] = [...rows[INVENTORY]!, { storageKey: "inventory/workers/eng.reviewer", value: { id: "eng.reviewer", kind: "agent" } }];
+ stored[INVENTORY] = [...stored[INVENTORY]!, { storageKey: "inventory/workers/eng.reviewer", value: { id: "eng.reviewer", kind: "agent" } }];
await act(async () => hear({ topic: { scope: "org", resource: "inventory/workers" }, kind: "resource" }));
await waitFor(() => expect(drawn.at(-1)).toEqual(["eng.coder:coder:codex", "eng.reviewer:agent:-", "amber:coder:-"]));
expect(lists.filter((list) => list === `org:${INVENTORY}`)).toHaveLength(2);
diff --git a/packages/shift-manager/test/helpers/directory.ts b/packages/shift-manager/test/helpers/directory.ts
index 600eb6b968..102b50724e 100644
--- a/packages/shift-manager/test/helpers/directory.ts
+++ b/packages/shift-manager/test/helpers/directory.ts
@@ -25,20 +25,20 @@ function readsOfSnapshot(snapshot: LabSnapshot | undefined, refresh: () => void)
const found = held.get(key);
if (found !== undefined) return found;
const loaded = snapshot === undefined || snapshot.refused !== undefined || snapshot.unreachable !== undefined ? undefined : snapshot;
- const rows = (section: { ok: true; value: T[] } | { ok: false; failure: { message: string; httpStatus?: number } } | undefined) =>
+ const read = (section: { ok: true; value: T[] } | { ok: false; failure: { message: string; httpStatus?: number } } | undefined) =>
section === undefined
- ? { rows: undefined, failure: undefined, refresh }
+ ? { values: undefined, failure: undefined, refresh }
: section.ok
- ? { rows: section.value, failure: undefined, refresh }
- : { rows: undefined, failure: section.failure, refresh };
+ ? { values: section.value, failure: undefined, refresh }
+ : { values: undefined, failure: section.failure, refresh };
// A partial fixture with no projects section reads as a Lab with none.
const projects = loaded?.projects ?? { ok: true as const, value: { rows: [] } };
const fixed: Fixed = {
- inventory: loaded === undefined ? rows(undefined) : rows(loaded.inventory.ok ? { ok: true, value: loaded.inventory.value.workers } : loaded.inventory),
+ inventory: loaded === undefined ? read(undefined) : read(loaded.inventory.ok ? { ok: true, value: loaded.inventory.value.workers } : loaded.inventory),
sessions: { list: loaded?.sessions, refresh },
projects: {
- shared: loaded === undefined ? rows(undefined) : rows(projects!.ok ? { ok: true, value: projects!.value.rows.filter((p) => p.visibility === "shared") } : projects!),
- own: loaded === undefined ? rows(undefined) : rows(projects!.ok ? { ok: true, value: projects!.value.rows.filter((p) => p.visibility === "private") } : { ok: true, value: [] }),
+ shared: loaded === undefined ? read(undefined) : read(projects!.ok ? { ok: true, value: projects!.value.rows.filter((p) => p.visibility === "shared") } : projects!),
+ own: loaded === undefined ? read(undefined) : read(projects!.ok ? { ok: true, value: projects!.value.rows.filter((p) => p.visibility === "private") } : { ok: true, value: [] }),
},
};
held.set(key, fixed);
diff --git a/packages/shift-manager/test/inventory-settings.ts b/packages/shift-manager/test/inventory-settings.ts
index 6f78a9e57c..8e70eff2b0 100644
--- a/packages/shift-manager/test/inventory-settings.ts
+++ b/packages/shift-manager/test/inventory-settings.ts
@@ -79,7 +79,7 @@ export const shiftManager: AppInventory = {
"src/lib/conversation.ts": ["WorkerConversation"],
"src/lib/derive.ts": ["Roster", "WorkerState", "WorkerStates"],
"src/lib/directory-reads.ts": [
- { name: "CollectionRead", reason: "a useResource read of a whole collection as the directory holds it: its parsed rows, its failure and its refresh" },
+ { name: "CollectionRead", reason: "a useResource read of a whole collection as the directory holds it: its parsed values, its failure and its refresh" },
{ name: "DirectoryReads", reason: "the directory's reads, one hook's output assembled from useResource, the roster watch and useSessionList" },
],
"src/lib/directory.tsx": [{ name: "Workers", reason: "the worker directory a screen draws: the inventory joined with the roster (D1), a hook's output assembled from two reads" }],
diff --git a/packages/shift-manager/test/messages-view.test.tsx b/packages/shift-manager/test/messages-view.test.tsx
index d47a8c8c0b..16202346b3 100644
--- a/packages/shift-manager/test/messages-view.test.tsx
+++ b/packages/shift-manager/test/messages-view.test.tsx
@@ -34,8 +34,8 @@ const answer = row({ id: "msg_b", from: "coordinator", to: "researcher", at: 3_0
const other = row({ id: "msg_c", from: "helper-a", to: "helper-b", at: 2_000, status: "refused", reason: "dispatch-rejected: down" });
/** The log's entries as the direct read answers them. */
-const entries = (rows: WorkerMessageResourceState[]) =>
- rows.map((r) => ({ topic: r.id, storageKey: `workforce/messages/${r.id}`, value: r, version: 1 }));
+const entries = (stored: WorkerMessageResourceState[]) =>
+ stored.map((r) => ({ topic: r.id, storageKey: `workforce/messages/${r.id}`, value: r, version: 1 }));
beforeEach(() => {
readAll.mockReset();
diff --git a/packages/shift-manager/test/roster.test.ts b/packages/shift-manager/test/roster.test.ts
index 4c6ed5e744..85f92aa809 100644
--- a/packages/shift-manager/test/roster.test.ts
+++ b/packages/shift-manager/test/roster.test.ts
@@ -120,8 +120,8 @@ describe("BR-1 to BR-5: the one status rule", () => {
});
it("BR-3: queued, blocked, errored and finished alone are off shift, and hold no slot", () => {
- const rows = ["pending", "held", "errored", "completed", "cancelled"].map((s) => row(s, s, "coder"));
- const state = workerStates(...directory([coder], rows)).workers.get("eng.coder")!;
+ const tasks = ["pending", "held", "errored", "completed", "cancelled"].map((s) => row(s, s, "coder"));
+ const state = workerStates(...directory([coder], tasks)).workers.get("eng.coder")!;
expect(state).toMatchObject({ status: "off shift", held: [] });
});
From 096798b4099e1f05c11a358a454b6dd2bda85843 Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 01:23:58 +0000
Subject: [PATCH 13/24] docs(shift-manager): the directory's comments name
workers and entries, not rows (FIX-2775)
The tree-wide retired-terms check counted three row lines and one member name
this branch moved or wrote.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiGfuuX5mPxVeUwVXfa
---
packages/shift-manager/src/lib/directory.tsx | 4 ++--
packages/shift-manager/src/lib/projects.ts | 4 ++--
packages/shift-manager/src/lib/shift.ts | 2 +-
3 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/packages/shift-manager/src/lib/directory.tsx b/packages/shift-manager/src/lib/directory.tsx
index 1450ecb872..82be8d6c63 100644
--- a/packages/shift-manager/src/lib/directory.tsx
+++ b/packages/shift-manager/src/lib/directory.tsx
@@ -6,7 +6,7 @@
* {@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 worker rows are the inventory joined with the roster (`workers.ts`);
+ * 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";
@@ -45,7 +45,7 @@ export type Workers = {
refresh: () => void;
};
-/** The directory: the worker rows, the sessions and the projects. */
+/** The directory: the workers, the sessions and the projects. */
type Directory = {
workers: Workers;
sessions: { list: readonly SessionSummary[] | undefined; refresh: () => void };
diff --git a/packages/shift-manager/src/lib/projects.ts b/packages/shift-manager/src/lib/projects.ts
index 348426c294..f48e815062 100644
--- a/packages/shift-manager/src/lib/projects.ts
+++ b/packages/shift-manager/src/lib/projects.ts
@@ -80,9 +80,9 @@ function strings(value: unknown): string[] {
// BP-030.
/**
- * A project row, as the projects collection's browser read publishes it. A row
+ * A project entry, as the projects collection's browser read publishes it. One
* missing its id, title or owner is not a project anyone can address or own,
- * and is left out; every other field reads as empty when absent, so a row an
+ * and is left out; every other field reads as empty when absent, so an entry an
* earlier version wrote still reads.
*/
export function toProject(value: unknown, visibility: ProjectVisibility = "shared"): Project | undefined {
diff --git a/packages/shift-manager/src/lib/shift.ts b/packages/shift-manager/src/lib/shift.ts
index 84b3d03dec..a2bb3940ec 100644
--- a/packages/shift-manager/src/lib/shift.ts
+++ b/packages/shift-manager/src/lib/shift.ts
@@ -142,7 +142,7 @@ export function teamsOf(workers: readonly Worker[]): Array<{ team: string; name:
if (team === undefined) teams.set(worker.team, [worker]);
else team.push(worker);
}
- const all = [...teams].map(([team, members]) => ({ team, name: members[0]!.teamName, workers: members }));
+ const all = [...teams].map(([team, onTeam]) => ({ team, name: onTeam[0]!.teamName, workers: onTeam }));
return [...all.filter((t) => t.team === GENERAL_TEAM), ...all.filter((t) => t.team !== GENERAL_TEAM)];
}
From b8d86d908cb5fbd98f64990eb7ac4f1d2d015b40 Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 01:26:47 +0000
Subject: [PATCH 14/24] goal(shift-manager): one answer leg and
status-from-snapshot control (FIX-2775)
it-shows-who-is-on-shift gains the leg the spec names: a worker off shift stops
for an approval, then it is approved from Inbox, and in every state the page
draws (a MutationObserver per committed change) the Inbox lists the ask
exactly when the worker's TEAMS square is on shift. The control counts the
snapshot's walked asks for status while the Inbox lists the view's.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiGfuuX5mPxVeUwVXfa
---
.../controls/status-from-snapshot.ts | 28 +++++++
.../it-shows-who-is-on-shift/run.mts | 81 ++++++++++++++++++-
2 files changed, 108 insertions(+), 1 deletion(-)
create mode 100644 goals/shift-manager/it-shows-who-is-on-shift/controls/status-from-snapshot.ts
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/run.mts b/goals/shift-manager/it-shows-who-is-on-shift/run.mts
index abe00d0034..e846decd34 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,6 +26,9 @@
* 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/shift.ts` swapped for a module
* under `controls/` (a Vite `resolveId` plugin; the build fails if the swap
@@ -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);
@@ -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,74 @@ 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;
+ await page.evaluate(
+ ({ workerId, sessionId }) => {
+ const w = window as unknown as { __frames: Frame[] };
+ w.__frames = [];
+ const read = (): Frame => ({
+ 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),
+ });
+ w.__frames.push(read());
+ new MutationObserver(() => w.__frames.push(read())).observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true });
+ },
+ { workerId: asker.id, sessionId },
+ );
+ 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 +506,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");
From 82c99e4ee4445850356afe17c0b7ed3b6a2b0fff Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 01:34:00 +0000
Subject: [PATCH 15/24] goal(shift-manager): one answer reads the page's states
with a script string; goal.md names the leg (FIX-2775)
tsx names a function's inner helpers with __name, which the page doesn't have,
so the recorder goes into the page as a string.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiGfuuX5mPxVeUwVXfa
---
.../it-shows-who-is-on-shift/goal.md | 4 ++-
.../it-shows-who-is-on-shift/run.mts | 25 ++++++++++---------
2 files changed, 16 insertions(+), 13 deletions(-)
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 f61e911419..078cc5466d 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.
@@ -31,6 +32,7 @@
**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 |
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 e846decd34..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
@@ -373,20 +373,21 @@ async function oneAnswer(page: Page, origin: string, userId: string, store: Stor
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;
- await page.evaluate(
- ({ workerId, sessionId }) => {
- const w = window as unknown as { __frames: Frame[] };
- w.__frames = [];
- const read = (): Frame => ({
+ // 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,
+ 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),
- });
- w.__frames.push(read());
- new MutationObserver(() => w.__frames.push(read())).observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true });
- },
- { workerId: asker.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) {
From 8ee63f43e0c5f52cdf431e5b3b284a726a799a09 Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 01:37:25 +0000
Subject: [PATCH 16/24] goal(shift-manager): it-shows-who-is-on-shift verdicts
for FIX-2775 PR 3
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiGfuuX5mPxVeUwVXfa
---
goals/shift-manager/it-shows-who-is-on-shift/goal.md | 4 ++++
1 file changed, 4 insertions(+)
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 078cc5466d..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
@@ -55,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)"* |
From 30f36df55887b637ea81cea3f972bcb35bc42f5c Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 01:41:15 +0000
Subject: [PATCH 17/24] fix(shift-manager): R reads again each screen's own
reads (FIX-2775)
With the screens off the snapshot, R read the Inbox view, the directory and
the projects, but not the message log, a project's workstreams, its report,
the project setup, Routines or Usage: on main those re-read on each Lab read's
readAt. Each of those reads now registers its read-again with the page
(page-reads.tsx) while mounted, and R reads every one. Caught by
realtime/app-views-read-on-notice a:lab-read, retargeted from the snapshot's
Refresh to R. page-reads.test.tsx was red before the hooks registered
(expected [1, 1] to deeply equal [2, 2]).
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiGfuuX5mPxVeUwVXfa
---
.../realtime/app-views-read-on-notice/goal.md | 2 +-
.../realtime/app-views-read-on-notice/run.mts | 14 ++--
packages/shift-manager/src/App.tsx | 15 ++--
packages/shift-manager/src/lib/messages.ts | 2 +
packages/shift-manager/src/lib/page-reads.tsx | 37 +++++++++
packages/shift-manager/src/lib/projects.ts | 4 +
packages/shift-manager/src/lib/routines.ts | 2 +
packages/shift-manager/src/lib/usage.ts | 3 +
.../shift-manager/test/page-reads.test.tsx | 76 +++++++++++++++++++
9 files changed, 143 insertions(+), 12 deletions(-)
create mode 100644 packages/shift-manager/src/lib/page-reads.tsx
create mode 100644 packages/shift-manager/test/page-reads.test.tsx
diff --git a/goals/realtime/app-views-read-on-notice/goal.md b/goals/realtime/app-views-read-on-notice/goal.md
index 4e9468b469..97bc31f9ad 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.
diff --git a/goals/realtime/app-views-read-on-notice/run.mts b/goals/realtime/app-views-read-on-notice/run.mts
index 9d4c0e0c65..2e661939bd 100644
--- a/goals/realtime/app-views-read-on-notice/run.mts
+++ b/goals/realtime/app-views-read-on-notice/run.mts
@@ -70,6 +70,7 @@ import { kitchenSinkWorkforce } from "../../../apps/kitchen-sink/lib/workforce-k
import { LabProvider, useLab } from "../../../packages/shift-manager/src/lib/lab-data.tsx";
import { useProjectWorkstreams } from "../../../packages/shift-manager/src/lib/projects.ts";
import { useMessages } from "../../../packages/shift-manager/src/lib/messages.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";
@@ -377,10 +378,11 @@ 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;
// 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 });
@@ -404,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(),
@@ -433,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,
@@ -619,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/packages/shift-manager/src/App.tsx b/packages/shift-manager/src/App.tsx
index d7d7958bef..6aeb4639e1 100644
--- a/packages/shift-manager/src/App.tsx
+++ b/packages/shift-manager/src/App.tsx
@@ -22,6 +22,7 @@ import type { Connection } from "./lib/connection";
import { LabProvider, useLab } from "./lib/lab-data";
import { DirectoryProvider, useDirectoryLanded, useProjects, 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";
@@ -98,9 +99,11 @@ function Shell({ gaps, devtoolUrl, look }: { gaps: Gaps; devtoolUrl: string | un
// Every read but the gate's waits behind it: the directory, the Inbox view and the screens' own.
return (
-
-
-
+
+
+
+
+
);
}
@@ -118,6 +121,7 @@ function Frame({ gaps, devtoolUrl, look }: { gaps: Gaps; devtoolUrl: string | un
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);
@@ -144,15 +148,16 @@ function Frame({ gaps, devtoolUrl, look }: { gaps: Gaps; devtoolUrl: string | un
if (e.key === "[") toggleNav();
else if (e.key === "]" && hasPanel) togglePanel();
else if (e.key === "r" || e.key === "R") {
- // The page's reads: the Inbox view, the worker directory and the sessions, the projects.
+ // The page's reads: the Inbox view, the worker directory and the sessions, the projects, and each screen's own.
refreshInbox();
refreshWorkers();
refreshProjects();
+ readPageAgain();
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
- }, [toggleNav, togglePanel, hasPanel, refreshInbox, refreshWorkers, refreshProjects]);
+ }, [toggleNav, togglePanel, hasPanel, refreshInbox, refreshWorkers, refreshProjects, readPageAgain]);
const levels = (
<>
diff --git a/packages/shift-manager/src/lib/messages.ts b/packages/shift-manager/src/lib/messages.ts
index fdea27ee7e..a4d0762710 100644
--- a/packages/shift-manager/src/lib/messages.ts
+++ b/packages/shift-manager/src/lib/messages.ts
@@ -9,6 +9,7 @@ import { useMemo } from "react";
import { useResource } from "@flow-state-dev/react";
import { workerMessageResourceStateSchema, workerMessagesResource, type WorkerMessageResourceState } from "@flow-state-dev/workforce/browser";
import { useLab } from "./lab-data";
+import { useReadAgainOnR } from "./page-reads";
import type { Failure } from "./failure";
export type { WorkerMessageResourceState };
@@ -61,6 +62,7 @@ export function firstLine(text: string): string {
export function useMessages(): { rows: WorkerMessageResourceState[] | null | undefined; failure: Failure | undefined; reread: () => void } {
const { client } = useLab();
const { value, failure, refresh } = useResource(workerMessagesResource, { client, all: true });
+ useReadAgainOnR(refresh);
const rows = useMemo(() => (value === null ? undefined : toMessages(value.map((entry) => entry.value))), [value]);
if (rows !== undefined) return { rows, failure: undefined, reread: refresh };
if (failure?.httpStatus === 404) return { rows: null, failure: undefined, reread: refresh };
diff --git a/packages/shift-manager/src/lib/page-reads.tsx b/packages/shift-manager/src/lib/page-reads.tsx
new file mode 100644
index 0000000000..b06a0a2731
--- /dev/null
+++ b/packages/shift-manager/src/lib/page-reads.tsx
@@ -0,0 +1,37 @@
+/**
+ * The reads a screen holds, for R to read again. Each screen read registers
+ * its read-again with {@link useReadAgainOnR} while it is mounted, and R reads
+ * again every one registered, beside the directory's and the Inbox view's: a
+ * person pressing R on Messages reads the message log again, and on a project
+ * its workstreams. Outside a {@link PageReadsProvider} (a component under test
+ * on its own) registering does nothing.
+ */
+import { createContext, useCallback, useContext, useEffect, useRef, type ReactNode } from "react";
+
+const PageReadsContext = createContext void> | null>(null);
+
+/** Hold the page's registered reads. */
+export function PageReadsProvider({ children }: { children: ReactNode }) {
+ const reads = useRef(new Set<() => void>()).current;
+ return {children};
+}
+
+/** Register `readAgain` for R while the calling component is mounted. */
+export function useReadAgainOnR(readAgain: () => void): void {
+ const reads = useContext(PageReadsContext);
+ useEffect(() => {
+ if (reads === null) return;
+ reads.add(readAgain);
+ return () => {
+ reads.delete(readAgain);
+ };
+ }, [reads, readAgain]);
+}
+
+/** Read again every read the page's screens registered. */
+export function useReadPageAgain(): () => void {
+ const reads = useContext(PageReadsContext);
+ return useCallback(() => {
+ for (const readAgain of [...(reads ?? [])]) readAgain();
+ }, [reads]);
+}
diff --git a/packages/shift-manager/src/lib/projects.ts b/packages/shift-manager/src/lib/projects.ts
index f48e815062..817b9f752c 100644
--- a/packages/shift-manager/src/lib/projects.ts
+++ b/packages/shift-manager/src/lib/projects.ts
@@ -39,6 +39,7 @@ import {
type ProjectSetup,
} from "@flow-state-dev/workforce/browser";
import { useLab } from "./lab-data";
+import { useReadAgainOnR } from "./page-reads";
import type { Failure } from "./failure";
/** Where a project lives: the organization's, or the user's own. */
@@ -214,6 +215,7 @@ export type ScreenRead = { value: T | undefined; failure: Failure | undefined
export function useProjectWorkstreams(address: ProjectAddress): ScreenRead {
const { client } = useLab();
const read = useResource(WORKSTREAMS[scopeOf(address.visibility)], { client, all: true, topicPrefix: entriesPrefix(address.id) });
+ useReadAgainOnR(read.refresh);
const listed = read.value;
// Going quiet is the absence of writes, so the page's own clock says when:
// one recompute at the next entry's threshold, with no read, then the next.
@@ -247,6 +249,7 @@ export function useProjectWorkstreams(address: ProjectAddress): ScreenRead): ScreenRead {
const { client } = useLab();
const { value, failure, refresh } = useView(workstreamReportView, { project, owner: entry.owner, id: entry.id }, { client });
+ useReadAgainOnR(refresh);
return { value: value === undefined ? undefined : value.report, failure, refresh };
}
@@ -258,6 +261,7 @@ export function useEntryReport(project: ProjectAddress, entry: Pick {
const { client } = useLab();
const { value, failure, refresh } = useView(projectSetupView, {}, { client });
+ useReadAgainOnR(refresh);
const none = value === undefined && failure?.httpStatus === 404;
return { value: none ? null : value, failure: none ? undefined : failure, refresh };
}
diff --git a/packages/shift-manager/src/lib/routines.ts b/packages/shift-manager/src/lib/routines.ts
index 80e2bb6ea5..e350fe3cee 100644
--- a/packages/shift-manager/src/lib/routines.ts
+++ b/packages/shift-manager/src/lib/routines.ts
@@ -12,6 +12,7 @@ import { useCallback, useMemo } from "react";
import { useView } from "@flow-state-dev/react";
import { ROUTINE_VERBS, SCHEDULES_PATTERN, listedRoutineSchema, routinesView, type ListedRoutine } from "@flow-state-dev/workforce/browser";
import { useLab } from "./lab-data";
+import { useReadAgainOnR } from "./page-reads";
import { describeFailure, type Failure } from "./failure";
const text = (value: unknown): string | null => (typeof value === "string" && value.length > 0 ? value : null);
@@ -65,6 +66,7 @@ export function useRoutines(): {
} {
const { client } = useLab();
const { value, failure, refresh } = useView(routinesView, {}, { client });
+ useReadAgainOnR(refresh);
const routines = useMemo(() => (value === undefined ? (failure?.httpStatus === 404 ? null : undefined) : toRoutines(value)), [value, failure?.httpStatus]);
const change = useCallback(
async (wanted) => {
diff --git a/packages/shift-manager/src/lib/usage.ts b/packages/shift-manager/src/lib/usage.ts
index b1b8a58731..7050e1cdd3 100644
--- a/packages/shift-manager/src/lib/usage.ts
+++ b/packages/shift-manager/src/lib/usage.ts
@@ -19,6 +19,7 @@ import { useView } from "@flow-state-dev/react";
import { harnessUsageViewRef, recheckHarnessUsage } from "@flow-state-dev/harness-manager/browser";
import { workerUsageView } from "@flow-state-dev/workforce/browser";
import { useLab } from "./lab-data";
+import { useReadAgainOnR } from "./page-reads";
import { describeFailure, type Failure } from "./failure";
/** The harness usage view, read with no session. */
@@ -86,6 +87,7 @@ export function useHarnessUsage(): {
setTries((n) => n + 1);
refresh();
}, [refresh]);
+ useReadAgainOnR(reread);
const conflict = recheck.state === "failed" && recheck.failure.httpStatus === 409 ? recheck.failure : undefined;
const refreshError = recheck.state === "failed" && conflict === undefined ? recheck.failure.message : null;
const rows = useMemo(
@@ -118,6 +120,7 @@ export function useWorkerUsage(days: number): {
} {
const { client } = useLab();
const { value, failure, refresh } = useView(workerUsageView, { days }, { client });
+ useReadAgainOnR(refresh);
if (value === undefined && failure !== undefined && servesNone(failure, false)) return { rows: null, failure: undefined, reread: refresh };
return { rows: value?.workers, failure, reread: refresh };
}
diff --git a/packages/shift-manager/test/page-reads.test.tsx b/packages/shift-manager/test/page-reads.test.tsx
new file mode 100644
index 0000000000..fd503462bd
--- /dev/null
+++ b/packages/shift-manager/test/page-reads.test.tsx
@@ -0,0 +1,76 @@
+// @vitest-environment happy-dom
+/**
+ * R reads again what the page holds (FIX-2775): the message log on Messages
+ * and a project's workstreams on its page, not only the directory and the
+ * Inbox. A screen's read registers while it is mounted and leaves when it
+ * unmounts, so R never reads for a screen that is gone.
+ *
+ * The client's direct reads are the test's; the screens' hooks and the
+ * registry are the app's.
+ */
+import { act, cleanup, render, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+/** Every whole read made, by pattern. */
+const lists: string[] = [];
+const client = {
+ userId: "u_1",
+ resource: ({ scope, pattern }: { scope: string; pattern: string }) => ({
+ scope,
+ key: pattern,
+ list: async () => ({ items: [] }),
+ listAll: async () => {
+ lists.push(pattern);
+ return [];
+ },
+ }),
+ subscribe: () => ({ close: () => {} }),
+};
+vi.mock("../src/lib/lab-data", () => ({ useLab: () => ({ client }) }));
+
+import { PageReadsProvider, useReadPageAgain } from "../src/lib/page-reads";
+import { useMessages } from "../src/lib/messages";
+import { useProjectWorkstreams } from "../src/lib/projects";
+
+let readPageAgain: () => void = () => {};
+function R() {
+ readPageAgain = useReadPageAgain();
+ return null;
+}
+function Messages() {
+ useMessages();
+ return null;
+}
+function Project() {
+ useProjectWorkstreams({ visibility: "shared", id: "desk" });
+ return null;
+}
+
+const count = (part: string) => lists.filter((pattern) => pattern.includes(part)).length;
+
+beforeEach(() => {
+ lists.splice(0);
+});
+afterEach(cleanup);
+
+describe("R reads again the reads the page's screens hold", () => {
+ it("reads the message log and a project's workstreams again, and stops reading a screen once it is gone", async () => {
+ const page = (screens: { messages: boolean; project: boolean }) => (
+
+
+ {screens.messages ? : null}
+ {screens.project ? : null}
+
+ );
+ const { rerender } = render(page({ messages: true, project: true }));
+ await waitFor(() => expect([count("messages"), count("workstreams")]).toEqual([1, 1]));
+
+ act(() => readPageAgain());
+ await waitFor(() => expect([count("messages"), count("workstreams")]).toEqual([2, 2]));
+
+ rerender(page({ messages: false, project: true }));
+ act(() => readPageAgain());
+ await waitFor(() => expect(count("workstreams")).toBe(3));
+ expect(count("messages")).toBe(2);
+ });
+});
From b9be6658e5c23eef924cfea28e33b2f1a2c99524 Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 01:45:08 +0000
Subject: [PATCH 18/24] fix(shift-manager): one definition per moved name, no
import cycle, no dead export (FIX-2775)
Fallow's audit on the PR found three things this branch left:
- reads.ts kept alias exports of Failure, Section, Worker, Project and
BoardTaskView beside their new homes, and derive.ts kept its snapshot
workerStates, WorkerState(s) and Roster beside shift.ts's. reads.ts now
imports the moved names; derive.ts drops the snapshot status, which no
screen reads (its one test case goes with it).
- lab-data -> reads -> projects -> lab-data: the snapshot reader parsed projects
through projects.ts, which holds hooks. Project, ProjectVisibility and
toProject move to a leaf, project.ts.
- StatusWord in ui.tsx had no caller; PartialMark and ShiftMark were imported
and unused in ShiftCoordinator.tsx.
The inventory allowlist loses the five reads.ts type entries that no longer
exist, and Project's screen-type reason moves with it to project.ts.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiGfuuX5mPxVeUwVXfa
---
packages/shift-manager/src/components/ui.tsx | 10 ---
packages/shift-manager/src/lib/derive.ts | 78 +------------------
.../shift-manager/src/lib/directory-reads.ts | 2 +-
packages/shift-manager/src/lib/directory.tsx | 2 +-
packages/shift-manager/src/lib/project.ts | 66 ++++++++++++++++
packages/shift-manager/src/lib/projects.ts | 60 +-------------
packages/shift-manager/src/lib/reads.ts | 23 +-----
.../shift-manager/src/surfaces/JumpTo.tsx | 3 +-
.../src/surfaces/ShiftCoordinator.tsx | 2 +-
.../shift-manager/src/surfaces/Sidebar.tsx | 3 +-
packages/shift-manager/test/columns.test.ts | 3 +-
.../shift-manager/test/conversation.test.tsx | 2 +-
packages/shift-manager/test/goal-labs.test.ts | 3 +-
.../shift-manager/test/helpers/inbox-view.ts | 3 +-
.../shift-manager/test/inbox-tasks.test.ts | 4 +-
packages/shift-manager/test/inbox.test.ts | 3 +-
.../test/inventory-allowlist.json | 5 --
.../shift-manager/test/inventory-settings.ts | 5 +-
packages/shift-manager/test/projects.test.tsx | 4 +-
packages/shift-manager/test/reads.test.ts | 10 +--
.../shift-manager/test/roster-screen.test.tsx | 4 +-
.../test/shift-coordinator.test.ts | 4 +-
.../shift-manager/test/task-actions.test.ts | 3 +-
.../shift-manager/test/task-screen.test.tsx | 3 +-
.../shift-manager/test/turn-routes.test.ts | 2 +-
.../test/worker-settings-screen.test.tsx | 3 +-
26 files changed, 113 insertions(+), 197 deletions(-)
create mode 100644 packages/shift-manager/src/lib/project.ts
diff --git a/packages/shift-manager/src/components/ui.tsx b/packages/shift-manager/src/components/ui.tsx
index 42c53ff4fd..378cbbd81a 100644
--- a/packages/shift-manager/src/components/ui.tsx
+++ b/packages/shift-manager/src/components/ui.tsx
@@ -244,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/derive.ts b/packages/shift-manager/src/lib/derive.ts
index 104d467e73..81c826a218 100644
--- a/packages/shift-manager/src/lib/derive.ts
+++ b/packages/shift-manager/src/lib/derive.ts
@@ -5,8 +5,10 @@
*/
import type { InboxItem } from "@flow-state-dev/orchestration/inbox";
import { isDone } from "./columns";
-import type { Ask, BoardTaskView, Failure, LabSnapshot, Project, Section, Worker } from "./reads";
-import { workerFor, type ShiftStatus } from "./shift";
+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). */
@@ -39,78 +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[] };
-
-/** 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.workers, 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
diff --git a/packages/shift-manager/src/lib/directory-reads.ts b/packages/shift-manager/src/lib/directory-reads.ts
index 40b8131005..65b8163d6d 100644
--- a/packages/shift-manager/src/lib/directory-reads.ts
+++ b/packages/shift-manager/src/lib/directory-reads.ts
@@ -13,7 +13,7 @@ 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 "./projects";
+import { toProject, type Project } from "./project";
import { useRoster, type RosterRead } from "./roster";
import { toWorker, type Worker } from "./workers";
diff --git a/packages/shift-manager/src/lib/directory.tsx b/packages/shift-manager/src/lib/directory.tsx
index 82be8d6c63..5bfae657c7 100644
--- a/packages/shift-manager/src/lib/directory.tsx
+++ b/packages/shift-manager/src/lib/directory.tsx
@@ -13,7 +13,7 @@ import { createContext, useCallback, useContext, useEffect, useMemo, useState, t
import type { SessionSummary } from "@flow-state-dev/client";
import { useDirectoryReads, type CollectionRead } from "./directory-reads";
import type { Failure, Section } from "./failure";
-import type { Project } from "./projects";
+import type { Project } from "./project";
import type { RosterRead } from "./roster";
import { joinWorkers, type Worker } from "./workers";
diff --git a/packages/shift-manager/src/lib/project.ts b/packages/shift-manager/src/lib/project.ts
new file mode 100644
index 0000000000..0a584ef5a9
--- /dev/null
+++ b/packages/shift-manager/src/lib/project.ts
@@ -0,0 +1,66 @@
+/**
+ * A project as Shift Manager draws it, and the parser that reads one from the
+ * projects collection. A leaf, with no hook and no connection, so the
+ * snapshot's reader and the directory's reads both parse with it without
+ * reaching the page's connection through `projects.ts`.
+ */
+
+/** Where a project lives: the organization's, or the user's own. */
+export type ProjectVisibility = "shared" | "private";
+
+/**
+ * A project: a row of the organization's `projects` collection (shared), or of
+ * the user's own (private), with where it lives. Its address is its
+ * visibility and its id: a private project and a shared one can share an id.
+ */
+export type Project = {
+ /** The row id; with the visibility, the project's address. */
+ id: string;
+ /** Where the row lives. */
+ visibility: ProjectVisibility;
+ title: string;
+ /** What the project is for; its Brief tab. `null` when none was given. */
+ brief: string | null;
+ status: string;
+ ownerUserId: string;
+ /** On a shared project, who may open workstreams in it. */
+ members: string[];
+ /** The git remote the project's code lives in, or `null` when it has none. A row written before the field reads as none. */
+ repository: string | null;
+};
+
+function field(value: unknown, key: string): unknown {
+ return typeof value === "object" && value !== null ? (value as Record)[key] : undefined;
+}
+function text(value: unknown): string | null {
+ return typeof value === "string" && value.length > 0 ? value : null;
+}
+function strings(value: unknown): string[] {
+ return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : [];
+}
+
+// BP-030.
+/**
+ * A project entry, as the projects collection's browser read publishes it. One
+ * missing its id, title or owner is not a project anyone can address or own,
+ * and is left out; every other field reads as empty when absent, so an entry an
+ * earlier version wrote still reads.
+ */
+export function toProject(value: unknown, visibility: ProjectVisibility = "shared"): Project | undefined {
+ const id = text(field(value, "id"));
+ const title = text(field(value, "title"));
+ const ownerUserId = text(field(value, "ownerUserId"));
+ if (id === null || title === null || ownerUserId === null) return undefined;
+ return {
+ id,
+ visibility,
+ title,
+ // An empty brief is still the brief the row was given; only a missing or non-string one is none.
+ brief: typeof field(value, "brief") === "string" ? (field(value, "brief") as string) : null,
+ status: text(field(value, "status")) ?? "active",
+ ownerUserId,
+ members: strings(field(value, "members")),
+ repository: text(field(value, "repository")),
+ };
+}
+
diff --git a/packages/shift-manager/src/lib/projects.ts b/packages/shift-manager/src/lib/projects.ts
index 817b9f752c..1829639dd9 100644
--- a/packages/shift-manager/src/lib/projects.ts
+++ b/packages/shift-manager/src/lib/projects.ts
@@ -41,69 +41,11 @@ import {
import { useLab } from "./lab-data";
import { useReadAgainOnR } from "./page-reads";
import type { Failure } from "./failure";
-
-/** Where a project lives: the organization's, or the user's own. */
-export type ProjectVisibility = "shared" | "private";
+import { toProject, type Project, type ProjectVisibility } from "./project";
/** A project's address: where it lives, and its id. */
export type ProjectAddress = { visibility: ProjectVisibility; id: string };
-/**
- * A project: a row of the organization's `projects` collection (shared), or of
- * the user's own (private), with where it lives. Its address is its
- * visibility and its id: a private project and a shared one can share an id.
- */
-export type Project = {
- /** The row id; with the visibility, the project's address. */
- id: string;
- /** Where the row lives. */
- visibility: ProjectVisibility;
- title: string;
- /** What the project is for; its Brief tab. `null` when none was given. */
- brief: string | null;
- status: string;
- ownerUserId: string;
- /** On a shared project, who may open workstreams in it. */
- members: string[];
- /** The git remote the project's code lives in, or `null` when it has none. A row written before the field reads as none. */
- repository: string | null;
-};
-
-function field(value: unknown, key: string): unknown {
- return typeof value === "object" && value !== null ? (value as Record)[key] : undefined;
-}
-function text(value: unknown): string | null {
- return typeof value === "string" && value.length > 0 ? value : null;
-}
-function strings(value: unknown): string[] {
- return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : [];
-}
-
-// BP-030.
-/**
- * A project entry, as the projects collection's browser read publishes it. One
- * missing its id, title or owner is not a project anyone can address or own,
- * and is left out; every other field reads as empty when absent, so an entry an
- * earlier version wrote still reads.
- */
-export function toProject(value: unknown, visibility: ProjectVisibility = "shared"): Project | undefined {
- const id = text(field(value, "id"));
- const title = text(field(value, "title"));
- const ownerUserId = text(field(value, "ownerUserId"));
- if (id === null || title === null || ownerUserId === null) return undefined;
- return {
- id,
- visibility,
- title,
- // An empty brief is still the brief the row was given; only a missing or non-string one is none.
- brief: typeof field(value, "brief") === "string" ? (field(value, "brief") as string) : null,
- status: text(field(value, "status")) ?? "active",
- ownerUserId,
- members: strings(field(value, "members")),
- repository: text(field(value, "repository")),
- };
-}
-
// BR-12.
/** One workstream of a project: its entry as Workforce parses it, its storage key, and whether it has gone quiet. */
export type WorkstreamEntry = ParsedWorkstreamEntry & {
diff --git a/packages/shift-manager/src/lib/reads.ts b/packages/shift-manager/src/lib/reads.ts
index 7edb8bdcdf..d824b6522a 100644
--- a/packages/shift-manager/src/lib/reads.ts
+++ b/packages/shift-manager/src/lib/reads.ts
@@ -64,25 +64,13 @@ import { suspensionShape } from "@flow-state-dev/react";
import { deriveSuspensions } from "@flow-state-dev/react/internal";
import { PROJECTS_PATTERN, ROSTER_FLOW, sessionIdOfFiling } from "@flow-state-dev/workforce/browser";
import { boardTaskOf, createWorkforceClient } from "@flow-state-dev/workforce/browser";
-import { describeFailure, type Failure as ScreenFailure } from "./failure";
-import { CONVERSATION_BOARD_COLLECTION, conversationBoardRef } from "./boards";
-import { toProject, type Project as ScreenProject, type ProjectVisibility } from "./projects";
-import { toWorker, workerOf, type Worker as DirectoryWorker } from "./workers";
+import { describeFailure, type Failure, type Section } from "./failure";
+import { CONVERSATION_BOARD_COLLECTION, conversationBoardRef, type BoardTaskView } from "./boards";
+import { toProject, type Project, type ProjectVisibility } from "./project";
+import { toWorker, workerOf, type Worker } from "./workers";
import type { Client } from "@flow-state-dev/client";
import { createInboxClient, inboxItems, taskActionName, type BoardActions, type InboxAnswer, type InboxHold, type InboxItem, type InboxTaskInput, type TaskHold } from "@flow-state-dev/orchestration/inbox";
-/** Why a read did not load: the screens' own. */
-export type Failure = ScreenFailure;
-
-/** One section's outcome: its value, or why it has none. */
-export type Section = { ok: true; value: T } | { ok: false; failure: Failure };
-
-/** A worker: the directory's row (`workers.ts`). */
-export type Worker = DirectoryWorker;
-
-/** A project: the screens' row (`projects.ts`). */
-export type Project = ScreenProject;
-
/** The projects the user reads: the organization's, and their own private ones. */
export type Projects = {
/** Every row: the shared ones in the collection's order, then the private ones. */
@@ -92,9 +80,6 @@ export type Projects = {
/** The run working a task, or the run that last worked it: workforce's board task names it. */
export type RunLink = NonNullable;
-/** One task on a conversation's board: workforce's board task. */
-export type BoardTaskView = BoardTask;
-
/** A conversation's board and every row on it. */
export type ConversationBoards = { refs: string[]; rows: BoardTaskView[] };
diff --git a/packages/shift-manager/src/surfaces/JumpTo.tsx b/packages/shift-manager/src/surfaces/JumpTo.tsx
index c3b9d56ce0..ef907f36f8 100644
--- a/packages/shift-manager/src/surfaces/JumpTo.tsx
+++ b/packages/shift-manager/src/surfaces/JumpTo.tsx
@@ -25,7 +25,8 @@ import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/compone
import { shiftCoordinatorOf, workerLabel } from "../lib/shift";
import type { InboxBoardTask } from "../lib/inbox";
import { handToShiftCoordinator } from "../lib/outbox";
-import { readProject, type Project, type WorkstreamEntry } from "../lib/projects";
+import { readProject, type WorkstreamEntry } from "../lib/projects";
+import type { Project } from "../lib/project";
import { useProjects, useWorkers } from "../lib/directory";
import { useDocuments } from "../lib/documents";
import { navigate, type Route } from "../lib/routes";
diff --git a/packages/shift-manager/src/surfaces/ShiftCoordinator.tsx b/packages/shift-manager/src/surfaces/ShiftCoordinator.tsx
index 8a64b051c6..f8ca747fd9 100644
--- a/packages/shift-manager/src/surfaces/ShiftCoordinator.tsx
+++ b/packages/shift-manager/src/surfaces/ShiftCoordinator.tsx
@@ -32,7 +32,7 @@ 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, Meta, PartialMark, ScreenTitle, SectionFailure, ShiftMark } from "../components/ui";
+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";
diff --git a/packages/shift-manager/src/surfaces/Sidebar.tsx b/packages/shift-manager/src/surfaces/Sidebar.tsx
index 42b5a8efcf..a204047133 100644
--- a/packages/shift-manager/src/surfaces/Sidebar.tsx
+++ b/packages/shift-manager/src/surfaces/Sidebar.tsx
@@ -35,7 +35,8 @@ import { useLab } from "../lib/lab-data";
import { useProjects, useWorkers } from "../lib/directory";
import { workerLabel, workerStates, shiftCounts, teamsOf } from "../lib/shift";
import { openBoardTasks, useInbox } from "../lib/inbox";
-import { useProjectWorkstreams, type Project, type WorkstreamEntry } from "../lib/projects";
+import { useProjectWorkstreams, type WorkstreamEntry } from "../lib/projects";
+import type { Project } from "../lib/project";
import { initialsOf } from "../lib/shell";
import { useShiftCoordinatorWorking } from "../lib/working";
import { Meta, PartialMark, SectionFailure, ShiftMark } from "../components/ui";
diff --git a/packages/shift-manager/test/columns.test.ts b/packages/shift-manager/test/columns.test.ts
index b1f9b1635d..f43c84afe1 100644
--- a/packages/shift-manager/test/columns.test.ts
+++ b/packages/shift-manager/test/columns.test.ts
@@ -10,7 +10,8 @@ import { taskStatusSchema } from "@flow-state-dev/orchestration/tasks";
import { COLUMNS, columnFor, isHeld, isDone } from "../src/lib/columns";
import { openTasks, type LoadedSnapshot } from "../src/lib/derive";
import { workerFor } from "../src/lib/shift";
-import { toBoardTaskView, type BoardTaskView } from "../src/lib/reads";
+import { toBoardTaskView } from "../src/lib/reads";
+import type { BoardTaskView } from "../src/lib/boards";
import { toWorker } from "../src/lib/workers";
/** Where BR-12 puts each shipped status. */
diff --git a/packages/shift-manager/test/conversation.test.tsx b/packages/shift-manager/test/conversation.test.tsx
index a9be7cd132..625200c0c4 100644
--- a/packages/shift-manager/test/conversation.test.tsx
+++ b/packages/shift-manager/test/conversation.test.tsx
@@ -13,7 +13,7 @@ import type { SessionSummary } from "@flow-state-dev/client";
import { useState } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { GAPS } from "../src/gaps";
-import type { Worker } from "../src/lib/reads";
+import type { Worker } from "../src/lib/workers";
import { TurnNotDelivered } from "../src/lib/deliver";
const read = vi.fn();
diff --git a/packages/shift-manager/test/goal-labs.test.ts b/packages/shift-manager/test/goal-labs.test.ts
index c81e482935..81852520a5 100644
--- a/packages/shift-manager/test/goal-labs.test.ts
+++ b/packages/shift-manager/test/goal-labs.test.ts
@@ -15,7 +15,8 @@ import { loadFsdevConfig } from "@flow-state-dev/fsdev";
import { readWorkforceFolder, type WorkforceFolder } from "@flow-state-dev/workforce/loader";
import type { Client } from "@flow-state-dev/client";
import { connect } from "../src/lib/connection";
-import { createLabReader, type Ask, type BoardTaskView } from "../src/lib/reads";
+import { createLabReader, type Ask } from "../src/lib/reads";
+import type { BoardTaskView } from "../src/lib/boards";
import { collectionOfBoard } from "../src/lib/boards";
import { GENERAL_TEAM } from "../src/lib/workers";
import { type LoadedSnapshot } from "../src/lib/derive";
diff --git a/packages/shift-manager/test/helpers/inbox-view.ts b/packages/shift-manager/test/helpers/inbox-view.ts
index 76694febef..1824a12560 100644
--- a/packages/shift-manager/test/helpers/inbox-view.ts
+++ b/packages/shift-manager/test/helpers/inbox-view.ts
@@ -8,7 +8,8 @@
import { suspendForUserKindOf } from "@flow-state-dev/core/types";
import { boardOwnerOf, type LoadedSnapshot } from "../../src/lib/derive";
import type { InboxAsk, InboxViewValue } from "../../src/lib/inbox";
-import type { Ask, LabSnapshot, Section } from "../../src/lib/reads";
+import type { Ask, LabSnapshot } from "../../src/lib/reads";
+import type { Section } from "../../src/lib/failure";
/** An ask as the view's detail carries it. */
function askOf(ask: Ask): InboxAsk {
diff --git a/packages/shift-manager/test/inbox-tasks.test.ts b/packages/shift-manager/test/inbox-tasks.test.ts
index 9dd6a58c0f..6f31862a08 100644
--- a/packages/shift-manager/test/inbox-tasks.test.ts
+++ b/packages/shift-manager/test/inbox-tasks.test.ts
@@ -16,7 +16,9 @@ import { elapsed, isQueued, nothingWaitingSentence, summaryLine } from "../src/l
import type { InboxAsk, InboxViewValue } from "../src/lib/inbox";
import { itemAtRoute } from "../src/lib/inbox-list";
import type { LoadedSnapshot } from "../src/lib/derive";
-import { inboxSection, type Ask, type BoardTaskView, type Worker } from "../src/lib/reads";
+import { inboxSection, type Ask } from "../src/lib/reads";
+import type { BoardTaskView } from "../src/lib/boards";
+import type { Worker } from "../src/lib/workers";
let index = 0;
function item(fields: Record): OutputItem {
diff --git a/packages/shift-manager/test/inbox.test.ts b/packages/shift-manager/test/inbox.test.ts
index ac43008e1a..7e7334a521 100644
--- a/packages/shift-manager/test/inbox.test.ts
+++ b/packages/shift-manager/test/inbox.test.ts
@@ -14,7 +14,8 @@ import { reconcileInbox, taskTruthOf, suspensionTruthOf, taskItemId, type InboxT
import { DEFAULT_ORG_ID } from "@flow-state-dev/core";
import { COORDINATOR_FLOW } from "@flow-state-dev/workforce";
import { connect } from "../src/lib/connection";
-import { conversationOfTopic, createLabReader, inboxSection, toBoardTaskView, type BoardTaskView, type LabSnapshot } from "../src/lib/reads";
+import { conversationOfTopic, createLabReader, inboxSection, toBoardTaskView, type LabSnapshot } from "../src/lib/reads";
+import type { BoardTaskView } from "../src/lib/boards";
import { CONVERSATION_BOARD_COLLECTION, conversationBoardRef } from "../src/lib/boards";
import { ASK_LAB_USER_ID, openAskLab } from "./fixtures/ask-lab/lab.mts";
import { ASKER_FLOW } from "./fixtures/ask-lab/asker.mts";
diff --git a/packages/shift-manager/test/inventory-allowlist.json b/packages/shift-manager/test/inventory-allowlist.json
index e7288dcbd3..40d6266985 100644
--- a/packages/shift-manager/test/inventory-allowlist.json
+++ b/packages/shift-manager/test/inventory-allowlist.json
@@ -6,13 +6,8 @@
{"file":"src/lib/snapshot-subscribe.ts","symbol":"topic","kind":"client import"},
{"file":"src/lib/derive.ts","symbol":"LoadedSnapshot","kind":"type"},
{"file":"src/lib/derive.ts","symbol":"ProjectsView","kind":"type"},
- {"file":"src/lib/reads.ts","symbol":"Failure","kind":"type"},
- {"file":"src/lib/reads.ts","symbol":"Section","kind":"type"},
- {"file":"src/lib/reads.ts","symbol":"Worker","kind":"type"},
- {"file":"src/lib/reads.ts","symbol":"Project","kind":"type"},
{"file":"src/lib/reads.ts","symbol":"Projects","kind":"type"},
{"file":"src/lib/reads.ts","symbol":"RunLink","kind":"type"},
- {"file":"src/lib/reads.ts","symbol":"BoardTaskView","kind":"type"},
{"file":"src/lib/reads.ts","symbol":"ConversationBoards","kind":"type"},
{"file":"src/lib/reads.ts","symbol":"Ask","kind":"type"},
{"file":"src/lib/reads.ts","symbol":"DeclaredResource","kind":"type"},
diff --git a/packages/shift-manager/test/inventory-settings.ts b/packages/shift-manager/test/inventory-settings.ts
index 8e70eff2b0..f010b9c78e 100644
--- a/packages/shift-manager/test/inventory-settings.ts
+++ b/packages/shift-manager/test/inventory-settings.ts
@@ -77,7 +77,6 @@ export const shiftManager: AppInventory = {
"src/lib/columns.ts": ["Column"],
"src/lib/conversation-tasks.ts": ["ConversationTask"],
"src/lib/conversation.ts": ["WorkerConversation"],
- "src/lib/derive.ts": ["Roster", "WorkerState", "WorkerStates"],
"src/lib/directory-reads.ts": [
{ name: "CollectionRead", reason: "a useResource read of a whole collection as the directory holds it: its parsed values, its failure and its refresh" },
{ name: "DirectoryReads", reason: "the directory's reads, one hook's output assembled from useResource, the roster watch and useSessionList" },
@@ -93,9 +92,11 @@ export const shiftManager: AppInventory = {
"src/lib/inbox.ts": ["ReviewData"],
"src/lib/lab-data.tsx": ["LabData"],
"src/lib/messages.ts": ["MessageExchange"],
+ "src/lib/project.ts": [
+ { name: "Project", reason: "a projects row with where it lives, parsed by toProject so a row an earlier version wrote still reads (BP-030); the collection's client data names no visibility" },
+ ],
"src/lib/projects.ts": [
"ProjectAddress",
- { name: "Project", reason: "a projects row with where it lives, parsed by toProject so a row an earlier version wrote still reads (BP-030); the collection's client data names no visibility" },
{ name: "WorkstreamEntry", reason: "workforce's ParsedWorkstreamEntry with its storage key and whether it has gone quiet, which the screen works out by projectProgress's clock" },
{ name: "ProjectWorkstreams", reason: "a project's entries with the progress the screen works out from them (projectProgress): a hook's output, assembled" },
{ name: "ScreenRead", reason: "UI state: a hook's value, its failure and its refresh, as the project screens draw a read" },
diff --git a/packages/shift-manager/test/projects.test.tsx b/packages/shift-manager/test/projects.test.tsx
index b25f3b143b..e531e497fd 100644
--- a/packages/shift-manager/test/projects.test.tsx
+++ b/packages/shift-manager/test/projects.test.tsx
@@ -17,8 +17,8 @@ import { readProject } from "../src/lib/projects";
import { connect } from "../src/lib/connection";
import { projectsOf, type LoadedSnapshot } from "../src/lib/derive";
import { PROJECTS_PATTERN } from "@flow-state-dev/workforce/browser";
-import { createLabReader, type Project } from "../src/lib/reads";
-import { toProject } from "../src/lib/projects";
+import { createLabReader } from "../src/lib/reads";
+import { toProject, type Project } from "../src/lib/project";
import { ASKER_FLOW } from "./fixtures/ask-lab/asker.mts";
import { ASK_LAB_USER_ID, openAskLab } from "./fixtures/ask-lab/lab.mts";
import { eventually, serveLab, type ServedLab } from "./helpers/serve-lab";
diff --git a/packages/shift-manager/test/reads.test.ts b/packages/shift-manager/test/reads.test.ts
index 7c4dffb3ee..4c6f7085cf 100644
--- a/packages/shift-manager/test/reads.test.ts
+++ b/packages/shift-manager/test/reads.test.ts
@@ -11,9 +11,7 @@ import { DEFAULT_ORG_ID } from "@flow-state-dev/core";
import { afterEach, describe, expect, it, vi } from "vitest";
import { connect } from "../src/lib/connection";
import { createLabReader, UNOWNED_SESSION_UNANSWERABLE, type LabSnapshot } from "../src/lib/reads";
-import { workerStates, type LoadedSnapshot } from "../src/lib/derive";
-import { joinWorkers } from "../src/lib/workers";
-import { createWorkforceClient } from "@flow-state-dev/workforce/browser";
+import type { LoadedSnapshot } from "../src/lib/derive";
import { ROSTER_FLOW, rosterView } from "@flow-state-dev/workforce/browser";
import { COORDINATOR_FLOW } from "@flow-state-dev/workforce";
import { ASK_LAB_COORDINATORS, ASK_LAB_USER_ID, openAskLab } from "./fixtures/ask-lab/lab.mts";
@@ -401,12 +399,6 @@ describe("asks through a coordinator's delivery (V7)", () => {
if (!snapshot.asks.ok || !snapshot.inventory.ok) throw new Error("not loaded");
expect(snapshot.inventory.value.workers.map((s) => s.id)).not.toContain("ops.mine");
expect(snapshot.asks.value.map((a) => [a.workerId, a.item.message])).toEqual([["ops.mine", "Approve: ship it"]]);
-
- // Roster and TEAMS join the roster the same way, so the worker is on shift there.
- const entries = await createWorkforceClient(client).roster();
- const { workers } = joinWorkers(snapshot.inventory.ok ? snapshot.inventory.value.workers : undefined, entries);
- const states = workerStates({ ...snapshot, inventory: { ok: true, value: { workers } } });
- expect(states.workers.get("ops.mine")?.status).toBe("on shift");
});
it("a roster that fails to load fails Inbox's asks by name, not by dropping the user's own workers", async () => {
diff --git a/packages/shift-manager/test/roster-screen.test.tsx b/packages/shift-manager/test/roster-screen.test.tsx
index 8f7d09df3d..e2e985f64c 100644
--- a/packages/shift-manager/test/roster-screen.test.tsx
+++ b/packages/shift-manager/test/roster-screen.test.tsx
@@ -11,7 +11,9 @@ import { GAPS } from "../src/gaps";
import type { Client } from "@flow-state-dev/client";
import { spendAfterWrite } from "@flow-state-dev/orchestration/tasks";
import type { LoadedSnapshot } from "../src/lib/derive";
-import { inboxSection, toBoardTaskView, type Ask, type BoardTaskView, type ConversationBoards, type LabSnapshot, type Section } from "../src/lib/reads";
+import { inboxSection, toBoardTaskView, type Ask, type ConversationBoards, type LabSnapshot } from "../src/lib/reads";
+import type { BoardTaskView } from "../src/lib/boards";
+import type { Section } from "../src/lib/failure";
import { GENERAL_TEAM, toWorker } from "../src/lib/workers";
let fixture: LabSnapshot;
diff --git a/packages/shift-manager/test/shift-coordinator.test.ts b/packages/shift-manager/test/shift-coordinator.test.ts
index ce5cc7e3e3..5ff28d6d8d 100644
--- a/packages/shift-manager/test/shift-coordinator.test.ts
+++ b/packages/shift-manager/test/shift-coordinator.test.ts
@@ -10,7 +10,9 @@ import { shiftSummary, type LoadedSnapshot } from "../src/lib/derive";
import { shiftCoordinatorOf } from "../src/lib/shift";
import { conversationAt } from "../src/lib/conversation";
import { parseRoute, pathFor, type Route } from "../src/lib/routes";
-import { inboxSection, type Ask, type BoardTaskView, type Worker } from "../src/lib/reads";
+import { inboxSection, type Ask } from "../src/lib/reads";
+import type { BoardTaskView } from "../src/lib/boards";
+import type { Worker } from "../src/lib/workers";
import { GENERAL_TEAM, toWorker } from "../src/lib/workers";
const ORG = "org_1";
diff --git a/packages/shift-manager/test/task-actions.test.ts b/packages/shift-manager/test/task-actions.test.ts
index 85e7ea6079..790e152432 100644
--- a/packages/shift-manager/test/task-actions.test.ts
+++ b/packages/shift-manager/test/task-actions.test.ts
@@ -11,7 +11,8 @@ import type { Client } from "@flow-state-dev/client";
import { taskActionName } from "@flow-state-dev/orchestration/inbox";
import { COORDINATOR_FLOW } from "@flow-state-dev/workforce";
import { connect } from "../src/lib/connection";
-import { createLabReader, type BoardTaskView } from "../src/lib/reads";
+import { createLabReader } from "../src/lib/reads";
+import type { BoardTaskView } from "../src/lib/boards";
import { CONVERSATION_BOARD_COLLECTION } from "../src/lib/boards";
import { ASK_LAB_USER_ID, openAskLab } from "./fixtures/ask-lab/lab.mts";
import { ASKER_FLOW } from "./fixtures/ask-lab/asker.mts";
diff --git a/packages/shift-manager/test/task-screen.test.tsx b/packages/shift-manager/test/task-screen.test.tsx
index b09aef2dd3..2a13d600ea 100644
--- a/packages/shift-manager/test/task-screen.test.tsx
+++ b/packages/shift-manager/test/task-screen.test.tsx
@@ -13,7 +13,8 @@ import { App } from "../src/App";
import { GAPS } from "../src/gaps";
import { connect } from "../src/lib/connection";
import { readSessionItems } from "./helpers/session-reads";
-import { createLabReader, toBoardTaskView, type BoardTaskView } from "../src/lib/reads";
+import { createLabReader, toBoardTaskView } from "../src/lib/reads";
+import type { BoardTaskView } from "../src/lib/boards";
import { CONVERSATION_BOARD_COLLECTION, conversationBoardRef } from "../src/lib/boards";
import { openRunLab, RUN_LAB_ASK, RUN_LAB_FAILURE, RUN_LAB_SPEND, RUN_LAB_USER_ID } from "./fixtures/run-lab/lab.mts";
import { eventually, serveLab, type ServedLab } from "./helpers/serve-lab";
diff --git a/packages/shift-manager/test/turn-routes.test.ts b/packages/shift-manager/test/turn-routes.test.ts
index f1f1c20ef0..3a7e23719f 100644
--- a/packages/shift-manager/test/turn-routes.test.ts
+++ b/packages/shift-manager/test/turn-routes.test.ts
@@ -4,7 +4,7 @@
*/
import { describe, expect, it } from "vitest";
import { doorOf } from "../src/lib/shift";
-import type { Worker } from "../src/lib/reads";
+import type { Worker } from "../src/lib/workers";
const worker = (id: string, door: string | null = "message", flow = "coder"): Worker => ({
id,
diff --git a/packages/shift-manager/test/worker-settings-screen.test.tsx b/packages/shift-manager/test/worker-settings-screen.test.tsx
index 4a157e8af1..b90f9a5e57 100644
--- a/packages/shift-manager/test/worker-settings-screen.test.tsx
+++ b/packages/shift-manager/test/worker-settings-screen.test.tsx
@@ -8,7 +8,8 @@ import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-li
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { App } from "../src/App";
import type { Client } from "@flow-state-dev/client";
-import { type LabSnapshot, type Worker } from "../src/lib/reads";
+import { type LabSnapshot } from "../src/lib/reads";
+import type { Worker } from "../src/lib/workers";
import { toWorker } from "../src/lib/workers";
import { MAX_RULE_CHARS } from "@flow-state-dev/workforce/browser";
From 44ff6ed49f048d4bf8435dd70c1559ed2d41231a Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 01:46:43 +0000
Subject: [PATCH 19/24] docs(shift-manager): page-reads names the user, not a
person (FIX-2775)
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiGfuuX5mPxVeUwVXfa
---
packages/shift-manager/src/lib/page-reads.tsx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/packages/shift-manager/src/lib/page-reads.tsx b/packages/shift-manager/src/lib/page-reads.tsx
index b06a0a2731..cf987ae70d 100644
--- a/packages/shift-manager/src/lib/page-reads.tsx
+++ b/packages/shift-manager/src/lib/page-reads.tsx
@@ -2,7 +2,7 @@
* The reads a screen holds, for R to read again. Each screen read registers
* its read-again with {@link useReadAgainOnR} while it is mounted, and R reads
* again every one registered, beside the directory's and the Inbox view's: a
- * person pressing R on Messages reads the message log again, and on a project
+ * user pressing R on Messages reads the message log again, and on a project
* its workstreams. Outside a {@link PageReadsProvider} (a component under test
* on its own) registering does nothing.
*/
From 68da78fe7ab15464e6830ad6abe0f742b5582146 Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 01:51:46 +0000
Subject: [PATCH 20/24] goal: import Worker and toWorker from workers.ts, not
reads.ts (FIX-2775)
The goals typecheck failed on optimistic-reply.ts, which imported Worker from
reads.ts after it moved. sent-line-rises-reply-stays's Shift Manager page
imported toWorker from reads.ts too (a page copied into the package, outside
the goals typecheck); its fake Lab drops the answered field Shift Manager no
longer has.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiGfuuX5mPxVeUwVXfa
---
.../pages/shift-manager/fakes/lab-data.ts | 2 +-
.../sent-line-rises-reply-stays/pages/shift-manager/main.tsx | 2 +-
.../controls/optimistic-reply.ts | 2 +-
3 files changed, 3 insertions(+), 3 deletions(-)
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/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";
From c235eb9028e7f70103ec94ee1dab8b5a6c19a683 Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 01:54:15 +0000
Subject: [PATCH 21/24] fix(shift-manager): the frame waits for the roster,
shows a failed session list, and Jump to drops stale documents (FIX-2775)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
From Codex's review of #5492:
- A first session list that failed landed as an empty list, so every screen
drew no sessions. The directory now keeps the last list that landed and the
failure apart; a failed first list is the couldn't-reach page with Retry, as
a failed first whole-Lab read was.
- The frame drew before the roster watch landed, so the inventory's workers
showed and then the user's own joined them. The directory has not landed
until the roster has.
- Jump to showed the previous flow set's documents while a new flow's manifest
was read. It is unread until the read for the current flows lands.
Each was red first: directory.test.tsx ('the given combination of arguments
(undefined and string) is invalid', 'expected true to be false'),
documents.test.tsx ('expected { ok: true, value: [ { …(2) } ] } to be
undefined').
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiGfuuX5mPxVeUwVXfa
---
packages/shift-manager/src/App.tsx | 21 +++++-
.../shift-manager/src/lib/directory-reads.ts | 19 ++++--
packages/shift-manager/src/lib/directory.tsx | 17 ++---
packages/shift-manager/src/lib/documents.ts | 3 +-
.../shift-manager/test/directory.test.tsx | 68 ++++++++++++++++---
.../shift-manager/test/documents.test.tsx | 51 ++++++++++++++
.../shift-manager/test/helpers/directory.ts | 2 +-
.../shift-manager/test/inventory-settings.ts | 1 +
8 files changed, 154 insertions(+), 28 deletions(-)
create mode 100644 packages/shift-manager/test/documents.test.tsx
diff --git a/packages/shift-manager/src/App.tsx b/packages/shift-manager/src/App.tsx
index 6aeb4639e1..f0a290ad5b 100644
--- a/packages/shift-manager/src/App.tsx
+++ b/packages/shift-manager/src/App.tsx
@@ -20,7 +20,7 @@ import { GAPS, type Gaps } from "./gaps";
import type { ThemeLook } from "./lib/theme";
import type { Connection } from "./lib/connection";
import { LabProvider, useLab } from "./lib/lab-data";
-import { DirectoryProvider, useDirectoryLanded, useProjects, useWorkers } from "./lib/directory";
+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";
@@ -108,9 +108,24 @@ function Shell({ gaps, devtoolUrl, look }: { gaps: Gaps; devtoolUrl: string | un
);
}
-/** The frame, once the directory's first reads have landed; until then, the page is still reading the Lab. */
+/**
+ * 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 }) {
- return useDirectoryLanded() ? children : READING;
+ 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. */
diff --git a/packages/shift-manager/src/lib/directory-reads.ts b/packages/shift-manager/src/lib/directory-reads.ts
index 65b8163d6d..e4e726b38c 100644
--- a/packages/shift-manager/src/lib/directory-reads.ts
+++ b/packages/shift-manager/src/lib/directory-reads.ts
@@ -20,14 +20,17 @@ 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. */
- sessions: { list: readonly SessionSummary[] | undefined; refresh: () => void };
+ /** 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 };
};
@@ -67,11 +70,13 @@ export function useDirectoryReads(): DirectoryReads {
const own = useParsed(useResource(privateProjectsResource, { client, all: true }), privateProject);
const roster = useRoster();
const listing = useSessionList({ client, includeDispatchRuns: true, includeStatus: false });
- // Undefined only before the first list lands: a later read of an empty list is still a list.
- const landed = useRef(false);
- if (!listing.isLoading || listing.sessions.length > 0 || listing.error !== null) landed.current = true;
- const listed = landed.current ? listing.sessions : undefined;
- const sessions = useMemo(() => ({ list: listed, refresh: listing.refresh }), [listed, listing.refresh]);
+ // 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
index 5bfae657c7..160b9d6eaa 100644
--- a/packages/shift-manager/src/lib/directory.tsx
+++ b/packages/shift-manager/src/lib/directory.tsx
@@ -10,8 +10,7 @@
* who is on shift reads the Inbox view against them (`shift.ts`).
*/
import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from "react";
-import type { SessionSummary } from "@flow-state-dev/client";
-import { useDirectoryReads, type CollectionRead } from "./directory-reads";
+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";
@@ -48,7 +47,7 @@ export type Workers = {
/** The directory: the workers, the sessions and the projects. */
type Directory = {
workers: Workers;
- sessions: { list: readonly SessionSummary[] | undefined; refresh: () => void };
+ sessions: Sessions;
projects: { section: Section | undefined; refresh: () => void };
};
@@ -61,7 +60,7 @@ const nothing = () => {};
*/
const UNREAD: Directory = {
workers: { inventory: undefined, workers: [], own: [], roster: undefined, readAt: undefined, refresh: nothing },
- sessions: { list: undefined, refresh: nothing },
+ sessions: { list: undefined, failure: undefined, refresh: nothing },
projects: { section: undefined, refresh: nothing },
};
@@ -151,11 +150,13 @@ export function useProjects(): Directory["projects"] {
/**
* Whether the directory's first reads have landed, or failed: the inventory,
- * 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. The roster
- * isn't waited for: a screen says when it hasn't loaded.
+ * 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();
- return workers.inventory !== undefined && sessions.list !== undefined && projects.section !== undefined;
+ 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
index f11b7f2c00..acaaeee6c8 100644
--- a/packages/shift-manager/src/lib/documents.ts
+++ b/packages/shift-manager/src/lib/documents.ts
@@ -73,5 +73,6 @@ export function useDocuments(): Section | undefined {
// The flows decide what is read; a session list that names the same flows reads nothing new.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [client, flows]);
- return read?.section;
+ // A read for another set of flows is never this one's answer: unread until it lands.
+ return read !== undefined && read.flows === flows ? read.section : undefined;
}
diff --git a/packages/shift-manager/test/directory.test.tsx b/packages/shift-manager/test/directory.test.tsx
index 74f755008c..e73be0be75 100644
--- a/packages/shift-manager/test/directory.test.tsx
+++ b/packages/shift-manager/test/directory.test.tsx
@@ -22,6 +22,8 @@ const hear = (notice: WireNotice) => opened.filter((o) => !o.closed).forEach((o)
const stored: Record> = {};
/** Every whole read made, by `:`. */
const lists: string[] = [];
+/** How the session list answers; a test swaps it. */
+let listSessions: (...args: unknown[]) => Promise = async () => [];
const client = {
userId: "u_1",
resource: ({ scope, pattern }: { scope: string; pattern: string }) => ({
@@ -39,26 +41,29 @@ const client = {
opened.push(entry);
return { close: () => void (entry.closed = true) };
},
- sessions: { list: async () => [] },
+ sessions: { list: (...args: unknown[]) => listSessions(...args) },
};
vi.mock("../src/lib/lab-data", () => ({ useLab: () => ({ client }) }));
let rosterWatches = 0;
+const ROSTER = [
+ { id: "eng.coder", flow: "coder", standard: true, description: null, name: null, teamName: null, settings: { harness: "codex" } },
+ { id: "amber", flow: "coder", standard: false, description: null, name: "Amber", teamName: null },
+];
+/** When set, the roster watch holds its first answer until the test calls it. */
+let holdRoster = false;
+let releaseRoster: (() => void) | undefined;
const workforce = {
watchRoster: (onRoster: (entries: unknown[]) => void) => {
rosterWatches += 1;
- void Promise.resolve().then(() =>
- onRoster([
- { id: "eng.coder", flow: "coder", standard: true, description: null, name: null, teamName: null, settings: { harness: "codex" } },
- { id: "amber", flow: "coder", standard: false, description: null, name: "Amber", teamName: null },
- ]),
- );
+ if (holdRoster) releaseRoster = () => onRoster(ROSTER);
+ else void Promise.resolve().then(() => onRoster(ROSTER));
return () => {};
},
};
vi.mock("../src/lib/workforce", () => ({ useWorkforce: () => workforce }));
-import { DirectoryProvider, useWorkers } from "../src/lib/directory";
+import { DirectoryProvider, useDirectoryLanded, useSessions, useWorkers } from "../src/lib/directory";
const INVENTORY = "inventory/workers/*";
const drawn: Array = [];
@@ -73,6 +78,9 @@ beforeEach(() => {
lists.splice(0);
drawn.splice(0);
rosterWatches = 0;
+ holdRoster = false;
+ releaseRoster = undefined;
+ listSessions = async () => [];
stored[INVENTORY] = [{ storageKey: "inventory/workers/eng.coder", value: { id: "eng.coder", kind: "coder", door: "run" } }];
});
afterEach(cleanup);
@@ -97,3 +105,47 @@ describe("the worker directory", () => {
expect(lists.filter((list) => list === `org:${INVENTORY}`)).toHaveLength(2);
});
});
+
+describe("the directory's first reads", () => {
+ type Seen = { landed: boolean; sessions: ReturnType };
+ const seen: Seen[] = [];
+ function Probe() {
+ seen.push({ landed: useDirectoryLanded(), sessions: useSessions() });
+ return null;
+ }
+ beforeEach(() => void seen.splice(0));
+
+ it("a session list that fails its first read lands as that failure, never as no sessions, and a refresh that lands clears it", async () => {
+ listSessions = async () => {
+ throw new Error("the session store is down");
+ };
+ render(
+
+
+ ,
+ );
+ await waitFor(() => expect(seen.at(-1)!.sessions.failure?.message).toContain("the session store is down"));
+ // Not one drawn state says the user has no sessions.
+ expect(seen.some((s) => s.sessions.list !== undefined)).toBe(false);
+ expect(seen.at(-1)!.landed).toBe(true);
+
+ listSessions = async () => [];
+ act(() => seen.at(-1)!.sessions.refresh());
+ await waitFor(() => expect(seen.at(-1)!.sessions.list).toEqual([]));
+ expect(seen.at(-1)!.sessions.failure).toBeUndefined();
+ });
+
+ it("hasn't landed until the roster has: no frame draws the inventory's workers before the user's own join them", async () => {
+ holdRoster = true;
+ render(
+
+
+ ,
+ );
+ await waitFor(() => expect(seen.at(-1)!.sessions.list).toEqual([]));
+ await waitFor(() => expect(lists).toContain(`org:${INVENTORY}`));
+ expect(seen.some((s) => s.landed)).toBe(false);
+ act(() => releaseRoster!());
+ await waitFor(() => expect(seen.at(-1)!.landed).toBe(true));
+ });
+});
diff --git a/packages/shift-manager/test/documents.test.tsx b/packages/shift-manager/test/documents.test.tsx
new file mode 100644
index 0000000000..faa657629e
--- /dev/null
+++ b/packages/shift-manager/test/documents.test.tsx
@@ -0,0 +1,51 @@
+// @vitest-environment happy-dom
+/**
+ * Jump to's documents (FIX-2775): read from each listed flow's manifest, and
+ * read again when a flow appears in the session list. While that read is out
+ * the section is unread, never the previous flow set's documents, which would
+ * leave out the new flow's as if it served none.
+ *
+ * The client's manifest reads and the session list are the test's; the hook is
+ * the app's.
+ */
+import { renderHook, waitFor } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+
+const doc = (ref: string) => ({ kind: "single", ref, client: { content: { read: true } } });
+/** Each flow's manifest; a flow whose answer is held resolves when the test says. */
+const manifests: Record> = {};
+const client = {
+ userId: "u_1",
+ resources: { getResourceManifest: (sessionId: string) => manifests[sessionId.replace(/^s-/, "")]! },
+};
+vi.mock("../src/lib/lab-data", () => ({ useLab: () => ({ client }) }));
+let listed: Array<{ id: string; flowKind: string; flowId?: string }> = [];
+vi.mock("../src/lib/directory", () => ({ useSessions: () => ({ list: listed, failure: undefined, refresh: () => {} }) }));
+
+import { useDocuments } from "../src/lib/documents";
+
+describe("Jump to's documents", () => {
+ it("are unread while a new flow's manifest is read, then list every flow's", async () => {
+ manifests.alpha = Promise.resolve({ resources: [doc("alpha-notes")] });
+ listed = [{ id: "s-alpha", flowKind: "alpha" }];
+ const { result, rerender } = renderHook(() => useDocuments());
+ await waitFor(() => expect(result.current).toEqual({ ok: true, value: [{ ref: "alpha-notes", sessionId: "s-alpha" }] }));
+
+ let answerBeta!: (manifest: { resources: unknown[] }) => void;
+ manifests.beta = new Promise((resolve) => (answerBeta = resolve));
+ listed = [...listed, { id: "s-beta", flowKind: "beta" }];
+ rerender();
+ expect(result.current).toBeUndefined();
+
+ answerBeta({ resources: [doc("beta-notes")] });
+ await waitFor(() =>
+ expect(result.current).toEqual({
+ ok: true,
+ value: [
+ { ref: "alpha-notes", sessionId: "s-alpha" },
+ { ref: "beta-notes", sessionId: "s-beta" },
+ ],
+ }),
+ );
+ });
+});
diff --git a/packages/shift-manager/test/helpers/directory.ts b/packages/shift-manager/test/helpers/directory.ts
index 102b50724e..f81f075de6 100644
--- a/packages/shift-manager/test/helpers/directory.ts
+++ b/packages/shift-manager/test/helpers/directory.ts
@@ -35,7 +35,7 @@ function readsOfSnapshot(snapshot: LabSnapshot | undefined, refresh: () => void)
const projects = loaded?.projects ?? { ok: true as const, value: { rows: [] } };
const fixed: Fixed = {
inventory: loaded === undefined ? read(undefined) : read(loaded.inventory.ok ? { ok: true, value: loaded.inventory.value.workers } : loaded.inventory),
- sessions: { list: loaded?.sessions, refresh },
+ sessions: { list: loaded?.sessions, failure: undefined, refresh },
projects: {
shared: loaded === undefined ? read(undefined) : read(projects!.ok ? { ok: true, value: projects!.value.rows.filter((p) => p.visibility === "shared") } : projects!),
own: loaded === undefined ? read(undefined) : read(projects!.ok ? { ok: true, value: projects!.value.rows.filter((p) => p.visibility === "private") } : { ok: true, value: [] }),
diff --git a/packages/shift-manager/test/inventory-settings.ts b/packages/shift-manager/test/inventory-settings.ts
index f010b9c78e..154698a52b 100644
--- a/packages/shift-manager/test/inventory-settings.ts
+++ b/packages/shift-manager/test/inventory-settings.ts
@@ -79,6 +79,7 @@ export const shiftManager: AppInventory = {
"src/lib/conversation.ts": ["WorkerConversation"],
"src/lib/directory-reads.ts": [
{ name: "CollectionRead", reason: "a useResource read of a whole collection as the directory holds it: its parsed values, its failure and its refresh" },
+ { name: "Sessions", reason: "useSessionList's sessions as the directory holds them: the last list that landed, why the last list failed, and its refresh" },
{ name: "DirectoryReads", reason: "the directory's reads, one hook's output assembled from useResource, the roster watch and useSessionList" },
],
"src/lib/directory.tsx": [{ name: "Workers", reason: "the worker directory a screen draws: the inventory joined with the roster (D1), a hook's output assembled from two reads" }],
From 25b6080c9fd150fe3abc4702baf8e972f811dc59 Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 01:55:14 +0000
Subject: [PATCH 22/24] check(FIX-2775): the built census lets FIX-2777's
allowlist shrink, never grow
Moving Failure, Section, Worker, Project and BoardTaskView out of reads.ts
leaves one definition each, so their five reads.ts type entries went with them
(21 -> 16). The built check held FIX-2777's count equal to main's; it now holds
it at most main's, as the inventory test holds the whole allowlist. The
pre-implementation count is unchanged. The inventory settings name Sessions.
Co-Authored-By: Claude Opus 5.5