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>>(); + +function manifestFor(client: Pick, flow: string, sessionId: string): Promise { + let byFlow = manifests.get(client); + if (byFlow === undefined) { + byFlow = new Map(); + manifests.set(client, byFlow); + } + const held = byFlow; + let found = held.get(flow); + if (found === undefined) { + found = client.resources.getResourceManifest(sessionId); + found.catch(() => held.delete(flow)); + held.set(flow, found); + } + return found; +} + +/** Every listed flow's single resources whose content a client may read, by ref. */ +async function documentsOf(client: Pick, sessions: readonly SessionSummary[]): Promise { + const byFlow = new Map(); + for (const session of sessions) { + const flow = session.flowId ?? session.flowKind; + if (!byFlow.has(flow)) byFlow.set(flow, session.id); + } + const found = new Map(); + for (const [flow, sessionId] of byFlow) { + for (const entry of (await manifestFor(client, flow, sessionId)).resources) { + if (entry.kind === "single" && entry.client.content?.read === true && !found.has(entry.ref)) found.set(entry.ref, { ref: entry.ref, sessionId }); + } + } + return [...found.values()].sort((a, b) => a.ref.localeCompare(b.ref)); +} + +/** + * The declared documents, read while the screen that draws them is open (Jump + * to), once the session list has landed, and again when a flow appears in it. + * `undefined` while they are read. + */ +export function useDocuments(): Section | undefined { + const { client } = useLab(); + const sessions = useSessions().list; + const [read, setRead] = useState<{ flows: string; section: Section } | undefined>(undefined); + const flows = sessions === undefined ? undefined : [...new Set(sessions.map((s) => s.flowId ?? s.flowKind))].sort().join("\n"); + useEffect(() => { + if (sessions === undefined || flows === undefined) return; + let live = true; + documentsOf(client, sessions).then( + (documents) => live && setRead({ flows, section: { ok: true, value: documents } }), + (error: unknown) => live && setRead({ flows, section: { ok: false, failure: describeFailure(error) } }), + ); + return () => { + live = false; + }; + // 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; +} diff --git a/packages/shift-manager/src/lib/failure.ts b/packages/shift-manager/src/lib/failure.ts new file mode 100644 index 0000000000..fe1f25182f --- /dev/null +++ b/packages/shift-manager/src/lib/failure.ts @@ -0,0 +1,18 @@ +/** + * Why a read or a write did not go through, in the words a screen shows, and + * a section's outcome: its value, or that failure. One rule with `react`'s + * hooks (`failureOf`), so a Retry note reads the same whether a hook's read + * failed or a write the screen sent was refused. + */ +import { failureOf, type ViewReadFailure } from "@flow-state-dev/react/internal"; + +/** Why a read did not load: the server's reason, and its HTTP status when it answered one. */ +export type Failure = ViewReadFailure; + +/** One section's outcome: its value, or why it has none. */ +export type Section = { ok: true; value: T } | { ok: false; failure: Failure }; + +/** A failure, in the server's own words when it sent any. */ +export function describeFailure(error: unknown): Failure { + return failureOf(error); +} diff --git a/packages/shift-manager/src/lib/gate.ts b/packages/shift-manager/src/lib/gate.ts new file mode 100644 index 0000000000..6e94854d8c --- /dev/null +++ b/packages/shift-manager/src/lib/gate.ts @@ -0,0 +1,67 @@ +/** + * Whether the Lab lets Shift Manager in: the organization it acts in for this + * user, from workforce's `organization()`, the roster flow's identity read + * under its sign-in. Shift Manager never draws a Lab under an unknown + * organization (ER-4), so every other read waits behind this one. + * + * - a 401 or 403, a Lab that serves no roster flow, or an identity read that + * names no organization is the refusal; + * - anything else (a 5xx, the network) is the Lab not being reached, which + * Retry reads again. + */ +import { useCallback, useEffect, useState } from "react"; +import { ROSTER_FLOW } from "@flow-state-dev/workforce/browser"; +import { useLab } from "./lab-data"; +import { describeFailure, type Failure } from "./failure"; +import { useWorkforce } from "./workforce"; + +/** Where the gate stands: reading, in under an organization, refused, or the Lab not reached. */ +export type Gate = { state: "reading" } | { state: "in"; orgId: string } | { state: "refused"; failure: Failure } | { state: "unreachable"; failure: Failure }; + +/** + * What the Lab answers a call on a flow it doesn't serve, for the roster + * flow's identity read: the engine's unknown-flow message. Matched exactly, so + * any other 404 is the Lab answering, not "no roster". + */ +const NO_ROSTER_FLOW = `Unknown flow "${ROSTER_FLOW}"`; + +/** Why a Lab is refused when it says nothing about which organization the user is in. */ +function noOrganization(userId: string, why = "it serves no roster flow to ask it under"): string { + return `The Lab names no organization for ${userId}: ${why}. Shift Manager asks the roster flow's identity read which organization the Lab puts them in; its README lists what a Lab serves.`; +} + +/** The gate for `userId`, from one organization read's outcome. */ +export 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) } }; + return failure.httpStatus === 401 || failure.httpStatus === 403 ? { state: "refused", failure } : { state: "unreachable", failure }; + } + if (typeof read.orgId !== "string" || read.orgId.length === 0) return { state: "refused", failure: { message: noOrganization(userId, "its identity read names none") } }; + return { state: "in", orgId: read.orgId }; +} + +/** + * The gate, read once per connection; `retry` reads it again after a refusal + * or an unreachable Lab. The workforce client keeps a good answer and forgets + * a failed one, so a retry asks the Lab anew. + */ +export function useGate(): { gate: Gate; retry: () => void } { + const { client } = useLab(); + const workforce = useWorkforce(); + const [read, setRead] = useState<{ workforce: unknown; tries: number; gate: Gate }>({ workforce, tries: 0, gate: { state: "reading" } }); + const [tries, setTries] = useState(0); + useEffect(() => { + let closed = false; + workforce.organization().then( + (orgId) => !closed && setRead({ workforce, tries, gate: gateOf(client.userId, { orgId }) }), + (error: unknown) => !closed && setRead({ workforce, tries, gate: gateOf(client.userId, { error }) }), + ); + return () => { + closed = true; + }; + }, [client, workforce, tries]); + const retry = useCallback(() => setTries((n) => n + 1), []); + // A read for another connection is never this one's answer. + return { gate: read.workforce === workforce ? read.gate : { state: "reading" }, retry }; +} diff --git a/packages/shift-manager/src/lib/inbox.ts b/packages/shift-manager/src/lib/inbox.ts index b3dff7f17a..508e1e5a72 100644 --- a/packages/shift-manager/src/lib/inbox.ts +++ b/packages/shift-manager/src/lib/inbox.ts @@ -13,16 +13,17 @@ * call; the suspension notice it publishes takes the item away, with no * read of the Lab after it. */ -import { useCallback, useMemo } from "react"; +import { useCallback, useEffect, useMemo, useState } from "react"; import type { SuspensionItem } from "@flow-state-dev/core/items"; import type { ResumeAction } from "@flow-state-dev/core/types"; import { useView } from "@flow-state-dev/react"; -import { createInboxClient, type InboxAnswer, type InboxHold, type InboxItem } from "@flow-state-dev/orchestration/inbox"; +import { createInboxClient, type BoardActions, type InboxAnswer, type InboxHold, type InboxItem } from "@flow-state-dev/orchestration/inbox"; import { inboxViewRef, type InboxSuspensionDetail as InboxAsk, type InboxBoardTask, type InboxViewValue } from "@flow-state-dev/workforce/browser"; import { isDone } from "./columns"; +import { CONVERSATION_BOARD_COLLECTION } from "./boards"; import { useReportFeedState } from "./feed-health"; import { useLab } from "./lab-data"; -import { describeFailure, type Failure, type Section } from "./reads"; +import { describeFailure, type Failure, type Section } from "./failure"; import { sessionOfHold } from "./inbox-list"; import { useRetrySessionFeed, useSharedSessionFeed } from "./session-feeds"; @@ -46,6 +47,8 @@ type InboxRead = { failure: Failure | undefined; /** Read the view again now: Retry, R and *as of · refresh*. */ refresh(): void; + /** When the view's answer last landed here, epoch ms: what *as of* says. `undefined` before. */ + readAt: number | undefined; }; /** @@ -64,7 +67,11 @@ export function useInbox(enabled = true): InboxRead { ); const lapsed = value !== undefined && stale && failure !== undefined; useReportFeedState(enabled && value !== undefined ? (lapsed ? "lapsed" : "live") : undefined); - return { section, stale, failure: lapsed ? (failure as Failure) : undefined, refresh }; + const [readAt, setReadAt] = useState(undefined); + useEffect(() => { + if (value !== undefined) setReadAt(Date.now()); + }, [value]); + return { section, stale, failure: lapsed ? (failure as Failure) : undefined, refresh, readAt }; } /** @@ -162,18 +169,30 @@ export function answerOfResolution(hold: InboxViewHold, action: ResumeAction, da /** * Answer one hold through orchestration's one answer call. No read follows: - * the server's notice takes the item away. An answer in a session marks it - * answered once, for a conversation on screen to read itself back. + * the server's notice takes the item away, and a conversation on screen hears + * its session's resume on its own live feed. */ export function useInboxAnswer(): (hold: InboxViewHold | InboxHold, answer: InboxAnswer) => Promise { - const { client, noteAnswered } = useLab(); + const { client } = useLab(); const inbox = useMemo(() => createInboxClient(client), [client]); - return useCallback( - async (hold, answer) => { - await inbox.answerOne(hold, answer); - if (hold.source.kind === "suspension" && hold.source.sessionId !== null) noteAnswered(hold.source.sessionId); - }, - [inbox, noteAnswered], + return useCallback((hold, answer) => inbox.answerOne(hold, answer), [inbox]); +} + +// FIX-2381. +/** + * The task actions of a conversation's board: cancel, steer, release, retry + * and re-file, orchestration's `inbox.board(...)` bound to the conversation's + * session and the flow that owns it, as the signed-in user. Each rejects with + * the board's refusal. `undefined` for a conversation whose session names no + * owning flow (or isn't listed yet): it has no board to act on. + */ +export function useBoardActions(conversation: { id: string; flowId: string } | undefined): BoardActions | undefined { + const { client } = useLab(); + const id = conversation?.id; + const flowId = conversation?.flowId; + return useMemo( + () => (id === undefined || flowId === undefined ? undefined : createInboxClient(client).board({ flowId, sessionId: id, board: CONVERSATION_BOARD_COLLECTION })), + [client, id, flowId], ); } diff --git a/packages/shift-manager/src/lib/mcp-credentials.ts b/packages/shift-manager/src/lib/mcp-credentials.ts index 29f6651260..8fb720cee5 100644 --- a/packages/shift-manager/src/lib/mcp-credentials.ts +++ b/packages/shift-manager/src/lib/mcp-credentials.ts @@ -7,15 +7,14 @@ * was set; nothing here keeps it. */ import { withBearerToken } from "@flow-state-dev/devtool/react"; -import { CONNECTOR_KEYS_PATH } from "@flow-state-dev/workforce/browser"; +import { useCallback, useEffect, useState } from "react"; +import { CONNECTOR_KEYS_PATH, type ConnectorKeyStatus } from "@flow-state-dev/workforce/browser"; import type { Connection } from "./connection"; -import type { Failure } from "./reads"; +import type { Failure } from "./failure"; +import { useLab } from "./lab-data"; -/** One server the Lab offers, and when this user's key for it was set (`null`: not set). */ -export type McpServerKey = { name: string; setAt: string | null }; - -/** What a read found: the servers, a Lab that offers none, or a failure. */ -export type McpKeysRead = { servers: McpServerKey[] } | { none: true } | { failure: Failure }; +/** What a read found: each server the Lab offers with when the user's key for it was set, a Lab that offers none, or a failure. */ +type KeysRead = { servers: ConnectorKeyStatus[] } | { none: true } | { failure: Failure }; const pathOf = (connection: Connection, server?: string) => `${connection.baseUrl ?? ""}${CONNECTOR_KEYS_PATH}${server === undefined ? "" : `/${encodeURIComponent(server)}`}`; @@ -34,13 +33,13 @@ async function failureOf(response: Response): Promise { } /** Read which servers the Lab offers and which of them this user has a key for. */ -export async function readMcpKeys(connection: Connection): Promise { +async function readMcpKeys(connection: Connection): Promise { try { const response = await fetchAs(connection)(pathOf(connection), { headers: { accept: "application/json" } }); // A Lab that offers no MCP servers serves no such route. if (response.status === 404) return { none: true }; if (!response.ok) return { failure: await failureOf(response) }; - const body = (await response.json()) as { servers: McpServerKey[] }; + const body = (await response.json()) as { servers: ConnectorKeyStatus[] }; return { servers: body.servers }; } catch (error) { return { failure: { message: error instanceof Error ? error.message : String(error) } }; @@ -69,3 +68,14 @@ export async function writeMcpKey(connection: Connection, server: string, value: return { message: error instanceof Error ? error.message : String(error) }; } } + +/** The user's keys, read when the screen opens and again on `reread` (after a set or a clear). `undefined` until read. */ +export function useMcpKeys(): { read: KeysRead | undefined; reread: () => void } { + const { connection } = useLab(); + const [read, setRead] = useState(undefined); + const reread = useCallback(() => { + void readMcpKeys(connection).then(setRead); + }, [connection]); + useEffect(reread, [reread]); + return { read, reread }; +} diff --git a/packages/shift-manager/src/lib/messages.ts b/packages/shift-manager/src/lib/messages.ts index f527568b94..fdea27ee7e 100644 --- a/packages/shift-manager/src/lib/messages.ts +++ b/packages/shift-manager/src/lib/messages.ts @@ -1,20 +1,18 @@ // FIX-1989; FIX-2624. /** - * The user's message log: Workforce's `workforce/messages/*`, read by user - * scope with no session. Another user's messages are not in it. + * The user's message log: Workforce's `workforce/messages/*`, read whole by + * user scope with no session through `react`'s `useResource`, and kept + * current by its notices: a new message is one entry read, never the whole + * log again. Another user's messages are not in it. */ -import { useCallback, useEffect, useRef, useState } from "react"; -import { topic, type LiveRead } from "@flow-state-dev/client"; -import { getPatternPrefix } from "@flow-state-dev/core/types"; -import { WORKER_MESSAGES_PATTERN, workerMessageResourceStateSchema, type WorkerMessageResourceState } from "@flow-state-dev/workforce/browser"; +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 { describeFailure, readEveryScopeEntry, type Failure } from "./reads"; +import type { Failure } from "./failure"; export type { WorkerMessageResourceState }; -/** The pace the view reads the log at while it is open, wherever push can miss a change. */ -const MESSAGES_POLL_MS = 5_000; - /** One exchange: a first message and every answer to it, newest first. */ export type MessageExchange = { id: string; @@ -23,10 +21,10 @@ export type MessageExchange = { }; /** The messages a log read returned, each parsed by Workforce's own schema: one that doesn't parse is left out. */ -export function toMessages(items: readonly { clientData?: unknown }[]): WorkerMessageResourceState[] { +export function toMessages(values: readonly unknown[]): WorkerMessageResourceState[] { const rows: WorkerMessageResourceState[] = []; - for (const item of items) { - const parsed = workerMessageResourceStateSchema.safeParse(item.clientData); + for (const value of values) { + const parsed = workerMessageResourceStateSchema.safeParse(value); if (parsed.success) rows.push(parsed.data); } return rows; @@ -55,56 +53,16 @@ export function firstLine(text: string): string { } /** - * The log, read when the view opens, again on each Lab read (`readAt`), and on - * each notice of a message under the user's scope; wherever push can miss a - * change, every {@link MESSAGES_POLL_MS} instead (`client.live`). A later read - * keeps the last rows until it lands, and a failed later read keeps them; only - * a failed first read shows. The live read tries a failed one again on its own. - * `rows` is `null` when no flow of the Lab declares the log (a 404): it keeps - * no roster for the user. + * The log, read whole when the view opens and kept current by its notices. + * A later read that fails keeps the rows already drawn; only a failed first + * read shows. `rows` is `null` when no flow of the Lab declares the log (a + * 404): it keeps no roster for the user. */ -export function useMessages( - readAt: number, -): { rows: WorkerMessageResourceState[] | null | undefined; failure: Failure | undefined; reread: () => void } { +export function useMessages(): { rows: WorkerMessageResourceState[] | null | undefined; failure: Failure | undefined; reread: () => void } { const { client } = useLab(); - const [rows, setRows] = useState(undefined); - const [failure, setFailure] = useState(undefined); - const live = useRef(null); - useEffect(() => { - // The log is the user's: a message sent from any session writes its row under the user's scope. - const watching = client.live([topic.user()], { - read: () => - readEveryScopeEntry(client, "user", WORKER_MESSAGES_PATTERN) - .then(toMessages) - .then( - (value): WorkerMessageResourceState[] | null => value, - (error: unknown) => { - if (describeFailure(error).httpStatus === 404) return null; - throw error; - }, - ), - onValue: (value) => { - setRows(value); - setFailure(undefined); - }, - onError: (error) => setFailure(describeFailure(error)), - hear: (notice) => notice.kind === "resource", - paths: [getPatternPrefix(WORKER_MESSAGES_PATTERN)], - pollIntervalMs: MESSAGES_POLL_MS, - }); - live.current = watching; - return () => { - watching.close(); - if (live.current === watching) live.current = null; - }; - }, [client]); - // A Lab read reads it again too; the live read's own first read covers the one it opened on. - const readAtSeen = useRef(readAt); - useEffect(() => { - if (readAtSeen.current === readAt) return; - readAtSeen.current = readAt; - live.current?.refresh(); - }, [readAt]); - const reread = useCallback(() => live.current?.refresh(), []); - return { rows, failure: rows === undefined ? failure : undefined, reread }; + const { value, failure, refresh } = useResource(workerMessagesResource, { client, all: true }); + 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 }; + return { rows: undefined, failure, reread: refresh }; } diff --git a/packages/shift-manager/src/lib/projects.ts b/packages/shift-manager/src/lib/projects.ts index 91e003296a..7db3832dae 100644 --- a/packages/shift-manager/src/lib/projects.ts +++ b/packages/shift-manager/src/lib/projects.ts @@ -1,146 +1,181 @@ // BR-18; BR-38. /** - * A project's own reads, beside the snapshot: its workstreams and the Lab's - * project setup. + * A project's reads: the rows the user reads, a project's workstreams, an + * entry's report and the Lab's project setup. * - * **What a project view reads**: the project's entry and its workstream - * entries by one prefix, by scope with no session (the roster flow declares - * both), and an entry's report through the roster flow's `workstreamReport` - * view, since a report is content. Never a Lab read. Progress is worked out from the - * entries here, by Workforce's own `projectProgress`, so the view and the - * project coordinator count the same way; nothing is stored. + * **The rows.** Every row of the organization's `projects` and of the user's + * own private one, read whole and kept current by `react`'s `useResource` + * (the directory holds the one read, `directory.tsx`), each parsed by + * {@link toProject} so a row an earlier version wrote still reads. * - * **The project setup.** Which flow writes workstreams, and the standard - * worker each user talks to a project through, their project coordinator. - * Shift Manager doesn't name it: the Lab's projects flow answers its - * `projectSetup` view with it, read with no session, once per connection. + * **A project's workstreams** are its entries by one prefix, read whole and + * kept current by `useResource` while something on screen draws them: only + * a notice under that project's prefix reads them again. Progress is worked + * out from the entries here, by Workforce's own `projectProgress`, so the + * view and the project coordinator count the same way; nothing is stored. + * + * **The project setup**: the standard worker each user talks to a project + * through, their project coordinator, from workforce's `projectSetup` view. + * A Lab with no projects flow serves no such view (404), and has none. * * Shift Manager opens no workstream itself. The user asks their project * coordinator for the work, and the coordinator opens one with a lead from * their roster. */ -import { useCallback, useEffect, useRef, useState } from "react"; -import { topic, viewRef, type Client, type LiveRead } from "@flow-state-dev/client"; +import { useEffect, useMemo, useState } from "react"; +import type { Client } from "@flow-state-dev/client"; +import { useResource, useView } from "@flow-state-dev/react"; import { DONE_STATUS, parseWorkstreamEntry, projectProgress, + projectSetupView, PROJECTS_PATTERN, STALE_AFTER_MS, WORKSTREAMS_PATTERN, workstreamReportView, type ParsedWorkstreamEntry, type ProjectProgress, + type ProjectSetup, } from "@flow-state-dev/workforce/browser"; import { useLab } from "./lab-data"; -import { describeFailure, readEveryScopeEntry, toProject, type Failure, type Project, type ProjectVisibility } from "./reads"; +import type { Failure } from "./failure"; + +/** Where a project lives: the organization's, or the user's own. */ +export type ProjectVisibility = "shared" | "private"; /** A project's address: where it lives, and its id. */ export type ProjectAddress = { visibility: ProjectVisibility; id: string }; -/** One objective of a workstream, met or not. */ -export type WorkstreamObjective = { text: string; met: boolean }; +/** + * 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(row: unknown, key: string): unknown { + return typeof row === "object" && row !== null ? (row 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 row, as the projects collection's browser read publishes it. A row + * 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 + * 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")); + 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", + ownerUserId, + members: strings(field(row, "members")), + repository: text(field(row, "repository")), + }; +} // BR-12. -/** One workstream of a project: its entry, as everyone who reads the project reads it. */ -export type WorkstreamEntry = { +/** One workstream of a project: its entry as Workforce parses it, its storage key, and whether it has gone quiet. */ +export type WorkstreamEntry = ParsedWorkstreamEntry & { /** Its storage key in the project's workstreams. */ key: string; - owner: string; - id: string; - title: string; - /** The worker that leads it, on its owner's roster. */ - lead: string; - /** The lead's workstream session, its owner's. `null` until its open has made it. */ - sessionId: string | null; - status: string; - due: string | null; - objectives: WorkstreamObjective[]; - updatedAt: string; // BR-19. /** Whether it has gone quiet, as the project's progress counts it: one clock, `progress.stale`. */ stale: boolean; }; -/** A project as its view opens: the row, its workstreams, and the progress worked out from them. */ -export type ProjectRead = { - project: Project; - entries: WorkstreamEntry[]; - progress: ProjectProgress; -}; - -/** What the Lab's projects flow says about its project setup. */ -export type ProjectSetup = { - /** The flow `openWorkstream` and `updateWorkstream` are actions of, and the setup a view of. */ - flow: string; - /** The standard worker each user's project coordinator runs as, or `null`. */ - projectCoordinator: string | null; -}; - -/** The view the Lab's projects flow names its setup on. */ -const PROJECT_SETUP_VIEW = "projectSetup"; - +/** A project's workstreams as its view draws them, and the progress worked out from them as of a moment. */ +export type ProjectWorkstreams = { entries: WorkstreamEntry[]; progress: ProjectProgress }; /** * An entry, from what the entries' browser read publishes, parsed by * Workforce's own entry parser so this view and `readProject` read one shape. - * A row that doesn't parse as an entry is left out of the view. + * A row that doesn't parse as an entry is left out. */ function toEntry(storageKey: string, data: unknown): Omit | undefined { - let parsed: ParsedWorkstreamEntry | undefined; try { - parsed = parseWorkstreamEntry(storageKey, data); + const parsed = parseWorkstreamEntry(storageKey, data); + return parsed === undefined ? undefined : { ...parsed, key: storageKey }; } catch { return undefined; } - if (parsed === undefined) return undefined; - return { - key: storageKey, - owner: parsed.owner, - id: parsed.id, - title: parsed.title, - lead: parsed.lead, - sessionId: parsed.sessionId, - status: parsed.status, - due: parsed.due, - objectives: parsed.objectives.map((objective) => ({ text: objective.text, met: objective.met })), - updatedAt: parsed.updatedAt, - }; +} + +/** Every row of a read that parses as an entry. */ +function entriesOf(rows: readonly { storageKey: string; value: unknown }[]): Omit[] { + return rows.map((row) => toEntry(row.storageKey, row.value)).filter((entry): entry is Omit => entry !== undefined); +} + +/** + * Entries as of `now`: their progress, worked out by Workforce's own + * `projectProgress`, and each entry marked gone quiet by that same clock. + */ +function withProgress(entries: readonly Omit[], now: number): ProjectWorkstreams { + const progress = projectProgress(entries, now); + const quiet = new Set(progress.stale.map((entry) => `${entry.owner}/${entry.id}`)); + return { entries: entries.map((entry) => ({ ...entry, stale: quiet.has(`${entry.owner}/${entry.id}`) })), progress }; } /** Where a project at `visibility` lives: a shared one in the organization, a private one in the user's own scope. */ const scopeOf = (visibility: ProjectVisibility) => (visibility === "private" ? "user" : "org"); +/** The workstreams' collection at each scope, as a browser reads it. */ +const WORKSTREAMS = { + org: { scope: "org", pattern: WORKSTREAMS_PATTERN }, + user: { scope: "user", pattern: WORKSTREAMS_PATTERN }, +} as const; + +/** The prefix of one project's entries: the slash keeps `apollo` from reading `apollo2`'s. */ +const entriesPrefix = (projectId: string) => `workstreams/${projectId}/`; + // FIX-2624. /** - * Read a project as its view opens: its row, and its entries by the - * project's one prefix, by scope with no session. `null` when the user can't - * read a row at that address: none there, or another user's private project. + * Read a project once, with no session: its row, and every one of its entries + * by the project's one prefix, with their progress as of `now`. Jump to's + * search reads each project so when it opens. `null` when the user can't read + * a row at that address: none there, or another user's private project. */ -export async function readProject(client: Client, address: ProjectAddress, now = Date.now()): Promise { +export async function readProject( + client: Pick, + address: ProjectAddress, + now = Date.now(), +): Promise<({ project: Project } & ProjectWorkstreams) | null> { const scope = scopeOf(address.visibility); - const [stored, entries] = await Promise.all([ + const [stored, rows] = await Promise.all([ client.resource({ scope, pattern: PROJECTS_PATTERN }).entry(`projects/${address.id}`).read(), - // The project's one prefix, through the snapshot's pager: its page ceiling and repeated-cursor check. - readEveryScopeEntry(client, scope, WORKSTREAMS_PATTERN, `workstreams/${address.id}/`).then((scopeEntries) => - scopeEntries.map((scopeEntry) => toEntry((scopeEntry as { storageKey?: string }).storageKey ?? `workstreams/${scopeEntry.topic}`, scopeEntry.clientData)).filter((entry): entry is Omit => entry !== undefined), - ), + client.resource({ scope, pattern: WORKSTREAMS_PATTERN }).listAll({ topicPrefix: entriesPrefix(address.id) }), ]); - if (stored.value === null) return null; - const project = toProject(stored.value, address.visibility); - if (project === undefined) return null; - return withProgress(project, entries, now); -} - -/** - * A project read as of `now`: its progress, worked out from its entries by - * Workforce's own `projectProgress`, and each entry marked gone quiet by that - * same clock. Pure, so a view can work it out again as time passes, with no read. - */ -function withProgress(project: Project, entries: readonly Omit[], now: number): ProjectRead { - const progress = projectProgress(entries, now); - const quiet = new Set(progress.stale.map((entry) => `${entry.owner}/${entry.id}`)); - return { project, entries: entries.map((entry) => ({ ...entry, stale: quiet.has(`${entry.owner}/${entry.id}`) })), progress }; + const project = stored.value === null ? undefined : toProject(stored.value, address.visibility); + return project === undefined ? null : { project, ...withProgress(entriesOf(rows), now) }; } /** The longest delay `setTimeout` keeps; a longer one fires at once. */ @@ -148,13 +183,13 @@ const MAX_TIMER_MS = 2 ** 31 - 1; // BR-19. /** - * When the next of `read`'s entries goes quiet, by `projectProgress`'s rule (an + * When the next of `entries` goes quiet, by `projectProgress`'s rule (an * unfinished entry unchanged for {@link STALE_AFTER_MS}), or `undefined` when * none will: a quiet entry is one nobody writes, so no notice says so. */ -function nextQuietAt(read: ProjectRead): number | undefined { +function nextQuietAt(entries: readonly WorkstreamEntry[]): number | undefined { let next: number | undefined; - for (const entry of read.entries) { + for (const entry of entries) { if (entry.stale || entry.status === DONE_STATUS) continue; const updated = Date.parse(entry.updatedAt); if (!Number.isFinite(updated)) continue; @@ -164,108 +199,29 @@ function nextQuietAt(read: ProjectRead): number | undefined { return next; } -// FIX-2624. -/** - * An entry's latest report, read when its view opens through the roster - * flow's `workstreamReport` view, with no session: `null` when its owner has - * written none. - */ -export async function readEntryReport( - client: Client, - project: ProjectAddress, - entry: Pick, -): Promise { - return (await client.view(workstreamReportView, { project, owner: entry.owner, id: entry.id })).value.report; -} - -/** Project setups read, per connection: one read per page load. */ -const setups = new WeakMap>(); - -/** - * The Lab's project setup, from its projects flow: the flow among the Lab's - * that opens workstreams, and its `projectSetup` view, read with no session. - * `null` for a Lab with no such flow. Read once per connection; a failed read - * is read again next time. - */ -export function readProjectSetup(client: Client): Promise { - let read = setups.get(client); - if (read === undefined) { - read = (async () => { - const flows = await client.flows(); - const flow = flows.find((entry) => entry.actions.includes("openWorkstream")); - if (flow === undefined) return null; - const { value } = await client.view(viewRef(flow.id, PROJECT_SETUP_VIEW), {}); - const answer = (value ?? {}) as { projectCoordinator?: unknown }; - return { - flow: flow.id, - projectCoordinator: typeof answer.projectCoordinator === "string" ? answer.projectCoordinator : null, - }; - })(); - read.catch(() => setups.delete(client)); - setups.set(client, read); - } - return read; -} - -/** A read in flight, landed, or failed. */ -type ProjectReadState = { value: ProjectRead | null } | { failure: Failure } | undefined; - -/** The pace a project's entries are read at while they are on screen, wherever push can miss a change. */ -const PROJECT_POLL_MS = 5_000; +/** A read on screen: its value once it lands, why the last read failed, and a read on demand. */ +export type ScreenRead = { value: T | undefined; failure: Failure | undefined; refresh: () => void }; // BR-18. /** - * The project's own read, row and entries, when the view opens, each - * time the Lab is read again (`readAt`), and on each notice of the project or - * one of its entries under the project's scope (the org's for a shared - * project, its owner's for a private one) while its entries are on screen, on - * a tab that draws them or open under the project in the sidebar: a - * workstream is opened by someone else's turn (the Shift Coordinator's, or a - * coordinator's in another window), so the list shows it without a reload. - * Wherever push can miss a change it reads every {@link PROJECT_POLL_MS} - * instead (`client.live`). `reread` reads it now, as after an open. A read - * again keeps the last one on screen until it lands, and keeps it if it - * fails; the live read tries a failed one again on its own. - * No read while `enabled` is false: nothing on screen draws the entries. + * A project's workstreams, read whole by the project's one prefix under its + * scope (the org's for a shared project, its owner's for a private one) and + * kept current by their own notices: a workstream opened by someone else's + * turn shows without a reload. Mounted only while something on screen draws + * them. A failed read again keeps the entries already drawn, beside its + * `failure`; only a failed first read shows alone. */ -export function useProjectRead(address: ProjectAddress, enabled: boolean, readAt: number) { +export function useProjectWorkstreams(address: ProjectAddress): ScreenRead { const { client } = useLab(); - const [read, setRead] = useState(undefined); - const live = useRef(null); - useEffect(() => { - if (!enabled) return; - const where = { visibility: address.visibility, id: address.id }; - const watching = client.live([where.visibility === "private" ? topic.user() : topic.org()], { - read: () => readProject(client, where), - onValue: (value) => setRead({ value }), - // A failed read again keeps the last good one on screen: one dropped - // read shouldn't blank the list. Only a failed first read shows. - onError: (error) => setRead((prev) => (prev !== undefined && "value" in prev ? prev : { failure: describeFailure(error) })), - hear: (notice) => notice.kind === "resource", - paths: [`projects/${where.id}`, `workstreams/${where.id}`], - pollIntervalMs: PROJECT_POLL_MS, - }); - live.current = watching; - return () => { - watching.close(); - if (live.current === watching) live.current = null; - }; - // The address is the view's key; its parts are what the read depends on. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [client, enabled, address.visibility, address.id]); - // A Lab read reads it again too; the live read's own first read covers the one it opened on. - const readAtSeen = useRef(readAt); - useEffect(() => { - if (readAtSeen.current === readAt) return; - readAtSeen.current = readAt; - live.current?.refresh(); - }, [readAt]); + const read = useResource(WORKSTREAMS[scopeOf(address.visibility)], { client, all: true, topicPrefix: entriesPrefix(address.id) }); + const rows = 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 landed = read !== undefined && "value" in read ? read.value : null; + const [now, setNow] = useState(() => Date.now()); + const value = useMemo(() => (rows === null ? undefined : withProgress(entriesOf(rows), now)), [rows, now]); useEffect(() => { - if (landed === null) return; - const at = nextQuietAt(landed); + if (value === undefined) return; + const at = nextQuietAt(value.entries); if (at === undefined) return; // A delay past setTimeout's cap fires early, as does one the wall clock stepped // back under: such a fire changes nothing and sets the timer again, here. @@ -273,12 +229,35 @@ export function useProjectRead(address: ProjectAddress, enabled: boolean, readAt const arm = () => { timer = setTimeout(() => { if (Date.now() < at) return arm(); - setRead((held) => (held !== undefined && "value" in held && held.value === landed ? { value: withProgress(landed.project, landed.entries, Date.now()) } : held)); + setNow(Date.now()); }, Math.min(MAX_TIMER_MS, Math.max(0, at - Date.now()))); }; arm(); return () => clearTimeout(timer); - }, [landed]); - const reread = useCallback(() => live.current?.refresh(), []); - return { read, reread }; + }, [value]); + return { value, failure: read.failure, refresh: read.refresh }; +} + +// FIX-2624. +/** + * An entry's latest report, through the roster flow's `workstreamReport` + * view, with no session, kept current by the view: `null` when its owner has + * written none. + */ +export function useEntryReport(project: ProjectAddress, entry: Pick): ScreenRead { + const { client } = useLab(); + const { value, failure, refresh } = useView(workstreamReportView, { project, owner: entry.owner, id: entry.id }, { client }); + return { value: value === undefined ? undefined : value.report, failure, refresh }; +} + +/** + * The Lab's project setup, from workforce's `projectSetup` view, read with no + * session and kept current by it. `null` for a Lab that serves none (a 404): + * it has no projects flow, so no project coordinator. + */ +export function useProjectSetup(): ScreenRead { + const { client } = useLab(); + const { value, failure, refresh } = useView(projectSetupView, {}, { client }); + 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/roster.ts b/packages/shift-manager/src/lib/roster.ts index a26ac892ed..c5e093d68c 100644 --- a/packages/shift-manager/src/lib/roster.ts +++ b/packages/shift-manager/src/lib/roster.ts @@ -1,68 +1,26 @@ /** - * The user's roster beside the worker inventory: their own workers, read - * through Workforce's client, joined to the inventory's rows so Roster and - * the sidebar's TEAMS draw the same workers. The roster is followed, not - * read once: a hire shows on every surface that draws it. + * The user's roster: their own workers and the standard ones, followed + * through Workforce's client (`watchRoster`), so a hire, fork, edit or fire, + * from any tab or by any worker's turn, redraws it. * * A worker the user hired is theirs alone, so the organization's worker - * inventory never names it. Workforce's roster answers for the caller only, - * and every surface that lists workers joins the inventory to it. + * inventory never names it: the directory (`directory.tsx`) joins the two, + * and holds the page's one roster watch. */ import { useEffect, useRef, useState } from "react"; -import type { RosterEntry, WorkforceClient } from "@flow-state-dev/workforce/browser"; -import type { LoadedSnapshot } from "./derive"; -import { describeFailure, workerNames, type Failure, type Worker } from "./reads"; +import type { RosterEntry } from "@flow-state-dev/workforce/browser"; +import { describeFailure, type Failure } from "./failure"; import { useLab } from "./lab-data"; import { useWorkforce } from "./workforce"; /** The roster read: its entries, its failure, or `undefined` until the first read lands. */ export type RosterRead = { entries: RosterEntry[] } | { failure: Failure } | undefined; -/** One roster watch, the last read it reported, and the views drawing it. */ -type SharedWatch = { read: RosterRead; views: Set<(read: RosterRead) => void>; stop: () => void }; - /** - * The roster watch for each Lab connection. Roster, the sidebar's TEAMS, a - * project's lead picker, worker settings and DELEGATES all draw the roster; - * sharing one watch keeps them on the same roster, and keeps them from - * racing two first reads. - * The last view to go stops it. - */ -const watches = new WeakMap(); - -function joinWatch(client: object, workforce: WorkforceClient, view: (read: RosterRead) => void): () => void { - let shared = watches.get(client); - if (shared === undefined) { - const created: SharedWatch = { read: undefined, views: new Set(), stop: () => {} }; - const tell = (read: RosterRead) => { - created.read = read; - for (const each of [...created.views]) each(read); - }; - created.stop = workforce.watchRoster((entries) => tell({ entries }), { - // A failed re-read keeps the roster already drawn; the next read that lands replaces it. - onError: (error) => { - if (created.read === undefined || "failure" in created.read) tell({ failure: describeFailure(error) }); - }, - }); - watches.set(client, created); - shared = created; - } - const held = shared; - held.views.add(view); - view(held.read); - return () => { - held.views.delete(view); - if (held.views.size > 0) return; - held.stop(); - if (watches.get(client) === held) watches.delete(client); - }; -} - -/** - * The user's roster, followed through Workforce's client (`watchRoster`): a - * hire, fork, edit or fire, from any tab or by any worker's turn, redraws - * it. `undefined` until the first read lands. Every caller on one connection - * shares one watch. + * The user's roster, followed through Workforce's client. `undefined` until + * the first read lands. A failed re-read keeps the roster already drawn; the + * next read that lands replaces it. Each call is one watch: the directory + * makes the page's one call. */ export function useRoster(): RosterRead { const { client } = useLab(); @@ -70,65 +28,19 @@ export function useRoster(): RosterRead { // The connection decides the watch; its workforce client is the one built over it. const workforceRef = useRef(workforce); workforceRef.current = workforce; - const [read, setRead] = useState(() => watches.get(client)?.read); - useEffect(() => joinWatch(client, workforceRef.current, setRead), [client]); - return read; -} - -/** - * The user's own workers as rows beside the inventory's: each on the flow - * it names, with that flow's door and its rules and task flags, grouped and named the way an inventory - * row is. - */ -function ownWorkers(entries: readonly RosterEntry[], inventory: readonly Worker[]): Worker[] { - return entries - .filter((entry) => !entry.standard && !inventory.some((worker) => worker.id === entry.id)) - .map((entry) => ({ - id: entry.id, - kind: entry.flow, - door: inventory.find((worker) => worker.kind === entry.flow)?.door ?? null, - rules: inventory.find((worker) => worker.kind === entry.flow)?.rules ?? false, - doorTakesTask: inventory.find((worker) => worker.kind === entry.flow)?.doorTakesTask ?? false, - ...workerNames(entry.id, entry.name, entry.teamName), - ...harnessOf(entry), - })); -} - -/** The harness a roster entry's settings name, as a {@link Worker} field; nothing when it names none. */ -function harnessOf(entry: RosterEntry | undefined): Pick { - const harness = entry?.settings?.harness; - return typeof harness === "string" ? { harness } : {}; -} - -/** A standard worker the roster lists and the inventory hasn't registered, as a row. */ -function standardWorkers(entries: readonly RosterEntry[], inventory: readonly Worker[]): Worker[] { - return ownWorkers( - entries.filter((entry) => entry.standard).map((entry) => ({ ...entry, standard: false })), - inventory, - ); -} - -/** - * The snapshot with the roster's workers in its inventory, the user's own - * ones listed in `own`. With the inventory unread, the standard workers the - * roster lists are still the user's, so they are added too. - */ -export function withRoster(snapshot: LoadedSnapshot, read: RosterRead): { snapshot: LoadedSnapshot; workers: Worker[]; own: Worker[] } { - const entries = read !== undefined && "entries" in read ? read.entries : []; - // A declared worker's harness rides on its roster entry, not on its inventory row. - const inventoryWorkers = (snapshot.inventory.ok ? snapshot.inventory.value.workers : []).map((worker) => ({ - ...worker, - ...harnessOf(entries.find((entry) => entry.id === worker.id)), - })); - const own = ownWorkers(entries, inventoryWorkers); - const extra = snapshot.inventory.ok ? own : [...standardWorkers(entries, inventoryWorkers), ...own]; - const workers = [...inventoryWorkers, ...extra]; - return { - snapshot: { - ...snapshot, - inventory: { ok: true, value: { workers } }, - }, - workers, - own, - }; + const [read, setRead] = useState<{ client: unknown; read: RosterRead }>({ client, read: undefined }); + useEffect(() => { + let last: RosterRead; + const tell = (next: RosterRead) => { + last = next; + setRead({ client, read: next }); + }; + setRead({ client, read: undefined }); + return workforceRef.current.watchRoster((entries) => tell({ entries }), { + onError: (error) => { + if (last === undefined || "failure" in last) tell({ failure: describeFailure(error) }); + }, + }); + }, [client]); + return read.client === client ? read.read : undefined; } diff --git a/packages/shift-manager/src/lib/routines.ts b/packages/shift-manager/src/lib/routines.ts index ce9efeea93..80e2bb6ea5 100644 --- a/packages/shift-manager/src/lib/routines.ts +++ b/packages/shift-manager/src/lib/routines.ts @@ -8,29 +8,11 @@ * time zone when the list is read; an event routine follows one thread, its * events reaching a worker's conversation as messages. */ -import { useCallback, useEffect, useState } from "react"; -import { ClientHttpError } from "@flow-state-dev/client"; -import { ROUTINE_VERBS, SCHEDULES_PATTERN, listedRoutineSchema, routinesView, type RoutineMaker } from "@flow-state-dev/workforce/browser"; +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 { describeFailure, type Failure } from "./reads"; - -/** One routine as the screen shows it. */ -export type Routine = { - id: string; - name: string; - /** The worker it acts through: whose board a clock routine files on, whose conversation hears an event routine. */ - worker: string; - paused: boolean; - madeBy: RoutineMaker | null; - description: string | null; - /** A clock routine's cron, zone and next run; `null` for an event routine. */ - clock: { cron: string; timezone: string; nextRunAt: string | null } | null; - /** An event routine's thread and the kinds it hears; `null` for a clock routine. */ - event: { thread: string; kinds: string[] | null; interest: string } | null; - /** A clock routine's task: what for, and who works it. */ - goal: string | null; - assignee: string | null; -}; +import { describeFailure, type Failure } from "./failure"; const text = (value: unknown): string | null => (typeof value === "string" && value.length > 0 ? value : null); @@ -39,69 +21,51 @@ const text = (value: unknown): string | null => (typeof value === "string" && va * routines soonest next run first, then event routines). Each is parsed by * Workforce's own schema; one that doesn't parse is left out. */ -export function toRoutines(output: unknown): Routine[] { +export function toRoutines(output: unknown): ListedRoutine[] { const listed = (output as { routines?: unknown } | null | undefined)?.routines; if (!Array.isArray(listed)) return []; - const routines: Routine[] = []; - for (const item of listed) { + return listed.flatMap((item) => { const parsed = listedRoutineSchema.safeParse(item); - if (!parsed.success) continue; - const r = parsed.data; - const task = (r.task ?? {}) as Record; - routines.push({ - id: r.id, - name: r.name, - worker: r.worker, - paused: r.paused, - madeBy: r.madeBy ?? null, - description: text(r.description), - clock: "clock" in r.trigger ? r.trigger.clock : null, - event: "event" in r.trigger ? { thread: r.trigger.event.thread, kinds: r.trigger.event.kinds ?? null, interest: r.trigger.event.interest } : null, - goal: text(task.goal), - assignee: text(task.assignee) - }); - } - return routines; + return parsed.success ? [parsed.data] : []; + }); +} + +/** A clock routine's cron, zone and next run; `null` for an event routine. */ +export function clockOf(routine: ListedRoutine): { cron: string; timezone: string; nextRunAt: string | null } | null { + return "clock" in routine.trigger ? routine.trigger.clock : null; +} + +/** An event routine's thread and the kinds it hears (`null`: every kind); `null` for a clock routine. */ +export function eventOf(routine: ListedRoutine): { thread: string; kinds: string[] | null; interest: string } | null { + if (!("event" in routine.trigger)) return null; + const { thread, kinds, interest } = routine.trigger.event; + return { thread, kinds: kinds ?? null, interest }; +} + +/** A clock routine's task: what for, and who works it. */ +export function taskOf(routine: ListedRoutine): { goal: string | null; assignee: string | null } { + const task = (routine.task ?? {}) as Record; + return { goal: text(task.goal), assignee: text(task.assignee) }; } /** What a pause, resume or delete came to: `undefined` when it went through, or why it didn't. */ export type RoutineChange = (change: { pause: string; paused: boolean } | { delete: string }) => Promise; /** - * The list, read when the view opens, again on each Lab read (`readAt`), and - * after each change. `routines` is `null` when this Lab serves no roster flow - * (404). A later read keeps the last list until it lands; only a failed first - * read shows. + * The list, from the routines view, kept current by it: a routine paused or + * added anywhere shows when the view does. `routines` is `null` when this + * Lab serves no roster flow (404). A later read keeps the last list; only a + * failed first read shows. */ -export function useRoutines(readAt: number): { - routines: Routine[] | null | undefined; +export function useRoutines(): { + routines: ListedRoutine[] | null | undefined; failure: Failure | undefined; reread: () => void; change: RoutineChange; } { const { client } = useLab(); - const [routines, setRoutines] = useState(undefined); - const [failure, setFailure] = useState(undefined); - const [reads, setReads] = useState(0); - useEffect(() => { - let closed = false; - client - .view(routinesView, {}) - .then(({ value }) => { - if (closed) return; - setRoutines(toRoutines(value)); - setFailure(undefined); - }) - .catch((error: unknown) => { - if (closed) return; - if (error instanceof ClientHttpError && error.status === 404) setRoutines(null); - else setFailure(describeFailure(error)); - }); - return () => { - closed = true; - }; - }, [client, readAt, reads]); - const reread = useCallback(() => setReads((n) => n + 1), []); + const { value, failure, refresh } = useView(routinesView, {}, { client }); + const routines = useMemo(() => (value === undefined ? (failure?.httpStatus === 404 ? null : undefined) : toRoutines(value)), [value, failure?.httpStatus]); const change = useCallback( async (wanted) => { const [verb, input] = "delete" in wanted ? [ROUTINE_VERBS.delete, { id: wanted.delete }] : [ROUTINE_VERBS.pause, { id: wanted.pause, paused: wanted.paused }]; @@ -112,10 +76,11 @@ export function useRoutines(readAt: number): { } catch (error: unknown) { return describeFailure(error).message; } finally { - setReads((n) => n + 1); + // The change's own notice re-runs the view; reading now draws it without waiting on the push. + refresh(); } }, - [client] + [client, refresh] ); - return { routines, failure: routines === undefined ? failure : undefined, reread, change }; + return { routines, failure: routines === undefined ? failure : undefined, reread: refresh, change }; } diff --git a/packages/shift-manager/src/lib/rules.ts b/packages/shift-manager/src/lib/rules.ts index bd8d7eef26..335f2b0329 100644 --- a/packages/shift-manager/src/lib/rules.ts +++ b/packages/shift-manager/src/lib/rules.ts @@ -11,7 +11,7 @@ */ import { useCallback, useEffect, useState } from "react"; import type { StandingRulesActionOutput } from "@flow-state-dev/workforce/browser"; -import { describeFailure, type Failure } from "./reads"; +import { describeFailure, type Failure } from "./failure"; import { useWorkforce } from "./workforce"; /** One rule as the page draws it. */ diff --git a/packages/shift-manager/src/lib/shift.ts b/packages/shift-manager/src/lib/shift.ts new file mode 100644 index 0000000000..1f7115f294 --- /dev/null +++ b/packages/shift-manager/src/lib/shift.ts @@ -0,0 +1,198 @@ +/** + * Who is on shift, and the counts every screen draws from it: the worker + * directory (`workers.ts`) against the Inbox view's one answer. A worker's + * held tasks are the view's `tasks`, each resolved by {@link workerFor}; its + * asks are the view's suspension holds, by the `workerId` the view stamped on + * each. So a worker's status and the Inbox list move in the same view update, + * and never disagree. + * + * Also the names and groupings the directory's screens share: teams, the + * Shift Coordinator, a flow's door. + */ +import type { InboxHold, InboxItem } from "@flow-state-dev/orchestration/inbox"; +import type { InboxBoardTask, InboxSuspensionDetail, InboxViewValue } from "@flow-state-dev/workforce/browser"; +import { GENERAL_TEAM, type Worker } from "./workers"; + +/** One of the Inbox view's holds, each suspension carrying its ask's detail. */ +type ViewHold = InboxHold; + +// FIX-1672. +/** + * The worker a row is held by, or `undefined` when no single worker is. + * + * A row names an `assignee`, which is a routing key a board's workers answer + * to, not a worker address: a board may name `` for the worker + * `.`. So, in order: + * + * 1. the worker whose id is the assignee; + * 2. the one worker whose own name is the assignee. + * + * A name more than one worker carries, or none, is no worker: a row is never + * shown against several workers, or against a guess. + */ +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); + if (exact !== undefined) return exact; + const named = workers.filter((worker) => worker.name === row.assignee); + return named.length === 1 ? named[0] : undefined; +} + +/** A worker's shift status, the one word Roster and the sidebar draw. */ +export type ShiftStatus = "on shift" | "off shift"; + +/** The two statuses, in the order Roster groups them. */ +export const SHIFT_STATUSES: readonly ShiftStatus[] = ["on shift", "off shift"]; + +/** One worker's state: its status, the tasks it holds, and the asks it waits on you with. */ +export type WorkerState = { + worker: Worker; + status: ShiftStatus; + /** Its tasks that are running, waiting on you included, in board order: its slots in use. */ + held: InboxBoardTask[]; + /** Of `held`, the tasks held on a question or confirm for you (their Inbox item's board holds). */ + waitsOnYou: InboxBoardTask[]; + /** Its pending asks, oldest first: the Inbox's suspension holds that name it. */ + asks: ViewHold[]; +}; + +/** Every worker's state, and whether the result is partial. */ +export type WorkerStates = { + /** Keyed by worker id, in the directory's order. */ + workers: Map; + /** The Inbox view did not load: every worker reads off shift, as far as this page knows. */ + partial: boolean; +}; + +/** Whether `item` holds its task on a question or confirm for you. */ +const holdsTask = (item: InboxItem) => item.holds.some((hold) => hold.source.kind === "task"); + +/** + * Every worker's status, from the Inbox view's answer (`undefined` while it is + * unread or failed): + * + * - **on shift**: it holds a running task (one waiting on you included) or a + * pending ask; + * - **off shift**: none of those. Queued, blocked, errored and finished tasks + * hold no slot. + * + * A task no single worker resolves to, and an ask whose session names no + * worker in the directory (a run with no conversation among them), count for + * nobody. Every screen that draws a status or a count reads this result. + */ +export function workerStates(workers: readonly Worker[], view: InboxViewValue | undefined): WorkerStates { + const states = new Map( + workers.map((worker) => [worker.id, { worker, status: "off shift", held: [], waitsOnYou: [], asks: [] }]), + ); + for (const task of view?.tasks ?? []) { + if (task.status !== "in_progress") continue; + const owner = workerFor(workers, task); + const state = owner === undefined ? undefined : states.get(owner.id); + if (state === undefined) continue; + state.held.push(task); + const item = view?.items.find((each) => each.task?.board === task.boardRef && each.task.taskId === task.id); + if (item !== undefined && holdsTask(item)) state.waitsOnYou.push(task); + } + const asks = (view?.items ?? []).flatMap((item) => item.holds.filter((hold) => hold.source.kind === "suspension")).sort((a, b) => a.openedAt - b.openedAt); + for (const hold of asks) { + const workerId = hold.detail?.workerId ?? null; + if (workerId !== null) states.get(workerId)?.asks.push(hold); + } + for (const state of states.values()) { + state.status = state.held.length > 0 || state.asks.length > 0 ? "on shift" : "off shift"; + } + return { workers: states, partial: view === undefined }; +} + +/** How many workers are in each status, and how many waits-on entries they have. */ +export type ShiftCounts = Record & { + /** Each held task holding on a question for you plus each pending ask, across the workers counted. */ + waiting: number; +}; + +/** The counts over every worker in `states`, or over one team's. */ +export function shiftCounts(states: WorkerStates, team?: string): ShiftCounts { + const counts: ShiftCounts = { "on shift": 0, "off shift": 0, waiting: 0 }; + for (const { worker, status, waitsOnYou, asks } of states.workers.values()) { + if (team !== undefined && worker.team !== team) continue; + counts[status] += 1; + counts.waiting += waitsOnYou.length + asks.length; + } + return counts; +} + +/** + * The door of the flow that owns a session: the inventory rows of the workers + * on that flow name it, since a worker flow is registered under its name. + * Every worker on one flow shares its door. `null` when no worker is on the + * flow, or its worker flow takes no message. + */ +export function doorOf(workers: readonly Worker[], flowId: string): string | null { + 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. + */ +export function teamsOf(workers: readonly Worker[]): Array<{ team: string; name: string; workers: Worker[] }> { + const teams = new Map(); + for (const worker of workers) { + const team = teams.get(worker.team); + if (team === undefined) teams.set(worker.team, [worker]); + else team.push(worker); + } + const all = [...teams].map(([team, members]) => ({ team, name: members[0]!.teamName, workers: members })); + return [...all.filter((t) => t.team === GENERAL_TEAM), ...all.filter((t) => t.team !== GENERAL_TEAM)]; +} + +/** The team a Roster address picks, or `null` (All) when the directory has no such team. */ +export function pickedTeam(workers: readonly Worker[], team: string | null): string | null { + return team !== null && workers.some((worker) => worker.team === team) ? team : null; +} + +/** + * The name a worker must carry to be the Shift Coordinator: an org worker's id, or a + * team worker's name. The only place Shift Manager names a worker (D2). + */ +const SHIFT_COORDINATOR = "shift-coordinator"; + +const isShiftCoordinator = (idOrName: string) => idOrName.slice(idOrName.indexOf(".") + 1) === SHIFT_COORDINATOR; + +/** How the screens name a worker: `shift-coordinator` is the Shift Coordinator. */ +export function workerLabel(idOrName: string): string { + return isShiftCoordinator(idOrName) ? "Shift Coordinator" : idOrName; +} + +/** Which worker Shift Manager talks to as the Shift Coordinator, if exactly one is. */ +export type ShiftCoordinator = { kind: "one"; worker: Worker } | { kind: "none" } | { kind: "several"; workers: Worker[] }; + +/** + * The Shift Coordinator among the directory's workers (D2): the workers whose + * name is exactly `shift-coordinator`, an org worker or a team's. One is the + * Shift Coordinator; two or more are a state, never a guess. + */ +export function shiftCoordinatorOf(workers: readonly Worker[]): ShiftCoordinator { + const found = workers.filter((worker) => isShiftCoordinator(worker.id)); + if (found.length === 0) return { kind: "none" }; + return found.length === 1 ? { kind: "one", worker: found[0]! } : { kind: "several", workers: found }; +} + +/** How long ago `since` was, in a short human form. */ +export function waited(since: number, now: number): string { + const seconds = Math.max(0, Math.round((now - since) / 1000)); + if (seconds < 60) return `${seconds}s`; + const minutes = Math.round(seconds / 60); + if (minutes < 60) return `${minutes}m`; + const hours = Math.round(minutes / 60); + if (hours < 48) return `${hours}h`; + return `${Math.round(hours / 24)}d`; +} diff --git a/packages/shift-manager/src/lib/task.tsx b/packages/shift-manager/src/lib/task.tsx index 3eeaf26496..90831314fb 100644 --- a/packages/shift-manager/src/lib/task.tsx +++ b/packages/shift-manager/src/lib/task.tsx @@ -33,7 +33,7 @@ import type { RequestStatus } from "@flow-state-dev/core/types"; import { useRequestStream } from "@flow-state-dev/react"; import { useConversationTasks, type ConversationTask } from "./conversation-tasks"; import { useLab } from "./lab-data"; -import { describeFailure, type Failure } from "./reads"; +import { describeFailure, type Failure } from "./failure"; import { useWorkforce } from "./workforce"; import { resolveRunFlow } from "./task-items"; diff --git a/packages/shift-manager/src/lib/tasks.ts b/packages/shift-manager/src/lib/tasks.ts index 1d99a6cede..47450945d8 100644 --- a/packages/shift-manager/src/lib/tasks.ts +++ b/packages/shift-manager/src/lib/tasks.ts @@ -2,13 +2,15 @@ * The numbers and words Tasks and Inbox draw in design v2's form: a row's * TIME, which rows the Queued toggle hides, Tasks' summary line and the empty * Inbox's sentence. The rows and the Inbox come from the inbox view the other - * screens read (`inbox.ts`), and who is on shift from `workerStates`, so - * Tasks, Inbox and Roster agree. + * screens read (`inbox.ts`), and who is on shift from `workerStates` over the + * same answer, so Tasks, Inbox and Roster agree. */ import { columnFor } from "./columns"; -import { workerStates, shiftCounts, type LoadedSnapshot } from "./derive"; +import { workerStates, shiftCounts } from "./shift"; import { openBoardTasks, type InboxViewValue } from "./inbox"; -import type { BoardTaskView, Section } from "./reads"; +import type { BoardTaskView } from "./boards"; +import type { Section } from "./failure"; +import type { Worker } from "./workers"; /** * Where a task's composer keeps its unsent line and *unconfirmed* warning. A @@ -58,11 +60,11 @@ const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : * Inbox items waiting on the user, who is on shift, and how many * streams (the conversations holding their boards) the rows in flight run in. */ -export function summaryLine(inbox: Section, snapshot: LoadedSnapshot): string { +export function summaryLine(inbox: Section, workers: readonly Worker[]): string { const inFlight = inbox.ok ? openBoardTasks(inbox.value).filter((row) => !isQueued(row)) : []; // An Inbox that didn't load says so: a count of 0 would read as all clear. const waiting = inbox.ok ? `${inbox.value.items.length} ${inbox.value.items.length === 1 ? "needs" : "need"} you` : "Inbox didn't load"; - const counts = shiftCounts(workerStates(snapshot)); + const counts = shiftCounts(workerStates(workers, inbox.ok ? inbox.value : undefined)); return [ `${inFlight.length} in flight`, waiting, diff --git a/packages/shift-manager/src/lib/usage.ts b/packages/shift-manager/src/lib/usage.ts index 4ed70bf2e3..b1b8a58731 100644 --- a/packages/shift-manager/src/lib/usage.ts +++ b/packages/shift-manager/src/lib/usage.ts @@ -7,151 +7,95 @@ * roster flow's `workerUsage` view. Neither read finds or makes a session. * * Opening Usage asks for a fresh reading. The Lab asks a harness at most once - * a minute, so a view that re-renders or re-reads costs nothing extra. What + * a minute, so a view that re-renders or re-reads costs nothing extra. Both + * views are kept current by their own notices: a run reporting usage shows + * when the view hears it. What * comes back is drawn as returned: every age and every "rolled over" is the * Lab's, worked out by its clock, never this page's. */ -import { useCallback, useEffect, useState } from "react"; -import { ClientHttpError, type Client } from "@flow-state-dev/client"; -import type { HarnessUsageLevel } from "@flow-state-dev/core/harness"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import type { ViewValueOf } from "@flow-state-dev/client"; +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 { describeFailure, type Failure } from "./reads"; +import { describeFailure, type Failure } from "./failure"; -/** One window as the view returns it. */ -export type UsageWindow = { - id: string; - label: string | null; - minutes: number | null; - /** `null` when the harness sent no percent: never shown as 0. */ - usedPercent: number | null; - /** How close to its limit, when the harness said: `ok`, `warning`, `reached`. `null` from Codex. */ - level: HarnessUsageLevel | null; - resetsAt: number | null; - checkedAt: number; - /** `read` when a look read it, `run` when a coding run reported it. */ - origin: string; - ageMs: number; - rolledOver: boolean; -}; +/** The harness usage view, read with no session. */ +const HARNESS_USAGE = harnessUsageViewRef(); -/** One harness as the view returns it. */ -export type HarnessUsage = { - harness: string; - status: "windows" | "api-key" | "signed-out" | "unavailable"; - reason: string | null; - plan: string | null; - windows: UsageWindow[]; - checkedAt: number | null; - ageMs: number | null; - refreshError: string | null; -}; +/** One harness as the usage view returns it. */ +export type HarnessUsage = ViewValueOf["harnesses"][number]; + +/** One window as the usage view returns it. */ +export type UsageWindow = HarnessUsage["windows"][number]; + +/** One worker as the worker usage view returns it. */ +export type WorkerUsage = ViewValueOf["workers"][number]; + +/** One source of a worker's spend, as the worker usage view returns it: a model, or a harness billed one way. */ +export type WorkerSourceUsage = WorkerUsage["bySource"][number]; /** - * Whether `error` says this Lab serves no such usage: no flow declares it or + * Whether a failure says this Lab serves no such usage: no flow declares it or * the view (404), or, on Re-check, a collection whose writer flow isn't * registered here (409 `runby_flow_missing`). Every other refusal is a failure * the screen shows. */ -function servesNone(error: unknown, onRecheck: boolean): boolean { - if (!(error instanceof ClientHttpError)) return false; - if (error.status === 404) return true; - return onRecheck && error.status === 409 && (error.body as { error?: unknown } | undefined)?.error === "runby_flow_missing"; -} - -/** - * Re-check, then the usage rows. `null` when this Lab serves no usage. Re-check - * asks each harness at most once a minute per user, so a re-read within the - * minute answers the stored rows. A Re-check that fails (a 5xx, a refused - * caller, the network) never hides them: they come back with why as each row's - * `refreshError`, as a failed refresh's do. A 409 other than a missing writer - * flow is thrown, for the screen to show. - */ -export async function readHarnessUsageView(client: Client): Promise { - let recheckFailure: string | null = null; - try { - await recheckHarnessUsage(client); - } catch (error) { - if (servesNone(error, true)) return null; - // A conflict is the Lab's set-up, not a missed attempt: the screen shows it. - if (error instanceof ClientHttpError && error.status === 409) throw error; - recheckFailure = describeFailure(error).message; - } - let harnesses: HarnessUsage[]; - try { - harnesses = toHarnessUsage((await client.view(harnessUsageViewRef(), {})).value); - } catch (error) { - if (servesNone(error, false)) return null; - throw error; - } - return recheckFailure === null ? harnesses : harnesses.map((usage) => ({ ...usage, refreshError: recheckFailure })); -} - -/** The view's rows, as sent. A row that isn't one is left out. */ -export function toHarnessUsage(output: unknown): HarnessUsage[] { - const rows = (output as { harnesses?: unknown } | null | undefined)?.harnesses; - return Array.isArray(rows) ? rows.filter((row): row is HarnessUsage => typeof (row as HarnessUsage)?.harness === "string") : []; +function servesNone(failure: Failure, onRecheck: boolean): boolean { + if (failure.httpStatus === 404) return true; + return onRecheck && failure.httpStatus === 409 && failure.message === "runby_flow_missing"; } /** - * The usage rows, re-checked when the view opens and on each Lab read - * (`readAt`). `rows` is `null` when this Lab serves no usage. A read - * that fails keeps the last rows and reports `failure` beside them, so stale - * rows never pass for fresh ones. + * The usage rows, from the usage view, kept current by it, after a Re-check + * when the screen opens and on its Retry. `rows` is `null` when this Lab + * serves no usage. Re-check asks each harness at most once a minute per user, + * so the view's answer within the minute is the stored rows. A Re-check that + * fails (a 5xx, a refused caller, the network) never hides them: they come + * with why as each row's `refreshError`. A 409 other than a missing writer + * flow is the Lab's set-up, not a missed attempt, and is the screen's failure. + * A read that fails keeps the last rows and reports `failure` beside them, so + * stale rows never pass for fresh ones. */ -export function useHarnessUsage(readAt: number): { +export function useHarnessUsage(): { rows: HarnessUsage[] | null | undefined; failure: Failure | undefined; reread: () => void; } { const { client } = useLab(); - const [rows, setRows] = useState(undefined); - const [failure, setFailure] = useState(undefined); - const [reads, setReads] = useState(0); + const { value, failure, refresh } = useView(HARNESS_USAGE, {}, { client }); + // What the last Re-check came to: none sent yet, gone through, serves none, or why it failed. + const [recheck, setRecheck] = useState<{ state: "sent" | "done" | "none" } | { state: "failed"; failure: Failure }>({ state: "sent" }); + const [tries, setTries] = useState(0); useEffect(() => { let closed = false; - readHarnessUsageView(client) - .then((read) => { + recheckHarnessUsage(client).then( + () => !closed && setRecheck({ state: "done" }), + (error: unknown) => { if (closed) return; - setRows(read); - setFailure(undefined); - }) - .catch((error: unknown) => { - if (!closed) setFailure(describeFailure(error)); - }); + const why = describeFailure(error); + setRecheck(servesNone(why, true) ? { state: "none" } : { state: "failed", failure: why }); + }, + ); return () => { closed = true; }; - }, [client, readAt, reads]); - const reread = useCallback(() => setReads((n) => n + 1), []); - return { rows, failure, reread }; + }, [client, tries]); + const reread = useCallback(() => { + setTries((n) => n + 1); + refresh(); + }, [refresh]); + 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( + () => (value === undefined ? undefined : refreshError === null ? value.harnesses : value.harnesses.map((usage) => ({ ...usage, refreshError }))), + [value, refreshError], + ); + if (recheck.state === "none" || (rows === undefined && failure !== undefined && servesNone(failure, false))) return { rows: null, failure: undefined, reread }; + return { rows, failure: conflict ?? failure, reread }; } -/** One source of a worker's spend, as the query returns it: a model, or a harness billed one way. */ -export type WorkerSourceUsage = { - source: string; - kind: "model" | "harness"; - billing: "api-key" | "subscription" | null; - inputTokens: number; - outputTokens: number; - /** A cost the harness reported on an API key. `null`: none was, never shown as $0. */ - costUsd: number | null; - runs: number; - /** Runs that reported no tokens. */ - unreported: number; -}; - -/** One worker as the query returns it. */ -export type WorkerUsage = { - worker: string; - /** No longer on the user's roster. */ - gone: boolean; - tokens: { input: number; output: number }; - costUsd: number | null; - bySource: WorkerSourceUsage[]; -}; - /** The periods the view offers, in UTC days ending today. */ export const USAGE_PERIODS = [ { days: 1, label: "Today" }, @@ -159,57 +103,23 @@ export const USAGE_PERIODS = [ { days: 30, label: "30 days" }, ] as const; -/** The query's worker entries, as sent. A row that isn't one is left out. */ -export function toWorkerUsage(output: unknown): WorkerUsage[] { - const rows = (output as { workers?: unknown } | null | undefined)?.workers; - return Array.isArray(rows) ? rows.filter((row): row is WorkerUsage => typeof (row as WorkerUsage)?.worker === "string") : []; -} - -/** Each worker's usage over the last `days` UTC days. `null` when this Lab keeps no roster flow (404). */ -export async function readWorkerUsageView(client: Client, days: number): Promise { - try { - return toWorkerUsage((await client.view(workerUsageView, { days })).value); - } catch (error) { - if (servesNone(error, false)) return null; - throw error; - } -} - /** - * Each worker's usage over the last `days` UTC days, read when the view opens, - * on each Lab read (`readAt`), and when the period changes. `rows` is `null` - * when this Lab keeps no roster flow. A read that fails keeps the last - * rows for the same period and reports `failure` beside them; rows read for - * another period are never returned, so one period's totals never stand - * under another's tab. + * Each worker's usage over the last `days` UTC days, from the worker usage + * view, kept current by it and read again when the period changes. `rows` is + * `null` when this Lab keeps no roster flow (404). A read that fails keeps + * the last rows for the same period and reports `failure` beside them; rows + * read for another period are never returned, so one period's totals never + * stand under another's tab. */ -export function useWorkerUsage( - readAt: number, - days: number, -): { +export function useWorkerUsage(days: number): { rows: WorkerUsage[] | null | undefined; failure: Failure | undefined; reread: () => void; } { const { client } = useLab(); - const [read, setRead] = useState<{ days: number; rows?: WorkerUsage[] | null; failure?: Failure } | undefined>(undefined); - const [reads, setReads] = useState(0); - useEffect(() => { - let closed = false; - readWorkerUsageView(client, days) - .then((rows) => { - if (!closed) setRead({ days, rows }); - }) - .catch((error: unknown) => { - if (!closed) setRead((last) => ({ days, rows: last?.days === days ? last.rows : undefined, failure: describeFailure(error) })); - }); - return () => { - closed = true; - }; - }, [client, readAt, reads, days]); - const reread = useCallback(() => setReads((n) => n + 1), []); - const current = read?.days === days ? read : undefined; - return { rows: current?.rows, failure: current?.failure, reread }; + const { value, failure, refresh } = useView(workerUsageView, { days }, { client }); + if (value === undefined && failure !== undefined && servesNone(failure, false)) return { rows: null, failure: undefined, reread: refresh }; + return { rows: value?.workers, failure, reread: refresh }; } /** A token count for a user: `840 tokens`, `12.5 K tokens`, `1.2 M tokens`. */ diff --git a/packages/shift-manager/src/lib/workers.ts b/packages/shift-manager/src/lib/workers.ts new file mode 100644 index 0000000000..c517ad035a --- /dev/null +++ b/packages/shift-manager/src/lib/workers.ts @@ -0,0 +1,160 @@ +/** + * The worker directory's rows: the organization's worker inventory joined + * with the user's roster (D1). Every screen that draws a worker draws one of + * these, joined here once, so two screens never name a worker two ways. + * + * A worker the user hired is theirs alone, so the inventory never names it: + * it comes from their roster, on the flow its entry names, with that flow's + * door and flags read off the inventory rows on the same flow. A standard + * worker's harness rides on its roster entry, not on its inventory row. + */ +import type { SessionSummary } from "@flow-state-dev/client"; +import { WORKER_ID_STATE_KEY, WORKSTREAM_STATE_KEY, type RosterEntry } from "@flow-state-dev/workforce/browser"; + +/** A worker, as the inventory registers it and the roster adds to it. */ +export type Worker = { + /** + * The worker's id: `.`, or a bare name for an org worker. Boards + * name the worker by it, and its sessions carry it as their `workerId`. + */ + id: string; + /** The worker flow the worker runs on, which is also that flow's copy id; `null` on a row that has none. */ + kind: string | null; + /** + * The action that takes a user's message into this worker's sessions, as + * the hire published it; `null` when its worker flow takes none, or on a row + * written before doors were published. + */ + door: string | null; + /** Whether the worker keeps standing rules: its worker flow declares the rules action. */ + rules: boolean; + /** Whether its door takes the task a line is sent from (`taskId`). A door that doesn't is sent none. */ + doorTakesTask: boolean; + /** The id of the team it sits under, or {@link GENERAL_TEAM} for an org worker. */ + team: string; + /** Its team's display name: the team's own, "General" for {@link GENERAL_TEAM}, else the team id. */ + teamName: string; + /** Its id without the team: what a board may name it by. */ + name: string; + /** What a user reads it by: its display name, or its id when it has none. */ + displayName: string; + /** The coding harness its roster entry's settings name; absent when it names none, or before the roster is read. */ + harness?: string; +}; + +function field(row: unknown, key: string): unknown { + return typeof row === "object" && row !== null ? (row as Record)[key] : undefined; +} +function text(value: unknown): string | null { + return typeof value === "string" && value.length > 0 ? value : null; +} + +/** + * The worker a session runs, as its state names it (`workerId`), or `null` + * when it names none. + */ +export function workerOf(session: SessionSummary): string | null { + return text(field((session as { state?: unknown }).state, WORKER_ID_STATE_KEY)); +} + +/** + * The workstream a session leads, as its readonly `workstreamId` names it + * (`//`), or `null` for a session outside + * any workstream. + */ +export function workstreamOf(session: SessionSummary): string | null { + return text(field((session as { state?: unknown }).state, WORKSTREAM_STATE_KEY)); +} + +/** + * The id of the group an org worker sits in: a worker whose address has no + * team, such as a Shift Coordinator or a researcher. A user reads it as + * {@link GENERAL_TEAM_NAME}. The underscore keeps it outside Workforce's team + * ids (lowercase letters, digits and hyphens), so a team folder named + * `general` stays its own team. + */ +export const GENERAL_TEAM = "_general"; + +/** {@link GENERAL_TEAM}'s display name. */ +export const GENERAL_TEAM_NAME = "General"; + +/** + * A worker's team and names, from its id and the display names its row + * carries (each `null` when unset): + * + * - `.` sits under its team: a team id carries no dot, so the team + * is everything before the first one; + * - an id with no dot is an org worker, and sits in {@link GENERAL_TEAM}. + */ +export function workerNames( + id: string, + displayName: string | null, + teamName: string | null, +): Pick { + const dot = id.indexOf("."); + const team = dot > 0 ? id.slice(0, dot) : GENERAL_TEAM; + return { + team, + teamName: dot > 0 ? (teamName ?? team) : GENERAL_TEAM_NAME, + name: dot > 0 ? id.slice(dot + 1) : id, + displayName: displayName ?? id, + }; +} + +/** 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")); + 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"))), + }; +} + +/** The harness a roster entry's settings name, as a {@link Worker} field; nothing when it names none. */ +function harnessOf(entry: RosterEntry | undefined): Pick { + const harness = entry?.settings?.harness; + return typeof harness === "string" ? { harness } : {}; +} + +/** + * The user's own workers as rows beside the inventory's: each on the flow it + * names, with that flow's door and its rules and task flags, grouped and + * named the way an inventory row is. + */ +function ownWorkers(entries: readonly RosterEntry[], inventory: readonly Worker[]): Worker[] { + return entries + .filter((entry) => !entry.standard && !inventory.some((worker) => worker.id === entry.id)) + .map((entry) => { + const onFlow = inventory.find((worker) => worker.kind === entry.flow); + return { + id: entry.id, + kind: entry.flow, + door: onFlow?.door ?? null, + rules: onFlow?.rules ?? false, + doorTakesTask: onFlow?.doorTakesTask ?? false, + ...workerNames(entry.id, entry.name, entry.teamName), + ...harnessOf(entry), + }; + }); +} + +/** The joined directory: every worker, and which of them are the user's own. */ +export type JoinedWorkers = { workers: Worker[]; own: Worker[] }; + +/** + * The inventory's workers (`undefined` while it is unread or failed) joined + * with the roster's entries. With the inventory unread, the standard workers + * the roster lists are still the user's, so they are drawn too. + */ +export function joinWorkers(inventory: readonly Worker[] | undefined, entries: readonly RosterEntry[]): JoinedWorkers { + const declared = (inventory ?? []).map((worker) => ({ ...worker, ...harnessOf(entries.find((entry) => entry.id === worker.id)) })); + const own = ownWorkers(entries, declared); + const standard = + inventory === undefined ? ownWorkers(entries.filter((entry) => entry.standard).map((entry) => ({ ...entry, standard: false })), declared) : []; + return { workers: [...declared, ...standard, ...own], own }; +} diff --git a/packages/shift-manager/src/lib/workforce.ts b/packages/shift-manager/src/lib/workforce.ts index 1575c5f4f8..1ca16134b5 100644 --- a/packages/shift-manager/src/lib/workforce.ts +++ b/packages/shift-manager/src/lib/workforce.ts @@ -10,16 +10,32 @@ * may import only `contracts`, `core` and `client`, and `@flow-state-dev/workforce` * may not import `react`, so neither package can hold a hook over * `createWorkforceClient`. An app builds the same client with `useMemo`. + * + * One workforce client per Lab client, shared by every screen, so what it + * reads once (the organization) is read once for the page. */ import { useMemo } from "react"; +import type { Client } from "@flow-state-dev/client"; import { createWorkforceClient, type WorkforceClient } from "@flow-state-dev/workforce/browser"; import { useLab } from "./lab-data"; +const built = new WeakMap(); + +/** The one workforce client over `client`. */ +function workforceOf(client: Client): WorkforceClient { + let found = built.get(client); + if (found === undefined) { + found = createWorkforceClient(client); + built.set(client, found); + } + return found; +} + /** * The workforce client for the Lab this page reads, one per connection. * Throws outside a `LabProvider`. */ export function useWorkforce(): WorkforceClient { const { client } = useLab(); - return useMemo(() => createWorkforceClient(client), [client]); + return useMemo(() => workforceOf(client), [client]); } diff --git a/packages/shift-manager/src/surfaces/Inbox.tsx b/packages/shift-manager/src/surfaces/Inbox.tsx index adeafcf7cb..1a2f28e4f4 100644 --- a/packages/shift-manager/src/surfaces/Inbox.tsx +++ b/packages/shift-manager/src/surfaces/Inbox.tsx @@ -32,10 +32,11 @@ import { AskCard } from "../components/AskCard"; import { TurnComposer } from "../components/TurnComposer"; import { EmptyState, Meta, ScreenTitle, SectionFailure, StateSquare, Tabs } from "../components/ui"; import { askSessionOf, type SessionCall, type SessionReply } from "../lib/ask-session"; -import { doorOf, rosterOf, waited, workerLabel, type LoadedSnapshot } from "../lib/derive"; +import { doorOf, waited, workerLabel } from "../lib/shift"; +import { useWorkers, type Workers } from "../lib/directory"; import type { InboxHold, InboxAnswer, InboxItem as OrchestrationInboxItem } from "@flow-state-dev/orchestration/inbox"; import type { SuspensionItem } from "@flow-state-dev/core/items"; -import { describeFailure, type Failure } from "../lib/reads"; +import { describeFailure, type Failure } from "../lib/failure"; import { useInbox, useInboxAnswer, type InboxAsk } from "../lib/inbox"; import { groupedByWorker, itemAtRoute, sessionOfHold, workerOfHold } from "../lib/inbox-list"; import { navigate } from "../lib/routes"; @@ -137,7 +138,7 @@ function ItemButton({ item, selected, from, now }: { item: InboxItem; selected: ); } -export function Inbox({ snapshot, itemId, gaps }: { snapshot: LoadedSnapshot; itemId: string | null; gaps: Gaps }) { +export function Inbox({ itemId, gaps }: { itemId: string | null; gaps: Gaps }) { const inbox = useInbox(); const [filter, setFilter] = useState("All"); // Bumped when a reply is delivered, so the ask's session is read again then. @@ -233,7 +234,6 @@ export function Inbox({ snapshot, itemId, gaps }: { snapshot: LoadedSnapshot; it ) : ( setReplies((n) => n + 1)} @@ -247,13 +247,11 @@ export function Inbox({ snapshot, itemId, gaps }: { snapshot: LoadedSnapshot; it /** A suspension's detail: its card, its session, and the reply box under it. */ function AskDetail({ hold: selected, - snapshot, gaps, replies, onDelivered, }: { hold: InboxViewHold; - snapshot: LoadedSnapshot; gaps: Gaps; replies: number; onDelivered: () => void; @@ -280,7 +278,6 @@ function AskDetail({ @@ -500,15 +497,16 @@ function AskSession({ hold }: { hold: InboxViewHold; reread?: number }) { } /** Why a reply can't go into the ask's session, or the door it goes through. */ -function replyRoute(hold: InboxViewHold, snapshot: LoadedSnapshot, gaps: Gaps): { blocked: string } | { blocked: null; sessionId: string; flowId: string; door: string } { +function replyRoute(hold: InboxViewHold, directory: Workers, gaps: Gaps): { blocked: string } | { blocked: null; sessionId: string; flowId: string; door: string } { const sessionId = sessionOfHold(hold); // A run with no conversation has no session to reply into. if (sessionId === null) return { blocked: NO_CONVERSATION_REPLY }; const flowId = hold.source.flowId; // A session written before instance ownership names no flow, so no door. if (flowId === null) return { blocked: hold.unanswerable ?? "This session names no flow to send through." }; - if (!snapshot.inventory.ok) return { blocked: snapshot.inventory.failure.message }; - const door = doorOf(rosterOf(snapshot).workers, flowId); + if (directory.inventory === undefined) return { blocked: "Reading the Lab's workers first…" }; + if (!directory.inventory.ok) return { blocked: directory.inventory.failure.message }; + const door = doorOf(directory.workers, flowId); if (door === null) return { blocked: `${workerLabel(workerOfHold(hold) ?? flowId)} ${gaps.turn.replyNoDoor}` }; return { blocked: null, sessionId, flowId, door }; } @@ -517,16 +515,14 @@ function replyRoute(hold: InboxViewHold, snapshot: LoadedSnapshot, gaps: Gaps): /** The reply box under an ask. */ function Reply({ hold, - snapshot, gaps, onDelivered, }: { hold: InboxViewHold; - snapshot: LoadedSnapshot; gaps: Gaps; onDelivered: () => void; }) { - const route = replyRoute(hold, snapshot, gaps); + const route = replyRoute(hold, useWorkers(), gaps); const worker = workerOfHold(hold); const workforce = useWorkforce(); const deliver = useDeliverLine(); diff --git a/packages/shift-manager/src/surfaces/JumpTo.tsx b/packages/shift-manager/src/surfaces/JumpTo.tsx index a8fe3d866d..c3b9d56ce0 100644 --- a/packages/shift-manager/src/surfaces/JumpTo.tsx +++ b/packages/shift-manager/src/surfaces/JumpTo.tsx @@ -2,7 +2,7 @@ /** * Jump to (⌘K; Shift+⌘K opens it in message mode): find any screen the sidebar * reaches, a project, a workstream, a worker, a task or a declared document, - * from the one snapshot, and go there. A query matches a result's + * from the reads the page holds, and go there. A query matches a result's * shown name, its hint, or its id. A worker opens Roster on its team with its * row in view and focus. A document opens read-only. A Lab that serves no * document to the browser gets a line saying so, and a failed read of them, or @@ -22,10 +22,12 @@ import type { Client } from "@flow-state-dev/client"; import { useEffect, useMemo, useRef, useState } from "react"; import { Command, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command"; import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog"; -import { shiftCoordinatorOf, workerLabel, type LoadedSnapshot } from "../lib/derive"; +import { shiftCoordinatorOf, workerLabel } from "../lib/shift"; import type { InboxBoardTask } from "../lib/inbox"; import { handToShiftCoordinator } from "../lib/outbox"; -import { readProject, type WorkstreamEntry } from "../lib/projects"; +import { readProject, type Project, type WorkstreamEntry } from "../lib/projects"; +import { useProjects, useWorkers } from "../lib/directory"; +import { useDocuments } from "../lib/documents"; import { navigate, type Route } from "../lib/routes"; import { RouteLink } from "../components/RouteLink"; import type { Gaps } from "../gaps"; @@ -61,9 +63,8 @@ type Workstreams = { key: string; project: string; to: (entry: WorkstreamEntry) * Each project's workstreams, read once per project while the palette is open: * a palette open for a minute does not poll. */ -function useWorkstreams(snapshot: LoadedSnapshot, client: Client | undefined): Workstreams[] { +function useWorkstreams(projects: readonly Project[], client: Client | undefined): Workstreams[] { const [reads, setReads] = useState([]); - const projects = snapshot.projects.ok ? snapshot.projects.value.rows : []; const addresses = projects.map((p) => `${p.visibility}/${p.id}`).join("\n"); useEffect(() => { if (client === undefined) return; @@ -109,14 +110,12 @@ function focusWhenDrawn(selector: string) { } export function JumpTo({ - snapshot, tasks, gaps, client, initialQuery = "", onClose, }: { - snapshot: LoadedSnapshot; /** Every board row, from the inbox view; without them, Jump to lists no tasks. */ tasks?: readonly InboxBoardTask[]; /** Reads each project's workstreams when the palette opens; without one, Jump to lists no workstreams. */ @@ -133,11 +132,13 @@ export function JumpTo({ // What had focus before the palette opened. The dialog only gives focus back to a trigger, and Jump to has none. const [opener] = useState(() => (typeof document === "undefined" ? null : (document.activeElement as HTMLElement | null))); const messaging = query.startsWith(MESSAGE_PREFIX); - const workstreams = useWorkstreams(snapshot, client); + const { inventory, workers } = useWorkers(); + const projectRows = useProjects().section; + const projects = useMemo(() => (projectRows?.ok === true ? projectRows.value : []), [projectRows]); + const workstreams = useWorkstreams(projects, client); + const documents = useDocuments(); const index = useMemo(() => { - const workers = snapshot.inventory.ok ? snapshot.inventory.value.workers : []; - const projects = snapshot.projects.ok ? snapshot.projects.value.rows : []; return [ ...VIEWS, ...projects.map((p): Entry => ({ @@ -161,9 +162,9 @@ export function JumpTo({ focus: `[data-testid="roster-worker"][data-worker-id="${w.id.replace(/"/g, '\\"')}"]`, })), ...(tasks ?? []).map((r): Entry => ({ group: "Tasks", label: r.title, hint: `${r.status} · ${r.boardRef}`, keywords: [r.id], to: { level: "task", boardRef: r.boardRef, taskId: r.id, tab: "session" } })), - ...(snapshot.resources.ok ? snapshot.resources.value : []).map((d): Entry => ({ group: "Resources", label: d.ref, hint: "read-only", keywords: [d.sessionId], to: { level: "resource", sessionId: d.sessionId, ref: d.ref } })), + ...(documents?.ok === true ? documents.value : []).map((d): Entry => ({ group: "Resources", label: d.ref, hint: "read-only", keywords: [d.sessionId], to: { level: "resource", sessionId: d.sessionId, ref: d.ref } })), ]; - }, [snapshot, workstreams, tasks]); + }, [workers, projects, workstreams, tasks, documents]); const needle = query.trim().toLowerCase(); const matches = (e: Entry) => needle === "" || [e.label, e.hint, ...e.keywords].some((word) => word.toLowerCase().includes(needle)); @@ -176,8 +177,8 @@ export function JumpTo({ const sendMessage = () => { const message = query.slice(MESSAGE_PREFIX.length).trim(); if (message === "") return; - if (!snapshot.inventory.ok) return setSendFailure("The Lab's workers didn't load, so there is no one to send this to."); - const shiftCoordinator = shiftCoordinatorOf(snapshot.inventory.value.workers); + if (inventory?.ok !== true) return setSendFailure("The Lab's workers didn't load, so there is no one to send this to."); + const shiftCoordinator = shiftCoordinatorOf(workers); if (shiftCoordinator.kind !== "one") return setSendFailure("There isn't exactly one Shift Coordinator to send this to."); if (shiftCoordinator.worker.door === null) return setSendFailure(`${workerLabel(shiftCoordinator.worker.id)} ${gaps.turn.noDoor}`); handToShiftCoordinator(message); @@ -247,11 +248,11 @@ export function JumpTo({ {read.project}'s workstreams did not load: {read.failed}

))} - {!snapshot.resources.ok ? ( + {documents === undefined ? null : !documents.ok ? (

- The Lab's documents did not load: {snapshot.resources.failure.message} + The Lab's documents did not load: {documents.failure.message}

- ) : snapshot.resources.value.length === 0 ? ( + ) : documents.value.length === 0 ? (

{gaps.resources}

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 =

Reading the project…

; + } else if (!view.ok) { body = (
- void refresh()} testId="project-failure" /> +
); } else { - const found = view.value.projects.find((row) => row.id === projectId && row.visibility === address.visibility); + const found = view.value.find((row) => row.id === projectId && row.visibility === address.visibility); if (found === undefined) { body = ( @@ -101,7 +116,6 @@ export function ProjectView({ snapshot, route, gaps }: { snapshot: LoadedSnapsho body = ( ; retry: () => void } { - const { client } = useLab(); - const [read, setRead] = useState>(undefined); - const [tries, setTries] = useState(0); - useEffect(() => { - let closed = false; - readProjectSetup(client) - .then((value) => !closed && setRead({ value })) - .catch((error: unknown) => !closed && setRead({ failure: describeFailure(error) })); - return () => { - closed = true; - }; - }, [client, tries]); - const retry = useCallback(() => setTries((n) => n + 1), []); - return { setup: read, retry }; -} - -/** A project's tabs, once the snapshot has it. */ +/** A project's tabs, once the projects read has it. */ function ProjectBody({ - snapshot, route, address, gaps, repository, brief, }: { - snapshot: LoadedSnapshot; route: ProjectRoute; address: ProjectAddress; gaps: Gaps; repository: string | null; brief: string | null; }) { - const { refresh } = useLab(); - // Only Board and Workstreams draw entries; Stream and Brief never pay for the read. - const needsEntries = route.tab === "board" || route.tab === "workstreams"; - const { read, reread } = useProjectRead(address, needsEntries, snapshot.readAt); - const { setup, retry: retrySetup } = useProjectSetup(); - const roster = useRoster(); - const { workers } = withRoster(snapshot, roster); - const entries = read !== undefined && "value" in read && read.value !== null ? read.value.entries : undefined; - const readFailure = - read !== undefined && "failure" in read ? ( -
- -
- ) : 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 =

Reading the project…

; + const setupRead = useProjectSetup(); + const setup = readOf(setupRead); + const { workers, roster } = useWorkers(); switch (route.tab) { case "stream": - return ; + return ; case "brief": return (
@@ -225,38 +200,53 @@ function ProjectBody({
); case "board": - if (readFailure !== null) return readFailure; - if (entries === undefined) return reading; - return ; - case "workstreams": { - if (readFailure !== null) return readFailure; - if (entries === undefined || read === undefined || !("value" in read) || read.value === null) return reading; - if (route.entry !== undefined) { - const entry = entries.find((e) => e.owner === route.entry!.owner && e.id === route.entry!.id); - return ( - - ); - } + // Only Board and Workstreams draw entries; Stream and Brief never pay for the read. + return {(read) => }; + case "workstreams": return ( -
- - - -
+ + {(read) => { + if (route.entry !== undefined) { + const entry = read.entries.find((e) => e.owner === route.entry!.owner && e.id === route.entry!.id); + return ( + + ); + } + return ( +
+ + + +
+ ); + }} +
); - } } } +/** 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

Reading the roster…

; + } + if (!inventory.ok && workers.length === 0) { return (
- void refresh()} testId="roster-inventory-failure" /> +
); } const ownIds = new Set(own.map((worker) => worker.id)); const team = pickedTeam(workers, asked); - const states = workerStates(withOwn); + const states = workerStates(workers, inbox.section?.ok === true ? inbox.section.value : undefined); // The Shift Coordinator first: the coordinator the user's work goes through. const shiftCoordinator = shiftCoordinatorOf(workers); const first = shiftCoordinator.kind === "one" ? shiftCoordinator.worker.id : undefined; @@ -190,7 +182,6 @@ export function RosterView({ .filter((s) => team === null || s.worker.team === team) .sort((a, b) => Number(b.worker.id === first) - Number(a.worker.id === first)); const counts = shiftCounts(states, team ?? undefined); - const unread = Object.entries(snapshot.boards).flatMap(([workstreamId, boards]) => (boards.ok ? [] : [{ workstreamId, failure: boards.failure }])); const title = [lookName ?? "Roster", ...(team === null ? [] : [team])].join(" · "); return ( @@ -205,7 +196,7 @@ export function RosterView({ {counts["on shift"]} on shift · {counts["off shift"]} off shift · {counts.waiting} waiting on you - · read {new Date(snapshot.readAt).toLocaleTimeString()} + {readAt === undefined ? null : · read {new Date(readAt).toLocaleTimeString()}} {states.partial ? : null}

@@ -235,9 +226,9 @@ export function RosterView({ WAITING ON YOU
- {snapshot.inventory.ok ? null : ( + {inventory.ok ? null : (
- void refresh()} testId="roster-inventory-failure" /> +
)} {roster !== undefined && "failure" in roster ? ( @@ -245,16 +236,11 @@ export function RosterView({ Your own workers didn't load: {roster.failure.message}

) : null} - {snapshot.asks.ok ? null : ( + {inbox.section === undefined || inbox.section.ok ? null : (
- void refresh()} testId="roster-asks-failure" /> +
)} - {unread.map(({ workstreamId, failure }) => ( -
- void refresh()} testId="roster-boards-failure" /> -
- ))} {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 }) {

SHIFT SUMMARY · FROM SHIFT MANAGER

-
+
{inbox.ok ? (

{needsYou === 0 ? ( @@ -190,7 +188,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({ />
- {!open ? null : ( -
- {read !== undefined && "failure" in read ? ( -

- Workstreams didn't load.{" "} - -

- ) : entries === undefined ? null : entries.length === 0 ? ( -

- No workstreams -

- ) : ( - entries.map((entry) => ( - - )) - )} -
- )} + {!open ? null : } +
+ ); +} + +/** An open project's workstreams in the sidebar: read only while it is open, so a closed one costs nothing. */ +function ProjectWorkstreams({ project, route, to }: { project: Project; route: Route; to: (entry?: { owner: string; id: string }) => Route }) { + const { value, failure, refresh: reread } = useProjectWorkstreams({ visibility: project.visibility, id: project.id }); + const entries = value?.entries; + const here = route.level === "project" && route.projectId === project.id && (route.visibility ?? "shared") === project.visibility; + return ( +
+ {entries === undefined && failure !== undefined ? ( +

+ Workstreams didn't load.{" "} + +

+ ) : entries === undefined ? null : entries.length === 0 ? ( +

+ No workstreams +

+ ) : ( + entries.map((entry) => ( + + )) + )}
); } @@ -379,15 +377,16 @@ function StreamItem({ entry, active, to }: { entry: WorkstreamEntry; active: boo // BR-22. /** PROJECTS: each project by title, with its workstreams beneath it while it is open. */ -function ProjectsSection({ snapshot, route, onRetry }: { snapshot: LoadedSnapshot; route: Route; onRetry: () => void }) { - const view = projectsOf(snapshot); - if (!view.ok) { - return ; +function ProjectsSection({ route }: { route: Route }) { + const { section, refresh } = useProjects(); + if (section === undefined) return null; + if (!section.ok) { + return ; } return ( <> - {view.value.projects.map((project) => ( - + {section.value.map((project) => ( + ))} ); @@ -412,23 +411,18 @@ export function Sidebar({ collapsed: boolean; onToggle: () => void; }) { - const { snapshot, refresh, client, asking } = useLab(); - const loaded = snapshot !== undefined && snapshot.refused === undefined && snapshot.unreachable === undefined ? (snapshot as LoadedSnapshot) : undefined; - const retry = () => void refresh(); - // The counts dim only while a read the user asked for runs. - const dim = asking ? ` ${ASKING_CLASS}` : ""; + const { client } = useLab(); + const directory = useWorkers(); + const { inventory, roster } = directory; // FIX-2774: the Inbox count and the Tasks count are the inbox view's, the same answer those screens list. const inbox = useInbox().section; const inboxCount = inbox === undefined ? "…" : inbox.ok ? inbox.value.items.length : "!"; const tasksCount = inbox === undefined ? "…" : inbox.ok ? openBoardTasks(inbox.value).length : "!"; const waiting = inbox?.ok === true && inbox.value.items.length > 0; - // The user's own workers are on their roster, not in the inventory: joined as Roster joins them. - const roster = useRoster(); - const joined = loaded === undefined ? undefined : withRoster(loaded, roster); // With the inventory unread and nobody on the roster, TEAMS has only its failure to show. - const drawn = joined !== undefined && (loaded?.inventory.ok === true || joined.workers.length > 0) ? joined : undefined; - const states = drawn === undefined ? undefined : workerStates(drawn.snapshot); + const drawn = inventory !== undefined && (inventory.ok || directory.workers.length > 0) ? directory : undefined; + const states = drawn === undefined ? undefined : workerStates(drawn.workers, inbox?.ok === true ? inbox.value : undefined); const counts = states === undefined ? undefined : shiftCounts(states); const partial = states?.partial === true ? : null; @@ -460,11 +454,10 @@ export function Sidebar({ mark={ // v2's badge (v2:60): the highlighter only while an ask waits on the user. {inboxCount} @@ -477,7 +470,7 @@ export function Sidebar({ label="Tasks" icon={} mark={ - + {tasksCount} } @@ -519,7 +512,7 @@ export function Sidebar({ PROJECTS
- {loaded === undefined ? null : } +
@@ -555,8 +548,8 @@ export function Sidebar({ )) )} - {loaded === undefined || loaded.inventory.ok ? null : ( - + {inventory === undefined || inventory.ok ? null : ( + )} {roster !== undefined && "failure" in roster ? (

diff --git a/packages/shift-manager/src/surfaces/TaskFrame.tsx b/packages/shift-manager/src/surfaces/TaskFrame.tsx index 67e3a0765b..56e2221368 100644 --- a/packages/shift-manager/src/surfaces/TaskFrame.tsx +++ b/packages/shift-manager/src/surfaces/TaskFrame.tsx @@ -11,7 +11,7 @@ * What the screen reads is held by {@link TaskProvider}; this file only draws * it. The screen writes three ways: the abort behind Interrupt, the * composer's message, which goes through the one send path (`lib/deliver.ts`), - * and the task actions, the board's own through the reader's `taskActions`. + * and the task actions, the board's own through `useBoardActions`. * * The keyboard stop is deliberate: Esc twice within the window, or Cmd/Ctrl+. * One Esc only dismisses, and an Esc in the composer is the composer's. @@ -20,8 +20,9 @@ import { interruptChordLabel, useInterruptKeys } from "@flow-state-dev/react"; import { useEffect, useMemo, useState } from "react"; import { EmptyState, ScreenTitle, SectionFailure, StateSquare, Tabs } from "../components/ui"; import { columnFor } from "../lib/columns"; -import { doorOf, rosterOf, workerFor, workerLabel, waited } from "../lib/derive"; -import { taskAsks, useInbox } from "../lib/inbox"; +import { doorOf, workerFor, workerLabel, waited } from "../lib/shift"; +import { taskAsks, useBoardActions, useInbox } from "../lib/inbox"; +import { useSessions, useWorkers } from "../lib/directory"; import { useLab } from "../lib/lab-data"; import { navigate, TASK_TABS, type TaskTab } from "../lib/routes"; import { RouteLink } from "../components/RouteLink"; @@ -41,7 +42,8 @@ import { TaskActions } from "../components/flow-state/task-actions"; export function TaskFrame({ tab, gaps }: { tab: TaskTab; gaps: Gaps }) { const task = useTask(); - const { snapshot, stale } = useLab(); + const { stale } = useLab(); + const { workers } = useWorkers(); const { row, boardRef, taskId } = task; const stoppable = task.run.kind === "open" && task.status === "in_progress" && task.interrupt.kind !== "pending"; const keys = useInterruptKeys({ enabled: stoppable, onInterrupt: () => void task.requestInterrupt() }); @@ -61,7 +63,7 @@ export function TaskFrame({ tab, gaps }: { tab: TaskTab; gaps: Gaps }) { // The same resolver the inspector and Tasks use, so a name two teams share // resolves to no worker at all. - const found = row === undefined || snapshot === undefined || snapshot.refused !== undefined || snapshot.unreachable !== undefined ? undefined : workerFor(rosterOf(snapshot), row); + const found = row === undefined ? undefined : workerFor(workers, row); const worker = row?.assignee == null ? null : workerLabel(found?.id ?? row.assignee); return ( @@ -199,17 +201,14 @@ function Activity({ worker, armed }: { worker: string | null; armed: boolean }) /** Interrupt, the task's actions, and the controls with no shipped operation (D2). */ function Actions({ gaps }: { gaps: Gaps }) { const task = useTask(); - const { reader, snapshot, refresh } = useLab(); + const sessions = useSessions().list; const running = task.run.kind === "open" && task.status === "in_progress"; const pending = task.interrupt.kind === "pending"; // The board's actions run on the conversation that holds it, through the // flow that conversation's session names as its owner. No owner, no actions. const holder = holderSessionOf(task.boardRef); - const flowId = - snapshot === undefined || snapshot.refused !== undefined || snapshot.unreachable !== undefined || !isConversationBoard(task.boardRef) - ? undefined - : (snapshot.sessions.find((session) => session.id === holder)?.flowId ?? undefined); - const board = useMemo(() => (flowId === undefined ? undefined : reader.taskActions({ id: holder, flowId })), [reader, holder, flowId]); + const flowId = !isConversationBoard(task.boardRef) ? undefined : (sessions?.find((session) => session.id === holder)?.flowId ?? undefined); + const board = useBoardActions(flowId === undefined ? undefined : { id: holder, flowId }); return (

- {inbox.section === undefined ? "…" : summaryLine(inbox.section, snapshot)} + {inbox.section === undefined ? "…" : summaryLine(inbox.section, workers)}
@@ -125,8 +126,8 @@ export function Tasks({ snapshot, by, gaps }: { snapshot: LoadedSnapshot; by: Ta
) : null} - {!snapshot.inventory.ok ? ( - void refresh()} /> + {inventory?.ok === false ? ( + ) : inbox.section === undefined ? (

Reading the boards… @@ -167,7 +168,7 @@ export function Tasks({ snapshot, by, gaps }: { snapshot: LoadedSnapshot; by: Ta - {by === "worker" ? workerLabel(roster.workers.find((worker) => worker.id === key)?.displayName ?? key) : key}{" "} + {by === "worker" ? workerLabel(workers.find((worker) => worker.id === key)?.displayName ?? key) : key}{" "} {groupRows.length} {by === "state" && key === "IN REVIEW" ? ( @@ -177,7 +178,7 @@ export function Tasks({ snapshot, by, gaps }: { snapshot: LoadedSnapshot; by: Ta {groupRows.map((row) => { - const worker = workerFor(roster, row); + const worker = workerFor(workers, row); const time = elapsed(row, now); return ( (7); - const { rows, failure, reread } = useWorkerUsage(readAt, days); + const { rows, failure, reread } = useWorkerUsage(days); // A Lab that answers no per-worker query shows nothing here. if (rows === null) return null; return ( @@ -232,8 +231,8 @@ function WorkerUsageSection({ readAt }: { readAt: number }) { ); } -export function Usage({ snapshot }: { snapshot: LoadedSnapshot }) { - const { rows, failure, reread } = useHarnessUsage(snapshot.readAt); +export function Usage() { + const { rows, failure, reread } = useHarnessUsage(); return (

@@ -259,7 +258,7 @@ export function Usage({ snapshot }: { snapshot: LoadedSnapshot }) { ) : ( rows.map((row) => ) )} - +
); diff --git a/packages/shift-manager/src/surfaces/WorkerSettings.tsx b/packages/shift-manager/src/surfaces/WorkerSettings.tsx index 3ddeefc2e5..2c9a107146 100644 --- a/packages/shift-manager/src/surfaces/WorkerSettings.tsx +++ b/packages/shift-manager/src/surfaces/WorkerSettings.tsx @@ -6,17 +6,16 @@ */ import { StandingRules } from "../components/StandingRules"; import { ScreenTitle } from "../components/ui"; -import { shiftCoordinatorOf, type LoadedSnapshot } from "../lib/derive"; -import { useRoster, withRoster } from "../lib/roster"; +import { shiftCoordinatorOf } from "../lib/shift"; +import { useWorkers } from "../lib/directory"; import { RouteLink } from "../components/RouteLink"; // FIX-1747. /** What Shift Manager calls the `shift-coordinator` worker. */ const SHIFT_COORDINATOR_NAME = "Shift Coordinator"; -export function WorkerSettingsView({ snapshot, workerId, devtoolUrl }: { snapshot: LoadedSnapshot; workerId: string; devtoolUrl?: string }) { - const roster = useRoster(); - const { workers } = withRoster(snapshot, roster); +export function WorkerSettingsView({ workerId, devtoolUrl }: { workerId: string; devtoolUrl?: string }) { + const { workers, roster } = useWorkers(); const worker = workers.find((w) => w.id === workerId); const shiftCoordinator = shiftCoordinatorOf(workers); const name = shiftCoordinator.kind === "one" && shiftCoordinator.worker.id === workerId ? SHIFT_COORDINATOR_NAME : (worker?.name ?? workerId); From a86d6eb8c6f28ce5c60c53a21145cbd46d03b08b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 00:05:09 +0000 Subject: [PATCH 02/24] wip: allowlist, reads.ts and derive.ts shrink --- packages/shift-manager/src/lib/derive.ts | 147 +------- packages/shift-manager/src/lib/reads.ts | 324 ++---------------- .../test/inventory-allowlist.json | 18 +- .../shift-manager/test/inventory-settings.ts | 36 +- 4 files changed, 63 insertions(+), 462 deletions(-) diff --git a/packages/shift-manager/src/lib/derive.ts b/packages/shift-manager/src/lib/derive.ts index e2fd283918..104d467e73 100644 --- a/packages/shift-manager/src/lib/derive.ts +++ b/packages/shift-manager/src/lib/derive.ts @@ -1,21 +1,13 @@ /** - * What the screens compute from one snapshot, kept out of the components so - * every surface computes it the same way. + * What the snapshot's reads compute from one snapshot. No screen reads the + * snapshot any more: the screens compute from their own reads (`shift.ts`, + * `inbox.ts`), and the helpers both share live there. */ import type { InboxItem } from "@flow-state-dev/orchestration/inbox"; import { isDone } from "./columns"; -import { - GENERAL_TEAM, - type Ask, - type BoardTaskView, - type Failure, - type LabSnapshot, - type Project, - type Section, - type Worker, - workerOf, - workstreamOf, -} from "./reads"; +import type { Ask, BoardTaskView, Failure, LabSnapshot, Project, Section, Worker } from "./reads"; +import { workerFor, type ShiftStatus } from "./shift"; +import { workerOf, workstreamOf } from "./workers"; /** A loaded snapshot (not a refusal, not an unreachable Lab). */ export type LoadedSnapshot = Exclude; @@ -50,36 +42,6 @@ export function openTasks(snapshot: LoadedSnapshot): BoardTaskView[] { /** The workers a row's assignee is resolved against. */ export type Roster = { workers: readonly Worker[] }; -// FIX-1672. -/** - * The worker a row is held by, or `undefined` when no single worker is. - * - * A row names an `assignee`, which is a routing key a board's workers answer - * to, not a worker address: a board may name `` for the worker - * `.`. So, in order: - * - * 1. the worker whose id is the assignee; - * 2. the one worker whose own name is the assignee. - * - * A name more than one worker carries, or none, is no worker: a row is never shown against - * several workers, or against a guess. Which worker actually claimed the row is - * not published to a browser, and a declared assignee-to-worker map - * arrives in a later release. - */ -export function workerFor(roster: Roster, row: Pick): Worker | undefined { - if (row.assignee === null) return undefined; - const exact = roster.workers.find((worker) => worker.id === row.assignee); - if (exact !== undefined) return exact; - const named = roster.workers.filter((worker) => worker.name === row.assignee); - return named.length === 1 ? named[0] : undefined; -} - -/** A worker's shift status, the one word Roster and the sidebar draw. */ -export type ShiftStatus = "on shift" | "off shift"; - -/** The two statuses, in the order Roster groups them. */ -export const SHIFT_STATUSES: readonly ShiftStatus[] = ["on shift", "off shift"]; - /** One worker's state: its status, the tasks it holds, and the asks it waits on you with. */ export type WorkerState = { worker: Worker; @@ -127,7 +89,7 @@ export function workerStates(snapshot: LoadedSnapshot): WorkerStates { ); for (const row of allTasks(snapshot)) { if (row.status !== "in_progress") continue; - const owner = workerFor(roster, row); + const owner = workerFor(roster.workers, row); if (owner === undefined) continue; const state = workers.get(owner.id); state?.held.push(row); @@ -200,39 +162,6 @@ export function asksOfTask(snapshot: LabSnapshot | undefined, row: Pick worker.kind === flowId)?.door ?? null; -} - -/** - * Whether the door of the flow that owns a session takes a task id, read the - * same way as {@link doorOf}. `false` when no worker entry is on the flow. - */ -export function doorTakesTaskOf(workers: readonly Worker[], flowId: string): boolean { - return workers.find((worker) => worker.kind === flowId)?.doorTakesTask ?? false; -} - -/** - * The teams in the worker inventory, each with its display name and its - * workers, in first-seen order, with the org workers' General group first. - */ -export function teamsOf(workers: readonly Worker[]): Array<{ team: string; name: string; workers: Worker[] }> { - const teams = new Map(); - for (const worker of workers) { - const team = teams.get(worker.team); - if (team === undefined) teams.set(worker.team, [worker]); - else team.push(worker); - } - const all = [...teams].map(([team, workers]) => ({ team, name: workers[0]!.teamName, workers })); - return [...all.filter((t) => t.team === GENERAL_TEAM), ...all.filter((t) => t.team !== GENERAL_TEAM)]; -} - /** PROJECTS: every project the user reads. */ export type ProjectsView = { projects: Project[] }; @@ -247,57 +176,6 @@ export function projectsOf(snapshot: LoadedSnapshot): Section { return { ok: true, value: { projects: snapshot.projects.value.rows } }; } - -/** How many workers are in each status, and how many waits-on entries they have. */ -export type ShiftCounts = Record & { - /** Each held task holding on a question for you plus each pending ask, across the workers counted. */ - waiting: number; -}; - -/** The counts over every worker in `states`, or over one team's. */ -export function shiftCounts(states: WorkerStates, team?: string): ShiftCounts { - const counts: ShiftCounts = { "on shift": 0, "off shift": 0, waiting: 0 }; - for (const { worker, status, waitsOnYou, asks } of states.workers.values()) { - if (team !== undefined && worker.team !== team) continue; - counts[status] += 1; - counts.waiting += waitsOnYou.length + asks.length; - } - return counts; -} - -/** The team a Roster address picks, or `null` (All) when the inventory has no such team. */ -export function pickedTeam(workers: readonly Worker[], team: string | null): string | null { - return team !== null && workers.some((worker) => worker.team === team) ? team : null; -} - -/** - * The name a worker must carry to be the Shift Coordinator: an org worker's id, or a - * team worker's name. The only place Shift Manager names a worker (D2). - */ -const SHIFT_COORDINATOR = "shift-coordinator"; - -const isShiftCoordinator = (idOrName: string) => idOrName.slice(idOrName.indexOf(".") + 1) === SHIFT_COORDINATOR; - -/** How the screens name a worker: `shift-coordinator` is the Shift Coordinator. */ -export function workerLabel(idOrName: string): string { - return isShiftCoordinator(idOrName) ? "Shift Coordinator" : idOrName; -} - -/** Which worker Shift Manager talks to as the Shift Coordinator, if exactly one is. */ -export type ShiftCoordinator = { kind: "one"; worker: Worker } | { kind: "none" } | { kind: "several"; workers: Worker[] }; - -/** - * The Shift Coordinator among the inventory's workers (D2): the workers whose name is - * exactly `shift-coordinator`. That is an org worker (`shift-coordinator`) or a - * team's worker (`.shift-coordinator`). One is the Shift Coordinator; two or - * more are a state, never a guess. - */ -export function shiftCoordinatorOf(workers: readonly Worker[]): ShiftCoordinator { - const found = workers.filter((worker) => isShiftCoordinator(worker.id)); - if (found.length === 0) return { kind: "none" }; - return found.length === 1 ? { kind: "one", worker: found[0]! } : { kind: "several", workers: found }; -} - /** Whether a row is running. */ const isRunning = (row: BoardTaskView) => row.status === "in_progress"; @@ -332,14 +210,3 @@ export function shiftSummary(snapshot: LoadedSnapshot): { : { ok: false, failure: failed }, }; } - -/** How long ago `since` was, in a short human form. */ -export function waited(since: number, now: number): string { - const seconds = Math.max(0, Math.round((now - since) / 1000)); - if (seconds < 60) return `${seconds}s`; - const minutes = Math.round(seconds / 60); - if (minutes < 60) return `${minutes}m`; - const hours = Math.round(minutes / 60); - if (hours < 48) return `${hours}h`; - return `${Math.round(hours / 24)}d`; -} diff --git a/packages/shift-manager/src/lib/reads.ts b/packages/shift-manager/src/lib/reads.ts index 6f1eee7505..7edb8bdcdf 100644 --- a/packages/shift-manager/src/lib/reads.ts +++ b/packages/shift-manager/src/lib/reads.ts @@ -57,110 +57,31 @@ * session records as its owner (`flowId`), never the board's. */ import { ClientHttpError, readEveryCollectionPage, type ResourceManifest, type SessionSummary } from "@flow-state-dev/client"; +import type { BoardTask } from "@flow-state-dev/workforce/browser"; import type { FileContent, OutputItem, SuspensionItem } from "@flow-state-dev/core/items"; import { isUserSuspension, suspendForUserKindOf, type ResumeAction } from "@flow-state-dev/core/types"; import { suspensionShape } from "@flow-state-dev/react"; import { deriveSuspensions } from "@flow-state-dev/react/internal"; -import { PROJECTS_PATTERN, ROSTER_FLOW, sessionIdOfFiling, WORKER_ID_STATE_KEY, WORKSTREAM_STATE_KEY } from "@flow-state-dev/workforce/browser"; +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 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"; -import type { TaskSpendView } from "@flow-state-dev/orchestration/tasks"; -/** Why a read did not load. */ -export type Failure = { message: string; httpStatus?: number }; - -/** - * The worker a session runs, as its state names it (`workerId`), or `null` - * when it names none. - */ -export function workerOf(session: SessionSummary): string | null { - return text(field((session as { state?: unknown }).state, WORKER_ID_STATE_KEY)); -} - -/** - * The workstream a session leads, as its readonly `workstreamId` names it - * (`//`), or `null` for a session outside - * any workstream. - */ -export function workstreamOf(session: SessionSummary): string | null { - return text(field((session as { state?: unknown }).state, WORKSTREAM_STATE_KEY)); -} +/** 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, as the worker inventory registers it: one worker. */ -export type Worker = { - /** - * The worker's id: `.`, or a bare name for an org worker. Boards - * name the worker by it, and its sessions carry it as their `workerId`. - */ - id: string; - /** The worker flow the worker runs on, which is also that flow's copy id; `null` on a row that has none. */ - kind: string | null; - /** - * The action that takes a user's message into this worker's sessions, as - * the hire published it; `null` when its worker flow takes none, or on a row - * written before doors were published. - */ - door: string | null; - /** - * Whether the worker keeps standing rules: its worker flow declares the - * rules action, as the hire published it. `false` on a row written before - * the field. - */ - rules: boolean; - /** - * Whether its door takes the task a line is sent from (`taskId`), and - * stamps the turn with it, as the hire published it. `false` on a row - * written before the field: such a door is sent no `taskId`. - */ - doorTakesTask: boolean; - /** The id of the team it sits under, or {@link GENERAL_TEAM} for an org worker (see {@link toWorker}). */ - team: string; - /** Its team's display name: the team's own, "General" for {@link GENERAL_TEAM}, else the team id. */ - teamName: string; - /** Its id without the team: what a board may name it by. */ - name: string; - /** What a user reads it by: its display name, or its id when it has none. */ - displayName: string; - /** - * The coding harness it names in its `harness` setting, off the user's - * roster (`showSettings`); absent when it names none, or before the roster - * is read. - */ - harness?: string; -}; +/** A worker: the directory's row (`workers.ts`). */ +export type Worker = DirectoryWorker; -/** 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). It names no team: its workstreams are its - * entries, read on its screen. 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 - * (its coding work runs on its files). A row written before the field - * existed reads as none. - */ - repository: string | null; -}; +/** 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 = { @@ -168,63 +89,11 @@ export type Projects = { rows: Project[]; }; -/** - * The run working a task, or the run that last worked it: the session a - * dispatched attempt runs in, that attempt's request there, and the attempt - * number. The board's claim gate writes it from inside the run; the next claim - * clears it. It carries no flow: the run's flow is the one its session records - * as its owner. - */ -export type RunLink = { sessionId: string; requestId: string; attempt: number }; - -/** One task on a conversation's board, with the fields a board publishes to a browser. */ -export type BoardTaskView = { - /** The board's ref: `.tasks`, the conversation that holds it and the collection. */ - boardRef: string; - /** The session id of the conversation that holds the board. */ - ownerSessionId: string; - id: string; - title: string; - /** The row's goal, as filed. */ - goal: string | null; - /** The rest of the brief beside the goal, as filed, or `null` when it has none. */ - context: string | null; - // FIX-2522. - /** The brief's files, as references, in order: every run of the task gets them. Empty when it has none. */ - attachments: FileContent[]; - /** The status as stored (see `columns.ts` for how it is read). */ - status: string; - assignee: string | null; - priority: string | null; - labels: string[]; - /** The ids of the rows on the same board this one waits on. */ - deps: string[]; - /** - * The run the board's gate linked to this row, or `null`: never claimed, - * claimed but not yet started, or stored before the link existed. - */ - run: RunLink | null; - error: string | null; - // FIX-2133. - /** - * What holds the row: its questions and confirms, and its run's - * stop for the user. Empty when nothing does. The Inbox lists the task's - * item from the open ones. - */ - holds: TaskHold[]; - /** Its steers as the Inbox reads them: which question each answers. A question is open while none does. */ - steers: Array<{ id: string; answers?: string }>; - /** - * What its runs spent, folded by orchestration's task view: harness, - * model, tokens and the vendor's charge. `null` before it runs, or from a - * board that publishes no spend. - */ - spend: TaskSpendView | null; - createdAt: number | null; - updatedAt: number | null; - startedAt: number | null; - completedAt: number | null; -}; +/** 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[] }; @@ -339,31 +208,6 @@ const ASK_READ_BATCH = 6; */ const NO_ROSTER_FLOW = `Unknown flow "${ROSTER_FLOW}"`; -// FIX-2624. -/** - * Every entry of a user or org collection the user may read, by scope and key - * pattern, with no session: the direct read (`client.resource`), paged through - * the client's one cursor loop (`readEveryCollectionPage`), whose ceiling and - * repeated-cursor check it keeps. Each row carries the entry's client - * projection as `clientData`, as a session-addressed read does, so one parser - * reads either. A 404 is no flow declaring the collection, or a caller none of - * them signs in. `topicPrefix` keeps the entries whose storage key starts with it. - */ -export function readEveryScopeEntry(client: Client, scope: "user" | "org", pattern: string, topicPrefix?: string) { - const collection = client.resource({ scope, pattern }); - const pages = { - listCollectionResources: async (_sessionId: string, _ref: string, options: { limit?: number; cursor?: string } = {}) => { - const page = await collection.list({ ...options, ...(topicPrefix === undefined ? {} : { topicPrefix }) }); - return { - items: page.items.map((entry) => ({ topic: entry.topic, storageKey: entry.storageKey, clientData: entry.value })), - ...(page.nextCursor === undefined ? {} : { nextCursor: page.nextCursor }), - }; - }, - }; - // No session: the direct read takes none, so the loop's session and ref are the address's. - return readEveryCollectionPage(pages, scope, pattern, { limit: PAGE_SIZE }); -} - /** What a user's ask asks for: an approval, a review, or a question (an input). */ function askTypeOf(item: SuspensionItem): Ask["kind"] { const asked = suspendForUserKindOf(item) ?? (suspensionShape(item) === "approval" ? "approval" : "input"); @@ -394,108 +238,6 @@ export async function readPendingSuspensions(client: Client, sessionId: string): return deriveSuspensions(items).pending; } -/** A failure, in the server's own words when it sent any. */ -export function describeFailure(error: unknown): Failure { - if (error instanceof ClientHttpError) { - const body = error.body as { error?: unknown; message?: unknown } | undefined; - const said = typeof body?.error === "string" ? body.error : typeof body?.message === "string" ? body.message : undefined; - return { httpStatus: error.status, message: said ?? error.message }; - } - return { message: error instanceof Error ? error.message : String(error) }; -} - -function field(row: unknown, key: string): unknown { - return typeof row === "object" && row !== null ? (row as Record)[key] : undefined; -} -function text(value: unknown): string | null { - return typeof value === "string" && value.length > 0 ? value : null; -} -function time(value: unknown): number | null { - if (typeof value === "number" && Number.isFinite(value)) return value; - if (typeof value === "string") { - const parsed = Date.parse(value); - return Number.isNaN(parsed) ? null : parsed; - } - return null; -} - -/** - * The id of the group an org worker sits in: a worker whose address has no - * team, such as a Shift Coordinator or a researcher. A user reads it as - * {@link GENERAL_TEAM_NAME}. The underscore keeps it outside Workforce's team - * ids (lowercase letters, digits and hyphens), so a team folder named - * `general` stays its own team. - */ -export const GENERAL_TEAM = "_general"; - -/** {@link GENERAL_TEAM}'s display name. */ -export const GENERAL_TEAM_NAME = "General"; - -/** - * A worker's team and names, from its id and the display names its row - * carries (each `null` when unset): - * - * - `.` sits under its team: a team id carries no dot, so the team - * is everything before the first one; - * - an id with no dot is an org worker, and sits in {@link GENERAL_TEAM}. - */ -export function workerNames( - id: string, - displayName: string | null, - teamName: string | null, -): Pick { - const dot = id.indexOf("."); - const team = dot > 0 ? id.slice(0, dot) : GENERAL_TEAM; - return { - team, - teamName: dot > 0 ? (teamName ?? team) : GENERAL_TEAM_NAME, - name: dot > 0 ? id.slice(dot + 1) : id, - displayName: displayName ?? id, - }; -} - -/** A worker inventory row, grouped and named by {@link workerNames}. */ -export function toWorker(row: unknown): Worker | undefined { - const id = text(field(row, "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"))), - }; -} - -// BP-030. -/** - * A project entry. A row 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 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")); - 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", - ownerUserId, - members: strings(field(row, "members")), - repository: text(field(row, "repository")), - }; -} - -function strings(value: unknown): string[] { - return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : []; -} - // FIX-2774: workforce's `boardTaskOf` is the one mapper; the inbox view reads tasks through it too. // The snapshot's boards, and this wrapper with them, go with FIX-2775/2776. /** @@ -509,30 +251,6 @@ export function toBoardTaskView(boardRef: string, ownerSessionId: string, topic: return boardTaskOf(boardRef, ownerSessionId, topic, stored); } -/** - * 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; -} - /** * The conversation a conversation-ledger row belongs to: its topic is * `/`, the partition the conversation's `filingSessionId` @@ -735,8 +453,8 @@ export function createLabReader(client: Client): LabReader { */ const readInventory = async (): Promise> => { try { - const workers = (await readEveryScopeEntry(client, "org", WORKER_INVENTORY_PATTERN)) - .map((r) => toWorker(r.clientData)) + const workers = (await client.resource({ scope: "org", pattern: WORKER_INVENTORY_PATTERN }).listAll({ limit: PAGE_SIZE })) + .map((r) => toWorker(r.value)) .filter((worker): worker is Worker => worker !== undefined); // Every Workforce Lab's roster flow declares the workers, so none there is the Lab not having // opened its inventory, or these pages looking for keys it no longer writes: said below. @@ -768,8 +486,8 @@ export function createLabReader(client: Client): LabReader { const readProjects = async (): Promise> => { const rowsAt = async (scope: "org" | "user", visibility: ProjectVisibility) => { try { - return (await readEveryScopeEntry(client, scope, PROJECTS_PATTERN)) - .map((row) => toProject(row.clientData, visibility)) + return (await client.resource({ scope, pattern: PROJECTS_PATTERN }).listAll({ limit: PAGE_SIZE })) + .map((row) => toProject(row.value, visibility)) .filter((p): p is Project => p !== undefined); } catch (error) { if (describeFailure(error).httpStatus === 404) return []; diff --git a/packages/shift-manager/test/inventory-allowlist.json b/packages/shift-manager/test/inventory-allowlist.json index f1ce836d4e..e7288dcbd3 100644 --- a/packages/shift-manager/test/inventory-allowlist.json +++ b/packages/shift-manager/test/inventory-allowlist.json @@ -1,22 +1,11 @@ [ {"file":"src/lib/reads.ts","symbol":"(file)","kind":"gone"}, - {"file":"src/lib/messages.ts","symbol":"topic","kind":"client import"}, - {"file":"src/lib/projects.ts","symbol":"topic","kind":"client import"}, - {"file":"src/lib/projects.ts","symbol":"viewRef","kind":"client import"}, {"file":"src/lib/reads.ts","symbol":"ClientHttpError","kind":"client import"}, {"file":"src/lib/reads.ts","symbol":"readEveryCollectionPage","kind":"client import"}, {"file":"src/lib/reads.ts","symbol":"read","kind":"flow call"}, - {"file":"src/lib/routines.ts","symbol":"ClientHttpError","kind":"client import"}, {"file":"src/lib/snapshot-subscribe.ts","symbol":"topic","kind":"client import"}, - {"file":"src/lib/usage.ts","symbol":"ClientHttpError","kind":"client import"}, {"file":"src/lib/derive.ts","symbol":"LoadedSnapshot","kind":"type"}, {"file":"src/lib/derive.ts","symbol":"ProjectsView","kind":"type"}, - {"file":"src/lib/mcp-credentials.ts","symbol":"McpServerKey","kind":"type"}, - {"file":"src/lib/mcp-credentials.ts","symbol":"McpKeysRead","kind":"type"}, - {"file":"src/lib/projects.ts","symbol":"WorkstreamObjective","kind":"type"}, - {"file":"src/lib/projects.ts","symbol":"WorkstreamEntry","kind":"type"}, - {"file":"src/lib/projects.ts","symbol":"ProjectRead","kind":"type"}, - {"file":"src/lib/projects.ts","symbol":"ProjectSetup","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"}, @@ -30,10 +19,5 @@ {"file":"src/lib/reads.ts","symbol":"Inventory","kind":"type"}, {"file":"src/lib/reads.ts","symbol":"LabSnapshot","kind":"type"}, {"file":"src/lib/reads.ts","symbol":"PendingSuspension","kind":"type"}, - {"file":"src/lib/reads.ts","symbol":"LabReader","kind":"type"}, - {"file":"src/lib/routines.ts","symbol":"Routine","kind":"type"}, - {"file":"src/lib/usage.ts","symbol":"UsageWindow","kind":"type"}, - {"file":"src/lib/usage.ts","symbol":"HarnessUsage","kind":"type"}, - {"file":"src/lib/usage.ts","symbol":"WorkerSourceUsage","kind":"type"}, - {"file":"src/lib/usage.ts","symbol":"WorkerUsage","kind":"type"} + {"file":"src/lib/reads.ts","symbol":"LabReader","kind":"type"} ] diff --git a/packages/shift-manager/test/inventory-settings.ts b/packages/shift-manager/test/inventory-settings.ts index 37f530d443..6f78a9e57c 100644 --- a/packages/shift-manager/test/inventory-settings.ts +++ b/packages/shift-manager/test/inventory-settings.ts @@ -77,16 +77,48 @@ 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", "ShiftCounts", "ShiftCoordinator"], + "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: "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" }], + "src/lib/failure.ts": [ + { name: "Failure", reason: "react's own ViewReadFailure, the reason useView and useResource give a failed read" }, + { name: "Section", reason: "UI state: a section's value, or the failure its read gave, as a screen draws it" }, + ], + "src/lib/gate.ts": [{ name: "Gate", reason: "UI state: whether the shell is in, refused or not reaching the Lab, computed from the organization read" }], "src/lib/feed-health.ts": ["ReportFeed"], "src/lib/first-run.ts": ["StarterDelegate"], "src/lib/inbox.ts": ["ReviewData"], "src/lib/lab-data.tsx": ["LabData"], "src/lib/messages.ts": ["MessageExchange"], - "src/lib/projects.ts": ["ProjectAddress"], + "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" }, + ], "src/lib/roster.ts": ["RosterRead"], "src/lib/routes.ts": ["ProjectTab", "TaskTab", "TaskGrouping", "Route"], "src/lib/routines.ts": ["RoutineChange"], + "src/lib/shift.ts": [ + { name: "WorkerState", reason: "a worker's status, held tasks and asks, computed from the directory and the Inbox view (moved from derive.ts)" }, + { name: "WorkerStates", reason: "every worker's state, computed once from the directory and the Inbox view (moved from derive.ts)" }, + { name: "ShiftCounts", reason: "counts the screen computes over the worker states (moved from derive.ts)" }, + { name: "ShiftCoordinator", reason: "which worker is the Shift Coordinator, computed from the directory by name (moved from derive.ts)" }, + ], + "src/lib/usage.ts": [ + { name: "HarnessUsage", reason: "the harness usage view's own row, taken from its value (ViewValueOf)" }, + { name: "UsageWindow", reason: "a window of the harness usage view's row, taken from its value (ViewValueOf)" }, + { name: "WorkerUsage", reason: "the worker usage view's own row, taken from its value (ViewValueOf)" }, + { name: "WorkerSourceUsage", reason: "a source of the worker usage view's row, taken from its value (ViewValueOf)" }, + ], + "src/lib/workers.ts": [ + { name: "Worker", reason: "the joined worker (D1): an inventory row named and grouped by workerNames, with its roster entry's harness, or one of the user's own off their roster" }, + { name: "JoinedWorkers", reason: "the directory join's output: every worker and the user's own, assembled from two reads" }, + ], "src/lib/rules.ts": ["StandingRule", "RulesRead", "RuleEditInput", "StandingRulesView"], "src/lib/task.tsx": [ "RunState", "InterruptState", "TaskView", From 69cbf78291080d5267a5a0c868d50de0540b2aec Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 00:07:31 +0000 Subject: [PATCH 03/24] wip(react): pin topicPrefix live paths, held read mode by value, failureOf on internal --- packages/react/src/hooks/useResource.ts | 10 +++--- packages/react/test/internal-subpath.test.ts | 4 +-- packages/react/test/useResource-all.test.ts | 36 ++++++++++++++++++++ 3 files changed, 44 insertions(+), 6 deletions(-) diff --git a/packages/react/src/hooks/useResource.ts b/packages/react/src/hooks/useResource.ts index c0e202fbf3..5e6f0a0ca5 100644 --- a/packages/react/src/hooks/useResource.ts +++ b/packages/react/src/hooks/useResource.ts @@ -273,11 +273,13 @@ export function useResource( // A collection's entries as last read, for this handle read this way, while no other // read is out: a notice that names entries re-reads just those over them (FIX-2625). const how = useMemo(() => ({ all, topicPrefix }), [all, topicPrefix]); - const held = useRef<{ handle: unknown; how: CollectionRead; entries: ScopeEntry[] } | undefined>(undefined); + // Held entries are a baseline only for the same read mode, named by value so the match never rests on `how`'s identity. + const mode = all ? `all:${topicPrefix ?? ""}` : "page"; + const held = useRef<{ handle: unknown; mode: string; entries: ScopeEntry[] } | undefined>(undefined); const reading = useRef(0); const { data, error, cause, refresh } = useFencedRead[] | null>( // `client` too: by `sessionId` there is no handle, and a value one client read is never shown under another. - [handle, scope, key, sessionId, client, how], + [handle, scope, key, sessionId, client, mode], null, `Failed to read "${key}"`, async (stillCurrent, notice) => { @@ -287,7 +289,7 @@ export function useResource( } if (handle === undefined) return null; if (!("list" in handle)) return (await handle.read()).value; - const last = held.current?.handle === handle && held.current.how === how && reading.current === 0 ? held.current.entries : undefined; + const last = held.current?.handle === handle && held.current.mode === mode && reading.current === 0 ? held.current.entries : undefined; reading.current += 1; try { const entries = @@ -296,7 +298,7 @@ export function useResource( ? await handle.listAll({ limit: ENTRY_PAGE, ...(topicPrefix === undefined ? {} : { topicPrefix }) }) : (await handle.list({ limit: ENTRY_PAGE })).items); // Only the read in play is a baseline: one a newer read superseded is older than what's shown. - if (stillCurrent()) held.current = { handle, how, entries }; + if (stillCurrent()) held.current = { handle, mode, entries }; return entries; } catch (error) { if (stillCurrent()) held.current = undefined; diff --git a/packages/react/test/internal-subpath.test.ts b/packages/react/test/internal-subpath.test.ts index 0bf9ab6393..9417a4a1d5 100644 --- a/packages/react/test/internal-subpath.test.ts +++ b/packages/react/test/internal-subpath.test.ts @@ -19,8 +19,8 @@ const manifest = JSON.parse(readFileSync(fileURLToPath(new URL("../package.json" }; describe("@flow-state-dev/react/internal", () => { - it("carries the read fence, the suspension reduction, and the client and fenced read workforce's components use", () => { - expect(Object.keys(internal).sort()).toEqual(["deriveSuspensions", "useClient", "useFencedRead", "useReadFence"]); + it("carries the read fence, the suspension reduction, the client and fenced read workforce's components use, and the words a failed read is shown in", () => { + expect(Object.keys(internal).sort()).toEqual(["deriveSuspensions", "failureOf", "useClient", "useFencedRead", "useReadFence"]); }); it("is gone from the root, with no alias", () => { diff --git a/packages/react/test/useResource-all.test.ts b/packages/react/test/useResource-all.test.ts index 89bc436e06..3ab9ce601a 100644 --- a/packages/react/test/useResource-all.test.ts +++ b/packages/react/test/useResource-all.test.ts @@ -198,6 +198,42 @@ describe("useResource(def, { all: true, topicPrefix })", () => { expect(entryReads).toEqual(["projects/p1/c"]); expect(lists).toHaveLength(listed); }); + + // The live read's path filter is the client's (`liveRead`'s `paths`), not the subscription's, so + // the narrowed root is pinned by which notice with no ids reads the list again. + it("narrows its live paths to the prefix's whole segments: its own project's notice re-reads, the next project's doesn't", async () => { + const stored = new Map([ + ["projects/p1/a", entry("p1a")], + ["projects/p2/a", entry("p2a")] + ]); + const { client, lists, hear } = lab(stored); + const { result } = renderHook(() => useResource(projects, { all: true, topicPrefix: "projects/p1/", client })); + await waitFor(() => expect(keys(result.current.value)).toEqual(["projects/p1/a"])); + const listed = lists.length; + + await hear({ topic: { scope: "org", resource: "projects/p2" }, kind: "resource" }); + expect(lists).toHaveLength(listed); + stored.set("projects/p1/b", entry("p1b")); + await hear({ topic: { scope: "org", resource: "projects/p1" }, kind: "resource" }); + await waitFor(() => expect(keys(result.current.value)).toEqual(["projects/p1/a", "projects/p1/b"])); + expect(lists).toHaveLength(listed + 1); + }); + + it("narrows a prefix that ends mid-segment to the segment above it, so a sibling project's notice is still heard", async () => { + // `projects/p1` (no slash) also matches `projects/p10/...`: the path rule matches by segment, so the root is `projects`. + const stored = new Map([ + ["projects/p1/a", entry("p1a")], + ["projects/p10/a", entry("p10a")], + ["projects/p2/a", entry("p2a")] + ]); + const { client, lists, hear } = lab(stored); + const { result } = renderHook(() => useResource(projects, { all: true, topicPrefix: "projects/p1", client })); + await waitFor(() => expect(keys(result.current.value)).toEqual(["projects/p1/a", "projects/p10/a"])); + const listed = lists.length; + + await hear({ topic: { scope: "org", resource: "projects/p2" }, kind: "resource" }); + await waitFor(() => expect(lists).toHaveLength(listed + 1)); + }); }); describe("useResource's failure and refresh()", () => { From e152d89e70fd88fa77894bda6dda1c6cc61b1479 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 00:25:34 +0000 Subject: [PATCH 04/24] wip: tests onto the directory reads --- .../shift-manager/src/lib/conversation.ts | 25 ++-- packages/shift-manager/src/lib/gate.ts | 19 +-- .../shift-manager/test/answer-follow.test.tsx | 14 +- .../test/ask-card-review.test.tsx | 7 +- packages/shift-manager/test/columns.test.ts | 6 +- .../shift-manager/test/connection.test.tsx | 125 ++++++++++++++---- .../test/conversation-opens-at-end.test.tsx | 2 +- .../conversation-task-pull-request.test.tsx | 2 +- .../test/conversation-tasks-panel.test.tsx | 2 +- .../shift-manager/test/conversation.test.tsx | 8 +- .../test/coordinator-view.test.tsx | 14 +- .../devteam-shift-coordinator-tasks.test.ts | 2 +- packages/shift-manager/test/goal-labs.test.ts | 7 +- .../shift-manager/test/helpers/directory.ts | 70 ++++++++++ .../shift-manager/test/helpers/run-action.ts | 2 +- .../shift-manager/test/inbox-groups.test.tsx | 3 +- .../shift-manager/test/inbox-stale.test.tsx | 37 +++++- packages/shift-manager/test/inbox.test.ts | 12 +- .../shift-manager/test/jump-message.test.tsx | 28 +++- .../test/messages-read-on-notice.test.tsx | 88 ++++++------ .../shift-manager/test/messages-view.test.tsx | 53 ++++---- packages/shift-manager/test/projects.test.tsx | 3 +- packages/shift-manager/test/reads.test.ts | 6 +- .../shift-manager/test/roster-screen.test.tsx | 19 ++- packages/shift-manager/test/roster.test.ts | 122 ++++++++++------- .../shift-manager/test/routines-view.test.tsx | 19 ++- .../shift-manager/test/session-view.test.tsx | 23 +++- .../test/shift-coordinator.test.ts | 6 +- .../test/snapshot-subscribe.test.tsx | 47 ++++--- .../shift-manager/test/task-actions.test.ts | 3 +- .../test/task-card-in-feed.test.tsx | 11 +- .../shift-manager/test/task-screen.test.tsx | 3 +- .../shift-manager/test/task-session.test.tsx | 2 +- .../shift-manager/test/turn-routes.test.ts | 2 +- .../shift-manager/test/usage-views.test.ts | 13 +- packages/shift-manager/test/usage.test.ts | 77 +++++++---- .../test/worker-settings-screen.test.tsx | 9 +- .../test/worker-usage-period.test.tsx | 10 +- 38 files changed, 610 insertions(+), 291 deletions(-) create mode 100644 packages/shift-manager/test/helpers/directory.ts diff --git a/packages/shift-manager/src/lib/conversation.ts b/packages/shift-manager/src/lib/conversation.ts index 97afbc2a9d..6aea69c9cb 100644 --- a/packages/shift-manager/src/lib/conversation.ts +++ b/packages/shift-manager/src/lib/conversation.ts @@ -13,7 +13,7 @@ * a line opened here holds nothing the user hasn't seen. A lapse after the * first read keeps it on screen; only a failed first read shows. */ -import { useCallback, useEffect, useMemo, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { SessionSummary } from "@flow-state-dev/client"; import type { OutputItem } from "@flow-state-dev/core/items"; import { COORDINATOR_FLOW, deriveWorkerSessionId, type ProjectAddressRef } from "@flow-state-dev/workforce/browser"; @@ -79,7 +79,10 @@ interface Derived { */ function useDerivedId(worker: Pick | undefined): Derived { const { client } = useLab(); - const workforce = useWorkforce(); + // The connection decides the organization; its workforce client is the one built over it. + const current = useWorkforce(); + const workforce = useRef(current); + workforce.current = current; const flow = worker?.kind ?? null; const id = worker?.id; const [derived, setDerived] = useState<{ key: string; id: string | null; failure?: Failure } | null>(null); @@ -87,21 +90,21 @@ function useDerivedId(worker: Pick | undefined): Derived useEffect(() => { if (key === null || flow === null || id === undefined) return; let closed = false; - workforce + workforce.current .organization() .then((orgId) => derivedIdOf(`${key}\n${orgId}`, { userId: client.userId, orgId, flow, criteria: { worker: id } })) .then( - (sessionId) => { - if (!closed) setDerived({ key, id: sessionId }); - }, - (error: unknown) => { - if (!closed) setDerived({ key, id: null, failure: describeFailure(error) }); - } - ); + (sessionId) => { + if (!closed) setDerived({ key, id: sessionId }); + }, + (error: unknown) => { + if (!closed) setDerived({ key, id: null, failure: describeFailure(error) }); + }, + ); return () => { closed = true; }; - }, [key, workforce, client.userId, flow, id]); + }, [key, client.userId, flow, id]); if (key === null) return { id: null, failure: undefined }; return derived !== null && derived.key === key ? { id: derived.id, failure: derived.failure } : { id: undefined, failure: undefined }; } diff --git a/packages/shift-manager/src/lib/gate.ts b/packages/shift-manager/src/lib/gate.ts index 6e94854d8c..708004492c 100644 --- a/packages/shift-manager/src/lib/gate.ts +++ b/packages/shift-manager/src/lib/gate.ts @@ -9,7 +9,7 @@ * - anything else (a 5xx, the network) is the Lab not being reached, which * Retry reads again. */ -import { useCallback, useEffect, useState } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import { ROSTER_FLOW } from "@flow-state-dev/workforce/browser"; import { useLab } from "./lab-data"; import { describeFailure, type Failure } from "./failure"; @@ -48,20 +48,23 @@ export function gateOf(userId: string, read: { orgId: unknown } | { error: unkno */ export function useGate(): { gate: Gate; retry: () => void } { const { client } = useLab(); - const workforce = useWorkforce(); - const [read, setRead] = useState<{ workforce: unknown; tries: number; gate: Gate }>({ workforce, tries: 0, gate: { state: "reading" } }); + // The connection decides the read; its workforce client is the one built over it. + const current = useWorkforce(); + const workforce = useRef(current); + workforce.current = current; + const [read, setRead] = useState<{ client: unknown; gate: Gate }>({ client, gate: { state: "reading" } }); const [tries, setTries] = useState(0); useEffect(() => { let closed = false; - workforce.organization().then( - (orgId) => !closed && setRead({ workforce, tries, gate: gateOf(client.userId, { orgId }) }), - (error: unknown) => !closed && setRead({ workforce, tries, gate: gateOf(client.userId, { error }) }), + workforce.current.organization().then( + (orgId) => !closed && setRead({ client, gate: gateOf(client.userId, { orgId }) }), + (error: unknown) => !closed && setRead({ client, gate: gateOf(client.userId, { error }) }), ); return () => { closed = true; }; - }, [client, workforce, tries]); + }, [client, tries]); const retry = useCallback(() => setTries((n) => n + 1), []); // A read for another connection is never this one's answer. - return { gate: read.workforce === workforce ? read.gate : { state: "reading" }, retry }; + return { gate: read.client === client ? read.gate : { state: "reading" }, retry }; } diff --git a/packages/shift-manager/test/answer-follow.test.tsx b/packages/shift-manager/test/answer-follow.test.tsx index 884876b1ad..f8b157f7be 100644 --- a/packages/shift-manager/test/answer-follow.test.tsx +++ b/packages/shift-manager/test/answer-follow.test.tsx @@ -4,15 +4,16 @@ * count and a task's asks read workforce's inbox view, which the server's * suspension notice re-runs once the answer is recorded: a whole-Lab read * after the answer, and another once the run it resumed stops, would be the - * re-read loop this issue removes. The answer marks its session answered - * once, for a conversation on screen to read itself back. + * re-read loop this issue removes. Nor does it mark anything for a + * conversation on screen to read itself back (FIX-2775): the conversation's + * own live feed hears the session's resume. * * The connection's client records each answer sent; the reader counts its reads. */ import { act, cleanup, render, waitFor } from "@testing-library/react"; import { afterEach, describe, expect, it, vi } from "vitest"; import type { InboxHold } from "@flow-state-dev/orchestration/inbox"; -import { LabProvider, useLab, type LabData } from "../src/lib/lab-data"; +import { LabProvider } from "../src/lib/lab-data"; import { useInboxAnswer } from "../src/lib/inbox"; let reads = 0; @@ -30,7 +31,7 @@ vi.mock("../src/lib/connection", () => ({ }), }), })); -vi.mock("../src/lib/workforce", () => ({ useWorkforce: () => ({ watchRoster: () => () => {} }) })); +vi.mock("../src/lib/workforce", () => ({ useWorkforce: () => ({ organization: async () => "acme", watchRoster: () => () => {} }) })); vi.mock("../src/lib/reads", async (importOriginal) => { const real = await importOriginal(); return { @@ -47,10 +48,8 @@ vi.mock("../src/lib/reads", async (importOriginal) => { afterEach(cleanup); -let lab: LabData | undefined; let answer: ReturnType | undefined; function Grab() { - lab = useLab(); answer = useInboxAnswer(); return null; } @@ -66,7 +65,7 @@ const hold: InboxHold = { }; describe("an answer given in Shift Manager", () => { - it("goes through the answer route, reads nothing of the Lab after it, and marks its session answered once", async () => { + it("goes through the answer route, and reads nothing of the Lab after it", async () => { render( @@ -79,6 +78,5 @@ describe("an answer given in Shift Manager", () => { }); expect(answers).toEqual([{ suspensionId: "susp_1", action: "approve" }]); expect(reads).toBe(1); - expect(lab!.answered).toEqual({ sessionId: "s1", count: 1 }); }); }); diff --git a/packages/shift-manager/test/ask-card-review.test.tsx b/packages/shift-manager/test/ask-card-review.test.tsx index 3a67e99932..bf33684991 100644 --- a/packages/shift-manager/test/ask-card-review.test.tsx +++ b/packages/shift-manager/test/ask-card-review.test.tsx @@ -14,8 +14,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { fakeLabClient, reviewHold } from "./helpers/ask-hold"; const lab = fakeLabClient(undefined); -const noteAnswered = vi.fn(); -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"); @@ -23,17 +22,15 @@ const { AskCard } = await import("../src/components/AskCard"); afterEach(() => { cleanup(); lab.answers.splice(0); - noteAnswered.mockClear(); }); describe("Inbox draws a coding run's review with the review card", () => { - it("Accept answers the ask with submit and { verdict: accepted }, and marks its session answered once", async () => { + it("Accept answers the ask with submit and { verdict: accepted }", async () => { render(); expect(await screen.findByText("Ready for review")).toBeTruthy(); fireEvent.click(screen.getByRole("button", { name: "Accept" })); await waitFor(() => expect(lab.answers).toHaveLength(1)); expect(lab.answers).toEqual([{ suspensionId: "susp-1", action: "submit", data: { verdict: "accepted" } }]); - expect(noteAnswered.mock.calls).toEqual([["sess-run"]]); }); it("Ask for changes sends the words as a revision", async () => { diff --git a/packages/shift-manager/test/columns.test.ts b/packages/shift-manager/test/columns.test.ts index cc24bf05b3..b3d8eae66e 100644 --- a/packages/shift-manager/test/columns.test.ts +++ b/packages/shift-manager/test/columns.test.ts @@ -8,8 +8,10 @@ import { describe, expect, it } from "vitest"; import { taskStatusSchema } from "@flow-state-dev/orchestration/tasks"; import { COLUMNS, columnFor, isHeld, isDone } from "../src/lib/columns"; -import { openTasks, workerFor, type LoadedSnapshot, type Roster } from "../src/lib/derive"; -import { toBoardTaskView, toWorker, type BoardTaskView } from "../src/lib/reads"; +import { openTasks, type LoadedSnapshot, type Roster } from "../src/lib/derive"; +import { workerFor } from "../src/lib/shift"; +import { toBoardTaskView, type BoardTaskView } from "../src/lib/reads"; +import { toWorker } from "../src/lib/workers"; /** Where BR-12 puts each shipped status. */ const EXPECTED: Record = { diff --git a/packages/shift-manager/test/connection.test.tsx b/packages/shift-manager/test/connection.test.tsx index bd53357eea..2f2bdde277 100644 --- a/packages/shift-manager/test/connection.test.tsx +++ b/packages/shift-manager/test/connection.test.tsx @@ -4,43 +4,71 @@ * * Swapping the shell for the couldn't-reach page on a later refresh throws * away the route, the open task and anything typed, for a failure the next - * read usually fixes. So once a read has landed, a failed refresh keeps the - * last good snapshot on screen, says the server is gone in a bar above the - * shell, greys the statuses drawn from it and stops their clocks, and reads - * again on its own until one lands. The full-screen page stays for a first - * read, before there is anything to keep. + * read usually fixes. So once in, a read that lapses (R reading the Inbox view + * again, here) keeps the last good answer on screen, says the server is gone + * in a bar above the shell, greys the statuses drawn from it and stops their + * clocks. The snapshot's own read still retries on the client's backoff until + * one lands. The full-screen page stays for the organization read, before + * there is anything to keep (`lib/gate.ts`). * * The bar reads one state for the page: the worst of the snapshot read's and - * the session feeds on screen, so a conversation whose stream has lapsed says - * so even while the snapshot reads fine. + * the reads and session feeds on screen, so a conversation whose stream has + * lapsed says so even while the rest reads fine. * * The reader is swapped for one the test answers, as the roster tests do. */ import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { ClientHttpError } from "@flow-state-dev/client"; import { App } from "../src/App"; import { useReportFeedState, worstFeedState } from "../src/lib/feed-health"; import { LabProvider, useLab } from "../src/lib/lab-data"; -import { inboxSection, toBoardTaskView, toWorker, type LabSnapshot } from "../src/lib/reads"; +import { inboxSection, toBoardTaskView, type LabSnapshot } from "../src/lib/reads"; +import { toWorker } from "../src/lib/workers"; import type { LoadedSnapshot } from "../src/lib/derive"; import type { ConnectionFeedStatus } from "../src/components/flow-state/connection-banner"; /** What the next read answers. */ let answer: () => LabSnapshot; let reads = 0; +/** What the organization read answers: the gate's read. */ +let organization: () => Promise; +let organizationReads = 0; +/** The Inbox view's read lapses: an earlier answer stays drawn, and says why it may be out of date. */ +let viewDown = false; +/** The good read the directory draws: one object, as a read lands once. */ +let drawn: LabSnapshot; // One object, as the provider hands one: a new one each render re-reads the roster on every render. const workforce = { + organization: () => { + organizationReads += 1; + return organization(); + }, roster: async () => [], // The roster watch, reporting one read. watchRoster: (onRoster: (entries: never[]) => void, options?: { onError?: (error: unknown) => void }) => (void Promise.resolve([] as never[]).then(onRoster, options?.onError), () => {}), }; vi.mock("../src/lib/workforce", () => ({ useWorkforce: () => workforce })); -// FIX-2774: Tasks' rows are the inbox view's: here, the view of the good read, while the Lab read comes and goes. +// FIX-2774: Tasks' rows are the inbox view's: here, the view of the good read. A read of it that lapses keeps +// that answer, says it is stale, and tells the page's bar, as `useInbox` does; R reads it again. vi.mock("../src/lib/inbox", async (importOriginal) => { const real = await importOriginal(); const { viewOfSnapshot } = await import("./helpers/inbox-view"); - return { ...real, useInbox: () => ({ section: viewOfSnapshot(lab()), stale: false, refresh: () => {} }) }; + const { useReducer } = await import("react"); + const { useReportFeedState } = await import("../src/lib/feed-health"); + return { + ...real, + useInbox: () => { + const [, redraw] = useReducer((n: number) => n + 1, 0); + useReportFeedState(viewDown ? "lapsed" : "live"); + return { section: viewOfSnapshot(drawn), stale: viewDown, failure: viewDown ? { httpStatus: 503, message: "store offline" } : undefined, refresh: redraw, readAt: startedAt }; + }, + }; +}); +vi.mock("../src/lib/directory-reads", async () => { + const { useFixtureReads } = await import("./helpers/directory"); + return { useDirectoryReads: () => useFixtureReads(() => drawn) }; }); vi.mock("../src/lib/reads", async (importOriginal) => { const real = await importOriginal(); @@ -83,6 +111,10 @@ const down = (): LabSnapshot => ({ unreachable: { httpStatus: 503, message: "sto beforeEach(() => { answer = lab; reads = 0; + organization = async () => "acme"; + organizationReads = 0; + viewDown = false; + drawn = lab(); (window as unknown as { happyDOM: { setViewport(viewport: { width: number; height: number }): void } }).happyDOM.setViewport({ width: 1600, height: 900 }); }); afterEach(() => { @@ -95,14 +127,11 @@ async function openTasks() { render(); await screen.findByTestId("tasks"); } -/** - * R, pressed outside any field: the Lab read again (and the inbox view with - * it, FIX-2774). Tasks' own Retry reads the view now, not the Lab. - */ +/** R, pressed outside any field: the page's reads read again, the Inbox view's among them. */ const retryBoards = () => act(async () => void fireEvent.keyDown(document.body, { key: "r" })); const sleep = (ms: number) => act(() => new Promise((r) => setTimeout(r, ms))); -describe("a refresh that can't reach the Lab after a good read", () => { +describe("a read that can't reach the Lab after a good one", () => { it("keeps the shell, the route and a typed draft, shows the bar, and a good read clears it", async () => { await openTasks(); expect(screen.queryByTestId("connection-banner")).toBeNull(); @@ -111,7 +140,7 @@ describe("a refresh that can't reach the Lab after a good read", () => { const query = (await screen.findByTestId("jump-input")) as HTMLInputElement; fireEvent.change(query, { target: { value: "E-1 half typed" } }); - answer = down; + viewDown = true; await retryBoards(); expect(screen.getByTestId("connection-banner").textContent).toContain("Lost the server"); expect(screen.queryByTestId("unreachable")).toBeNull(); @@ -120,7 +149,7 @@ describe("a refresh that can't reach the Lab after a good read", () => { expect((screen.getByTestId("jump-input") as HTMLInputElement).value).toBe("E-1 half typed"); expect(screen.getByTestId("task-row-title").textContent).toBe("E-1 title"); - answer = lab; + viewDown = false; await retryBoards(); expect(screen.queryByTestId("connection-banner")).toBeNull(); }); @@ -134,7 +163,7 @@ describe("a refresh that can't reach the Lab after a good read", () => { expect(time().textContent).toBe("1m 00s"); expect(screen.getByTestId("task-row-status").className).not.toContain(STALE); - answer = down; + viewDown = true; await retryBoards(); expect(time().className).toContain(STALE); expect(screen.getByTestId("task-row-status").className).toContain(STALE); @@ -142,19 +171,35 @@ describe("a refresh that can't reach the Lab after a good read", () => { await sleep(1_200); expect(time().textContent).toBe("1m 00s"); - answer = lab; + viewDown = false; await retryBoards(); await sleep(1_200); expect(time().className).not.toContain(STALE); expect(time().textContent).toBe("10m"); }); - it("reads again on its own on the client's backoff, 1s after a failure and then 2s after the next, without a click", async () => { - await openTasks(); + it("the snapshot read reads again on its own on the client's backoff, 1s after a failure and then 2s after the next", async () => { + // The connection bar still counts the snapshot's read (FIX-2777 rewires it); nothing on screen reads + // from it, so its refresh is driven here from inside the provider. + let refresh: (() => Promise) | undefined; + let landed = false; + function Probe() { + const lab = useLab(); + refresh = lab.refresh; + landed = lab.snapshot !== undefined; + return null; + } + render( + + + , + ); + // The live read opens once a good read has landed: what a failed refresh hands its retry to. + await waitFor(() => expect(landed).toBe(true)); answer = down; const before = reads; - await retryBoards(); - // The click's read fails, and the live read takes the failure over: it reads at once, which fails too. + await act(async () => void (await refresh!())); + // The refresh's read fails, and the live read takes the failure over: it reads at once, which fails too. await waitFor(() => expect(reads).toBe(before + 2)); const after = reads; await sleep(700); @@ -163,21 +208,45 @@ describe("a refresh that can't reach the Lab after a good read", () => { answer = lab; await sleep(1_500); expect(reads).toBe(after + 1); - await waitFor(() => expect(screen.queryByTestId("connection-banner")).toBeNull(), { timeout: 1_500 }); - expect(reads).toBe(after + 2); + await waitFor(() => expect(reads).toBe(after + 2), { timeout: 1_500 }); // Back: nothing reads again on its own. await sleep(2_500); expect(reads).toBe(after + 2); }, 15_000); - it("a first read that fails still gets the full-screen page, which reads again on its own", async () => { - answer = down; + it("an organization read that can't reach the Lab gets the full-screen page, which reads again on its own", async () => { + organization = async () => { + throw new ClientHttpError("Service Unavailable", { status: 503, body: { error: "store offline" } }); + }; (window as unknown as { happyDOM: { setURL(url: string): void } }).happyDOM.setURL("http://lab.local/tasks"); render(); expect((await screen.findByTestId("unreachable-message")).textContent).toBe("503 · store offline"); expect(screen.queryByTestId("shell")).toBeNull(); - answer = lab; + organization = async () => "acme"; await screen.findByTestId("tasks", undefined, { timeout: 3_000 }); + expect(organizationReads).toBe(2); + }); + + it("an organization read the Lab refuses gets the refusal page in today's words, and nothing else is read", async () => { + organization = async () => { + throw new ClientHttpError("Forbidden", { status: 403, body: { error: "no verified organization" } }); + }; + render(); + const refused = await screen.findByTestId("refusal"); + expect(refused.textContent).toContain("This Lab won't let Shift Manager in"); + expect(refused.textContent).toContain("403 · no verified organization"); + expect(refused.textContent).toContain("the request carried no verified organization"); + expect(screen.queryByTestId("shell")).toBeNull(); + }); + + it("a Lab that serves no roster flow is refused, naming the organization read it couldn't make", async () => { + organization = async () => { + throw new ClientHttpError("Not Found", { status: 404, body: { error: 'Unknown flow "workforce-roster"' } }); + }; + render(); + const refused = await screen.findByTestId("refusal"); + expect(refused.textContent).toContain("The Lab names no organization for u_test: it serves no roster flow to ask it under."); + expect(refused.textContent).toContain("doesn't say which one you're in"); }); }); diff --git a/packages/shift-manager/test/conversation-opens-at-end.test.tsx b/packages/shift-manager/test/conversation-opens-at-end.test.tsx index 1582b67394..d093b5d8c1 100644 --- a/packages/shift-manager/test/conversation-opens-at-end.test.tsx +++ b/packages/shift-manager/test/conversation-opens-at-end.test.tsx @@ -8,7 +8,7 @@ import { act, cleanup, render, screen } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { Conversation } from "../src/components/Conversation"; -import { toWorker } from "../src/lib/reads"; +import { toWorker } from "../src/lib/workers"; vi.mock("../src/lib/lab-data", () => ({ useLab: () => ({ client: { userId: "alice" }, refresh: async () => undefined, answered: undefined }), diff --git a/packages/shift-manager/test/conversation-task-pull-request.test.tsx b/packages/shift-manager/test/conversation-task-pull-request.test.tsx index d207869e72..99468f2ec2 100644 --- a/packages/shift-manager/test/conversation-task-pull-request.test.tsx +++ b/packages/shift-manager/test/conversation-task-pull-request.test.tsx @@ -10,7 +10,7 @@ import { act, cleanup, render, screen } from "@testing-library/react"; import { afterEach, describe, expect, it, vi } from "vitest"; import { TasksPanel } from "../src/components/TasksPanel"; import { pullRequestsWaitedOn, type ConversationTask } from "../src/lib/conversation-tasks"; -import { toWorker } from "../src/lib/reads"; +import { toWorker } from "../src/lib/workers"; const URL_7 = "https://github.com/acme/app/pull/7"; diff --git a/packages/shift-manager/test/conversation-tasks-panel.test.tsx b/packages/shift-manager/test/conversation-tasks-panel.test.tsx index 8e46129c65..1b287082d5 100644 --- a/packages/shift-manager/test/conversation-tasks-panel.test.tsx +++ b/packages/shift-manager/test/conversation-tasks-panel.test.tsx @@ -16,7 +16,7 @@ import { TasksPanel } from "../src/components/TasksPanel"; /** The view's own timer where push can miss a change: `useView`'s default. */ const VIEW_POLL_MS = 3_000; -import { toWorker } from "../src/lib/reads"; +import { toWorker } from "../src/lib/workers"; type StoredTask = { id: string; goal: string; title?: string; status: string; assignee?: string; attempts: number }; let rows: StoredTask[] = []; diff --git a/packages/shift-manager/test/conversation.test.tsx b/packages/shift-manager/test/conversation.test.tsx index 0a4af42187..a9be7cd132 100644 --- a/packages/shift-manager/test/conversation.test.tsx +++ b/packages/shift-manager/test/conversation.test.tsx @@ -26,7 +26,7 @@ const lab = { snapshot: { orgId: "org_1", sessions: [], inventory: { ok: true, value: { workers: [] } } }, }; const upload = vi.fn(); -const workforce = { ensureWorkerSession, upload }; +const workforce = { organization: async () => "org_1", ensureWorkerSession, upload }; vi.mock("../src/lib/lab-data", () => ({ useLab: () => lab })); vi.mock("../src/lib/workforce", () => ({ useWorkforce: () => workforce })); /** @@ -440,11 +440,13 @@ describe("sending", () => { expect(read).toHaveBeenCalledTimes(1); }); - it("reads the Lab again and shows the reason when the door refuses, keeping the line", async () => { + // FIX-2775: what a turn changes elsewhere reaches each screen through that read's own notices, so a send + // reads nothing of the Lab after it, refused or not. + it("shows the reason when the door refuses, keeping the line, and reads nothing of the Lab after it", async () => { sendTurn.mockRejectedValue(new TurnNotDelivered("refused", "no thanks")); drawn([session(s1)]); await send("nope"); - expect(lab.refresh).toHaveBeenCalled(); + expect(lab.refresh).not.toHaveBeenCalled(); expect(screen.getByTestId("rev-composer-error").textContent).toContain("no thanks"); expect((screen.getByTestId("rev-composer-input") as HTMLInputElement).value).toBe("nope"); }); diff --git a/packages/shift-manager/test/coordinator-view.test.tsx b/packages/shift-manager/test/coordinator-view.test.tsx index d6da760425..841b82f2ce 100644 --- a/packages/shift-manager/test/coordinator-view.test.tsx +++ b/packages/shift-manager/test/coordinator-view.test.tsx @@ -9,14 +9,18 @@ * changes nothing), BR-29 (a `coordinator-route` record is never drawn as a * line), and BR-20's "under the delegate's name". */ -import { act, cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { act, cleanup, fireEvent, render as draw, screen } from "@testing-library/react"; +import type { ReactElement } from "react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { DataItem } from "@flow-state-dev/core/items"; import { DelegatesPanel } from "../src/components/DelegatesPanel"; +import { DirectoryProvider } from "../src/lib/directory"; + +const render = (ui: ReactElement) => draw(ui, { wrapper: DirectoryProvider }); import { CoordinatorRoute } from "../src/components/CoordinatorRoute"; import { shiftManagerRenderers } from "../src/components/ToolLine"; import { knownWorkers, senderOf } from "../src/lib/conversation"; -import { toWorker } from "../src/lib/reads"; +import { toWorker } from "../src/lib/workers"; let listed: Array<{ worker: string; note?: string }> = []; const calls: string[] = []; @@ -29,6 +33,11 @@ const changeList = (next: Array<{ worker: string; note?: string }>) => { for (const heard of [...changed]) heard(); }; +// FIX-2775: the directory, holding the page's one roster watch: nothing else read. +vi.mock("../src/lib/directory-reads", async () => { + const { useFixtureReads } = await import("./helpers/directory"); + return { useDirectoryReads: () => useFixtureReads(() => undefined) }; +}); // One connection and one workforce client, as the app memoizes them per Lab. vi.mock("../src/lib/lab-data", () => { const lab = { client: { userId: "alice" } }; @@ -36,6 +45,7 @@ vi.mock("../src/lib/lab-data", () => { }); vi.mock("../src/lib/workforce", () => { const workforce = { + organization: async () => "acme", // The roster watch: reports one read, and each roster a test tells it of. watchRoster(onRoster: (entries: unknown[]) => void) { rosterViews.add(onRoster); diff --git a/packages/shift-manager/test/devteam-shift-coordinator-tasks.test.ts b/packages/shift-manager/test/devteam-shift-coordinator-tasks.test.ts index ecc8e67303..096ccb5f18 100644 --- a/packages/shift-manager/test/devteam-shift-coordinator-tasks.test.ts +++ b/packages/shift-manager/test/devteam-shift-coordinator-tasks.test.ts @@ -32,7 +32,7 @@ import { encodeUserSegment } from "@flow-state-dev/core/types"; import { createTaskToolsCapability } from "@flow-state-dev/orchestration"; import { LIST_TASKS_ACTION } from "../src/lib/conversation-tasks"; import { taskActionName } from "@flow-state-dev/orchestration/inbox"; -import { CONVERSATION_BOARD_COLLECTION } from "../src/lib/reads"; +import { CONVERSATION_BOARD_COLLECTION } from "../src/lib/boards"; import { selectHarness } from "../teams/devteam/harness.mts"; import { LAB_ORG_ID, LAB_USER_ID, openLab, type Lab } from "../teams/devteam/host.mts"; import { harnessStub, type HarnessStub, type HarnessStubOptions, type StubRun } from "@flow-state-dev/harness-manager"; diff --git a/packages/shift-manager/test/goal-labs.test.ts b/packages/shift-manager/test/goal-labs.test.ts index 038967f8ed..c81e482935 100644 --- a/packages/shift-manager/test/goal-labs.test.ts +++ b/packages/shift-manager/test/goal-labs.test.ts @@ -15,8 +15,11 @@ 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 { collectionOfBoard, createLabReader, GENERAL_TEAM, type Ask, type BoardTaskView } from "../src/lib/reads"; -import { teamsOf, type LoadedSnapshot } from "../src/lib/derive"; +import { createLabReader, type Ask, type BoardTaskView } from "../src/lib/reads"; +import { collectionOfBoard } from "../src/lib/boards"; +import { GENERAL_TEAM } from "../src/lib/workers"; +import { type LoadedSnapshot } from "../src/lib/derive"; +import { teamsOf } from "../src/lib/shift"; import type { OutputItem } from "@flow-state-dev/core/items"; import { followRequest, readSessionItems, readRunFlow } from "./helpers/session-reads"; import { taskItems } from "../src/lib/task-items"; diff --git a/packages/shift-manager/test/helpers/directory.ts b/packages/shift-manager/test/helpers/directory.ts new file mode 100644 index 0000000000..476d4afed1 --- /dev/null +++ b/packages/shift-manager/test/helpers/directory.ts @@ -0,0 +1,70 @@ +/** + * The directory's reads for a fixture snapshot, for screen tests that draw a + * fixed Lab: the inventory's workers, the listed sessions and the projects the + * snapshot holds, as `useDirectoryReads` would hand them over. A screen test + * mocks `src/lib/directory-reads` with {@link useFixtureReads}, keeping the + * real roster watch (`useRoster`), so the directory's join, the gate and + * every screen run as they do over the Lab. + * + * Each fixture reads as the same objects every render, as the real hooks + * hold their values; a refresh draws whatever the fixture holds by then. + */ +import { useReducer } from "react"; +import type { DirectoryReads } from "../../src/lib/directory-reads"; +import type { RosterRead } from "../../src/lib/roster"; +import type { LabSnapshot } from "../../src/lib/reads"; +import { useRoster } from "../../src/lib/roster"; + +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 { + const key = snapshot ?? held; + 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) => + section === undefined + ? { rows: undefined, failure: undefined, refresh } + : section.ok + ? { rows: section.value, failure: undefined, refresh } + : { rows: 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), + 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: [] }), + }, + }; + held.set(key, fixed); + return fixed; +} + +/** + * `useDirectoryReads` over the fixture `current()` returns: its reads, beside + * the real roster watch. A refresh redraws, so a test that changed the + * fixture sees it after the screen's Retry or R, as it would after a read. + */ +export function useFixtureReads(current: () => LabSnapshot | undefined): DirectoryReads { + const [, redraw] = useReducer((n: number) => n + 1, 0); + const roster = useRoster(); + return { ...readsOfSnapshot(current(), redraw), roster }; +} + +/** A roster with nobody on it: one object, as a read that landed holds one. */ +const NOBODY: RosterRead = { entries: [] }; + +/** + * `useDirectoryReads` over the fixture `current()` returns, with a fixed + * roster read in place of the watch: for a component test whose workforce + * stand-in follows no roster. + */ +export function useFixedReads(current: () => LabSnapshot | undefined, roster: RosterRead = NOBODY): DirectoryReads { + const [, redraw] = useReducer((n: number) => n + 1, 0); + return { ...readsOfSnapshot(current(), redraw), roster }; +} diff --git a/packages/shift-manager/test/helpers/run-action.ts b/packages/shift-manager/test/helpers/run-action.ts index 1f62246327..a41e680ecb 100644 --- a/packages/shift-manager/test/helpers/run-action.ts +++ b/packages/shift-manager/test/helpers/run-action.ts @@ -12,7 +12,7 @@ import { ClientHttpError } from "@flow-state-dev/client"; import type { Client, RequestResult, SentRequest } from "@flow-state-dev/client"; import { newSessionId } from "../../src/lib/ids"; -import { describeFailure } from "../../src/lib/reads"; +import { describeFailure } from "../../src/lib/failure"; /** * An action the Lab answered with a refusal and its reason: a request that diff --git a/packages/shift-manager/test/inbox-groups.test.tsx b/packages/shift-manager/test/inbox-groups.test.tsx index a89f5913c1..b168778eae 100644 --- a/packages/shift-manager/test/inbox-groups.test.tsx +++ b/packages/shift-manager/test/inbox-groups.test.tsx @@ -11,7 +11,6 @@ import { cleanup, render, screen, within } from "@testing-library/react"; import { afterEach, describe, expect, it, vi } from "vitest"; import { inboxItems, taskActionName } from "@flow-state-dev/orchestration/inbox"; import { GAPS } from "../src/gaps"; -import type { LoadedSnapshot } from "../src/lib/derive"; import type { InboxAsk, InboxViewValue } from "../src/lib/inbox"; import { Inbox } from "../src/surfaces/Inbox"; @@ -72,7 +71,7 @@ const reports: Asked[] = [ ]; const approval: Asked = { id: "sp4", workerId: "shift-coordinator", sessionId: "s_coord", title: "Fire eng.coder?", message: "It has been idle a week.", since: 3 }; -const screenOf = (itemId: string | null) => ; +const screenOf = (itemId: string | null) => ; describe("an untitled ask in a worker's group", () => { // Its heading is already what it asks: the line under it would say it twice. diff --git a/packages/shift-manager/test/inbox-stale.test.tsx b/packages/shift-manager/test/inbox-stale.test.tsx index eb494bee86..ffca714494 100644 --- a/packages/shift-manager/test/inbox-stale.test.tsx +++ b/packages/shift-manager/test/inbox-stale.test.tsx @@ -7,12 +7,12 @@ * * `useView` is replaced by a stand-in whose answer each step sets. */ -import { act, cleanup, render, screen } from "@testing-library/react"; +import { act, cleanup, render, renderHook, screen } from "@testing-library/react"; import { afterEach, describe, expect, it, vi } from "vitest"; import type { ConnectionFeedStatus } from "../src/components/flow-state/connection-banner"; import { GAPS } from "../src/gaps"; import { FeedHealthContext } from "../src/lib/feed-health"; -import type { LoadedSnapshot } from "../src/lib/derive"; +import { useInbox } from "../src/lib/inbox"; import { Inbox } from "../src/surfaces/Inbox"; type Read = { value?: unknown; stale: boolean; failure?: { message: string; httpStatus?: number }; refresh: () => void }; @@ -38,7 +38,7 @@ describe("an Inbox whose refresh failed after a good read", () => { const report = (_key: string, state: ConnectionFeedStatus | null) => void reported.push(state); const screenOf = () => ( - + ); @@ -65,3 +65,34 @@ describe("an Inbox whose refresh failed after a good read", () => { expect(reported.at(-1)).toBe("live"); }); }); + +// FIX-2775: *as of* says when the summary's reads last landed: the view's answer, not a whole-Lab read. +describe("when the inbox view's answer last landed", () => { + it("is unset before an answer, set when one lands, moves when the next does, and stays put while a read fails", () => { + const at = (ms: number) => vi.setSystemTime(ms); + vi.useFakeTimers({ toFake: ["Date"] }); + try { + read = { stale: false, refresh }; + const hook = renderHook(() => useInbox()); + expect(hook.result.current.readAt).toBeUndefined(); + + at(1_000); + read = { value: EMPTY, stale: false, refresh }; + hook.rerender(); + expect(hook.result.current.readAt).toBe(1_000); + + at(5_000); + read = { value: { items: [], tasks: [] }, stale: false, refresh }; + hook.rerender(); + expect(hook.result.current.readAt).toBe(5_000); + + // A failed read keeps the last answer, so *as of* keeps its time. + at(9_000); + read = { ...read, stale: true, failure: { message: "offline" } }; + hook.rerender(); + expect(hook.result.current.readAt).toBe(5_000); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/packages/shift-manager/test/inbox.test.ts b/packages/shift-manager/test/inbox.test.ts index dde5f9bcb3..ac43008e1a 100644 --- a/packages/shift-manager/test/inbox.test.ts +++ b/packages/shift-manager/test/inbox.test.ts @@ -14,16 +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 { - CONVERSATION_BOARD_COLLECTION, - conversationBoardRef, - conversationOfTopic, - createLabReader, - inboxSection, - toBoardTaskView, - type BoardTaskView, - type LabSnapshot, -} from "../src/lib/reads"; +import { conversationOfTopic, createLabReader, inboxSection, toBoardTaskView, type BoardTaskView, type LabSnapshot } from "../src/lib/reads"; +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"; import { eventually, serveLab, type ServedLab } from "./helpers/serve-lab"; diff --git a/packages/shift-manager/test/jump-message.test.tsx b/packages/shift-manager/test/jump-message.test.tsx index ddc18965a9..e36d220dc4 100644 --- a/packages/shift-manager/test/jump-message.test.tsx +++ b/packages/shift-manager/test/jump-message.test.tsx @@ -5,7 +5,8 @@ * composer, which sends it as if typed there, so the feed follows it and a * failure shows in the composer. A palette with no one to send to stays open. */ -import { act, cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { act, cleanup, fireEvent, render as draw, screen } from "@testing-library/react"; +import type { ReactElement } from "react"; import { afterEach, describe, expect, it, vi } from "vitest"; import { TurnComposer } from "../src/components/TurnComposer"; import { TurnNotDelivered } from "../src/lib/deliver"; @@ -13,6 +14,19 @@ import type { LoadedSnapshot } from "../src/lib/derive"; import { clearHandedLine, handToShiftCoordinator, useHandedLine } from "../src/lib/outbox"; import { GAPS as gaps } from "../src/gaps"; import { JumpTo } from "../src/surfaces/JumpTo"; +import { DirectoryProvider } from "../src/lib/directory"; + +// FIX-2775: Jump to finds its workers and projects in the page's directory: here, the case's snapshot. +let drawn: LoadedSnapshot | undefined; +vi.mock("../src/lib/lab-data", () => { + const lab = { client: {} }; + return { useLab: () => lab }; +}); +vi.mock("../src/lib/directory-reads", async () => { + const { useFixedReads } = await import("./helpers/directory"); + return { useDirectoryReads: () => useFixedReads(() => drawn) }; +}); +const render = (ui: ReactElement) => draw(ui, { wrapper: DirectoryProvider }); const withWorkers = (workers: unknown[]) => ({ @@ -41,14 +55,16 @@ function Composer({ send, blocked = null }: { send: (message: string) => Promise describe("`> ` in Jump to messages the Shift Coordinator", () => { it("opens already in message mode when seeded with the prefix (Shift+⌘K)", () => { - render(); + drawn = snapshot; + render(); expect(screen.getByTestId("jump-message")).toBeTruthy(); expect(screen.queryAllByTestId("jump-result")).toHaveLength(0); }); it("switches off the results, then hands the text after the prefix over and closes", () => { const onClose = vi.fn(); - render(); + drawn = snapshot; + render(); type("> ship the release"); expect(screen.getByTestId("jump-message")).toBeTruthy(); expect(screen.queryAllByTestId("jump-result")).toHaveLength(0); @@ -63,7 +79,8 @@ describe("`> ` in Jump to messages the Shift Coordinator", () => { it("stays open with the reason when there is no Coordinator, and hands nothing over", () => { const onClose = vi.fn(); - render(); + drawn = withWorkers([]); + render(); type("> hello"); enter(); expect(screen.getByTestId("jump-message-failure")).toBeTruthy(); @@ -73,7 +90,8 @@ describe("`> ` in Jump to messages the Shift Coordinator", () => { }); it("a plain query still searches, and a bare `>` hands nothing over", () => { - render( undefined} />); + drawn = snapshot; + render( undefined} />); type("chief"); expect(screen.queryByTestId("jump-message")).toBeNull(); type("> "); diff --git a/packages/shift-manager/test/messages-read-on-notice.test.tsx b/packages/shift-manager/test/messages-read-on-notice.test.tsx index 4d21b6f204..b7b3fb39c4 100644 --- a/packages/shift-manager/test/messages-read-on-notice.test.tsx +++ b/packages/shift-manager/test/messages-read-on-notice.test.tsx @@ -1,23 +1,23 @@ // @vitest-environment happy-dom /** - * The message log reads on a change, not every 5 s: when the view opens, - * again on a notice of a message under the user's scope (`workforce/messages`) - * and on each Lab read (`readAt`), and on nothing else while push covers the - * page. Wherever push can miss a change, the subscription keeps the old 5 s - * pace. A failed later read keeps the last messages; only a failed first read - * shows, and a Lab that declares no log (404) reads as none. + * The message log reads on a change, not on a clock (FIX-2775): read whole when + * the view opens through react's `useResource`, and then only on a notice of a + * message under the user's scope (`workforce/messages`). A notice that names a + * new message reads that one entry, never the whole log again; one that names + * none reads it whole. Nothing reads it on a Lab read. A failed later read + * keeps the last messages; only a failed first read shows, and a Lab that + * declares no log (404) reads as none. * - * The client's own live read rides a subscription the test drives. + * The client's direct read and its subscription are the test's. */ import { cleanup, render, waitFor } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { ClientHttpError, type WireNotice, type WireTopic } from "@flow-state-dev/client"; -import { liveRead } from "@flow-state-dev/client/internal"; -type Opened = { topics: readonly WireTopic[]; pollIntervalMs?: number; onChange: (notice: WireNotice | null) => void; closed: boolean }; +type Opened = { topics: readonly WireTopic[]; onChange: (notice: WireNotice | null) => void; closed: boolean }; const opened: Opened[] = []; -const subscribe = (topics: readonly WireTopic[], options: { onChange: (notice: WireNotice | null) => void; pollIntervalMs?: number }) => { - const entry: Opened = { topics, pollIntervalMs: options.pollIntervalMs, onChange: options.onChange, closed: false }; +const 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) }; }; @@ -37,33 +37,43 @@ const message = (id: string, at: number) => ({ hop: 1, status: "delivered", }); +const keyOf = (id: string) => `workforce/messages/${id}`; let logged = [message("msg_1", 1)]; let failWith: Error | undefined; let logReads = 0; -const client = { - userId: "u_1", - resource: () => ({ - list: async () => { - logReads += 1; +const entryReads: string[] = []; +const handle = { + scope: "user", + key: "workforce/messages/*", + list: async () => ({ items: [] }), + listAll: async () => { + logReads += 1; + if (failWith !== undefined) throw failWith; + return logged.map((m) => ({ topic: m.id, storageKey: keyOf(m.id), value: m, version: 1 })); + }, + entry: (storageKey: string) => ({ + read: async () => { + entryReads.push(storageKey); if (failWith !== undefined) throw failWith; - return { items: logged.map((m) => ({ topic: m.id, storageKey: `workforce/messages/${m.id}`, value: m })) }; + const found = logged.find((m) => keyOf(m.id) === storageKey); + return { value: found ?? null, version: 1 }; }, }), - live: (topics: readonly WireTopic[], options: Parameters[2]) => liveRead(subscribe as never, topics, options), }; +const client = { userId: "u_1", resource: () => handle, subscribe }; vi.mock("../src/lib/lab-data", () => ({ useLab: () => ({ client }) })); import { useMessages } from "../src/lib/messages"; type Shown = ReturnType; const shown: Shown[] = []; -function Probe({ readAt }: { readAt: number }) { - shown.push(useMessages(readAt)); +function Probe() { + shown.push(useMessages()); return null; } const ids = () => shown.at(-1)?.rows?.map((m) => m.id); const settle = () => new Promise((r) => setTimeout(r, 50)); -const resource = (path: string): WireNotice => ({ topic: { scope: "user", resource: path }, kind: "resource" }); +const resource = (path: string, named?: string[]): WireNotice => ({ topic: { scope: "user", resource: path }, kind: "resource", ...(named === undefined ? {} : { ids: named }) }); beforeEach(() => { opened.splice(0); @@ -71,6 +81,7 @@ beforeEach(() => { logged = [message("msg_1", 1)]; failWith = undefined; logReads = 0; + entryReads.splice(0); }); afterEach(() => { cleanup(); @@ -78,45 +89,48 @@ afterEach(() => { }); describe("the message log", () => { - it("reads on open, then only on a notice of a message under the user's scope and on a Lab read; at the old pace where push can miss one", async () => { - vi.useFakeTimers({ shouldAdvanceTime: true }); - const view = render(); + it("reads whole on open, then only on a notice under the user's messages: a new message is one entry read", async () => { + render(); await waitFor(() => expect(ids()).toEqual(["msg_1"])); + const sub = opened.find((o) => !o.closed); + expect(sub?.topics).toEqual([{ scope: "user" }]); - // Push covers the page: nothing on a clock, and nothing for another resource of the user's. - await vi.advanceTimersByTimeAsync(12_000); + // Another resource of the user's: nothing is read. hear(resource("lab-pins")); hear(resource("workforce/workers/eng")); hear(resource("workforce/message-chains/c1")); await settle(); expect(logReads).toBe(1); - const sub = opened.find((o) => !o.closed); - expect(sub?.topics).toEqual([{ scope: "user" }]); - expect(sub?.pollIntervalMs).toBe(5_000); + expect(entryReads).toEqual([]); + // A new message, named: that one entry is read and placed, and the log isn't listed again. logged = [message("msg_1", 1), message("msg_2", 2)]; - hear(resource("workforce/messages/msg_2")); + hear(resource("workforce/messages", [keyOf("msg_2")])); await waitFor(() => expect(ids()).toEqual(["msg_1", "msg_2"])); - expect(logReads).toBe(2); + expect(entryReads).toEqual([keyOf("msg_2")]); + expect(logReads).toBe(1); - view.rerender(); - await waitFor(() => expect(logReads).toBe(3)); + // A notice that names nothing under the log reads it whole. + logged = [...logged, message("msg_3", 3)]; + hear(resource("workforce/messages")); + await waitFor(() => expect(ids()).toEqual(["msg_1", "msg_2", "msg_3"])); + expect(logReads).toBe(2); }); it("keeps the last messages when a later read fails; only a failed first read shows", async () => { failWith = new Error("store offline"); - render(); + render(); await waitFor(() => expect(shown.at(-1)?.failure).toBeDefined()); expect(shown.at(-1)?.rows).toBeUndefined(); failWith = undefined; - hear(resource("workforce/messages/msg_1")); + hear(resource("workforce/messages")); await waitFor(() => expect(ids()).toEqual(["msg_1"])); expect(shown.at(-1)?.failure).toBeUndefined(); failWith = new Error("store offline"); const before = logReads; - hear(resource("workforce/messages/msg_1")); + hear(resource("workforce/messages")); await waitFor(() => expect(logReads).toBe(before + 1)); await settle(); expect(ids()).toEqual(["msg_1"]); @@ -125,7 +139,7 @@ describe("the message log", () => { it("reads as none, not a failure, where no flow of the Lab declares the log", async () => { failWith = new ClientHttpError("Request failed (404) Not Found", { status: 404, body: { error: "unknown_resource" } }); - render(); + render(); await waitFor(() => expect(shown.at(-1)?.rows).toBeNull()); expect(shown.at(-1)?.failure).toBeUndefined(); }); diff --git a/packages/shift-manager/test/messages-view.test.tsx b/packages/shift-manager/test/messages-view.test.tsx index 015cb0f17f..d47a8c8c0b 100644 --- a/packages/shift-manager/test/messages-view.test.tsx +++ b/packages/shift-manager/test/messages-view.test.tsx @@ -3,21 +3,15 @@ import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { ClientHttpError } from "@flow-state-dev/client"; -import { liveRead } from "@flow-state-dev/client/internal"; import type { ToolOutputItem } from "@flow-state-dev/core/items"; -import type { LoadedSnapshot } from "../src/lib/derive"; import { firstLine, exchangesOf, toMessages, type WorkerMessageResourceState } from "../src/lib/messages"; import { parseRoute, pathFor } from "../src/lib/routes"; -const readPages = vi.fn(); -vi.mock("@flow-state-dev/client", async (original) => ({ - ...(await original()), - readEveryCollectionPage: (...a: unknown[]) => readPages(...a), -})); -const resource = vi.fn((def: { scope: string; pattern?: string }) => ({ ...def, list: vi.fn() })); -// The client's own live read, over a subscription that hears nothing: each view reads once on open. -const live = (topics: Parameters[1], options: Parameters[2]) => liveRead(() => ({ close: () => {} }), topics, options); -const lab = { client: { userId: "u_1", resources: {}, resource, live }, refresh: vi.fn() }; +// FIX-2775: the log is read whole through react's `useResource`, by `listAll()` on the client's direct read. +const readAll = vi.fn(); +const resource = vi.fn((def: { scope: string; pattern?: string }) => ({ ...def, list: vi.fn(), listAll: (...a: unknown[]) => readAll(...a), entry: vi.fn() })); +// A subscription that hears nothing: each view reads once on open. +const lab = { client: { userId: "u_1", resources: {}, resource, subscribe: () => ({ close: () => {} }) }, refresh: vi.fn() }; vi.mock("../src/lib/lab-data", () => ({ useLab: () => lab })); import { Messages } from "../src/surfaces/Messages"; @@ -39,11 +33,12 @@ const ask = row({ id: "msg_a", from: "researcher", to: "coordinator", at: 1_000, const answer = row({ id: "msg_b", from: "coordinator", to: "researcher", at: 3_000, exchange: "msg_a", inReplyTo: "msg_a", text: "BLUE-HERON", hop: 2 }); const other = row({ id: "msg_c", from: "helper-a", to: "helper-b", at: 2_000, status: "refused", reason: "dispatch-rejected: down" }); -// FIX-2624: the user holds no session at all; the log is read by user scope. -const snapshot = { sessions: [], readAt: 1 } as unknown as LoadedSnapshot; +/** 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 })); beforeEach(() => { - readPages.mockReset(); + readAll.mockReset(); resource.mockClear(); window.history.replaceState(null, "", "/messages"); }); @@ -57,7 +52,7 @@ describe("the message log, as exchanges", () => { }); it("leaves out a row that isn't a message, rather than drawing half of one", () => { - expect(toMessages([{ clientData: ask }, { clientData: { id: "x" } }, {}]).map((r) => r.id)).toEqual(["msg_a"]); + expect(toMessages([ask, { id: "x" }, undefined]).map((r) => r.id)).toEqual(["msg_a"]); }); it("shows a message by its first line", () => { @@ -67,10 +62,12 @@ describe("the message log, as exchanges", () => { describe("the Messages view", () => { it("lists every message with both sides, read by user scope with no session, and opens either side's session", async () => { - readPages.mockResolvedValue([ask, answer, other].map((r) => ({ topic: `workforce/messages/${r.id}`, clientData: r }))); - render(); + readAll.mockResolvedValue(entries([ask, answer, other])); + render(); const lines = await screen.findAllByTestId("message"); - expect(resource).toHaveBeenCalledWith({ scope: "user", pattern: "workforce/messages/*" }); + expect(resource).toHaveBeenCalledWith(expect.objectContaining({ scope: "user", pattern: "workforce/messages/*" }), undefined); + // Every page, not the first: the log is read whole. + expect(readAll).toHaveBeenCalledTimes(1); expect(lines.map((l) => `${l.getAttribute("data-from")}>${l.getAttribute("data-to")}`)).toEqual([ "coordinator>researcher", "researcher>coordinator", @@ -88,8 +85,8 @@ describe("the Messages view", () => { it("says a message is on its way until its recipient takes it, and when it couldn't be delivered", async () => { const onItsWay = row({ id: "msg_d", from: "researcher", to: "helper-a", at: 4_000, status: "unconfirmed" }); const gaveUp = row({ id: "msg_e", from: "researcher", to: "helper-b", at: 5_000, status: "undeliverable", reason: "it couldn't be delivered within 1440 minutes" }); - readPages.mockResolvedValue([onItsWay, gaveUp].map((r) => ({ topic: `workforce/messages/${r.id}`, clientData: r }))); - render(); + readAll.mockResolvedValue(entries([onItsWay, gaveUp])); + render(); const lines = await screen.findAllByTestId("message"); const status = (id: string) => within(lines.find((l) => l.getAttribute("data-message-id") === id)!).getByTestId("message-status").textContent; expect(status("msg_d")).toBe("on its way"); @@ -101,8 +98,8 @@ describe("the Messages view", () => { const onPerson = row({ id: "msg_g", from: "researcher", to: "helper-b", at: 7_000, status: "unconfirmed", replyRequested: true, queuedBehind: "user" }); const answered = row({ id: "msg_h", from: "researcher", to: "coordinator", at: 8_000, replyRequested: true, deadlineAt: 68_000, answeredBy: "msg_x" }); const late = row({ id: "msg_i", from: "researcher", to: "coordinator", at: 9_000, replyRequested: true, deadlineAt: 10_000, waitEndedAt: 10_000, answeredBy: "msg_y" }); - readPages.mockResolvedValue([waiting, onPerson, answered, late, ask].map((r) => ({ topic: `workforce/messages/${r.id}`, clientData: r }))); - render(); + readAll.mockResolvedValue(entries([waiting, onPerson, answered, late, ask])); + render(); const lines = await screen.findAllByTestId("message"); const replyState = (id: string) => within(lines.find((l) => l.getAttribute("data-message-id") === id)!).queryByTestId("message-reply-state")?.textContent; expect(replyState("msg_f")).toBe("reply · waiting"); @@ -114,20 +111,20 @@ describe("the Messages view", () => { }); it("says so when there are none", async () => { - readPages.mockResolvedValue([]); - render(); + readAll.mockResolvedValue([]); + render(); expect((await screen.findByTestId("messages-empty")).textContent).toContain("No messages yet"); }); it("says this Lab keeps no log when no flow declares it", async () => { - readPages.mockRejectedValue(new ClientHttpError("Request failed (404) Not Found", { status: 404, body: { error: "unknown_resource" } })); - render(); + readAll.mockRejectedValue(new ClientHttpError("Request failed (404) Not Found", { status: 404, body: { error: "unknown_resource" } })); + render(); expect((await screen.findByTestId("messages-empty")).textContent).toContain("keeps no roster"); }); it("says what the Lab answered when the log didn't load", async () => { - readPages.mockRejectedValue(new Error("store offline")); - render(); + readAll.mockRejectedValue(new Error("store offline")); + render(); await waitFor(() => expect(screen.getByTestId("messages-failure").textContent).toContain("store offline")); }); diff --git a/packages/shift-manager/test/projects.test.tsx b/packages/shift-manager/test/projects.test.tsx index 012c1e215c..b25f3b143b 100644 --- a/packages/shift-manager/test/projects.test.tsx +++ b/packages/shift-manager/test/projects.test.tsx @@ -17,7 +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, toProject, type Project } from "../src/lib/reads"; +import { createLabReader, type Project } from "../src/lib/reads"; +import { toProject } from "../src/lib/projects"; 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 0483ee6f3a..75a69998c7 100644 --- a/packages/shift-manager/test/reads.test.ts +++ b/packages/shift-manager/test/reads.test.ts @@ -10,11 +10,7 @@ import type { Client } from "@flow-state-dev/client"; 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 { createLabReader, UNOWNED_SESSION_UNANSWERABLE, type LabSnapshot } from "../src/lib/reads"; import { workerStates, type LoadedSnapshot } from "../src/lib/derive"; import { withRoster } from "../src/lib/roster"; import { createWorkforceClient } from "@flow-state-dev/workforce/browser"; diff --git a/packages/shift-manager/test/roster-screen.test.tsx b/packages/shift-manager/test/roster-screen.test.tsx index b99fe30cb8..8f7d09df3d 100644 --- a/packages/shift-manager/test/roster-screen.test.tsx +++ b/packages/shift-manager/test/roster-screen.test.tsx @@ -11,7 +11,8 @@ 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 { GENERAL_TEAM, inboxSection, toBoardTaskView, toWorker, type Ask, type BoardTaskView, type ConversationBoards, type LabSnapshot, type Section } from "../src/lib/reads"; +import { inboxSection, toBoardTaskView, type Ask, type BoardTaskView, type ConversationBoards, type LabSnapshot, type Section } from "../src/lib/reads"; +import { GENERAL_TEAM, toWorker } from "../src/lib/workers"; let fixture: LabSnapshot; @@ -31,6 +32,7 @@ const rosterViews = new Set<(entries: never[]) => void>(); vi.mock("../src/lib/workforce", () => ({ useWorkforce: () => ({ + organization: async () => "acme", roster: () => rosterRead(), // The roster watch, reporting one read; `rosterWatches` counts the watches started. watchRoster: (onRoster: (entries: never[]) => void, options?: { onError?: (error: unknown) => void }) => { @@ -42,6 +44,12 @@ vi.mock("../src/lib/workforce", () => ({ }), })); +// FIX-2775: the directory's reads are the fixture's, beside the real roster watch. +vi.mock("../src/lib/directory-reads", async () => { + const { useFixtureReads } = await import("./helpers/directory"); + return { useDirectoryReads: () => useFixtureReads(() => fixture) }; +}); + vi.mock("../src/lib/reads", async (importOriginal) => { const real = await importOriginal(); return { @@ -268,10 +276,13 @@ describe("Roster (V3)", () => { expect(screen.queryByTestId("roster-summary")).toBeNull(); }); - it("BR-19: a conversation whose board did not load is named, and none of its tasks counts", async () => { + // FIX-2775: the boards and the asks are one answer, the Inbox view's: a board it can't read fails that + // answer whole, so Roster names the failure and draws no status it can't back. + it("BR-19: a board the Inbox view can't read fails the view, which Roster names, with no count from a guess", async () => { await open("/roster", lab({ boards: "ops failed" })); - expect((await screen.findByTestId("roster-boards-failure")).textContent).toMatch(/s_ops/); - expect(screen.getByTestId("roster-summary").textContent).toMatch(/^3 on shift · 2 off shift/); + expect((await screen.findByTestId("roster-asks-failure")).textContent).toMatch(/board offline/); + expect(screen.getByTestId("roster-summary").textContent).toMatch(/^0 on shift · 5 off shift/); + expect(within(screen.getByTestId("roster")).getByTestId("partial-mark")).toBeTruthy(); }); it("BR-20: asks that did not load put the partial mark on Roster", async () => { diff --git a/packages/shift-manager/test/roster.test.ts b/packages/shift-manager/test/roster.test.ts index bd7c9e2153..4c6ed5e744 100644 --- a/packages/shift-manager/test/roster.test.ts +++ b/packages/shift-manager/test/roster.test.ts @@ -1,14 +1,15 @@ /** * Roster's rules, below the screen: where a worker is grouped (BR-13a, BR-13b), - * the one status rule every screen draws (BR-1 to BR-6, BR-20), the counts - * reduced from it (BR-12, BR-14, BR-15), and the route (BR-13). + * the one status rule every screen draws (BR-1 to BR-6, BR-20), read from the + * worker directory against the Inbox view's one answer, the counts reduced + * from it (BR-12, BR-14, BR-15), and the route (BR-13). */ import { describe, expect, it } from "vitest"; -import { pickedTeam, workerStates, shiftCounts, teamsOf, type LoadedSnapshot } from "../src/lib/derive"; +import { boardTaskOf, type InboxBoardTask, type InboxSuspensionDetail, type InboxViewValue } from "@flow-state-dev/workforce/browser"; +import type { InboxHold, InboxItem } from "@flow-state-dev/orchestration/inbox"; +import { pickedTeam, workerStates, shiftCounts, teamsOf } from "../src/lib/shift"; import { parseRoute, pathFor } from "../src/lib/routes"; -import { GENERAL_TEAM, inboxSection, toBoardTaskView, toWorker, type Ask, type BoardTaskView, type Worker } from "../src/lib/reads"; - -const ORG = "acme"; +import { GENERAL_TEAM, toWorker } from "../src/lib/workers"; describe("BR-13a, BR-13b: which group a worker sits in", () => { it("an org worker (no dot) sits in General, never in a team of its own", () => { @@ -48,34 +49,49 @@ describe("BR-13a, BR-13b: which group a worker sits in", () => { }); }); -/** A loaded snapshot of `workers`, one conversation's board holding `rows`, and `asks` (or asks that failed). */ -function snapshotOf(workers: Worker[], rows: BoardTaskView[], asks: Ask[] | "failed" = []) { - const read = { - readAt: 0, - sessions: [], - orgId: ORG, - inventory: { ok: true, value: { workers } }, - boards: { s_desk: { ok: true, value: { refs: ["s_desk.tasks"], rows } } }, - asks: asks === "failed" ? { ok: false, failure: { message: "asks offline" } } : { ok: true, value: asks }, - resources: { ok: true, value: [] }, - } as unknown as Omit; - return { ...read, inbox: inboxSection(read.asks, read.boards, read.sessions) } as LoadedSnapshot; +/** + * The Inbox view's answer over one conversation's board holding `rows`, with + * an item per task held on you and one per `asks` hold no task claims, as the + * server builds it. `"failed"` stands for a view that didn't load. + */ +function viewOf(rows: InboxBoardTask[], asks: InboxHold[] = []): InboxViewValue { + const held: InboxItem[] = rows + .filter((task) => task.holds.length > 0) + .map((task) => ({ + id: `${task.boardRef}/${task.id}`, + task: { board: task.boardRef, taskId: task.id }, + holds: task.holds.map((hold) => ({ ...hold, source: { kind: "task" as const } })) as unknown as InboxHold[], + }) as unknown as InboxItem); + const own = asks.map((hold) => ({ id: hold.id, holds: [hold] }) as unknown as InboxItem); + return { items: [...held, ...own], tasks: rows }; } const worker = (id: string) => toWorker({ id, kind: "worker" })!; -const row = (id: string, status: string, assignee: string | null): BoardTaskView => - toBoardTaskView("s_desk.tasks", "s_desk", id, { id, title: id, status, assignee }); +const task = (id: string, stored: Record): InboxBoardTask => ({ ...boardTaskOf("s_desk.tasks", "s_desk", id, { id, title: id, ...stored }), owner: "@desk" }); +const row = (id: string, status: string, assignee: string | null): InboxBoardTask => task(id, { status, assignee }); /** A running row held on a question for you (FIX-2131): what a task waiting on you is. */ -const waiting = (id: string, assignee: string | null): BoardTaskView => - toBoardTaskView("s_desk.tasks", "s_desk", id, { - id, - title: id, +const waiting = (id: string, assignee: string | null): InboxBoardTask => + task(id, { status: "in_progress", assignee, holds: [{ id: `q-${id}`, actor: "user", openedAt: 1, source: { kind: "task", closedBy: [{ by: "answer" }] }, ask: { kind: "question", prompt: "Which one?" } }], }); -const ask = (workerId: string | null, suspensionId: string): Ask => - ({ sessionId: `s_${suspensionId}`, workerId, flowId: workerId, parentSessionId: null, kind: "approval", item: { suspensionId }, since: 0, unanswerable: null }) as unknown as Ask; +/** A pending approval the view lists, its detail naming the worker its session names (or none). */ +const ask = (workerId: string | null, suspensionId: string, openedAt = 0): InboxHold => + ({ + id: suspensionId, + source: { kind: "suspension", flowId: workerId, sessionId: `s_${suspensionId}`, requestId: `r_${suspensionId}`, suspensionId }, + ask: { kind: "approval", prompt: "May I?" }, + openedAt, + answerable: true, + unanswerable: null, + detail: { suspensionId, sessionId: `s_${suspensionId}`, workerId }, + }) as unknown as InboxHold; + +/** The arguments `workerStates` takes: the directory's workers and the view's answer (`"failed"`: none). */ +function directory(workers: ReturnType[], rows: InboxBoardTask[], asks: InboxHold[] | "failed" = []) { + return [workers, asks === "failed" ? undefined : viewOf(rows, asks)] as const; +} describe("BR-1 to BR-5: the one status rule", () => { const coder = worker("eng.coder"); @@ -83,21 +99,21 @@ describe("BR-1 to BR-5: the one status rule", () => { const idle = worker("eng.idle"); it("returns every inventory worker once, in inventory order", () => { - const states = workerStates(snapshotOf([coder, reviewer, idle], [])); + const states = workerStates(...directory([coder, reviewer, idle], [])); expect([...states.workers.keys()]).toEqual(["eng.coder", "eng.reviewer", "eng.idle"]); expect([...states.workers.values()].map((s) => s.status)).toEqual(["off shift", "off shift", "off shift"]); }); it("BR-1: a running task is on shift, and beats waiting", () => { - const states = workerStates(snapshotOf([coder], [waiting("a", "coder"), row("b", "in_progress", "coder")], [ask("eng.coder", "q1")])); + const states = workerStates(...directory([coder], [waiting("a", "coder"), row("b", "in_progress", "coder")], [ask("eng.coder", "q1")])); const state = states.workers.get("eng.coder")!; expect(state.status).toBe("on shift"); expect(state.held.map((r) => r.id)).toEqual(["a", "b"]); - expect(state.asks.map((a) => a.item.suspensionId)).toEqual(["q1"]); + expect(state.asks.map((a) => a.id)).toEqual(["q1"]); }); it("BR-2: a task held on a question for you alone, or an ask alone, is on shift: the worker is mid-task, waiting on you", () => { - const states = workerStates(snapshotOf([coder, reviewer], [waiting("a", "coder")], [ask("eng.reviewer", "q1")])); + const states = workerStates(...directory([coder, reviewer], [waiting("a", "coder")], [ask("eng.reviewer", "q1")])); expect(states.workers.get("eng.coder")!.status).toBe("on shift"); expect(states.workers.get("eng.reviewer")!.status).toBe("on shift"); expect(states.workers.get("eng.reviewer")!.held).toEqual([]); @@ -105,7 +121,7 @@ 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(snapshotOf([coder], rows)).workers.get("eng.coder")!; + const state = workerStates(...directory([coder], rows)).workers.get("eng.coder")!; expect(state).toMatchObject({ status: "off shift", held: [] }); }); @@ -113,7 +129,7 @@ describe("BR-1 to BR-5: the one status rule", () => { const ops = worker("ops.coder"); // `coder` names a worker in two teams: no single worker. const states = workerStates( - snapshotOf([coder, ops], [row("a", "in_progress", "coder"), row("b", "in_progress", "ghost")], [ask(null, "q1"), ask("nobody.here", "q2")]), + ...directory([coder, ops], [row("a", "in_progress", "coder"), row("b", "in_progress", "ghost")], [ask(null, "q1"), ask("nobody.here", "q2")]), ); expect([...states.workers.values()].map((s) => [s.status, s.held.length, s.asks.length])).toEqual([ ["off shift", 0, 0], @@ -121,16 +137,32 @@ describe("BR-1 to BR-5: the one status rule", () => { ]); }); - it("BR-20: asks that did not load mark the whole result partial, and leave statuses from the boards alone", () => { - const states = workerStates(snapshotOf([coder, reviewer], [row("a", "in_progress", "coder"), waiting("b", "reviewer")], "failed")); + it("BR-20: an Inbox view that did not load marks the whole result partial: no status is drawn from a guess", () => { + const states = workerStates(...directory([coder, reviewer], [row("a", "in_progress", "coder")], "failed")); expect(states.partial).toBe(true); - expect([...states.workers.values()].map((s) => s.status)).toEqual(["on shift", "on shift"]); - expect(workerStates(snapshotOf([coder], [])).partial).toBe(false); - }); - - it("is one result per snapshot, so every screen reads the same object", () => { - const snapshot = snapshotOf([coder], []); - expect(workerStates(snapshot)).toBe(workerStates(snapshot)); + expect([...states.workers.values()].map((s) => s.status)).toEqual(["off shift", "off shift"]); + expect(workerStates(...directory([coder], [])).partial).toBe(false); + }); + + // FIX-2775: one answer. The Inbox lists an ask, and the worker whose session it waits in reads on shift + // from that same answer; when the answer drops it, the worker is off shift again. Nothing else is read. + it("one answer: a worker is on shift for exactly as long as the Inbox view lists its ask", () => { + const listed = viewOf([], [ask("eng.reviewer", "q1")]); + expect(listed.items.map((item) => item.id)).toEqual(["q1"]); + expect(workerStates([coder, reviewer], listed).workers.get("eng.reviewer")).toMatchObject({ status: "on shift", held: [] }); + const answered = viewOf([], []); + expect(workerStates([coder, reviewer], answered).workers.get("eng.reviewer")!.status).toBe("off shift"); + }); + + it("an ask held on a task's run counts for the worker its session names, beside the task's own slot", () => { + const run = waiting("a", "coder"); + const view: InboxViewValue = { tasks: [run], items: [{ id: "s_desk.tasks/a", task: { board: "s_desk.tasks", taskId: "a" }, holds: [ask("eng.coder", "r1")] } as unknown as InboxItem] }; + const state = workerStates([coder], view).workers.get("eng.coder")!; + expect(state).toMatchObject({ status: "on shift" }); + expect(state.held.map((t) => t.id)).toEqual(["a"]); + // A run's stop for you is an ask, never a question the task holds: it waits on you once. + expect(state.waitsOnYou).toEqual([]); + expect(state.asks.map((hold) => hold.id)).toEqual(["r1"]); }); }); @@ -139,19 +171,19 @@ describe("BR-12, BR-14, BR-15: counts reduce from the one result", () => { const reviewer = worker("eng.reviewer"); const asker = worker("ops.asker"); const shiftCoordinator = worker("shift-coordinator"); - const snapshot = snapshotOf( + const read = directory( [coder, reviewer, asker, shiftCoordinator], [row("a", "in_progress", "coder"), waiting("b", "coder"), waiting("c", "reviewer"), row("d", "pending", "asker")], [ask("ops.asker", "q1"), ask("ops.asker", "q2")], ); it("counts each group, and every waits-on entry, an on-shift worker's included", () => { - expect(shiftCounts(workerStates(snapshot))).toEqual({ "on shift": 3, "off shift": 1, waiting: 4 }); + expect(shiftCounts(workerStates(...read))).toEqual({ "on shift": 3, "off shift": 1, waiting: 4 }); }); it("counts only the workers shown when a team is picked", () => { - expect(shiftCounts(workerStates(snapshot), "ops")).toEqual({ "on shift": 1, "off shift": 0, waiting: 2 }); - expect(shiftCounts(workerStates(snapshot), GENERAL_TEAM)).toEqual({ "on shift": 0, "off shift": 1, waiting: 0 }); + expect(shiftCounts(workerStates(...read), "ops")).toEqual({ "on shift": 1, "off shift": 0, waiting: 2 }); + expect(shiftCounts(workerStates(...read), GENERAL_TEAM)).toEqual({ "on shift": 0, "off shift": 1, waiting: 0 }); }); it("lists teams with General first, each with exactly its workers", () => { diff --git a/packages/shift-manager/test/routines-view.test.tsx b/packages/shift-manager/test/routines-view.test.tsx index f5675ed57f..2815a4dda0 100644 --- a/packages/shift-manager/test/routines-view.test.tsx +++ b/packages/shift-manager/test/routines-view.test.tsx @@ -7,7 +7,6 @@ */ import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { LoadedSnapshot } from "../src/lib/derive"; import { parseRoute, pathFor } from "../src/lib/routes"; import { ClientHttpError } from "@flow-state-dev/client"; import { toRoutines } from "../src/lib/routines"; @@ -20,6 +19,8 @@ const lab = { client: { userId: "u_1", view: (...a: unknown[]) => view(...a), + // FIX-2775: the list is `useView`'s, kept current by the view's own notices; none arrive here. + subscribe: () => ({ close: () => {} }), resource: (def: { pattern: string }) => ({ send: (verb: string, input: unknown) => send(def.pattern, verb, input) }), }, refresh: vi.fn(), @@ -48,8 +49,6 @@ const review = { }; const declared = { ...weekly, id: "clock:cfg_abc", name: "cfg_abc", madeBy: { by: "app", entry: "weekly-digest" } }; -// No session of the roster flow: the list and its changes need none. -const snapshot = { sessions: [], readAt: 1 } as unknown as LoadedSnapshot; const listed = (routines: unknown[]) => ({ value: { routines }, topics: [] }); beforeEach(() => { @@ -72,14 +71,14 @@ describe("the routine list", () => { it("says a paused routine is paused, whatever its cron, and names who made each", () => { expect(nextRunLabel("2026-10-26T09:00:00.000Z", true)).toBe("paused"); expect(nextRunLabel(null, false)).toBe("no next run"); - expect([madeByLabel({ by: "user" }), madeByLabel({ by: "app", entry: "x" }), madeByLabel(null)]).toEqual(["made by you", "the app's", ""]); + expect([madeByLabel({ by: "user" }), madeByLabel({ by: "app", entry: "x" }), madeByLabel(undefined)]).toEqual(["made by you", "the app's", ""]); }); }); describe("the Routines view", () => { it("lists clock and event routines read through the roster flow's view, with no session", async () => { view.mockResolvedValue(listed([weekly, off, review])); - render(); + render(); const lines = await screen.findAllByTestId("routine"); expect(view.mock.calls[0]![0]).toMatchObject({ flow: "workforce-roster", view: "routines" }); expect(lines.map((l) => [l.getAttribute("data-id"), l.getAttribute("data-trigger"), l.getAttribute("data-paused")])).toEqual([ @@ -97,7 +96,7 @@ describe("the Routines view", () => { it("pauses, resumes and deletes from a line by a send to the routines collection, and reads the list again", async () => { view.mockResolvedValue(listed([weekly, off])); send.mockResolvedValue({ ok: true, routine: weekly }); - render(); + render(); const [on, paused] = await screen.findAllByTestId("routine"); fireEvent.click(within(on!).getByTestId("routine-pause")); fireEvent.click(within(paused!).getByTestId("routine-pause")); @@ -115,7 +114,7 @@ describe("the Routines view", () => { it("offers an app's routine a pause and no delete, and says why a change was refused", async () => { view.mockResolvedValue(listed([declared])); send.mockResolvedValue({ ok: false, error: "declared: it follows the app's config" }); - render(); + render(); const [line] = await screen.findAllByTestId("routine"); expect(within(line!).queryByTestId("routine-delete")).toBeNull(); fireEvent.click(within(line!).getByTestId("routine-pause")); @@ -124,19 +123,19 @@ describe("the Routines view", () => { it("says so when there are none", async () => { view.mockResolvedValue(listed([])); - render(); + render(); expect((await screen.findByTestId("routines-empty")).textContent).toContain("No routines yet"); }); it("says the Lab keeps no routines when it serves no roster flow", async () => { view.mockRejectedValue(new ClientHttpError("Request failed (404)", { status: 404, body: { error: 'Unknown flow "workforce-roster"' } })); - render(); + render(); expect((await screen.findByTestId("routines-empty")).textContent).toContain("keeps no roster for you"); }); it("says what the Lab answered when the list didn't load", async () => { view.mockRejectedValue(new Error("store offline")); - render(); + render(); await waitFor(() => expect(screen.getByTestId("routines-failure").textContent).toContain("store offline")); }); diff --git a/packages/shift-manager/test/session-view.test.tsx b/packages/shift-manager/test/session-view.test.tsx index 89d3907089..9e5885e92b 100644 --- a/packages/shift-manager/test/session-view.test.tsx +++ b/packages/shift-manager/test/session-view.test.tsx @@ -2,11 +2,12 @@ /** * draws one session by id, opened from Messages (FIX-1989). * What is checked: a task's session and a delegate's session for another conversation take no line whatever the - * worker, a worker's own conversation does, and a session the snapshot - * doesn't list yet is looked up in a fresh listing before it is called + * worker, a worker's own conversation does, and a session the page's list + * doesn't hold yet is looked up in a fresh listing before it is called * missing. The read and the listing are stood in for. */ -import { act, cleanup, render, screen } from "@testing-library/react"; +import { act, cleanup, render as draw, screen } from "@testing-library/react"; +import type { ReactElement } from "react"; import type { SessionSummary } from "@flow-state-dev/client"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { GAPS } from "../src/gaps"; @@ -20,11 +21,20 @@ const lab = { snapshot: { orgId: "org_1", sessions: [], inventory: { ok: true, value: { workers: [] } } }, }; vi.mock("../src/lib/lab-data", () => ({ useLab: () => lab })); -vi.mock("../src/lib/workforce", () => ({ useWorkforce: () => ({ ensureWorkerSession: vi.fn() }) })); +/** What the page's directory holds: the session list and the inventory the case draws. */ +let listed: unknown; +vi.mock("../src/lib/directory-reads", async () => { + const { useFixedReads } = await import("./helpers/directory"); + return { useDirectoryReads: () => useFixedReads(() => listed as never) }; +}); +vi.mock("../src/lib/workforce", () => ({ useWorkforce: () => ({ organization: async () => "org_1", ensureWorkerSession: vi.fn() }) })); // The conversation follows its session: its first answer is `read`'s. vi.mock("../src/lib/session-feeds", async () => (await import("./helpers/fake-feed")).fakeFeeds([], (sessionId) => read(lab.client, sessionId))); import { SessionView } from "../src/surfaces/SessionView"; +import { DirectoryProvider } from "../src/lib/directory"; + +const render = (ui: ReactElement) => draw(ui, { wrapper: DirectoryProvider }); // A registered worker with a door: only the session decides whether a line may go. const reviewer = { id: "eng.reviewer", kind: "agent", door: "talk", rules: false, team: "", name: "Reviewer" }; @@ -41,7 +51,8 @@ beforeEach(() => { afterEach(() => cleanup()); async function drawn(sessions: SessionSummary[], sessionId: string) { - render(); + listed = snapshot(sessions); + render(); await act(async () => {}); } @@ -61,7 +72,7 @@ describe("a session opened by id", () => { expect(screen.queryByTestId("session-composer-blocked")).toBeNull(); }); - it("looks up a session the snapshot doesn't list, among dispatch runs too, before calling it missing", async () => { + it("looks up a session the page's list doesn't hold, among dispatch runs too, before calling it missing", async () => { listSessions.mockResolvedValue([session("s_new")]); await drawn([], "s_new"); expect(listSessions).toHaveBeenCalledWith({ userId: "u_1", include: "dispatch-runs" }); diff --git a/packages/shift-manager/test/shift-coordinator.test.ts b/packages/shift-manager/test/shift-coordinator.test.ts index 8449464a7e..ce5cc7e3e3 100644 --- a/packages/shift-manager/test/shift-coordinator.test.ts +++ b/packages/shift-manager/test/shift-coordinator.test.ts @@ -6,10 +6,12 @@ */ import { describe, expect, it } from "vitest"; import type { SessionSummary } from "@flow-state-dev/client"; -import { shiftCoordinatorOf, shiftSummary, type LoadedSnapshot } from "../src/lib/derive"; +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 { GENERAL_TEAM, inboxSection, toWorker, type Ask, type BoardTaskView, type Worker } from "../src/lib/reads"; +import { inboxSection, type Ask, type BoardTaskView, type Worker } from "../src/lib/reads"; +import { GENERAL_TEAM, toWorker } from "../src/lib/workers"; const ORG = "org_1"; const worker = (id: string, door: string | null = "run"): Worker => ({ ...toWorker({ id, kind: "agent", door })! }); diff --git a/packages/shift-manager/test/snapshot-subscribe.test.tsx b/packages/shift-manager/test/snapshot-subscribe.test.tsx index 445662b09a..d254c64791 100644 --- a/packages/shift-manager/test/snapshot-subscribe.test.tsx +++ b/packages/shift-manager/test/snapshot-subscribe.test.tsx @@ -7,9 +7,10 @@ * the org's topics and each listed session but Shift Manager's own. Only the * notices that change what the snapshot reads start a read: never a streamed * item, never a resource the snapshot doesn't read, never Shift Manager's own - * reading and usage sessions, or each read would start the next. The summary - * says when it was last read (D1), and counts dim only while a read the user - * asked for runs (D2). + * reading and usage sessions, or each read would start the next. No screen + * reads the snapshot any more (FIX-2775): the summary says when its own reads + * last landed (D1), and its refresh and R read those again, never the + * snapshot. * * The client's `subscribe` and the reader are swapped for ones the test drives. */ @@ -49,13 +50,21 @@ vi.mock("../src/lib/connection", async () => { readConnection: () => ({ userId: USER }), }; }); -const workforce = { watchRoster: () => () => {} }; +const workforce = { organization: async () => "acme", watchRoster: () => () => {} }; 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); +const viewRefresh = vi.fn(); vi.mock("../src/lib/inbox", async (importOriginal) => { const real = await importOriginal(); const { viewOfSnapshot } = await import("./helpers/inbox-view"); - return { ...real, useInbox: () => ({ section: viewOfSnapshot(snapshotOf()), stale: false, refresh: () => {} }) }; + return { ...real, useInbox: () => ({ section: viewOfSnapshot(snapshotOf()), stale: false, refresh: viewRefresh, readAt: viewReadAt }) }; +}); +// 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) }; }); let sessions: SessionSummary[] = []; @@ -112,6 +121,8 @@ beforeEach(() => { reads = 0; held = undefined; holdNext = false; + viewReadAt = Date.UTC(2026, 10, 4, 14, 2); + viewRefresh.mockClear(); }); afterEach(() => cleanup()); @@ -308,39 +319,33 @@ describe("the summary's age and R", () => { return screen.findByTestId("shift-coordinator-as-of"); } - it("says when the snapshot was last read, never that it is live, and moves when a read lands (D1)", async () => { + it("says when the summary's own reads last landed, never that it is live (D1)", async () => { + viewReadAt = Date.UTC(2026, 10, 4, 14, 7); const line = await openShiftCoordinator(); - expect(line.textContent).toBe(`as of ${clockTime(readAt)} · refresh`); + expect(line.textContent).toBe(`as of ${clockTime(viewReadAt)} · refresh`); expect(line.textContent).not.toMatch(/live/i); - readAt += 5 * 60_000; - await waitFor(() => expect(live()).toHaveLength(1)); - await hear(notice({ scope: "session", id: "conv-1" }, "request")); - await waitFor(() => expect(screen.getByTestId("shift-coordinator-as-of").textContent).toBe(`as of ${clockTime(readAt)} · refresh`)); }); - it("reads now from its refresh link and from R, dimming the counts until the read lands, but not from R typed in a field", async () => { + it("reads the summary's reads again from its refresh link and from R, and nothing of the snapshot; not from R typed in a field", async () => { await openShiftCoordinator(); await settle(); const before = reads; - holdNext = true; fireEvent.click(screen.getByTestId("shift-coordinator-as-of-refresh")); - await waitFor(() => expect(held).toBeDefined()); - expect(reads).toBe(before + 1); - expect(screen.getByTestId("nav-inbox-count").getAttribute("data-asking")).toBe("true"); - expect(screen.getByTestId("shift-coordinator-summary").querySelector("[data-look='summary-prose']")!.getAttribute("data-asking")).toBe("true"); - await act(async () => held!.land()); - await waitFor(() => expect(screen.getByTestId("nav-inbox-count").getAttribute("data-asking")).toBeNull()); + await settle(); + expect(viewRefresh).toHaveBeenCalledTimes(1); act(() => void fireEvent.keyDown(window, { key: "r" })); await settle(); - expect(reads).toBe(before + 2); + expect(viewRefresh).toHaveBeenCalledTimes(2); const field = document.createElement("input"); document.body.appendChild(field); act(() => void fireEvent.keyDown(field, { key: "r" })); act(() => void fireEvent.keyDown(window, { key: "r", metaKey: true })); await settle(); - expect(reads).toBe(before + 2); + expect(viewRefresh).toHaveBeenCalledTimes(2); field.remove(); + // Nothing on screen asked the snapshot for a read. + expect(reads).toBe(before); }); }); diff --git a/packages/shift-manager/test/task-actions.test.ts b/packages/shift-manager/test/task-actions.test.ts index 06b8194aae..85e7ea6079 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 { CONVERSATION_BOARD_COLLECTION, createLabReader, type BoardTaskView } from "../src/lib/reads"; +import { createLabReader, type BoardTaskView } from "../src/lib/reads"; +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"; import { eventually, serveLab, type ServedLab } from "./helpers/serve-lab"; diff --git a/packages/shift-manager/test/task-card-in-feed.test.tsx b/packages/shift-manager/test/task-card-in-feed.test.tsx index 5d94771093..455feb3265 100644 --- a/packages/shift-manager/test/task-card-in-feed.test.tsx +++ b/packages/shift-manager/test/task-card-in-feed.test.tsx @@ -3,10 +3,14 @@ * One card per task the turn filed. Status comes from the board, so a task * the feed still holds as running can show errored. */ -import { act, cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { act, cleanup, fireEvent, render as draw, screen } from "@testing-library/react"; +import type { ReactElement } from "react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { OutputItem } from "@flow-state-dev/core/items"; import { SessionScope, TaskBoardMeta } from "../src/components/TaskBoardMeta"; +import { DirectoryProvider } from "../src/lib/directory"; + +const render = (ui: ReactElement) => draw(ui, { wrapper: DirectoryProvider }); import type { SubscribeOptions, WireNotice, WireTopic } from "@flow-state-dev/client"; /** The view's own timer where push can miss a change: `useView`'s default. */ @@ -40,6 +44,11 @@ const lab: { client: { userId: string; subscribe: typeof subscribe; view: typeof refresh: async () => void refreshes++, }; vi.mock("../src/lib/lab-data", () => ({ useLab: () => lab })); +// FIX-2775: the directory the card reads its workers and sessions from: the case's snapshot. +vi.mock("../src/lib/directory-reads", async () => { + const { useFixedReads } = await import("./helpers/directory"); + return { useDirectoryReads: () => useFixedReads(() => ("inventory" in lab.snapshot ? lab.snapshot : undefined) as never) }; +}); // The user's conversation with the Error Reporter, as the snapshot lists it; `null` before a first line. let reporterConversation: string | null = null; const conversationsAskedFor: unknown[] = []; diff --git a/packages/shift-manager/test/task-screen.test.tsx b/packages/shift-manager/test/task-screen.test.tsx index 3769bd5020..b09aef2dd3 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 { CONVERSATION_BOARD_COLLECTION, conversationBoardRef, createLabReader, toBoardTaskView, type BoardTaskView } from "../src/lib/reads"; +import { createLabReader, toBoardTaskView, type BoardTaskView } from "../src/lib/reads"; +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/task-session.test.tsx b/packages/shift-manager/test/task-session.test.tsx index 26ae7c83b4..6c6c29443e 100644 --- a/packages/shift-manager/test/task-session.test.tsx +++ b/packages/shift-manager/test/task-session.test.tsx @@ -45,7 +45,7 @@ vi.mock("../src/lib/task-items", async (original) => ({ })); import { taskBriefMetadata } from "@flow-state-dev/workforce/browser"; -import { collectionOfBoard } from "../src/lib/reads"; +import { collectionOfBoard } from "../src/lib/boards"; import { TaskSession } from "../src/surfaces/TaskSession"; const step = (n: number) => ({ diff --git a/packages/shift-manager/test/turn-routes.test.ts b/packages/shift-manager/test/turn-routes.test.ts index 6038784e5c..f1f1c20ef0 100644 --- a/packages/shift-manager/test/turn-routes.test.ts +++ b/packages/shift-manager/test/turn-routes.test.ts @@ -3,7 +3,7 @@ * publishes. A pure read of the snapshot, so each case is staged exactly. */ import { describe, expect, it } from "vitest"; -import { doorOf } from "../src/lib/derive"; +import { doorOf } from "../src/lib/shift"; import type { Worker } from "../src/lib/reads"; const worker = (id: string, door: string | null = "message", flow = "coder"): Worker => ({ diff --git a/packages/shift-manager/test/usage-views.test.ts b/packages/shift-manager/test/usage-views.test.ts index e37d30bd9a..767d82695a 100644 --- a/packages/shift-manager/test/usage-views.test.ts +++ b/packages/shift-manager/test/usage-views.test.ts @@ -14,11 +14,22 @@ import { afterEach, describe, expect, it } from "vitest"; import type { HarnessUsageReader } from "@flow-state-dev/core/harness"; import { inMemoryStores } from "@flow-state-dev/engine"; import { harnessStub } from "@flow-state-dev/harness-manager"; +import type { Client } from "@flow-state-dev/client"; +import { harnessUsageViewRef, recheckHarnessUsage } from "@flow-state-dev/harness-manager/browser"; +import { workerUsageView } from "@flow-state-dev/workforce/browser"; import { connect } from "../src/lib/connection"; -import { readHarnessUsageView, readWorkerUsageView } from "../src/lib/usage"; import { LAB_USERS, openLab, type Lab } from "../teams/devteam/host.mts"; import { serveLab } from "./helpers/serve-lab"; +// FIX-2775: the reads Usage makes, made once: Re-check, then the usage view; the worker usage view. +async function readHarnessUsageView(client: Client) { + await recheckHarnessUsage(client); + return (await client.view(harnessUsageViewRef(), {})).value.harnesses; +} +async function readWorkerUsageView(client: Client, days: number) { + return (await client.view(workerUsageView, { days })).value.workers; +} + const cleanups: Array<() => Promise | void> = []; afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); diff --git a/packages/shift-manager/test/usage.test.ts b/packages/shift-manager/test/usage.test.ts index 2820250f79..65472c3d2f 100644 --- a/packages/shift-manager/test/usage.test.ts +++ b/packages/shift-manager/test/usage.test.ts @@ -1,9 +1,12 @@ +// @vitest-environment happy-dom /** * Usage's labels: what a window, an age and a harness are called on screen. - * The rows themselves are the Lab's; these only name them. + * 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 { describe, expect, it } from "vitest"; -import { ClientHttpError, type Client } from "@flow-state-dev/client"; +import { renderHook, waitFor } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; +import { ClientHttpError } from "@flow-state-dev/client"; import { ageLabel, billingLabel, @@ -13,11 +16,9 @@ import { harnessName, levelLabel, percentLabel, - readHarnessUsageView, - readWorkerUsageView, tokensLabel, - toHarnessUsage, - toWorkerUsage, + useHarnessUsage, + useWorkerUsage, USAGE_PERIODS, windowName, type HarnessUsage, @@ -56,11 +57,9 @@ describe("Usage labels", () => { expect(levelLabel(null, "claude-code")).not.toMatch(/\d/); }); - it("names harnesses for the user, and keeps only rows that are rows", () => { + it("names harnesses for the user", () => { expect(harnessName("codex")).toBe("Codex"); expect(harnessName("claude-code")).toBe("Claude Code"); - expect(toHarnessUsage({ harnesses: [{ harness: "codex" }, null, "x"] })).toEqual([{ harness: "codex" }]); - expect(toHarnessUsage(undefined)).toEqual([]); }); }); @@ -100,10 +99,8 @@ describe("Usage by worker labels", () => { expect(billingLabel(null)).toBeNull(); }); - it("offers today, 7 and 30 days, and keeps only rows that are rows", () => { + it("offers today, 7 and 30 days", () => { expect(USAGE_PERIODS.map((p) => p.days)).toEqual([1, 7, 30]); - expect(toWorkerUsage({ workers: [{ worker: "coder" }, null, 3] })).toEqual([{ worker: "coder" }]); - expect(toWorkerUsage(undefined)).toEqual([]); }); it("never labels a total as left, remaining or a limit", () => { @@ -133,34 +130,60 @@ const STORED: HarnessUsage = { refreshError: null, }; +/** The page's connection, for the reads to go through. */ +let lab: { client: unknown }; +vi.mock("../src/lib/lab-data", () => ({ useLab: () => lab })); + function fakeLab(answers: { recheck?: () => Promise; view?: () => Promise }) { - return { - userId: "alice", - resource: () => ({ send: answers.recheck ?? (async () => ({ asked: [] })) }), - view: async () => ({ value: await (answers.view ?? (async () => ({ harnesses: [STORED], workers: [] })))(), topics: [] }), - } as unknown as Client; + lab = { + client: { + userId: "alice", + resource: () => ({ send: answers.recheck ?? (async () => ({ asked: [] })) }), + view: async () => ({ value: await (answers.view ?? (async () => ({ harnesses: [STORED], workers: [] })))(), topics: [] }), + // The views are kept current by their notices; none arrive here. + subscribe: () => ({ close: () => {} }), + }, + }; } const refused = (status: number, error: string) => async () => { throw new ClientHttpError(`Request failed (${status})`, { status, body: { error, message: error } }); }; +/** What the harness hook settles on. */ +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)); + return result.current; +} + +async function workerRead(answers: Parameters[0]) { + fakeLab(answers); + const { result } = renderHook(() => useWorkerUsage(7)); + await waitFor(() => expect(result.current.rows !== undefined || result.current.failure !== undefined).toBe(true)); + return result.current; +} + describe("the usage reads", () => { it("read as no usage only when nothing serves it: a 404, or a Re-check whose writer flow isn't registered", async () => { - expect(await readHarnessUsageView(fakeLab({ recheck: refused(404, "unknown_resource") }))).toBeNull(); - expect(await readHarnessUsageView(fakeLab({ recheck: refused(409, "runby_flow_missing") }))).toBeNull(); - expect(await readHarnessUsageView(fakeLab({ view: refused(404, "unknown_view") }))).toBeNull(); - expect(await readWorkerUsageView(fakeLab({ view: refused(404, "unknown_view") }), 7)).toBeNull(); + expect((await harnessRead({ recheck: refused(404, "unknown_resource") })).rows).toBeNull(); + expect((await harnessRead({ recheck: refused(409, "runby_flow_missing") })).rows).toBeNull(); + expect((await harnessRead({ view: refused(404, "unknown_view") })).rows).toBeNull(); + expect((await workerRead({ view: refused(404, "unknown_view") })).rows).toBeNull(); }); it("pass any other 409 on to the screen, from Re-check and from either view", async () => { - await expect(readHarnessUsageView(fakeLab({ recheck: refused(409, "declarations_disagree") }))).rejects.toThrow(/409/); - await expect(readHarnessUsageView(fakeLab({ view: refused(409, "declarations_disagree") }))).rejects.toThrow(/409/); - await expect(readWorkerUsageView(fakeLab({ view: refused(409, "runby_flow_missing") }), 7)).rejects.toThrow(/409/); + expect((await harnessRead({ recheck: refused(409, "declarations_disagree") })).failure).toMatchObject({ httpStatus: 409 }); + expect((await harnessRead({ view: refused(409, "declarations_disagree") })).failure).toMatchObject({ httpStatus: 409 }); + expect((await workerRead({ view: refused(409, "runby_flow_missing") })).failure).toMatchObject({ httpStatus: 409 }); }); it("still answer the stored rows when Re-check fails, with why beside them", async () => { - const harnesses = await readHarnessUsageView(fakeLab({ recheck: refused(500, "store offline") })); - expect(harnesses).toEqual([{ ...STORED, refreshError: "store offline" }]); + const read = await harnessRead({ recheck: refused(500, "store offline") }); + expect(read.rows).toEqual([{ ...STORED, refreshError: "store offline" }]); + expect(read.failure).toBeUndefined(); }); }); diff --git a/packages/shift-manager/test/worker-settings-screen.test.tsx b/packages/shift-manager/test/worker-settings-screen.test.tsx index 7a4e2bf969..4a157e8af1 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 { toWorker, type LabSnapshot, type Worker } from "../src/lib/reads"; +import { type LabSnapshot, type Worker } from "../src/lib/reads"; +import { toWorker } from "../src/lib/workers"; import { MAX_RULE_CHARS } from "@flow-state-dev/workforce/browser"; type Rule = { number: number; text: string; addedAt: number; sessionId: string | null }; @@ -40,6 +41,7 @@ let roster: () => Promise; // One client for the page, as the app's own hook keeps one: a new one per render would read the list again on every render. const workforce = { + organization: async () => "acme", roster: () => roster(), // The roster watch, reporting one read. watchRoster: (onRoster: (entries: never[]) => void, options?: { onError?: (error: unknown) => void }) => (void (roster() as Promise).then(onRoster, options?.onError), () => {}), @@ -50,6 +52,11 @@ vi.mock("../src/lib/workforce", () => ({ })); let fixture: LabSnapshot; +// FIX-2775: the directory's reads are the fixture's, beside the real roster watch. +vi.mock("../src/lib/directory-reads", async () => { + const { useFixtureReads } = await import("./helpers/directory"); + return { useDirectoryReads: () => useFixtureReads(() => fixture) }; +}); vi.mock("../src/lib/reads", async (importOriginal) => { const real = await importOriginal(); return { ...real, createLabReader: () => ({ read: async () => fixture, readBoard: async () => [], resume: async () => {} }) }; diff --git a/packages/shift-manager/test/worker-usage-period.test.tsx b/packages/shift-manager/test/worker-usage-period.test.tsx index a402556935..5eaf7a71fe 100644 --- a/packages/shift-manager/test/worker-usage-period.test.tsx +++ b/packages/shift-manager/test/worker-usage-period.test.tsx @@ -4,7 +4,7 @@ * read for a new period that fails never leaves the last period's totals * standing under the new tab. */ -import { renderHook, waitFor } from "@testing-library/react"; +import { act, renderHook, waitFor } from "@testing-library/react"; import { describe, expect, it, vi } from "vitest"; import type { Client } from "@flow-state-dev/client"; import { useWorkerUsage } from "../src/lib/usage"; @@ -16,6 +16,8 @@ let answer: (days: number) => Promise; const client = { userId: "alice", view: async (_ref: unknown, input: { days: number }) => ({ value: await answer(input.days), topics: [] }), + // The view is kept current by its notices; none arrive here. + subscribe: () => ({ close: () => {} }), } as unknown as Client; vi.mock("../src/lib/lab-data", () => ({ useLab: () => ({ client }) })); @@ -27,7 +29,7 @@ const totals = (days: number) => ({ describe("Usage by worker across a period change", () => { it("shows no rows under a period whose read failed, never the last period's", async () => { answer = async (days) => totals(days); - const { result, rerender } = renderHook(({ days }) => useWorkerUsage(0, days), { initialProps: { days: 30 } }); + const { result, rerender } = renderHook(({ days }) => useWorkerUsage(days), { initialProps: { days: 30 } }); await waitFor(() => expect(result.current.rows?.[0]?.tokens.input).toBe(30)); answer = async () => { @@ -42,13 +44,13 @@ describe("Usage by worker across a period change", () => { it("keeps the last rows beside a failure when the same period is read again", async () => { answer = async (days) => totals(days); - const { result, rerender } = renderHook(({ readAt }) => useWorkerUsage(readAt, 7), { initialProps: { readAt: 0 } }); + const { result } = renderHook(() => useWorkerUsage(7)); await waitFor(() => expect(result.current.rows?.[0]?.tokens.input).toBe(7)); answer = async () => { throw new Error("usage read failed"); }; - rerender({ readAt: 1 }); + act(() => result.current.reread()); await waitFor(() => expect(result.current.failure).toBeDefined()); expect(result.current.rows?.[0]?.tokens.input).toBe(7); }); From eb836e27aa4812ac3ac677bbe1a24b76ffc96b8e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 00:28:27 +0000 Subject: [PATCH 05/24] wip: more tests onto the package reads --- packages/shift-manager/test/columns.test.ts | 8 +- .../test/devteam-em-workstream.test.ts | 6 +- .../shift-manager/test/inbox-tasks.test.ts | 8 +- .../test/project-read-on-notice.test.tsx | 170 ++++++++++-------- .../test/project-setup-view.test.ts | 11 +- .../test/project-workstreams.test.tsx | 11 +- packages/shift-manager/test/reads.test.ts | 5 +- packages/shift-manager/test/static.test.ts | 6 +- 8 files changed, 124 insertions(+), 101 deletions(-) diff --git a/packages/shift-manager/test/columns.test.ts b/packages/shift-manager/test/columns.test.ts index b3d8eae66e..b1f9b1635d 100644 --- a/packages/shift-manager/test/columns.test.ts +++ b/packages/shift-manager/test/columns.test.ts @@ -8,7 +8,7 @@ import { describe, expect, it } from "vitest"; import { taskStatusSchema } from "@flow-state-dev/orchestration/tasks"; import { COLUMNS, columnFor, isHeld, isDone } from "../src/lib/columns"; -import { openTasks, type LoadedSnapshot, type Roster } from "../src/lib/derive"; +import { openTasks, type LoadedSnapshot } from "../src/lib/derive"; import { workerFor } from "../src/lib/shift"; import { toBoardTaskView, type BoardTaskView } from "../src/lib/reads"; import { toWorker } from "../src/lib/workers"; @@ -56,17 +56,17 @@ describe("which worker holds a row, when a bare name is in more than one team", const rowFor = (assignee: string) => toBoardTaskView("s_1.tasks", "s_1", "r", { id: "r", title: "r", status: "in_progress", assignee }); it("attributes the row to no worker, never to several", () => { - const roster: Roster = { workers: [ops, eng] }; + const roster = [ops, eng]; expect(workerFor(roster, rowFor("builder"))).toBeUndefined(); }); it("resolves a name only one worker carries", () => { - const roster: Roster = { workers: [ops, toWorker({ id: "eng.reviewer", kind: "worker" })!] }; + const roster = [ops, toWorker({ id: "eng.reviewer", kind: "worker" })!]; expect(workerFor(roster, rowFor("builder"))?.id).toBe("ops.builder"); }); it("a full worker id always wins", () => { - const roster: Roster = { workers: [ops, eng] }; + const roster = [ops, eng]; expect(workerFor(roster, rowFor("ops.builder"))?.id).toBe("ops.builder"); }); }); diff --git a/packages/shift-manager/test/devteam-em-workstream.test.ts b/packages/shift-manager/test/devteam-em-workstream.test.ts index e9dd609543..0263b9f69b 100644 --- a/packages/shift-manager/test/devteam-em-workstream.test.ts +++ b/packages/shift-manager/test/devteam-em-workstream.test.ts @@ -29,7 +29,8 @@ import { inMemoryStores } from "@flow-state-dev/engine"; import { runAction } from "./helpers/run-action"; import type { Client } from "@flow-state-dev/client"; import { connect } from "../src/lib/connection"; -import { readEntryReport, readProject, type ProjectAddress } from "../src/lib/projects"; +import { readProject, type ProjectAddress } from "../src/lib/projects"; +import { workstreamReportView } from "@flow-state-dev/workforce/browser"; import { createLabReader } from "../src/lib/reads"; import { createWorkforceClient } from "@flow-state-dev/workforce/browser"; import { harnessStub } from "@flow-state-dev/harness-manager"; @@ -232,7 +233,8 @@ describe("the EM files from the workstream it leads", () => { // The EM updated her entry, and her project screen reads the report. const entry = (await readProject(client, STOREFRONT))!.entries.find((e) => e.owner === ALICE.userId && e.id === "feature")!; - expect(await readEntryReport(client, STOREFRONT, entry)).toBe(REPORT); + // The read an entry's view makes (`useEntryReport`): the roster flow's report view, with no session. + expect((await client.view(workstreamReportView, { project: STOREFRONT, owner: entry.owner, id: entry.id })).value.report).toBe(REPORT); // Every session the job made is Alice's: her workstream session, and each task's session under it. const sessions = await runtime.stores.session.list({ orgId: LAB_ORG_ID, parentage: "all" }); diff --git a/packages/shift-manager/test/inbox-tasks.test.ts b/packages/shift-manager/test/inbox-tasks.test.ts index 11c782a2cb..9dd6a58c0f 100644 --- a/packages/shift-manager/test/inbox-tasks.test.ts +++ b/packages/shift-manager/test/inbox-tasks.test.ts @@ -154,9 +154,8 @@ describe("Tasks (BR-14, K1, K4, K8)", () => { row("C", "pending"), row("D", "completed", { ownerSessionId: "s_other" }), ]; - // Who is on shift is still the snapshot's (FIX-2775); the tasks and the Inbox are the view's. - const s = snapshot(tasks, asks, workers); - expect(summaryLine({ ok: true, value: viewOf(tasks, [{ suspensionId: "a1", workerId: "eng.em" }]) }, s)).toBe("2 in flight · 2 need you · 2 on shift · 2 streams"); + // Who is on shift is the view's too (FIX-2775): the tasks, the Inbox and the on-shift count are one answer. + expect(summaryLine({ ok: true, value: viewOf(tasks, [{ suspensionId: "a1", workerId: "eng.em" }]) }, workers)).toBe("2 in flight · 2 need you · 2 on shift · 2 streams"); }); it("an Inbox link written with a suspension id still opens the task's item that holds it", () => { @@ -195,8 +194,7 @@ describe("Tasks (BR-14, K1, K4, K8)", () => { }); it("an Inbox that didn't load says so in the summary, never 0 need you, which reads as all clear", () => { - const s = snapshot([row("A", "in_progress")]); - const line = summaryLine({ ok: false, failure: { message: "asks offline" } }, s); + const line = summaryLine({ ok: false, failure: { message: "asks offline" } }, []); // With no answer there are no rows to count either: the line says the Inbox didn't load. expect(line).toBe("0 in flight · Inbox didn't load · 0 on shift · 0 streams"); expect(line).not.toMatch(/need/); diff --git a/packages/shift-manager/test/project-read-on-notice.test.tsx b/packages/shift-manager/test/project-read-on-notice.test.tsx index 89516a83f9..cb75aeae66 100644 --- a/packages/shift-manager/test/project-read-on-notice.test.tsx +++ b/packages/shift-manager/test/project-read-on-notice.test.tsx @@ -1,131 +1,149 @@ // @vitest-environment happy-dom /** - * A project's entries read on a change, not every 5 s: the view reads the - * project and its workstream entries when it opens, again on a notice of either under - * the project's scope (the org's for a shared project, the user's for a - * private one) and on each Lab read (`readAt`), and on nothing else while push - * covers the page. Wherever push can miss a change, the subscription keeps the - * old 5 s pace. A failed later read keeps the last rows; only a failed first - * read shows. + * A project's workstreams read on a change, not on a clock (FIX-2775): read + * whole by the project's one prefix through react's `useResource` when they + * are drawn, and again only on a notice under that prefix in the project's + * scope (the org's for a shared project, the user's for a private one). A + * notice that names entries reads just those; one that names none reads the + * prefix whole. Nothing reads them on a Lab read. A failed later read keeps + * the last rows; only a failed first read shows. * - * The client's own live read rides a subscription the test drives. + * The client's direct read and its subscription are the test's. */ import { 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"; -import { liveRead } from "@flow-state-dev/client/internal"; -type Opened = { topics: readonly WireTopic[]; pollIntervalMs?: number; onChange: (notice: WireNotice | null) => void; closed: boolean }; +type Opened = { topics: readonly WireTopic[]; onChange: (notice: WireNotice | null) => void; closed: boolean }; const opened: Opened[] = []; -const subscribe = (topics: readonly WireTopic[], options: { onChange: (notice: WireNotice | null) => void; pollIntervalMs?: number }) => { - const entry: Opened = { topics, pollIntervalMs: options.pollIntervalMs, onChange: options.onChange, closed: false }; +const 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) }; }; const hear = (notice: WireNotice) => opened.filter((o) => !o.closed).forEach((o) => o.onChange(notice)); -let title = "Apollo"; let entries: Array<{ storageKey: string; clientData: unknown }> = []; let failing = false; let projectReads = 0; +const prefixes: string[] = []; +const entryReads: string[] = []; +const stored = () => entries.map((entry) => ({ topic: entry.storageKey, storageKey: entry.storageKey, value: entry.clientData, version: 1 })); const client = { userId: "u_1", - // The direct read by scope (FIX-2624): the project by its key, and its entries by one prefix. - resource: ({ pattern }: { pattern: string }) => - pattern === "projects/*" - ? { - entry: () => ({ - read: async () => { - projectReads += 1; - if (failing) throw new Error("unavailable"); - return { value: { id: "apollo", title, ownerUserId: "u_1" }, version: 1 }; - }, - }), - } - : { list: async () => ({ items: entries.map((entry) => ({ topic: entry.storageKey, storageKey: entry.storageKey, value: entry.clientData, version: 1 })) }) }, - live: (topics: readonly WireTopic[], options: Parameters[2]) => liveRead(subscribe as never, topics, options), + // The direct read by scope (FIX-2624): a project's entries by its one prefix. + resource: ({ scope, pattern }: { scope: string; pattern: string }) => ({ + scope, + key: pattern, + list: async () => ({ items: stored() }), + listAll: async (options: { topicPrefix?: string } = {}) => { + projectReads += 1; + prefixes.push(`${scope}:${options.topicPrefix}`); + if (failing) throw new Error("unavailable"); + return stored().filter((entry) => options.topicPrefix === undefined || entry.storageKey.startsWith(options.topicPrefix)); + }, + entry: (storageKey: string) => ({ + read: async () => { + entryReads.push(storageKey); + if (failing) throw new Error("unavailable"); + const found = stored().find((entry) => entry.storageKey === storageKey); + return { value: found?.value ?? null, version: 1 }; + }, + }), + }), + subscribe, }; vi.mock("../src/lib/lab-data", () => ({ useLab: () => ({ client }) })); import { STALE_AFTER_MS } from "@flow-state-dev/workforce/browser"; -import { useProjectRead, type ProjectAddress } from "../src/lib/projects"; +import { useProjectWorkstreams, type ProjectAddress } from "../src/lib/projects"; -type Shown = ReturnType["read"]; +type Shown = ReturnType; const shown: Shown[] = []; -function Probe({ address, readAt }: { address: ProjectAddress; readAt: number }) { - const { read } = useProjectRead(address, true, readAt); - shown.push(read); +function Probe({ address }: { address: ProjectAddress }) { + shown.push(useProjectWorkstreams(address)); return null; } -const titleShown = () => { - const last = shown.at(-1); - return last !== undefined && "value" in last ? last.value?.project.title : undefined; -}; const settle = () => new Promise((r) => setTimeout(r, 50)); -const resource = (scope: "user" | "org", path: string): WireNotice => ({ topic: { scope, resource: path }, kind: "resource" }); +const resource = (scope: "user" | "org", path: string, named?: string[]): WireNotice => ({ + topic: { scope, resource: path }, + kind: "resource", + ...(named === undefined ? {} : { ids: named }), +}); +const entry = (owner: string, id: string, title: string) => { + const at = new Date().toISOString(); + return { + storageKey: `workstreams/apollo/~${owner}/${id}`, + clientData: { title, lead: "researcher", sessionId: null, status: "on-track", due: null, objectives: [], openedAt: at, updatedAt: at, writtenBy: { userId: owner } }, + }; +}; +const titles = () => shown.at(-1)?.value?.entries.map((e) => e.title); beforeEach(() => { opened.splice(0); shown.splice(0); - title = "Apollo"; - entries = []; + entries = [entry("u_1", "research", "Research")]; failing = false; projectReads = 0; + prefixes.splice(0); + entryReads.splice(0); }); afterEach(() => { cleanup(); vi.useRealTimers(); }); -describe("a project's entries", () => { - it("read on open, then only on a notice of the project or its entries under its scope and on a Lab read; at the old pace where push can miss one", async () => { - vi.useFakeTimers({ shouldAdvanceTime: true }); - const view = render(); - await waitFor(() => expect(titleShown()).toBe("Apollo")); +describe("a project's workstreams", () => { + it("read whole by the project's prefix, then only on a notice under it: a named entry is one entry read", async () => { + render(); + await waitFor(() => expect(titles()).toEqual(["Research"])); + expect(prefixes).toEqual(["org:workstreams/apollo/"]); + expect(opened.find((o) => !o.closed)?.topics).toEqual([{ scope: "org" }]); - // Push covers the page: nothing on a clock, and nothing for another project or another collection. - await vi.advanceTimersByTimeAsync(12_000); - hear(resource("org", "projects/zeus")); - hear(resource("org", "workstreams/zeus/u_1/research")); + // Another project, another collection, the projects themselves: nothing is read. + hear(resource("org", "workstreams/zeus")); + hear(resource("org", "workstreams/zeus/~u_1/research", ["workstreams/zeus/~u_1/research"])); hear(resource("org", "inventory/workers/eng")); + hear(resource("org", "projects/apollo")); await settle(); expect(projectReads).toBe(1); - const sub = opened.find((o) => !o.closed); - expect(sub?.topics).toEqual([{ scope: "org" }]); - expect(sub?.pollIntervalMs).toBe(5_000); - - title = "Apollo, renamed"; - hear(resource("org", "workstreams/apollo/u_2/search")); - await waitFor(() => expect(titleShown()).toBe("Apollo, renamed")); - expect(projectReads).toBe(2); - hear(resource("org", "projects/apollo")); - await waitFor(() => expect(projectReads).toBe(3)); + expect(entryReads).toEqual([]); + + // A workstream someone else's turn opened: that one entry is read and drawn. + entries = [...entries, entry("u_2", "search", "Search")]; + hear(resource("org", "workstreams/apollo", ["workstreams/apollo/~u_2/search"])); + await waitFor(() => expect(titles()).toEqual(["Research", "Search"])); + expect(entryReads).toEqual(["workstreams/apollo/~u_2/search"]); + expect(projectReads).toBe(1); - view.rerender(); - await waitFor(() => expect(projectReads).toBe(4)); + // A notice under the project that names none reads it whole. + hear(resource("org", "workstreams/apollo")); + await waitFor(() => expect(projectReads).toBe(2)); }); - it("of a private project are heard under the user's scope", async () => { - render(); - await waitFor(() => expect(titleShown()).toBe("Apollo")); + it("of a private project are read and heard under the user's scope", async () => { + render(); + await waitFor(() => expect(titles()).toEqual(["Research"])); + expect(prefixes).toEqual(["user:workstreams/apollo/"]); expect(opened.find((o) => !o.closed)?.topics).toEqual([{ scope: "user" }]); }); it("keep the last rows when a later read fails; only a failed first read shows", async () => { failing = true; - render(); - await waitFor(() => expect(shown.at(-1)).toHaveProperty("failure")); + render(); + await waitFor(() => expect(shown.at(-1)?.failure).toBeDefined()); + expect(shown.at(-1)?.value).toBeUndefined(); failing = false; - hear(resource("org", "workstreams/apollo/u_1/research")); - await waitFor(() => expect(titleShown()).toBe("Apollo")); + shown.at(-1)!.refresh(); + await waitFor(() => expect(titles()).toEqual(["Research"])); failing = true; const before = projectReads; - hear(resource("org", "projects/apollo")); + hear(resource("org", "workstreams/apollo")); await waitFor(() => expect(projectReads).toBe(before + 1)); await settle(); - expect(titleShown()).toBe("Apollo"); + expect(titles()).toEqual(["Research"]); }); }); @@ -141,11 +159,8 @@ describe("a workstream going quiet", () => { clientData: { title: "Research", lead: "researcher", sessionId: null, status: "on-track", due: null, objectives: [], openedAt: updatedAt, updatedAt, writtenBy: { userId: "u_1" } }, }, ]; - render(); - const value = () => { - const last = shown.at(-1); - return last !== undefined && "value" in last ? last.value : undefined; - }; + render(); + const value = () => shown.at(-1)?.value; await waitFor(() => expect(value()?.entries.map((e) => e.id)).toEqual(["research"])); expect(value()!.entries[0]!.stale).toBe(false); expect(value()!.progress.stale).toEqual([]); @@ -169,11 +184,8 @@ describe("a workstream going quiet", () => { clientData: { title: "Research", lead: "researcher", sessionId: null, status: "on-track", due: null, objectives: [], openedAt: updatedAt, updatedAt, writtenBy: { userId: "u_1" } }, }, ]; - render(); - const value = () => { - const last = shown.at(-1); - return last !== undefined && "value" in last ? last.value : undefined; - }; + render(); + const value = () => shown.at(-1)?.value; await waitFor(() => expect(value()?.entries.map((e) => e.id)).toEqual(["research"])); await vi.advanceTimersByTimeAsync(26 * DAY); expect(value()!.entries[0]!.stale).toBe(false); diff --git a/packages/shift-manager/test/project-setup-view.test.ts b/packages/shift-manager/test/project-setup-view.test.ts index 2ce52899a4..bc857be70c 100644 --- a/packages/shift-manager/test/project-setup-view.test.ts +++ b/packages/shift-manager/test/project-setup-view.test.ts @@ -11,8 +11,8 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { harnessStub } from "@flow-state-dev/harness-manager"; +import { projectSetupView } from "@flow-state-dev/workforce/browser"; import { connect } from "../src/lib/connection"; -import { readProjectSetup } from "../src/lib/projects"; import { inMemoryStores } from "@flow-state-dev/engine"; import { LAB_USERS, openLab, PROJECTS_FLOW, type Lab } from "../teams/devteam/host.mts"; import { serveLab, type ServedLab } from "./helpers/serve-lab"; @@ -22,7 +22,7 @@ afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); }); -describe("readProjectSetup on the DevTeam Lab", () => { +describe("the project setup view on the DevTeam Lab", () => { it("names the projects flow and its project coordinator, read with no session", async () => { const root = mkdtempSync(join(tmpdir(), "sm-project-setup-")); cleanups.push(() => rmSync(root, { recursive: true, force: true })); @@ -36,9 +36,10 @@ describe("readProjectSetup on the DevTeam Lab", () => { const before = await sessionIds(); const client = connect({ userId: LAB_USERS.member.userId, baseUrl: served.baseUrl, bearerToken: LAB_USERS.member.bearer }); - const setup = await readProjectSetup(client); - expect(setup?.flow).toBe(PROJECTS_FLOW); - expect(setup?.projectCoordinator).toEqual(expect.any(String)); + // The read Project's Stream makes (`useProjectSetup`): workforce's view, on the projects flow. + expect(projectSetupView.flow).toBe(PROJECTS_FLOW); + const setup = (await client.view(projectSetupView, {})).value; + expect(setup.projectCoordinator).toEqual(expect.any(String)); expect(await sessionIds()).toEqual(before); }, 60_000); }); diff --git a/packages/shift-manager/test/project-workstreams.test.tsx b/packages/shift-manager/test/project-workstreams.test.tsx index ef09fcc7fa..8bb5045633 100644 --- a/packages/shift-manager/test/project-workstreams.test.tsx +++ b/packages/shift-manager/test/project-workstreams.test.tsx @@ -36,7 +36,16 @@ import { WORKER_ID_STATE_KEY, type RosterEntry } from "@flow-state-dev/workforce import { runAction } from "./helpers/run-action"; import type { Client } from "@flow-state-dev/client"; import { connect, type Connection } from "../src/lib/connection"; -import { readProject, readProjectSetup, type ProjectAddress, type ProjectSetup } from "../src/lib/projects"; +import { readProject, type ProjectAddress } from "../src/lib/projects"; +import { PROJECTS_FLOW, projectSetupView } from "@flow-state-dev/workforce/browser"; + +/** The project setup as these tests drive it: the flow that opens workstreams, and the coordinator the view names. */ +type ProjectSetup = { flow: string; projectCoordinator: string | null }; + +/** The setup, from workforce's view, as Project's Stream reads it (`useProjectSetup`). */ +async function readProjectSetup(client: Client): Promise { + return { flow: PROJECTS_FLOW, projectCoordinator: (await client.view(projectSetupView, {})).value.projectCoordinator }; +} import { createLabReader } from "../src/lib/reads"; import { readSessionItems } from "./helpers/session-reads"; import { createWorkforceClient } from "@flow-state-dev/workforce/browser"; diff --git a/packages/shift-manager/test/reads.test.ts b/packages/shift-manager/test/reads.test.ts index 75a69998c7..7c4dffb3ee 100644 --- a/packages/shift-manager/test/reads.test.ts +++ b/packages/shift-manager/test/reads.test.ts @@ -12,7 +12,7 @@ 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 { withRoster } from "../src/lib/roster"; +import { joinWorkers } from "../src/lib/workers"; import { createWorkforceClient } from "@flow-state-dev/workforce/browser"; import { ROSTER_FLOW, rosterView } from "@flow-state-dev/workforce/browser"; import { COORDINATOR_FLOW } from "@flow-state-dev/workforce"; @@ -404,7 +404,8 @@ describe("asks through a coordinator's delivery (V7)", () => { // Roster and TEAMS join the roster the same way, so the worker is on shift there. const entries = await createWorkforceClient(client).roster(); - const states = workerStates(withRoster(snapshot, { entries }).snapshot); + 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"); }); diff --git a/packages/shift-manager/test/static.test.ts b/packages/shift-manager/test/static.test.ts index 1b649996e8..f126b5c406 100644 --- a/packages/shift-manager/test/static.test.ts +++ b/packages/shift-manager/test/static.test.ts @@ -111,7 +111,7 @@ describe("V8", () => { // Workforce's conversation ledger id isn't exported; the boards' own // action name is, by the task tools' rule (`_`), and the // Lab tests that read a board end to end fail if either drifts. - const { CONVERSATION_BOARD_COLLECTION } = await import("../src/lib/reads"); + const { CONVERSATION_BOARD_COLLECTION } = await import("../src/lib/boards"); const { LIST_TASKS_ACTION } = await import("../src/lib/conversation-tasks"); expect(LIST_TASKS_ACTION).toBe(`listTasks_${CONVERSATION_BOARD_COLLECTION}`); }); @@ -177,8 +177,8 @@ describe("V8", () => { // The abort is one run's stop, through workforce (FIX-2776 D3). expect(readFileSync(join(src, "lib/task.tsx"), "utf8")).toContain("await workforce.stopRun(openRun.sessionId, openRun.requestId)"); // The header's action row changes the task only through the board's own - // actions, the reader's `taskActions`, handed to the registry's row whole. - expect(readFileSync(join(src, "surfaces/TaskFrame.tsx"), "utf8")).toContain("reader.taskActions("); + // actions, orchestration's `inbox.board(...)` (`useBoardActions`), handed to the registry's row whole. + expect(readFileSync(join(src, "surfaces/TaskFrame.tsx"), "utf8")).toContain("useBoardActions("); // Planted: a second write is caught. expect(writes(`await client.flow(f).send("run", {});`)).toHaveLength(1); expect(writes(`await client.flow(f).request(id).abort();`)).toHaveLength(1); From 57700a18a37ad6634e2617d0c525b8ba279a3b15 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 00:34:31 +0000 Subject: [PATCH 06/24] wip: changeset, leftover snapshot fields, tests --- ...shift-manager-directory-follows-changes.md | 7 ++++ .../src/components/TaskBoardMeta.tsx | 4 +- packages/shift-manager/src/components/ui.tsx | 14 ++----- packages/shift-manager/src/lib/lab-data.tsx | 20 +-------- packages/shift-manager/src/lib/task.tsx | 4 +- .../shift-manager/src/surfaces/Sidebar.tsx | 42 +++++++++---------- .../test/ask-card-review-detail.test.tsx | 2 +- .../test/ask-card-review-read.test.tsx | 2 +- .../test/project-workstreams.test.tsx | 10 ++--- packages/shift-manager/test/shell.test.tsx | 8 +++- .../shift-manager/test/teams-roster.test.ts | 16 +++---- 11 files changed, 59 insertions(+), 70 deletions(-) create mode 100644 .changeset/shift-manager-directory-follows-changes.md diff --git a/.changeset/shift-manager-directory-follows-changes.md b/.changeset/shift-manager-directory-follows-changes.md new file mode 100644 index 0000000000..22937375f1 --- /dev/null +++ b/.changeset/shift-manager-directory-follows-changes.md @@ -0,0 +1,7 @@ +--- +"@flow-state-dev/shift-manager": patch +--- + +Shift Manager's directory screens follow changes made elsewhere (FIX-2775). Roster, the sidebar's TEAMS, PROJECTS and counts, Jump to, a project, Messages, Routines, Usage and Settings read the Lab's views and collections directly and stay current on their own: a hire, a new project, a paused routine or a new message from another tab or a worker's turn shows when its read hears it, not on the next whole-Lab read. A worker's on-shift status moves in the same update as the Inbox, so the two always agree. Lists show every row past 200, Retry and R read again what the screen shows, and a Lab that refuses Shift Manager or can't be reached gets the same page and words as before. + +Docs: packages/shift-manager/README.md (the directory screens read live; R reads what the page holds again) diff --git a/packages/shift-manager/src/components/TaskBoardMeta.tsx b/packages/shift-manager/src/components/TaskBoardMeta.tsx index 0aaf8f8808..6f96a47b73 100644 --- a/packages/shift-manager/src/components/TaskBoardMeta.tsx +++ b/packages/shift-manager/src/components/TaskBoardMeta.tsx @@ -66,8 +66,8 @@ function isConversationTaskChange(item: OutputItem): boolean { /** * Watches the conversation's task-list view (`useConversationTasks`): current * on each board change, with the view's own timer where push can miss one. A - * failed read leaves the last answer, or the feed's record. The snapshot hears - * the same moves on its own (`lab-data.tsx`), so what it counts agrees with + * failed read leaves the last answer, or the feed's record. The Inbox view + * hears the same moves on its own (`inbox.ts`), so what it counts agrees with * the card. */ function LiveBoard({ flow, sessionId, boardRef, children }: { flow: string; sessionId: string; boardRef: string; children: ReactNode }) { diff --git a/packages/shift-manager/src/components/ui.tsx b/packages/shift-manager/src/components/ui.tsx index 9d7736672d..42c53ff4fd 100644 --- a/packages/shift-manager/src/components/ui.tsx +++ b/packages/shift-manager/src/components/ui.tsx @@ -2,8 +2,8 @@ * Shift Manager's small shared pieces: the named empty state, a failed section with * Retry, tabs whose selection lives in the URL, a worker's status mark, a feed's * Load earlier, and the parts of design v2's look every screen draws with: a screen's title, - * mono meta text, a task's state square, and the snapshot's *as of* line with - * the dimming its counts take while a read the user asked for runs. + * mono meta text, a task's state square, and the *as of* line that says when + * a screen's reads last landed. * * Every piece is square (v2 draws no rounded corner) and paints only tokens. */ @@ -195,14 +195,8 @@ export function Meta({ } /** - * Classes for counts while a read the user asked for runs (`useLab().asking`): - * dimmed until it lands. A read nobody asked for gives no sign. - */ -export const ASKING_CLASS = "opacity-60 transition-opacity"; - -/** - * When the snapshot was last read, *as of 14:02 · refresh*, never that it is - * live. *refresh* reads the Lab now, as R does. + * When a screen's reads last landed, *as of 14:02 · refresh*, never that they + * are live. *refresh* reads them again now, as R does. */ export function AsOf({ readAt, onRefresh, testId }: { readAt: number; onRefresh: () => void; testId?: string }) { return ( diff --git a/packages/shift-manager/src/lib/lab-data.tsx b/packages/shift-manager/src/lib/lab-data.tsx index e389bd8085..1c6cad41f0 100644 --- a/packages/shift-manager/src/lib/lab-data.tsx +++ b/packages/shift-manager/src/lib/lab-data.tsx @@ -34,12 +34,6 @@ import { FeedHealthContext, worstFeedState, type ReportFeed } from "./feed-healt import { createLabReader, type LabReader, type LabSnapshot } from "./reads"; import { heard, heardSessionIds, SNAPSHOT_POLL_MS, snapshotPaths, snapshotTopics } from "./snapshot-subscribe"; -// FIX-2774 interim: the Inbox, its count, Tasks, the shift summary and a task's asks read the inbox view, -// but the snapshot still carries its own `asks` and `boards`, read by the roster's workers (`derive.ts`, -// `Roster.tsx`) and the task route (`task.tsx`); `inbox.ts`'s selectors mirror `derive.ts`'s over the view meanwhile. -// Until FIX-2775 and FIX-2776 move those screens onto the view and drop the sections, two screens can briefly -// disagree: an ask can show in the Inbox before it shows beside its worker on the roster, and a run with no conversation shows only there. - /** What a surface reads from the provider. */ export type LabData = { /** Who the Lab is read as, and with what credential. */ @@ -66,14 +60,6 @@ export type LabData = { stale: boolean; /** Read everything again, as the user asked: counts dim until it lands. */ refresh(): Promise; - // FIX-2774. - /** An ask in session `sessionId` was answered here: moves {@link answered} once. */ - noteAnswered(sessionId: string): void; - /** - * The session of the latest ask answered here, with a count that moves once - * the answer lands. `undefined` before any answer. - */ - answered: { sessionId: string; count: number } | undefined; }; const LabContext = createContext(null); @@ -88,13 +74,11 @@ export function LabProvider({ connection, children }: { connection: Connection; // Refreshes in a row that couldn't reach the Lab after a good read. The snapshot stays; the read is `lapsed`. const [lapses, setLapses] = useState(0); const [feeds, setFeeds] = useState>(new Map()); - const [answered, setAnswered] = useState(undefined); // The snapshot on screen is a good read of this client's Lab: a later unreachable one doesn't replace it. const loaded = useRef(false); useEffect(() => { loaded.current = false; }, [client]); - const bump = useCallback((sessionId: string) => setAnswered((last) => ({ sessionId, count: (last?.count ?? 0) + 1 })), []); // Only the latest refresh may land: an older one finishing late would draw // a Lab that has moved on. const generation = useRef(0); @@ -181,8 +165,8 @@ export function LabProvider({ connection, children }: { connection: Connection; const stale = isFeedStale(health); const value = useMemo( - () => ({ connection, client, reader, snapshot, refreshing, asking, health, stale, refresh, noteAnswered: bump, answered }), - [connection, client, reader, snapshot, refreshing, asking, health, stale, refresh, bump, answered], + () => ({ connection, client, reader, snapshot, refreshing, asking, health, stale, refresh }), + [connection, client, reader, snapshot, refreshing, asking, health, stale, refresh], ); return ( diff --git a/packages/shift-manager/src/lib/task.tsx b/packages/shift-manager/src/lib/task.tsx index 90831314fb..f1ec4f203d 100644 --- a/packages/shift-manager/src/lib/task.tsx +++ b/packages/shift-manager/src/lib/task.tsx @@ -25,8 +25,8 @@ * workforce's `stopRun` and draws *interrupted* only once the stream reads * `aborted` (the run's record decides). * - * A task's asks are not read here: the screens read them from the snapshot - * until the Inbox's own view answers them. + * A task's asks are not read here: the screens read them from the Inbox + * view (`inbox.ts`). */ import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from "react"; import type { RequestStatus } from "@flow-state-dev/core/types"; diff --git a/packages/shift-manager/src/surfaces/Sidebar.tsx b/packages/shift-manager/src/surfaces/Sidebar.tsx index 43965d496c..42b5a8efcf 100644 --- a/packages/shift-manager/src/surfaces/Sidebar.tsx +++ b/packages/shift-manager/src/surfaces/Sidebar.tsx @@ -328,27 +328,27 @@ function ProjectWorkstreams({ project, route, to }: { project: Project; route: R const here = route.level === "project" && route.projectId === project.id && (route.visibility ?? "shared") === project.visibility; return (
- {entries === undefined && failure !== undefined ? ( -

- Workstreams didn't load.{" "} - -

- ) : entries === undefined ? null : entries.length === 0 ? ( -

- No workstreams -

- ) : ( - entries.map((entry) => ( - - )) - )} + {entries === undefined && failure !== undefined ? ( +

+ Workstreams didn't load.{" "} + +

+ ) : entries === undefined ? null : entries.length === 0 ? ( +

+ No workstreams +

+ ) : ( + entries.map((entry) => ( + + )) + )}
); } 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 = ( +

+ Reading the Lab… +

+); + function Shell({ gaps, devtoolUrl, look }: { gaps: Gaps; devtoolUrl: string | undefined; look: ThemeLook | undefined }) { const { gate, retry } = useGate(); - if (gate.state === "reading") { - return

Reading the Lab…

; - } + 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 Claude-Session: https://claude.ai/code/session_01NczDiGfuuX5mPxVeUwVXfa --- specs/issues/FIX-2775/poc/directory-census/check.mjs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/specs/issues/FIX-2775/poc/directory-census/check.mjs b/specs/issues/FIX-2775/poc/directory-census/check.mjs index 0b56fe00e4..5a137fc7cd 100644 --- a/specs/issues/FIX-2775/poc/directory-census/check.mjs +++ b/specs/issues/FIX-2775/poc/directory-census/check.mjs @@ -87,7 +87,11 @@ for (const [file, owner] of Object.entries(byFile)) { } const wantEntries = BUILT ? { ...EXPECTED.entries, "FIX-2775": 0 } : EXPECTED.entries; for (const [owner, want] of Object.entries(wantEntries)) { - if ((counts[owner] ?? 0) !== want) failures.push(`${owner} holds ${counts[owner] ?? 0} entries, the spec says ${want}`); + const held = counts[owner] ?? 0; + // Built, FIX-2777's entries may shrink but never grow: moving a `reads.ts` name + // to its screen module leaves one definition, so its type entry goes with it. + const ok = BUILT && owner === "FIX-2777" ? held <= want : held === want; + if (!ok) failures.push(`${owner} holds ${held} entries, the spec says ${BUILT && owner === "FIX-2777" ? `at most ${want}` : want}`); } // ── 2. The census ──────────────────────────────────────────────────────── From a449098bf042c9c1750f2a8e9970b4099ddd38f4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 02:05:30 +0000 Subject: [PATCH 23/24] goal(realtime): app-views-read-on-notice verdicts for FIX-2775 PR 3 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NczDiGfuuX5mPxVeUwVXfa --- goals/realtime/app-views-read-on-notice/goal.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/goals/realtime/app-views-read-on-notice/goal.md b/goals/realtime/app-views-read-on-notice/goal.md index 97bc31f9ad..44236dc660 100644 --- a/goals/realtime/app-views-read-on-notice/goal.md +++ b/goals/realtime/app-views-read-on-notice/goal.md @@ -53,3 +53,5 @@ | 2026-11-19 | fix/FIX-2846-fallback-read (pre-push) | n/a | FAIL (red) | Scratch edit: the task-list view given `pollIntervalMs: null`, so the waiting screen has no timer. `c:fallback-reads`: task run link made no read over 6 s | | 2026-11-19 | fix/FIX-2846-fallback-read (pre-push) | n/a | FAIL (expected) | `timer`: `a:idle-0-reads` (task run link 3 board reads while waiting; 4, 4, 7, 14, Talk 7, entries 2, log 2 idle) | | 2026-11-19 | fix/FIX-2846-fallback-read (pre-push) | n/a | FAIL (expected) | `every-kind`: `b:as-short` (102/105/106 reads for 200 items against 5/5/8 for 2) | +| 2026-11-20 | fix-2775-screen-migration on 8ee63f43e0 (FIX-2775 PR 3) | n/a | FAIL | Before R read the screens' own reads: *"a:lab-read: Shift Manager message log read never after a Lab read (bound 1000)"*, and the same for the project entries. The log and the entries no longer re-read on the snapshot's `readAt`, and R read only the directory and the Inbox | +| 2026-11-20 | fix-2775-screen-migration on 25b6080c9f | n/a | PASS | `a:lab-read` now presses Shift Manager's R (`useReadPageAgain`): *"a: read again after a Lab read: Shift Manager message log 0 ms, Shift Manager project entries 0 ms · a: 0 reads over 10 s idle in each of 8 views"* | From 2dc5566edbd4998ed7efa8a8abd2656ebbce1798 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 02:22:40 +0000 Subject: [PATCH 24/24] goal(shift-manager): it-opens-a-lab grades the task frame's title once its row lands (FIX-2775) The frame titles a task by its id until its row is read (a session read and the board's view, 14-22 ms here), and the check read the title as the frame drew. It now waits for a title other than the id, at most 20 s, then grades it against the store as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NczDiGfuuX5mPxVeUwVXfa --- goals/shift-manager/it-opens-a-lab/goal.md | 2 ++ goals/shift-manager/it-opens-a-lab/run.mts | 3 +++ 2 files changed, 5 insertions(+) diff --git a/goals/shift-manager/it-opens-a-lab/goal.md b/goals/shift-manager/it-opens-a-lab/goal.md index 332c7dca3a..faec69c8b8 100644 --- a/goals/shift-manager/it-opens-a-lab/goal.md +++ b/goals/shift-manager/it-opens-a-lab/goal.md @@ -104,3 +104,5 @@ The empty Inbox's running count has no control of its own. No Lab reaches an emp | 2026-11-13 | claude/fix-2627-impl-e-b2 (the workforce kit) | n/a | FAIL (expected) | `queued-shown`: **Tasks equals the store's open rows** (*"the Queued toggle says 0, the store holds 1 queued row(s)"*). | | 2026-11-13 | claude/fix-2627-impl-e-b2 (the workforce kit) | n/a | FAIL (expected) | `static-names`: beside the line above, **TEAMS equals the store's seats** on multi-worker-collab (*"missing [eng.builder, eng.planner, eng.queue], extra [error-reporter, …]"*). | | 2026-11-13 | claude/fix-2627-impl-e-b2 (the workforce kit) | n/a | FAIL (not shown failing on its leg) | `unanswerable-asks`: only the clean run's line above. **an answer lands in the store** never failed. That leg passes when no ask is pending, and a red run doesn't print its evidence, so this run can't say whether one was. | +| 2026-11-20 | fix-2775-screen-migration on a449098bf0 (FIX-2775 PR 3), twice | n/a | FAIL | *"[devteam] Tasks equals the store's open rows: the task frame titles task_… \"task_…\", stored \"Add a release notes page that lists the last three tags.\""*, and the same on multi-worker-collab. The check read the title as the frame drew, before its row landed: the frame titles a task by its id until the row is read | +| 2026-11-20 | same, the title graded once the row lands (`reachTaskFrame` waits for a title other than the id, at most 20 s) | n/a | PASS | The row landed 14 ms and 22 ms after the frame drew. *"Shift Manager built with Vite and served by its command over both goal Labs; every level walked in Chromium and graded against each tree on disk and each store read through the Lab's routes."* | diff --git a/goals/shift-manager/it-opens-a-lab/run.mts b/goals/shift-manager/it-opens-a-lab/run.mts index 7ecae12fc4..60f6e972fa 100644 --- a/goals/shift-manager/it-opens-a-lab/run.mts +++ b/goals/shift-manager/it-opens-a-lab/run.mts @@ -437,6 +437,9 @@ async function checkLab(name: LabName, pages: string, failures: string[], eviden /** The task frame a click just opened: titled as stored, with a panel slot, and every tab drawing. */ const reachTaskFrame = async (row: Store["rows"][string][number], titleLeg: string) => { await page.getByTestId("task-frame").waitFor(); + // The frame draws as the click lands and titles the task by its id until its row is read (one + // session read and the board's view): grade the title once the row has landed, or after 20 s. + await page.waitForFunction((id) => document.querySelector("[data-testid=task-title]")?.textContent !== id, row.id, { timeout: 20_000 }).catch(() => undefined); const title = await page.getByTestId("task-title").textContent(); if (title !== row.title) fail(titleLeg, `the task frame titles ${row.id} "${title}", stored "${row.title}"`); if (!(await visible(page, "task-panel-slot"))) fail("reach", `the task frame for ${row.id} has no panel slot`);