diff --git a/FORK.md b/FORK.md index 9a461f9af419b..e8a1ace58706b 100644 --- a/FORK.md +++ b/FORK.md @@ -163,6 +163,10 @@ Landing-order collision: two cases landed as `15.`; resolved by the `b` suffix o 33. Artifacts (PR #109, corrected 2026-09-14). Storage is server-owned application data, never the repository: `apps/server/src/j5/artifacts/ArtifactWorkspace.ts` keeps one directory per project under `/artifacts//`, so there is no Git exclusion and no per-thread folder. Production decorates the existing `RunFinalizationObserver` with J5-owned `ArtifactRunFinalizationObserver.ts` (wrapped in turn by the handoff observer), preserving both upstream refresh methods (`refreshAfterTurn` is now `(projectId) => Effect`; the decorators pass it through unchanged, nesting handoff → artifact → upstream). It reads the settled projection to export the final proposed plan to the project's `plan.md`; no observer argument extension is needed. `apps/server/src/j5/a2a/J5AuthenticatedRoutes.ts` appends the authenticated, project-addressed artifact read route to the sole J5 aggregate; the list is the RPC `j5.artifacts.list` (case 64). The operate-scoped permanent delete is the RPC `j5.artifacts.delete` in the J5 artifact group, served by J5-owned `ArtifactDeletion.ts` (case 64). Deletion uses non-recursive platform filesystem removal and adds no runtime dependency or packaging seam. Successful deletion reconciles a matching saved-agent handoff to `missing` and publishes the normal handoff refresh; reconciliation stays best-effort because the file has already been deleted and cannot be rolled back. The artifact change stream is a J5 RPC group, `J5ArtifactRpcGroup` in `packages/contracts/src/j5/artifacts.ts`, merged into `WsRpcGroup` in `packages/contracts/src/rpc.ts` beside the persona group (one appended `.merge`); `apps/server/src/auth/RpcAuthorization.ts` spreads its scopes, its handlers from J5-owned `apps/server/src/j5/artifacts/artifactRpc.ts` are served through case 58's `layerJ5WsRpc`, and `packages/client-runtime/src/rpc/client.ts` names its tag in the subscription-tag union. `apps/web/src/components/sidebar/SidebarChrome.tsx` adds the Artifacts footer item, and case 6's `isSidebarUtilityPage` entry gives `/artifacts` its Back behavior; `rightPanelStore.ts`, `RightPanelTabs.tsx`, and `ChatView.tsx` add a project-scoped singleton right-panel surface that reuses the J5-owned artifact view, and upstream's `components/chat/RightPanelSurfaceContent.tsx`, which holds the surface switch since upstream moved it out of `ChatView.tsx`, renders it in a `case "artifacts"` from an `artifactsProjectId` prop that `ChatView.tsx` passes (the switch has no default, so a lost case leaves the tab blank and no check fails); `rightPanelStore` storage version is 15 (J5 13 + upstream 14), and its version-agnostic migration drops `plan`/`agents` and normalizes `artifacts`. `ChatMarkdown.tsx` recognizes workspace-relative `artifacts/` file references, gives them distinct presentation, and routes their primary action to that surface with the referenced artifact selected. J5's instructions (case 8) carry one planning-document placement bullet. The MCP `j5_write_artifact`, `j5_read_artifact`, and `j5_list_artifacts` tools (`apps/server/src/mcp/toolkits/artifacts/`, `ArtifactMcpService.ts`) are registered by case 2's `layerJ5Toolkits`. The route, client, project page, filesystem policy, path classifier, previews, and change subscription otherwise live in J5-owned files. The generated `apps/web/src/routeTree.gen.ts` delta is not hand-authored. On every rebase, keep plan export and post-delete handoff reconciliation best-effort so neither can poison a completed operation, preserve the finalization observer's original refresh behavior, and keep one shared project namespace. 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. @@ -416,7 +420,7 @@ migrations after upstream migrations. The client's reads followed (step 3 of the issue, Jackson's 2026-10-11 go-ahead), by upstream's own rule: a small read is a socket query, and a large, compressible payload goes over HTTP (upstream's comment on its pull-request diff route in `environmentHttp.ts`). `packages/contracts/src/rpc.ts` gains one more `.merge(J5ClientReadRpcGroup)`: the Inbox list and open count, Crew proposals, Crew runtime requests, Crew memberships, the Fleet, spawned children, the archive preflight, participant identities and the peer list. The three playbook reads join `J5PlaybookRpcGroup` and the artifact list joins `J5ArtifactRpcGroup`. All need read scope, except the peer list, which needs `access:read` as its route did; none is guarded, because a guarded method cannot back a query. `ClientReadsService` serves them through `apps/server/src/j5/a2a/clientReadRpc.ts`, and `playbooks/WorkspacePlaybooks.ts` resolves the workspace a playbook request names for its read, export, delete and rename. Their routes are removed with no overlap, as the actions' were. On the client each is upstream's `createEnvironmentRpcQueryAtomFamily` or, for a one-off read, `createEnvironmentRpcCommand`; the per-route probe for a missing route is gone (case 34), and a server too old to have a read shows "This view needs a newer server." - Those reads are told when to run again by one change stream per environment, in place of the foreground timers they ran on ([#182](https://github.com/Jacksondr5/j5code/issues/182), the other half of step 3). `j5.reads.subscribeChanges` is a stream RPC in `J5ClientReadRpcGroup` with read scope. It carries five counters and never what changed: `inbox`, `crew`, `fleet`, `runtimeRequests` and `peers`, the whole record each time, starting with where they stand, so a client that reconnects sees a counter that moved while it was away. They restart with the server. J5-owned `apps/server/src/j5/a2a/ReadChanges.ts` holds them, as one layer object shared by reference in `runtimeLayer.ts` between the writers and the socket handler (it joins `J5WsRpcServices` in `apps/server/src/j5/wsRpc.ts`, so `ws.ts` is not edited), and coalesces a burst of writes into one message. `ReadChangeFeeds.ts` moves them from what the server already publishes: the ledger's committed events move `inbox` when an Exchange closes or is dropped and when a message to a person is delivered, cancelled or fails, `fleet` on every participant event and on an Exchange opening, closing or being dropped, and `peers` on a send to a peer server and on every delivery outcome (an outcome does not say whether its message waited for a peer), since the peer list counts each peer's waiting messages; the playbook store's revision moves `fleet`; the peer registry's `subscribeListChanges` moves `peers` after each write the peer list shows (a peer recorded, rotated, adopted or removed, a heartbeat, a changed last error or name, and a session issued for a peer, which `PeerAdminService` tells it of), and stays apart from the `subscribeChanges` the pollers follow, so a heartbeat reconciles no poller; and the orchestration event store moves `runtimeRequests` on `runtime-request.updated`, on an approval request among the `turn-item.updated` events, and on a thread being archived, unarchived or deleted. Two writers move a counter themselves: `SpawnCompositionService.recordFacts` moves `fleet`, because a placement on a thread that is already registered commits no ledger event, and `layerNotifying` in `AgentCrewProposalService.ts` and `AgentCrewInstanceService.ts` (the layers the server runs) moves `crew` after each write to a proposal, a Crew or its seats. On the client, `packages/client-runtime/src/rpc/client.ts` names the tag in `EnvironmentSubscriptionRpcTag` (its import and one union member, beside the artifact and playbook tags), and each read in `packages/client-runtime/src/j5/state.ts` names its counters as upstream's `refreshTrigger`, the pattern of `createLinkedPullRequestSummaryAtomFamily`: the Inbox list and open count follow `inbox`, Crew proposals `crew`, Crew runtime requests `crew` and `runtimeRequests`, the Fleet `crew` and `fleet`, and the peer list `peers`. A mounted read holds the subscription open, so a server that does not report `j5ProjectLedger`, whose reads are not made once its config has loaded (case 34), is not left subscribed to. The sidebar's Crew chips and spawned children are batched commands and not queries, so `createFleetRowRefresher` in `apps/web/src/j5/fleet/fleet.logic.ts` re-reads them after each roster read a moved counter caused: the chips on `crew`, the children on `crew` or `fleet`, for case 23's involved rows. None of these reads runs on a timer, and neither do the playbook reads, which follow the playbook store's own revision (`j5.playbooks.subscribeChanges`, case 45). That revision moves on each run mutation and resolved or targeted hand-off, on a definition renamed or deleted through the store, on a read that cancelled a run whose owner is gone (and on no other read, or each read would cause the next), and on a change on disk to the YAML an active run is shown from: J5-owned `apps/server/src/j5/playbooks/PlaybookDefinitionWatch.ts` follows the revision, watches each directory that holds an active run's definition, and stops when the directory's last run ends, so a server with no active run holds no file handle for it. A watch that fails or ends is not started again until its directory has no active run. Still without a signal: a renamed project; a playbook YAML file no active run uses, which the library reads each time it is opened; a peer's session revoked or expired in the auth database by another path; and a playbook directory deleted or replaced under an active run, whose watch is lost. Each of these views reads again when the tab is focused or shown, which also covers a server too old to have the stream. On rebase, keep `ReadChanges` one instance for every writer and the handler, and move a counter only after the write it reports has committed. + Those reads are told when to run again by one change stream per environment, in place of the foreground timers they ran on ([#182](https://github.com/Jacksondr5/j5code/issues/182), the other half of step 3). `j5.reads.subscribeChanges` is a stream RPC in `J5ClientReadRpcGroup` with read scope. It carries five counters and never what changed: `inbox`, `crew`, `fleet`, `runtimeRequests` and `peers`, the whole record each time, starting with where they stand, so a client that reconnects sees a counter that moved while it was away. They restart with the server. J5-owned `apps/server/src/j5/a2a/ReadChanges.ts` holds them, as one layer object shared by reference in `runtimeLayer.ts` between the writers and the socket handler (it joins `J5WsRpcServices` in `apps/server/src/j5/wsRpc.ts`, so `ws.ts` is not edited), and coalesces a burst of writes into one message. `ReadChangeFeeds.ts` moves them from what the server already publishes: the ledger's committed events move `inbox` when an Exchange closes or is dropped and when a message to a person is delivered, cancelled or fails, `fleet` on every participant event and on an Exchange opening, closing or being dropped, and `fleet` on an alarmed delivery failure or a cancellation; `peers` moves on a send to a peer server and on every delivery outcome (an outcome does not say whether its message waited for a peer), since the peer list counts each peer's waiting messages; the playbook store's revision moves `fleet`; the peer registry's `subscribeListChanges` moves `peers` after each write the peer list shows (a peer recorded, rotated, adopted or removed, a heartbeat, a changed last error or name, and a session issued for a peer, which `PeerAdminService` tells it of), and stays apart from the `subscribeChanges` the pollers follow, so a heartbeat reconciles no poller; and the orchestration event store moves `runtimeRequests` on `runtime-request.updated`, on an approval request among the `turn-item.updated` events, and on a thread being archived, unarchived or deleted. Two writers move a counter themselves: `SpawnCompositionService.recordFacts` moves `fleet`, because a placement on a thread that is already registered commits no ledger event, and `layerNotifying` in `AgentCrewProposalService.ts` and `AgentCrewInstanceService.ts` (the layers the server runs) moves `crew` after each write to a proposal, a Crew or its seats. On the client, `packages/client-runtime/src/rpc/client.ts` names the tag in `EnvironmentSubscriptionRpcTag` (its import and one union member, beside the artifact and playbook tags), and each read in `packages/client-runtime/src/j5/state.ts` names its counters as upstream's `refreshTrigger`, the pattern of `createLinkedPullRequestSummaryAtomFamily`: the Inbox list and open count follow `inbox`, Crew proposals `crew`, Crew runtime requests `crew` and `runtimeRequests`, the Fleet `crew` and `fleet`, and the peer list `peers`. A mounted read holds the subscription open, so a server that does not report `j5ProjectLedger`, whose reads are not made once its config has loaded (case 34), is not left subscribed to. The sidebar's Crew chips and spawned children are batched commands and not queries, so `createFleetRowRefresher` in `apps/web/src/j5/fleet/fleet.logic.ts` re-reads them after each roster read a moved counter caused: the chips on `crew`, the children on `crew` or `fleet`, for case 23's involved rows. None of these reads runs on a timer, and neither do the playbook reads, which follow the playbook store's own revision (`j5.playbooks.subscribeChanges`, case 45). That revision moves on each run mutation and resolved or targeted hand-off, on a definition renamed or deleted through the store, on a read that cancelled a run whose owner is gone (and on no other read, or each read would cause the next), and on a change on disk to the YAML an active run is shown from: J5-owned `apps/server/src/j5/playbooks/PlaybookDefinitionWatch.ts` follows the revision, watches each directory that holds an active run's definition, and stops when the directory's last run ends, so a server with no active run holds no file handle for it. A watch that fails or ends is not started again until its directory has no active run. Still without a signal: a renamed project; a playbook YAML file no active run uses, which the library reads each time it is opened; a peer's session revoked or expired in the auth database by another path; and a playbook directory deleted or replaced under an active run, whose watch is lost. Each of these views reads again when the tab is focused or shown, which also covers a server too old to have the stream. On rebase, keep `ReadChanges` one instance for every writer and the handler, and move a counter only after the write it reports has committed. Two things stay on HTTP for a client. Reading one artifact's content (`POST /api/j5/artifacts/read`) can be megabytes, up to the 5 MB artifact limit and a third more as base64, so it keeps case 34's request helper as that helper's only caller. `GET /api/j5/a2a/peers` stays for the `j5 a2a peer list` CLI and calls `PeerAdminService.list`, as the RPC does. @@ -804,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 | @@ -847,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 | @@ -864,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/server/src/j5/a2a/ClientReadsService.ts b/apps/server/src/j5/a2a/ClientReadsService.ts index db8e35e8f1da6..aa1c5d07a1dec 100644 --- a/apps/server/src/j5/a2a/ClientReadsService.ts +++ b/apps/server/src/j5/a2a/ClientReadsService.ts @@ -24,6 +24,7 @@ import { A2AArchiveFacts } from "./ArchiveFactsService.ts"; import { makeCrewMembershipsRead } from "./crewMembershipsRead.ts"; import { projectCrewProposal } from "./crewProposalProjection.ts"; import { CrewRuntimeRequestService } from "./CrewRuntimeRequestService.ts"; +import { clientReadBatches } from "./clientReadBatches.ts"; import { makeFleetRead } from "./fleetRead.ts"; import { type A2AHumanInboxError, A2AHumanInbox } from "./HumanInboxService.ts"; import { A2ALedger } from "./LedgerService.ts"; @@ -94,20 +95,9 @@ interface QueryPlanRow { readonly detail: string; } -/** Leaves headroom under SQLite's bind-parameter ceiling for viewport-sized reads. */ -export const CLIENT_READ_PARTICIPANT_BATCH_SIZE = 900; - const uniqueInFirstOccurrenceOrder = (values: ReadonlyArray) => Array.from(new Set(values)); -const batchesOf = (values: ReadonlyArray) => { - const batches: Array> = []; - for (let index = 0; index < values.length; index += CLIENT_READ_PARTICIPANT_BATCH_SIZE) { - batches.push(values.slice(index, index + CLIENT_READ_PARTICIPANT_BATCH_SIZE)); - } - return batches; -}; - const unknownIdentity = (): DisplayIdentity => ({ kind: "unknown" }); const toIdentity = (row: IdentityRow | undefined): DisplayIdentity => { @@ -308,7 +298,7 @@ export const layer: Layer.Layer< const uniqueParticipantIds = uniqueInFirstOccurrenceOrder(input.participantIds); if (uniqueParticipantIds.length === 0) return { entries: [] }; const rows: Array = []; - for (const participantIdBatch of batchesOf(uniqueParticipantIds)) { + for (const participantIdBatch of clientReadBatches(uniqueParticipantIds)) { rows.push(...(yield* participantIdentityRows(sql, participantIdBatch))); // Machine senders have no thread; their display name is their registered name. rows.push( diff --git a/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts b/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts index acc95a73f3a95..b69230be1fc94 100644 --- a/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts +++ b/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts @@ -35,6 +35,7 @@ import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; +import { readFleetLedgerFacts } from "./fleetFacts.ts"; import { HttpClient, HttpClientResponse } from "effect/http"; import * as SqlClient from "effect/sql/SqlClient"; @@ -545,6 +546,10 @@ const vmAsksLaptop = Effect.fn("test.j5.a2a.peer.pollRoundTrip.vmAsks")(function // The next poll acknowledges it. yield* pair.poll; assert.equal((yield* deliveryStatus(pair.vmServer.sql, asked.messageId))?.status, "delivered"); + const receivedOrigins = yield* pair.laptopServer.sql<{ origin_environment_id: string }>` + SELECT origin_environment_id FROM j5_a2a_delivery WHERE exchange_id = ${asked.exchangeId} + `; + assert.equal(receivedOrigins[0]?.origin_environment_id, vmDescriptor.environmentId); return ExchangeId.make(asked.exchangeId!); }); @@ -1021,3 +1026,34 @@ const runEnded = (thread: ThreadId, status: "completed" | "failed"): Orchestrati }, } as OrchestrationV2StoredEvent; }; + +it.effect("exposes a polled receiver alarm under the origin's client environment identity", () => + Effect.scoped( + Effect.gen(function* () { + const pair = yield* pollPair(); + const exchangeId = yield* vmAsksLaptop(pair, "command:poll-alarm-read"); + const accepted = yield* pair.vmServer + .sql`SELECT * FROM j5_a2a_delivery WHERE exchange_id = ${exchangeId}`; + yield* pair.laptopServer + .sql`UPDATE j5_a2a_delivery SET status = 'alarmed', last_error = 'thread unavailable' + WHERE exchange_id = ${exchangeId}`; + const facts = yield* readFleetLedgerFacts( + pair.laptopServer.sql, + laptop.projectId, + [laptop.agent.id], + () => null, + ); + assert.equal(facts.remoteDeliveryAlarms.length, 1); + assert.equal(facts.remoteDeliveryAlarms[0]?.originEnvironmentId, vmDescriptor.environmentId); + assert.equal(facts.remoteDeliveryAlarms[0]?.senderId, vm.agent.id); + assert.equal(facts.remoteDeliveryAlarms[0]?.problem.exchangeId, exchangeId); + assert.isTrue(facts.remoteDeliveryAlarms[0]?.problem.exchangeOpen); + assert.equal(facts.problems.size, 0); + assert.deepStrictEqual(yield* pair.poll, { kind: "polled", received: 0, more: false }); + assert.deepStrictEqual( + yield* pair.vmServer.sql`SELECT * FROM j5_a2a_delivery WHERE exchange_id = ${exchangeId}`, + accepted, + ); + }), + ), +); diff --git a/apps/server/src/j5/a2a/PeerRoundTrip.test.ts b/apps/server/src/j5/a2a/PeerRoundTrip.test.ts index b4eeddf403606..43d19ea232f48 100644 --- a/apps/server/src/j5/a2a/PeerRoundTrip.test.ts +++ b/apps/server/src/j5/a2a/PeerRoundTrip.test.ts @@ -13,6 +13,8 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; +import { readFleetLedgerFacts } from "./fleetFacts.ts"; import * as SqlClient from "effect/sql/SqlClient"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; @@ -113,6 +115,7 @@ const makeServer = ( peer: Ref.Ref, delivered: Ref.Ref>, crossed: Ref.Ref>, + failLocal = false, ) => { const database = NodeSqliteClient.layer({ filename: ":memory:" }); const ledger = ledgerLayer.pipe(Layer.provide(database)); @@ -146,7 +149,15 @@ const makeServer = ( A2ADeliveryTransport, A2ADeliveryTransport.of({ cancelAgent: () => Effect.succeed("cancelled" as const), - deliverAgent: (input) => Ref.update(delivered, (rows) => [...rows, input]), + deliverAgent: (input) => + failLocal + ? Effect.fail( + new A2ADeliveryTransportError({ + operation: "deliver to agent", + cause: "thread unavailable", + }), + ) + : Ref.update(delivered, (rows) => [...rows, input]), deliverHuman: () => Effect.void, deliverPeer: (input) => Effect.gen(function* () { @@ -287,6 +298,7 @@ const seed = Effect.fn("test.j5.a2a.peer.roundtrip.seed")(function* (self: Serve /** Both servers up and introduced, with Work's agent holding an open ask to Home's agent that has crossed. */ const pairWithOpenAsk = Effect.fn("test.j5.a2a.peer.roundtrip.pairWithOpenAsk")(function* ( commandId: string, + failReceiver = false, ) { const workDoor = yield* Ref.make(null); const homeDoor = yield* Ref.make(null); @@ -297,7 +309,7 @@ const pairWithOpenAsk = Effect.fn("test.j5.a2a.peer.roundtrip.pairWithOpenAsk")( makeServer(work, home, "Home", homeDoor, workDelivered, crossed), ); const homeContext = yield* Layer.build( - makeServer(home, work, "Work", workDoor, homeDelivered, crossed), + makeServer(home, work, "Work", workDoor, homeDelivered, crossed, failReceiver), ); const workServer = yield* seed(work, home).pipe(Effect.provide(workContext)); const homeServer = yield* seed(home, work).pipe(Effect.provide(homeContext)); @@ -313,8 +325,11 @@ const pairWithOpenAsk = Effect.fn("test.j5.a2a.peer.roundtrip.pairWithOpenAsk")( acceptedAt: timestamp, }); assert.equal((yield* workServer.worker.runOnce)?.state, "delivered"); - assert.equal((yield* homeServer.worker.runOnce)?.state, "delivered"); - assert.equal((yield* Ref.get(homeDelivered)).length, 1, "the ask reached Home's agent"); + assert.equal( + (yield* homeServer.worker.runOnce)?.state, + failReceiver ? "retry_scheduled" : "delivered", + ); + assert.equal((yield* Ref.get(homeDelivered)).length, failReceiver ? 0 : 1); return { workServer, homeServer, @@ -693,3 +708,41 @@ it.effect( }), ), ); + +it.effect("reads a pushed receiver alarm without sending any message back to the origin", () => + Effect.scoped( + Effect.gen(function* () { + const pair = yield* pairWithOpenAsk("command:read-remote-alarm", true); + const original = yield* pair.workServer.sql`SELECT * FROM j5_a2a_delivery`; + yield* TestClock.adjust("250 millis"); + assert.equal((yield* pair.homeServer.worker.runOnce)?.state, "retry_scheduled"); + yield* TestClock.adjust("500 millis"); + assert.equal((yield* pair.homeServer.worker.runOnce)?.state, "alarmed"); + assert.isNull(yield* pair.homeServer.worker.runOnce); + const facts = yield* readFleetLedgerFacts( + pair.homeServer.sql, + home.projectId, + [home.agent.id], + () => null, + ); + const remote = facts.remoteDeliveryAlarms[0]!; + assert.equal(remote.originEnvironmentId, work.environmentId); + assert.equal(remote.senderId, work.agent.id); + assert.equal(remote.problem.exchangeId, pair.exchangeId); + assert.isTrue(remote.problem.exchangeOpen); + assert.equal(facts.problems.size, 0); + assert.equal((yield* Ref.get(pair.crossed)).length, 1, "only the authored ask crossed"); + assert.deepStrictEqual(yield* pair.workServer.sql`SELECT * FROM j5_a2a_delivery`, original); + assert.equal((yield* Ref.get(pair.workDelivered)).length, 0); + assert.equal( + (yield* exchangeStatus(pair.workServer.sql, pair.exchangeId))[0]?.status, + "open", + ); + assert.equal( + (yield* pair.homeServer + .sql`SELECT 1 FROM j5_a2a_delivery WHERE envelope_channel = 'lifecycle_notice'`).length, + 0, + ); + }), + ), +); diff --git a/apps/server/src/j5/a2a/ReadChangeFeeds.test.ts b/apps/server/src/j5/a2a/ReadChangeFeeds.test.ts index 0f8497e845363..39f140c5f5263 100644 --- a/apps/server/src/j5/a2a/ReadChangeFeeds.test.ts +++ b/apps/server/src/j5/a2a/ReadChangeFeeds.test.ts @@ -54,10 +54,36 @@ it("maps each ledger event to the reads it puts out of date", () => { "message.delivery_failed", ] as const) { // An outcome does not say whether its message waited for a peer, so each moves the peer list. - assert.deepStrictEqual(changed(kind, person), ["inbox", "peers"], kind); - assert.deepStrictEqual(changed(kind, agent), ["peers"], kind); + assert.deepStrictEqual( + changed(kind, person), + kind === "message.cancelled" ? ["inbox", "fleet", "peers"] : ["inbox", "peers"], + kind, + ); + assert.deepStrictEqual( + changed(kind, agent), + kind === "message.cancelled" ? ["fleet", "peers"] : ["peers"], + kind, + ); // An event that names no receiver is counted rather than missed. - assert.deepStrictEqual(changed(kind, null), ["inbox", "peers"], kind); + assert.deepStrictEqual( + changed(kind, null), + kind === "message.cancelled" ? ["inbox", "fleet", "peers"] : ["inbox", "peers"], + kind, + ); + } + for (const receiver of [person, agent, null]) { + assert.deepStrictEqual( + readsChangedByLedgerEvent( + ledgerEvent("message.delivery_failed", receiver, { alarmed: true }), + ), + receiver === agent ? ["fleet", "peers"] : ["inbox", "fleet", "peers"], + ); + assert.deepStrictEqual( + readsChangedByLedgerEvent( + ledgerEvent("message.delivery_failed", receiver, { alarmed: false }), + ), + receiver === agent ? ["peers"] : ["inbox", "peers"], + ); } for (const kind of ["message.sent", "message.received", "silence.notice"] as const) assert.deepStrictEqual(changed(kind, person), [], kind); diff --git a/apps/server/src/j5/a2a/ReadChangeFeeds.ts b/apps/server/src/j5/a2a/ReadChangeFeeds.ts index 5c16a0d2e2388..447b2ca59f737 100644 --- a/apps/server/src/j5/a2a/ReadChangeFeeds.ts +++ b/apps/server/src/j5/a2a/ReadChangeFeeds.ts @@ -46,12 +46,22 @@ export const readsChangedByLedgerEvent = ( return ["inbox", "fleet"]; case "exchange.opened": return ["fleet"]; + // Fleet changes only when an alarm appears or is cancelled; an alarm is never retried. // The peer list counts the messages waiting for each peer. An outcome does not say whether // its message was for a peer, so each one counts while this server has a peer; the daemon // below drops `peers` while it has none. - case "message.delivered": case "message.cancelled": + return reachesPerson(event) ? ["inbox", "fleet", "peers"] : ["fleet", "peers"]; case "message.delivery_failed": + if ( + typeof event.payload === "object" && + event.payload !== null && + "alarmed" in event.payload && + event.payload.alarmed === true + ) + return reachesPerson(event) ? ["inbox", "fleet", "peers"] : ["fleet", "peers"]; + return reachesPerson(event) ? ["inbox", "peers"] : ["peers"]; + case "message.delivered": return reachesPerson(event) ? ["inbox", "peers"] : ["peers"]; case "message.sent": return sentToPeer(event) ? ["peers"] : []; diff --git a/apps/server/src/j5/a2a/clientReadBatches.ts b/apps/server/src/j5/a2a/clientReadBatches.ts new file mode 100644 index 0000000000000..a4826495e3a5c --- /dev/null +++ b/apps/server/src/j5/a2a/clientReadBatches.ts @@ -0,0 +1,10 @@ +/** Leaves headroom under SQLite's bind ceiling for the other fields in a client read. */ +const PARTICIPANT_BATCH_SIZE = 900; + +export const clientReadBatches = (values: ReadonlyArray) => { + const batches: Array> = []; + for (let index = 0; index < values.length; index += PARTICIPANT_BATCH_SIZE) { + batches.push(values.slice(index, index + PARTICIPANT_BATCH_SIZE)); + } + return batches; +}; diff --git a/apps/server/src/j5/a2a/fleetFacts.test.ts b/apps/server/src/j5/a2a/fleetFacts.test.ts new file mode 100644 index 0000000000000..492d4cf406b39 --- /dev/null +++ b/apps/server/src/j5/a2a/fleetFacts.test.ts @@ -0,0 +1,339 @@ +import { assert, it } from "@effect/vitest"; +import { ThreadId } from "@t3tools/contracts"; +import * as Layer from "effect/Layer"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; + +import { runMigrations } from "../../persistence/Migrations.ts"; +import { runJ5A2AMigrations } from "./Migrations.ts"; +import { A2ALedger } from "./LedgerService.ts"; +import { ParticipantPlacementService } from "./PlacementService.ts"; +import { AgentCrewInstanceService } from "./AgentCrewInstanceService.ts"; +import { PlaybookCrewRelay } from "../playbooks/PlaybookCrewRelay.ts"; +import { CREW_ALERT_EXCHANGE_PREFIX } from "./crewFailureAlert.ts"; +import { makeFleetRead } from "./fleetRead.ts"; +import { LedgerProjectId, ParticipantId } from "./contracts.ts"; +import type { ParticipantPlacementView } from "./placementContracts.ts"; +import { readFleetLedgerFacts } from "./fleetFacts.ts"; + +const database = NodeSqliteClient.layer({ filename: ":memory:" }); +const sender = "agent:sender"; +const receiver = "agent:receiver"; +const at = "2026-10-19T10:00:00.000Z"; + +it.effect("bounds both Fleet ask summaries without changing the stored intent", () => + Effect.gen(function* () { + yield* runMigrations(); + yield* runJ5A2AMigrations(); + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO j5_a2a_project_ledger (project_id, created_at) VALUES ('p', ${at})`; + for (const [intent, summary] of [ + ["Review the diff", "Review the diff"], + ["a".repeat(200), "a".repeat(200)], + ["a".repeat(10_000), `${"a".repeat(199)}…`], + ["🚀".repeat(5_000), `${"🚀".repeat(199)}…`], + ]) { + yield* sql`INSERT INTO j5_a2a_exchange ( + project_id, exchange_id, sender_id, receiver_id, status, intent, opened_seq, created_at, updated_at + ) VALUES ('p', 'ask', ${sender}, ${receiver}, 'open', ${intent}, 1, ${at}, ${at}) + ON CONFLICT (project_id, exchange_id) DO UPDATE SET intent = excluded.intent`; + const facts = yield* readFleetLedgerFacts(sql, "p", [sender, receiver], () => null); + assert.equal(facts.awaited.get(sender)?.[0]?.intent, summary); + assert.equal(facts.owed.get(receiver)?.[0]?.intent, summary); + const stored = yield* sql<{ intent: string }>` + SELECT intent FROM j5_a2a_exchange WHERE project_id = 'p' AND exchange_id = 'ask' + `; + assert.equal(stored[0]?.intent, intent); + } + }).pipe(Effect.provide(database)), +); + +it.effect( + "reads both ask directions across projects and keeps local/remote alarms on their sender", + () => + Effect.gen(function* () { + yield* runMigrations(); + yield* runJ5A2AMigrations(); + const sql = yield* SqlClient.SqlClient; + for (const project of ["p", "other"]) + yield* sql`INSERT INTO j5_a2a_project_ledger (project_id, created_at) VALUES (${project}, ${at})`; + const exchange = Effect.fnUntraced(function* ( + id: string, + project: string, + from: string, + to: string, + ) { + yield* sql`INSERT INTO j5_a2a_exchange ( + project_id, exchange_id, sender_id, receiver_id, status, intent, opened_seq, created_at, updated_at + ) VALUES (${project}, ${id}, ${from}, ${to}, 'open', ${id}, 1, ${at}, ${at})`; + }); + yield* exchange("outgoing", "p", sender, receiver); + yield* exchange("incoming", "other", "human:operator", sender); + const alarm = Effect.fnUntraced(function* ( + id: string, + channel: string, + exchangeId: string | null, + remote: string | null = null, + status = "alarmed", + receiverId = receiver, + ) { + yield* sql`INSERT INTO j5_a2a_delivery ( + project_id, message_id, command_id, sent_seq, sender_id, receiver_id, receiver_project_id, + exchange_id, exchange_role, correlation_id, message_text, status, attempts, last_error, + created_at, updated_at, envelope_channel, receiver_environment_id + ) VALUES ('p', ${id}, ${id}, 1, ${sender}, ${receiverId}, 'p', ${exchangeId}, + ${exchangeId === null ? "none" : "followup"}, ${id}, 'hello', ${status}, 3, 'transport unavailable', + ${at}, ${at}, ${channel}, ${remote})`; + }); + const platformExchange = `${CREW_ALERT_EXCHANGE_PREFIX}crew/run`; + yield* exchange(platformExchange, "p", sender, "human:operator"); + yield* alarm("platform-alert", "peer", platformExchange, null, "alarmed", "human:operator"); + yield* alarm("local-ask", "peer", "outgoing"); + yield* alarm("remote-ask", "peer", "outgoing", "remote-env"); + yield* alarm("plain", "peer", null); + yield* alarm("silence", "silence_notice", null); + yield* alarm("lifecycle", "lifecycle_notice", null); + yield* alarm("retry", "peer", null, null, "retry_scheduled"); + yield* alarm("delivered", "peer", null, null, "delivered"); + yield* alarm("accepted-peer", "peer", "outgoing", "receiver-env", "delivered"); + yield* sql`UPDATE j5_a2a_delivery SET exchange_role = 'ask' WHERE message_id = 'accepted-peer'`; + yield* alarm("inbound-peer", "peer", "outgoing"); + yield* sql`UPDATE j5_a2a_delivery SET origin_environment_id = 'origin-env' + WHERE message_id = 'inbound-peer'`; + yield* alarm("inbound-platform", "lifecycle_notice", null); + yield* sql`UPDATE j5_a2a_delivery SET origin_environment_id = 'origin-env' + WHERE message_id = 'inbound-platform'`; + const read = () => + readFleetLedgerFacts(sql, "p", [sender, receiver], (id) => + id === receiver ? "Receiver" : null, + ); + const before = yield* read(); + assert.equal(before.owed.get(sender)?.length, 1); + assert.equal(before.owed.get(receiver)?.length, 1); + assert.deepStrictEqual(before.awaited.get(sender), [ + { + exchangeId: "outgoing", + counterpartyId: receiver, + counterpartyName: "Receiver", + intent: "outgoing", + openedAt: at, + }, + ]); + assert.deepStrictEqual( + before.problems + .get(sender) + ?.map( + (problem) => + problem.kind === "delivery-failed" && [problem.messageId, problem.exchangeOpen], + ), + [ + ["local-ask", true], + ["plain", false], + ["remote-ask", true], + ], + ); + assert.isUndefined(before.problems.get(receiver)); + assert.deepStrictEqual(before.deliveryEnvironmentIds.get(sender), ["receiver-env"]); + assert.deepStrictEqual(before.remoteDeliveryAlarms, [ + { + originEnvironmentId: "origin-env", + senderId: sender, + problem: { + kind: "delivery-failed", + messageId: "inbound-peer", + exchangeId: "outgoing", + receiverId: receiver, + receiverName: "Receiver", + at, + reason: "transport unavailable", + exchangeOpen: true, + }, + }, + ]); + assert.equal( + (yield* readFleetLedgerFacts(sql, "p", [], () => null)).remoteDeliveryAlarms.length, + 1, + ); + yield* sql`UPDATE j5_a2a_exchange SET status = 'closed' WHERE exchange_id = 'outgoing'`; + const closed = yield* read(); + assert.isUndefined(closed.awaited.get(sender)); + assert.isUndefined(closed.deliveryEnvironmentIds.get(sender)); + assert.equal(closed.problems.get(sender)?.length, 3); + assert.isTrue( + closed.problems + .get(sender)! + .every((problem) => problem.kind === "delivery-failed" && !problem.exchangeOpen), + ); + yield* sql`UPDATE j5_a2a_delivery SET status = 'cancelled' WHERE message_id = 'local-ask'`; + assert.equal((yield* read()).problems.get(sender)?.length, 2); + assert.equal( + (yield* readFleetLedgerFacts(sql, "other", [sender], () => null)).problems.size, + 0, + ); + yield* sql`INSERT INTO j5_a2a_human_person + (person_id, is_local_operator, created_at, display_name, name_key) + VALUES ('human:operator', 1, ${at}, 'Operator', 'operator')`; + const participant = (id: string, project: string): ParticipantPlacementView => ({ + projectId: LedgerProjectId.make(project), + participantId: ParticipantId.make(id), + participant: { + kind: "agent", + id: ParticipantId.make(id), + threadId: ThreadId.make(id), + }, + threadId: ThreadId.make(id), + provenance: { kind: "unrecorded" }, + placementParentId: null, + }); + yield* sql`INSERT INTO orchestration_v2_projection_threads ( + thread_id, project_id, title, default_provider, runtime_mode, interaction_mode, + active_provider_thread_id, created_at, updated_at, archived_at, deleted_at, payload_json + ) VALUES (${receiver}, 'other', 'Remote receiver', 'codex', 'full-access', 'default', + NULL, ${at}, ${at}, NULL, NULL, '{}')`; + const fleetRead = yield* makeFleetRead.pipe( + Effect.provide( + Layer.mergeAll( + Layer.mock(A2ALedger)({ + listProjectLedgers: () => + Effect.succeed([ + { id: LedgerProjectId.make("p"), name: "P", createdAt: at }, + { id: LedgerProjectId.make("other"), name: "Other", createdAt: at }, + ]), + }), + Layer.mock(ParticipantPlacementService)({ + listParticipants: (project) => + Effect.succeed([ + project === "p" ? participant(sender, "p") : participant(receiver, "other"), + ]), + }), + Layer.mock(AgentCrewInstanceService)({ listForProject: () => Effect.succeed([]) }), + Layer.mock(PlaybookCrewRelay)({}), + ), + ), + ); + const snapshot = yield* fleetRead(false); + assert.equal(snapshot.remoteDeliveryAlarms?.[0]?.originEnvironmentId, "origin-env"); + assert.equal(snapshot.remoteDeliveryAlarms?.[0]?.senderId, sender); + assert.equal(snapshot.remoteDeliveryAlarms?.[0]?.problem.exchangeOpen, false); + assert.deepStrictEqual(snapshot.projects[0]?.agents[0]?.facts?.deliveryEnvironmentIds, []); + assert.equal(snapshot.asOf, "1970-01-01T00:00:00.000Z"); + assert.equal(snapshot.projects[0]?.agents[0]?.facts?.asks.owed.length, 1); + assert.equal( + snapshot.projects[0]?.agents[0]?.facts?.asks.owed[0]?.counterpartyName, + "Operator", + ); + assert.equal(snapshot.projects[0]?.agents[0]?.facts?.problems.length, 2); + assert.deepStrictEqual( + snapshot.projects[0]?.agents[0]?.facts?.problems.map( + (problem) => problem.kind === "delivery-failed" && problem.receiverName, + ), + ["Remote receiver", "Remote receiver"], + ); + yield* sql`INSERT INTO j5_a2a_human_person + (person_id, is_local_operator, created_at, display_name, name_key, removed_at) + VALUES ('human:viewer', 0, ${at}, 'Viewer', 'viewer', NULL), + ('human:removed', 0, ${at}, 'Removed person', NULL, ${at})`; + yield* sql`INSERT INTO j5_a2a_person_level + (person_id, scope_kind, scope_id, level, created_at, updated_at) + VALUES ('human:viewer', 'project', 'p', 'viewer', ${at}, ${at})`; + yield* exchange("viewer-ask", "other", "human:viewer", sender); + yield* exchange("removed-ask", "other", "human:removed", sender); + const withPeople = yield* fleetRead(false); + assert.deepStrictEqual( + withPeople.projects[0]?.agents[0]?.facts?.asks.owed.map((ask) => ask.counterpartyName), + ["Operator", "Removed person", "Viewer"], + ); + }).pipe(Effect.provide(database)), +); + +it.effect( + "reads beyond SQLite's unbatched bind limit without duplicating cross-project Exchanges", + () => + Effect.gen(function* () { + yield* runMigrations(); + yield* runJ5A2AMigrations(); + const sql = yield* SqlClient.SqlClient; + const agents = Array.from({ length: 17_000 }, (_, index) => `agent:${index}`); + for (const project of ["p", "other"]) { + yield* sql`INSERT INTO j5_a2a_project_ledger (project_id, created_at) VALUES (${project}, ${at})`; + yield* sql`INSERT INTO j5_a2a_exchange ( + project_id, exchange_id, sender_id, receiver_id, status, intent, opened_seq, created_at, updated_at + ) VALUES (${project}, 'shared', ${agents[0]!}, ${agents[900]!}, 'open', ${project}, 1, ${at}, ${at})`; + } + for (const id of [agents[0]!, agents.at(-1)!]) { + yield* sql`INSERT INTO j5_a2a_delivery ( + project_id, message_id, command_id, sent_seq, sender_id, receiver_id, receiver_project_id, + exchange_id, exchange_role, correlation_id, message_text, status, attempts, last_error, + created_at, updated_at, envelope_channel + ) VALUES ('p', ${id}, ${id}, 1, ${id}, 'agent:remote', 'other', NULL, + 'none', ${id}, 'hello', 'alarmed', 3, 'transport unavailable', ${at}, ${at}, 'peer')`; + } + // Binding these ids in both directions together would exceed SQLite's 32,766 variable ceiling. + const facts = yield* readFleetLedgerFacts(sql, "p", agents, () => null); + assert.equal(facts.awaited.get(agents[0]!)?.length, 2); + assert.equal(facts.owed.get(agents[900]!)?.length, 2); + assert.equal(facts.problems.get(agents[0]!)?.length, 1); + assert.equal(facts.problems.get(agents.at(-1)!)?.length, 1); + assert.isNull(facts.awaited.get(agents[0]!)?.[0]?.counterpartyName); + }).pipe(Effect.provide(database)), +); + +it.effect("tracks only open origin-owned ask destinations across projects before acceptance", () => + Effect.gen(function* () { + yield* runMigrations(); + yield* runJ5A2AMigrations(); + const sql = yield* SqlClient.SqlClient; + for (const project of ["p", "other"]) + yield* sql`INSERT INTO j5_a2a_project_ledger (project_id, created_at) VALUES (${project}, ${at})`; + yield* sql`INSERT INTO j5_a2a_peer (environment_id, label, link_mode, origin, credential, created_at, updated_at) + VALUES ('removed-peer', 'Removed', 'push', 'https://removed.example', 'test-token', ${at}, ${at})`; + const add = Effect.fnUntraced(function* ( + id: string, + status: "open" | "closed", + role: "ask" | "followup" | "none", + destination: string, + originEnvironment: string | null = null, + channel = "peer", + from = sender, + ) { + const to = `agent:receiver:${id}`; + const exchangeId = role === "none" ? null : id; + if (exchangeId !== null) + yield* sql`INSERT INTO j5_a2a_exchange + (project_id, exchange_id, sender_id, receiver_id, status, intent, opened_seq, created_at, updated_at) + VALUES ('other', ${id}, ${from}, ${to}, ${status}, ${id}, 1, ${at}, ${at})`; + yield* sql`INSERT INTO j5_a2a_delivery + (project_id, message_id, command_id, sent_seq, sender_id, receiver_id, receiver_project_id, + exchange_id, exchange_role, correlation_id, message_text, status, attempts, + created_at, updated_at, envelope_channel, receiver_environment_id, origin_environment_id) + VALUES ('other', ${id}, ${id}, 1, ${from}, ${to}, 'remote-project', ${exchangeId}, ${role}, + ${id}, 'hello', 'pending', 0, ${at}, ${at}, ${channel}, ${destination}, ${originEnvironment})`; + }); + yield* add("open-ask", "open", "ask", "active-peer"); + yield* add("old-ask", "closed", "ask", "removed-peer"); + yield* add("plain", "closed", "none", "plain-peer"); + yield* add("followup", "open", "followup", "followup-peer"); + yield* add("received-ask", "open", "ask", "inbound-peer", "foreign-origin"); + yield* add(`${CREW_ALERT_EXCHANGE_PREFIX}notice`, "open", "ask", "platform-peer"); + yield* add("lifecycle", "open", "ask", "notice-peer", null, "lifecycle_notice"); + yield* add("other-sender", "open", "ask", "other-peer", null, "peer", "agent:other"); + const read = () => readFleetLedgerFacts(sql, "p", [sender], () => null); + const pending = yield* read(); + assert.deepStrictEqual(pending.deliveryEnvironmentIds.get(sender), ["active-peer"]); + assert.isTrue(pending.awaited.get(sender)?.some((ask) => ask.exchangeId === "open-ask")); + for (const status of ["retry_scheduled", "delivered"]) { + yield* sql`UPDATE j5_a2a_delivery SET status = ${status} WHERE message_id = 'open-ask'`; + assert.deepStrictEqual((yield* read()).deliveryEnvironmentIds.get(sender), ["active-peer"]); + } + yield* sql`UPDATE j5_a2a_delivery SET status = 'delivered' WHERE message_id = 'old-ask'`; + yield* sql`DELETE FROM j5_a2a_peer WHERE environment_id = 'removed-peer'`; + yield* sql`UPDATE j5_a2a_exchange SET status = 'closed' WHERE exchange_id = 'open-ask'`; + assert.isUndefined((yield* read()).deliveryEnvironmentIds.get(sender)); + assert.equal( + (yield* sql`SELECT 1 FROM j5_a2a_delivery WHERE message_id = 'old-ask' AND status = 'delivered'`) + .length, + 1, + ); + }).pipe(Effect.provide(database)), +); diff --git a/apps/server/src/j5/a2a/fleetFacts.ts b/apps/server/src/j5/a2a/fleetFacts.ts new file mode 100644 index 0000000000000..696317cf7c8dd --- /dev/null +++ b/apps/server/src/j5/a2a/fleetFacts.ts @@ -0,0 +1,137 @@ +import type { FleetAgentFacts, FleetDeliveryProblem, FleetResponse } from "@t3tools/contracts/j5"; +import * as Effect from "effect/Effect"; +import type * as SqlClient from "effect/sql/SqlClient"; + +import { CREW_ALERT_EXCHANGE_PREFIX } from "./crewFailureAlert.ts"; +import { clientReadBatches } from "./clientReadBatches.ts"; + +type Ask = FleetAgentFacts["asks"]["owed"][number]; +type ExchangeRow = { + readonly project_id: string; + readonly exchange_id: string; + readonly sender_id: string; + readonly receiver_id: string; + readonly intent: string; + readonly created_at: string; +}; +type AlarmRow = { + readonly sender_id: string; + readonly receiver_id: string; + readonly message_id: string; + readonly exchange_id: string | null; + readonly origin_environment_id: string | null; + readonly updated_at: string; + readonly last_error: string | null; + readonly exchange_open: number; +}; + +/** Both directions span project boundaries: the Exchange lives with its sender. */ +export const readFleetLedgerFacts = Effect.fn("readFleetLedgerFacts")(function* ( + sql: SqlClient.SqlClient, + projectId: string, + agentIds: ReadonlyArray, + nameOf: (id: string) => string | null, +) { + const owed = new Map>(); + const awaited = new Map>(); + const problems = new Map>(); + const deliveryEnvironmentIds = new Map>(); + const batches = clientReadBatches([...new Set(agentIds)]); + const exchanges = new Map>(); + for (const batch of batches) { + for (const column of ["sender_id", "receiver_id"]) { + const rows = yield* sql` + SELECT project_id, exchange_id, sender_id, receiver_id, + CASE WHEN length(intent) > 200 THEN substr(intent, 1, 199) || '…' ELSE intent END AS intent, + created_at + FROM j5_a2a_exchange + WHERE status = 'open' AND ${sql(column)} IN ${sql.in(batch)} + AND exchange_id NOT LIKE ${`${CREW_ALERT_EXCHANGE_PREFIX}%`} + `; + for (const row of rows) { + const projectExchanges = exchanges.get(row.project_id) ?? new Map(); + projectExchanges.set(row.exchange_id, row); + exchanges.set(row.project_id, projectExchanges); + } + } + } + const orderedExchanges = [...exchanges.values()] + .flatMap((rows) => [...rows.values()]) + .toSorted( + (left, right) => + left.created_at.localeCompare(right.created_at) || + left.exchange_id.localeCompare(right.exchange_id) || + left.project_id.localeCompare(right.project_id), + ); + for (const row of orderedExchanges) { + const ask = (counterpartyId: string): Ask => ({ + exchangeId: row.exchange_id, + counterpartyId, + counterpartyName: nameOf(counterpartyId), + intent: row.intent, + openedAt: row.created_at, + }); + const senderAsks = awaited.get(row.sender_id) ?? []; + senderAsks.push(ask(row.receiver_id)); + awaited.set(row.sender_id, senderAsks); + const receiverAsks = owed.get(row.receiver_id) ?? []; + receiverAsks.push(ask(row.sender_id)); + owed.set(row.receiver_id, receiverAsks); + } + // Coverage follows the open debt, so acceptance needs no extra Fleet invalidation. + // CROSS JOIN keeps the small open-Exchange set ahead of indexed receiver-route lookups. + for (const batch of batches) { + const destinations = yield* sql<{ sender_id: string; receiver_environment_id: string }>` + SELECT DISTINCT d.sender_id, d.receiver_environment_id + FROM j5_a2a_exchange e CROSS JOIN j5_a2a_delivery d + ON d.project_id = e.project_id AND d.exchange_id = e.exchange_id + AND d.sender_id = e.sender_id AND d.receiver_id = e.receiver_id + WHERE e.status = 'open' AND e.sender_id IN ${sql.in(batch)} + AND e.exchange_id NOT LIKE ${`${CREW_ALERT_EXCHANGE_PREFIX}%`} + AND d.origin_environment_id IS NULL AND d.receiver_environment_id IS NOT NULL + AND d.exchange_role = 'ask' AND d.envelope_channel = 'peer' + ORDER BY d.receiver_environment_id + `; + for (const row of destinations) { + const environments = deliveryEnvironmentIds.get(row.sender_id) ?? []; + environments.push(row.receiver_environment_id); + deliveryEnvironmentIds.set(row.sender_id, environments); + } + } + const alarms = yield* sql` + SELECT d.sender_id, d.receiver_id, d.message_id, d.exchange_id, d.origin_environment_id, + d.updated_at, d.last_error, + EXISTS (SELECT 1 FROM j5_a2a_exchange e WHERE e.project_id = d.project_id + AND e.exchange_id = d.exchange_id AND e.status = 'open') AS exchange_open + FROM j5_a2a_delivery d + WHERE d.project_id = ${projectId} AND d.status = 'alarmed' AND d.envelope_channel = 'peer' + AND (d.exchange_id IS NULL OR d.exchange_id NOT LIKE ${`${CREW_ALERT_EXCHANGE_PREFIX}%`}) + ORDER BY d.sent_seq, d.message_id + `; + const localAgents = new Set(agentIds); + const remoteDeliveryAlarms: NonNullable[number][] = []; + for (const row of alarms) { + const problem: FleetDeliveryProblem = { + kind: "delivery-failed", + messageId: row.message_id, + exchangeId: row.exchange_id, + receiverId: row.receiver_id, + receiverName: nameOf(row.receiver_id), + at: row.updated_at, + reason: row.last_error, + exchangeOpen: row.exchange_open === 1, + }; + if (row.origin_environment_id !== null) { + remoteDeliveryAlarms.push({ + originEnvironmentId: row.origin_environment_id, + senderId: row.sender_id, + problem, + }); + } else if (localAgents.has(row.sender_id)) { + const senderProblems = problems.get(row.sender_id) ?? []; + senderProblems.push(problem); + problems.set(row.sender_id, senderProblems); + } + } + return { owed, awaited, problems, deliveryEnvironmentIds, remoteDeliveryAlarms }; +}); diff --git a/apps/server/src/j5/a2a/fleetRead.ts b/apps/server/src/j5/a2a/fleetRead.ts index eea4706ade006..f372f71167a9b 100644 --- a/apps/server/src/j5/a2a/fleetRead.ts +++ b/apps/server/src/j5/a2a/fleetRead.ts @@ -1,3 +1,4 @@ +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as J5Contracts from "@t3tools/contracts/j5"; import * as SqlClient from "effect/sql/SqlClient"; @@ -7,6 +8,8 @@ import { AgentCrewInstanceService, type AgentCrewInstance } from "./AgentCrewIns import { A2ALedger } from "./LedgerService.ts"; import { ParticipantPlacementService } from "./PlacementService.ts"; import { LedgerProjectId, isOutsideAgentParticipantId } from "./contracts.ts"; +import { clientReadBatches } from "./clientReadBatches.ts"; +import { readFleetLedgerFacts } from "./fleetFacts.ts"; import { outsideAgentNameRows } from "./outsideAgentNames.ts"; import type { ParticipantPlacementView } from "./placementContracts.ts"; @@ -23,6 +26,7 @@ export const projectFleetProject = (input: { readonly participants: ReadonlyArray; readonly crews: ReadonlyArray; readonly openAsks: ReadonlyMap; + readonly facts?: ReadonlyMap; /** Each live Crew's active playbook run, by Crew id. */ readonly playbookRuns?: ReadonlyMap; /** The label of each outside agent that spawned one of the participants, by its id. */ @@ -62,6 +66,15 @@ export const projectFleetProject = (input: { placementParentId: crew.captainParticipantId, crew: seatByParticipant.get(member.participantId) ?? null, openAsks: 0, + ...(input.facts === undefined + ? {} + : { + facts: { + asks: { owed: [], awaited: [] }, + problems: [], + deliveryEnvironmentIds: [], + }, + }), })), ); return { @@ -97,6 +110,9 @@ export const projectFleetProject = (input: { : {}), crew: seatByParticipant.get(row.participantId) ?? null, openAsks: input.openAsks.get(row.participantId) ?? 0, + ...(input.facts?.has(row.participantId) + ? { facts: input.facts.get(row.participantId)! } + : {}), })), ...unrecordedSeats, ], @@ -130,8 +146,7 @@ export const projectFleetProject = (input: { /** * The Roster read (SB6): every project with its active agents, placement parents, Crew seats, - * and the count of open asks each agent owes. Status and last activity come from the client's - * thread state, so this read carries only what the ledger knows. Unknowns stay unknown. + * and open Exchanges and delivery alarms. Runtime facts stay on the live shell stream. */ export const makeFleetRead = Effect.gen(function* () { const ledger = yield* A2ALedger; @@ -143,20 +158,45 @@ export const makeFleetRead = Effect.gen(function* () { Effect.gen(function* () { const projects = yield* ledger.listProjectLedgers(); const result: Array = []; + const remoteDeliveryAlarms: NonNullable[number][] = []; + const participantsByProject = new Map>(); + // Removed people keep their names on historical Exchange and delivery facts. + const people = yield* sql<{ readonly person_id: string; readonly display_name: string }>` + SELECT person_id, display_name FROM j5_a2a_human_person + WHERE display_name IS NOT NULL + `; + const names = new Map(people.map((person) => [person.person_id, person.display_name])); for (const project of projects) { const participants = yield* placements.listParticipants(project.id); + participantsByProject.set(project.id, participants); + for (const row of participants) { + if ("displayName" in row.participant && typeof row.participant.displayName === "string") + names.set(row.participantId, row.participant.displayName); + } + } + const agents = [...participantsByProject.values()] + .flat() + .filter((row) => row.threadId !== null); + const threadIds = [ + ...new Set(agents.flatMap((row) => (row.threadId === null ? [] : [row.threadId]))), + ]; + const threadNames = new Map(); + for (const batch of clientReadBatches(threadIds)) { + const titles = yield* sql<{ readonly thread_id: string; readonly title: string }>` + SELECT thread_id, title FROM orchestration_v2_projection_threads + WHERE thread_id IN ${sql.in(batch)} + `; + for (const row of titles) threadNames.set(row.thread_id, row.title); + } + for (const row of agents) { + const title = row.threadId === null ? undefined : threadNames.get(row.threadId); + if (title !== undefined) names.set(row.participantId, title); + } + for (const project of projects) { + const participants = participantsByProject.get(project.id)!; const agentIds = participants .filter((row) => row.participant.kind === "agent") .map((row) => row.participantId); - const openAsks = new Map(); - if (agentIds.length > 0) { - const rows = yield* sql<{ readonly receiver_id: string; readonly count: number }>` - SELECT receiver_id, COUNT(*) AS count FROM j5_a2a_exchange - WHERE status = 'open' AND receiver_id IN ${sql.in([...agentIds])} - GROUP BY receiver_id - `; - for (const row of rows) openAsks.set(row.receiver_id, Number(row.count)); - } const outsideSpawnerIds = [ ...new Set( participants.flatMap((row) => @@ -170,9 +210,32 @@ export const makeFleetRead = Effect.gen(function* () { const outsideAgentNames = new Map( (outsideSpawnerIds.length === 0 ? [] - : yield* outsideAgentNameRows(sql, outsideSpawnerIds) + : yield* Effect.forEach(clientReadBatches(outsideSpawnerIds), (batch) => + outsideAgentNameRows(sql, batch), + ).pipe(Effect.map((batches) => batches.flat())) ).map((row) => [row.participant_id, row.display_name] as const), ); + const ledgerFacts = yield* readFleetLedgerFacts( + sql, + project.id, + agentIds, + (id) => names.get(id) ?? outsideAgentNames.get(id) ?? null, + ); + remoteDeliveryAlarms.push(...ledgerFacts.remoteDeliveryAlarms); + const facts = new Map( + agentIds.map((id) => [ + id, + { + asks: { + owed: ledgerFacts.owed.get(id) ?? [], + awaited: ledgerFacts.awaited.get(id) ?? [], + }, + problems: ledgerFacts.problems.get(id) ?? [], + deliveryEnvironmentIds: ledgerFacts.deliveryEnvironmentIds.get(id) ?? [], + }, + ]), + ); + const openAsks = new Map(agentIds.map((id) => [id, ledgerFacts.owed.get(id)?.length ?? 0])); // Retired Crews carry rosters and briefs; only the page that shows them pays for them. const projectCrews = (yield* crews.listForProject(project.id)).filter( (crew) => includeRetired || crew.archivedAt === null, @@ -187,11 +250,16 @@ export const makeFleetRead = Effect.gen(function* () { participants, crews: projectCrews, openAsks, + facts, playbookRuns, outsideAgentNames, }), ); } - return { projects: result } satisfies FleetResponse; + return { + projects: result, + remoteDeliveryAlarms, + asOf: DateTime.formatIso(yield* DateTime.now), + } satisfies FleetResponse; }); }); diff --git a/apps/server/src/j5/run-observability/QueuedRunWatchdog.ts b/apps/server/src/j5/run-observability/QueuedRunWatchdog.ts index 6f3cec4c7437b..48ff0dd9c9f8b 100644 --- a/apps/server/src/j5/run-observability/QueuedRunWatchdog.ts +++ b/apps/server/src/j5/run-observability/QueuedRunWatchdog.ts @@ -3,6 +3,7 @@ import { type OrchestrationV2Run, type OrchestrationV2ThreadProjection, } from "@t3tools/contracts"; +import { FLEET_DISPATCH_THRESHOLD_MS } from "@t3tools/contracts/j5"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -21,7 +22,7 @@ import { import { makeProviderFailure } from "@t3tools/provider-core/server/failure"; import { forkParked } from "../../serverActivation.ts"; -export const QUEUED_RUN_WATCHDOG_DELAY_MS = 5 * 60 * 1000; +export const QUEUED_RUN_WATCHDOG_DELAY_MS = FLEET_DISPATCH_THRESHOLD_MS; export const QUEUED_RUN_WATCHDOG_POLL_MS = 60 * 1000; export const QUEUED_RUN_WATCHDOG_MAX_CANDIDATES = 100; 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/docs/j5/product/features/fleet-page.md b/docs/j5/product/features/fleet-page.md index c1c348d150c0d..970df0a0eb961 100644 --- a/docs/j5/product/features/fleet-page.md +++ b/docs/j5/product/features/fleet-page.md @@ -75,7 +75,7 @@ The Fleet page is **not** the inbox: it never demands a reply. It is **not** a p ### The four facts -15. Status shows the runtime's own fact: Working, Waiting, Approval, Input or Failed; "Waiting to start · Nm" takes precedence while a run has been requested and not dispatched; "Idle since ⟨time⟩" appears only when nothing is active and no background work remains. +15. Status shows the runtime's own fact: Working, Waiting, Approval, Input or Failed; "Waiting to start · Nm" takes precedence while a run has been requested and not dispatched and no other run is in progress; a follow-up queued behind an active run keeps that active run's status; "Idle since ⟨time⟩" appears only when nothing is active and no background work holds completion; a non-holding command such as a dev server does not prevent Idle. 16. Read and snooze bookkeeping (upstream's Woke and Done) is not a status and does not appear. 17. Silence notices are not shown on the page; the age of an open ask is the visible fact. 18. Open asks show two counts, "Owes N" for open asks the agent must answer and "Awaiting N" for open asks it is waiting on, with a hover list of counterparty, intent and age; a follow-up joined to an open Exchange counts once. @@ -84,8 +84,8 @@ The Fleet page is **not** the inbox: it never demands a reply. It is **not** a p ### Problems and the badge -21. A row's measured problems are a failed latest run, a delivery alarm, and a run that has waited past the dispatch threshold; the row lists every one it has. -22. A delivery alarm is shown on the sender's row as "Delivery failed · to ⟨receiver⟩ · ⟨time⟩ · ⟨reason⟩" and stays while the fact is true; it is never inferred repaired ([agent-to-agent communication](../a2a/index.md)). +21. A row's measured problems are a failed latest run, a delivery alarm, and a requested run that has waited past the dispatch threshold with no other run in progress; the row lists every one it has. +22. A delivery alarm is shown on the sender's row as "Delivery failed · to ⟨receiver⟩ · ⟨time⟩ · ⟨reason⟩" and stays while the fact is true, including a receiving server's alarm on a remote sender when both environments are connected to this client; it is never inferred repaired ([agent-to-agent communication](../a2a/index.md)). 23. The badge counts agents that have at least one measured problem across every project the page reads; an agent counts once however many problems it has, unknowns never count, and the badge never counts open asks to the person or silence notices. 24. A delivery alarm counts toward the badge only while the Exchange it belongs to is open; an alarm on a plain message is shown on the row and never counted; a failed delivery of a platform-authored notice is neither shown nor counted. @@ -146,3 +146,5 @@ The Fleet page is **not** the inbox: it never demands a reply. It is **not** a p - 2026-09-25 — a retired Crew comes back with its Captain when it retired because the Captain was archived, so AC28 no longer says it can never be reactivated; the roster snapshot shows why each seat joined, since the roster records no approver (Bryant; [#312](https://github.com/Jacksondr5/j5code/issues/312)). - 2026-10-07 — Squadrons retired: the page reads every project and groups roots by upstream's logical project, the sidebar is upstream's project sidebar, and every thread but a provider Subagent is a participant, so AC1 (the Squadron scope) and AC13 (the footer for threads without a home) are retired. Placement and provenance moved here from the retired Squadron definition: its AC10, AC12 and AC13 are AC34 and AC35 (Jackson, 2026-10-05; [#412](https://github.com/Jacksondr5/j5code/issues/412)). - 2026-10-12 — an outside agent can be a spawner: the agent it starts is placed at its project's root and its provenance names the outside agent by its label; AC12 and AC34 (Jackson, 2026-10-11; [#498](https://github.com/Jacksondr5/j5code/issues/498)). +- 2026-10-21 — clarified AC15 and AC21: queued follow-ups preserve the active run's status, only completion-holding background work prevents Idle, and dispatch is overdue only when no other run is in progress ([#360](https://github.com/Jacksondr5/j5code/issues/360); [#662](https://github.com/Jacksondr5/j5code/pull/662)). +- 2026-10-24 — receiving servers expose later peer delivery alarms through their own Fleet read, and the client attaches them to the remote sender only while both environments are readable; unavailable receivers of open asks leave badge coverage incomplete, with no alarm returned over A2A (Jackson, 2026-10-24; [#662](https://github.com/Jacksondr5/j5code/pull/662)). diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 15164e86ba390..2445e893a0401 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -375,6 +375,10 @@ "types": "./src/j5/http.ts", "default": "./src/j5/http.ts" }, + "./j5/fleetFacts": { + "types": "./src/j5/fleetFacts.ts", + "default": "./src/j5/fleetFacts.ts" + }, "./j5/state": { "types": "./src/j5/state.ts", "default": "./src/j5/state.ts" diff --git a/packages/client-runtime/src/j5/fleetFacts.test.ts b/packages/client-runtime/src/j5/fleetFacts.test.ts new file mode 100644 index 0000000000000..6b449a5367afb --- /dev/null +++ b/packages/client-runtime/src/j5/fleetFacts.test.ts @@ -0,0 +1,872 @@ +import { describe, expect, it, vi, afterEach } from "vite-plus/test"; +import { + EnvironmentId, + RunId, + RuntimeRequestId, + type OrchestrationV2ThreadShell, +} from "@t3tools/contracts"; +import { + FleetResponse, + FLEET_DISPATCH_THRESHOLD_MS, + type FleetAgentFacts, + type FleetDeliveryProblem, +} from "@t3tools/contracts/j5"; +import * as DateTime from "effect/DateTime"; +import * as Schema from "effect/Schema"; +import { Atom, AtomRegistry } from "effect/reactivity"; + +import { v2ThreadShell } from "../state/orchestrationV2TestFixtures.ts"; +import type { J5ReadSource } from "./readSources.ts"; +import { + createFleetFactsAtom, + deriveFleetFacts, + summarizeFleetProblems, + fleetAgentKey, + mergeFleetDeliveryFacts, + type FleetFactRow, +} from "./fleetFacts.ts"; + +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: [], + deliveryEnvironmentIds: [], +}; +const shell = (changes: Partial = {}): OrchestrationV2ThreadShell => ({ + ...v2ThreadShell, + latestRunId: RunId.make("r"), + status: "starting", + latestRunRequestedAt: date, + latestRunStartedAt: null, + latestRunCompletedAt: null, + activityRunStatus: "starting", + pendingBackgroundTasks: [], + ...changes, +}); +const derive = (source: OrchestrationV2ThreadShell | undefined, clock = now) => + deriveFleetFacts({ shell: source, ledger, now: clock }); + +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); + expect(before.facts.runtime).toMatchObject({ status: "waiting-to-start" }); + expect(before.nextDeadline).toBe(now + FLEET_DISPATCH_THRESHOLD_MS); + expect(before.facts.problems).toEqual([]); + const due = derive(shell(), now + FLEET_DISPATCH_THRESHOLD_MS); + expect(due.facts.problems).toEqual([{ kind: "dispatch-overdue", runId: "r", at }]); + expect(due.nextDeadline).toBeUndefined(); + expect(derive(shell(), now + 900_000).nextDeadline).toBeUndefined(); + const dispatched = derive( + shell({ status: "running", activityRunStatus: "running", latestRunStartedAt: date }), + now + 900_000, + ); + expect(dispatched.facts.runtime).toMatchObject({ status: "working" }); + expect(dispatched.facts.problems).toEqual([]); + }); + + it("preserves raw runtime activity when an older shell omits activityRunStatus", () => { + const source = shell({ + status: "running", + activeRunId: RunId.make("r"), + latestRunStartedAt: date, + activityRunStatus: undefined, + }); + expect(derive(source).facts.runtime).toMatchObject({ + state: "known", + status: "working", + settled: false, + }); + expect(derive({ ...source, status: "waiting" }).facts.runtime).toMatchObject({ + status: "waiting", + }); + expect(derive({ ...source, status: "preparing" }).facts.runtime).toMatchObject({ + status: "waiting", + }); + }); + + it("gives undispatched work precedence over approval, then follows input and background state", () => { + const pending = { + id: RuntimeRequestId.make("approval"), + kind: "command" as const, + createdAt: date, + }; + expect(derive(shell({ pendingRuntimeRequest: pending })).facts.runtime).toMatchObject({ + status: "waiting-to-start", + }); + const started = shell({ + latestRunStartedAt: date, + activityRunStatus: "running", + status: "running", + pendingRuntimeRequest: pending, + }); + expect(derive(started).facts.runtime).toMatchObject({ status: "approval" }); + expect( + derive({ ...started, pendingRuntimeRequest: { ...pending, kind: "user_input" } }).facts + .runtime, + ).toMatchObject({ status: "input" }); + expect( + derive( + shell({ + status: "completed", + activityRunStatus: null, + latestRunStartedAt: date, + latestRunCompletedAt: date, + pendingBackgroundTasks: [{ kind: "background_task", taskId: "background" }], + settledAt: date, + }), + ).facts.runtime, + ).toMatchObject({ status: "waiting", settled: false }); + expect( + derive( + shell({ + status: "completed", + activityRunStatus: null, + latestRunStartedAt: date, + latestRunCompletedAt: date, + settledAt: date, + }), + ).facts.runtime, + ).toMatchObject({ status: "idle", since: at, settled: true }); + }); + + it("leaves queued follow-ups behind another run Working, Approval or Input without a deadline", () => { + const queued = shell({ + status: "queued", + activeRunId: RunId.make("earlier"), + activityRunStatus: "running", + }); + const overdueClock = now + FLEET_DISPATCH_THRESHOLD_MS * 2; + expect(derive(queued, overdueClock)).toMatchObject({ + facts: { runtime: { status: "working" }, problems: [] }, + }); + expect(derive(queued, overdueClock).nextDeadline).toBeUndefined(); + const pending = { + id: RuntimeRequestId.make("request"), + kind: "command" as const, + createdAt: date, + }; + expect( + derive({ ...queued, pendingRuntimeRequest: pending }, overdueClock).facts.runtime, + ).toMatchObject({ status: "approval" }); + expect( + derive({ ...queued, pendingRuntimeRequest: { ...pending, kind: "user_input" } }, overdueClock) + .facts.runtime, + ).toMatchObject({ status: "input" }); + expect( + derive({ ...queued, activityRunStatus: "waiting", activeRunId: null }, overdueClock), + ).toMatchObject({ facts: { runtime: { status: "waiting" }, problems: [] } }); + const alone = shell({ status: "queued", activeRunId: null, activityRunStatus: null }); + expect(derive(alone, now + FLEET_DISPATCH_THRESHOLD_MS - 1).facts.problems).toEqual([]); + expect(derive(alone, now + FLEET_DISPATCH_THRESHOLD_MS).facts.problems).toEqual([ + { kind: "dispatch-overdue", runId: "r", at }, + ]); + }); + + it("lets non-holding commands remain idle and reports holding background work as Waiting", () => { + const completed = shell({ + status: "completed", + activityRunStatus: null, + latestRunStartedAt: date, + latestRunCompletedAt: date, + }); + expect( + derive({ ...completed, pendingBackgroundTasks: [{ kind: "command", taskId: "dev-server" }] }) + .facts.runtime, + ).toMatchObject({ status: "idle", since: at }); + for (const kind of ["subagent", "monitor", "background_task"] as const) { + expect( + derive({ ...completed, pendingBackgroundTasks: [{ kind, taskId: "work" }] }).facts.runtime, + ).toMatchObject({ status: "waiting", settled: false }); + } + }); + + 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", + activityRunStatus: null, + 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 }, + ]); + expect( + derive({ ...failed, status: "completed", latestRunCompletedAt: null }).facts.runtime, + ).toMatchObject({ + state: "unknown", + reason: "The latest run has no measured completion time.", + }); + expect(derive({ ...failed, status: "completed" }).facts.problems).toEqual([]); + expect(derive({ ...failed, status: "completed" }).facts.runtime).toMatchObject({ + status: "idle", + }); + }); + + it("measures a steering message without changing the running turn", () => { + const receivedAt = "2026-10-19T10:10:00.000Z"; + const source = shell({ + status: "running", + activityRunStatus: "running", + latestRunStartedAt: date, + latestVisibleMessage: null, + latestUserMessageAt: DateTime.makeUnsafe(receivedAt), + }); + expect(derive(source).facts.lastActivity).toEqual({ + state: "known", + label: "Message received", + at: receivedAt, + }); + expect(derive(source).facts.runtime).toMatchObject({ state: "known", status: "working" }); + const completedAt = "2026-10-19T10:11:00.000Z"; + expect( + derive({ + ...source, + status: "completed", + activityRunStatus: null, + latestRunCompletedAt: DateTime.makeUnsafe(completedAt), + }).facts.lastActivity, + ).toEqual({ state: "known", label: "Turn ended", at: completedAt }); + }); + + it("ignores bookkeeping updatedAt and labels the latest measured event", () => { + const source = shell({ + status: "completed", + activityRunStatus: null, + latestRunStartedAt: date, + latestRunCompletedAt: date, + updatedAt: DateTime.makeUnsafe(now + 60_000), + settledAt: DateTime.makeUnsafe(now + 60_000), + }); + expect(derive(source).facts.lastActivity).toEqual({ state: "known", label: "Turn ended", at }); + expect(derive({ ...source, latestRunCompletedAt: undefined }).facts.lastActivity).toEqual({ + state: "unknown", + reason: "This environment does not report run timestamps.", + }); + }); + + it("keeps known delivery facts when runtime is missing and leaves old ledger facts absent", () => { + const alarm = { + kind: "delivery-failed" as const, + messageId: "m", + receiverId: "other", + receiverName: null, + at, + reason: "offline", + exchangeOpen: true, + }; + const missing = deriveFleetFacts({ + shell: undefined, + ledger: { ...ledger, problems: [alarm] }, + now, + }); + expect(missing.facts.runtime.state).toBe("unknown"); + expect(missing.facts.problems).toEqual([alarm]); + const old = decodeFleet({ + projects: [ + { + id: "p", + title: "P", + crews: [], + agents: [ + { + participantId: "a", + threadId: "t", + displayName: null, + origin: "human", + placementParentId: null, + crew: null, + openAsks: 4, + }, + ], + }, + ], + }); + expect(old.asOf).toBeUndefined(); + expect(old.projects[0]!.agents[0]!.facts).toBeUndefined(); + const source = shell({ + status: "completed", + activityRunStatus: null, + latestRunStartedAt: date, + latestRunCompletedAt: date, + }); + const partial = deriveFleetFacts({ + shell: source, + ledger: old.projects[0]!.agents[0]!.facts, + now, + }).facts; + expect(partial.asks).toBeUndefined(); + expect(partial.runtime).toMatchObject({ state: "known", status: "idle" }); + expect(partial.lastActivity).toEqual({ + state: "unknown", + reason: "This environment does not report Exchange or delivery activity.", + }); + const later = "2026-10-19T10:01:00.000Z"; + const restored = deriveFleetFacts({ + shell: source, + ledger: { ...ledger, problems: [{ ...alarm, at: later }] }, + now: Date.parse(later), + }).facts; + expect(restored.lastActivity).toEqual({ + state: "known", + label: "Delivery failed", + at: later, + }); + }); +}); + +it("shares one local deadline across consumers, clears stale/removed rows, and never rereads ledger", () => { + vi.useFakeTimers(); + vi.setSystemTime(now); + const rows = Atom.make>([ + { key: "env-a:a", shell: shell(), ledger, live: true }, + { + key: "env-b:a", + shell: shell({ latestRunRequestedAt: DateTime.makeUnsafe(now + 1_000) }), + ledger, + live: true, + }, + ]); + const facts = createFleetFactsAtom(rows); + const registry = AtomRegistry.make({ defaultIdleTTL: 0 }); + const callback = vi.fn(); + const first = registry.subscribe(facts, callback, { immediate: true }); + const second = registry.subscribe(facts, callback, { immediate: true }); + vi.advanceTimersByTime(0); + const timerCount = vi.getTimerCount(); + expect(timerCount).toBe(1); + const unchanged = registry.get(facts).get("env-a:a"); + registry.set( + rows, + registry + .get(rows) + .map((row) => + row.key === "env-b:a" ? { ...row, shell: { ...row.shell!, title: "Renamed" } } : row, + ), + ); + expect(registry.get(facts).get("env-a:a")).toBe(unchanged); + vi.advanceTimersByTime(FLEET_DISPATCH_THRESHOLD_MS); + expect(registry.get(facts).get("env-a:a")!.problems).toHaveLength(1); + expect(registry.get(facts).get("env-b:a")!.problems).toHaveLength(0); + expect(vi.getTimerCount()).toBe(1); + registry.set( + rows, + registry.get(rows).map((row) => ({ ...row, live: false })), + ); + vi.advanceTimersByTime(0); + expect(vi.getTimerCount()).toBe(0); + registry.set(rows, []); + expect(registry.get(facts).size).toBe(0); + first(); + second(); + registry.dispose(); +}); + +it("does not advance offline dispatch facts when unrelated live rows change", () => { + vi.useFakeTimers(); + vi.setSystemTime(now); + const alarm = { + kind: "delivery-failed" as const, + messageId: "m", + receiverId: "other", + receiverName: null, + at, + reason: "offline", + exchangeOpen: true, + }; + const rows = Atom.make>([ + { + key: "offline:a", + shell: shell(), + ledger: { ...ledger, problems: [alarm], deliveryEnvironmentIds: [] }, + live: true, + }, + { key: "cached:a", shell: shell(), ledger, live: false }, + ]); + const facts = createFleetFactsAtom(rows); + const registry = AtomRegistry.make({ defaultIdleTTL: 0 }); + const stop = registry.subscribe(facts, () => {}, { immediate: true }); + const measured = registry.get(facts).get("offline:a")!; + expect(measured.problemsIncomplete).toBe(false); + registry.set( + rows, + registry.get(rows).map((row) => ({ ...row, live: false })), + ); + const frozen = registry.get(facts).get("offline:a")!; + expect(frozen.problemsIncomplete).toBe(true); + expect(frozen.runtime).toBe(measured.runtime); + expect(frozen.lastActivity).toBe(measured.lastActivity); + expect(frozen.asks).toBe(measured.asks); + expect(frozen.problems).toBe(measured.problems); + vi.advanceTimersByTime(FLEET_DISPATCH_THRESHOLD_MS * 2); + registry.set(rows, [ + ...registry.get(rows), + { + key: "live:a", + shell: shell({ + status: "completed", + activityRunStatus: null, + latestRunStartedAt: date, + latestRunCompletedAt: date, + }), + ledger, + live: true, + }, + ]); + const stale = registry.get(facts).get("offline:a")!; + expect(stale).toBe(frozen); + expect(stale.runtime).toMatchObject({ state: "known", status: "waiting-to-start" }); + expect(stale.lastActivity.state).toBe("known"); + expect(stale.problems).toEqual([alarm]); + expect(registry.get(facts).get("cached:a")?.runtime.state).toBe("unknown"); + registry.set( + rows, + registry.get(rows).map((row) => (row.key === "offline:a" ? { ...row, live: true } : row)), + ); + expect(registry.get(facts).get("offline:a")?.problemsIncomplete).toBe(false); + stop(); + registry.dispose(); +}); + +describe("receiving-environment delivery alarm merge", () => { + const senderId = "agent:shared"; + const ask = (exchangeId: string) => ({ + exchangeId, + counterpartyId: "agent:receiver", + counterpartyName: "Receiver", + intent: "Review", + openedAt: at, + }); + const openLedger: FleetAgentFacts = { + ...ledger, + asks: { owed: [], awaited: [ask("exchange")] }, + deliveryEnvironmentIds: ["receiver"], + }; + const problem = { + kind: "delivery-failed" as const, + messageId: "received-message", + exchangeId: "exchange", + receiverId: "agent:receiver", + receiverName: "Receiver", + at, + reason: "thread unavailable", + exchangeOpen: true, + }; + const project = (facts: FleetAgentFacts | undefined, id = "project") => ({ + id, + title: id, + crews: [], + agents: [ + { + participantId: senderId, + threadId: "thread", + displayName: "Sender", + origin: "human" as const, + placementParentId: null, + crew: null, + openAsks: 0, + ...(facts === undefined ? {} : { facts }), + }, + ], + }); + const source = (id: string, data: FleetResponse): J5ReadSource => ({ + environmentId: EnvironmentId.make(id), + environmentLabel: id, + connected: true, + status: "ready", + data, + error: null, + refreshing: false, + }); + const origin = (facts: FleetAgentFacts | undefined = openLedger, id = "origin") => + source(id, { projects: [project(facts)], remoteDeliveryAlarms: [] }); + const receiver = (changes: Partial = {}) => + source("receiver", { + projects: [], + remoteDeliveryAlarms: [ + { originEnvironmentId: "origin", senderId, problem: { ...problem, ...changes } }, + ], + }); + const merge = (...sources: J5ReadSource[]) => + mergeFleetDeliveryFacts( + { isReady: true, sources }, + new Map(sources.map((entry) => [entry.environmentId, true])), + ); + const key = fleetAgentKey("origin", senderId); + + it("attaches remote facts to the origin environment and participant without phantom rows", () => { + const receiving = source("receiver", { + projects: [], + remoteDeliveryAlarms: [ + ...receiver().data!.remoteDeliveryAlarms!, + { + originEnvironmentId: "other", + senderId, + problem: { ...problem, messageId: "other-message" }, + }, + { originEnvironmentId: "origin", senderId: "agent:elsewhere", problem }, + ], + }); + const facts = merge(origin(), origin(openLedger, "other"), receiving); + expect(facts.get(key)?.ledger?.problems).toEqual([problem]); + expect(facts.get(fleetAgentKey("other", senderId))?.ledger?.problems).toEqual([ + { ...problem, messageId: "other-message" }, + ]); + expect(facts.get(key)?.problemsIncomplete).toBe(false); + expect(merge(receiving).size).toBe(0); + expect(facts.size).toBe(2); + }); + + it("counts a remote alarm only while both Exchange reads say open, preserving closed and plain facts", () => { + expect(merge(origin(), receiver()).get(key)?.ledger?.problems).toEqual([problem]); + const closedOrigin = { ...openLedger, asks: ledger.asks }; + expect(merge(origin(closedOrigin), receiver()).get(key)?.ledger?.problems).toEqual([ + { ...problem, exchangeOpen: false }, + ]); + expect(merge(origin(), receiver({ exchangeOpen: false })).get(key)?.ledger?.problems).toEqual([ + { ...problem, exchangeOpen: false }, + ]); + expect(merge(origin(), receiver({ exchangeId: null })).get(key)?.ledger?.problems).toEqual([ + { ...problem, exchangeId: null, exchangeOpen: false }, + ]); + }); + + it("attaches a later receiver alarm using the unchanged pending-origin snapshot", () => { + const pendingOrigin = origin(); + const before = merge( + pendingOrigin, + source("receiver", { projects: [], remoteDeliveryAlarms: [] }), + ); + expect(before.get(key)).toMatchObject({ ledger: { problems: [] }, problemsIncomplete: false }); + const after = merge(pendingOrigin, receiver()); + expect(after.get(key)).toMatchObject({ + ledger: { problems: [problem] }, + problemsIncomplete: false, + }); + expect(pendingOrigin.data?.projects[0]?.agents[0]?.facts?.problems).toEqual([]); + }); + + it("shows connected plain and closed-Exchange alarms independently of badge coverage dependencies", () => { + const noOpenDebt = origin({ ...ledger, deliveryEnvironmentIds: [] }); + expect(merge(noOpenDebt, receiver({ exchangeId: null })).get(key)).toMatchObject({ + ledger: { problems: [{ ...problem, exchangeId: null, exchangeOpen: false }] }, + problemsIncomplete: false, + }); + expect(merge(noOpenDebt, receiver()).get(key)).toMatchObject({ + ledger: { problems: [{ ...problem, exchangeOpen: false }] }, + problemsIncomplete: false, + }); + expect( + merge(noOpenDebt, { ...receiver(), connected: false, status: "offline" }).get(key), + ).toMatchObject({ ledger: { problems: [] }, problemsIncomplete: false }); + }); + + it("reports missing, old, disconnected and unreadable relevant receivers as incomplete", () => { + const unavailable: J5ReadSource[] = [ + { ...receiver(), connected: false, status: "offline" }, + { ...receiver(), status: "error", error: "read failed" }, + { ...receiver(), status: "loading" }, + { ...receiver(), status: "unsupported" }, + source("receiver", { projects: [] }), + ]; + for (const receiving of unavailable) { + expect(merge(origin(), receiving).get(key)).toMatchObject({ + ledger: { problems: [] }, + problemsIncomplete: true, + }); + } + expect(merge(origin()).get(key)?.problemsIncomplete).toBe(true); + expect( + merge(origin({ ...ledger, deliveryEnvironmentIds: [] }), ...unavailable).get(key) + ?.problemsIncomplete, + ).toBe(false); + 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: [] }, + problemsIncomplete: true, + }); + expect( + mergeFleetDeliveryFacts( + { isReady: true, sources: [origin(), receiver()] }, + new Map([ + ["origin", true], + ["receiver", false], + ]), + ).get(key), + ).toMatchObject({ ledger: { problems: [] }, problemsIncomplete: true }); + }); + + it("aggregates repeated placements across projects before merging receiver alarms", () => { + const first = { ...openLedger, problems: [{ ...problem, messageId: "local-first" }] }; + const second = { + ...openLedger, + asks: { owed: [], awaited: [ask("second")] }, + deliveryEnvironmentIds: ["second-receiver"], + }; + const sending = source("origin", { + projects: [project(first, "one"), project(second, "two"), project(first, "three")], + remoteDeliveryAlarms: [], + }); + const receiving = source("second-receiver", { + projects: [], + remoteDeliveryAlarms: [ + { + originEnvironmentId: "origin", + senderId, + problem: { ...problem, messageId: "second-message", exchangeId: "second" }, + }, + ], + }); + const result = merge(sending, receiver(), receiving).get(key)!; + expect(result.problemsIncomplete).toBe(false); + expect(result.ledger?.deliveryEnvironmentIds).toEqual(["receiver", "second-receiver"]); + expect(result.ledger?.asks.awaited.map((entry) => entry.exchangeId)).toEqual([ + "exchange", + "second", + ]); + expect( + result.ledger?.problems.map((entry) => entry.kind === "delivery-failed" && entry.messageId), + ).toEqual(["local-first", "received-message", "second-message"]); + }); + + it("removes a cached receiver alarm from a live origin when receiver coverage is lost", () => { + const rows = Atom.make>([]); + const facts = createFleetFactsAtom(rows); + const registry = AtomRegistry.make(); + const stop = registry.subscribe(facts, () => {}, { immediate: true }); + const update = (receiving: J5ReadSource) => { + const merged = merge(origin(), receiving).get(key)!; + registry.set(rows, [ + { key, shell: shell({ latestRunId: null, status: "completed" }), live: true, ...merged }, + ]); + }; + update(receiver()); + expect(registry.get(facts).get(key)?.problems).toEqual([problem]); + update({ ...receiver(), connected: false, status: "offline" }); + expect(registry.get(facts).get(key)).toMatchObject({ problems: [], problemsIncomplete: true }); + stop(); + registry.dispose(); + }); +}); diff --git a/packages/client-runtime/src/j5/fleetFacts.ts b/packages/client-runtime/src/j5/fleetFacts.ts new file mode 100644 index 0000000000000..8439605ef0887 --- /dev/null +++ b/packages/client-runtime/src/j5/fleetFacts.ts @@ -0,0 +1,435 @@ +import type { OrchestrationV2ThreadShell } from "@t3tools/contracts"; +import { + FLEET_DISPATCH_THRESHOLD_MS, + type FleetAgentFacts, + type FleetRuntimeFact, + type FleetActivityFact, + type FleetProblem, + type FleetResponse, +} from "@t3tools/contracts/j5"; +import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; +import * as Equal from "effect/Equal"; +import * as Option from "effect/Option"; +import { Atom } from "effect/reactivity"; +import * as DateTime from "effect/DateTime"; +import type { J5ReadSources } from "./readSources.ts"; + +const iso = (value: DateTime.Utc | null | undefined) => + value == null ? null : DateTime.formatIso(value); + +export const fleetAgentKey = (environmentId: string, participantId: string) => + `${environmentId.length}:${environmentId}${participantId}`; + +/** Remote alarms are current only when both independently read environments are readable. */ +export const mergeFleetDeliveryFacts = ( + sources: J5ReadSources, + live: ReadonlyMap, +) => { + const readable = (source: J5ReadSources["sources"][number]) => + source.connected && + source.status === "ready" && + source.data !== null && + live.get(source.environmentId) === true; + const readableReceivers = new Set(); + const remoteAlarms = new Map< + string, + NonNullable[number][] + >(); + for (const source of sources.sources) { + if (!readable(source) || source.data?.remoteDeliveryAlarms === undefined) continue; + readableReceivers.add(source.environmentId); + for (const alarm of source.data.remoteDeliveryAlarms) { + const key = fleetAgentKey(alarm.originEnvironmentId, alarm.senderId); + const alarms = remoteAlarms.get(key) ?? []; + alarms.push(alarm); + remoteAlarms.set(key, alarms); + } + } + const unique = (values: ReadonlyArray, key: (value: A) => string) => [ + ...new Map(values.map((value) => [key(value), value])).values(), + ]; + const origins = new Map< + string, + { + readable: boolean; + ledger: FleetAgentFacts | undefined; + incomplete: boolean; + } + >(); + for (const source of sources.sources) { + for (const project of source.data?.projects ?? []) { + for (const agent of project.agents) { + const key = fleetAgentKey(source.environmentId, agent.participantId); + const previous = origins.get(key); + const left = previous?.ledger; + const right = agent.facts; + const ledger = + left === undefined + ? right + : right === undefined + ? left + : { + asks: { + owed: unique([...left.asks.owed, ...right.asks.owed], (ask) => ask.exchangeId), + awaited: unique( + [...left.asks.awaited, ...right.asks.awaited], + (ask) => ask.exchangeId, + ), + }, + problems: unique([...left.problems, ...right.problems], (problem) => + JSON.stringify([ + problem.kind, + problem.kind === "delivery-failed" ? problem.messageId : problem.runId, + ]), + ), + deliveryEnvironmentIds: [ + ...new Set([ + ...(left.deliveryEnvironmentIds ?? []), + ...(right.deliveryEnvironmentIds ?? []), + ]), + ], + }; + origins.set(key, { + readable: readable(source), + ledger, + incomplete: previous?.incomplete === true || right?.deliveryEnvironmentIds === undefined, + }); + } + } + } + const result = new Map< + string, + { readonly ledger: FleetAgentFacts | undefined; readonly problemsIncomplete: boolean } + >(); + for (const [key, origin] of origins) { + const { ledger } = origin; + const destinations = ledger?.deliveryEnvironmentIds ?? []; + const openExchanges = new Set( + [...(ledger?.asks.owed ?? []), ...(ledger?.asks.awaited ?? [])].map((ask) => ask.exchangeId), + ); + const remoteProblems = origin.readable + ? (remoteAlarms.get(key) ?? []).map((alarm) => ({ + ...alarm.problem, + // The origin owns the Exchange; its closure can precede the receiver's mirror. + exchangeOpen: + alarm.problem.exchangeOpen && + alarm.problem.exchangeId != null && + openExchanges.has(alarm.problem.exchangeId), + })) + : []; + result.set(key, { + ledger: + ledger === undefined || remoteProblems.length === 0 + ? ledger + : { + ...ledger, + problems: [...ledger.problems, ...remoteProblems], + }, + problemsIncomplete: + !origin.readable || + origin.incomplete || + destinations.some((environmentId) => !readableReceivers.has(environmentId)), + }); + } + return result; +}; + +export interface FleetDerivedFacts { + readonly runtime: FleetRuntimeFact; + readonly asks: FleetAgentFacts["asks"] | undefined; + readonly lastActivity: FleetActivityFact; + readonly problems: ReadonlyArray; + 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 } => { + const { shell } = input; + const problems = [...(input.ledger?.problems ?? [])]; + const asks = input.ledger?.asks; + const problemsIncomplete = + input.problemsIncomplete ?? input.ledger?.deliveryEnvironmentIds === undefined; + if (shell === undefined) { + const unknown = { + state: "unknown" as const, + reason: "This environment has no readable thread shell.", + }; + return { + facts: { runtime: unknown, lastActivity: unknown, asks, problems, problemsIncomplete }, + }; + } + const missingRunTimes = + shell.latestRunId !== null && + (shell.latestRunRequestedAt === undefined || + shell.latestRunStartedAt === undefined || + shell.latestRunCompletedAt === undefined); + const requestedAt = iso(shell.latestRunRequestedAt); + const startedAt = iso(shell.latestRunStartedAt); + const completedAt = iso(shell.latestRunCompletedAt); + const otherRunInProgress = + (shell.activeRunId !== null && shell.activeRunId !== shell.latestRunId) || + shell.activityRunStatus === "running" || + shell.activityRunStatus === "waiting"; + const undispatched = + shell.latestRunId !== null && + !otherRunInProgress && + requestedAt !== null && + startedAt === null && + (shell.status === "queued" || shell.status === "preparing" || shell.status === "starting"); + const dueIn = undispatched + ? Date.parse(requestedAt) + FLEET_DISPATCH_THRESHOLD_MS - input.now + : null; + if (!missingRunTimes && shell.status === "failed" && shell.latestRunId !== null) { + problems.push({ + kind: "failed-run", + runId: shell.latestRunId, + at: completedAt, + }); + } + if (!missingRunTimes && dueIn !== null && dueIn <= 0) { + problems.push({ kind: "dispatch-overdue", runId: shell.latestRunId!, at: requestedAt! }); + } + const candidates: Array<{ readonly label: string; readonly at: string }> = [ + { label: "Agent created", at: iso(shell.createdAt)! }, + ]; + if (requestedAt !== null) candidates.push({ label: "Turn requested", at: requestedAt }); + if (startedAt !== null) candidates.push({ label: "Turn started", at: startedAt }); + if (completedAt !== null) candidates.push({ label: "Turn ended", at: completedAt }); + const receivedAt = iso(shell.latestUserMessageAt); + if (receivedAt !== null) candidates.push({ label: "Message received", at: receivedAt }); + if (shell.pendingRuntimeRequest !== null) + candidates.push({ + label: + shell.pendingRuntimeRequest.kind === "user_input" + ? "Input requested" + : shell.pendingRuntimeRequest.kind === "auth_refresh" + ? "Authentication requested" + : "Approval requested", + at: iso(shell.pendingRuntimeRequest.createdAt)!, + }); + for (const ask of input.ledger?.asks.awaited ?? []) + candidates.push({ label: "Ask opened", at: ask.openedAt }); + for (const problem of input.ledger?.problems ?? []) + if (problem.kind === "delivery-failed") + candidates.push({ label: "Delivery failed", at: problem.at }); + const latest = candidates.reduce((left, right) => + Date.parse(right.at) >= Date.parse(left.at) ? right : left, + ); + const lastActivity: FleetActivityFact = missingRunTimes + ? { state: "unknown", reason: "This environment does not report run timestamps." } + : input.ledger === undefined + ? { + state: "unknown", + reason: "This environment does not report Exchange or delivery activity.", + } + : { 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" + : approval + ? "approval" + : needsInput + ? "input" + : shell.pendingRuntimeRequest?.kind === "auth_refresh" + ? "waiting" + : activity === "running" + ? "working" + : activity === "waiting" + ? "waiting" + : 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 && + shell.activityRunStatus == null && + shell.status !== "running" && + shell.status !== "waiting" + ? "This environment does not report the active run's status." + : status === "idle" && shell.latestRunId !== null && completedAt === null + ? "The latest run has no measured completion time." + : null; + const runtime: FleetRuntimeFact = + unknownRuntimeReason !== null + ? { state: "unknown", reason: unknownRuntimeReason } + : { + state: "known", + status, + since: undispatched + ? requestedAt + : status === "idle" + ? shell.latestRunId === null + ? iso(shell.createdAt) + : completedAt + : iso(shell.activityRunStartedAt), + settled: + status === "idle" && + (shell.settledOverride === "settled" || + (shell.settledOverride !== "active" && shell.settledAt !== null)), + }; + return { + facts: { runtime, asks, lastActivity, problems, problemsIncomplete }, + ...(!missingRunTimes && dueIn !== null && dueIn > 0 ? { nextDeadline: input.now + dueIn } : {}), + }; +}; + +export interface FleetFactRow { + readonly key: string; + 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) => { + // @effect-diagnostics-next-line globalDate:off - This Atom runs outside an Effect runtime and shares one presentation deadline. + const now = Date.now(); + const previous = Option.getOrUndefined(get.self>()); + const facts = new Map(); + let nextDeadline: number | undefined; + for (const row of get(rows)) { + if (!row.live) { + const cached = previous?.get(row.key); + const frozen = + cached === undefined || cached.problemsIncomplete + ? cached + : { ...cached, problemsIncomplete: true }; + const unknown = { + state: "unknown" as const, + reason: "This environment is unavailable; runtime and activity are not current.", + }; + 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 existing = facts.get(row.key); + facts.set( + row.key, + 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); + get.addFinalizer(() => clearTimeout(timer)); + } + return facts; + }); diff --git a/packages/contracts/src/j5.ts b/packages/contracts/src/j5.ts index 336681709b96b..a32dd4137b91a 100644 --- a/packages/contracts/src/j5.ts +++ b/packages/contracts/src/j5.ts @@ -3,6 +3,7 @@ import * as Schema from "effect/Schema"; import * as Struct from "effect/Struct"; import { Rpc, RpcGroup } from "effect/rpc"; export * from "./j5/actionError.ts"; +export * from "./j5/fleet.ts"; export * from "./j5/peerPoll.ts"; export * from "./j5/playbook.ts"; export * from "./j5/access.ts"; @@ -11,6 +12,8 @@ export * from "./j5/people.ts"; export * from "./j5/sharedConversation.ts"; export * from "./j5/sharing.ts"; +import { FleetAgentFacts, FleetDeliveryProblem } from "./j5/fleet.ts"; + import { ModelSelection } from "./modelSelection.ts"; import { ProviderApprovalDecision, @@ -384,6 +387,8 @@ export const FleetAgent = Schema.Struct({ ), /** Open Exchanges this agent owes a reply on. */ openAsks: Schema.Number, + /** Absent on older environments; clients must show unknown, never healthy. */ + facts: Schema.optionalKey(FleetAgentFacts), }); export type FleetAgent = typeof FleetAgent.Type; /** One project's agents and Crews. `title` is the server's, for a project the client cannot find. */ @@ -397,7 +402,20 @@ export type FleetProject = typeof FleetProject.Type; /** The rail badge reads the live roster only; the Fleet page asks for retired Crews as well. */ export const FleetReadRequest = Schema.Struct({ includeRetired: Schema.optional(Schema.Boolean) }); export type FleetReadRequest = typeof FleetReadRequest.Type; -export const FleetResponse = Schema.Struct({ projects: Schema.Array(FleetProject) }); +export const FleetResponse = Schema.Struct({ + /** Receiving-server facts, attributed by the sender's stable environment and participant. */ + remoteDeliveryAlarms: Schema.optionalKey( + Schema.Array( + Schema.Struct({ + originEnvironmentId: Schema.String, + senderId: Schema.String, + problem: FleetDeliveryProblem, + }), + ), + ), + projects: Schema.Array(FleetProject), + asOf: Schema.optionalKey(Schema.String), +}); export type FleetResponse = typeof FleetResponse.Type; /** A person stopping a Crew from the app: every running seat is interrupted, nothing is retired. */ diff --git a/packages/contracts/src/j5/fleet.ts b/packages/contracts/src/j5/fleet.ts new file mode 100644 index 0000000000000..10bc2cccab826 --- /dev/null +++ b/packages/contracts/src/j5/fleet.ts @@ -0,0 +1,78 @@ +import * as Schema from "effect/Schema"; + +export const FLEET_DISPATCH_THRESHOLD_MS = 5 * 60 * 1000; + +const UnknownFact = Schema.Struct({ state: Schema.Literal("unknown"), reason: Schema.String }); + +export const FleetRuntimeFact = Schema.Union([ + UnknownFact, + Schema.Struct({ + state: Schema.Literal("known"), + status: Schema.Literals([ + "working", + "waiting", + "approval", + "input", + "failed", + "idle", + "waiting-to-start", + ]), + since: Schema.NullOr(Schema.String), + settled: Schema.Boolean, + }), +]); +export type FleetRuntimeFact = typeof FleetRuntimeFact.Type; + +const OpenAsk = Schema.Struct({ + exchangeId: Schema.String, + counterpartyId: Schema.String, + counterpartyName: Schema.NullOr(Schema.String), + intent: Schema.String, + openedAt: Schema.String, +}); + +export const FleetActivityFact = Schema.Union([ + UnknownFact, + Schema.Struct({ + state: Schema.Literal("known"), + label: Schema.String, + at: Schema.String, + }), +]); +export type FleetActivityFact = typeof FleetActivityFact.Type; + +export const FleetDeliveryProblem = Schema.Struct({ + kind: Schema.Literal("delivery-failed"), + messageId: Schema.String, + exchangeId: Schema.optionalKey(Schema.NullOr(Schema.String)), + receiverId: Schema.String, + receiverName: Schema.NullOr(Schema.String), + at: Schema.String, + reason: Schema.NullOr(Schema.String), + /** Closing the Exchange changes eligibility, not the delivery fact. */ + exchangeOpen: Schema.Boolean, +}); +export type FleetDeliveryProblem = typeof FleetDeliveryProblem.Type; + +export const FleetProblem = Schema.Union([ + Schema.Struct({ + kind: Schema.Literal("failed-run"), + runId: Schema.String, + at: Schema.NullOr(Schema.String), + }), + Schema.Struct({ + kind: Schema.Literal("dispatch-overdue"), + runId: Schema.String, + at: Schema.String, + }), + FleetDeliveryProblem, +]); +export type FleetProblem = typeof FleetProblem.Type; + +export const FleetAgentFacts = Schema.Struct({ + asks: Schema.Struct({ owed: Schema.Array(OpenAsk), awaited: Schema.Array(OpenAsk) }), + problems: Schema.Array(FleetProblem), + /** Remote receivers of this sender's open asks whose reads complete badge coverage. */ + deliveryEnvironmentIds: Schema.optionalKey(Schema.Array(Schema.String)), +}); +export type FleetAgentFacts = typeof FleetAgentFacts.Type; 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