From 0ba38853f00e6f511f33581ee572ca9886c36a35 Mon Sep 17 00:00:00 2001 From: Bastian Huppertz <29781772+BastiHu@users.noreply.github.com> Date: Mon, 19 Oct 2026 16:17:38 +0000 Subject: [PATCH 1/9] fix(fleet): show measured status, asks and problems Use the existing live shell and ledger facts for Fleet rows, with explicit unknown reasons, per-environment read times and frozen stale measurements. Add the Fleet command-palette delegate and keep section and Crew summaries aligned with those measurements. Co-authored-by: GPT-6.1 Sol AI-Model: gpt-6.1-sol AI-Harness: Codex --- FORK.md | 4 +- apps/web/src/components/CommandPalette.tsx | 4 +- apps/web/src/j5/fleet/FleetFacts.tsx | 257 ++++++++++++++++++ apps/web/src/j5/fleet/FleetPage.tsx | 121 ++++----- apps/web/src/j5/fleet/fleet.logic.test.ts | 42 ++- apps/web/src/j5/fleet/fleet.logic.ts | 21 +- apps/web/src/j5/fleet/fleetClient.ts | 7 +- apps/web/src/j5/fleet/fleetPalette.tsx | 23 ++ .../src/j5/fleet/fleetPresentation.test.ts | 115 ++++++++ apps/web/src/j5/fleet/fleetPresentation.ts | 90 ++++++ apps/web/src/j5/fleet/fleetState.ts | 91 +++++++ .../client-runtime/src/j5/fleetFacts.test.ts | 20 ++ packages/client-runtime/src/j5/fleetFacts.ts | 45 ++- 13 files changed, 736 insertions(+), 104 deletions(-) create mode 100644 apps/web/src/j5/fleet/FleetFacts.tsx create mode 100644 apps/web/src/j5/fleet/fleetPalette.tsx create mode 100644 apps/web/src/j5/fleet/fleetPresentation.test.ts create mode 100644 apps/web/src/j5/fleet/fleetPresentation.ts create mode 100644 apps/web/src/j5/fleet/fleetState.ts diff --git a/FORK.md b/FORK.md index fb82e4b7f960b..0873f5580b5ae 100644 --- a/FORK.md +++ b/FORK.md @@ -165,6 +165,8 @@ Landing-order collision: two cases landed as `15.`; resolved by the `b` suffix o 34. Issue #105's cross-environment reads for the project ledger and the human inbox (read models merge in the client; authority stays on each server, per [`docs/j5/product/cross-device.md`](docs/j5/product/cross-device.md)): `packages/contracts/src/environment.ts` adds three optional capability keys beside upstream's existing optional capabilities: `j5ProjectLedger`, which gates every J5 read, and `j5Squadrons` and `j5HumanInbox`, the two keys a J5 server reported while its ledger was keyed by Squadron. `apps/server/src/environment/ServerEnvironment.ts` (with its test) spreads J5-owned `J5_LEDGER_CAPABILITIES` (`packages/contracts/src/j5.ts`) into its descriptor: `j5ProjectLedger` true and the two older keys false. A server that does not report `j5ProjectLedger` true is shown as unsupported in the Inbox, Fleet, Crew, peer and playbook views, which send it no reads; the sidebar's row reads, the archive preflight and the artifact list still ask it and get "Unknown request tag", as they got a 404 before. An older J5 server, which reports `j5Squadrons` true, is refused at connection (case 56). `packages/contracts/package.json` adds the `./j5` export for J5-owned `packages/contracts/src/j5.ts`; `packages/client-runtime/package.json` appends six `./j5/*` exports for the J5-owned read-source, HTTP, and merge modules under `packages/client-runtime/src/j5/`. Those modules reuse upstream's environment registry and per-environment query atoms. `packages/client-runtime/src/state/environmentHttpAuth.ts` exposes `executeAuthenticatedEnvironmentRawHttpRequest` for the one J5 route a client still calls, the read of an artifact's content (case 64 moved every other read onto the socket); it and upstream's typed-group `executeAuthenticatedEnvironmentHttpRequest` both sit on upstream's `executeEnvironmentRequest`, the one credential/retry implementation, and start their relay DPoP root spans through one helper. That core keeps a `url(httpBaseUrl)` callback, which the raw helper passes as is; the typed wrapper builds it from upstream's contract URL builder, so a typed caller signs the URL the client sends. This keeps cookie, bearer, and relay DPoP with one refresh-and-retry shared without assigning J5 routes to an unrelated upstream API group, and no J5 read falls back to the primary environment. The upstream mount that remains (`CommandPalette.logic.ts`'s thread value, `thread::`) carries the environment beside the id so two environments' rows never collide; no new mount or door is added. Environment labels appear only once a read model spans more than one environment. The draft's Squadron environment lock went with the draft chip (the Squadron fold, [#412](https://github.com/Jacksondr5/j5code/issues/412)): `ChatView.tsx`'s three environment-selection doors are upstream's again. Native mobile screens are deferred. On every rebase, verify the capability keys stay optional, the J5 request helper still goes through the shared authenticated transport, and the scoped identities survive in each recorded mount. Fleet measurements (#360) add the `./j5/fleetFacts` export to `packages/client-runtime/package.json`. The J5-owned module derives runtime, dispatch deadlines and labeled activity from the existing raw live shell; its shared Atom owns one future local deadline and performs no RPC reads. Ledger Exchanges, sender delivery alarms and the read time remain in the J5 Fleet read. Keep this subpath on upstream sync. + + The Fleet command-palette entry is J5-owned `apps/web/src/j5/fleet/fleetPalette.tsx`; `apps/web/src/components/CommandPalette.tsx` adds one import, one hook call and appends those items beside the other J5 delegates. Preserve that mount when upstream moves palette actions. Web and desktop use the same Fleet page; native mobile has no Fleet entry or badge. Cases 10, 11 and 12 are retired, so no launch policy remains to verify here. Client permission guards (Jackson's 2026-10-08 decision 23; [#506](https://github.com/Jacksondr5/j5code/issues/506)). J5's protected actions are registered with upstream's guard and its controls read the guard's answer, as upstream's own do: case 64. A session without the operate scope cannot use Crew approve and decline, Crew runtime answers, Stop and Archive crew, Inbox answers, artifact delete, the playbook and persona library mutations or the skill mutations; peering needs `access:write`. The server remains the authority in every case. @@ -772,7 +774,7 @@ explicitly marked. | `apps/web/src/environments/primary/auth.ts` | N | 70 | | `apps/web/src/components/CommandPalette.logic.test.ts` | R | 34 | | `apps/web/src/components/CommandPalette.logic.ts` | R | 34 | -| `apps/web/src/components/CommandPalette.tsx` | A | 42, 71, 75 | +| `apps/web/src/components/CommandPalette.tsx` | A | 42, 71, 75, 34 | | `apps/web/src/components/ConfirmDialogHost.tsx` | R | 22 | | `apps/web/src/components/LegacySidebar.tsx` | R | 21, 22 | | `apps/web/src/components/Sidebar.logic.test.ts` | R | 21 | diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 99e2ca4567de1..b271caa7ac5e1 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -1,5 +1,6 @@ "use client"; +import { useFleetPaletteItems } from "../j5/fleet/fleetPalette"; import { useHighlightsPaletteItems } from "../j5/highlights/highlightsPalette"; import { useSharingPaletteItems } from "../j5/sharing/sharingPalette"; import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility"; @@ -1653,6 +1654,7 @@ function OpenCommandPaletteDialog(props: { projectRef: contextualProjectRef, }); const highlightsPaletteItems = useHighlightsPaletteItems(); + const fleetPaletteItems = useFleetPaletteItems(); const actionItems: Array = []; if (projects.length > 0) { const activeProjectTitle = @@ -2126,7 +2128,7 @@ function OpenCommandPaletteDialog(props: { }, }); - actionItems.push(...sharingPaletteItems, ...highlightsPaletteItems); + actionItems.push(...sharingPaletteItems, ...highlightsPaletteItems, ...fleetPaletteItems); const contextualProjectGroup = (contextualProjectRef diff --git a/apps/web/src/j5/fleet/FleetFacts.tsx b/apps/web/src/j5/fleet/FleetFacts.tsx new file mode 100644 index 0000000000000..782ccc7c46efb --- /dev/null +++ b/apps/web/src/j5/fleet/FleetFacts.tsx @@ -0,0 +1,257 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { FleetDerivedFacts } from "@t3tools/client-runtime/j5/fleetFacts"; +import type { EnvironmentId } from "@t3tools/contracts"; +import type { FleetAgent, FleetAgentFacts } from "@t3tools/contracts/j5"; +import type { ReactNode } from "react"; + +import { Tooltip, TooltipPopup, TooltipTrigger } from "../../components/ui/tooltip"; +import { useNowMinute } from "../../hooks/useNowMinute"; +import { fleetSourcesAtom } from "../state"; +import { + fleetFactsAtom, + fleetLiveRowsAtom, + fleetAgentFactsAtom, + fleetLiveAgentAtom, + fleetEnvironmentLivenessAtom, + fleetReadTimeAtom, +} from "./fleetState"; +import { + fleetCrewSummary, + fleetAgentKey, + fleetStatusLabel, + fleetMinutes, + fleetTime, + fleetProblemLabel, +} from "./fleetPresentation"; + +export function FleetFactHint({ + reason, + children, + className, +}: { + readonly reason: string | undefined; + readonly children: ReactNode; + readonly className?: string; +}) { + if (reason === undefined) return {children}; + return ( + + }>{children} + {reason} + + ); +} + +export function FleetSourceReadout() { + const sources = useAtomValue(fleetSourcesAtom); + const live = useAtomValue(fleetEnvironmentLivenessAtom); + return ( +
+ {sources.sources.map((source) => ( +

+ {source.environmentLabel} · ledger as of{" "} + {source.data?.asOf === undefined ? ( + + ? + + ) : ( + + + + )} + {live.get(source.environmentId) === true + ? " · runtime live" + : " · stale — current facts unavailable"} +

+ ))} +
+ ); +} + +function WaitingMinutes({ since }: { readonly since: string }) { + const minute = useNowMinute(); + return <>{fleetMinutes(since, Date.parse(`${minute}:00Z`))}m; +} + +function AskAge({ openedAt }: { readonly openedAt: string }) { + const minute = useNowMinute(); + return <>{fleetMinutes(openedAt, Date.parse(`${minute}:00Z`))}m ago; +} + +function AskDetails({ + asks, + live, + asOf, +}: { + readonly asks: FleetAgentFacts["asks"]; + readonly live: boolean; + readonly asOf: string | undefined; +}) { + return ( +
+ {( + [ + ["Owes", asks.owed], + ["Awaiting", asks.awaited], + ] as const + ).map(([label, entries]) => ( +
+

+ {label} {entries.length} +

+ {entries.map((ask) => ( +

+ + {ask.counterpartyName ?? ask.counterpartyId} + {ask.counterpartyName === null ? " (name unavailable)" : ""} + + {` · ${ask.intent} · `} + {live ? ( + + ) : ( + `${asOf === undefined ? "age ?" : `${fleetMinutes(ask.openedAt, Date.parse(asOf))}m at last read`} · opened ${fleetTime(ask.openedAt)} (stale)` + )} +

+ ))} +
+ ))} +
+ ); +} + +export function FleetFactCells({ + environmentId, + agent, +}: { + readonly environmentId: EnvironmentId; + readonly agent: FleetAgent; +}) { + const key = fleetAgentKey(environmentId, agent.participantId); + const facts = useAtomValue(fleetAgentFactsAtom(key)); + const live = useAtomValue(fleetLiveAgentAtom(key)); + const asOf = useAtomValue(fleetReadTimeAtom(environmentId)); + const runtime = facts?.runtime; + const activity = facts?.lastActivity; + const unknownReason = "The live Fleet read has not provided this fact."; + return ( + <> + + {runtime === undefined ? ( + "?" + ) : runtime.state === "known" && + runtime.status === "waiting-to-start" && + runtime.since !== null ? ( + <> + Waiting to start ·{" "} + {live ? : `since ${fleetTime(runtime.since)}`} + + ) : ( + fleetStatusLabel(runtime) + )} + {!live ? (stale) : null} + + {facts?.asks === undefined ? ( + + ? + + ) : ( + + }> + Owes {facts.asks.owed.length} · Awaiting {facts.asks.awaited.length} + + + + + + )} + + {activity?.state === "known" ? `${activity.label} ${fleetTime(activity.at)}` : "?"} + + + + ); +} + +function FleetProblems({ + facts, + ledgerKnown, +}: { + readonly facts: FleetDerivedFacts | undefined; + readonly ledgerKnown: boolean; +}) { + const runtimeKnown = facts?.runtime.state === "known"; + if (facts?.problems.length === 0 && runtimeKnown && ledgerKnown) + return ( + No measured problems + ); + return ( + + {facts?.problems.map((problem) => ( + + {fleetProblemLabel(problem)} + + ))} + {!ledgerKnown || !runtimeKnown ? ( + + Problems ? + + ) : null} + + ); +} + +export function FleetCrewSummary({ + environmentId, + agents, +}: { + readonly environmentId: EnvironmentId; + readonly agents: ReadonlyArray; +}) { + const facts = useAtomValue(fleetFactsAtom); + const live = useAtomValue(fleetLiveRowsAtom); + const summary = fleetCrewSummary( + agents.map((agent) => fleetAgentKey(environmentId, agent.participantId)), + facts, + live, + ); + return summary === "" ? null : <> · {summary}; +} diff --git a/apps/web/src/j5/fleet/FleetPage.tsx b/apps/web/src/j5/fleet/FleetPage.tsx index 326e1f84bb55d..8a440468358ef 100644 --- a/apps/web/src/j5/fleet/FleetPage.tsx +++ b/apps/web/src/j5/fleet/FleetPage.tsx @@ -9,7 +9,6 @@ import { ChevronRightIcon, RefreshCwIcon } from "lucide-react"; import { useCallback, useMemo, useState, type ReactNode } from "react"; import { ProjectFavicon } from "../../components/ProjectFavicon"; -import { resolveThreadStatusPill } from "../../components/Sidebar.logic"; import { WorkspaceBreadcrumb, WorkspaceBreadcrumbItem } from "../../components/WorkspaceBreadcrumb"; import { WorkspacePageHeader } from "../../components/WorkspacePageHeader"; import { Badge } from "../../components/ui/badge"; @@ -31,12 +30,7 @@ import { useLogicalProjects } from "../logicalProjects"; import { requestConfirmDialog } from "../../confirmDialog"; import { ArchiveWarningCrewSeats, type ArchiveWarningCrew } from "../a2a/ArchiveWarningContent"; import { archiveCrew } from "../crew/crewArchiveClient"; -import { - classifyCrewSeat, - crewHasRunningSeat, - formatCrewStateSummary, - summarizeCrewState, -} from "../crew/crewState"; +import { classifyCrewSeat, crewHasRunningSeat, summarizeCrewState } from "../crew/crewState"; import { stopCrew } from "../crew/crewStopClient"; import { countFleetProjects, @@ -60,8 +54,13 @@ import { type ScopedFleetLedgerProject, } from "./fleetClient"; +import { fleetSeatStatesAtom } from "./fleetState"; +import { fleetAgentKey } from "./fleetPresentation"; +import { FleetFactCells, FleetSourceReadout, FleetFactHint, FleetCrewSummary } from "./FleetFacts"; + /** Header and rows share one template so the Project, Status, asks, and activity columns line up. */ -const FLEET_GRID_CLASS = "grid grid-cols-[minmax(0,1fr)_11rem_8rem_5rem_7rem] items-center gap-3"; +const FLEET_GRID_CLASS = + "grid grid-cols-[minmax(12rem,1fr)_10rem_11rem_9rem_12rem] items-center gap-3"; type ThreadLookup = ReadonlyMap; @@ -102,6 +101,7 @@ export function FleetPage() { const navigate = useNavigate(); const threads = useThreadShells(); const sources = useAtomValue(fleetDetailSourcesAtom); + const seatStates = useAtomValue(fleetSeatStatesAtom); useFleetDetailRefresh(); const [refreshing, setRefreshing] = useState(false); const projects = useMemo(() => mergeFleetSources(sources), [sources]); @@ -143,15 +143,17 @@ export function FleetPage() { [logicalProjectOf], ); const sections = useMemo(() => { - const partitioned = partitionFleet(projects, (environmentId, threadId) => - threadsByKey.get(scopedThreadKey(scopeThreadRef(environmentId, ThreadId.make(threadId)))), + const partitioned = partitionFleet( + projects, + (environmentId, agent) => + seatStates.get(fleetAgentKey(environmentId, agent.participantId)) ?? "unknown", ); return { ...partitioned, active: orderFleetRowsByProject(partitioned.active, projectOf), settled: orderFleetRowsByProject(partitioned.settled, projectOf), }; - }, [projectOf, projects, threadsByKey]); + }, [projectOf, projects, seatStates]); const projectCount = useMemo( () => countFleetProjects([...sections.active, ...sections.settled], projectOf), [projectOf, sections], @@ -205,7 +207,7 @@ export function FleetPage() { -
+

Fleet

@@ -226,6 +228,7 @@ export function FleetPage() { Refresh
+ {notices.length > 0 ? (
    {notices.map((notice) => ( @@ -299,29 +302,31 @@ function FleetTable( ) { const { rows, ...shared } = props; return ( -
    -
    - Agent - Project - Status - Open asks - Last activity +
    +
    +
    + Agent + Project + Status + Open asks + Last activity +
    +
      + {rows.map(({ project: ledgerProject, node }) => ( + + ))} +
    -
      - {rows.map(({ project: ledgerProject, node }) => ( - - ))} -
    ); } @@ -446,12 +451,14 @@ function FleetNodeRows( {(() => { const seats = crew.members.map((member) => member.row); const state = crewState(seats); - const summary = formatCrewStateSummary(state); return ( <> {crew.members.length} {crew.members.length === 1 ? "seat" : "seats"} - {summary === null ? "" : ` · ${summary}`} + seat.agent)} + /> {crew.playbookRun === null ? null : ( @@ -678,10 +685,7 @@ function FleetRowItem( const { agent } = props.row; const { environmentId } = props.project; const thread = threadFor(props.threadsByKey, environmentId, agent); - const status = thread === undefined ? null : resolveThreadStatusPill({ thread }); const title = thread?.title ?? agent.displayName ?? agent.participantId; - const lastActivity = - thread === undefined ? "?" : formatElapsedDurationLabel(thread.updatedAt) || "just now"; return (
  • ); diff --git a/apps/web/src/j5/fleet/fleet.logic.test.ts b/apps/web/src/j5/fleet/fleet.logic.test.ts index fd65266f39c26..370cb03f8ac7a 100644 --- a/apps/web/src/j5/fleet/fleet.logic.test.ts +++ b/apps/web/src/j5/fleet/fleet.logic.test.ts @@ -2,7 +2,12 @@ import { describe, expect, it, vi } from "vite-plus/test"; import { EnvironmentId } from "@t3tools/contracts"; -import { formatCrewStateSummary, summarizeCrewState, type CrewSeatThread } from "../crew/crewState"; +import { + classifyCrewSeat, + formatCrewStateSummary, + summarizeCrewState, + type CrewSeatThread, +} from "../crew/crewState"; import { buildFleetTree, countFleetAlerts, @@ -305,8 +310,10 @@ describe("fleet sections", () => { const running = shell({ runtime: { status: "running" } }); // Test agents' thread ids are `thread:`, so shells are keyed by participant. const lookupFrom = - (shells: Record) => (_: EnvironmentId, threadId: string) => - shells[threadId.replace(/^thread:/, "")]; + (shells: Record) => (_: EnvironmentId, agent: FleetAgent) => + classifyCrewSeat( + agent.threadId === null ? undefined : shells[agent.threadId.replace(/^thread:/, "")], + ); const project = (id: string, agents: ReadonlyArray) => ({ id: `project-${id}`, title: id, @@ -457,8 +464,10 @@ describe("roster seats without thread facts", () => { { ...solo, environmentId }, { ...solo, environmentId: other }, ], - (env, threadId) => - env === environmentId && threadId === "thread:x" ? settledShell : undefined, + (env, row) => + classifyCrewSeat( + env === environmentId && row.threadId === "thread:x" ? settledShell : undefined, + ), ); expect(sections.settled.map((row) => row.project.environmentId)).toEqual([environmentId]); expect(sections.active.map((row) => row.project.environmentId)).toEqual([other]); @@ -516,3 +525,26 @@ describe("fleet rows by project", () => { expect(countFleetProjects([], projectOf)).toBe(0); }); }); + +describe("Fleet measured section states", () => { + it("keeps whole placement trees Active when any live measurement is unknown or waiting", () => { + const environmentId = EnvironmentId.make("facts"); + const project = { + id: "p", + title: "P", + crews: [], + environmentId, + agents: [agent("parent"), agent("child", { placementParentId: "parent" })], + }; + const section = (child: "settled" | "running" | "unknown") => + partitionFleet([project], (_, row) => (row.participantId === "parent" ? "settled" : child)); + expect(section("settled").settledAgentCount).toBe(2); + for (const child of ["running", "unknown"] as const) { + expect(section(child).settledAgentCount).toBe(0); + expect(section(child).active.map((entry) => entry.node.row.agent.participantId)).toEqual([ + "parent", + ]); + expect(section(child).active[0]?.node.children[0]?.row.agent.participantId).toBe("child"); + } + }); +}); diff --git a/apps/web/src/j5/fleet/fleet.logic.ts b/apps/web/src/j5/fleet/fleet.logic.ts index 64c770040eb89..bd46a5e52cbf1 100644 --- a/apps/web/src/j5/fleet/fleet.logic.ts +++ b/apps/web/src/j5/fleet/fleet.logic.ts @@ -2,7 +2,7 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { ThreadId, type EnvironmentId, type ScopedThreadRef } from "@t3tools/contracts"; import type { J5ReadRevisions } from "@t3tools/contracts/j5"; -import { classifyCrewSeat, type CrewSeatState, type CrewSeatThread } from "../crew/crewState"; +import type { CrewSeatState } from "../crew/crewState"; import type { FleetAgent, FleetCrew, FleetLedgerProject } from "./fleetClient"; /** One rendered row of the Roster tree. Crew members hang under their Captain as one unit. */ @@ -176,12 +176,6 @@ export interface FleetSections CrewSeatThread | undefined; - /** Every agent in a subtree: the node itself, its plain children, and every Crew seat beneath it. */ export function* fleetNodeAgents(node: FleetNode): Generator { yield node.row.agent; @@ -191,8 +185,7 @@ export function* fleetNodeAgents(node: FleetNode): Generator { /** * A subtree is settled only when every agent in it, Crew seats included, reads as settled from - * upstream's settle mechanic on its thread shell (`settledAt` / `settledOverride`, the facts - * `classifyCrewSeat` reads). One running, failed, needs-you, idle, or unknown agent anywhere + * the same measured runtime and settle facts its row displays. One running, failed, needs-you, idle, or unknown agent anywhere * beneath the root keeps the whole subtree in Active: a settled Captain whose seats still work is * not done, and an agent the client cannot see is not assumed done. Idle is not settled; nothing * is inferred from silence. @@ -215,16 +208,16 @@ export const isSettledFleetNode = ( */ export function partitionFleet< S extends FleetLedgerProject & { readonly environmentId: EnvironmentId }, ->(projects: ReadonlyArray, shellFor: FleetShellLookup): FleetSections { +>( + projects: ReadonlyArray, + measuredState: (environmentId: EnvironmentId, agent: FleetAgent) => CrewSeatState, +): FleetSections { const active: Array> = []; const settled: Array> = []; let settledAgentCount = 0; let agentCount = 0; for (const ledgerProject of projects) { - const classify = (agent: FleetAgent) => - classifyCrewSeat( - agent.threadId === null ? undefined : shellFor(ledgerProject.environmentId, agent.threadId), - ); + const classify = (agent: FleetAgent) => measuredState(ledgerProject.environmentId, agent); agentCount += ledgerProject.agents.length; for (const node of buildFleetTree(ledgerProject)) { if (isSettledFleetNode(node, classify)) { diff --git a/apps/web/src/j5/fleet/fleetClient.ts b/apps/web/src/j5/fleet/fleetClient.ts index de39db9a37595..ca83f5e74b7f6 100644 --- a/apps/web/src/j5/fleet/fleetClient.ts +++ b/apps/web/src/j5/fleet/fleetClient.ts @@ -17,6 +17,7 @@ import { refreshJ5Sources, } from "../state"; import { createVisibleRefreshHook } from "../useVisibleRefresh"; +import { fleetFactsAtom } from "./fleetState"; import { createFleetRowRefresher, fleetInvolvedThreadRefs } from "./fleet.logic"; export type { FleetAgent, FleetCrew, FleetResponse } from "@t3tools/contracts/j5"; @@ -42,7 +43,10 @@ export const mergeFleetSources = ( /** The page's read, retired Crews and rosters included. */ export const refreshFleet = () => - refreshJ5Sources(fleetDetailSourcesAtom, fleetDetailQueryAtom, { force: true }); + Promise.all([ + refreshJ5Sources(fleetDetailSourcesAtom, fleetDetailQueryAtom, { force: true }), + refreshJ5Sources(fleetSourcesAtom, fleetQueryAtom, { force: true }), + ]); const refreshFleetRows = createFleetRowRefresher({ memberships: refreshCrewMembershipRows, @@ -102,6 +106,7 @@ const useFleetFocusRefresh = createVisibleRefreshHook(() => { export function useFleetRefresh() { useFleetFocusRefresh(); useEffect(followFleetRows, []); + useEffect(() => appAtomRegistry.mount(fleetFactsAtom), []); } /** The Fleet page's own refresh on focus while it is open; retired Crews ride only here. */ diff --git a/apps/web/src/j5/fleet/fleetPalette.tsx b/apps/web/src/j5/fleet/fleetPalette.tsx new file mode 100644 index 0000000000000..516f054f69f3e --- /dev/null +++ b/apps/web/src/j5/fleet/fleetPalette.tsx @@ -0,0 +1,23 @@ +import { useNavigate } from "@tanstack/react-router"; +import { RadarIcon } from "lucide-react"; + +import { + ITEM_ICON_CLASS, + type CommandPaletteActionItem, +} from "../../components/CommandPalette.logic"; + +export function useFleetPaletteItems(): ReadonlyArray { + const navigate = useNavigate(); + return [ + { + kind: "action", + value: "action:j5-fleet", + title: "Open fleet", + searchTerms: ["fleet", "agents", "crews", "roster"], + icon: , + run: async () => { + await navigate({ to: "/fleet" }); + }, + }, + ]; +} diff --git a/apps/web/src/j5/fleet/fleetPresentation.test.ts b/apps/web/src/j5/fleet/fleetPresentation.test.ts new file mode 100644 index 0000000000000..eca40b0b8fc0e --- /dev/null +++ b/apps/web/src/j5/fleet/fleetPresentation.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, it } from "vite-plus/test"; +import type { FleetDerivedFacts } from "@t3tools/client-runtime/j5/fleetFacts"; +import type { FleetRuntimeFact } from "@t3tools/contracts/j5"; +import { + fleetCrewSummary, + fleetAgentKey, + fleetMinutes, + fleetProblemLabel, + fleetSeatState, + fleetSourceIsLive, + fleetStatusLabel, +} from "./fleetPresentation"; + +const at = "2026-10-19T10:00:00.000Z"; +const runtime = ( + status: Extract["status"], + settled = false, +): FleetRuntimeFact => ({ state: "known", status, settled, since: at }); +const facts = (value: FleetRuntimeFact): FleetDerivedFacts => ({ + runtime: value, + asks: undefined, + lastActivity: { state: "unknown", reason: "old server" }, + problems: [], +}); + +describe("Fleet presentation", () => { + it("uses runtime vocabulary and makes old or unavailable measurements explicit", () => { + for (const [status, label] of [ + ["working", "Working"], + ["waiting", "Waiting"], + ["approval", "Approval"], + ["input", "Input"], + ["failed", "Failed"], + ["waiting-to-start", "Waiting to start"], + ] as const) + expect(fleetStatusLabel(runtime(status))).toBe(label); + expect(fleetStatusLabel(runtime("idle"))).toMatch(/^Idle since /); + expect(fleetStatusLabel(runtime("idle", true))).toBe("Settled"); + expect(fleetStatusLabel({ state: "unknown", reason: "missing runtime" })).toBe("?"); + }); + + it("keeps stale or unknown agents Active and respects background Waiting over a settle mark", () => { + expect(fleetSeatState(facts(runtime("idle", true)), true)).toBe("settled"); + expect(fleetSeatState(facts(runtime("waiting")), true)).toBe("running"); + expect(fleetSeatState(facts(runtime("failed")), true)).toBe("failed"); + expect(fleetSeatState(facts(runtime("idle", true)), false)).toBe("unknown"); + expect(fleetSeatState(facts({ state: "unknown", reason: "old server" }), true)).toBe("unknown"); + expect(fleetSeatState(undefined, true)).toBe("unknown"); + }); + + it("summarizes Crews from the same measured states as their rows", () => { + const measured = new Map([ + ["waiting", facts(runtime("waiting"))], + ["settled", facts(runtime("idle", true))], + ]); + expect( + fleetCrewSummary( + ["waiting", "settled"], + measured, + new Map([ + ["waiting", true], + ["settled", true], + ]), + ), + ).toBe("1 waiting · 1 settled"); + expect(fleetCrewSummary(["waiting", "settled"], measured, new Map())).toBe("2 unknown"); + }); + + it("requires both a current ledger and a live shell stream", () => { + expect(fleetSourceIsLive({ connected: true, status: "ready" }, "live")).toBe(true); + for (const status of ["offline", "error", "loading", "unsupported"] as const) + expect(fleetSourceIsLive({ connected: true, status }, "live")).toBe(false); + expect(fleetSourceIsLive({ connected: false, status: "ready" }, "live")).toBe(false); + for (const shell of ["cached", "synchronizing", "empty"]) + expect(fleetSourceIsLive({ connected: true, status: "ready" }, shell)).toBe(false); + }); + + it("keeps environment-qualified ids collision-free and freezes ages at a supplied observation", () => { + expect(fleetAgentKey("a:b", "c")).not.toBe(fleetAgentKey("a", "b:c")); + expect(fleetAgentKey("first", "agent")).not.toBe(fleetAgentKey("second", "agent")); + expect(fleetMinutes(at, Date.parse(at) + 299_999)).toBe(4); + expect(fleetMinutes(at, Date.parse(at) + 300_000)).toBe(5); + }); + + it("labels every measured problem and never invents a failure time or a missing reason", () => { + expect(fleetProblemLabel({ kind: "failed-run", runId: "r", at: null })).toBe( + "Latest run failed · time unavailable", + ); + expect(fleetProblemLabel({ kind: "dispatch-overdue", runId: "r", at })).toMatch( + /^Run not dispatched · requested /, + ); + expect( + fleetProblemLabel({ + kind: "delivery-failed", + messageId: "m", + receiverId: "agent:unknown", + receiverName: null, + at, + reason: null, + exchangeOpen: false, + }), + ).toMatch(/^Delivery failed · to agent:unknown · .* · reason unavailable$/); + expect( + fleetProblemLabel({ + kind: "delivery-failed", + messageId: "m", + receiverId: "agent:known", + receiverName: "Builder", + at, + reason: "Transport unavailable", + exchangeOpen: true, + }), + ).toContain("to Builder"); + }); +}); diff --git a/apps/web/src/j5/fleet/fleetPresentation.ts b/apps/web/src/j5/fleet/fleetPresentation.ts new file mode 100644 index 0000000000000..040e047aca995 --- /dev/null +++ b/apps/web/src/j5/fleet/fleetPresentation.ts @@ -0,0 +1,90 @@ +import type { FleetDerivedFacts } from "@t3tools/client-runtime/j5/fleetFacts"; +import type { J5ReadSource } from "@t3tools/client-runtime/j5/readSources"; +import type { FleetProblem, FleetRuntimeFact } from "@t3tools/contracts/j5"; +import type { CrewSeatState } from "../crew/crewState"; + +export const fleetAgentKey = (environmentId: string, participantId: string) => + `${environmentId.length}:${environmentId}${participantId}`; + +export const fleetSourceIsLive = ( + source: Pick, "connected" | "status">, + shellStatus: string, +) => source.connected && source.status === "ready" && shellStatus === "live"; + +export const fleetTime = (at: string | null | undefined) => + at == null + ? "?" + : new Date(at).toLocaleTimeString([], { + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }); + +export const fleetMinutes = (since: string, now: number) => + Math.max(0, Math.floor((now - Date.parse(since)) / 60_000)); + +export const fleetStatusLabel = (runtime: FleetRuntimeFact) => { + if (runtime.state === "unknown") return "?"; + if (runtime.settled) return "Settled"; + switch (runtime.status) { + case "working": + return "Working"; + case "waiting": + return "Waiting"; + case "approval": + return "Approval"; + case "input": + return "Input"; + case "failed": + return "Failed"; + case "waiting-to-start": + return "Waiting to start"; + case "idle": + return `Idle since ${fleetTime(runtime.since)}`; + } +}; + +export const fleetSeatState = ( + facts: FleetDerivedFacts | undefined, + live: boolean, +): CrewSeatState => { + if (!live || facts?.runtime.state !== "known") return "unknown"; + const { runtime } = facts; + if (runtime.status === "failed") return "failed"; + if (runtime.status === "approval" || runtime.status === "input") return "needs-you"; + if (runtime.settled) return "settled"; + if (runtime.status === "idle") return "idle"; + return "running"; +}; + +export const fleetProblemLabel = (problem: FleetProblem) => { + switch (problem.kind) { + case "failed-run": + return `Latest run failed · ${problem.at === null ? "time unavailable" : fleetTime(problem.at)}`; + case "dispatch-overdue": + return `Run not dispatched · requested ${fleetTime(problem.at)}`; + case "delivery-failed": + return `Delivery failed · to ${problem.receiverName ?? problem.receiverId} · ${fleetTime(problem.at)} · ${problem.reason ?? "reason unavailable"}`; + } +}; + +export const fleetCrewSummary = ( + keys: ReadonlyArray, + facts: ReadonlyMap, + live: ReadonlyMap, +) => { + const counts = new Map(); + for (const key of keys) { + const runtime = facts.get(key)?.runtime; + const label = + live.get(key) !== true || runtime?.state !== "known" + ? "unknown" + : runtime.settled + ? "settled" + : runtime.status === "waiting-to-start" + ? "waiting to start" + : runtime.status; + counts.set(label, (counts.get(label) ?? 0) + 1); + } + return [...counts].map(([label, count]) => `${count} ${label}`).join(" · "); +}; diff --git a/apps/web/src/j5/fleet/fleetState.ts b/apps/web/src/j5/fleet/fleetState.ts new file mode 100644 index 0000000000000..0fbf6ae7162e0 --- /dev/null +++ b/apps/web/src/j5/fleet/fleetState.ts @@ -0,0 +1,91 @@ +import { createFleetFactsAtom, type FleetFactRow } from "@t3tools/client-runtime/j5/fleetFacts"; +import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { ThreadId, type EnvironmentId } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; +import * as Option from "effect/Option"; + +import { environmentShell } from "../../state/shell"; +import { environmentThreadShells } from "../../state/threads"; +import { fleetSourcesAtom } from "../state"; +import { fleetAgentKey, fleetSourceIsLive, fleetSeatState } from "./fleetPresentation"; + +export const fleetEnvironmentLivenessAtom = Atom.make( + (get) => + new Map( + get(fleetSourcesAtom).sources.map((source) => { + const shell = get(environmentShell.stateValueAtom(source.environmentId)); + return [ + source.environmentId, + fleetSourceIsLive(source, shell.status) && Option.isNone(shell.error), + ] as const; + }), + ), +); + +const fleetFactRowsAtom = Atom.make((get): ReadonlyArray => { + const threads = new Map( + get(environmentThreadShells.threadShellsAtom).map((thread) => [ + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), + thread, + ]), + ); + const environments = get(fleetEnvironmentLivenessAtom); + return get(fleetSourcesAtom).sources.flatMap((source) => { + const live = environments.get(source.environmentId) === true; + return (source.data?.projects ?? []).flatMap((project) => + project.agents.map((agent) => { + const thread = + agent.threadId === null + ? undefined + : threads.get( + scopedThreadKey( + scopeThreadRef(source.environmentId, ThreadId.make(agent.threadId)), + ), + ); + return { + key: fleetAgentKey(source.environmentId, agent.participantId), + shell: thread?.source, + pendingSubagentRequest: thread?.pendingSubagentRequest, + ledger: agent.facts, + live, + }; + }), + ); + }); +}); + +export const fleetFactsAtom = createFleetFactsAtom(fleetFactRowsAtom); +export const fleetAgentFactsAtom = Atom.family((key: string) => + Atom.make((get) => get(fleetFactsAtom).get(key)), +); +export const fleetLiveRowsAtom = Atom.make( + (get) => new Map(get(fleetFactRowsAtom).map((row) => [row.key, row.live])), +); +export const fleetLiveAgentAtom = Atom.family((key: string) => + Atom.make((get) => get(fleetLiveRowsAtom).get(key) === true), +); + +/** Only classification changes rebuild the placement sections; activity and elapsed time do not. */ +export const fleetSeatStatesAtom = Atom.make((get) => { + const live = get(fleetLiveRowsAtom); + const states = new Map( + [...get(fleetFactsAtom)].map(([key, facts]) => [ + key, + fleetSeatState(facts, live.get(key) === true), + ]), + ); + const previous = Option.getOrUndefined(get.self()); + return previous !== undefined && + previous.size === states.size && + [...states].every(([key, state]) => previous.get(key) === state) + ? previous + : states; +}); + +export const fleetReadTimeAtom = Atom.family((environmentId: EnvironmentId) => + Atom.make( + (get) => + get(fleetSourcesAtom).sources.find((source) => source.environmentId === environmentId)?.data + ?.asOf, + ), +); diff --git a/packages/client-runtime/src/j5/fleetFacts.test.ts b/packages/client-runtime/src/j5/fleetFacts.test.ts index 6338a86b04d78..1ed95c1324c50 100644 --- a/packages/client-runtime/src/j5/fleetFacts.test.ts +++ b/packages/client-runtime/src/j5/fleetFacts.test.ts @@ -168,6 +168,22 @@ describe("Fleet runtime measurements", () => { } }); + it("preserves native child approval and input measurements on the parent row", () => { + const source = shell({ + status: "running", + activityRunStatus: "running", + latestRunStartedAt: date, + }); + expect( + deriveFleetFacts({ shell: source, ledger, pendingSubagentRequest: "approval", now }).facts + .runtime, + ).toMatchObject({ status: "approval" }); + expect( + deriveFleetFacts({ shell: source, ledger, pendingSubagentRequest: "user_input", now }).facts + .runtime, + ).toMatchObject({ status: "input" }); + }); + it("clears failed-latest-run when a healthy latest run replaces it", () => { const failed = shell({ status: "failed", @@ -175,6 +191,10 @@ describe("Fleet runtime measurements", () => { latestRunStartedAt: date, latestRunCompletedAt: date, }); + expect( + derive({ ...failed, pendingBackgroundTasks: [{ kind: "monitor", taskId: "watch" }] }).facts + .runtime, + ).toMatchObject({ status: "failed" }); expect(derive(failed).facts.problems).toEqual([{ kind: "failed-run", runId: "r", at }]); expect(derive({ ...failed, latestRunCompletedAt: null }).facts.problems).toEqual([ { kind: "failed-run", runId: "r", at: null }, diff --git a/packages/client-runtime/src/j5/fleetFacts.ts b/packages/client-runtime/src/j5/fleetFacts.ts index a905a2ee9b335..c1a73ceb5bde9 100644 --- a/packages/client-runtime/src/j5/fleetFacts.ts +++ b/packages/client-runtime/src/j5/fleetFacts.ts @@ -25,6 +25,7 @@ export interface FleetDerivedFacts { export const deriveFleetFacts = (input: { readonly shell: OrchestrationV2ThreadShell | undefined; readonly ledger: FleetAgentFacts | undefined; + readonly pendingSubagentRequest?: "approval" | "user_input" | null | undefined; readonly now: number; }): { readonly facts: FleetDerivedFacts; readonly nextDeadline?: number } => { const { shell } = input; @@ -101,25 +102,33 @@ export const deriveFleetFacts = (input: { ? { state: "unknown", reason: "This environment does not report run timestamps." } : { state: "known", ...latest }; const activity = shell.activityRunStatus ?? shell.status; + const approval = + input.pendingSubagentRequest === "approval" || + (shell.pendingRuntimeRequest !== null && + shell.pendingRuntimeRequest.kind !== "user_input" && + shell.pendingRuntimeRequest.kind !== "auth_refresh"); + const needsInput = + input.pendingSubagentRequest === "user_input" || + shell.pendingRuntimeRequest?.kind === "user_input"; const status = undispatched ? "waiting-to-start" - : shell.pendingRuntimeRequest !== null - ? shell.pendingRuntimeRequest.kind === "user_input" + : approval + ? "approval" + : needsInput ? "input" - : shell.pendingRuntimeRequest.kind === "auth_refresh" + : shell.pendingRuntimeRequest?.kind === "auth_refresh" ? "waiting" - : "approval" - : activity === "running" - ? "working" - : activity === "waiting" - ? "waiting" - : activity === "preparing" || activity === "starting" || shell.status === "queued" - ? "waiting" - : backgroundWorkHoldsCompletion(shell.pendingBackgroundTasks ?? []) + : activity === "running" + ? "working" + : activity === "waiting" ? "waiting" - : shell.status === "failed" - ? "failed" - : "idle"; + : activity === "preparing" || activity === "starting" || shell.status === "queued" + ? "waiting" + : shell.status === "failed" + ? "failed" + : backgroundWorkHoldsCompletion(shell.pendingBackgroundTasks ?? []) + ? "waiting" + : "idle"; const unknownRuntimeReason = missingRunTimes ? "This environment does not report run timestamps." : otherRunInProgress && @@ -159,6 +168,7 @@ export interface FleetFactRow { readonly shell: OrchestrationV2ThreadShell | undefined; readonly ledger: FleetAgentFacts | undefined; readonly live: boolean; + readonly pendingSubagentRequest?: "approval" | "user_input" | null | undefined; } /** Shared by every consumer in one registry. Only a future dispatch boundary schedules work. */ @@ -186,7 +196,12 @@ export const createFleetFactsAtom = (rows: Atom.Atom ); continue; } - const result = deriveFleetFacts({ shell: row.shell, ledger: row.ledger, now }); + const result = deriveFleetFacts({ + shell: row.shell, + ledger: row.ledger, + pendingSubagentRequest: row.pendingSubagentRequest, + now, + }); const cached = previous?.get(row.key); facts.set( row.key, From 999f37b6db77744cc265d218809035f74b2de189 Mon Sep 17 00:00:00 2001 From: Bastian Huppertz <29781772+BastiHu@users.noreply.github.com> Date: Mon, 19 Oct 2026 16:20:54 +0000 Subject: [PATCH 2/9] fix(fleet): keep dates explicit in measured timestamps Use the existing absolute timestamp formatter for every Fleet time, including the date and year, so stale measurements never depend on midnight clocks. Omit the empty problems line while preserving unknowns and actual problems. Co-authored-by: GPT-6.1 Sol AI-Model: gpt-6.1-sol AI-Harness: Codex --- apps/web/src/j5/fleet/FleetFacts.tsx | 5 +-- .../src/j5/fleet/fleetPresentation.test.ts | 31 ++++++++++++++++++- apps/web/src/j5/fleet/fleetPresentation.ts | 9 ++---- 3 files changed, 33 insertions(+), 12 deletions(-) diff --git a/apps/web/src/j5/fleet/FleetFacts.tsx b/apps/web/src/j5/fleet/FleetFacts.tsx index 782ccc7c46efb..b7193a822ed2d 100644 --- a/apps/web/src/j5/fleet/FleetFacts.tsx +++ b/apps/web/src/j5/fleet/FleetFacts.tsx @@ -203,10 +203,7 @@ function FleetProblems({ readonly ledgerKnown: boolean; }) { const runtimeKnown = facts?.runtime.state === "known"; - if (facts?.problems.length === 0 && runtimeKnown && ledgerKnown) - return ( - No measured problems - ); + if (facts?.problems.length === 0 && runtimeKnown && ledgerKnown) return null; return ( {facts?.problems.map((problem) => ( diff --git a/apps/web/src/j5/fleet/fleetPresentation.test.ts b/apps/web/src/j5/fleet/fleetPresentation.test.ts index eca40b0b8fc0e..5504114a303e3 100644 --- a/apps/web/src/j5/fleet/fleetPresentation.test.ts +++ b/apps/web/src/j5/fleet/fleetPresentation.test.ts @@ -1,10 +1,11 @@ -import { describe, expect, it } from "vite-plus/test"; +import { describe, expect, it, vi } from "vite-plus/test"; import type { FleetDerivedFacts } from "@t3tools/client-runtime/j5/fleetFacts"; import type { FleetRuntimeFact } from "@t3tools/contracts/j5"; import { fleetCrewSummary, fleetAgentKey, fleetMinutes, + fleetTime, fleetProblemLabel, fleetSeatState, fleetSourceIsLive, @@ -39,6 +40,34 @@ describe("Fleet presentation", () => { expect(fleetStatusLabel({ state: "unknown", reason: "missing runtime" })).toBe("?"); }); + it("keeps prior-day dates explicit without advancing stale timestamps at midnight", () => { + vi.useFakeTimers(); + try { + vi.setSystemTime(new Date("2026-10-19T10:00:00.000Z")); + const prior = "2026-10-18T10:00:00.000Z"; + const idle = { ...runtime("idle"), since: prior }; + const label = fleetStatusLabel(idle); + expect(label).toContain("18th October 2026"); + expect(fleetTime(prior)).toContain("18th October 2026"); + expect( + fleetProblemLabel({ + kind: "delivery-failed", + messageId: "m", + receiverId: "a", + receiverName: "Agent", + at: prior, + reason: "offline", + exchangeOpen: false, + }), + ).toContain("18th October 2026"); + vi.advanceTimersByTime(3 * 86_400_000); + expect(fleetStatusLabel(idle)).toBe(label); + expect(vi.getTimerCount()).toBe(0); + } finally { + vi.useRealTimers(); + } + }); + it("keeps stale or unknown agents Active and respects background Waiting over a settle mark", () => { expect(fleetSeatState(facts(runtime("idle", true)), true)).toBe("settled"); expect(fleetSeatState(facts(runtime("waiting")), true)).toBe("running"); diff --git a/apps/web/src/j5/fleet/fleetPresentation.ts b/apps/web/src/j5/fleet/fleetPresentation.ts index 040e047aca995..bc513d43046b9 100644 --- a/apps/web/src/j5/fleet/fleetPresentation.ts +++ b/apps/web/src/j5/fleet/fleetPresentation.ts @@ -1,6 +1,7 @@ import type { FleetDerivedFacts } from "@t3tools/client-runtime/j5/fleetFacts"; import type { J5ReadSource } from "@t3tools/client-runtime/j5/readSources"; import type { FleetProblem, FleetRuntimeFact } from "@t3tools/contracts/j5"; +import { formatChatTimestampTooltip } from "../../timestampFormat"; import type { CrewSeatState } from "../crew/crewState"; export const fleetAgentKey = (environmentId: string, participantId: string) => @@ -12,13 +13,7 @@ export const fleetSourceIsLive = ( ) => source.connected && source.status === "ready" && shellStatus === "live"; export const fleetTime = (at: string | null | undefined) => - at == null - ? "?" - : new Date(at).toLocaleTimeString([], { - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - }); + at == null ? "?" : formatChatTimestampTooltip(at, "locale") || "?"; export const fleetMinutes = (since: string, now: number) => Math.max(0, Math.floor((now - Date.parse(since)) / 60_000)); From cb5ea76c6d8811a60ce5ffdf3007bb496b8b183e Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 23 Oct 2026 14:03:59 +0000 Subject: [PATCH 3/9] fix(fleet): make row fact details keyboard accessible --- apps/web/package.json | 1 + .../src/j5/fleet/FleetFacts.keyboard.test.tsx | 197 ++++++++++++++++++ apps/web/src/j5/fleet/FleetFacts.tsx | 114 +++++++++- apps/web/src/j5/fleet/FleetPage.tsx | 15 +- pnpm-lock.yaml | 3 + 5 files changed, 325 insertions(+), 5 deletions(-) create mode 100644 apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx diff --git a/apps/web/package.json b/apps/web/package.json index e048338dfa236..049fc7ba7b0a6 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -78,6 +78,7 @@ "@effect/vitest": "catalog:", "@tailwindcss/vite": "^4.0.0", "@tanstack/router-plugin": "^1.161.0", + "@testing-library/user-event": "14.6.7", "@types/compression": "^1.8.1", "@types/culori": "^4.0.1", "@types/mdast": "^4.0.4", diff --git a/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx b/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx new file mode 100644 index 0000000000000..a4a242aa71f97 --- /dev/null +++ b/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx @@ -0,0 +1,197 @@ +// @vitest-environment jsdom + +import type { FleetDerivedFacts } from "@t3tools/client-runtime/j5/fleetFacts"; +import { EnvironmentId } from "@t3tools/contracts"; +import type { FleetAgent } from "@t3tools/contracts/j5"; +import userEvent from "@testing-library/user-event"; +import { act, type ReactNode } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test"; + +const state = vi.hoisted(() => ({ + facts: undefined as FleetDerivedFacts | undefined, + live: true, + asOf: "2026-10-23T12:05:00Z", + minute: vi.fn(() => "2026-10-23T12:10"), +})); +vi.mock("@effect/atom-react", () => ({ + useAtomValue: (atom: { read: () => unknown }) => atom.read(), +})); +vi.mock("./fleetState", () => ({ + fleetAgentFactsAtom: () => ({ read: () => state.facts }), + fleetLiveAgentAtom: () => ({ read: () => state.live }), + fleetReadTimeAtom: () => ({ read: () => state.asOf }), +})); +vi.mock("../../hooks/useNowMinute", () => ({ useNowMinute: state.minute })); +vi.mock("../../components/ui/tooltip", () => ({ + Tooltip: ({ children }: { children: ReactNode }) => children, + TooltipTrigger: ({ children }: { children: ReactNode }) => children, + TooltipPopup: () => null, +})); +vi.mock("../state", () => ({})); +vi.mock("./fleetClient", () => ({})); +vi.mock("../logicalProjects", () => ({})); +vi.mock("../../state/entities", () => ({})); +vi.mock("../crew/crewArchiveClient", () => ({})); +vi.mock("../crew/crewStopClient", () => ({})); +vi.mock("../playbooks/PlaybookRunsSection", () => ({})); +vi.mock("../../confirmDialog", () => ({})); +vi.mock("../../components/ProjectFavicon", () => ({ ProjectFavicon: () => null })); +vi.mock("../../components/WorkspaceBreadcrumb", () => ({})); +vi.mock("../../components/WorkspacePageHeader", () => ({})); +vi.mock("../../components/ui/sidebar", () => ({})); +vi.mock("../../components/ui/scroll-area", () => ({})); +vi.mock("../../components/ui/toast", () => ({})); +vi.mock("../a2a/ArchiveWarningContent", () => ({})); +vi.mock("../../threadRoutes", () => ({})); +vi.mock("../../env", () => ({ isElectron: false })); + +import { FleetRowItem } from "./FleetPage"; + +const environmentId = EnvironmentId.make("fleet-test"); +const agent: FleetAgent = { + participantId: "agent:test", + threadId: "thread:test", + displayName: "Builder", + origin: "unknown", + placementParentId: null, + crew: null, + openAsks: 1, +}; +const measured: FleetDerivedFacts = { + runtime: { state: "unknown", reason: "This environment has no readable thread shell." }, + lastActivity: { state: "unknown", reason: "Ledger activity is unavailable." }, + asks: { + owed: [ + { + exchangeId: "owed", + counterpartyId: "captain", + counterpartyName: "Captain", + intent: "Review the patch", + openedAt: "2026-10-23T12:00:00Z", + }, + ], + awaited: [ + { + exchangeId: "awaited", + counterpartyId: "peer", + counterpartyName: "Reviewer", + intent: "Send the result", + openedAt: "2026-10-23T12:02:00Z", + }, + ], + }, + problems: [], +}; +let root: Root; +let container: HTMLDivElement; +const navigate = vi.fn(); +beforeEach(() => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + state.facts = measured; + state.live = true; + state.minute.mockClear(); + navigate.mockClear(); + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); +}); +afterEach(async () => { + await act(() => root.unmount()); + container.remove(); + vi.unstubAllGlobals(); +}); +async function render(rowAgent = agent) { + await act(() => + root.render( +
      + undefined} + onOpenThread={navigate} + /> +
    , + ), + ); +} +const summary = () => container.querySelector("button[aria-expanded]")!; +const disclosure = () => document.getElementById(summary().getAttribute("aria-controls")!)!; +const navigation = () => container.querySelector("button:not([aria-expanded])")!; + +async function key(user: ReturnType, value: string) { + await act(() => user.keyboard(value)); +} + +it("reveals the complete facts with Tab and Enter, closes with Space, and preserves row navigation", async () => { + const user = userEvent.setup(); + await render(); + expect(disclosure().hidden).toBe(true); + expect(state.minute).not.toHaveBeenCalled(); + await act(() => user.tab()); + expect(document.activeElement).toBe(navigation()); + await act(() => user.tab()); + expect(document.activeElement).toBe(summary()); + expect(summary().getAttribute("aria-label")).toBe("Facts for Builder"); + await key(user, "{Enter}"); + expect(disclosure().hidden).toBe(false); + expect(disclosure().textContent).toContain("Captain · Review the patch · 10m ago"); + expect(disclosure().textContent).toContain("Reviewer · Send the result · 8m ago"); + expect(disclosure().textContent).toContain("This environment has no readable thread shell."); + expect(disclosure().textContent).toContain("Ledger activity is unavailable."); + expect(disclosure().textContent).toContain( + "This environment has no recorded provenance for this agent.", + ); + expect(navigate).not.toHaveBeenCalled(); + expect(navigation().querySelector("summary, button, details")).toBeNull(); + await key(user, " "); + expect(disclosure().hidden).toBe(true); + expect(disclosure().querySelector("div")).toBeNull(); + await act(() => user.tab({ shift: true })); + expect(document.activeElement).toBe(navigation()); + await act(() => user.keyboard("{Enter}")); + expect(navigate).toHaveBeenCalledExactlyOnceWith(environmentId, "thread:test"); +}); + +it("keeps unknown reasons reachable when the agent has no thread and navigation is disabled", async () => { + const user = userEvent.setup(); + state.facts = undefined; + await render({ ...agent, threadId: null }); + expect(navigation().disabled).toBe(true); + await act(() => user.tab()); + expect(document.activeElement).toBe(summary()); + await key(user, "{Enter}"); + expect(disclosure().textContent).toContain("The live Fleet read has not provided this fact."); + expect(disclosure().textContent).toContain( + "This environment does not provide owed and awaited Exchange details.", + ); + expect(disclosure().textContent).toContain( + "This environment does not provide delivery problems.", + ); + expect(navigate).not.toHaveBeenCalled(); +}); + +it("keeps stale ask ages frozen and names outside spawners in the disclosure", async () => { + const user = userEvent.setup(); + state.live = false; + await render({ + ...agent, + outsideSpawner: { participantId: "outside", name: "External captain" }, + }); + summary().focus(); + await key(user, "{Enter}"); + expect(disclosure().textContent).toContain("this environment is unavailable"); + expect(disclosure().textContent).toContain("Captain · Review the patch · 5m at last read"); + expect(disclosure().textContent).toContain("Provenance: Spawned by External captain"); + expect(state.minute).not.toHaveBeenCalled(); +}); diff --git a/apps/web/src/j5/fleet/FleetFacts.tsx b/apps/web/src/j5/fleet/FleetFacts.tsx index b7193a822ed2d..0f362816c372b 100644 --- a/apps/web/src/j5/fleet/FleetFacts.tsx +++ b/apps/web/src/j5/fleet/FleetFacts.tsx @@ -2,8 +2,9 @@ import { useAtomValue } from "@effect/atom-react"; import type { FleetDerivedFacts } from "@t3tools/client-runtime/j5/fleetFacts"; import type { EnvironmentId } from "@t3tools/contracts"; import type { FleetAgent, FleetAgentFacts } from "@t3tools/contracts/j5"; -import type { ReactNode } from "react"; +import { useId, useState, type ReactNode } from "react"; +import { Button } from "../../components/ui/button"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../../components/ui/tooltip"; import { useNowMinute } from "../../hooks/useNowMinute"; import { fleetSourcesAtom } from "../state"; @@ -119,6 +120,117 @@ function AskDetails({ ); } +export function FleetFactDetails({ + environmentId, + agent, + title, +}: { + readonly environmentId: EnvironmentId; + readonly agent: FleetAgent; + readonly title: string; +}) { + const [open, setOpen] = useState(false); + const contentId = useId(); + return ( +
    + + +
    + ); +} + +function FleetFactDetailContent({ + environmentId, + agent, +}: { + readonly environmentId: EnvironmentId; + readonly agent: FleetAgent; +}) { + const key = fleetAgentKey(environmentId, agent.participantId); + const facts = useAtomValue(fleetAgentFactsAtom(key)); + const live = useAtomValue(fleetLiveAgentAtom(key)); + const asOf = useAtomValue(fleetReadTimeAtom(environmentId)); + const runtime = facts?.runtime; + const activity = facts?.lastActivity; + return ( +
    + {!live ?

    Showing the last measured facts; this environment is unavailable.

    : null} +

    + Status:{" "} + {runtime === undefined ? ( + "The live Fleet read has not provided this fact." + ) : runtime.state === "unknown" ? ( + runtime.reason + ) : runtime.status === "waiting-to-start" && runtime.since !== null ? ( + <> + Waiting to start ·{" "} + {live ? : `since ${fleetTime(runtime.since)}`} + + ) : ( + fleetStatusLabel(runtime) + )} +

    +

    + Provenance:{" "} + {agent.outsideSpawner !== undefined + ? `Spawned by ${agent.outsideSpawner.name ?? agent.outsideSpawner.participantId}` + : agent.origin === "unknown" + ? "This environment has no recorded provenance for this agent." + : agent.origin === "agent" + ? "Spawned by an agent." + : "Unrecorded."} +

    + {facts?.asks === undefined ? ( +

    This environment does not provide owed and awaited Exchange details.

    + ) : ( + + )} +

    + Last activity:{" "} + {activity === undefined + ? "The live Fleet read has not provided this fact." + : activity.state === "unknown" + ? activity.reason + : `${activity.label} ${fleetTime(activity.at)}`} +

    +
    +

    Problems

    + {facts?.problems.map((problem) => ( +

    + {fleetProblemLabel(problem)} +

    + ))} + {facts?.asks === undefined ? ( +

    This environment does not provide delivery problems.

    + ) : null} + {runtime?.state !== "known" ? ( +

    {runtime?.reason ?? "Runtime facts are unavailable."}

    + ) : null} + {runtime?.state === "known" && facts?.asks !== undefined && facts.problems.length === 0 ? ( +

    No measured problems.

    + ) : null} +
    +
    + ); +} + export function FleetFactCells({ environmentId, agent, diff --git a/apps/web/src/j5/fleet/FleetPage.tsx b/apps/web/src/j5/fleet/FleetPage.tsx index e82ee6b741a29..4f8cc44776adb 100644 --- a/apps/web/src/j5/fleet/FleetPage.tsx +++ b/apps/web/src/j5/fleet/FleetPage.tsx @@ -33,7 +33,7 @@ import { useLogicalProjects } from "../logicalProjects"; import { requestConfirmDialog } from "../../confirmDialog"; import { ArchiveWarningCrewSeats, type ArchiveWarningCrew } from "../a2a/ArchiveWarningContent"; import { archiveCrew } from "../crew/crewArchiveClient"; -import { classifyCrewSeat, crewHasRunningSeat, summarizeCrewState } from "../crew/crewState"; +import { crewHasRunningSeat, summarizeCrewState } from "../crew/crewState"; import { stopCrew } from "../crew/crewStopClient"; import { countFleetProjects, @@ -59,7 +59,13 @@ import { import { fleetSeatStatesAtom } from "./fleetState"; import { fleetAgentKey } from "./fleetPresentation"; -import { FleetFactCells, FleetSourceReadout, FleetFactHint, FleetCrewSummary } from "./FleetFacts"; +import { + FleetFactCells, + FleetFactDetails, + FleetSourceReadout, + FleetFactHint, + FleetCrewSummary, +} from "./FleetFacts"; /** Header and rows share one template so the Project, Status, asks, and activity columns line up. */ const FLEET_GRID_CLASS = @@ -352,7 +358,7 @@ function FleetNodeRows( members.map(({ agent }) => threadFor(props.threadsByKey, environmentId, agent)), ); // The person's Stop crew: interrupts every running seat, retires nothing. The seats' status - // pills tell the truth afterwards; a refused or failed call says so, since a button that does + // facts reflect the result; a refused or failed call says so, since a button that does // nothing visible is a lying spinner. const [busy, setBusy] = useState(null); const stop = async (crew: { crewInstanceId: string; crewName: string }) => { @@ -676,7 +682,7 @@ function ProjectLabel( ); } -function FleetRowItem( +export function FleetRowItem( props: FleetRowsProps & { readonly project: ScopedFleetLedgerProject; readonly row: FleetRow; @@ -743,6 +749,7 @@ function FleetRowItem( {props.row.depth === 0 ? : } + ); } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e034d3fb66c35..1acd44770215f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -959,6 +959,9 @@ importers: '@tanstack/router-plugin': specifier: ^1.161.0 version: 1.168.13(@tanstack/react-router@1.170.10(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(@voidzero-dev/vite-plus-core@1.0.0(@types/node@24.12.4)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@7.0.2)(unrun@0.2.39)(yaml@2.9.0)) + '@testing-library/user-event': + specifier: 14.6.7 + version: 14.6.7(@testing-library/dom@10.4.1) '@types/compression': specifier: ^1.8.1 version: 1.8.1 From 4dec13485694bc64202142dcd9f4d4dec8c39252 Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 23 Oct 2026 14:11:07 +0000 Subject: [PATCH 4/9] docs(fleet): record keyboard test dependency seam --- FORK.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/FORK.md b/FORK.md index 1f3d74f8eb451..bdb03936f2975 100644 --- a/FORK.md +++ b/FORK.md @@ -166,7 +166,7 @@ Landing-order collision: two cases landed as `15.`; resolved by the `b` suffix o Fleet measurements (#360) add the `./j5/fleetFacts` export to `packages/client-runtime/package.json`. The J5-owned module derives runtime, dispatch deadlines and labeled activity from the existing raw live shell; its shared Atom owns one future local deadline and performs no RPC reads. Ledger Exchanges, sender delivery alarms and the read time remain in the J5 Fleet read. Keep this subpath on upstream sync. - The Fleet command-palette entry is J5-owned `apps/web/src/j5/fleet/fleetPalette.tsx`; `apps/web/src/components/CommandPalette.tsx` adds one import, one hook call and appends those items beside the other J5 delegates. Preserve that mount when upstream moves palette actions. Web and desktop use the same Fleet page; native mobile has no Fleet entry or badge. + The Fleet command-palette entry is J5-owned `apps/web/src/j5/fleet/fleetPalette.tsx`; `apps/web/src/components/CommandPalette.tsx` adds one import, one hook call and appends those items beside the other J5 delegates. Preserve that mount when upstream moves palette actions. Web and desktop use the same Fleet page; native mobile has no Fleet entry or badge. `apps/web/package.json` adds the test-only `@testing-library/user-event` dependency for the Fleet row’s keyboard disclosure regression; `pnpm-lock.yaml` records its web importer. Keep it while that interaction test uses it. Cases 10, 11 and 12 are retired, so no launch policy remains to verify here. Client permission guards (Jackson's 2026-10-08 decision 23; [#506](https://github.com/Jacksondr5/j5code/issues/506)). J5's protected actions are registered with upstream's guard and its controls read the guard's answer, as upstream's own do: case 64. A session without the operate scope cannot use Crew approve and decline, Crew runtime answers, Stop and Archive crew, Inbox answers, artifact delete, the playbook and persona library mutations or the skill mutations; peering needs `access:write`. The server remains the authority in every case. @@ -821,6 +821,7 @@ explicitly marked. | `apps/web/src/routes/_chat.tsx` | R | B | | `apps/web/src/routeTree.gen.ts` | R | generated route registrations for 6/9 | | `apps/web/src/components/onboarding/WelcomeWizard.tsx` | R | 39, B | +| `apps/web/package.json` | N | 34 | | `apps/web/tsconfig.json` | R | B | | `packages/client-runtime/package.json` | R | 23, 34, 45, 69, 70, 75 | | `packages/client-runtime/src/connection/compatibility.ts` | A | 56 | @@ -838,7 +839,7 @@ explicitly marked. | `packages/shared/src/model.test.ts` | A | 32 | | `packages/ssh/src/tunnel.test.ts` | R | H, 50 | | `packages/ssh/src/tunnel.ts` | R | H, 50 | -| `pnpm-lock.yaml` | N | 45 | +| `pnpm-lock.yaml` | N | 34, 45 | | `scripts/build-cli-archive.ts` | N | 50 | | `scripts/build-desktop-artifact.test.ts` | A | B, S, 50 | | `scripts/build-desktop-artifact.ts` | R | B, S, 50 | From 3e2bc8af8c2bf666905b26435d8ab4f93fe9dc2d Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 26 Oct 2026 10:28:50 +0000 Subject: [PATCH 5/9] fix(fleet): refresh relative timestamps while live --- .../src/j5/fleet/FleetFacts.keyboard.test.tsx | 223 +++++++++++++++--- apps/web/src/j5/fleet/FleetFacts.tsx | 169 +++++++++---- .../src/j5/fleet/fleetPresentation.test.ts | 62 +++-- apps/web/src/j5/fleet/fleetPresentation.ts | 36 ++- 4 files changed, 378 insertions(+), 112 deletions(-) diff --git a/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx b/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx index a4a242aa71f97..0d8693844ece6 100644 --- a/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx +++ b/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx @@ -11,24 +11,63 @@ import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test"; const state = vi.hoisted(() => ({ facts: undefined as FleetDerivedFacts | undefined, live: true, + version: 0, + listeners: new Set<() => void>(), + timestampFormat: "24-hour" as "12-hour" | "24-hour", asOf: "2026-10-23T12:05:00Z", - minute: vi.fn(() => "2026-10-23T12:10"), -})); -vi.mock("@effect/atom-react", () => ({ - useAtomValue: (atom: { read: () => unknown }) => atom.read(), })); +vi.mock("@effect/atom-react", async () => { + const { useSyncExternalStore } = await import("react"); + return { + useAtomValue: (atom: { read: () => unknown }) => { + useSyncExternalStore( + (listener) => { + state.listeners.add(listener); + return () => state.listeners.delete(listener); + }, + () => state.version, + ); + return atom.read(); + }, + }; +}); +vi.mock("../../hooks/useSettings", async () => { + const { useSyncExternalStore } = await import("react"); + return { + useClientSettings: ( + select: (settings: { timestampFormat: typeof state.timestampFormat }) => unknown, + ) => { + useSyncExternalStore( + (listener) => { + state.listeners.add(listener); + return () => state.listeners.delete(listener); + }, + () => state.version, + ); + return select({ timestampFormat: state.timestampFormat }); + }, + }; +}); vi.mock("./fleetState", () => ({ fleetAgentFactsAtom: () => ({ read: () => state.facts }), fleetLiveAgentAtom: () => ({ read: () => state.live }), fleetReadTimeAtom: () => ({ read: () => state.asOf }), + fleetEnvironmentLivenessAtom: { read: () => new Map([["fleet-test", state.live]]) }, })); -vi.mock("../../hooks/useNowMinute", () => ({ useNowMinute: state.minute })); vi.mock("../../components/ui/tooltip", () => ({ Tooltip: ({ children }: { children: ReactNode }) => children, TooltipTrigger: ({ children }: { children: ReactNode }) => children, TooltipPopup: () => null, })); -vi.mock("../state", () => ({})); +vi.mock("../state", () => ({ + fleetSourcesAtom: { + read: () => ({ + sources: [ + { environmentId: "fleet-test", environmentLabel: "Test", data: { asOf: state.asOf } }, + ], + }), + }, +})); vi.mock("./fleetClient", () => ({})); vi.mock("../logicalProjects", () => ({})); vi.mock("../../state/entities", () => ({})); @@ -47,6 +86,7 @@ vi.mock("../../threadRoutes", () => ({})); vi.mock("../../env", () => ({ isElectron: false })); import { FleetRowItem } from "./FleetPage"; +import { FleetSourceReadout } from "./FleetFacts"; const environmentId = EnvironmentId.make("fleet-test"); const agent: FleetAgent = { @@ -90,7 +130,9 @@ beforeEach(() => { vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); state.facts = measured; state.live = true; - state.minute.mockClear(); + state.timestampFormat = "24-hour"; + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-10-23T12:10:00Z")); navigate.mockClear(); container = document.createElement("div"); document.body.append(container); @@ -99,32 +141,42 @@ beforeEach(() => { afterEach(async () => { await act(() => root.unmount()); container.remove(); + vi.useRealTimers(); vi.unstubAllGlobals(); }); async function render(rowAgent = agent) { await act(() => root.render( -
      - undefined} - onOpenThread={navigate} - /> -
    , + <> + +
      + undefined} + onOpenThread={navigate} + /> +
    + , ), ); } +async function refreshState() { + await act(() => { + state.version++; + for (const listener of state.listeners) listener(); + }); +} const summary = () => container.querySelector("button[aria-expanded]")!; const disclosure = () => document.getElementById(summary().getAttribute("aria-controls")!)!; const navigation = () => container.querySelector("button:not([aria-expanded])")!; @@ -134,10 +186,9 @@ async function key(user: ReturnType, value: string) { } it("reveals the complete facts with Tab and Enter, closes with Space, and preserves row navigation", async () => { - const user = userEvent.setup(); + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); await render(); expect(disclosure().hidden).toBe(true); - expect(state.minute).not.toHaveBeenCalled(); await act(() => user.tab()); expect(document.activeElement).toBe(navigation()); await act(() => user.tab()); @@ -145,8 +196,8 @@ it("reveals the complete facts with Tab and Enter, closes with Space, and preser expect(summary().getAttribute("aria-label")).toBe("Facts for Builder"); await key(user, "{Enter}"); expect(disclosure().hidden).toBe(false); - expect(disclosure().textContent).toContain("Captain · Review the patch · 10m ago"); - expect(disclosure().textContent).toContain("Reviewer · Send the result · 8m ago"); + expect(disclosure().textContent).toContain("Captain · Review the patch · opened 10m"); + expect(disclosure().textContent).toContain("Reviewer · Send the result · opened 8m"); expect(disclosure().textContent).toContain("This environment has no readable thread shell."); expect(disclosure().textContent).toContain("Ledger activity is unavailable."); expect(disclosure().textContent).toContain( @@ -164,7 +215,7 @@ it("reveals the complete facts with Tab and Enter, closes with Space, and preser }); it("keeps unknown reasons reachable when the agent has no thread and navigation is disabled", async () => { - const user = userEvent.setup(); + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); state.facts = undefined; await render({ ...agent, threadId: null }); expect(navigation().disabled).toBe(true); @@ -182,7 +233,7 @@ it("keeps unknown reasons reachable when the agent has no thread and navigation }); it("keeps stale ask ages frozen and names outside spawners in the disclosure", async () => { - const user = userEvent.setup(); + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); state.live = false; await render({ ...agent, @@ -193,5 +244,113 @@ it("keeps stale ask ages frozen and names outside spawners in the disclosure", a expect(disclosure().textContent).toContain("this environment is unavailable"); expect(disclosure().textContent).toContain("Captain · Review the patch · 5m at last read"); expect(disclosure().textContent).toContain("Provenance: Spawned by External captain"); - expect(state.minute).not.toHaveBeenCalled(); +}); + +const timedFacts: FleetDerivedFacts = { + ...measured, + runtime: { state: "known", status: "idle", settled: false, since: "2026-10-23T12:00:00Z" }, + lastActivity: { state: "known", at: "2026-10-23T12:03:00Z", label: "Last turn ended" }, + problems: [ + { + kind: "delivery-failed", + messageId: "failed", + receiverId: "peer", + receiverName: "Reviewer", + at: "2026-10-23T12:08:00Z", + reason: "offline", + exchangeOpen: true, + }, + ], +}; + +it("refreshes live row, expanded facts, asks and environment times on the shared minute tick", async () => { + state.facts = timedFacts; + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + await render(); + summary().focus(); + await key(user, "{Enter}"); + expect(navigation().textContent).toContain("Idle since 10m"); + expect(navigation().textContent).toContain("Last turn ended 7m"); + expect(navigation().textContent).toContain("Delivery failed · to Reviewer · 2m · offline"); + expect(disclosure().textContent).toContain("opened 10m"); + expect(container.querySelector("p")?.textContent).toContain("ledger as of 5m"); + + await act(() => vi.advanceTimersByTime(60_000)); + + expect(navigation().textContent).toContain("Idle since 11m"); + expect(navigation().textContent).toContain("Last turn ended 8m"); + expect(navigation().textContent).toContain("Delivery failed · to Reviewer · 3m · offline"); + expect(disclosure().textContent).toContain("Status: Idle since 11m"); + expect(disclosure().textContent).toContain("Last activity: Last turn ended 8m"); + expect(disclosure().textContent).toContain("Delivery failed · to Reviewer · 3m · offline"); + expect(disclosure().textContent).toContain("opened 11m"); + expect(container.querySelector("p")?.textContent).toContain("ledger as of 6m"); + expect(disclosure().textContent).toContain("12:00, 23rd October 2026"); + expect(disclosure().textContent).toContain("12:03, 23rd October 2026"); + expect(disclosure().textContent).toContain("12:08, 23rd October 2026"); + + state.timestampFormat = "12-hour"; + await refreshState(); + expect(disclosure().textContent).toContain("12:00 PM, 23rd October 2026"); + expect(disclosure().textContent).toContain("12:03 PM, 23rd October 2026"); + expect(disclosure().textContent).toContain("12:08 PM, 23rd October 2026"); +}); + +it("stops aging every measurement when a live row freezes, then resumes from the current clock", async () => { + state.facts = timedFacts; + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + await render(); + summary().focus(); + await key(user, "{Enter}"); + expect(navigation().textContent).toContain("Idle since 10m"); + + state.live = false; + await refreshState(); + const frozen = container.textContent; + expect(vi.getTimerCount()).toBe(0); + expect(frozen).toContain("23rd October 2026"); + expect(disclosure().textContent).toContain("5m at last read · opened"); + expect(navigation().textContent).not.toContain("Idle since 10m"); + expect(navigation().textContent).not.toContain("Last turn ended 7m"); + expect(navigation().textContent).not.toContain("Reviewer · 2m"); + expect(container.querySelector("p")?.textContent).toContain("stale"); + + await act(() => vi.advanceTimersByTime(3 * 86_400_000)); + expect(container.textContent).toBe(frozen); + + state.live = true; + await refreshState(); + expect(navigation().textContent).toContain("Idle since 3d"); + expect(navigation().textContent).toContain("Last turn ended 3d"); + expect(disclosure().textContent).toContain("opened 3d"); + expect(container.querySelector("p")?.textContent).toContain("ledger as of 3d"); +}); + +it("advances waiting-to-start ages and freezes their absolute request time", async () => { + state.facts = { + ...measured, + runtime: { + state: "known", + status: "waiting-to-start", + settled: false, + since: "2026-10-23T12:00:00Z", + }, + problems: [{ kind: "dispatch-overdue", runId: "requested", at: "2026-10-23T12:00:00Z" }], + }; + await render(); + expect(navigation().textContent).toContain("Waiting to start · 10m"); + expect(navigation().textContent).toContain("Run not dispatched · requested 10m"); + await act(() => vi.advanceTimersByTime(60_000)); + expect(navigation().textContent).toContain("Waiting to start · 11m"); + expect(navigation().textContent).toContain("Run not dispatched · requested 11m"); + + state.live = false; + await refreshState(); + expect(navigation().textContent).toContain("Waiting to start · since 12:00, 23rd October 2026"); + expect(navigation().textContent).toContain( + "Run not dispatched · requested 12:00, 23rd October 2026", + ); + const frozen = navigation().textContent; + await act(() => vi.advanceTimersByTime(60_000)); + expect(navigation().textContent).toBe(frozen); }); diff --git a/apps/web/src/j5/fleet/FleetFacts.tsx b/apps/web/src/j5/fleet/FleetFacts.tsx index 0f362816c372b..a840c3fa05a23 100644 --- a/apps/web/src/j5/fleet/FleetFacts.tsx +++ b/apps/web/src/j5/fleet/FleetFacts.tsx @@ -1,12 +1,14 @@ import { useAtomValue } from "@effect/atom-react"; import type { FleetDerivedFacts } from "@t3tools/client-runtime/j5/fleetFacts"; import type { EnvironmentId } from "@t3tools/contracts"; -import type { FleetAgent, FleetAgentFacts } from "@t3tools/contracts/j5"; +import type { TimestampFormat } from "@t3tools/contracts/settings"; +import type { FleetAgent, FleetAgentFacts, FleetRuntimeFact } from "@t3tools/contracts/j5"; import { useId, useState, type ReactNode } from "react"; import { Button } from "../../components/ui/button"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../../components/ui/tooltip"; import { useNowMinute } from "../../hooks/useNowMinute"; +import { useClientSettings } from "../../hooks/useSettings"; import { fleetSourcesAtom } from "../state"; import { fleetFactsAtom, @@ -43,6 +45,69 @@ export function FleetFactHint({ ); } +type TimedLabelProps = { + readonly at: string | null | undefined; + readonly label?: (now: number | undefined, timestampFormat: TimestampFormat) => string; + readonly showAbsolute?: boolean | undefined; +}; + +function FleetTimeLabel({ + at, + label, + showAbsolute, + now, +}: TimedLabelProps & { readonly now?: number }) { + const timestampFormat = useClientSettings((settings) => settings.timestampFormat); + const absolute = fleetTime(at, undefined, timestampFormat); + return ( + + + {showAbsolute && now !== undefined && at != null ? ` (${absolute})` : null} + + ); +} + +function FleetLiveTimeLabel(props: TimedLabelProps) { + const minute = useNowMinute(); + return ; +} + +function FleetTimestamp({ live, ...props }: TimedLabelProps & { readonly live: boolean }) { + return live ? : ; +} + +function FleetRuntimeLabel({ + runtime, + live, + showAbsolute, +}: { + readonly runtime: FleetRuntimeFact; + readonly live: boolean; + readonly showAbsolute?: boolean | undefined; +}) { + if ( + runtime.state !== "known" || + runtime.settled || + (runtime.status !== "idle" && runtime.status !== "waiting-to-start") + ) { + return <>{fleetStatusLabel(runtime)}; + } + return ( + + runtime.status === "waiting-to-start" && runtime.since !== null + ? `Waiting to start · ${now === undefined ? `since ${fleetTime(runtime.since, undefined, timestampFormat)}` : `${fleetMinutes(runtime.since, now)}m`}` + : fleetStatusLabel(runtime, now, timestampFormat) + } + /> + ); +} + export function FleetSourceReadout() { const sources = useAtomValue(fleetSourcesAtom); const live = useAtomValue(fleetEnvironmentLivenessAtom); @@ -56,9 +121,7 @@ export function FleetSourceReadout() { ? ) : ( - - - + )} {live.get(source.environmentId) === true ? " · runtime live" @@ -69,24 +132,16 @@ export function FleetSourceReadout() { ); } -function WaitingMinutes({ since }: { readonly since: string }) { - const minute = useNowMinute(); - return <>{fleetMinutes(since, Date.parse(`${minute}:00Z`))}m; -} - -function AskAge({ openedAt }: { readonly openedAt: string }) { - const minute = useNowMinute(); - return <>{fleetMinutes(openedAt, Date.parse(`${minute}:00Z`))}m ago; -} - function AskDetails({ asks, live, asOf, + showAbsolute, }: { readonly asks: FleetAgentFacts["asks"]; readonly live: boolean; readonly asOf: string | undefined; + readonly showAbsolute?: boolean | undefined; }) { return (
    @@ -107,11 +162,11 @@ function AskDetails({ {ask.counterpartyName === null ? " (name unavailable)" : ""} {` · ${ask.intent} · `} - {live ? ( - - ) : ( - `${asOf === undefined ? "age ?" : `${fleetMinutes(ask.openedAt, Date.parse(asOf))}m at last read`} · opened ${fleetTime(ask.openedAt)} (stale)` - )} + {!live + ? `${asOf === undefined ? "age ?" : `${fleetMinutes(ask.openedAt, Date.parse(asOf))}m at last read`} · ` + : null} + opened + {!live ? " (stale)" : null}

    ))}
    @@ -172,13 +227,8 @@ function FleetFactDetailContent({ "The live Fleet read has not provided this fact." ) : runtime.state === "unknown" ? ( runtime.reason - ) : runtime.status === "waiting-to-start" && runtime.since !== null ? ( - <> - Waiting to start ·{" "} - {live ? : `since ${fleetTime(runtime.since)}`} - ) : ( - fleetStatusLabel(runtime) + )}

    @@ -194,15 +244,24 @@ function FleetFactDetailContent({ {facts?.asks === undefined ? (

    This environment does not provide owed and awaited Exchange details.

    ) : ( - + )}

    Last activity:{" "} - {activity === undefined - ? "The live Fleet read has not provided this fact." - : activity.state === "unknown" - ? activity.reason - : `${activity.label} ${fleetTime(activity.at)}`} + {activity === undefined ? ( + "The live Fleet read has not provided this fact." + ) : activity.state === "unknown" ? ( + activity.reason + ) : ( + + `${activity.label} ${fleetTime(activity.at, now, timestampFormat)}` + } + /> + )}

    Problems

    @@ -214,7 +273,12 @@ function FleetFactDetailContent({ : `${problem.kind}:${problem.runId}` } > - {fleetProblemLabel(problem)} + fleetProblemLabel(problem, now, timestampFormat)} + />

    ))} {facts?.asks === undefined ? ( @@ -254,23 +318,10 @@ export function FleetFactCells({ ? unknownReason : runtime.state === "unknown" ? runtime.reason - : !live - ? "Showing the last measured runtime; this environment is unavailable." - : undefined + : undefined } > - {runtime === undefined ? ( - "?" - ) : runtime.state === "known" && - runtime.status === "waiting-to-start" && - runtime.since !== null ? ( - <> - Waiting to start ·{" "} - {live ? : `since ${fleetTime(runtime.since)}`} - - ) : ( - fleetStatusLabel(runtime) - )} + {runtime === undefined ? "?" : } {!live ? (stale) : null} {facts?.asks === undefined ? ( @@ -296,13 +347,23 @@ export function FleetFactCells({ activity?.state === "unknown" ? activity.reason : activity?.state === "known" - ? activity.at + ? undefined : unknownReason } > - {activity?.state === "known" ? `${activity.label} ${fleetTime(activity.at)}` : "?"} + {activity?.state === "known" ? ( + + `${activity.label} ${fleetTime(activity.at, now, timestampFormat)}` + } + /> + ) : ( + "?" + )} - + ); } @@ -310,9 +371,11 @@ export function FleetFactCells({ function FleetProblems({ facts, ledgerKnown, + live, }: { readonly facts: FleetDerivedFacts | undefined; readonly ledgerKnown: boolean; + readonly live: boolean; }) { const runtimeKnown = facts?.runtime.state === "known"; if (facts?.problems.length === 0 && runtimeKnown && ledgerKnown) return null; @@ -327,7 +390,11 @@ function FleetProblems({ : `${problem.kind}:${problem.runId}` } > - {fleetProblemLabel(problem)} + fleetProblemLabel(problem, now, timestampFormat)} + /> ))} {!ledgerKnown || !runtimeKnown ? ( diff --git a/apps/web/src/j5/fleet/fleetPresentation.test.ts b/apps/web/src/j5/fleet/fleetPresentation.test.ts index 5504114a303e3..1ffccca2bcbe5 100644 --- a/apps/web/src/j5/fleet/fleetPresentation.test.ts +++ b/apps/web/src/j5/fleet/fleetPresentation.test.ts @@ -40,34 +40,56 @@ describe("Fleet presentation", () => { expect(fleetStatusLabel({ state: "unknown", reason: "missing runtime" })).toBe("?"); }); - it("keeps prior-day dates explicit without advancing stale timestamps at midnight", () => { + it("uses relative live times and keeps stale measurements absolute across midnight", () => { + const now = Date.parse(at); + const prior = "2026-10-18T10:00:00.000Z"; + const idle = { ...runtime("idle"), since: prior }; + expect(fleetTime(prior, now)).toBe("1d"); + expect(fleetTime(prior, now + 3 * 86_400_000)).toBe("4d"); + expect(fleetStatusLabel(idle, now)).toBe("Idle since 1d"); + expect(fleetStatusLabel(idle, now + 3 * 86_400_000)).toBe("Idle since 4d"); + expect(fleetTime(prior)).toContain("18th October 2026"); + expect(fleetTime(undefined, now)).toBe("?"); + expect(fleetTime("invalid", now)).toBe("?"); + expect(fleetTime("invalid")).toBe("?"); + vi.useFakeTimers(); try { - vi.setSystemTime(new Date("2026-10-19T10:00:00.000Z")); - const prior = "2026-10-18T10:00:00.000Z"; - const idle = { ...runtime("idle"), since: prior }; - const label = fleetStatusLabel(idle); - expect(label).toContain("18th October 2026"); - expect(fleetTime(prior)).toContain("18th October 2026"); - expect( - fleetProblemLabel({ - kind: "delivery-failed", - messageId: "m", - receiverId: "a", - receiverName: "Agent", - at: prior, - reason: "offline", - exchangeOpen: false, - }), - ).toContain("18th October 2026"); + vi.setSystemTime(now); + const stale = fleetStatusLabel(idle); + expect(stale).toContain("18th October 2026"); vi.advanceTimersByTime(3 * 86_400_000); - expect(fleetStatusLabel(idle)).toBe(label); - expect(vi.getTimerCount()).toBe(0); + expect(fleetStatusLabel(idle)).toBe(stale); } finally { vi.useRealTimers(); } }); + it("advances every problem kind with the supplied clock while preserving missing times", () => { + const now = Date.parse(at) + 60_000; + const problems = [ + { kind: "failed-run", runId: "r", at }, + { kind: "dispatch-overdue", runId: "r", at }, + { + kind: "delivery-failed", + messageId: "m", + receiverId: "a", + receiverName: "Agent", + at, + reason: "offline", + exchangeOpen: false, + }, + ] as const; + for (const problem of problems) { + expect(fleetProblemLabel(problem, now)).toContain("1m"); + expect(fleetProblemLabel(problem, now + 60_000)).toContain("2m"); + expect(fleetProblemLabel(problem)).toContain("19th October 2026"); + } + expect(fleetProblemLabel({ kind: "failed-run", runId: "r", at: null }, now)).toBe( + "Latest run failed · time unavailable", + ); + }); + it("keeps stale or unknown agents Active and respects background Waiting over a settle mark", () => { expect(fleetSeatState(facts(runtime("idle", true)), true)).toBe("settled"); expect(fleetSeatState(facts(runtime("waiting")), true)).toBe("running"); diff --git a/apps/web/src/j5/fleet/fleetPresentation.ts b/apps/web/src/j5/fleet/fleetPresentation.ts index bc513d43046b9..2fc7754d00254 100644 --- a/apps/web/src/j5/fleet/fleetPresentation.ts +++ b/apps/web/src/j5/fleet/fleetPresentation.ts @@ -1,7 +1,8 @@ import type { FleetDerivedFacts } from "@t3tools/client-runtime/j5/fleetFacts"; import type { J5ReadSource } from "@t3tools/client-runtime/j5/readSources"; import type { FleetProblem, FleetRuntimeFact } from "@t3tools/contracts/j5"; -import { formatChatTimestampTooltip } from "../../timestampFormat"; +import type { TimestampFormat } from "@t3tools/contracts/settings"; +import { formatChatTimestampTooltip, formatElapsedDurationLabel } from "../../timestampFormat"; import type { CrewSeatState } from "../crew/crewState"; export const fleetAgentKey = (environmentId: string, participantId: string) => @@ -12,13 +13,26 @@ export const fleetSourceIsLive = ( shellStatus: string, ) => source.connected && source.status === "ready" && shellStatus === "live"; -export const fleetTime = (at: string | null | undefined) => - at == null ? "?" : formatChatTimestampTooltip(at, "locale") || "?"; +// An omitted clock keeps frozen measurements absolute rather than aging an old read. +export const fleetTime = ( + at: string | null | undefined, + now?: number, + timestampFormat: TimestampFormat = "locale", +) => + at == null + ? "?" + : (now === undefined + ? formatChatTimestampTooltip(at, timestampFormat) + : formatElapsedDurationLabel(at, now)) || "?"; export const fleetMinutes = (since: string, now: number) => Math.max(0, Math.floor((now - Date.parse(since)) / 60_000)); -export const fleetStatusLabel = (runtime: FleetRuntimeFact) => { +export const fleetStatusLabel = ( + runtime: FleetRuntimeFact, + now?: number, + timestampFormat?: TimestampFormat, +) => { if (runtime.state === "unknown") return "?"; if (runtime.settled) return "Settled"; switch (runtime.status) { @@ -35,7 +49,7 @@ export const fleetStatusLabel = (runtime: FleetRuntimeFact) => { case "waiting-to-start": return "Waiting to start"; case "idle": - return `Idle since ${fleetTime(runtime.since)}`; + return `Idle since ${fleetTime(runtime.since, now, timestampFormat)}`; } }; @@ -52,14 +66,18 @@ export const fleetSeatState = ( return "running"; }; -export const fleetProblemLabel = (problem: FleetProblem) => { +export const fleetProblemLabel = ( + problem: FleetProblem, + now?: number, + timestampFormat?: TimestampFormat, +) => { switch (problem.kind) { case "failed-run": - return `Latest run failed · ${problem.at === null ? "time unavailable" : fleetTime(problem.at)}`; + return `Latest run failed · ${problem.at === null ? "time unavailable" : fleetTime(problem.at, now, timestampFormat)}`; case "dispatch-overdue": - return `Run not dispatched · requested ${fleetTime(problem.at)}`; + return `Run not dispatched · requested ${fleetTime(problem.at, now, timestampFormat)}`; case "delivery-failed": - return `Delivery failed · to ${problem.receiverName ?? problem.receiverId} · ${fleetTime(problem.at)} · ${problem.reason ?? "reason unavailable"}`; + return `Delivery failed · to ${problem.receiverName ?? problem.receiverId} · ${fleetTime(problem.at, now, timestampFormat)} · ${problem.reason ?? "reason unavailable"}`; } }; From 155a0f9056a5e1fd01f1abd31fcf5faed8c0b9d2 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 26 Oct 2026 10:31:20 +0000 Subject: [PATCH 6/9] fix(fleet): keep exact times accessible and relative labels clear --- .../src/j5/fleet/FleetFacts.keyboard.test.tsx | 74 +++++++++++-------- apps/web/src/j5/fleet/FleetFacts.tsx | 72 ++++++++++++++---- .../src/j5/fleet/fleetPresentation.test.ts | 13 +++- apps/web/src/j5/fleet/fleetPresentation.ts | 17 ++++- 4 files changed, 124 insertions(+), 52 deletions(-) diff --git a/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx b/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx index 0d8693844ece6..8907e08a0bfcf 100644 --- a/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx +++ b/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx @@ -4,7 +4,7 @@ import type { FleetDerivedFacts } from "@t3tools/client-runtime/j5/fleetFacts"; import { EnvironmentId } from "@t3tools/contracts"; import type { FleetAgent } from "@t3tools/contracts/j5"; import userEvent from "@testing-library/user-event"; -import { act, type ReactNode } from "react"; +import { act } from "react"; import { createRoot, type Root } from "react-dom/client"; import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test"; @@ -54,11 +54,7 @@ vi.mock("./fleetState", () => ({ fleetReadTimeAtom: () => ({ read: () => state.asOf }), fleetEnvironmentLivenessAtom: { read: () => new Map([["fleet-test", state.live]]) }, })); -vi.mock("../../components/ui/tooltip", () => ({ - Tooltip: ({ children }: { children: ReactNode }) => children, - TooltipTrigger: ({ children }: { children: ReactNode }) => children, - TooltipPopup: () => null, -})); + vi.mock("../state", () => ({ fleetSourcesAtom: { read: () => ({ @@ -196,8 +192,8 @@ it("reveals the complete facts with Tab and Enter, closes with Space, and preser expect(summary().getAttribute("aria-label")).toBe("Facts for Builder"); await key(user, "{Enter}"); expect(disclosure().hidden).toBe(false); - expect(disclosure().textContent).toContain("Captain · Review the patch · opened 10m"); - expect(disclosure().textContent).toContain("Reviewer · Send the result · opened 8m"); + expect(disclosure().textContent).toContain("Captain · Review the patch · opened 10m ago"); + expect(disclosure().textContent).toContain("Reviewer · Send the result · opened 8m ago"); expect(disclosure().textContent).toContain("This environment has no readable thread shell."); expect(disclosure().textContent).toContain("Ledger activity is unavailable."); expect(disclosure().textContent).toContain( @@ -269,25 +265,27 @@ it("refreshes live row, expanded facts, asks and environment times on the shared await render(); summary().focus(); await key(user, "{Enter}"); - expect(navigation().textContent).toContain("Idle since 10m"); - expect(navigation().textContent).toContain("Last turn ended 7m"); - expect(navigation().textContent).toContain("Delivery failed · to Reviewer · 2m · offline"); - expect(disclosure().textContent).toContain("opened 10m"); - expect(container.querySelector("p")?.textContent).toContain("ledger as of 5m"); + expect(navigation().textContent).toContain("Idle 10m"); + expect(navigation().textContent).toContain("Last turn ended 7m ago"); + expect(navigation().textContent).toContain("Delivery failed · to Reviewer · 2m ago · offline"); + expect(disclosure().textContent).toContain("opened 10m ago"); + expect(container.querySelector("p")?.textContent).toContain("ledger read 5m ago"); await act(() => vi.advanceTimersByTime(60_000)); - expect(navigation().textContent).toContain("Idle since 11m"); - expect(navigation().textContent).toContain("Last turn ended 8m"); - expect(navigation().textContent).toContain("Delivery failed · to Reviewer · 3m · offline"); - expect(disclosure().textContent).toContain("Status: Idle since 11m"); - expect(disclosure().textContent).toContain("Last activity: Last turn ended 8m"); - expect(disclosure().textContent).toContain("Delivery failed · to Reviewer · 3m · offline"); - expect(disclosure().textContent).toContain("opened 11m"); - expect(container.querySelector("p")?.textContent).toContain("ledger as of 6m"); + expect(navigation().textContent).toContain("Idle 11m"); + expect(navigation().textContent).toContain("Last turn ended 8m ago"); + expect(navigation().textContent).toContain("Delivery failed · to Reviewer · 3m ago · offline"); + expect(disclosure().textContent).toContain("Status: Idle 11m"); + expect(disclosure().textContent).toContain("Last activity: Last turn ended 8m ago"); + expect(disclosure().textContent).toContain("Delivery failed · to Reviewer · 3m ago · offline"); + expect(disclosure().textContent).toContain("opened 11m ago"); + expect(container.querySelector("p")?.textContent).toContain("ledger read 6m ago"); expect(disclosure().textContent).toContain("12:00, 23rd October 2026"); expect(disclosure().textContent).toContain("12:03, 23rd October 2026"); expect(disclosure().textContent).toContain("12:08, 23rd October 2026"); + expect(disclosure().textContent).toContain("Environment read: 6m ago (12:05, 23rd October 2026)"); + expect(container.querySelector("p")?.textContent).toContain("6m ago (12:05, 23rd October 2026)"); state.timestampFormat = "12-hour"; await refreshState(); @@ -302,7 +300,7 @@ it("stops aging every measurement when a live row freezes, then resumes from the await render(); summary().focus(); await key(user, "{Enter}"); - expect(navigation().textContent).toContain("Idle since 10m"); + expect(navigation().textContent).toContain("Idle 10m"); state.live = false; await refreshState(); @@ -310,8 +308,8 @@ it("stops aging every measurement when a live row freezes, then resumes from the expect(vi.getTimerCount()).toBe(0); expect(frozen).toContain("23rd October 2026"); expect(disclosure().textContent).toContain("5m at last read · opened"); - expect(navigation().textContent).not.toContain("Idle since 10m"); - expect(navigation().textContent).not.toContain("Last turn ended 7m"); + expect(navigation().textContent).not.toContain("Idle 10m"); + expect(navigation().textContent).not.toContain("Last turn ended 7m ago"); expect(navigation().textContent).not.toContain("Reviewer · 2m"); expect(container.querySelector("p")?.textContent).toContain("stale"); @@ -320,10 +318,10 @@ it("stops aging every measurement when a live row freezes, then resumes from the state.live = true; await refreshState(); - expect(navigation().textContent).toContain("Idle since 3d"); - expect(navigation().textContent).toContain("Last turn ended 3d"); - expect(disclosure().textContent).toContain("opened 3d"); - expect(container.querySelector("p")?.textContent).toContain("ledger as of 3d"); + expect(navigation().textContent).toContain("Idle 3d"); + expect(navigation().textContent).toContain("Last turn ended 3d ago"); + expect(disclosure().textContent).toContain("opened 3d ago"); + expect(container.querySelector("p")?.textContent).toContain("ledger read 3d ago"); }); it("advances waiting-to-start ages and freezes their absolute request time", async () => { @@ -339,10 +337,10 @@ it("advances waiting-to-start ages and freezes their absolute request time", asy }; await render(); expect(navigation().textContent).toContain("Waiting to start · 10m"); - expect(navigation().textContent).toContain("Run not dispatched · requested 10m"); + expect(navigation().textContent).toContain("Run not dispatched · requested 10m ago"); await act(() => vi.advanceTimersByTime(60_000)); expect(navigation().textContent).toContain("Waiting to start · 11m"); - expect(navigation().textContent).toContain("Run not dispatched · requested 11m"); + expect(navigation().textContent).toContain("Run not dispatched · requested 11m ago"); state.live = false; await refreshState(); @@ -354,3 +352,19 @@ it("advances waiting-to-start ages and freezes their absolute request time", asy await act(() => vi.advanceTimersByTime(60_000)); expect(navigation().textContent).toBe(frozen); }); + +it("shows ask ages in one tooltip without nested triggers and refreshes the open popup", async () => { + await render(); + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + const asks = [ + ...navigation().querySelectorAll('[data-slot="tooltip-trigger"]'), + ].find((element) => element.textContent === "Owes 1 · Awaiting 1")!; + await act(() => user.hover(asks)); + await act(() => vi.advanceTimersByTime(1_000)); + const popup = document.querySelector('[data-slot="tooltip-popup"]')!; + expect(popup).not.toBeNull(); + expect(popup.textContent).toContain("Captain · Review the patch · opened 10m ago"); + expect(popup.querySelector('[data-slot="tooltip-trigger"]')).toBeNull(); + await act(() => vi.advanceTimersByTime(60_000)); + expect(popup.textContent).toContain("Captain · Review the patch · opened 11m ago"); +}); diff --git a/apps/web/src/j5/fleet/FleetFacts.tsx b/apps/web/src/j5/fleet/FleetFacts.tsx index a840c3fa05a23..7a97c67808185 100644 --- a/apps/web/src/j5/fleet/FleetFacts.tsx +++ b/apps/web/src/j5/fleet/FleetFacts.tsx @@ -24,6 +24,7 @@ import { fleetStatusLabel, fleetMinutes, fleetTime, + fleetAgo, fleetProblemLabel, } from "./fleetPresentation"; @@ -62,7 +63,7 @@ function FleetTimeLabel({ return ( {showAbsolute && now !== undefined && at != null ? ` (${absolute})` : null} @@ -115,13 +116,17 @@ export function FleetSourceReadout() {
    {sources.sources.map((source) => (

    - {source.environmentLabel} · ledger as of{" "} + {source.environmentLabel} · ledger read{" "} {source.data?.asOf === undefined ? ( ? ) : ( - + )} {live.get(source.environmentId) === true ? " · runtime live" @@ -137,12 +142,17 @@ function AskDetails({ live, asOf, showAbsolute, + plain = false, + now, }: { readonly asks: FleetAgentFacts["asks"]; readonly live: boolean; readonly asOf: string | undefined; readonly showAbsolute?: boolean | undefined; + readonly plain?: boolean; + readonly now?: number | undefined; }) { + const timestampFormat = useClientSettings((settings) => settings.timestampFormat); return (

    {( @@ -165,7 +175,12 @@ function AskDetails({ {!live ? `${asOf === undefined ? "age ?" : `${fleetMinutes(ask.openedAt, Date.parse(asOf))}m at last read`} · ` : null} - opened + opened{" "} + {plain ? ( + fleetAgo(ask.openedAt, now, timestampFormat) + ) : ( + + )} {!live ? " (stale)" : null}

    ))} @@ -175,6 +190,34 @@ function AskDetails({ ); } +type AskTooltipProps = { + readonly asks: FleetAgentFacts["asks"]; + readonly live: boolean; + readonly asOf: string | undefined; +}; + +function FleetAskTooltipContent({ now, ...props }: AskTooltipProps & { readonly now?: number }) { + return ( + + }> + Owes {props.asks.owed.length} · Awaiting {props.asks.awaited.length} + + + + + + ); +} + +function FleetLiveAskTooltip(props: AskTooltipProps) { + const minute = useNowMinute(); + return ; +} + +function FleetAskTooltip(props: AskTooltipProps) { + return props.live ? : ; +} + export function FleetFactDetails({ environmentId, agent, @@ -231,6 +274,14 @@ function FleetFactDetailContent({ )}

    +

    + Environment read:{" "} + {asOf === undefined ? ( + "This environment does not report its Fleet read time." + ) : ( + + )} +

    Provenance:{" "} {agent.outsideSpawner !== undefined @@ -258,7 +309,7 @@ function FleetFactDetailContent({ live={live} showAbsolute label={(now, timestampFormat) => - `${activity.label} ${fleetTime(activity.at, now, timestampFormat)}` + `${activity.label} ${fleetAgo(activity.at, now, timestampFormat)}` } /> )} @@ -332,14 +383,7 @@ export function FleetFactCells({ ? ) : ( - - }> - Owes {facts.asks.owed.length} · Awaiting {facts.asks.awaited.length} - - - - - + )} - `${activity.label} ${fleetTime(activity.at, now, timestampFormat)}` + `${activity.label} ${fleetAgo(activity.at, now, timestampFormat)}` } /> ) : ( diff --git a/apps/web/src/j5/fleet/fleetPresentation.test.ts b/apps/web/src/j5/fleet/fleetPresentation.test.ts index 1ffccca2bcbe5..7318ec8fb6ad8 100644 --- a/apps/web/src/j5/fleet/fleetPresentation.test.ts +++ b/apps/web/src/j5/fleet/fleetPresentation.test.ts @@ -6,6 +6,7 @@ import { fleetAgentKey, fleetMinutes, fleetTime, + fleetAgo, fleetProblemLabel, fleetSeatState, fleetSourceIsLive, @@ -45,9 +46,13 @@ describe("Fleet presentation", () => { const prior = "2026-10-18T10:00:00.000Z"; const idle = { ...runtime("idle"), since: prior }; expect(fleetTime(prior, now)).toBe("1d"); + expect(fleetAgo(prior, now)).toBe("1d ago"); + expect(fleetAgo(at, now)).toBe("just now"); + expect(fleetAgo(undefined, now)).toBe("?"); + expect(fleetAgo(prior)).toContain("18th October 2026"); expect(fleetTime(prior, now + 3 * 86_400_000)).toBe("4d"); - expect(fleetStatusLabel(idle, now)).toBe("Idle since 1d"); - expect(fleetStatusLabel(idle, now + 3 * 86_400_000)).toBe("Idle since 4d"); + expect(fleetStatusLabel(idle, now)).toBe("Idle 1d"); + expect(fleetStatusLabel(idle, now + 3 * 86_400_000)).toBe("Idle 4d"); expect(fleetTime(prior)).toContain("18th October 2026"); expect(fleetTime(undefined, now)).toBe("?"); expect(fleetTime("invalid", now)).toBe("?"); @@ -81,8 +86,8 @@ describe("Fleet presentation", () => { }, ] as const; for (const problem of problems) { - expect(fleetProblemLabel(problem, now)).toContain("1m"); - expect(fleetProblemLabel(problem, now + 60_000)).toContain("2m"); + expect(fleetProblemLabel(problem, now)).toContain("1m ago"); + expect(fleetProblemLabel(problem, now + 60_000)).toContain("2m ago"); expect(fleetProblemLabel(problem)).toContain("19th October 2026"); } expect(fleetProblemLabel({ kind: "failed-run", runId: "r", at: null }, now)).toBe( diff --git a/apps/web/src/j5/fleet/fleetPresentation.ts b/apps/web/src/j5/fleet/fleetPresentation.ts index 2fc7754d00254..2fdf253ba6b17 100644 --- a/apps/web/src/j5/fleet/fleetPresentation.ts +++ b/apps/web/src/j5/fleet/fleetPresentation.ts @@ -25,6 +25,15 @@ export const fleetTime = ( ? formatChatTimestampTooltip(at, timestampFormat) : formatElapsedDurationLabel(at, now)) || "?"; +export const fleetAgo = ( + at: string | null | undefined, + now?: number, + timestampFormat?: TimestampFormat, +) => { + const time = fleetTime(at, now, timestampFormat); + return now === undefined || time === "just now" || time === "?" ? time : `${time} ago`; +}; + export const fleetMinutes = (since: string, now: number) => Math.max(0, Math.floor((now - Date.parse(since)) / 60_000)); @@ -49,7 +58,7 @@ export const fleetStatusLabel = ( case "waiting-to-start": return "Waiting to start"; case "idle": - return `Idle since ${fleetTime(runtime.since, now, timestampFormat)}`; + return `Idle${now === undefined ? " since" : ""} ${fleetTime(runtime.since, now, timestampFormat)}`; } }; @@ -73,11 +82,11 @@ export const fleetProblemLabel = ( ) => { switch (problem.kind) { case "failed-run": - return `Latest run failed · ${problem.at === null ? "time unavailable" : fleetTime(problem.at, now, timestampFormat)}`; + return `Latest run failed · ${problem.at === null ? "time unavailable" : fleetAgo(problem.at, now, timestampFormat)}`; case "dispatch-overdue": - return `Run not dispatched · requested ${fleetTime(problem.at, now, timestampFormat)}`; + return `Run not dispatched · requested ${fleetAgo(problem.at, now, timestampFormat)}`; case "delivery-failed": - return `Delivery failed · to ${problem.receiverName ?? problem.receiverId} · ${fleetTime(problem.at, now, timestampFormat)} · ${problem.reason ?? "reason unavailable"}`; + return `Delivery failed · to ${problem.receiverName ?? problem.receiverId} · ${fleetAgo(problem.at, now, timestampFormat)} · ${problem.reason ?? "reason unavailable"}`; } }; From 73333ad0eee1b8f84f470bf98c6f98f03845b9c2 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 26 Oct 2026 10:35:08 +0000 Subject: [PATCH 7/9] fix(fleet): merge receiver facts and qualify incomplete coverage --- .../src/j5/fleet/FleetFacts.keyboard.test.tsx | 31 ++++ apps/web/src/j5/fleet/FleetFacts.tsx | 18 +- .../src/j5/fleet/fleetPresentation.test.ts | 1 + apps/web/src/j5/fleet/fleetPresentation.ts | 3 +- apps/web/src/j5/fleet/fleetState.test.ts | 171 ++++++++++++++++++ apps/web/src/j5/fleet/fleetState.ts | 17 +- 6 files changed, 233 insertions(+), 8 deletions(-) create mode 100644 apps/web/src/j5/fleet/fleetState.test.ts diff --git a/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx b/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx index 8907e08a0bfcf..f8cf1e1f5e1dd 100644 --- a/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx +++ b/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx @@ -118,6 +118,7 @@ const measured: FleetDerivedFacts = { ], }, problems: [], + problemsIncomplete: false, }; let root: Root; let container: HTMLDivElement; @@ -368,3 +369,33 @@ it("shows ask ages in one tooltip without nested triggers and refreshes the open await act(() => vi.advanceTimersByTime(60_000)); expect(popup.textContent).toContain("Captain · Review the patch · opened 11m ago"); }); + +it("keeps incomplete delivery coverage visible and keyboard-readable until a complete read", async () => { + state.facts = { ...timedFacts, problems: [], problemsIncomplete: true }; + await render(); + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + expect(navigation().textContent).toContain("Delivery problems ?"); + summary().focus(); + await key(user, "{Enter}"); + expect(disclosure().textContent).toContain("Delivery problems may be missing"); + expect(disclosure().textContent).not.toContain("No measured problems."); + + state.facts = { ...state.facts, problemsIncomplete: false }; + await refreshState(); + expect(navigation().textContent).not.toContain("Delivery problems ?"); + expect(disclosure().textContent).not.toContain("Delivery problems may be missing"); + expect(disclosure().textContent).toContain("No measured problems."); +}); + +it("preserves measured delivery failures while warning about incomplete coverage", async () => { + state.facts = { ...timedFacts, problemsIncomplete: true }; + await render(); + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + expect(navigation().textContent).toContain("Delivery failed · to Reviewer · 2m ago · offline"); + expect(navigation().textContent).toContain("Delivery problems ?"); + summary().focus(); + await key(user, "{Enter}"); + expect(disclosure().textContent).toContain("Delivery failed · to Reviewer · 2m ago · offline"); + expect(disclosure().textContent).toContain("Delivery problems may be missing"); + expect(disclosure().textContent).not.toContain("No measured problems."); +}); diff --git a/apps/web/src/j5/fleet/FleetFacts.tsx b/apps/web/src/j5/fleet/FleetFacts.tsx index 7a97c67808185..5c75b27686e5b 100644 --- a/apps/web/src/j5/fleet/FleetFacts.tsx +++ b/apps/web/src/j5/fleet/FleetFacts.tsx @@ -28,6 +28,9 @@ import { fleetProblemLabel, } from "./fleetPresentation"; +const incompleteDeliveryReason = + "Delivery problems may be missing because an environment is unavailable or does not provide complete delivery facts."; + export function FleetFactHint({ reason, children, @@ -334,11 +337,16 @@ function FleetFactDetailContent({ ))} {facts?.asks === undefined ? (

    This environment does not provide delivery problems.

    + ) : facts.problemsIncomplete ? ( +

    {incompleteDeliveryReason}

    ) : null} {runtime?.state !== "known" ? (

    {runtime?.reason ?? "Runtime facts are unavailable."}

    ) : null} - {runtime?.state === "known" && facts?.asks !== undefined && facts.problems.length === 0 ? ( + {runtime?.state === "known" && + facts?.asks !== undefined && + !facts.problemsIncomplete && + facts.problems.length === 0 ? (

    No measured problems.

    ) : null}
    @@ -422,7 +430,8 @@ function FleetProblems({ readonly live: boolean; }) { const runtimeKnown = facts?.runtime.state === "known"; - if (facts?.problems.length === 0 && runtimeKnown && ledgerKnown) return null; + if (facts?.problems.length === 0 && !facts.problemsIncomplete && runtimeKnown && ledgerKnown) + return null; return ( {facts?.problems.map((problem) => ( @@ -441,6 +450,11 @@ function FleetProblems({ /> ))} + {ledgerKnown && facts?.problemsIncomplete ? ( + + Delivery problems ? + + ) : null} {!ledgerKnown || !runtimeKnown ? ( ({ asks: undefined, lastActivity: { state: "unknown", reason: "old server" }, problems: [], + problemsIncomplete: false, }); describe("Fleet presentation", () => { diff --git a/apps/web/src/j5/fleet/fleetPresentation.ts b/apps/web/src/j5/fleet/fleetPresentation.ts index 2fdf253ba6b17..09536cdb1946b 100644 --- a/apps/web/src/j5/fleet/fleetPresentation.ts +++ b/apps/web/src/j5/fleet/fleetPresentation.ts @@ -5,8 +5,7 @@ import type { TimestampFormat } from "@t3tools/contracts/settings"; import { formatChatTimestampTooltip, formatElapsedDurationLabel } from "../../timestampFormat"; import type { CrewSeatState } from "../crew/crewState"; -export const fleetAgentKey = (environmentId: string, participantId: string) => - `${environmentId.length}:${environmentId}${participantId}`; +export { fleetAgentKey } from "@t3tools/client-runtime/j5/fleetFacts"; export const fleetSourceIsLive = ( source: Pick, "connected" | "status">, diff --git a/apps/web/src/j5/fleet/fleetState.test.ts b/apps/web/src/j5/fleet/fleetState.test.ts new file mode 100644 index 0000000000000..95686e8c20d51 --- /dev/null +++ b/apps/web/src/j5/fleet/fleetState.test.ts @@ -0,0 +1,171 @@ +import type { J5ReadSources } from "@t3tools/client-runtime/j5/readSources"; +import { EnvironmentId } from "@t3tools/contracts"; +import type { FleetAgent, FleetResponse } from "@t3tools/contracts/j5"; +import * as Option from "effect/Option"; +import { Atom, AtomRegistry } from "effect/reactivity"; +import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test"; + +const input = vi.hoisted(() => ({ + sources: undefined as unknown as Atom.Writable>, + shell: undefined as unknown as (id: string) => Atom.Writable<{ + status: string; + error: Option.Option; + }>, +})); +vi.mock("../state", async () => { + const { Atom } = await import("effect/reactivity"); + input.sources = Atom.make>({ isReady: true, sources: [] }); + return { fleetSourcesAtom: input.sources }; +}); +vi.mock("../../state/shell", async () => { + const { Atom } = await import("effect/reactivity"); + const Option = await import("effect/Option"); + input.shell = Atom.family((_id: string) => + Atom.make({ status: "live", error: Option.none() }), + ); + return { environmentShell: { stateValueAtom: input.shell } }; +}); +vi.mock("../../state/threads", async () => { + const { Atom } = await import("effect/reactivity"); + return { environmentThreadShells: { threadShellsAtom: Atom.make([]) } }; +}); + +import { fleetAgentKey } from "./fleetPresentation"; +import { fleetFactsAtom } from "./fleetState"; + +const at = "2026-10-26T10:00:00.000Z"; +const origin = EnvironmentId.make("origin"); +const receiver = EnvironmentId.make("receiver"); +const key = fleetAgentKey(origin, "sender"); +const ask = { + exchangeId: "exchange", + counterpartyId: "receiver-agent", + counterpartyName: "Receiver", + intent: "Review", + openedAt: at, +}; +const agent = (open = true): FleetAgent => ({ + participantId: "sender", + threadId: null, + displayName: "Sender", + origin: "human", + placementParentId: null, + crew: null, + openAsks: 0, + facts: { + asks: { owed: [], awaited: open ? [ask] : [] }, + problems: [], + deliveryEnvironmentIds: [receiver], + }, +}); +const sources = ( + options: { + connected?: boolean; + open?: boolean; + mirrorOpen?: boolean; + includeOrigin?: boolean; + oldReceiver?: boolean; + } = {}, +): J5ReadSources => ({ + isReady: true, + sources: [ + ...(options.includeOrigin === false + ? [] + : [ + { + environmentId: origin, + environmentLabel: "Origin", + connected: true, + status: "ready" as const, + error: null, + refreshing: false, + data: { + asOf: at, + remoteDeliveryAlarms: [], + projects: [ + { id: "project", title: "Project", agents: [agent(options.open)], crews: [] }, + ], + }, + }, + ]), + { + environmentId: receiver, + environmentLabel: "Receiver", + connected: options.connected ?? true, + status: options.connected === false ? "offline" : "ready", + error: null, + refreshing: false, + data: { + asOf: at, + projects: [], + ...(options.oldReceiver === true + ? {} + : { + remoteDeliveryAlarms: [ + { + originEnvironmentId: origin, + senderId: "sender", + problem: { + kind: "delivery-failed" as const, + messageId: "message", + receiverId: "receiver-agent", + receiverName: "Receiver", + at, + reason: "Thread delivery failed", + exchangeId: "exchange", + exchangeOpen: options.mirrorOpen ?? true, + }, + }, + ], + }), + }, + }, + ], +}); + +let registry: AtomRegistry.AtomRegistry; +let stop: () => void; +beforeEach(() => { + registry = AtomRegistry.make(); + registry.set(input.sources, sources()); + stop = registry.mount(fleetFactsAtom); +}); +afterEach(() => { + stop(); + registry.dispose(); +}); + +it("attaches a receiver's alarm to the origin row and honors either Exchange closure", () => { + expect(registry.get(fleetFactsAtom).get(key)?.problems).toMatchObject([ + { kind: "delivery-failed", exchangeOpen: true }, + ]); + expect(registry.get(fleetFactsAtom).get(key)?.problemsIncomplete).toBe(false); + for (const closed of [{ open: false }, { mirrorOpen: false }]) { + registry.set(input.sources, sources(closed)); + expect(registry.get(fleetFactsAtom).get(key)?.problems).toMatchObject([ + { kind: "delivery-failed", exchangeOpen: false }, + ]); + } +}); + +it("drops cached receiver alarms on disconnect or a stale shell and recovers on reconnect", () => { + registry.set(input.sources, sources({ connected: false })); + expect(registry.get(fleetFactsAtom).get(key)?.problems).toEqual([]); + expect(registry.get(fleetFactsAtom).get(key)?.problemsIncomplete).toBe(true); + registry.set(input.sources, sources()); + expect(registry.get(fleetFactsAtom).get(key)?.problems).toHaveLength(1); + registry.set(input.shell(receiver), { status: "cached", error: Option.none() }); + expect(registry.get(fleetFactsAtom).get(key)?.problems).toEqual([]); + expect(registry.get(fleetFactsAtom).get(key)?.problemsIncomplete).toBe(true); + registry.set(input.shell(receiver), { status: "live", error: Option.none() }); + expect(registry.get(fleetFactsAtom).get(key)?.problems).toHaveLength(1); + expect(registry.get(fleetFactsAtom).get(key)?.problemsIncomplete).toBe(false); +}); + +it("qualifies old receiver reads and creates no phantom sender row", () => { + registry.set(input.sources, sources({ oldReceiver: true })); + expect(registry.get(fleetFactsAtom).get(key)?.problems).toEqual([]); + expect(registry.get(fleetFactsAtom).get(key)?.problemsIncomplete).toBe(true); + registry.set(input.sources, sources({ includeOrigin: false })); + expect(registry.get(fleetFactsAtom).size).toBe(0); +}); diff --git a/apps/web/src/j5/fleet/fleetState.ts b/apps/web/src/j5/fleet/fleetState.ts index 0fbf6ae7162e0..cdc6f83c0309e 100644 --- a/apps/web/src/j5/fleet/fleetState.ts +++ b/apps/web/src/j5/fleet/fleetState.ts @@ -1,4 +1,8 @@ -import { createFleetFactsAtom, type FleetFactRow } from "@t3tools/client-runtime/j5/fleetFacts"; +import { + createFleetFactsAtom, + mergeFleetDeliveryFacts, + type FleetFactRow, +} from "@t3tools/client-runtime/j5/fleetFacts"; import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; import { ThreadId, type EnvironmentId } from "@t3tools/contracts"; import { Atom } from "effect/reactivity"; @@ -30,7 +34,9 @@ const fleetFactRowsAtom = Atom.make((get): ReadonlyArray => { ]), ); const environments = get(fleetEnvironmentLivenessAtom); - return get(fleetSourcesAtom).sources.flatMap((source) => { + const sources = get(fleetSourcesAtom); + const deliveries = mergeFleetDeliveryFacts(sources, environments); + return sources.sources.flatMap((source) => { const live = environments.get(source.environmentId) === true; return (source.data?.projects ?? []).flatMap((project) => project.agents.map((agent) => { @@ -42,11 +48,14 @@ const fleetFactRowsAtom = Atom.make((get): ReadonlyArray => { scopeThreadRef(source.environmentId, ThreadId.make(agent.threadId)), ), ); + const key = fleetAgentKey(source.environmentId, agent.participantId); + const delivery = deliveries.get(key); return { - key: fleetAgentKey(source.environmentId, agent.participantId), + key, shell: thread?.source, pendingSubagentRequest: thread?.pendingSubagentRequest, - ledger: agent.facts, + ledger: delivery?.ledger, + problemsIncomplete: delivery?.problemsIncomplete ?? true, live, }; }), From a0e89707ffc832c37319e69bb9ef609df9364998 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 26 Oct 2026 13:46:57 +0000 Subject: [PATCH 8/9] test(fleet): respect local timezone in keyboard assertions --- .../src/j5/fleet/FleetFacts.keyboard.test.tsx | 32 ++++++++++++------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx b/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx index f8cf1e1f5e1dd..60a396e6290ee 100644 --- a/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx +++ b/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx @@ -8,6 +8,8 @@ import { act } from "react"; import { createRoot, type Root } from "react-dom/client"; import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test"; +import { formatChatTimestampTooltip } from "../../timestampFormat"; + const state = vi.hoisted(() => ({ facts: undefined as FleetDerivedFacts | undefined, live: true, @@ -84,6 +86,8 @@ vi.mock("../../env", () => ({ isElectron: false })); import { FleetRowItem } from "./FleetPage"; import { FleetSourceReadout } from "./FleetFacts"; +const absoluteTime = (iso: string) => formatChatTimestampTooltip(iso, state.timestampFormat); + const environmentId = EnvironmentId.make("fleet-test"); const agent: FleetAgent = { participantId: "agent:test", @@ -282,17 +286,21 @@ it("refreshes live row, expanded facts, asks and environment times on the shared expect(disclosure().textContent).toContain("Delivery failed · to Reviewer · 3m ago · offline"); expect(disclosure().textContent).toContain("opened 11m ago"); expect(container.querySelector("p")?.textContent).toContain("ledger read 6m ago"); - expect(disclosure().textContent).toContain("12:00, 23rd October 2026"); - expect(disclosure().textContent).toContain("12:03, 23rd October 2026"); - expect(disclosure().textContent).toContain("12:08, 23rd October 2026"); - expect(disclosure().textContent).toContain("Environment read: 6m ago (12:05, 23rd October 2026)"); - expect(container.querySelector("p")?.textContent).toContain("6m ago (12:05, 23rd October 2026)"); + expect(disclosure().textContent).toContain(absoluteTime("2026-10-23T12:00:00Z")); + expect(disclosure().textContent).toContain(absoluteTime("2026-10-23T12:03:00Z")); + expect(disclosure().textContent).toContain(absoluteTime("2026-10-23T12:08:00Z")); + expect(disclosure().textContent).toContain( + `Environment read: 6m ago (${absoluteTime(state.asOf)})`, + ); + expect(container.querySelector("p")?.textContent).toContain( + `6m ago (${absoluteTime(state.asOf)})`, + ); state.timestampFormat = "12-hour"; await refreshState(); - expect(disclosure().textContent).toContain("12:00 PM, 23rd October 2026"); - expect(disclosure().textContent).toContain("12:03 PM, 23rd October 2026"); - expect(disclosure().textContent).toContain("12:08 PM, 23rd October 2026"); + expect(disclosure().textContent).toContain(absoluteTime("2026-10-23T12:00:00Z")); + expect(disclosure().textContent).toContain(absoluteTime("2026-10-23T12:03:00Z")); + expect(disclosure().textContent).toContain(absoluteTime("2026-10-23T12:08:00Z")); }); it("stops aging every measurement when a live row freezes, then resumes from the current clock", async () => { @@ -307,7 +315,7 @@ it("stops aging every measurement when a live row freezes, then resumes from the await refreshState(); const frozen = container.textContent; expect(vi.getTimerCount()).toBe(0); - expect(frozen).toContain("23rd October 2026"); + expect(frozen).toContain(absoluteTime("2026-10-23T12:00:00Z")); expect(disclosure().textContent).toContain("5m at last read · opened"); expect(navigation().textContent).not.toContain("Idle 10m"); expect(navigation().textContent).not.toContain("Last turn ended 7m ago"); @@ -345,9 +353,11 @@ it("advances waiting-to-start ages and freezes their absolute request time", asy state.live = false; await refreshState(); - expect(navigation().textContent).toContain("Waiting to start · since 12:00, 23rd October 2026"); expect(navigation().textContent).toContain( - "Run not dispatched · requested 12:00, 23rd October 2026", + `Waiting to start · since ${absoluteTime("2026-10-23T12:00:00Z")}`, + ); + expect(navigation().textContent).toContain( + `Run not dispatched · requested ${absoluteTime("2026-10-23T12:00:00Z")}`, ); const frozen = navigation().textContent; await act(() => vi.advanceTimersByTime(60_000)); From 0e7b6f613acee18feedc6628349ddd9a1abac9c9 Mon Sep 17 00:00:00 2001 From: Bastian Huppertz Date: Tue, 27 Oct 2026 14:56:04 +0100 Subject: [PATCH 9/9] fix(fleet): badge counts agents with measured problems (#664) * fix(fleet): badge counts agents with measured problems Count live agents with failed runs, overdue dispatch or open-Exchange delivery failures once per environment and participant. Keep source gaps and unmeasured agents explicit, and preserve facts across duplicate project placements. Co-authored-by: GPT-6.1 Sol AI-Model: gpt-6.1-sol AI-Harness: Codex * fix(fleet): omit counts when every source is unavailable * test(fleet): verify cross-environment badge coverage and recovery --------- Co-authored-by: GPT-6.1 Sol Co-authored-by: Codex --- apps/web/src/j5/fleet/FleetPage.tsx | 12 +- apps/web/src/j5/fleet/FleetRailEntry.tsx | 25 +-- apps/web/src/j5/fleet/fleet.logic.test.ts | 4 +- apps/web/src/j5/fleet/fleet.logic.ts | 8 - .../src/j5/fleet/fleetPresentation.test.ts | 57 ++++- apps/web/src/j5/fleet/fleetPresentation.ts | 25 ++- apps/web/src/j5/fleet/fleetState.test.ts | 24 ++- apps/web/src/j5/fleet/fleetState.ts | 28 +++ .../client-runtime/src/j5/fleetFacts.test.ts | 204 +++++++++++++++++- packages/client-runtime/src/j5/fleetFacts.ts | 107 +++++++-- 10 files changed, 442 insertions(+), 52 deletions(-) diff --git a/apps/web/src/j5/fleet/FleetPage.tsx b/apps/web/src/j5/fleet/FleetPage.tsx index 4f8cc44776adb..224c51689b9c6 100644 --- a/apps/web/src/j5/fleet/FleetPage.tsx +++ b/apps/web/src/j5/fleet/FleetPage.tsx @@ -57,8 +57,8 @@ import { type ScopedFleetLedgerProject, } from "./fleetClient"; -import { fleetSeatStatesAtom } from "./fleetState"; -import { fleetAgentKey } from "./fleetPresentation"; +import { fleetSeatStatesAtom, fleetProblemSummaryAtom } from "./fleetState"; +import { fleetAgentKey, fleetProblemNotices } from "./fleetPresentation"; import { FleetFactCells, FleetFactDetails, @@ -111,18 +111,20 @@ export function FleetPage() { const threads = useThreadShells(); const sources = useAtomValue(fleetDetailSourcesAtom); const seatStates = useAtomValue(fleetSeatStatesAtom); + const problemSummary = useAtomValue(fleetProblemSummaryAtom); useFleetDetailRefresh(); const [refreshing, setRefreshing] = useState(false); const projects = useMemo(() => mergeFleetSources(sources), [sources]); const showEnvironment = spansMultipleEnvironments(projects); const loading = !sources.isReady || sources.sources.some((source) => source.status === "loading"); const notices = [ - ...new Set( - sources.sources.flatMap((source) => { + ...new Set([ + ...fleetProblemNotices(problemSummary), + ...sources.sources.flatMap((source) => { const notice = j5SourceNotice(source); return notice === null ? [] : [notice]; }), - ), + ]), ]; const refresh = useCallback(async () => { diff --git a/apps/web/src/j5/fleet/FleetRailEntry.tsx b/apps/web/src/j5/fleet/FleetRailEntry.tsx index 76f8a3bdcd994..462b0fa7eb707 100644 --- a/apps/web/src/j5/fleet/FleetRailEntry.tsx +++ b/apps/web/src/j5/fleet/FleetRailEntry.tsx @@ -1,34 +1,27 @@ import { useAtomValue } from "@effect/atom-react"; import { Link } from "@tanstack/react-router"; import { RadarIcon } from "lucide-react"; -import { useCallback, useMemo } from "react"; +import { useCallback } from "react"; import { useSidebar } from "../../components/ui/sidebar"; import { cn } from "../../lib/utils"; -import { fleetSourcesAtom } from "../state"; -import { countFleetAlerts } from "./fleet.logic"; -import { mergeFleetSources, useFleetRefresh } from "./fleetClient"; +import { useFleetRefresh } from "./fleetClient"; +import { fleetBadgeLabel } from "./fleetPresentation"; +import { fleetProblemSummaryAtom } from "./fleetState"; /** - * Rail entry for the Roster (SB6). The badge counts agents that owe a reply across every - * connected environment, a measured fact, so hidden Background agents stay visible somewhere - * even though the sidebar no longer lists them. + * The always-mounted rail shares the page's facts and local dispatch deadline. */ export function FleetRailEntry({ onBackdrop }: { readonly onBackdrop: boolean }) { const { isMobile, setOpenMobile } = useSidebar(); - const sources = useAtomValue(fleetSourcesAtom); + const summary = useAtomValue(fleetProblemSummaryAtom); useFleetRefresh(); - const alerts = useMemo(() => { - const known = sources.sources.filter((source) => source.data !== null); - return known.length === 0 ? null : countFleetAlerts(mergeFleetSources(sources)); - }, [sources]); const closeMobileSidebar = useCallback(() => { if (isMobile) setOpenMobile(false); }, [isMobile, setOpenMobile]); - const label = - alerts === null || alerts === 0 ? "Open fleet" : `Open fleet, ${alerts} agents owe a reply`; + const label = fleetBadgeLabel(summary); return ( - {alerts !== null && alerts > 0 ? ( + {summary.agentsWithProblems > 0 ? ( - {alerts} + {summary.agentsWithProblems} ) : null} diff --git a/apps/web/src/j5/fleet/fleet.logic.test.ts b/apps/web/src/j5/fleet/fleet.logic.test.ts index 370cb03f8ac7a..1ccf88e881ff9 100644 --- a/apps/web/src/j5/fleet/fleet.logic.test.ts +++ b/apps/web/src/j5/fleet/fleet.logic.test.ts @@ -10,7 +10,6 @@ import { } from "../crew/crewState"; import { buildFleetTree, - countFleetAlerts, countFleetProjects, createFleetRowRefresher, fleetInvolvedThreadRefs, @@ -88,14 +87,13 @@ describe("fleet tree", () => { ]); }); - it("never loops on a cyclic placement and counts alerts from owed asks only", () => { + it("never loops on a cyclic placement", () => { const cyclic: FleetLedgerProject = { ...project, agents: [agent("a", { placementParentId: "b" }), agent("b", { placementParentId: "a" })], }; const roots = buildFleetTree(cyclic); expect(roots.map((node) => node.row.agent.participantId).length).toBeGreaterThan(0); - expect(countFleetAlerts([project])).toBe(1); expect(originLabel({ origin: "unknown" })).toBe("?"); }); }); diff --git a/apps/web/src/j5/fleet/fleet.logic.ts b/apps/web/src/j5/fleet/fleet.logic.ts index bd46a5e52cbf1..7667d3d450710 100644 --- a/apps/web/src/j5/fleet/fleet.logic.ts +++ b/apps/web/src/j5/fleet/fleet.logic.ts @@ -284,14 +284,6 @@ export function countFleetProjects< ).size; } -/** Roster alert badge: measured "needs a human" facts only, so nothing here is guessed. */ -export const countFleetAlerts = (projects: ReadonlyArray) => - projects.reduce( - (count, ledgerProject) => - count + ledgerProject.agents.filter((agent) => agent.openAsks > 0).length, - 0, - ); - /** * Origin copy for the Roster row; unknown renders as `?` rather than a plausible guess. An * outside agent that started the agent is named by the label it signed in with, and by its id diff --git a/apps/web/src/j5/fleet/fleetPresentation.test.ts b/apps/web/src/j5/fleet/fleetPresentation.test.ts index 0a859dc346ca7..a72b1bc66820f 100644 --- a/apps/web/src/j5/fleet/fleetPresentation.test.ts +++ b/apps/web/src/j5/fleet/fleetPresentation.test.ts @@ -1,5 +1,8 @@ import { describe, expect, it, vi } from "vite-plus/test"; -import type { FleetDerivedFacts } from "@t3tools/client-runtime/j5/fleetFacts"; +import { + summarizeFleetProblems, + type FleetDerivedFacts, +} from "@t3tools/client-runtime/j5/fleetFacts"; import type { FleetRuntimeFact } from "@t3tools/contracts/j5"; import { fleetCrewSummary, @@ -8,6 +11,8 @@ import { fleetTime, fleetAgo, fleetProblemLabel, + fleetBadgeLabel, + fleetProblemNotices, fleetSeatState, fleetSourceIsLive, fleetStatusLabel, @@ -27,6 +32,56 @@ const facts = (value: FleetRuntimeFact): FleetDerivedFacts => ({ }); describe("Fleet presentation", () => { + it("qualifies zero and positive badge counts when source or agent measurements are missing", () => { + const complete = { + agentsWithProblems: 0, + unmeasuredAgents: 0, + incompleteSources: false, + hasReadableSource: true, + }; + expect(fleetBadgeLabel(complete)).toBe("Open fleet, 0 agents have measured problems."); + expect(fleetProblemNotices(complete)).toEqual([]); + const unmeasured = { ...complete, unmeasuredAgents: 1 }; + expect(fleetBadgeLabel(unmeasured)).toContain("1 agent unmeasured."); + expect(fleetBadgeLabel(unmeasured)).toContain("Counts include current measured problems only."); + expect(fleetBadgeLabel(unmeasured)).not.toContain("coverage is incomplete"); + const partial = { ...unmeasured, agentsWithProblems: 1, incompleteSources: true }; + expect(fleetBadgeLabel(partial)).toContain("1 agent has measured problems."); + expect(fleetBadgeLabel(partial)).toContain("Problem coverage is incomplete"); + expect(fleetProblemNotices(partial)).toContain( + "Counts include current measured problems only.", + ); + }); + it("distinguishes an unavailable count from a measured zero, including an empty live source", () => { + const measured = new Map([ + [ + "env:agent", + { + ...facts(runtime("failed")), + asks: { owed: [], awaited: [] }, + problems: [{ kind: "failed-run" as const, runId: "run", at }], + }, + ], + ]); + for (const sourceFacts of [new Map(), measured]) { + const unavailable = summarizeFleetProblems( + sourceFacts, + new Map([["env:agent", false]]), + "unavailable", + ); + expect(fleetBadgeLabel(unavailable)).toContain("problem count unavailable"); + expect(fleetBadgeLabel(unavailable)).not.toMatch(/\d/); + expect(fleetBadgeLabel(unavailable)).toContain("coverage is incomplete"); + } + const emptyLive = summarizeFleetProblems(new Map(), new Map(), "complete"); + expect(fleetBadgeLabel(emptyLive)).toBe("Open fleet, 0 agents have measured problems."); + const partialZero = summarizeFleetProblems(new Map(), new Map(), "partial"); + expect(fleetBadgeLabel(partialZero)).toContain("0 agents have measured problems"); + expect(fleetBadgeLabel(partialZero)).toContain("coverage is incomplete"); + const restored = summarizeFleetProblems(measured, new Map([["env:agent", true]]), "partial"); + expect(fleetBadgeLabel(restored)).toContain("1 agent has measured problems"); + expect(fleetBadgeLabel(restored)).toContain("coverage is incomplete"); + }); it("uses runtime vocabulary and makes old or unavailable measurements explicit", () => { for (const [status, label] of [ ["working", "Working"], diff --git a/apps/web/src/j5/fleet/fleetPresentation.ts b/apps/web/src/j5/fleet/fleetPresentation.ts index 09536cdb1946b..7fd8d69651182 100644 --- a/apps/web/src/j5/fleet/fleetPresentation.ts +++ b/apps/web/src/j5/fleet/fleetPresentation.ts @@ -1,4 +1,4 @@ -import type { FleetDerivedFacts } from "@t3tools/client-runtime/j5/fleetFacts"; +import type { FleetDerivedFacts, FleetProblemSummary } from "@t3tools/client-runtime/j5/fleetFacts"; import type { J5ReadSource } from "@t3tools/client-runtime/j5/readSources"; import type { FleetProblem, FleetRuntimeFact } from "@t3tools/contracts/j5"; import type { TimestampFormat } from "@t3tools/contracts/settings"; @@ -7,6 +7,29 @@ import type { CrewSeatState } from "../crew/crewState"; export { fleetAgentKey } from "@t3tools/client-runtime/j5/fleetFacts"; +export const fleetProblemNotices = (summary: FleetProblemSummary): ReadonlyArray => [ + ...(summary.incompleteSources + ? [ + "Problem coverage is incomplete: some environments are unavailable or do not report Fleet facts.", + ] + : []), + ...(summary.unmeasuredAgents > 0 + ? [ + `${summary.unmeasuredAgents} ${summary.unmeasuredAgents === 1 ? "agent" : "agents"} unmeasured.`, + ] + : []), + ...(summary.incompleteSources || summary.unmeasuredAgents > 0 + ? ["Counts include current measured problems only."] + : []), +]; + +export const fleetBadgeLabel = (summary: FleetProblemSummary) => + `${ + summary.hasReadableSource + ? `Open fleet, ${summary.agentsWithProblems} ${summary.agentsWithProblems === 1 ? "agent has" : "agents have"} measured problems.` + : "Open fleet, problem count unavailable." + } ${fleetProblemNotices(summary).join(" ")}`.trim(); + export const fleetSourceIsLive = ( source: Pick, "connected" | "status">, shellStatus: string, diff --git a/apps/web/src/j5/fleet/fleetState.test.ts b/apps/web/src/j5/fleet/fleetState.test.ts index 95686e8c20d51..2437b6f92b15c 100644 --- a/apps/web/src/j5/fleet/fleetState.test.ts +++ b/apps/web/src/j5/fleet/fleetState.test.ts @@ -31,7 +31,7 @@ vi.mock("../../state/threads", async () => { }); import { fleetAgentKey } from "./fleetPresentation"; -import { fleetFactsAtom } from "./fleetState"; +import { fleetFactsAtom, fleetProblemSummaryAtom } from "./fleetState"; const at = "2026-10-26T10:00:00.000Z"; const origin = EnvironmentId.make("origin"); @@ -169,3 +169,25 @@ it("qualifies old receiver reads and creates no phantom sender row", () => { registry.set(input.sources, sources({ includeOrigin: false })); expect(registry.get(fleetFactsAtom).size).toBe(0); }); + +it("updates badge eligibility and coverage through closure, disconnection, old reads and recovery", () => { + const stopBadge = registry.mount(fleetProblemSummaryAtom); + try { + const badge = () => registry.get(fleetProblemSummaryAtom); + expect(badge()).toMatchObject({ agentsWithProblems: 1, incompleteSources: false }); + registry.set(input.sources, sources({ open: false })); + expect(badge()).toMatchObject({ agentsWithProblems: 0, incompleteSources: false }); + registry.set(input.sources, sources({ mirrorOpen: false })); + expect(badge()).toMatchObject({ agentsWithProblems: 0, incompleteSources: false }); + registry.set(input.sources, sources({ connected: false })); + expect(badge()).toMatchObject({ agentsWithProblems: 0, incompleteSources: true }); + registry.set(input.sources, sources({ oldReceiver: true })); + expect(badge()).toMatchObject({ agentsWithProblems: 0, incompleteSources: true }); + registry.set(input.sources, sources()); + expect(badge()).toMatchObject({ agentsWithProblems: 1, incompleteSources: false }); + registry.set(input.sources, sources({ includeOrigin: false })); + expect(badge().agentsWithProblems).toBe(0); + } finally { + stopBadge(); + } +}); diff --git a/apps/web/src/j5/fleet/fleetState.ts b/apps/web/src/j5/fleet/fleetState.ts index cdc6f83c0309e..bd48f0907c71b 100644 --- a/apps/web/src/j5/fleet/fleetState.ts +++ b/apps/web/src/j5/fleet/fleetState.ts @@ -1,5 +1,6 @@ import { createFleetFactsAtom, + summarizeFleetProblems, mergeFleetDeliveryFacts, type FleetFactRow, } from "@t3tools/client-runtime/j5/fleetFacts"; @@ -74,6 +75,33 @@ export const fleetLiveAgentAtom = Atom.family((key: string) => Atom.make((get) => get(fleetLiveRowsAtom).get(key) === true), ); +export const fleetProblemSummaryAtom = Atom.make((get) => { + const sources = get(fleetSourcesAtom); + const environments = get(fleetEnvironmentLivenessAtom); + const readable = sources.sources.filter( + (source) => environments.get(source.environmentId) === true, + ); + const summary = summarizeFleetProblems( + get(fleetFactsAtom), + get(fleetLiveRowsAtom), + readable.length === 0 + ? "unavailable" + : sources.isReady && + readable.length === sources.sources.length && + readable.every((source) => source.data?.asOf !== undefined) + ? "complete" + : "partial", + ); + const previous = Option.getOrUndefined(get.self()); + return previous !== undefined && + previous.agentsWithProblems === summary.agentsWithProblems && + previous.unmeasuredAgents === summary.unmeasuredAgents && + previous.incompleteSources === summary.incompleteSources && + previous.hasReadableSource === summary.hasReadableSource + ? previous + : summary; +}); + /** Only classification changes rebuild the placement sections; activity and elapsed time do not. */ export const fleetSeatStatesAtom = Atom.make((get) => { const live = get(fleetLiveRowsAtom); diff --git a/packages/client-runtime/src/j5/fleetFacts.test.ts b/packages/client-runtime/src/j5/fleetFacts.test.ts index 8aa3e68db318d..6b449a5367afb 100644 --- a/packages/client-runtime/src/j5/fleetFacts.test.ts +++ b/packages/client-runtime/src/j5/fleetFacts.test.ts @@ -20,6 +20,7 @@ import type { J5ReadSource } from "./readSources.ts"; import { createFleetFactsAtom, deriveFleetFacts, + summarizeFleetProblems, fleetAgentKey, mergeFleetDeliveryFacts, type FleetFactRow, @@ -30,7 +31,11 @@ const decodeFleet = Schema.decodeUnknownSync(FleetResponse); const at = "2026-10-19T10:00:00.000Z"; const now = Date.parse(at); const date = DateTime.makeUnsafe(at); -const ledger: FleetAgentFacts = { asks: { owed: [], awaited: [] }, problems: [] }; +const ledger: FleetAgentFacts = { + asks: { owed: [], awaited: [] }, + problems: [], + deliveryEnvironmentIds: [], +}; const shell = (changes: Partial = {}): OrchestrationV2ThreadShell => ({ ...v2ThreadShell, latestRunId: RunId.make("r"), @@ -47,6 +52,198 @@ const derive = (source: OrchestrationV2ThreadShell | undefined, clock = now) => afterEach(() => vi.useRealTimers()); +const deliveryProblem = (exchangeOpen: boolean) => ({ + kind: "delivery-failed" as const, + messageId: "message", + receiverId: "receiver", + receiverName: null, + at, + reason: "transport unavailable", + exchangeOpen, +}); + +describe("Fleet problem badge", () => { + it("keeps alarms from every project placement without duplicating shared asks or badge agents", () => { + const ask = { + exchangeId: "shared", + counterpartyId: "other", + counterpartyName: null, + intent: "help", + openedAt: at, + }; + const source = shell({ + status: "completed", + activityRunStatus: null, + latestRunStartedAt: date, + latestRunCompletedAt: date, + }); + const rows = Atom.make>([ + { + key: "env:sender", + shell: source, + ledger: { asks: { owed: [], awaited: [ask] }, problems: [deliveryProblem(true)] }, + live: true, + }, + { + key: "env:sender", + shell: source, + ledger: { asks: { owed: [], awaited: [ask] }, problems: [] }, + live: true, + }, + ]); + const facts = createFleetFactsAtom(rows); + const registry = AtomRegistry.make({ defaultIdleTTL: 0 }); + const stop = registry.subscribe(facts, () => {}, { immediate: true }); + expect(registry.get(facts).size).toBe(1); + expect(registry.get(facts).get("env:sender")?.asks?.awaited).toEqual([ask]); + expect(registry.get(facts).get("env:sender")?.problems).toEqual([deliveryProblem(true)]); + expect( + summarizeFleetProblems(registry.get(facts), new Map([["env:sender", true]]), "complete") + .agentsWithProblems, + ).toBe(1); + stop(); + registry.dispose(); + }); + it("counts each live environment+participant once regardless of how many problems it has", () => { + const failed = derive(shell({ status: "failed", activityRunStatus: null })).facts; + const mixed = { ...failed, problems: [...failed.problems, deliveryProblem(true)] }; + const facts = new Map([ + ["env-a:sender", mixed], + ["env-b:sender", failed], + ["offline:sender", mixed], + ["plain", { ...failed, problems: [deliveryProblem(false)] }], + ["closed-exchange", { ...failed, problems: [deliveryProblem(false)] }], + [ + "open-asks", + { + ...derive(shell()).facts, + asks: { + owed: [ + { + exchangeId: "ask", + counterpartyId: "other", + counterpartyName: null, + intent: "help", + openedAt: at, + }, + ], + awaited: [], + }, + }, + ], + ]); + const live = new Map([...facts.keys()].map((key) => [key, key !== "offline:sender"])); + expect(summarizeFleetProblems(facts, live, "partial")).toEqual({ + agentsWithProblems: 2, + unmeasuredAgents: 0, + incompleteSources: true, + hasReadableSource: true, + }); + // Silence and platform notices have no problem fact; absence must not manufacture one. + expect( + summarizeFleetProblems( + new Map([["notice", derive(shell()).facts]]), + new Map([["notice", true]]), + "complete", + ).agentsWithProblems, + ).toBe(0); + }); + + it("separates an unrecorded seat's missing runtime from missing source coverage", () => { + const unrecordedSeat = deriveFleetFacts({ shell: undefined, ledger, now }).facts; + const facts = new Map([["seat-without-thread", unrecordedSeat]]); + const live = new Map([["seat-without-thread", true]]); + expect(summarizeFleetProblems(facts, live, "complete")).toEqual({ + agentsWithProblems: 0, + unmeasuredAgents: 1, + incompleteSources: false, + hasReadableSource: true, + }); + facts.set("seat-without-thread", { ...unrecordedSeat, problems: [deliveryProblem(true)] }); + expect(summarizeFleetProblems(facts, live, "complete").agentsWithProblems).toBe(1); + facts.set("seat-without-thread", { ...unrecordedSeat, asks: undefined }); + expect(summarizeFleetProblems(facts, live, "complete")).toEqual({ + agentsWithProblems: 0, + unmeasuredAgents: 1, + incompleteSources: true, + hasReadableSource: true, + }); + expect(summarizeFleetProblems(new Map(), new Map(), "unavailable").incompleteSources).toBe( + true, + ); + live.set("seat-without-thread", false); + expect(summarizeFleetProblems(facts, live, "partial").unmeasuredAgents).toBe(0); + }); + + it("updates the badge at the shared deadline, then clears on dispatch, healthy run and Exchange close", () => { + vi.useFakeTimers(); + vi.setSystemTime(now); + const rows = Atom.make>([ + { key: "env:sender", shell: shell(), ledger, live: true }, + ]); + const facts = createFleetFactsAtom(rows); + const badge = Atom.make((get) => + summarizeFleetProblems( + get(facts), + new Map(get(rows).map((row) => [row.key, row.live])), + get(rows).some((row) => row.live) ? "complete" : "unavailable", + ), + ); + const registry = AtomRegistry.make({ defaultIdleTTL: 0 }); + const rail = registry.subscribe(badge, () => {}, { immediate: true }); + const page = registry.subscribe(facts, () => {}, { immediate: true }); + const count = () => registry.get(badge).agentsWithProblems; + const update = (source: OrchestrationV2ThreadShell, measured = ledger) => + registry.set(rows, [{ key: "env:sender", shell: source, ledger: measured, live: true }]); + vi.advanceTimersByTime(0); + expect(vi.getTimerCount()).toBe(1); + vi.advanceTimersByTime(FLEET_DISPATCH_THRESHOLD_MS - 1); + expect(count()).toBe(0); + vi.advanceTimersByTime(1); + expect(count()).toBe(1); + vi.advanceTimersByTime(0); + expect(vi.getTimerCount()).toBe(0); + const started = shell({ + status: "running", + activityRunStatus: "running", + latestRunStartedAt: date, + }); + update(started); + expect(count()).toBe(0); + update({ ...started, status: "failed", activityRunStatus: null, latestRunCompletedAt: date }); + expect(count()).toBe(1); + const healthy = { + ...started, + status: "completed" as const, + activityRunStatus: null, + latestRunCompletedAt: date, + }; + update(healthy); + expect(count()).toBe(0); + update(healthy, { ...ledger, problems: [deliveryProblem(true)] }); + expect(count()).toBe(1); + registry.set( + rows, + registry.get(rows).map((row) => ({ ...row, live: false })), + ); + expect(registry.get(facts).get("env:sender")?.problems).toEqual([deliveryProblem(true)]); + expect(registry.get(badge)).toEqual({ + agentsWithProblems: 0, + unmeasuredAgents: 0, + incompleteSources: true, + hasReadableSource: false, + }); + update(healthy, { ...ledger, problems: [deliveryProblem(true)] }); + expect(count()).toBe(1); + update(healthy, { ...ledger, problems: [deliveryProblem(false)] }); + expect(count()).toBe(0); + expect(registry.get(facts).get("env:sender")?.problems).toEqual([deliveryProblem(false)]); + rail(); + page(); + registry.dispose(); + }); +}); + describe("Fleet runtime measurements", () => { it("crosses the exact dispatch boundary once and recovers immediately when dispatched", () => { const before = derive(shell(), now + FLEET_DISPATCH_THRESHOLD_MS - 1); @@ -601,7 +798,10 @@ describe("receiving-environment delivery alarm merge", () => { merge(origin({ ...ledger, deliveryEnvironmentIds: [] }), ...unavailable).get(key) ?.problemsIncomplete, ).toBe(false); - expect(merge(origin(ledger), receiver()).get(key)?.problemsIncomplete).toBe(true); + expect( + merge(origin({ asks: ledger.asks, problems: ledger.problems }), receiver()).get(key) + ?.problemsIncomplete, + ).toBe(true); const staleOrigin = { ...origin(), connected: false, status: "offline" as const }; expect(merge(staleOrigin, receiver()).get(key)).toMatchObject({ ledger: { problems: [] }, diff --git a/packages/client-runtime/src/j5/fleetFacts.ts b/packages/client-runtime/src/j5/fleetFacts.ts index 079e9d91d6792..8439605ef0887 100644 --- a/packages/client-runtime/src/j5/fleetFacts.ts +++ b/packages/client-runtime/src/j5/fleetFacts.ts @@ -142,6 +142,49 @@ export interface FleetDerivedFacts { readonly problemsIncomplete: boolean; } +export interface FleetProblemSummary { + readonly agentsWithProblems: number; + readonly unmeasuredAgents: number; + readonly incompleteSources: boolean; + readonly hasReadableSource: boolean; +} + +/** Keys identify environment + participant, so repeated project placements count once. */ +export const summarizeFleetProblems = ( + facts: ReadonlyMap, + liveRows: ReadonlyMap, + sourceCoverage: "complete" | "partial" | "unavailable", +): FleetProblemSummary => { + let agentsWithProblems = 0; + let unmeasuredAgents = 0; + let incompleteSources = sourceCoverage !== "complete"; + for (const [key, live] of liveRows) { + if (!live) { + incompleteSources = true; + continue; + } + const row = facts.get(key); + if (row?.asks === undefined || row.problemsIncomplete) incompleteSources = true; + if (row === undefined || row.runtime.state === "unknown" || row.asks === undefined) + unmeasuredAgents++; + if ( + row?.problems.some( + (problem) => + problem.kind === "failed-run" || + problem.kind === "dispatch-overdue" || + (problem.kind === "delivery-failed" && problem.exchangeOpen), + ) + ) + agentsWithProblems++; + } + return { + agentsWithProblems, + unmeasuredAgents, + incompleteSources, + hasReadableSource: sourceCoverage !== "unavailable", + }; +}; + export const deriveFleetFacts = (input: { readonly shell: OrchestrationV2ThreadShell | undefined; readonly ledger: FleetAgentFacts | undefined; @@ -299,6 +342,37 @@ export interface FleetFactRow { readonly problemsIncomplete?: boolean | undefined; } +const uniqueFacts = (values: ReadonlyArray, key: (value: A) => string): ReadonlyArray => [ + ...new Map(values.map((value) => [key(value), value])).values(), +]; + +const mergeAgentFacts = (left: FleetDerivedFacts, right: FleetDerivedFacts): FleetDerivedFacts => ({ + problemsIncomplete: left.problemsIncomplete || right.problemsIncomplete, + runtime: left.runtime.state === "known" ? left.runtime : right.runtime, + lastActivity: + left.lastActivity.state === "known" && + (right.lastActivity.state === "unknown" || + Date.parse(left.lastActivity.at) >= Date.parse(right.lastActivity.at)) + ? left.lastActivity + : right.lastActivity, + asks: + left.asks === undefined || right.asks === undefined + ? undefined + : { + owed: uniqueFacts([...left.asks.owed, ...right.asks.owed], (ask) => ask.exchangeId), + awaited: uniqueFacts( + [...left.asks.awaited, ...right.asks.awaited], + (ask) => ask.exchangeId, + ), + }, + problems: uniqueFacts([...left.problems, ...right.problems], (problem) => + JSON.stringify([ + problem.kind, + problem.kind === "delivery-failed" ? problem.messageId : problem.runId, + ]), + ), +}); + /** Shared by every consumer in one registry. Only a future dispatch boundary schedules work. */ export const createFleetFactsAtom = (rows: Atom.Atom>) => Atom.make((get) => { @@ -318,19 +392,18 @@ export const createFleetFactsAtom = (rows: Atom.Atom state: "unknown" as const, reason: "This environment is unavailable; runtime and activity are not current.", }; - facts.set( - row.key, - frozen ?? { - ...deriveFleetFacts({ - shell: undefined, - ledger: row.ledger, - problemsIncomplete: true, - now, - }).facts, - runtime: unknown, - lastActivity: unknown, - }, - ); + const stale = frozen ?? { + ...deriveFleetFacts({ + shell: undefined, + ledger: row.ledger, + problemsIncomplete: true, + now, + }).facts, + runtime: unknown, + lastActivity: unknown, + }; + const existing = facts.get(row.key); + facts.set(row.key, existing === undefined ? stale : mergeAgentFacts(existing, stale)); continue; } const result = deriveFleetFacts({ @@ -340,15 +413,19 @@ export const createFleetFactsAtom = (rows: Atom.Atom problemsIncomplete: row.problemsIncomplete, now, }); - const cached = previous?.get(row.key); + const existing = facts.get(row.key); facts.set( row.key, - cached !== undefined && Equal.equals(cached, result.facts) ? cached : result.facts, + existing === undefined ? result.facts : mergeAgentFacts(existing, result.facts), ); if (result.nextDeadline !== undefined) { nextDeadline = Math.min(nextDeadline ?? result.nextDeadline, result.nextDeadline); } } + for (const [key, value] of facts) { + const cached = previous?.get(key); + if (cached !== undefined && Equal.equals(cached, value)) facts.set(key, cached); + } if (nextDeadline !== undefined) { // @effect-diagnostics-next-line globalTimers:off - Atom lifecycle owns this one deadline, outside an Effect runtime. const timer = setTimeout(() => get.refreshSelf(), nextDeadline - now);