diff --git a/FORK.md b/FORK.md index bf5d67e67405f..e8a1ace58706b 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; receiving-server alarms carry their origin identity for the shared client merge, whose badge coverage follows each sender's open-Exchange receiving environments. 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. `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. @@ -806,7 +808,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, 85 | +| `apps/web/src/components/CommandPalette.tsx` | A | 42, 71, 75, 85, 34 | | `apps/web/src/components/ConfirmDialogHost.tsx` | R | 22 | | `apps/web/src/components/LegacySidebar.tsx` | A | 21, 22, 85 | | `apps/web/src/components/Sidebar.logic.test.ts` | R | 21 | @@ -849,6 +851,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 | @@ -866,7 +869,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, patched-package pins | +| `pnpm-lock.yaml` | N | 34, 45, patched-package pins | | `pnpm-workspace.yaml` | N | patched-package pins | | `scripts/build-cli-archive.ts` | N | 50 | | `scripts/build-desktop-artifact.test.ts` | A | B, S, 50 | 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/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 5f2a2535773f0..ef8c5d556b47d 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 { useCanAddProject, useCanStartIn } from "../j5/sharing/access"; @@ -1684,6 +1685,7 @@ function OpenCommandPaletteDialog(props: { projectRef: contextualProjectRef, }); const highlightsPaletteItems = useHighlightsPaletteItems(); + const fleetPaletteItems = useFleetPaletteItems(); const actionItems: Array = []; if (projects.length > 0 && projectThreadItems.length > 0) { const activeProjectTitle = @@ -2161,7 +2163,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.keyboard.test.tsx b/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx new file mode 100644 index 0000000000000..60a396e6290ee --- /dev/null +++ b/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx @@ -0,0 +1,411 @@ +// @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 } 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, + version: 0, + listeners: new Set<() => void>(), + timestampFormat: "24-hour" as "12-hour" | "24-hour", + asOf: "2026-10-23T12:05:00Z", +})); +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("../state", () => ({ + fleetSourcesAtom: { + read: () => ({ + sources: [ + { environmentId: "fleet-test", environmentLabel: "Test", data: { asOf: state.asOf } }, + ], + }), + }, +})); +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"; +import { FleetSourceReadout } from "./FleetFacts"; + +const absoluteTime = (iso: string) => formatChatTimestampTooltip(iso, state.timestampFormat); + +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: [], + problemsIncomplete: false, +}; +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.timestampFormat = "24-hour"; + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-10-23T12:10:00Z")); + navigate.mockClear(); + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); +}); +afterEach(async () => { + await act(() => root.unmount()); + container.remove(); + vi.useRealTimers(); + vi.unstubAllGlobals(); +}); +async function render(rowAgent = agent) { + await act(() => + root.render( + <> + +
    + 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])")!; + +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({ advanceTimers: vi.advanceTimersByTime }); + await render(); + expect(disclosure().hidden).toBe(true); + 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 · 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( + "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({ advanceTimers: vi.advanceTimersByTime }); + 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({ advanceTimers: vi.advanceTimersByTime }); + 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"); +}); + +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 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 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(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(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 () => { + state.facts = timedFacts; + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + await render(); + summary().focus(); + await key(user, "{Enter}"); + expect(navigation().textContent).toContain("Idle 10m"); + + state.live = false; + await refreshState(); + const frozen = container.textContent; + expect(vi.getTimerCount()).toBe(0); + 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"); + 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 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 () => { + 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 ago"); + await act(() => vi.advanceTimersByTime(60_000)); + expect(navigation().textContent).toContain("Waiting to start · 11m"); + expect(navigation().textContent).toContain("Run not dispatched · requested 11m ago"); + + state.live = false; + await refreshState(); + expect(navigation().textContent).toContain( + `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)); + 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"); +}); + +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 new file mode 100644 index 0000000000000..5c75b27686e5b --- /dev/null +++ b/apps/web/src/j5/fleet/FleetFacts.tsx @@ -0,0 +1,491 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { FleetDerivedFacts } from "@t3tools/client-runtime/j5/fleetFacts"; +import type { EnvironmentId } from "@t3tools/contracts"; +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, + fleetLiveRowsAtom, + fleetAgentFactsAtom, + fleetLiveAgentAtom, + fleetEnvironmentLivenessAtom, + fleetReadTimeAtom, +} from "./fleetState"; +import { + fleetCrewSummary, + fleetAgentKey, + fleetStatusLabel, + fleetMinutes, + fleetTime, + fleetAgo, + 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, + className, +}: { + readonly reason: string | undefined; + readonly children: ReactNode; + readonly className?: string; +}) { + if (reason === undefined) return {children}; + return ( + + }>{children} + {reason} + + ); +} + +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); + return ( +
+ {sources.sources.map((source) => ( +

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

+ ))} +
+ ); +} + +function AskDetails({ + asks, + 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 ( +
+ {( + [ + ["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`} · ` + : null} + opened{" "} + {plain ? ( + fleetAgo(ask.openedAt, now, timestampFormat) + ) : ( + + )} + {!live ? " (stale)" : null} +

+ ))} +
+ ))} +
+ ); +} + +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, + 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 + ) : ( + + )} +

+

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

+

+ 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} ${fleetAgo(activity.at, now, timestampFormat)}` + } + /> + )} +

+
+

Problems

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

+ fleetProblemLabel(problem, now, timestampFormat)} + /> +

+ ))} + {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.problemsIncomplete && + facts.problems.length === 0 ? ( +

No measured problems.

+ ) : null} +
+
+ ); +} + +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 ? "?" : } + {!live ? (stale) : null} + + {facts?.asks === undefined ? ( + + ? + + ) : ( + + )} + + {activity?.state === "known" ? ( + + `${activity.label} ${fleetAgo(activity.at, now, timestampFormat)}` + } + /> + ) : ( + "?" + )} + + + + ); +} + +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 && !facts.problemsIncomplete && runtimeKnown && ledgerKnown) + return null; + return ( + + {facts?.problems.map((problem) => ( + + fleetProblemLabel(problem, now, timestampFormat)} + /> + + ))} + {ledgerKnown && facts?.problemsIncomplete ? ( + + Delivery problems ? + + ) : null} + {!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 2d49d41b0b8fb..224c51689b9c6 100644 --- a/apps/web/src/j5/fleet/FleetPage.tsx +++ b/apps/web/src/j5/fleet/FleetPage.tsx @@ -12,7 +12,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"; @@ -34,12 +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, - formatCrewStateSummary, - summarizeCrewState, -} from "../crew/crewState"; +import { crewHasRunningSeat, summarizeCrewState } from "../crew/crewState"; import { stopCrew } from "../crew/crewStopClient"; import { countFleetProjects, @@ -63,8 +57,19 @@ import { type ScopedFleetLedgerProject, } from "./fleetClient"; +import { fleetSeatStatesAtom, fleetProblemSummaryAtom } from "./fleetState"; +import { fleetAgentKey, fleetProblemNotices } from "./fleetPresentation"; +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 = "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; @@ -105,18 +110,21 @@ export function FleetPage() { const navigate = useNavigate(); 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 () => { @@ -146,15 +154,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], @@ -208,7 +218,7 @@ export function FleetPage() { -
+

Fleet

@@ -229,6 +239,7 @@ export function FleetPage() { Refresh
+ {notices.length > 0 ? (
    {notices.map((notice) => ( @@ -302,29 +313,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 }) => ( - - ))} -
    ); } @@ -347,7 +360,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 }) => { @@ -449,12 +462,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 : ( @@ -669,7 +684,7 @@ function ProjectLabel( ); } -function FleetRowItem( +export function FleetRowItem( props: FleetRowsProps & { readonly project: ScopedFleetLedgerProject; readonly row: FleetRow; @@ -681,10 +696,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/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 fd65266f39c26..1ccf88e881ff9 100644 --- a/apps/web/src/j5/fleet/fleet.logic.test.ts +++ b/apps/web/src/j5/fleet/fleet.logic.test.ts @@ -2,10 +2,14 @@ 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, countFleetProjects, createFleetRowRefresher, fleetInvolvedThreadRefs, @@ -83,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("?"); }); }); @@ -305,8 +308,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 +462,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 +523,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..7667d3d450710 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)) { @@ -291,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/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..a72b1bc66820f --- /dev/null +++ b/apps/web/src/j5/fleet/fleetPresentation.test.ts @@ -0,0 +1,227 @@ +import { describe, expect, it, vi } from "vite-plus/test"; +import { + summarizeFleetProblems, + type FleetDerivedFacts, +} from "@t3tools/client-runtime/j5/fleetFacts"; +import type { FleetRuntimeFact } from "@t3tools/contracts/j5"; +import { + fleetCrewSummary, + fleetAgentKey, + fleetMinutes, + fleetTime, + fleetAgo, + fleetProblemLabel, + fleetBadgeLabel, + fleetProblemNotices, + 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: [], + problemsIncomplete: false, +}); + +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"], + ["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("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(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 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("?"); + expect(fleetTime("invalid")).toBe("?"); + + vi.useFakeTimers(); + try { + vi.setSystemTime(now); + const stale = fleetStatusLabel(idle); + expect(stale).toContain("18th October 2026"); + vi.advanceTimersByTime(3 * 86_400_000); + 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 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( + "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"); + 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..7fd8d69651182 --- /dev/null +++ b/apps/web/src/j5/fleet/fleetPresentation.ts @@ -0,0 +1,134 @@ +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"; +import { formatChatTimestampTooltip, formatElapsedDurationLabel } from "../../timestampFormat"; +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, +) => source.connected && source.status === "ready" && shellStatus === "live"; + +// 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 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)); + +export const fleetStatusLabel = ( + runtime: FleetRuntimeFact, + now?: number, + timestampFormat?: TimestampFormat, +) => { + 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${now === undefined ? " since" : ""} ${fleetTime(runtime.since, now, timestampFormat)}`; + } +}; + +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, + now?: number, + timestampFormat?: TimestampFormat, +) => { + switch (problem.kind) { + case "failed-run": + return `Latest run failed · ${problem.at === null ? "time unavailable" : fleetAgo(problem.at, now, timestampFormat)}`; + case "dispatch-overdue": + return `Run not dispatched · requested ${fleetAgo(problem.at, now, timestampFormat)}`; + case "delivery-failed": + return `Delivery failed · to ${problem.receiverName ?? problem.receiverId} · ${fleetAgo(problem.at, now, timestampFormat)} · ${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.test.ts b/apps/web/src/j5/fleet/fleetState.test.ts new file mode 100644 index 0000000000000..2437b6f92b15c --- /dev/null +++ b/apps/web/src/j5/fleet/fleetState.test.ts @@ -0,0 +1,193 @@ +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, fleetProblemSummaryAtom } 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); +}); + +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 new file mode 100644 index 0000000000000..bd48f0907c71b --- /dev/null +++ b/apps/web/src/j5/fleet/fleetState.ts @@ -0,0 +1,128 @@ +import { + createFleetFactsAtom, + summarizeFleetProblems, + 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"; +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); + 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) => { + const thread = + agent.threadId === null + ? undefined + : threads.get( + scopedThreadKey( + scopeThreadRef(source.environmentId, ThreadId.make(agent.threadId)), + ), + ); + const key = fleetAgentKey(source.environmentId, agent.participantId); + const delivery = deliveries.get(key); + return { + key, + shell: thread?.source, + pendingSubagentRequest: thread?.pendingSubagentRequest, + ledger: delivery?.ledger, + problemsIncomplete: delivery?.problemsIncomplete ?? true, + 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), +); + +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); + 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 42ac92a51903f..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); @@ -181,6 +378,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", @@ -188,6 +401,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 }, @@ -581,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 21cc8e5d98aec..8439605ef0887 100644 --- a/packages/client-runtime/src/j5/fleetFacts.ts +++ b/packages/client-runtime/src/j5/fleetFacts.ts @@ -142,9 +142,53 @@ 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; + readonly pendingSubagentRequest?: "approval" | "user_input" | null | undefined; readonly now: number; readonly problemsIncomplete?: boolean | undefined; }): { readonly facts: FleetDerivedFacts; readonly nextDeadline?: number } => { @@ -228,25 +272,33 @@ export const deriveFleetFacts = (input: { } : { 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" - ? "waiting" - : "approval" - : activity === "running" - ? "working" - : activity === "waiting" + : shell.pendingRuntimeRequest?.kind === "auth_refresh" ? "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 && @@ -286,9 +338,41 @@ export interface FleetFactRow { readonly shell: OrchestrationV2ThreadShell | undefined; readonly ledger: FleetAgentFacts | undefined; readonly live: boolean; + readonly pendingSubagentRequest?: "approval" | "user_input" | null | undefined; 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) => { @@ -308,36 +392,40 @@ 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({ shell: row.shell, ledger: row.ledger, + pendingSubagentRequest: row.pendingSubagentRequest, 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); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6b4c5ede7d14a..4cba89af9303a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -974,6 +974,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