diff --git a/FORK.md b/FORK.md index c095f397d260..515d65025071 100644 --- a/FORK.md +++ b/FORK.md @@ -93,7 +93,7 @@ Against upstream pin `d2c440312e5f39d59827ed466838a623516454d6`, the inventory h 4. The authenticated shared-toolkit integration proof: J5-owned `apps/server/src/j5/a2a/mcp/registration.test.ts`, test `production mcp layer lists worktree tools over http`. It asserts the exact production inventory, 82 tool names since the advance onto stable v0.1.3. Before it there were 99: the 79 from before the 2026-10-08 advance, the ten upstream tools admitted then (`html_preview`, `html_render`, `request_secret`, `preview_dialog`, `preview_hover`, `preview_select`, `preview_drag`, `preview_upload`, `watch_pull_request`, `unwatch_pull_request`; decision 7), the three admitted on 2026-10-11 (`t3_project_create`, `t3_project_update`, `t3_environment_preferences_update`; #519), less `t3_thread_send_attachments`, retired the same day, the three admitted on 2026-10-17 (`t3_workflow_stop`, `write_pull_request_guides`, `read_pull_request_guide`), J5's `j5_playbook_save`, added with the environment-wide playbook library ([#621](https://github.com/Jacksondr5/j5code/pull/621)), and the four queue tools admitted on 2026-10-24 (`t3_queue_edit`, `t3_queue_cancel`, `t3_queue_reorder`, `t3_queue_promote_to_steer`; #136). Upstream's merge of 18 tools into action tools (case 2) took out 22 names and brought in four (`t3_thread_transfer`, `t3_queue`, `t3_pending_request` and `preview_act`), and `t3_background_wait` is the fifth new name, admitted by Jackson on 2026-10-27 (case 2): 99 − 22 + 5 = 82. Upstream's registration asks for each tool's declared dependencies, so the test provides empty mocks of the J5 and upstream services those tools declare; listing tools never calls them. It also asserts the absence of `t3_thread_wait`, the raw thread-send, interrupt, launch and creation tools and `t3_project_delete`. Upstream deleted the file that held this test, `apps/server/src/mcp/toolkits/worktree/registration.test.ts`, at the 2026-10-24 advance (pingdotgg/t3code#22557), so the proof lives in J5's own file again. The upstream provider-adapter read-only-tool assertion derives its expectation from the upstream toolkit rather than the J5 production surface, so it is intentionally unchanged; this direct J5 exact-registration proof is the gate of record. Revisit that protected upstream read-only assertion only after an actual drift incident that this J5 proof fails to catch. 5. Shared J5 server composition: `apps/server/src/server.ts` appends only `j5AuthenticatedRoutesLayer` to `layerMakeRoutes`, after upstream's `Ws.layer`, provides `J5ThreadRegistrationLayer` once to the V2 runtime (`RuntimeLayer.layerProduction`) and `J5A2AAuxiliaryLayer` once around the combined HTTP/MCP graph. Both transport registrations consume that shared graph and must never create nested J5 runtimes. The aggregate in case 9 owns all J5 authenticated route additions, including the human inbox. Upstream's `http.ts` carries no J5 edit; the desktop renderer origins it allows come from `httpCors.ts`, a branding site (`BRANDING.md`). 6. A4's visible human-inbox navigation append: in `apps/web/src/components/sidebar/SidebarChrome.tsx`, `SidebarChromeHeader` mounts the J5-owned `HumanInboxBell` and `FleetRailEntry` in a trailing control group, after the brand and optional environment pill, and `SidebarBrandMark` renders the J5 wordmark (`BRANDING.md`). Back behavior moved with upstream: `isSidebarUtilityPage` in `apps/web/src/components/sidebar/mainAppLocation.ts` names `/inbox`, `/fleet` and `/artifacts` beside upstream's utility pages (since stable v0.1.3 those are project pages and Pull Requests, because Settings and Usage open as modals over the thread), so none of them becomes the remembered Back target. Upstream's `SidebarBrandWidthProbe` measures the brand and not J5's two rail icons. The route files `routes/inbox.tsx` and `routes/fleet.tsx`, the pages, the bell, the rail entry, and their clients remain under J5-owned files (`j5/a2a`, `j5/fleet`); Settings, Pull Requests, Usage, and Back behavior are unchanged. -7. J5's user-message seam (the A2A timeline design of 2026-10-24, register D38, which replaced D16 and retired the A2A cards): `apps/web/src/components/chat/TimelineUserMessageRow.tsx` imports J5-owned `renderThreadA2ADelivery`, `useJ5UserMessagePresentation` and `J5MessageAuthorLine` from `apps/web/src/j5/a2a/ThreadA2ARenderer.tsx`. `UserMessageRow` first calls `renderThreadA2ADelivery` with upstream's `formatDayAwareTimestamp` label and the participant labels, thread and markdown folder from `TimelineRowCtx` (case 24), and returns its answer when it is not null: J5's platform notices, which are Crew notices, a shared conversation's note (case 80), silence lines, and the raw card for a platform delivery no parser reads yet, kept until [#698](https://github.com/Jacksondr5/j5code/issues/698). In `UserTimelineRow`, `useJ5UserMessagePresentation(row.message)` replaces upstream's `resolveUserMessagePresentation`. It returns upstream's shape with the words without J5's envelope as `text`, and `"agent"` as the attribution of every participant who is not a person, so upstream's fold applies to agents, machine participants, outside agents, peers and spawn briefs; it adds `j5`, `literalContext`, `authorName`, `side` and `preview`. `resolvedContext` reads `userMessage.literalContext ?? resolveUserMessageContext(row.message)`, so a spawn brief's context is taken as written. The row is `items-start` when `userMessage.side === "left"`, as it already is for case 80's `sharedAuthor`. Case 80's author slot is ``: "You · via Inbox", another person's name with "· via Inbox", the participant identity line with its Exchange badge or tag, or else case 80's `SharedMessageAuthorLine`. The expanded row's footer shows J5-owned `J5OpenSenderThread` (the sender's resolved scoped thread, so a spawn brief or a peer's message gets Open thread) ahead of upstream's `senderThreadId` button. `MessageAuthorHeading` reads `sharedAuthor?.name ?? userMessage.authorName ?? "You"`. `FoldedMessageHeader` gets an empty `label` for a message J5 read (the name is on the identity line) and renders its label span only when the label is not empty; its `summary` is `userMessage.preview ?? foldSummary`. Classification and every envelope parser are J5-owned `packages/client-runtime/src/j5/userMessagePresentation.ts` and `crewNotices.ts`, so web and mobile share one parser, reached through the `./j5/user-message` and `./j5/crew-notices` exports this case appends to upstream-owned `packages/client-runtime/package.json`; `userMessagePresentation.test.ts` is the proof. Upstream's `MessagesTimeline.browser.test.tsx` mocks `useJ5UserMessagePresentation` with upstream's own presentation, because its tests cover upstream's row. Upstream's own thread sends, which carry no J5 envelope, are group 3 too: on the left, named from the sender thread's title. Groups 4 and 5 of the design (J5's notices as grey lines, and J5's look for upstream's platform prompts and Automation row) are not built yet ([#698](https://github.com/Jacksondr5/j5code/issues/698)). On a pin advance: if upstream reshapes the user row or its fold, keep the presentation swap, the context swap, the author slot, the side and the preview. +7. J5's user-message seam (the A2A timeline design of 2026-10-24, register D38, which replaced D16 and retired the A2A cards): `apps/web/src/components/chat/TimelineUserMessageRow.tsx` imports J5-owned `renderThreadA2ADelivery`, `useJ5UserMessagePresentation` and `J5MessageAuthorLine` from `apps/web/src/j5/a2a/ThreadA2ARenderer.tsx`. `UserMessageRow` first calls `renderThreadA2ADelivery` with upstream's `formatDayAwareTimestamp` label and the participant labels, thread and markdown folder from `TimelineRowCtx` (case 24), and returns its answer when it is not null: group 4, one grey line through J5-owned `apps/web/src/j5/a2a/J5NoticeLine.tsx` for every J5 notice the classifier has a summary for and every Crew notice, plus a shared conversation's note (case 80). A notice nothing can read returns null and is upstream's row. Upstream's own platform messages never reach this row: `notificationTurnItem` makes them notification items, and `MessagesTimeline.logic.ts` draws `/compact` as a compaction row, so J5 leaves those rows alone. Group 5 reuses upstream's `AutomationMessageRow` instead of a J5 copy, because it already has the fold, find, copy, steer marker, status and revert: `UserMessageRow` also sends a message to it when J5-owned `j5PromptRow(row.message)` is not null; in the row, `j5Prompt ?? resolveUserMessagePresentation(row.message)` gives `text` and `scheduledTaskId`, `j5Prompt?.summary` leads `summary`, and `j5Prompt?.label` and `j5Prompt?.icon` lead the heading, label and icon; and the row is `items-start` with `border border-border` in place of `items-end` and `bg-message text-message-foreground`, for upstream's automation runs too. A J5 prompt's pill is `w-full` while folded too, because the header caps its label at half the pill's width and J5's labels are long. In `UserTimelineRow`, `useJ5UserMessagePresentation(row.message)` replaces upstream's `resolveUserMessagePresentation`. It returns upstream's shape with the words without J5's envelope as `text`, and `"agent"` as the attribution of every participant who is not a person, so upstream's fold applies to agents, machine participants, outside agents, peers and spawn briefs; it adds `j5`, `literalContext`, `authorName`, `side` and `preview`. `resolvedContext` reads `userMessage.literalContext ?? resolveUserMessageContext(row.message)`, so a spawn brief's context is taken as written. The row is `items-start` when `userMessage.side === "left"`, as it already is for case 80's `sharedAuthor`. Case 80's author slot is ``: "You · via Inbox", another person's name with "· via Inbox", the participant identity line with its Exchange badge or tag, or else case 80's `SharedMessageAuthorLine`. The expanded row's footer shows J5-owned `J5OpenSenderThread` (the sender's resolved scoped thread, so a spawn brief or a peer's message gets Open thread) ahead of upstream's `senderThreadId` button. `MessageAuthorHeading` reads `sharedAuthor?.name ?? userMessage.authorName ?? "You"`. `FoldedMessageHeader` gets an empty `label` for a message J5 read (the name is on the identity line) and renders its label span only when the label is not empty; its `summary` is `userMessage.preview ?? foldSummary`. Classification and every envelope parser are J5-owned `packages/client-runtime/src/j5/userMessagePresentation.ts` and `crewNotices.ts`, with the wording of J5's notices and prompts read in `platformMessages.ts`, so web and mobile share one parser, reached through the `./j5/user-message` and `./j5/crew-notices` exports this case appends to upstream-owned `packages/client-runtime/package.json`; `userMessagePresentation.test.ts` is the proof. Upstream's `MessagesTimeline.browser.test.tsx` mocks `useJ5UserMessagePresentation` with upstream's own presentation, because its tests cover upstream's row. Upstream's own thread sends, which carry no J5 envelope, are group 3 too: on the left, named from the sender thread's title. On a pin advance: if upstream reshapes the user row or its fold, keep the presentation swap, the context swap, the author slot, the side and the preview; if it reshapes the Automation row, keep it drawing J5's prompts, on the left without a fill. 8. A2's provider steering seam. J5's standing instructions for agents live in J5-owned `packages/provider-core/src/j5/`: `orchestrationInstructions.ts` holds the text as sections of under 4,000 bytes each (`J5_ORCHESTRATION_SECTIONS`, joined as `J5_ORCHESTRATION_INSTRUCTIONS`), built from `agentInvocationInstructions.ts` (persona mentions) and `playbookInstructions.ts` (case 45). Upstream keeps its own text and helpers in `packages/provider-core/src/server/orchestrationInstructions.ts`. J5's one logic edit there (Jackson, 2026-10-09; on the sections since the 2026-10-24 advance, when upstream split its text into them) replaces upstream's literal sections with `export const T3_CODE_ORCHESTRATION_SECTIONS: ReadonlyArray = J5_ORCHESTRATION_SECTIONS`, and upstream's own line joins them into `T3_CODE_ORCHESTRATION_INSTRUCTIONS`, so upstream's helpers in that file and every consumer of either constant carry J5's text: Codex, Claude, Cursor, both OpenCode adapters, the ACP adapter, Pi's extension (`packages/provider-pi/src/server/mcpExtensionSource.ts`), and any provider upstream moves into a package later. Upstream's literal is deleted, not kept beside the alias, so an upstream edit to it conflicts in the merge instead of landing unseen in unused text. Since the advance onto stable v0.1.3 the file has a second alias of the same kind: `T3_CODE_ACP_MCP_FALLBACK_INSTRUCTIONS`, the terminal fallback upstream sends only to ACP harnesses, is J5-owned `J5_ACP_MCP_FALLBACK_INSTRUCTIONS`, which names the J5 tools and keeps the Peer Agent and Exchange rules in force over that transport. The file's other J5 edits are branding strings: the "J5 Code browser" heading and the ACP mode text. `Adapters/ClaudeAdapterV2.ts` and the package adapters (`packages/provider-acp/src/server/adapter.ts`, `packages/provider-cursor/src/server/adapter.ts`, and `packages/provider-opencode/src/server/adapter.ts` and `v2/adapter.ts`) import the package as upstream wrote them and carry no edit for this case. The package's `exports` map is unchanged, because nothing outside the package imports `src/j5`. A rebase that restores upstream's literal is a protected-seam regression. What the text says. It replaces upstream's delegated-task steering with three ways of working and two ways to get help (Bryant, 2026-10-27, #746; Jackson, 2026-10-31, kept an explicit request as the trigger). An explicit request for a Crew, a Peer Agent or a subagent gets that mechanism, and a requested crew goes through `j5_propose_crew` (the 2026-09-17 rule from Jackson's proposal on PR #148); a word mentioned in passing or in quoted text is not a request. When the person asked for none, the agent chooses from the work: work directly; use subagents for independent assignments; use a Crew for work whose workers must respond to each other. It may reassess mid-work without restarting completed work. Help comes two ways: create a subagent (the provider's native tool, or `delegate_task` across providers), or put members on a Crew (`j5_propose_crew` starts one, `j5_request_crew_member` grows one). `j5_spawn_agent` is described for a user's explicit request for a Peer Agent or standalone agent and for callers that already use it, and as not a way to get help when nobody asked; the spawn brief itself states the task and whether and what reply is expected. A follow-up `j5_send_message(..., expect_reply=true, intent="...")` opens an Exchange only for later work owed by an existing participant; it is never the second half of a spawn sequence. A Crew chosen but unavailable through `j5_propose_crew` is reported, not replaced by other agents. The text covers custom members, members' own review loops (findings go straight to the teammate who owns the work, the Captain hears only a review pass, a blocker, an unsettled disagreement, or the member's final result or step report), and direct additions with `j5_request_crew_member`. The same rules reach members through the `` block in J5-owned `apps/server/src/j5/a2a/spawnIds.ts`, and each tool description names the path it serves. No edit to the upstream file beyond the existing alias is needed for any of this. The Crew bullet says custom seats take the Captain's harness, model, and reasoning but run with full access unless `runtime_mode` is set (#326). The ratified SP4 brief sentence lives exactly once, in the J5 `j5_spawn_agent` Tool description; the steering restates the contract without duplicating that sentence. @@ -251,7 +251,7 @@ Upstream settings sections no longer accept a `description` prop; J5 library pan `apps/server/src/orchestration-v2/ThreadMessageIntake.ts` treats the J5 `resolve-agent-persona` launch refusal as pre-dispatch failure and releases claimed uploads; the pending upload remains available for retry. -Bryant requested a shared agent picker for Codex and Claude, invoking a saved agent as a subagent within the current conversation. This is a narrow exception to the earlier native-only Subagent steering: the child uses the existing delegated-child engine with `lineage.relationshipToParent = subagent`. Its child thread is backing storage, not a top-level Peer Agent. Ordinary native subagent requests and `j5_spawn_agent` retain their existing meanings; `j5_spawn_agent`'s optional `agent` input (2026-09-09) resolves a saved agent into a Peer Agent's immutable assignment entirely inside `apps/server/src/j5/agents/agentPersonaSpawn.ts` and the J5 toolkit handlers, with no further upstream hook. Proposal-driven Crews use ordinary conversation. The former `/crew` send-path wrapper in `ChatView.tsx` and slash-menu spread in `ChatComposer.tsx` are removed; case 8's standing instructions guide the agent to propose a roster, including custom members, and wait for the person's decision before launching. The platform's `` decisions render as notices through case 7's `renderThreadA2ADelivery` call: J5-owned `apps/web/src/j5/crew/CrewNoticeRenderer.tsx` draws them, the shared parser in `packages/client-runtime/src/j5/crewNotices.ts` recognizes the tagged blocks strictly (anything unparsed stays raw), and the call passes the thread and markdown folder from `TimelineRowCtx`, so a seat opens its thread and the brief renders as markdown (2026-09-16). Mobile has no delivery seam and shows these notices in upstream's rows, as it does A2A deliveries. `ChatView.tsx` passes J5-owned `CrewRosterGate` (`apps/web/src/j5/crew/CrewRosterGate.tsx`) through the existing `ChatComposer.threadProgressControl` slot alongside Playbooks. It uses upstream’s `ComposerBanner` attachment and expands from a compact strip above the Captain’s composer; Add/Edit member dialogs stay outside the composer’s focus flow. The slot is hidden while a blocking tool approval or question is open, so the proposal disappears meanwhile; the person's saved roster edits live in J5-owned `apps/web/src/j5/crew/crewProposalDraftStore.ts` (keyed by environment and proposal, cleared when the proposal is approved or declined) and are restored when the gate returns. Mid-run seat additions stay on the inbox bell (`crewProposals.logic.ts` decides which is which). The same fragment mounts J5-owned `AdjudicationDock` (`apps/web/src/j5/a2a/AdjudicationDock.tsx`) beside it: a Captain's open ask to the person, pinned above its composer, shown only for a thread that commands a Crew and answered with the Inbox's own command (#747). It changes nothing about what the composer does. The human gate (open proposals, approve with edited seats, decline) lives entirely in J5 files: `apps/web/src/j5/crew/`, the J5 inbox page and bell, and the list, preview and resolve RPCs (case 64). One adapter append makes the gate reachable from Claude: `claudeMcpQueryOverrides` in `apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts` spreads J5-owned `J5_CLAUDE_MCP_ALLOWED_TOOLS` (`apps/server/src/j5/a2a/mcp/claudeAllowedTools.ts`) into the read-only pre-approval list, because Claude runs read-only personas in `dontAsk` mode and would otherwise deny every J5 coordination tool; the upstream `CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS` constant and its toolkit cross-check stay untouched, and the two exact-allowlist assertions in `ClaudeAdapterV2.test.ts` include the J5 spread. The Codex counterpart is one spread in `codexThreadRuntimeParams` (`apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts`, private to that file since the 2026-10-24 advance): upstream's injected `"mcp_servers.t3-code"` entry gains J5-owned `J5_CODEX_T3_MCP_SERVER_CONFIG` (`apps/server/src/j5/a2a/mcp/codexToolApproval.ts`; since 2026-09-14 a per-tool `tools..approval_mode = "approve"` map naming the J5 verbs plus `j5_write_artifact` (a saved agent's declared handoff artifact lives in application storage, never the workspace) and, since 2026-09-15, the provider-native Subagent verbs `delegate_task`, `task_status`, and `task_cancel` (a Crew member refused `j5_spawn_agent` is sent there), never a server-wide default, so worktree handoff, browser preview, and scheduling keep Codex's own verdict for read-only personas), because Codex 0.153+ rejects every non-read-only MCP tool under approval policy `never` with "MCP tool call requires approval, but approval policy is never"; that policy is what full-access mode and every saved-agent runtime policy send, so without the spread `j5_send_message`, `j5_spawn_agent`, and `j5_propose_crew` all fail on Codex. The full spread applies when the thread's resolved approval policy is `never` (`j5ApprovalPolicyIsNever`). Since 2026-09-24 both appends draw their names from one J5 leaf module, `apps/server/src/j5/a2a/mcp/j5ToolPreapproval.ts` (`J5_PREAPPROVED_TOOLS`, the interactive-mode `J5_COORDINATION_TOOLS`, and `j5PreapprovedTools(runtimePolicy)`), so Codex and Claude, the two harnesses J5 pre-approves its tools on (Jackson's ruling on #233), pre-approve the same set. Interactive modes pre-approve only routine messaging and the crew proposal/request tools. Pre-approval is the Captain's own staffing decision: a roster waits for the person unless the project's Crew approval is automatic (#743), and a Captain's addition (`j5_request_crew_member`) is automatic. A member's access defaults to Full access unless the Captain sets one, so a Supervised Captain can start a Full-access custom member without review; Jackson accepted that (2026-10-31). The Agent Setup approval setting governs rosters only; additions are always automatic. Other tools retain Codex's prompting. The ten upstream tools admitted on 2026-10-08 (case 4) are not in J5's pre-approval lists; they keep each harness's own verdict, and upstream's Claude read-only list already carries `html_preview` and `html_render`. The expected thread config in `CodexAdapterV2.test.ts` includes the spread. +Bryant requested a shared agent picker for Codex and Claude, invoking a saved agent as a subagent within the current conversation. This is a narrow exception to the earlier native-only Subagent steering: the child uses the existing delegated-child engine with `lineage.relationshipToParent = subagent`. Its child thread is backing storage, not a top-level Peer Agent. Ordinary native subagent requests and `j5_spawn_agent` retain their existing meanings; `j5_spawn_agent`'s optional `agent` input (2026-09-09) resolves a saved agent into a Peer Agent's immutable assignment entirely inside `apps/server/src/j5/agents/agentPersonaSpawn.ts` and the J5 toolkit handlers, with no further upstream hook. Proposal-driven Crews use ordinary conversation. The former `/crew` send-path wrapper in `ChatView.tsx` and slash-menu spread in `ChatComposer.tsx` are removed; case 8's standing instructions guide the agent to propose a roster, including custom members, and wait for the person's decision before launching. The platform's `` decisions render as notices through case 7's `renderThreadA2ADelivery` call: J5-owned `apps/web/src/j5/crew/CrewNoticeRenderer.tsx` draws them, the shared parser in `packages/client-runtime/src/j5/crewNotices.ts` recognizes the tagged blocks strictly (anything unparsed is upstream's row), and the call passes the thread and markdown folder from `TimelineRowCtx`, so a seat opens its thread and the brief renders as markdown (2026-09-16). Mobile has no delivery seam and shows these notices in upstream's rows, as it does A2A deliveries. `ChatView.tsx` passes J5-owned `CrewRosterGate` (`apps/web/src/j5/crew/CrewRosterGate.tsx`) through the existing `ChatComposer.threadProgressControl` slot alongside Playbooks. It uses upstream’s `ComposerBanner` attachment and expands from a compact strip above the Captain’s composer; Add/Edit member dialogs stay outside the composer’s focus flow. The slot is hidden while a blocking tool approval or question is open, so the proposal disappears meanwhile; the person's saved roster edits live in J5-owned `apps/web/src/j5/crew/crewProposalDraftStore.ts` (keyed by environment and proposal, cleared when the proposal is approved or declined) and are restored when the gate returns. Mid-run seat additions stay on the inbox bell (`crewProposals.logic.ts` decides which is which). The same fragment mounts J5-owned `AdjudicationDock` (`apps/web/src/j5/a2a/AdjudicationDock.tsx`) beside it: a Captain's open ask to the person, pinned above its composer, shown only for a thread that commands a Crew and answered with the Inbox's own command (#747). It changes nothing about what the composer does. The human gate (open proposals, approve with edited seats, decline) lives entirely in J5 files: `apps/web/src/j5/crew/`, the J5 inbox page and bell, and the list, preview and resolve RPCs (case 64). One adapter append makes the gate reachable from Claude: `claudeMcpQueryOverrides` in `apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts` spreads J5-owned `J5_CLAUDE_MCP_ALLOWED_TOOLS` (`apps/server/src/j5/a2a/mcp/claudeAllowedTools.ts`) into the read-only pre-approval list, because Claude runs read-only personas in `dontAsk` mode and would otherwise deny every J5 coordination tool; the upstream `CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS` constant and its toolkit cross-check stay untouched, and the two exact-allowlist assertions in `ClaudeAdapterV2.test.ts` include the J5 spread. The Codex counterpart is one spread in `codexThreadRuntimeParams` (`apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts`, private to that file since the 2026-10-24 advance): upstream's injected `"mcp_servers.t3-code"` entry gains J5-owned `J5_CODEX_T3_MCP_SERVER_CONFIG` (`apps/server/src/j5/a2a/mcp/codexToolApproval.ts`; since 2026-09-14 a per-tool `tools..approval_mode = "approve"` map naming the J5 verbs plus `j5_write_artifact` (a saved agent's declared handoff artifact lives in application storage, never the workspace) and, since 2026-09-15, the provider-native Subagent verbs `delegate_task`, `task_status`, and `task_cancel` (a Crew member refused `j5_spawn_agent` is sent there), never a server-wide default, so worktree handoff, browser preview, and scheduling keep Codex's own verdict for read-only personas), because Codex 0.153+ rejects every non-read-only MCP tool under approval policy `never` with "MCP tool call requires approval, but approval policy is never"; that policy is what full-access mode and every saved-agent runtime policy send, so without the spread `j5_send_message`, `j5_spawn_agent`, and `j5_propose_crew` all fail on Codex. The full spread applies when the thread's resolved approval policy is `never` (`j5ApprovalPolicyIsNever`). Since 2026-09-24 both appends draw their names from one J5 leaf module, `apps/server/src/j5/a2a/mcp/j5ToolPreapproval.ts` (`J5_PREAPPROVED_TOOLS`, the interactive-mode `J5_COORDINATION_TOOLS`, and `j5PreapprovedTools(runtimePolicy)`), so Codex and Claude, the two harnesses J5 pre-approves its tools on (Jackson's ruling on #233), pre-approve the same set. Interactive modes pre-approve only routine messaging and the crew proposal/request tools. Pre-approval is the Captain's own staffing decision: a roster waits for the person unless the project's Crew approval is automatic (#743), and a Captain's addition (`j5_request_crew_member`) is automatic. A member's access defaults to Full access unless the Captain sets one, so a Supervised Captain can start a Full-access custom member without review; Jackson accepted that (2026-10-31). The Agent Setup approval setting governs rosters only; additions are always automatic. Other tools retain Codex's prompting. The ten upstream tools admitted on 2026-10-08 (case 4) are not in J5's pre-approval lists; they keep each harness's own verdict, and upstream's Claude read-only list already carries `html_preview` and `html_render`. The expected thread config in `CodexAdapterV2.test.ts` includes the spread. `packages/client-runtime/src/state/models.ts` accepts a status-only runtime in `threadRuntimeIsActive`; J5 crew state reuses that exported predicate without importing the upstream-private status helper. Preserve this narrow input contract when carrying crew reads forward. diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index 06e2e1110fae..2090791cf7cd 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -79,6 +79,7 @@ import { useSharedMessageAuthor } from "../../j5/sharing/sharedTimeline"; import { J5MessageAuthorLine, J5OpenSenderThread, + j5PromptRow, renderThreadA2ADelivery, useJ5UserMessagePresentation, } from "../../j5/a2a/ThreadA2ARenderer"; @@ -144,7 +145,8 @@ export function UserMessageRow({ row }: { row: Extract ctx.onOpenThread(ThreadId.make(threadId))} /> - ) : resolveUserMessagePresentation(row.message).attribution === "automation" ? ( + ) : resolveUserMessagePresentation(row.message).attribution === "automation" || + j5PromptRow(row.message) !== null ? ( ) : ( @@ -156,7 +158,9 @@ function AutomationMessageRow({ row }: { row: Extract setExpanded(true)); - const { text, scheduledTaskId } = resolveUserMessagePresentation(row.message); + // J5 (case 7): J5's platform prompts draw as this row, with their own label, title and words. + const j5Prompt = j5PromptRow(row.message); + const { text, scheduledTaskId } = j5Prompt ?? resolveUserMessagePresentation(row.message); const tasksQuery = useEnvironmentQuery( scheduledTaskId ? serverEnvironment.scheduledTasksLive({ @@ -166,7 +170,7 @@ function AutomationMessageRow({ row }: { row: Extract task.id === scheduledTaskId)?.title; - const summary = taskTitle ?? text.trim().split(/\r?\n/, 1)[0] ?? ""; + const summary = j5Prompt?.summary ?? taskTitle ?? text.trim().split(/\r?\n/, 1)[0] ?? ""; const revertTurnCount = row.revertTurnCount; const promptLink = promptLinkFor(text); @@ -174,21 +178,24 @@ function AutomationMessageRow({ row }: { row: Extract +
{row.message.inputIntent === "steer" || row.message.inputIntent === "promoted_queued_to_steer" ? ( ) : null}
- Automation + {j5Prompt?.label ?? "Automation"} setExpanded((value) => !value)} diff --git a/apps/web/src/j5/a2a/J5NoticeLine.browser.test.tsx b/apps/web/src/j5/a2a/J5NoticeLine.browser.test.tsx new file mode 100644 index 000000000000..e714f5d7c65b --- /dev/null +++ b/apps/web/src/j5/a2a/J5NoticeLine.browser.test.tsx @@ -0,0 +1,117 @@ +import { MessageId } from "@t3tools/contracts"; +import { expect, it } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; + +import type { ChatMessage } from "~/types"; + +import { render } from "../../../test/render"; +import { TimelineRowCtx } from "../../components/chat/timelineRowContext"; +import { renderThreadA2ADelivery } from "./ThreadA2ARenderer"; + +const CREATED_AT = "2026-10-31T12:00:00.000Z"; +const notice = (id: string, text: string, input: Partial = {}): ChatMessage => ({ + id: MessageId.make(id), + role: "user", + text, + runId: null, + streaming: false, + createdBy: "system", + creationSource: "server", + createdAt: CREATED_AT, + updatedAt: CREATED_AT, + ...input, +}); + +const notDelivered = notice( + "message:j5:a2a:delivery:one", + [ + "[Cross-agent messaging system notice: message not delivered]", + "Your message m1 to agent:peer was not delivered: delivery failed 3 times", + "This is a platform-authored notice, not a peer reply.", + ].join("\n\n"), +); + +const rowContext = (findActive = false) => + ({ + findActive, + participantLabels: new Map([["agent:peer", "Builder"]]), + skills: [], + threadRef: null, + markdownCwd: undefined, + }) as never; + +it("folds a notice to one named line and opens to its detail", async () => { + await using screen = await render( + + {renderThreadA2ADelivery({ message: notDelivered, timestampLabel: "8:00 AM" })} + , + ); + const line = screen.getByRole("button", { name: /Message to Builder not delivered/ }); + await expect.element(line).toHaveAttribute("aria-expanded", "false"); + await expect.element(screen.getByText("8:00 AM")).toBeVisible(); + expect(screen.container.textContent).not.toContain("agent:peer"); + expect(screen.container.textContent).not.toContain("Cross-agent"); + expect(screen.container.textContent).not.toContain("delivery failed"); + + await userEvent.click(line); + await expect.element(screen.getByText(/Delivery failed 3 times/)).toBeVisible(); +}); + +it("opens a folded notice when find matches its detail", async () => { + await using screen = await render( + + {renderThreadA2ADelivery({ message: notDelivered })} + , + ); + const line = screen.getByRole("button", { name: /Message to Builder not delivered/ }); + const detail = screen.container.querySelector("[data-j5-notice-detail]")!; + expect(detail.hidden).toBe(true); + expect(detail.querySelector("[data-thread-find-text]")?.textContent).toContain("Delivery failed"); + + detail.dispatchEvent(new Event("beforematch")); + await expect.element(line).toHaveAttribute("aria-expanded", "true"); +}); + +it("draws a seat in trouble with its tone, opening to the error", async () => { + const report = [ + "", + "proposal_id: p1", + "kind: addition", + "decision: approved", + "crew_name: Comedy", + "seat_failed: punchline | failed | provider_error", + "seat_pending: prosecutor", + "roster:", + "- punchline: participant_id=agent:p persona=advocate thread_id=thread:p start=failed", + "- prosecutor: participant_id=agent:q persona=critic thread_id=thread:q start=pending", + "", + ].join("\n"); + await using screen = await render( + + {renderThreadA2ADelivery({ message: notice("message:crew", report) })} + , + ); + await expect.element(screen.getByText("punchline couldn't start")).toBeVisible(); + await expect.element(screen.getByText("prosecutor hasn't confirmed it started")).toBeVisible(); + expect( + [...screen.container.querySelectorAll("[data-j5-notice-tone]")].map((icon) => + icon.getAttribute("data-j5-notice-tone"), + ), + ).toEqual(["bad", "warn"]); + await userEvent.click(screen.getByRole("button", { name: /punchline couldn't start/ })); + await expect.element(screen.getByText("provider_error")).toBeVisible(); +}); + +it("draws a declined roster as one line", async () => { + const declined = + "\nproposal_id: p2\nkind: roster\ndecision: declined\ndecided_by: Priya\ncrew_name: Comedy\nrequested_seats: setup=scout\n\n\nThe user declined this crew request."; + await using screen = await render( + + {renderThreadA2ADelivery({ message: notice("message:crew", declined) })} + , + ); + await userEvent.click( + screen.getByRole("button", { name: /Crew Comedy · roster declined by Priya/ }), + ); + await expect.element(screen.getByText(/Requested: setup \(scout\)/)).toBeVisible(); +}); diff --git a/apps/web/src/j5/a2a/J5NoticeLine.tsx b/apps/web/src/j5/a2a/J5NoticeLine.tsx new file mode 100644 index 000000000000..9c181d5940d1 --- /dev/null +++ b/apps/web/src/j5/a2a/J5NoticeLine.tsx @@ -0,0 +1,146 @@ +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import { ChevronDownIcon, type LucideIcon } from "lucide-react"; +import { use, useState, type ReactNode } from "react"; + +import ChatMarkdown from "../../components/ChatMarkdown"; +import { findRevealRef } from "../../components/chat/markdownFindContext"; +import { MESSAGE_HEADING_LEVEL } from "../../components/chat/TimelineRowParts"; +import { TimelineRowCtx } from "../../components/chat/timelineRowContext"; +import { InlineButton } from "../../components/ui/button"; +import { cn } from "../../lib/utils"; +import { buildThreadRouteParams } from "../../threadRoutes"; + +const TONE_CLASS = { + bad: "text-destructive", + warn: "text-warning", + none: "", +} as const; + +/** + * A platform notice (group 4): one grey line on the left, with an icon, a plain summary, the time + * and, when there is something to open, a chevron. Opened, its detail hangs under a thin rule. + */ +export function J5NoticeLine(props: { + /** Which notice this is, for finding the row in tests and captures. */ + readonly kind: string; + readonly icon: LucideIcon; + readonly tone?: keyof typeof TONE_CLASS; + readonly summary: string; + readonly timestampLabel?: string | undefined; + readonly children?: ReactNode; +}) { + const { findActive } = use(TimelineRowCtx); + const [expanded, setExpanded] = useState(false); + const revealRef = findRevealRef(() => setExpanded(true)); + const Icon = props.icon; + const hasDetail = props.children !== undefined && props.children !== null; + const content = ( + <> + + {/* Find can only show a match in a summary that isn't cut off. */} + + {props.summary} + + {props.timestampLabel ? ( + + {props.timestampLabel} + + ) : null} + + ); + const lineClass = "flex min-w-0 max-w-full items-center gap-1.5 py-0.5 text-left"; + return ( +
+ {hasDetail ? ( + + ) : ( +
{content}
+ )} + {/* Find reads the DOM, so a folded detail stays mounted but hidden while find is open. */} + {hasDetail && (expanded || findActive) ? ( + + ) : null} +
+ ); +} + +/** A notice's words, as markdown so a link or a list in them reads as one. */ +export function J5NoticeDetailText({ text }: { readonly text: string }) { + const ctx = use(TimelineRowCtx); + return ( +
+ +
+ ); +} + +/** The row of things a notice opens, under its words. */ +export function J5NoticeActions({ children }: { readonly children: ReactNode }) { + return ( +
+ {children} +
+ ); +} + +export function J5OpenThread({ + threadRef, + label = "Open thread", +}: { + readonly threadRef: ScopedThreadRef; + readonly label?: string; +}) { + const navigate = useNavigate(); + return ( + + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(threadRef), + }) + } + tone="muted" + > + {label} + + ); +} diff --git a/apps/web/src/j5/a2a/ThreadA2ARenderer.test.tsx b/apps/web/src/j5/a2a/ThreadA2ARenderer.test.tsx index cb71e5b24392..be59d22da45f 100644 --- a/apps/web/src/j5/a2a/ThreadA2ARenderer.test.tsx +++ b/apps/web/src/j5/a2a/ThreadA2ARenderer.test.tsx @@ -1,5 +1,4 @@ import { MessageId } from "@t3tools/contracts"; -import { renderToStaticMarkup } from "react-dom/server"; import { describe, expect, it } from "vite-plus/test"; import { presentJ5UserMessage } from "@t3tools/client-runtime/j5/user-message"; @@ -12,11 +11,11 @@ import { literalUserMessageContext, participantIdsForThreadA2ADelivery, participantIdsForThreadA2AEnvelope, + j5PromptRow, renderThreadA2ADelivery, } from "./ThreadA2ARenderer"; const CREATED_AT = "2026-08-29T12:00:00.000Z"; -const TIMESTAMP_LABEL = "Today, 8:00 AM"; const deliveryId = (suffix: string) => MessageId.make(`${J5_A2A_DELIVERY_MESSAGE_PREFIX}${suffix}`); function message(input: Partial = {}): ChatMessage { @@ -58,6 +57,9 @@ const silenceRaw = [ "This is a platform-authored delivery signal, not a peer reply.", ].join("\n"); +const systemNotice = (text: string, id = deliveryId("notice")) => + message({ id, createdBy: "system", creationSource: "server", text }); + const machineRaw = [ "[Message from automation machine:watchdog in project project-monitoring (Monitoring)]", "", @@ -75,28 +77,8 @@ const outsideAgentRaw = [ ].join("\n"); describe("renderThreadA2ADelivery", () => { - it("draws a silence notice as a muted line with its summary and the timeline's time", () => { - const markup = renderToStaticMarkup( - renderThreadA2ADelivery({ - message: message({ id: deliveryId("silence"), createdBy: "system", text: silenceRaw }), - timestampLabel: TIMESTAMP_LABEL, - }), - ); - const summary = markup.match(/(.*?)<\/span>/)?.[1]; - expect(summary).toContain("agent:counterpart's turn ended without replying"); - expect(summary).toContain(TIMESTAMP_LABEL); - expect(summary).not.toContain("turn-ended-no-reply"); - }); - - it("keeps the raw card for a platform notice it cannot read yet", () => { - const raw = silenceRaw.replace("turn-ended-no-reply", "future-detector-v7"); - const markup = renderToStaticMarkup( - renderThreadA2ADelivery({ - message: message({ id: deliveryId("future"), createdBy: "system", text: raw }), - }), - ); - expect(markup).toContain('data-j5-a2a-renderer="raw"'); - expect(markup).toContain("future-detector-v7"); + it("draws a notice the classifier has a summary for", () => { + expect(renderThreadA2ADelivery({ message: systemNotice(silenceRaw) })).not.toBeNull(); }); it.each([ @@ -110,11 +92,47 @@ describe("renderThreadA2ADelivery", () => { "a message that is not a delivery", message({ id: MessageId.make("message:mcp:session:thread-send:1"), text: peerPlainRaw }), ], + [ + "a platform notice nothing reads yet", + systemNotice(silenceRaw.replace("turn-ended-no-reply", "future-detector-v7")), + ], + [ + "a system message nothing reads yet", + systemNotice("Future words.", MessageId.make("message:future")), + ], ])("leaves %s to upstream's row", (_name, source) => { expect(renderThreadA2ADelivery({ message: source })).toBeNull(); }); }); +describe("j5PromptRow", () => { + it("gives upstream's Automation row J5's label, title and words, not the envelope", () => { + const step = [ + "", + "step: build | Build the fix", + "position: 2 of 5", + "", + "", + "Build it.", + "", + "Do this step now.", + ].join("\n"); + expect(j5PromptRow(systemNotice(step, MessageId.make("message:step")))).toMatchObject({ + label: "Playbook step 2 of 5", + summary: "Build the fix", + text: "Build it.", + scheduledTaskId: undefined, + }); + }); + + it("leaves an automation run and every other message alone", () => { + expect( + j5PromptRow(message({ id: MessageId.make("message:1"), scheduledTaskId: "t" as never })), + ).toBeNull(); + expect(j5PromptRow(message({ text: peerPlainRaw }))).toBeNull(); + }); +}); + describe("queued deliveries", () => { it("label each sender's first line, with the id to hover until the identity read names it", () => { expect( diff --git a/apps/web/src/j5/a2a/ThreadA2ARenderer.tsx b/apps/web/src/j5/a2a/ThreadA2ARenderer.tsx index 73b35b4d1c1f..1e2e0832b00f 100644 --- a/apps/web/src/j5/a2a/ThreadA2ARenderer.tsx +++ b/apps/web/src/j5/a2a/ThreadA2ARenderer.tsx @@ -1,33 +1,47 @@ import { j5MessageAuthorName, j5SenderThreadRef, + nameJ5NoticeParticipants, } from "@t3tools/client-runtime/j5/participant-identity"; import { - isJ5DeliveryMessage, participantIdsForJ5UserMessage, presentJ5UserMessage, resolveJ5UserMessagePresentation, + type J5NoticeKind, + type J5PromptKind, + type J5UserMessagePresentation, } from "@t3tools/client-runtime/j5/user-message"; import type { ScopedThreadRef } from "@t3tools/contracts"; -import { Link, useNavigate } from "@tanstack/react-router"; -import { BotIcon } from "lucide-react"; +import { Link } from "@tanstack/react-router"; +import { + BellIcon, + BotIcon, + CircleHelpIcon, + ListChecksIcon, + type LucideIcon, + MailWarningIcon, + MessageCircleOffIcon, + UndoIcon, + UnlinkIcon, +} from "lucide-react"; import { use, type ReactNode } from "react"; import { TimelineRowCtx } from "../../components/chat/timelineRowContext"; import { Badge } from "../../components/ui/badge"; -import { InlineButton } from "../../components/ui/button"; import { useQuietThreadShell } from "../../state/entities"; import { buildThreadRouteParams } from "../../threadRoutes"; import type { ResolvedUserMessageContext } from "~/lib/composerContextRecords"; import type { ChatMessage } from "~/types"; import { renderCrewNotice } from "../crew/CrewNoticeRenderer"; import { useConnectionAccess } from "../sharing/access"; +import { J5NoticeDetailText, J5NoticeLine } from "./J5NoticeLine"; import { PersonAvatar } from "../sharing/PersonAvatar"; import { renderSharedConversationNote, SharedMessageAuthorLine, } from "../sharing/SharedConversationCards"; +export { J5OpenThread as J5OpenSenderThread } from "./J5NoticeLine"; export { J5_A2A_DELIVERY_MESSAGE_PREFIX } from "@t3tools/client-runtime/j5/user-message"; export { formatJ5QueuedDelivery as formatThreadA2AQueuedDelivery, @@ -52,54 +66,68 @@ export function participantIdsForThreadA2ADelivery(message: ChatMessage): Readon return participantIdsForJ5UserMessage(message); } -function RawEnvelopeExpander({ rawEnvelope }: { readonly rawEnvelope: string }) { +const NOTICE_ICONS: Partial> = { + silence: MessageCircleOffIcon, + "not-delivered": MailWarningIcon, + "exchange-dropped": UnlinkIcon, + "exchange-withdrawn": UndoIcon, +}; + +function J5PlatformNotice(props: { + readonly notice: Extract; + readonly timestampLabel: string | undefined; +}) { + const { participantLabels } = use(TimelineRowCtx); + const { notice } = props; + const named = (text: string) => + nameJ5NoticeParticipants(text, notice.participantIds, participantLabels); return ( -
- - Show raw envelope - -
-        {rawEnvelope}
-      
-
+ + {notice.detail === null ? null : } + ); } /** * J5's platform notices (group 4), drawn in place of upstream's user row: Crew notices, a shared - * conversation's note, and the platform's notices about deliveries. Every other user message, - * agents' letters and Inbox replies included, is upstream's row (`useJ5UserMessagePresentation`). + * conversation's note, and any notice the classifier has a summary for. Every other user message is + * upstream's row, including a notice nothing here can read. Upstream's own platform messages never + * get here: they are its notification and compaction rows. */ export function renderThreadA2ADelivery(props: ThreadA2ADeliveryCompositionInput): ReactNode { const crewNotice = renderCrewNotice(props); if (crewNotice !== null) return crewNotice; const sharedNote = renderSharedConversationNote(props); if (sharedNote !== null) return sharedNote; - if (!isJ5DeliveryMessage(props.message) || props.message.createdBy !== "system") return null; - const presentation = presentJ5UserMessage(props.message); - if (presentation?.group === "notice" && presentation.kind === "silence") { - return ( -
- - ⚠ {presentation.summary} - {props.timestampLabel ? ` · ${props.timestampLabel}` : null} - -
- ); - } + if (presentation?.group !== "notice" || presentation.summary === null) return null; + return ; +} - // A platform notice this client cannot read yet keeps today's raw card until the notices are - // redrawn: upstream's row would draw it as the reader's own message. - return ( -
-

Raw A2A delivery

- -
- ); +const PROMPT_ICONS: Record, LucideIcon> = { + "playbook-step": ListChecksIcon, + "native-question": CircleHelpIcon, +}; + +/** + * What upstream's Automation row shows for J5's other platform prompts (group 5). Null for anything + * else, an automation run included: that row reads its own. + */ +export function j5PromptRow(message: ChatMessage) { + const j5 = presentJ5UserMessage(message); + if (j5?.group !== "prompt" || j5.kind === "automation") return null; + return { + text: j5.text, + scheduledTaskId: undefined, + label: j5.label, + summary: j5.preview, + icon: PROMPT_ICONS[j5.kind], + }; } export function literalUserMessageContext(text: string): ResolvedUserMessageContext { @@ -139,7 +167,8 @@ export function useJ5UserMessagePresentation(message: ChatMessage) { literalContext, authorName, senderThreadRef: senderThread === null ? null : senderThreadRef, - side: j5?.side ?? "right", + // The platform's words are never the reader's, even in a notice nothing here can read. + side: j5?.side ?? (message.createdBy === "system" ? "left" : "right"), // Upstream's own fold summary reads a message J5 did not unwrap. preview: j5?.group === "participant" && j5.unwrapped ? j5.preview : null, }; @@ -228,24 +257,3 @@ export function J5MessageAuthorLine({

); } - -/** - * The expanded row's "Open thread" for a message J5 read. It opens the sender's resolved thread, - * which upstream's footer cannot reach for a spawn brief or a peer's message (no `senderThreadId`). - */ -export function J5OpenSenderThread({ threadRef }: { readonly threadRef: ScopedThreadRef }) { - const navigate = useNavigate(); - return ( - - void navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(threadRef), - }) - } - tone="muted" - > - Open thread - - ); -} diff --git a/apps/web/src/j5/a2a/timelineRows.test.ts b/apps/web/src/j5/a2a/timelineRows.test.ts new file mode 100644 index 000000000000..ca5f20560d32 --- /dev/null +++ b/apps/web/src/j5/a2a/timelineRows.test.ts @@ -0,0 +1,186 @@ +import { + MessageId, + RunId, + ScheduledTaskId, + ThreadId, + TurnItemId, + type OrchestrationV2TurnItem, +} from "@t3tools/contracts"; +import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message"; +import * as DateTime from "effect/DateTime"; +import { describe, expect, it } from "vite-plus/test"; + +import { deriveMessagesTimelineRows } from "../../components/chat/MessagesTimeline.logic"; +import { deriveTimelineEntriesFromVisibleTurnItems } from "../../session-logic"; +import { + J5_A2A_DELIVERY_MESSAGE_PREFIX, + j5PromptRow, + renderThreadA2ADelivery, +} from "./ThreadA2ARenderer"; + +// The classifier and renderer only matter for what reaches a message row, so each kind goes through +// the timeline's own derivation from the turn item the server stores for it. +const now = DateTime.makeUnsafe("2026-11-02T00:00:00.000Z"); +const base = { + id: TurnItemId.make("item"), + threadId: ThreadId.make("thread-1"), + runId: RunId.make("run-1"), + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + status: "completed" as const, + title: null, + startedAt: now, + completedAt: now, + updatedAt: now, +}; + +const userMessage = ( + id: string, + text: string, + fields: Partial> = {}, +): OrchestrationV2TurnItem => ({ + ...base, + type: "user_message", + messageId: MessageId.make(id), + inputIntent: "turn_start", + text, + attachments: [], + createdBy: "system", + creationSource: "server", + ...fields, +}); + +const delivery = (text: string) => + userMessage(`${J5_A2A_DELIVERY_MESSAGE_PREFIX}notice`, text, { creationSource: "mcp" }); + +const rowsFor = (item: OrchestrationV2TurnItem) => + deriveMessagesTimelineRows({ + timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({ + visibleTurnItems: [ + { + position: 0, + visibility: "local", + sourceThreadId: item.threadId, + sourceItemId: item.id, + item, + }, + ], + optimisticMessages: [], + }), + isWorking: false, + turnDiffSummaries: [], + supportsConversationRollback: false, + }); + +const messageRow = (item: OrchestrationV2TurnItem) => { + const row = rowsFor(item).find((candidate) => candidate.kind === "message"); + if (row?.kind !== "message") throw new Error("Expected a message row"); + return row.message; +}; + +const terminalFooter = "This is a platform-authored terminal notice, not a peer reply."; + +describe("what reaches a J5 row", () => { + it.each([ + [ + "a silence", + delivery( + "[Cross-agent messaging system notice: turn-ended-no-reply]\n\nagent:b's turn ended without replying on exchange:1. The latest delivered message was processed.\n\nThis is a platform-authored delivery signal, not a peer reply.", + ), + ], + [ + "a queued message removed", + delivery( + "[Cross-agent messaging system notice: queued-message-removed]\n\nYour message m1 to agent:b was removed from its queue before it ran, so agent:b never read it. Send it again if it still matters. The message began: Hi\n\nThis is a platform-authored delivery signal, not a peer reply.", + ), + ], + [ + "a message not delivered", + delivery( + "[Cross-agent messaging system notice: message not delivered]\n\nYour message m1 to agent:b was not delivered: gone\n\nThis is a platform-authored notice, not a peer reply.", + ), + ], + [ + "a dropped Exchange", + delivery( + `[Cross-agent messaging system notice: exchange dropped]\n\nExchange e1 ended because agent:b was archived (receiver-retired).\n\nFacts: replyRequired=false.\n\n${terminalFooter}`, + ), + ], + [ + "a withdrawn ask", + delivery( + `[Cross-agent messaging system notice: exchange withdrawn]\n\nExchange e1 was withdrawn by agent:b, who no longer needs an answer.\n\n${terminalFooter}`, + ), + ], + [ + "a handoff reminder", + userMessage("agent-handoff-nudge:run-1", "Your run ended without the declared handoff."), + ], + [ + "a declined roster", + userMessage( + "message:crew", + "\nproposal_id: p\nkind: roster\ndecision: declined\ncrew_name: C\n", + ), + ], + ])("draws %s as a notice line", (_name, item) => { + expect(renderThreadA2ADelivery({ message: messageRow(item) })).not.toBeNull(); + }); + + it.each([ + [ + "a playbook step", + userMessage( + "message:j5:a2a:mcp:j5-playbook-step:playbook-step:run", + "\nstep: a | Build\nposition: 1 of 2\n\n\nBuild it.\n\nDo this step now.", + ), + ], + [ + "a native question", + userMessage( + "message:j5:native-question:parent:request", + "Placed agent (threadId t, requestId r) asked a native question and can continue working. Read it with t3_pending_request.", + ), + ], + ])("draws %s as a pill", (_name, item) => { + expect(j5PromptRow(messageRow(item))).not.toBeNull(); + }); + + it("draws an automation run on upstream's row", () => { + const message = messageRow( + userMessage("scheduled-task-message:task:1:scheduled", "Run the nightly check.", { + createdBy: "agent", + creationSource: "mcp", + scheduledTaskId: ScheduledTaskId.make("task"), + }), + ); + expect(resolveUserMessagePresentation(message).attribution).toBe("automation"); + }); +}); + +describe("what upstream keeps on its own rows", () => { + it("draws a message the server made a notification as a work row, not a message", () => { + const rows = rowsFor({ + ...base, + type: "notification", + source: { kind: "monitor" }, + outcome: "updated", + summary: "#912: new comments", + } as OrchestrationV2TurnItem); + expect(rows.map((row) => row.kind)).toEqual(["work"]); + }); + + it("draws idle compaction as a compaction row, not a message", () => { + const rows = rowsFor( + userMessage("idle-compact:thread-1:run-1", "/compact", { + createdBy: "agent", + idleCompaction: "beforeCacheExpires", + }), + ); + expect(rows.some((row) => row.kind === "message")).toBe(false); + }); +}); diff --git a/apps/web/src/j5/crew/CrewContextCard.browser.test.tsx b/apps/web/src/j5/crew/CrewContextCard.browser.test.tsx index ab75e5255bf4..edd9f6e85d14 100644 --- a/apps/web/src/j5/crew/CrewContextCard.browser.test.tsx +++ b/apps/web/src/j5/crew/CrewContextCard.browser.test.tsx @@ -5,6 +5,7 @@ import { userEvent } from "vite-plus/test/browser"; import type { ChatMessage } from "~/types"; import { render } from "../../../test/render"; +import { TimelineRowCtx } from "../../components/chat/timelineRowContext"; import { renderThreadA2ADelivery } from "../a2a/ThreadA2ARenderer"; const CREATED_AT = "2026-10-31T12:00:00.000Z"; @@ -21,31 +22,30 @@ const message = (text: string): ChatMessage => ({ }); const context = (text: string) => `\n${text}\n`; +const rowContext = { findActive: false, participantLabels: new Map() } as never; it("shows the introduction folded to its title and opens to the text the model read", async () => { await using screen = await render( - <> + {renderThreadA2ADelivery({ message: message(context("\nYou are the reviewer.\n")), timestampLabel: "Today, 8:00 AM", })} - , + , { router: false }, ); - const card = screen.container.querySelector( - "details[data-j5-crew-context='introduction']", - )!; - await expect.element(screen.getByText("Introduction")).toBeVisible(); - expect(card.open).toBe(false); + const line = screen.getByRole("button", { name: /Introduction from J5/ }); + await expect.element(line).toHaveAttribute("aria-expanded", "false"); + expect(screen.container.textContent).not.toContain("You are the reviewer."); - await userEvent.click(screen.getByText("Introduction")); - expect(card.open).toBe(true); + await userEvent.click(line); + await expect.element(line).toHaveAttribute("aria-expanded", "true"); await expect.element(screen.getByText(/You are the reviewer\./)).toBeVisible(); }); -it("titles a roster change as its own card", async () => { +it("titles a roster change as its own line", async () => { await using screen = await render( - <> + {renderThreadA2ADelivery({ message: message( context( @@ -53,9 +53,11 @@ it("titles a roster change as its own card", async () => { ), ), })} - , + , { router: false }, ); - await expect.element(screen.getByText("Roster changed")).toBeVisible(); - expect(screen.container.querySelector("[data-j5-crew-context='roster-changed']")).not.toBeNull(); + await expect.element(screen.getByText("Roster changed from J5")).toBeVisible(); + expect( + screen.container.querySelector("[data-j5-notice='crew-context-roster-changed']"), + ).not.toBeNull(); }); diff --git a/apps/web/src/j5/crew/CrewNoticeRenderer.tsx b/apps/web/src/j5/crew/CrewNoticeRenderer.tsx index 7ce23599227f..8ce98ea6bec8 100644 --- a/apps/web/src/j5/crew/CrewNoticeRenderer.tsx +++ b/apps/web/src/j5/crew/CrewNoticeRenderer.tsx @@ -1,25 +1,25 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; -import { useNavigate } from "@tanstack/react-router"; -import { ChevronRightIcon, UsersIcon } from "lucide-react"; +import { CircleAlertIcon, TriangleAlertIcon, UsersIcon } from "lucide-react"; import type { ReactNode } from "react"; -import { cn } from "../../lib/utils"; -import { buildThreadRouteParams } from "../../threadRoutes"; import { + crewApprovalSummary, + crewDeclinedSummary, + crewNoticeLines, presentCrewContext, presentCrewNotice, - type CrewContextNotice, + type CrewNoticeLine, type CrewNoticeMessage, type CrewNoticePresentation, } from "@t3tools/client-runtime/j5/crew-notices"; import { - crewApprovalSummary, - crewGateTitle, - crewNoticeLines, - type CrewNoticeLine, -} from "./crewNotices.logic"; + J5NoticeActions, + J5NoticeDetailText, + J5NoticeLine, + J5OpenThread, +} from "../a2a/J5NoticeLine"; export interface CrewNoticeRenderInput { readonly message: CrewNoticeMessage & { @@ -32,180 +32,125 @@ export interface CrewNoticeRenderInput { readonly markdownCwd?: string | undefined; } -/** - * What the platform told this member with an assignment, folded to its title: the text is the - * model's own reading, long and not written for the person, so it opens on request. - */ -function CrewContextCard(props: { - readonly notice: CrewContextNotice; +const seatRef = (input: CrewNoticeRenderInput, threadId: string | null) => + threadId === null || !input.threadRef + ? null + : scopeThreadRef(input.threadRef.environmentId, ThreadId.make(threadId)); + +/** One seat that needs the person. A seat whose thread was never created has no link. */ +function CrewSeatLine(props: { + readonly line: CrewNoticeLine; readonly input: CrewNoticeRenderInput; }) { - const { notice, input } = props; + const { line, input } = props; + const threadRef = seatRef(input, line.threadId); + const summary = [line.crewName, line.seat, line.reason].filter(Boolean).join(" "); return ( -
- - - - {notice.title} - from J5 - {input.timestampLabel ? ( - - ) : null} - -
-        {notice.text}
-      
-
+ {line.detail === null && threadRef === null ? null : ( + <> + {line.detail === null ? null : } + {threadRef === null ? null : ( + + + + )} + + )} + ); } -/** A declined request as the Captain received it: what was asked for, and who declined it. */ -function CrewDeclinedCard(props: { +function CrewApprovedLine(props: { + readonly summary: string; readonly notice: Extract; readonly input: CrewNoticeRenderInput; }) { const { notice, input } = props; return ( -
-
- - - {crewGateTitle(notice)} - - {notice.crewName !== null ? ( - {notice.crewName} - ) : null} - {notice.decidedBy !== null ? ( - · by {notice.decidedBy} - ) : null} - - Declined - - {input.timestampLabel ? ( - - ) : null} -
- {notice.requestedSeats.length > 0 ? ( -

- Requested:{" "} - {notice.requestedSeats.map((seat) => `${seat.seat} (${seat.agentId})`).join(", ")} -

- ) : null} -

- The Captain can revise the request and propose again. -

-
- ); -} - -/** - * The seats a notice says need the person, one line each. A line opens its seat's thread; a seat - * whose thread was never created is named without a link. - */ -function CrewNoticeLines(props: { - readonly lines: ReadonlyArray; - readonly input: CrewNoticeRenderInput; -}) { - const navigate = useNavigate(); - const environmentId = props.input.threadRef?.environmentId; - return ( -
    - {props.lines.map((line, index) => { - const content = ( - <> - - {line.crewName === null ? null : {line.crewName}} - {line.seat} - {line.reason} - - ); - const className = cn( - "flex w-full min-w-0 items-start gap-2 rounded-md px-1.5 py-1 text-left", - line.tone === "bad" ? "text-destructive-foreground" : "text-warning-foreground", - ); - const threadId = line.threadId; - // A folded notice can carry one seat twice (it failed, was messaged, failed again). - return ( - // oxlint-disable-next-line react/no-array-index-key -- a folded notice can repeat a seat with the same reason, so no field is unique. -
  • - {threadId === null || environmentId === undefined ? ( -
    {content}
    - ) : ( - - )} -
  • - ); - })} -
+ {notice.changes === null ? null : ( + + )} + + {notice.roster.map((seat) => { + const threadRef = seatRef(input, seat.threadId); + return threadRef === null ? ( + {seat.seat} + ) : ( + + ); + })} + + ); } /** * Null for anything that is not a Crew notice; the caller then falls through to its own rendering. - * Approval summaries remain visible; completed finishes without a warning take no timeline row. + * Every Crew notice is a platform notice's one line. Approval summaries remain visible; completed + * finishes without a warning take no timeline row. */ export function renderCrewNotice(input: CrewNoticeRenderInput): ReactNode { const context = presentCrewContext(input.message); - if (context !== null) return ; + if (context !== null) { + // What the model read, long and not written for the person, so it opens on request. + return ( + +
+          {context.text}
+        
+
+ ); + } const notice = presentCrewNotice(input.message); if (notice === null) return null; - if (notice.kind === "gate" && notice.decision === "declined") - return ; + if (notice.kind === "gate" && notice.decision === "declined") { + const requested = notice.requestedSeats + .map((seat) => `${seat.seat} (${seat.agentId})`) + .join(", "); + return ( + + + + ); + } const summary = crewApprovalSummary(notice); return ( - <> - {summary === null ? null : ( -

- {summary} -

- )} - {crewNoticeLines(notice).length === 0 ? null : ( - +
+ {summary === null || notice.kind !== "gate" ? null : ( + )} - + {crewNoticeLines(notice).map((line, index) => ( + // oxlint-disable-next-line react/no-array-index-key -- a folded notice can repeat a seat with the same reason, so no field is unique. + + ))} +
); } diff --git a/apps/web/src/j5/crew/crewNotices.logic.test.ts b/apps/web/src/j5/crew/crewNotices.logic.test.ts index bd521c34d775..b2e4b55828a8 100644 --- a/apps/web/src/j5/crew/crewNotices.logic.test.ts +++ b/apps/web/src/j5/crew/crewNotices.logic.test.ts @@ -1,14 +1,13 @@ import { describe, expect, it } from "vite-plus/test"; -import { presentCrewNotice } from "@t3tools/client-runtime/j5/crew-notices"; - import { crewApprovalSummary, - crewGateTitle, + crewDeclinedSummary, crewNoticeLines, - isHiddenCrewNotice, - withoutHiddenCrewNotices, -} from "./crewNotices.logic"; + presentCrewNotice, +} from "@t3tools/client-runtime/j5/crew-notices"; + +import { isHiddenCrewNotice, withoutHiddenCrewNotices } from "./crewNotices.logic"; const approvedGate = [ "", @@ -154,8 +153,8 @@ describe("crew notices in the Captain's thread", () => { seat: "punchline", crewName: null, threadId: "thread:p", - reason: - "couldn't start · provider_error — API Error: Can't reach the API server | check DNS", + reason: "couldn't start", + detail: "provider_error — API Error: Can't reach the API server | check DNS", tone: "bad", }, { @@ -163,6 +162,7 @@ describe("crew notices in the Captain's thread", () => { crewName: null, threadId: "thread:q", reason: "hasn't confirmed it started", + detail: null, tone: "warn", }, ]); @@ -207,7 +207,8 @@ describe("crew notices in the Captain's thread", () => { seat: "punchline", crewName: null, threadId: null, - reason: "was never created · thread.create refused\nquota | retry later", + reason: "was never created", + detail: "thread.create refused\nquota | retry later", tone: "bad", }, ]); @@ -338,9 +339,9 @@ describe("crew notices in the Captain's thread", () => { roster: [], requestedSeats: [{ seat: "sitter", agentId: "sentry" }], }); - // A decline keeps its card: it has no lines, and is not hidden. + // A decline keeps its line: it has no seat lines, and is not hidden. if (declined?.kind === "gate") { - expect(crewGateTitle(declined)).toBe("Seat declined"); + expect(crewDeclinedSummary(declined)).toBe("Crew Invoice Export PR · seat declined"); expect(crewNoticeLines(declined)).toEqual([]); } expect( @@ -388,7 +389,8 @@ describe("crew notices in the Captain's thread", () => { seat: "critic", crewName: null, threadId: "thread:c", - reason: "finished · ReviewHandoff can't be read: not a regular file", + reason: "finished · ReviewHandoff can't be read", + detail: "not a regular file", tone: "warn", }, ]); @@ -463,7 +465,8 @@ describe("crew notices in the Captain's thread", () => { seat: "builder", crewName: null, threadId: "thread:b", - reason: "run failed · provider_error — API Error: Can't reach the API server", + reason: "run failed", + detail: "provider_error — API Error: Can't reach the API server", tone: "bad", }, ]); @@ -489,6 +492,7 @@ describe("crew notices in the Captain's thread", () => { crewName: null, threadId: "thread:c", reason: "finished · ReviewHandoff missing", + detail: null, tone: "warn", }, ]); diff --git a/apps/web/src/j5/crew/crewNotices.logic.ts b/apps/web/src/j5/crew/crewNotices.logic.ts index cc92d60660a2..6ef421c23fd3 100644 --- a/apps/web/src/j5/crew/crewNotices.logic.ts +++ b/apps/web/src/j5/crew/crewNotices.logic.ts @@ -1,111 +1,10 @@ import { + crewApprovalSummary, + crewNoticeLines, presentCrewNotice, type CrewNoticeMessage, - type CrewNoticePresentation, - type FinishedSeat, } from "@t3tools/client-runtime/j5/crew-notices"; -export interface CrewNoticeLine { - readonly seat: string; - /** Named only when one notice speaks for several Crews, where a seat name alone is ambiguous. */ - readonly crewName: string | null; - /** Null when the seat's thread was never created: the line names it and doesn't link. */ - readonly threadId: string | null; - readonly reason: string; - readonly tone: "bad" | "warn"; -} - -const handoffLine = (seat: FinishedSeat, crewName: string | null): CrewNoticeLine | null => { - const handoff = seat.handoff; - if (handoff.status === "missing") - return { - seat: seat.seat, - crewName, - threadId: seat.threadId, - reason: `finished · ${handoff.kind} missing`, - tone: "warn", - }; - if (handoff.status === "unavailable") - return { - seat: seat.seat, - crewName, - threadId: seat.threadId, - reason: `finished · ${handoff.kind} can't be read${handoff.reason === null ? "" : `: ${handoff.reason}`}`, - tone: "warn", - }; - return null; -}; - -/** - * What the person would act on in a notice, one line per seat: a seat that didn't start, or a run - * that didn't end clean. A seat that started or finished cleanly has no line; its row on the Fleet - * page and the Captain's expander says so. - */ -export const crewNoticeLines = (notice: CrewNoticePresentation): ReadonlyArray => { - if (notice.kind === "gate") { - if (notice.decision !== "approved") return []; - const threadOf = (seat: string) => - notice.roster.find((entry) => entry.seat === seat)?.threadId ?? null; - return [ - ...notice.failures.map((failure) => ({ - seat: failure.seat, - crewName: null, - threadId: threadOf(failure.seat), - reason: `couldn't start · ${failure.detail}`, - tone: "bad" as const, - })), - ...notice.notCreated.map((seat) => ({ - seat: seat.seat, - crewName: null, - threadId: null, - reason: `was never created · ${seat.detail}`, - tone: "bad" as const, - })), - ...notice.pendingSeats.map((seat) => ({ - seat, - crewName: null, - threadId: threadOf(seat), - reason: "hasn't confirmed it started", - tone: "warn" as const, - })), - ]; - } - // Finishes from several Crews fold into one notice when the Captain commands more than one. - const severalCrews = new Set(notice.seats.map((seat) => seat.crewName)).size > 1; - return notice.seats.flatMap((seat): ReadonlyArray => { - const crewName = severalCrews ? seat.crewName : null; - if (seat.runStatus === "completed") { - const line = handoffLine(seat, crewName); - return line === null ? [] : [line]; - } - const ended = - seat.runStatus === "failed" || seat.runStatus === "errored" - ? "run failed" - : `run ${seat.runStatus}`; - return [ - { - seat: seat.seat, - crewName, - threadId: seat.threadId, - reason: seat.failure === null ? ended : `${ended} · ${seat.failure}`, - tone: "bad", - }, - ]; - }); -}; - -/** - * The stored launch report records the approved members, including ones never created. The - * approver is named when the notice carries one, which only a shared conversation's does. - */ -export const crewApprovalSummary = (notice: CrewNoticePresentation): string | null => { - if (notice.kind !== "gate" || notice.decision !== "approved" || notice.requestKind !== "roster") - return null; - const count = notice.roster.length + notice.notCreated.length; - const by = notice.decidedBy ? ` · by ${notice.decidedBy}` : ""; - return `Crew approved · ${count} ${count === 1 ? "member" : "members"}${by}`; -}; - /** Completed finishes and successful additions take no row in the timeline. */ export const isHiddenCrewNotice = (message: CrewNoticeMessage): boolean => { const notice = presentCrewNotice(message); @@ -134,7 +33,3 @@ export const withoutHiddenCrewNotices = ( visibleRows.set(rows, visible); return visible; }; - -/** A declined gate's card title. */ -export const crewGateTitle = (notice: Extract) => - notice.requestKind === "roster" ? "Crew declined" : "Seat declined"; diff --git a/docs/j5/product/features/crews.md b/docs/j5/product/features/crews.md index 67e3effb7ac9..19a0ff0ba956 100644 --- a/docs/j5/product/features/crews.md +++ b/docs/j5/product/features/crews.md @@ -23,7 +23,7 @@ A **Crew** is a group of agents formed as a unit from a **roster its Captain pro **Communication is direct; handoff artifacts record durable outputs.** Members exchange findings, questions, and results directly with one another and their Captain, and run their own review loops (AC9); Captains can coordinate with other Captains. Neither an artifact nor a human approval is required for these messages. Members send their final result with evidence and unresolved issues to the Captain. How a message reaches a running turn depends on the provider (Messages and steering, below). A seat whose persona declares an output artifact (a Critic's ReviewHandoff, a Scout's ContextBrief) owes it as the same shared handoff artifact every persona writes — `handoffs//-.md` in the project's artifacts (see the [persona contract](../agent-personas/index.md)) — and its first turn names that exact path. The handoff gate checks for the file when a run ends and reminds the seat once. File existence is evidence of delivery, not validation or acceptance of the result; the Captain reviews the handoff artifact against the task. **Every seat tells its Captain when it finishes**, as measured facts: how the run ended first, the run's error when it failed, and whether its handoff artifact was written, missing, unavailable (with why), or never declared, with the artifact inline when short. A first turn that fails is a launch outcome, told once by the launch report and not again as a finish; and a seat's failure that its Captain hears this way is not repeated by the silence detector as an unanswered ask. The notice is posted the first time a seat finishes and again only when those facts change; a finish that would repeat the last notice word for word is silent, because the seat's own reply already reached the Captain. Notices that arrive while the Captain's turn is running fold into the one seat notice already queued behind that turn, so the Captain absorbs its Crew's news in one turn rather than one per seat. Notice delivery retries on a later finish or the next server startup if dispatch fails; it is not guaranteed promptly while the seat stays idle. Sign-in and permission failures also raise a platform notice in the person’s Inbox, with replies routed to the Captain; other failures remain for the Captain to assess. A Captain normally does not have to interview its Crew to learn a seat is done, and it never waits for one inside a turn: `t3_thread_wait` is not on its surface, because a turn that blocks cannot receive the notice it is waiting for. The person opens every handoff on the Artifacts page. A direct result message does not replace a handoff artifact explicitly required by a saved persona. -**Members report their finish.** When a member's run ends and it owes no open reply, the platform tells its Captain how the run ended and where its handoff artifact stands; a later message runs normally. The platform never settles a seat because its run finished: upstream settles by hand, by merged PR, or by idle days, and a seat marked settled seconds after launch read as wrong (Jackson, 2026-09-17). Settling the Captain settles its seats (AC17). **A Crew's state is its seats' states**, summarized from measured facts — how many seats are running, need a person, or were settled — on the Crew's row of the Fleet page and on the Captain's expander in the sidebar, where each seat's row also says how its last run ended (failed, interrupted, or completed); the person never has to interview a Crew to learn where it stands. **The Captain's timeline keeps approval compact and shows what needs attention.** The launch report and finish notices reach the Captain unchanged, but the person sees one line per seat that couldn't start, was never created, hasn't confirmed it started, failed, or finished with its handoff artifact missing or unreadable, each opening the seat's thread when it has one; a roster approval shows “Crew approved · N members” from the stored gate notice, including in existing threads; a clean finish shows nothing, and an interruption after the first turn, which comes from a stop, is silent there too. Members stay out of the thread sidebar unless pinned; the Captain's row carries the Captain's anchor mark and an expander into its members; the Fleet page lists every agent by project and placement with each Crew under its Captain. Crews are a web and desktop surface; mobile has no Crew surface today, deliberately. +**Members report their finish.** When a member's run ends and it owes no open reply, the platform tells its Captain how the run ended and where its handoff artifact stands; a later message runs normally. The platform never settles a seat because its run finished: upstream settles by hand, by merged PR, or by idle days, and a seat marked settled seconds after launch read as wrong (Jackson, 2026-09-17). Settling the Captain settles its seats (AC17). **A Crew's state is its seats' states**, summarized from measured facts — how many seats are running, need a person, or were settled — on the Crew's row of the Fleet page and on the Captain's expander in the sidebar, where each seat's row also says how its last run ended (failed, interrupted, or completed); the person never has to interview a Crew to learn where it stands. **The Captain's timeline keeps approval compact and shows what needs attention.** The launch report and finish notices reach the Captain unchanged, but the person sees, as [platform notices](thread-a2a-rendering.md), one line per seat that couldn't start, was never created, hasn't confirmed it started, failed, or finished with its handoff artifact missing or unreadable, each opening the seat's thread when it has one; a roster approval shows “Crew approved · N members” from the stored gate notice, including in existing threads; a clean finish shows nothing, and an interruption after the first turn, which comes from a stop, is silent there too. Members stay out of the thread sidebar unless pinned; the Captain's row carries the Captain's anchor mark and an expander into its members; the Fleet page lists every agent by project and placement with each Crew under its Captain. Crews are a web and desktop surface; mobile has no Crew surface today, deliberately. ### Captains @@ -85,7 +85,7 @@ A steer that races a Stop is a known case ([FORK.md](../../../FORK.md) case 26). ### Handoff artifacts -12. A seat whose definition declares an output artifact writes it as its handoff artifact in the project's artifacts; its first turn names the exact path. The first assignment carries its playbook context and handoff obligation; a later assignment reuses the same thread and workspace without repeating its introduction, unless the provider conversation was replaced (a model or provider switch, or a native session the provider lost), in which case the introduction is sent again with the current roster. Members that finished remain available on the roster. Started members receive net roster changes, naming who joined or left and their responsibility, at the top of their next delivery, including a message steered into a turn in progress. Waiting members receive the current roster with their first assignment. Context is attached at provider delivery, after queued edits, cancellations, and reordering; a start that never reaches the provider, because it was refused, stopped, or superseded, leaves it owed. A waiting member whose Crew retired must have its Crew restored before starting, and a worktree seat cannot fall back to the project root. What a member was told is kept in its own thread: once the provider has taken a prompt that carried the introduction or a roster change, the thread gains a collapsed card, **Introduction** or **Roster changed**, that opens to the text the model read, without the assignment. The card sits with the run it was told in, starts no run and queues none, and is posted once however often a delivery is retried; a refused or superseded send posts nothing. Roster changes alone start no turns, and availability produces no polling or acknowledgment turns. +12. A seat whose definition declares an output artifact writes it as its handoff artifact in the project's artifacts; its first turn names the exact path. The first assignment carries its playbook context and handoff obligation; a later assignment reuses the same thread and workspace without repeating its introduction, unless the provider conversation was replaced (a model or provider switch, or a native session the provider lost), in which case the introduction is sent again with the current roster. Members that finished remain available on the roster. Started members receive net roster changes, naming who joined or left and their responsibility, at the top of their next delivery, including a message steered into a turn in progress. Waiting members receive the current roster with their first assignment. Context is attached at provider delivery, after queued edits, cancellations, and reordering; a start that never reaches the provider, because it was refused, stopped, or superseded, leaves it owed. A waiting member whose Crew retired must have its Crew restored before starting, and a worktree seat cannot fall back to the project root. What a member was told is kept in its own thread: once the provider has taken a prompt that carried the introduction or a roster change, the thread gains a notice line, **Introduction** or **Roster changed**, that opens to the text the model read, without the assignment. The line sits with the run it was told in, starts no run and queues none, and is posted once however often a delivery is retried; a refused or superseded send posts nothing. Roster changes alone start no turns, and availability produces no polling or acknowledgment turns. 13. When a seat finishes, the Captain receives a notice that leads with how the run ended and, for a failed run, carries the run's recorded error, then whether the seat's handoff artifact was written, missing, unavailable with the reason it can never be read, or never declared, a written handoff artifact riding inline when short and by path otherwise; a finish whose notice would repeat the seat's last one is silent, and a notice arriving while the Captain's turn runs folds into the seat notice already queued behind it rather than queuing another turn. 14. A seat that finishes without its handoff artifact is reminded once and is reported to its Captain on its next finished run whatever happened. @@ -173,18 +173,9 @@ A steer that races a Stop is a known case ([FORK.md](../../../FORK.md) case 26). - 2026-10-27 — the Captain's timeline shows the person only what they would act on: launch and finish notices become one line per seat that needs them, and each seat's row says how its last run ended (Bryant; [#741](https://github.com/Jacksondr5/j5code/issues/741)). - 2026-10-27 — models for custom members: a project's lists of checked models and checked reasoning levels decide what custom seats, plain spawned agents and plain delegated tasks run on; personas keep their own; native subagents are outside the lists on every provider (AC24–AC30; Bryant; [#744](https://github.com/Jacksondr5/j5code/issues/744)). - 2026-10-27 — when the person asked for none, an agent chooses between working directly, subagents, and a Crew from the work; an explicit request for a Crew, a Peer Agent or a subagent still gets that mechanism; members run their own review loops and reach the Captain only for a review pass, a blocker, or a disagreement, or their final result (AC1, AC9; Bryant and Jackson; [#746](https://github.com/Jacksondr5/j5code/issues/746)). - <<<<<<< HEAD - 2026-10-27 — a Captain asks the person for a decision with `j5_send_message`: one request, listed in the Inbox and pinned above the Captain's composer, answered in either place (Bryant; [#747](https://github.com/Jacksondr5/j5code/issues/747)). This replaces the 2026-09-26 line that had the Captain ask inline with its own question tool. - <<<<<<< HEAD - 2026-10-27 — a new worktree seat's base is resolved to a commit when the proposal is accepted and launches from it, so branch renames cannot break a launch; a worktree prepared from that commit has no `gh-merge-base` (AC3; Bryant; [#752](https://github.com/Jacksondr5/j5code/issues/752)). - <<<<<<< HEAD - 2026-10-27 — AC19: the worktrees an archive keeps for uncommitted or unmerged work are filed as one Inbox approval, and removed only when the person approves ([#749](https://github.com/Jacksondr5/j5code/issues/749); Crews proposal v2). - 2026-11-02 — AC19: the worktree approval is per archive, withdrawn when the Crew comes back, and only for work its branch holds ([#749](https://github.com/Jacksondr5/j5code/issues/749), review). - \======= - \======= - \======= - 2026-10-31 — a member's introduction and roster changes are visible in its own thread, as a collapsed card that opens to what the model read, where they had been sent to the model only (Jackson, 2026-10-31; register D43). - -> > > > > > > s/746 -> > > > > > > s/747 -> > > > > > > s/752 +- 2026-11-02 — Crew notices take the look of every other platform notice: one grey line that opens, a red or amber icon on a seat in trouble, including the member's introduction and roster changes, which had been a collapsed card ([#698](https://github.com/Jacksondr5/j5code/issues/698)). Which notices appear is unchanged. diff --git a/docs/j5/product/features/thread-a2a-rendering.md b/docs/j5/product/features/thread-a2a-rendering.md index db57cf42910a..2993478e08e5 100644 --- a/docs/j5/product/features/thread-a2a-rendering.md +++ b/docs/j5/product/features/thread-a2a-rendering.md @@ -18,8 +18,10 @@ Every message in the person's place in a thread is shown by **who is speaking**, 1. **The person.** Upstream's full bubble on the right, unchanged. A reply the person sent from the inbox carries a caption above it, "You · via Inbox". 2. **Other people.** In a shared conversation, a full bubble on the left with their initials and name. An inbox reply from another person adds "· via Inbox" after the name. 3. **Other participants:** agents, machine participants, outside agents, agents on peer servers, and the agent that spawned this one. On the left, an **identity line** above the row, then upstream's folded row: the first line of the letter and a chevron. Opened, it shows the whole letter with upstream's footer: open the sender's thread, the time, copy. -4. **Platform notices** (not built yet). One muted line on the left, with no bubble and no identity: an icon, a plain summary, the time and a chevron. Opened, the detail hangs under it. J5's notices (a silence, a message not delivered or withdrawn, a Crew decision, a seat's report) and upstream's (a pull-request watch update, a finished delegated task, a continuation after a restart) look the same. -5. **Platform prompts** (not built yet). An outlined pill on the left: an icon, a kind label, the task or step title and a chevron. Opened, the full prompt. It covers upstream's automation runs and idle compaction, a playbook step handed to a Crew seat, and a question raised to a parent. +4. **Platform notices** that J5 writes. One muted line on the left, with no bubble and no identity: an icon, a plain summary, the time and a chevron. Opened, the detail hangs under a thin rule, with a link where there is something to open. It covers a silence, a message not delivered, an Exchange dropped or withdrawn, a queued message removed, a handoff reminder and a Crew notice. A line with nothing more to say has no chevron. Which Crew notices appear is the [Crews](crews.md) rule; a seat in trouble carries a red or amber icon. +5. **Platform prompts.** An outlined pill on the left: an icon, a kind label, the task or step title and a chevron. Opened, the full prompt. It covers upstream's automation runs, a playbook step handed to a Crew seat, and a native question raised to a placement parent. + +**Upstream's own platform rows keep upstream's look.** A pull-request watch update, a finished delegated or background task, a continuation after a restart, a delegated task's question and idle compaction are not user messages in the timeline: upstream draws them on its own notification and compaction rows, which are already one muted line. J5 leaves them there, because restyling them would be a new edit to upstream's work rows for little gain. The identity line is a bot glyph, the sender's name and at most one badge or tag. The **name** is the participant's label, a persona or agent name; without one, the title of the sender's thread; and otherwise "Agent". A spawn brief's line reads "⟨spawner⟩ · brief". The **badge** appears only when the message asks something of the reader, in the inbox's words: **Expects reply** on an ask, in amber, and **Replied** on a reply that closed an Exchange, in quiet green. A plain message and a follow-up carry none, because the platform never asserts a role it did not measure. A sender that is not an agent gets a **tag** instead: **Automation** for a machine participant, **Outside agent** for an MCP sign-in. The line leaves out Crew or Captain context (the seat's name says it), the delivery mode (upstream's steer marker already shows it) and the peer server's name. Badges are the only colored elements. Whether an Exchange is still open is not drawn: the [inbox](inbox.md) tracks waiting. @@ -46,14 +48,14 @@ This is **not** a change to what agents receive, **not** a summary layer, and ** 6. A received ask shows "Expects reply" and a reply that closed an Exchange shows "Replied"; a plain message and a follow-up show no badge; a machine participant shows the tag "Automation" and an outside agent "Outside agent". 7. Badges are the only colored elements: amber while something waits, quiet green when resolved. -### Platform notices (not built yet) +### Platform notices -8. A platform notice, J5's or upstream's, is one muted line on the left with an icon, a plain summary and the time, visibly distinct from any message, and opens to its detail. -9. A silence notice's summary names the counterpart and the age. +8. A platform notice J5 writes is one muted line on the left with an icon, a plain summary and the time, visibly distinct from any message, and opens to its detail when it has one. +9. A silence notice's summary names the counterpart, by its label, and shows when it was noticed. -### Platform prompts (not built yet) +### Platform prompts -10. A platform prompt (an automation run, idle compaction, a playbook step for a Crew seat, a question raised to a parent) is an outlined pill on the left with its kind and title, and opens to the full prompt. +10. A platform prompt (an automation run, a playbook step for a Crew seat, a native question raised to a parent) is an outlined pill on the left with its kind and title, and opens to the full prompt. ### Sent messages @@ -63,18 +65,21 @@ This is **not** a change to what agents receive, **not** a summary layer, and ** 12. No row, folded or open, shows an envelope, a tagged block or a participant id, and a folded row's preview is the first non-empty line the reader should see. 13. A message whose envelope the renderer does not recognize renders as upstream's row. -14. No surface shows Exchange-closure mechanics as reader copy; "Expects reply" and "Replied" are the only Exchange words a reader sees. +14. No surface shows Exchange-closure mechanics as reader copy: a letter's badge says only "Expects reply" or "Replied", and a notice says in plain words what happened to an Exchange. ### Conversation -15. Everything that is not a message in the person's place (the agent's replies, tool calls, work logs) renders exactly as upstream renders it. +15. Everything that is not a message in the person's place (the agent's replies, tool calls, work logs, upstream's notification and compaction rows) renders exactly as upstream renders it. +16. In-thread find reaches every folded row, and a match in a folded row opens it. ## Scenarios - **An ask arrives.** An agent in Billing Migration receives "which schema version do we target?" from its Captain: on the left, an identity line naming the Captain with an amber "Expects reply" badge, and one folded line, the question. The agent replies; the Captain's thread shows the reply folded under the agent's name with "Replied", and the agent's own thread shows the send as an ordinary tool call. (AC4, AC6, AC11) - **The user answers from the inbox.** The user replies in the inbox; the agent's thread shows the reply on the right under "You · via Inbox". (AC2) - **A Peer Agent starts.** A Peer Agent's thread opens with its spawner's brief, folded under "⟨spawner⟩ · brief" to the brief's first line; the platform context is never shown. (AC5, AC12) -- **A peer went quiet** (target). The Captain's turn ended without replying; the agent's thread shows one grey line, "Captain's turn ended without replying · 40m", and nothing that looks like a message. (AC8, AC9) +- **A peer went quiet.** The Captain's turn ended without replying; the agent's thread shows one grey line, "Captain's turn ended without replying", with the time, and nothing that looks like a message. (AC8, AC9) +- **A message didn't arrive.** A send failed three times; the sender's thread shows "Message to Reviewer not delivered", which opens to the reason. (AC8) +- **A seat is handed a step.** A Crew seat's thread shows an outlined "Playbook step 2 of 5" pill with the step's title, which opens to the step's prompt. (AC10) - **A plain update.** A peer sends a status update with no ask; its identity line has no badge. (AC6) ## History @@ -87,3 +92,4 @@ This is **not** a change to what agents receive, **not** a summary layer, and ** - 2026-10-10 — sent messages no longer get a card (AC6). Upstream's V2 orchestrator sends clients a trimmed tool call, without the message body or the Exchange state the card was drawn from, so the card had not rendered since J5 moved to it; Jackson chose to retire it over exempting sends from the trimming (#522). - 2026-10-17 — the sender's name links only when this client can open the sender's thread, on its own server or a connected peer; automations, outside agents and people have no thread to open (AC1). The 2026-08-31 clickable name had not been built (#625). - 2026-10-24 — rewritten from cards to five groups by speaker, after upstream began folding other agents' messages into one-line rows (pingdotgg/t3code#23135); Jackson's design of that day, register D38. Groups 1 to 3 are built; the notices and prompts (AC8 to AC10) wait on [#698](https://github.com/Jacksondr5/j5code/issues/698), and mobile on [#699](https://github.com/Jacksondr5/j5code/issues/699). A follow-up no longer shows a badge. Former identifiers: AC1 → AC4, AC5; AC2 → AC12, AC13; AC3 → AC6; AC4 → AC2, AC3; AC5 → AC8, AC9; AC6 → AC11; AC7 → AC7; AC8 → AC1; AC10 → AC14; AC13 → AC15. Former AC9 (clamped card bodies), AC11 (a reply's quote of its ask) and AC12 (a badge's link to its pair) are dropped with the cards. +- 2026-11-02 — groups 4 and 5 built on web ([#698](https://github.com/Jacksondr5/j5code/issues/698)): the raw card is gone, so a notice J5 cannot read is upstream's row. Upstream's platform messages left groups 4 and 5: the 2026-10-24 design assumed they were user messages, but upstream now draws them on its own notification and compaction rows, so J5 follows upstream (Captain's call on the build, Jackson told). AC9 no longer asks for an age, which the notice doesn't carry; the line shows the time. AC14 lets a notice name what happened to an Exchange. AC16 added. Mobile draws silences and a labelled card for the rest until it follows. diff --git a/docs/j5/product/upstream.md b/docs/j5/product/upstream.md index 03064efe0659..cadb9b7399ad 100644 --- a/docs/j5/product/upstream.md +++ b/docs/j5/product/upstream.md @@ -134,7 +134,7 @@ Letter codes in the Decided lines (SC2, QS1, AR3, and so on) are rulings recorde **Upstream:** a message in a thread's history is a turn: dispatching one always starts a run, queues one behind the running turn, or steers the running one. There is no way to add something to the history that the agent is not asked to answer. -**J5:** an internal command records a platform-authored message in a thread, as a user-role message from the platform, without starting, queuing or counting a run. J5 uses it for one thing: after the provider takes a prompt that carried a Crew member's introduction or a roster change, the member's thread records exactly what the model read, without the assignment, as a collapsed card. It sits with the run it was told in and is recorded once however often the delivery is retried. +**J5:** an internal command records a platform-authored message in a thread, as a user-role message from the platform, without starting, queuing or counting a run. J5 uses it for one thing: after the provider takes a prompt that carried a Crew member's introduction or a roster change, the member's thread records exactly what the model read, without the assignment, as a notice line that opens to it. It sits with the run it was told in and is recorded once however often the delivery is retried. **Why:** since the Crew member's introduction began riding with its first assignment for the model only, the person reading the member's thread could not see what the member had been told (Jackson, review of the first-assignment change). Posting it with `message.dispatch` would have started a run on a member that should only be told something. @@ -200,11 +200,11 @@ Letter codes in the Decided lines (SC2, QS1, AR3, and so on) are rulings recorde **Upstream:** a message another agent sends into a thread folds into a one-line row on the right, named after the sender's thread, and an automation's prompt folds into an "Automation" row, so the person's own messages stay easy to find (pingdotgg/t3code#23135, pingdotgg/t3code#22638). A message the app writes itself is a full message on the right with "Sent by T3 Code" above it. -**J5:** every message in the person's place in a thread is shown by who is speaking. The person's own messages keep upstream's bubble on the right. Another person's is a full bubble on the left with their name, and a reply sent from the Inbox says "via Inbox". Everyone else, whether an agent, a machine participant, an outside agent, an agent on a peer server or the spawner of a Peer Agent, folds on the left into upstream's one-line row, under an identity line: the participant's name and, when the message asks something of the reader, the Inbox's Exchange badge ("Expects reply" or "Replied"), or else an "Automation" or "Outside agent" tag. The folded row shows the first line of the letter, never J5's envelope, and opens to the whole letter. These messages stay out of the conversation minimap, and a queued one names its sender. Two more groups are agreed and not built yet ([#698](https://github.com/Jacksondr5/j5code/issues/698)): J5's platform notices (silences, undelivered messages, Crew decisions, seat reports) as one grey line each, and J5's look for the messages upstream's platform writes (grey lines for its notices, an outlined pill for its prompts, its Automation row included). Mobile gets the same design later ([#699](https://github.com/Jacksondr5/j5code/issues/699)). +**J5:** every message in the person's place in a thread is shown by who is speaking. The person's own messages keep upstream's bubble on the right. Another person's is a full bubble on the left with their name, and a reply sent from the Inbox says "via Inbox". Everyone else, whether an agent, a machine participant, an outside agent, an agent on a peer server or the spawner of a Peer Agent, folds on the left into upstream's one-line row, under an identity line: the participant's name and, when the message asks something of the reader, the Inbox's Exchange badge ("Expects reply" or "Replied"), or else an "Automation" or "Outside agent" tag. The folded row shows the first line of the letter, never J5's envelope, and opens to the whole letter. These messages stay out of the conversation minimap, and a queued one names its sender. J5's platform notices (a silence, an undelivered message, a dropped or withdrawn Exchange, a handoff reminder, a Crew notice) are one grey line each on the left, which opens to the detail. Platform prompts (upstream's automation runs, and J5's playbook steps and native questions) are upstream's Automation row moved to the left with its fill removed. Upstream's own platform rows (pull-request watch updates, finished tasks, restart continuations, delegated questions, idle compaction) keep upstream's look: upstream already draws them as one-line notification and compaction rows, not as user messages. Mobile draws silences and a labelled card for J5's other notices until it follows. -**Why:** upstream's reason holds for J5: other agents' letters pushed the person's own messages off screen, and J5's cards did so more than upstream's rows. J5 also knows what upstream does not: who each participant is, beyond a thread's title, and whether a message opens or closes an Exchange, so the folded row can say who is speaking and whether it waits on the reader. Upstream gives no reason for keeping folded rows on the right, and J5 already puts other people on the left, so only the person's own words sit on the right. Notices get one look whoever wrote them, so the person can tell a notice from a letter at a glance. +**Why:** upstream's reason holds for J5: other agents' letters pushed the person's own messages off screen, and J5's cards did so more than upstream's rows. J5 also knows what upstream does not: who each participant is, beyond a thread's title, and whether a message opens or closes an Exchange, so the folded row can say who is speaking and whether it waits on the reader. Upstream gives no reason for keeping folded rows on the right, and J5 already puts other people on the left, so only the person's own words sit on the right. J5's notices get one look, so the person can tell a notice from a letter at a glance. -**Consequences:** the seams sit in upstream's user row and timeline, and the classifier is J5's own, shared by web and mobile. A message whose envelope J5 does not recognize falls back to upstream's row, visibly. Until the notices are built, a platform notice no parser reads keeps J5's raw card. The two pending groups restyle messages upstream writes: the code is J5's and a message whose id upstream changes falls back to upstream's row, but the look is a divergence of its own, checked at every advance. Upstream's own thread sends, which carry no J5 envelope, get J5's treatment too, named from the sender's thread. Inbox replies no longer show the "Closed your exchange" chip. Upstream is still building agent-to-agent features (see the [upstream convergence watchlist](upstream-convergence.md)); prefer upstream's treatment if it comes to meet the need. +**Consequences:** the seams sit in upstream's user row and timeline, and the classifier is J5's own, shared by web and mobile. A message whose envelope J5 does not recognize falls back to upstream's row, visibly; J5's raw card is gone. Moving the Automation row left and removing its fill restyles a row upstream owns, a divergence of its own, checked at every advance. Upstream's own thread sends, which carry no J5 envelope, get J5's treatment too, named from the sender's thread. Inbox replies no longer show the "Closed your exchange" chip. Upstream is still building agent-to-agent features (see the [upstream convergence watchlist](upstream-convergence.md)); prefer upstream's treatment if it comes to meet the need. **Decided:** Jackson, 2026-10-24, during the advance onto upstream's nightly `v0.1.3-nightly.20261024.3630`; it replaces D16. Recorded in FORK.md cases 7, 24 and 80. @@ -657,3 +657,4 @@ J5 kept a run from resuming after a usage-limit reset when the person had presse - 2026-11-01 — D41 added: on mobile, a draft's persona has its own row under the checkout row, and the slash menu covers the draft rows (Jackson, Checkpoint 1; [#866](https://github.com/Jacksondr5/j5code/issues/866)). - 2026-10-27 — D1: when the person asked for none, agents choose between working directly, subagents and a Crew from the work, and get help in two ways, a subagent or a Crew member; an explicit request for a Crew, a Peer Agent or a subagent still gets that mechanism; `j5_spawn_agent` is described as for a Peer Agent the user asks for, not as a way to get help (Bryant, with Jackson's 2026-10-31 decision; [#746](https://github.com/Jacksondr5/j5code/issues/746)). - 2026-10-31 — D43 added: a thread can keep a message the platform wrote without a run, so a Crew member's introduction and roster changes show in its own thread (Jackson, 2026-10-31). +- 2026-11-02 — D38 now covers J5's platform notices and prompts, built on web ([#698](https://github.com/Jacksondr5/j5code/issues/698)); the raw card is retired. Upstream's platform messages stay on upstream's own rows, since upstream no longer draws them as user messages (Jackson, 2026-10-24 and 2026-10-31; Captain's call on the build, Jackson told). diff --git a/packages/client-runtime/src/j5/crewNotices.ts b/packages/client-runtime/src/j5/crewNotices.ts index 414ec46e0009..ee4344af094e 100644 --- a/packages/client-runtime/src/j5/crewNotices.ts +++ b/packages/client-runtime/src/j5/crewNotices.ts @@ -283,3 +283,123 @@ export const participantIdsForCrewNotice = (message: CrewNoticeMessage): Readonl if (notice?.kind === "seats") return notice.seats.map((seat) => seat.participantId); return []; }; + +/** One seat a Crew notice says needs the person. */ +export interface CrewNoticeLine { + readonly seat: string; + /** Named only when one notice speaks for several Crews, where a seat name alone is ambiguous. */ + readonly crewName: string | null; + /** Null when the seat's thread was never created: the line names it and doesn't link. */ + readonly threadId: string | null; + readonly reason: string; + /** The error or fact behind the reason, for the line to open to. */ + readonly detail: string | null; + readonly tone: "bad" | "warn"; +} + +const handoffLine = (seat: FinishedSeat, crewName: string | null): CrewNoticeLine | null => { + const handoff = seat.handoff; + if (handoff.status === "missing") + return { + seat: seat.seat, + crewName, + threadId: seat.threadId, + reason: `finished · ${handoff.kind} missing`, + detail: null, + tone: "warn", + }; + if (handoff.status === "unavailable") + return { + seat: seat.seat, + crewName, + threadId: seat.threadId, + reason: `finished · ${handoff.kind} can't be read`, + detail: handoff.reason, + tone: "warn", + }; + return null; +}; + +/** + * What the person would act on in a notice, one line per seat: a seat that didn't start, or a run + * that didn't end clean. A seat that started or finished cleanly has no line; its row on the Fleet + * page and the Captain's expander says so. + */ +export const crewNoticeLines = (notice: CrewNoticePresentation): ReadonlyArray => { + if (notice.kind === "gate") { + if (notice.decision !== "approved") return []; + const threadOf = (seat: string) => + notice.roster.find((entry) => entry.seat === seat)?.threadId ?? null; + return [ + ...notice.failures.map((failure) => ({ + seat: failure.seat, + crewName: null, + threadId: threadOf(failure.seat), + reason: "couldn't start", + detail: failure.detail, + tone: "bad" as const, + })), + ...notice.notCreated.map((seat) => ({ + seat: seat.seat, + crewName: null, + threadId: null, + reason: "was never created", + detail: seat.detail, + tone: "bad" as const, + })), + ...notice.pendingSeats.map((seat) => ({ + seat, + crewName: null, + threadId: threadOf(seat), + reason: "hasn't confirmed it started", + detail: null, + tone: "warn" as const, + })), + ]; + } + // Finishes from several Crews fold into one notice when the Captain commands more than one. + const severalCrews = new Set(notice.seats.map((seat) => seat.crewName)).size > 1; + return notice.seats.flatMap((seat): ReadonlyArray => { + const crewName = severalCrews ? seat.crewName : null; + if (seat.runStatus === "completed") { + const line = handoffLine(seat, crewName); + return line === null ? [] : [line]; + } + const ended = + seat.runStatus === "failed" || seat.runStatus === "errored" + ? "run failed" + : `run ${seat.runStatus}`; + return [ + { + seat: seat.seat, + crewName, + threadId: seat.threadId, + reason: ended, + detail: seat.failure, + tone: "bad", + }, + ]; + }); +}; + +/** + * The stored launch report records the approved members, including ones never created. The + * approver is named when the notice carries one, which only a shared conversation's does. + */ +export const crewApprovalSummary = (notice: CrewNoticePresentation): string | null => { + if (notice.kind !== "gate" || notice.decision !== "approved" || notice.requestKind !== "roster") + return null; + const count = notice.roster.length + notice.notCreated.length; + const by = notice.decidedBy ? ` · by ${notice.decidedBy}` : ""; + return `Crew approved · ${count} ${count === 1 ? "member" : "members"}${by}`; +}; + +/** A declined request's one line. */ +export const crewDeclinedSummary = (notice: Extract) => + `Crew ${notice.crewName === null ? "" : `${notice.crewName} `}· ${notice.requestKind === "roster" ? "roster" : "seat"} declined${notice.decidedBy === null ? "" : ` by ${notice.decidedBy}`}`; + +/** The notice's own line, beside the lines of the seats in it; null when it has none. */ +export const crewNoticeSummary = (notice: CrewNoticePresentation): string | null => + notice.kind === "gate" && notice.decision === "declined" + ? crewDeclinedSummary(notice) + : crewApprovalSummary(notice); diff --git a/packages/client-runtime/src/j5/participantIdentity.test.ts b/packages/client-runtime/src/j5/participantIdentity.test.ts index 1104dee006da..506150e59918 100644 --- a/packages/client-runtime/src/j5/participantIdentity.test.ts +++ b/packages/client-runtime/src/j5/participantIdentity.test.ts @@ -5,6 +5,7 @@ import { scopeThreadRef } from "../environment/scoped.ts"; import { j5MessageAuthorName, j5SenderThreadRef, + nameJ5NoticeParticipants, participantIdentitiesFromResponse, } from "./participantIdentity.ts"; import { @@ -160,3 +161,15 @@ describe("j5MessageAuthorName", () => { ).toBe("Someone without a name"); }); }); + +describe("nameJ5NoticeParticipants", () => { + it("replaces each id, the longest first, and says when one has no name", () => { + expect( + nameJ5NoticeParticipants( + "agent:ab is blocked on agent:a", + ["agent:a", "agent:ab"], + new Map([["agent:ab", "Builder"]]), + ), + ).toBe("Builder is blocked on Unnamed participant"); + }); +}); diff --git a/packages/client-runtime/src/j5/participantIdentity.ts b/packages/client-runtime/src/j5/participantIdentity.ts index 62a2a7366086..979999e1242c 100644 --- a/packages/client-runtime/src/j5/participantIdentity.ts +++ b/packages/client-runtime/src/j5/participantIdentity.ts @@ -55,6 +55,24 @@ export function presentParticipantIdentity(input: { }; } +/** A notice's words with each participant id replaced by its label, longest id first. */ +export function nameJ5NoticeParticipants( + text: string, + participantIds: ReadonlyArray, + participantLabels: ReadonlyMap, +): string { + return [...participantIds] + .sort((left, right) => right.length - left.length) + .reduce( + (named, participantId) => + named.replaceAll( + participantId, + presentParticipantIdentity({ participantId, participantLabels }).label, + ), + text, + ); +} + /** A queued delivery's row in "Up next": `From : `. Null for anything else. */ export function formatJ5QueuedDelivery( text: string, diff --git a/packages/client-runtime/src/j5/platformMessages.ts b/packages/client-runtime/src/j5/platformMessages.ts new file mode 100644 index 000000000000..7e7bebcbf041 --- /dev/null +++ b/packages/client-runtime/src/j5/platformMessages.ts @@ -0,0 +1,246 @@ +/** + * Reads J5's platform notices and prompts from what the server writes into a thread. Each reader + * is strict: words it does not recognize return null and the message falls back to upstream's row. + * Summaries and details keep participant ids, named in `participantIds`, for a client to replace + * with the identity read's labels; nothing else here is an id a reader should see. + */ +export interface PlatformNotice { + readonly summary: string; + readonly detail: string | null; + readonly participantIds: ReadonlyArray; +} + +export type DeliveryNoticeKind = + | "silence" + | "not-delivered" + | "exchange-dropped" + | "exchange-withdrawn"; + +const notice = ( + summary: string, + detail: string | null = null, + participantIds: ReadonlyArray = [], +): PlatformNotice => ({ summary, detail, participantIds }); + +const SILENCE_SUFFIX = "\n\nThis is a platform-authored delivery signal, not a peer reply."; +const TERMINAL_FOOTER = /^This is a platform-authored (?:terminal )?notice, not a peer reply\.$/; +const NOTICE_HEADER = /^\[Cross-agent messaging system notice: ([^\]\n]+)\]\n\n/; +const STOPPED_WORDS: Record = { rolled_back: "rolled back" }; +const HUMAN_STATES: Record = { + "human-knows": "The person has been told.", + "human-doesnt-know": "The person has not been told yet.", +}; + +function parseQueuedRemoval(body: string): PlatformNotice | null { + // Notices written before the message id was added read "Your message to ". + const match = /^Your message (?:\S+ )?to (\S+) was removed from its queue before it ran, /.exec( + body, + ); + if (match === null) return null; + const subject = match[1]!; + const begin = body.indexOf(" The message began: "); + const before = begin < 0 ? body : body.slice(0, begin); + const opening = begin < 0 ? null : body.slice(begin + " The message began: ".length); + const editor = / (\S+) had edited it in the queue\.$/.exec(before); + const edited = before.endsWith(" It had been edited in the queue.") + ? "It had been edited in the queue." + : editor === null + ? null + : `${editor[1]!} had edited it in the queue.`; + return notice( + `${subject} never read a queued message: it was removed before it ran`, + [edited, opening === null ? null : `The message began: ${opening}`] + .filter((line) => line !== null) + .join("\n\n") || null, + editor === null ? [subject] : [subject, editor[1]!], + ); +} + +function parseSilence(noticeType: string, body: string): PlatformNotice | null { + if (noticeType === "turn-ended-no-reply") { + const never = /^(\S+) did not start a turn for the delivered message on \S+\.$/.exec(body); + if (never) { + return notice(`${never[1]!} did not start a turn for the delivered message`, null, [ + never[1]!, + ]); + } + const ended = + /^(\S+)'s turn ended without replying on \S+\. (The latest delivered message was processed\.)$/.exec( + body, + ); + return ended + ? notice(`${ended[1]!}'s turn ended without replying`, ended[2]!, [ended[1]!]) + : null; + } + if (noticeType === "errored") { + const match = /^(\S+) errored without replying on \S+: ([\s\S]+)$/.exec(body); + return match ? notice(`${match[1]!} errored without replying`, match[2]!, [match[1]!]) : null; + } + if (noticeType === "stopped/cancelled") { + const match = + /^(\S+) was (interrupted|cancelled|rolled_back) without replying on \S+\. ([\s\S]+)$/.exec( + body, + ); + if (match === null) return null; + const word = STOPPED_WORDS[match[2]!] ?? match[2]!; + return notice(`${match[1]!} was ${word} without replying`, match[3]!, [match[1]!]); + } + if (noticeType === "queued-message-removed") return parseQueuedRemoval(body); + if (noticeType === "awaiting-human") { + const match = /^(\S+) is awaiting the human on \S+ \((.+)\)\.$/.exec(body); + return match + ? notice(`${match[1]!} is awaiting the human`, HUMAN_STATES[match[2]!] ?? null, [match[1]!]) + : null; + } + if (noticeType === "blocked-on-peer") { + const match = /^(\S+) is blocked on (\S+) via \S+\.$/.exec(body); + return match + ? notice(`${match[1]!} is blocked on ${match[2]!}`, null, [match[1]!, match[2]!]) + : null; + } + return null; +} + +const NOT_DELIVERED = + /^Your (?:message \S+|ask "(.*)" \(message \S+\)) to (\S+)(?: on (.+?))? (was not delivered|may not have been delivered): ([\s\S]+)$/; + +/** Paragraphs after the first, without the facts line and footer written for the agent. */ +const readableParagraphs = (paragraphs: ReadonlyArray) => + paragraphs.slice(1, -1).filter((paragraph) => !paragraph.startsWith("Facts: ")); + +const capitalized = (text: string) => `${text.charAt(0).toUpperCase()}${text.slice(1)}`; + +function parseNotDelivered(paragraphs: ReadonlyArray): PlatformNotice | null { + const match = NOT_DELIVERED.exec(paragraphs[0] ?? ""); + if (match === null) return null; + const [, intent, receiver, server, outcome, reason] = match; + const where = server === undefined ? receiver! : `${receiver!} on ${server}`; + const said = outcome === "was not delivered" ? "not delivered" : "may not have been delivered"; + const rest = readableParagraphs(paragraphs).map((paragraph) => + /^Exchange \S+ is still open; /.test(paragraph) + ? "The ask is still open; if it did arrive, its reply still comes." + : paragraph, + ); + return notice( + `Message to ${where} ${said}`, + [...(intent === undefined ? [] : [`Ask: "${intent}"`]), capitalized(reason!), ...rest].join( + "\n\n", + ), + [receiver!], + ); +} + +const PARTICIPANT_AT_START = /^((?:agent|human|machine|outside):\S+) /; + +function parseDropped(paragraphs: ReadonlyArray): PlatformNotice | null { + const match = /^Exchange \S+ ended because ([\s\S]+) \([a-z-]+\)\.$/.exec(paragraphs[0] ?? ""); + if (match === null) return null; + const because = match[1]!; + const subject = PARTICIPANT_AT_START.exec(because)?.[1]; + const rest = readableParagraphs(paragraphs).map((paragraph) => + paragraph.replace(/ \(message \S+\)\.$/, "."), + ); + return notice( + subject === undefined ? "An exchange was dropped" : `Exchange with ${subject} dropped`, + [`It ended because ${because}.`, ...rest].join("\n\n"), + subject === undefined ? [] : [subject], + ); +} + +function parseWithdrawn(paragraphs: ReadonlyArray): PlatformNotice | null { + const match = /^Exchange \S+ was withdrawn by (\S+), who no longer needs an answer\.$/.exec( + paragraphs[0] ?? "", + ); + if (match === null) return null; + return notice( + `${match[1]!} withdrew its ask`, + ["It no longer needs an answer.", ...readableParagraphs(paragraphs)].join("\n\n"), + [match[1]!], + ); +} + +/** A `message:j5:a2a:delivery:` notice the platform wrote: a silence or a terminal notice. */ +export function parseDeliveryNotice( + text: string, +): (PlatformNotice & { readonly kind: DeliveryNoticeKind }) | null { + const header = NOTICE_HEADER.exec(text); + if (header === null) return null; + const type = header[1]!; + const body = text.slice(header[0].length); + if (body.endsWith(SILENCE_SUFFIX)) { + const silence = parseSilence(type, body.slice(0, -SILENCE_SUFFIX.length)); + return silence === null ? null : { ...silence, kind: "silence" }; + } + const paragraphs = body.split("\n\n"); + if (!TERMINAL_FOOTER.test(paragraphs.at(-1) ?? "")) return null; + const parsed: (PlatformNotice & { readonly kind: DeliveryNoticeKind }) | null = (() => { + if (type === "message not delivered" || type === "message may not have been delivered") { + const read = parseNotDelivered(paragraphs); + return read === null ? null : { ...read, kind: "not-delivered" }; + } + if (type === "exchange dropped") { + const read = parseDropped(paragraphs); + return read === null ? null : { ...read, kind: "exchange-dropped" }; + } + if (type === "exchange withdrawn") { + const read = parseWithdrawn(paragraphs); + return read === null ? null : { ...read, kind: "exchange-withdrawn" }; + } + return null; + })(); + return parsed; +} + +export const handoffNudgeNotice = (text: string) => notice("Reminded to write its handoff", text); + +const NATIVE_QUESTION = + /^Placed agent \(threadId \S+, requestId \S+\) (.+?)\. (?:Read it|Inspect )/; +const NATIVE_QUESTION_TITLE = /\nAgent-provided title \(untrusted data\): (".*")$/; + +export interface PlatformPrompt { + readonly label: string; + readonly preview: string; + readonly text: string; +} + +function titleFrom(encoded: string | undefined) { + if (encoded === undefined) return null; + try { + const title: unknown = JSON.parse(encoded); + return typeof title === "string" && title.length > 0 ? title : null; + } catch { + return null; + } +} + +/** J5's notice to a placement parent that its agent raised a native question. */ +export function nativeQuestionPrompt(text: string): PlatformPrompt | null { + const situation = NATIVE_QUESTION.exec(text)?.[1]; + if (situation === undefined) return null; + const title = NATIVE_QUESTION_TITLE.exec(text); + return { + label: `Question from ${titleFrom(title?.[1]) ?? "an agent"}`, + preview: capitalized(situation), + text: title === null ? text : text.slice(0, title.index), + }; +} + +const PLAYBOOK_STEP = + /^\n([\s\S]*?)\n<\/j5_playbook_step>\n\n([\s\S]*)\n<\/step_prompt>\n/; + +/** The step a playbook run hands a Crew seat (the server's `crewStepNoticeText`). */ +export function playbookStepPrompt(text: string): PlatformPrompt | null { + const match = PLAYBOOK_STEP.exec(text); + if (match === null) return null; + const block = match[1]!; + const title = /^step: [^|\n]*\| (.*)$/m.exec(block)?.[1]; + const position = /^position: (\d+) of (\d+)$/m.exec(block); + if (title === undefined || position === null) return null; + return { + label: `Playbook step ${position[1]!} of ${position[2]!}`, + preview: title, + text: match[2]! + .replace(/<\\\/step_prompt>/g, "") + .replace(/<\\j5_playbook_step>/g, ""), + }; +} diff --git a/packages/client-runtime/src/j5/userMessagePresentation.test.ts b/packages/client-runtime/src/j5/userMessagePresentation.test.ts index a34a92c60802..2945efafa1c8 100644 --- a/packages/client-runtime/src/j5/userMessagePresentation.test.ts +++ b/packages/client-runtime/src/j5/userMessagePresentation.test.ts @@ -458,39 +458,185 @@ describe("groups 4 and 5: classified, drawn elsewhere", () => { side: "left", kind: "silence", summary: "agent:counterpart's turn ended without replying", + detail: "The latest delivered message was processed.", + participantIds: ["agent:counterpart"], text: silenceRaw, }); }); + // Each body is the server's own wording (SilenceDetector's `noticeMessage`, `removedNoticeMessage`). it.each([ + [ + "turn-ended-no-reply", + "agent:counterpart did not start a turn for the delivered message on exchange:one.", + "agent:counterpart did not start a turn for the delivered message", + null, + ], [ "errored", - "agent:counterpart errored without replying on exchange:one: socket closed", + "agent:counterpart errored without replying on exchange:one: socket closed: code 1\nretry later", "agent:counterpart errored without replying", + "socket closed: code 1\nretry later", ], [ "stopped/cancelled", "agent:counterpart was rolled_back without replying on exchange:one. The participant was rolled back.", - "agent:counterpart was rolled_back without replying", + "agent:counterpart was rolled back without replying", + "The participant was rolled back.", ], [ "queued-message-removed", - "Your message to agent:counterpart was removed from its queue before it ran, so agent:counterpart never read it. The message began: Review part 2.", + "Your message message:j5:a2a:one to agent:counterpart was removed from its queue before it ran, so agent:counterpart never read it. Send it again if it still matters. The message began: Review part 2.", "agent:counterpart never read a queued message: it was removed before it ran", + "The message began: Review part 2.", + ], + [ + "queued-message-removed", + "Your message to agent:counterpart was removed from its queue before it ran, so agent:counterpart never read it. The message began: Stored before ids.", + "agent:counterpart never read a queued message: it was removed before it ran", + "The message began: Stored before ids.", ], [ "awaiting-human", - "agent:counterpart is awaiting the human on exchange:human (awaiting-human).", + "agent:counterpart is awaiting the human on exchange:human (human-knows).", "agent:counterpart is awaiting the human", + "The person has been told.", ], [ "blocked-on-peer", "agent:counterpart is blocked on agent:peer via exchange:peer.", "agent:counterpart is blocked on agent:peer", + null, ], - ])("summarizes a %s notice", (noticeType, body, summary) => { + ])("reads a %s notice", (noticeType, body, summary, detail) => { const raw = `[Cross-agent messaging system notice: ${noticeType}]\n\n${body}\n\nThis is a platform-authored delivery signal, not a peer reply.`; - expect(presentJ5UserMessage(systemDelivery(raw))).toMatchObject({ kind: "silence", summary }); + expect(presentJ5UserMessage(systemDelivery(raw))).toMatchObject({ + kind: "silence", + summary, + detail, + }); + }); + + it("names who edited a removed message for the identity read", () => { + const raw = + "[Cross-agent messaging system notice: queued-message-removed]\n\nYour message m1 to agent:counterpart was removed from its queue before it ran, so agent:counterpart never read it. Send it again if it still matters. human:editor had edited it in the queue. The message began: Hi\n\nThis is a platform-authored delivery signal, not a peer reply."; + expect(presentJ5UserMessage(systemDelivery(raw))).toMatchObject({ + detail: "human:editor had edited it in the queue.\n\nThe message began: Hi", + }); + expect(participantIdsForJ5UserMessage(systemDelivery(raw))).toEqual([ + "agent:counterpart", + "human:editor", + ]); + }); + + // Each envelope is the server's own (deliveryNotices.ts, LifecycleService.ts, SendService.ts). + it.each([ + [ + "a plain message not delivered", + 'Your message message:one to agent:peer was not delivered: delivery failed 3 times, and it will not be tried again. The last attempt failed with: "boom"', + "message not delivered", + [], + "not-delivered", + "Message to agent:peer not delivered", + 'Delivery failed 3 times, and it will not be tried again. The last attempt failed with: "boom"', + ], + [ + "an ask that may not have arrived, still open", + 'Your ask "Which schema?" (message message:one) to agent:peer on Studio may not have been delivered: this server could not reach Studio in 3 attempts, and it will not be tried again.', + "message may not have been delivered", + [ + "Exchange exchange:one is still open; if the ask did arrive, its reply still comes on it. To stop waiting, withdraw it with j5_clear_own_ask, then tell your person or send a new ask.", + "Facts: exchangeId=exchange:one; exchangeOpen=true; retryScheduled=false.", + ], + "not-delivered", + "Message to agent:peer on Studio may not have been delivered", + 'Ask: "Which schema?"\n\nThis server could not reach Studio in 3 attempts, and it will not be tried again.\n\nThe ask is still open; if it did arrive, its reply still comes.', + ], + [ + "a refused ask, closed", + 'Your ask "Which schema?" (message message:one) to agent:peer on Studio was not delivered: Studio has no active participant with that id.', + "message not delivered", + [ + "The exchange is closed; nothing is owed and nothing will answer it.", + "Facts: exchangeId=exchange:one; replyRequired=false; retryAllowed=false; replacementRequired=false.", + ], + "not-delivered", + "Message to agent:peer on Studio not delivered", + 'Ask: "Which schema?"\n\nStudio has no active participant with that id.\n\nThe exchange is closed; nothing is owed and nothing will answer it.', + ], + [ + "an exchange dropped by archiving", + "Exchange exchange:one ended because agent:peer was archived (receiver-retired).", + "exchange dropped", + [ + "The receiver will not answer this Exchange. Do not retry it.", + "Facts: replyRequired=false; retryAllowed=false; replacementRequired=false.", + ], + "exchange-dropped", + "Exchange with agent:peer dropped", + "It ended because agent:peer was archived.\n\nThe receiver will not answer this Exchange. Do not retry it.", + ], + [ + "an exchange dropped when a person lost access", + "Exchange exchange:one ended because human:priya can no longer write to your thread, so they will not answer it (receiver-retired).", + "exchange dropped", + [ + "If you still need an answer, ask someone who can write to your thread; call j5_list_participants to see who.", + "Facts: replyRequired=false; retryAllowed=false; replacementRequired=false.", + ], + "exchange-dropped", + "Exchange with human:priya dropped", + "It ended because human:priya can no longer write to your thread, so they will not answer it.\n\nIf you still need an answer, ask someone who can write to your thread; call j5_list_participants to see who.", + ], + [ + "an exchange dropped by a peer's removal", + "Exchange exchange:one ended because Studio is no longer peered (receiver-retired).", + "exchange dropped", + [ + 'It was opened by your ask "Which schema?" (message message:one).', + "The receiver will not answer this Exchange. Do not retry it.", + "Facts: replyRequired=false; retryAllowed=false; replacementRequired=false.", + ], + "exchange-dropped", + "An exchange was dropped", + 'It ended because Studio is no longer peered.\n\nIt was opened by your ask "Which schema?".\n\nThe receiver will not answer this Exchange. Do not retry it.', + ], + [ + "a withdrawn ask", + "Exchange exchange:one was withdrawn by agent:asker, who no longer needs an answer.", + "exchange withdrawn", + ["Your reply obligation has ended; do not reply to this Exchange."], + "exchange-withdrawn", + "agent:asker withdrew its ask", + "It no longer needs an answer.\n\nYour reply obligation has ended; do not reply to this Exchange.", + ], + ])("reads %s", (_name, first, type, more, kind, summary, detail) => { + const raw = [ + `[Cross-agent messaging system notice: ${type}]`, + first, + ...more, + "This is a platform-authored terminal notice, not a peer reply.", + ].join("\n\n"); + expect(presentJ5UserMessage(systemDelivery(raw))).toMatchObject({ + group: "notice", + kind, + summary, + detail, + }); + expect(detail).not.toContain("exchange:one"); + expect(detail).not.toContain("message:one"); + }); + + it("names the receiver of an undelivered message for the identity read", () => { + const raw = + "[Cross-agent messaging system notice: message not delivered]\n\nYour message m1 to agent:peer was not delivered: gone\n\nThis is a platform-authored notice, not a peer reply."; + expect(participantIdsForJ5UserMessage(systemDelivery(raw))).toEqual(["agent:peer"]); + }); + + it("leaves a terminal notice it cannot read to upstream's row", () => { + const raw = + "[Cross-agent messaging system notice: exchange dropped]\n\nFuture wording.\n\nThis is a platform-authored terminal notice, not a peer reply."; + expect(presentJ5UserMessage(systemDelivery(raw))).toBeNull(); }); it("returns null for a notice it cannot read rather than guessing", () => { @@ -509,7 +655,7 @@ describe("groups 4 and 5: classified, drawn elsewhere", () => { ).toBeNull(); }); - it("classifies Crew notices and upstream's platform messages, leaving upstream's row as is", () => { + it("classifies Crew notices and an automation run, leaving upstream's row as is", () => { const gate = [ "", "proposal_id: crew:proposal:1", @@ -528,16 +674,6 @@ describe("groups 4 and 5: classified, drawn elsewhere", () => { createdBy: "system", }), ).toMatchObject({ group: "notice", kind: "crew-context", summary: "Introduction" }); - expect( - presentJ5UserMessage({ - id: "message:restart-continuation:run-1", - role: "user", - text: "Go on.", - }), - ).toMatchObject({ group: "notice", kind: "restart-continuation" }); - expect( - presentJ5UserMessage({ id: "idle-compact:thread:run", role: "user", text: "/compact" }), - ).toMatchObject({ group: "prompt", kind: "compaction" }); const automation = { id: "message:1", role: "user", @@ -555,6 +691,137 @@ describe("groups 4 and 5: classified, drawn elsewhere", () => { }); }); +const upstreamMessage = ( + id: string, + text: string, + creationSource: "server" | "provider" | "mcp" = "server", +) => ({ id, role: "user", text, createdBy: "agent" as const, creationSource }); + +describe("upstream's platform messages", () => { + it.each([ + ["message:pr-watch:uuid", "Update on pull request #912."], + ["message:restart-continuation:run", "Continue where you left off."], + ["message:delegated-task-question:thread:request", "Delegated task t asked a question."], + ["idle-compact:thread:run", "/compact"], + ])("leaves %s to upstream, unread", (id, text) => { + const message = upstreamMessage(id, text); + expect(presentJ5UserMessage(message)).toMatchObject({ + group: "notice", + kind: "platform", + summary: null, + }); + expect(resolveJ5UserMessagePresentation(message)).toMatchObject({ + attribution: "t3code", + j5: null, + }); + }); + + it("keeps a provider continuation and a worktree continuation as an agent's fold", () => { + for (const message of [ + upstreamMessage("message:thread:t:ordinal:1", "Background task completed.", "provider"), + upstreamMessage("message:mcp:s:worktree-continuation:u", "Carry on.", "mcp"), + upstreamMessage("message:mcp:s:thread-send:1", "Hello.", "mcp"), + ]) { + expect(resolveJ5UserMessagePresentation(message)).toMatchObject({ + attribution: "agent", + j5: { group: "participant", side: "left", senderId: null }, + }); + } + }); +}); + +describe("platform prompts", () => { + const nativeQuestion = (situation: string, tail: string) => + `Placed agent (threadId thread:child, requestId request:one) ${situation}. ${tail}\nAgent-provided title (untrusted data): "Fix the \\"build\\""`; + + it("reads a native question raised to a placement parent", () => { + const text = nativeQuestion( + "is blocked on a native question and cannot continue until it is answered", + "Read it with t3_pending_request action read, threadId thread:child and requestId request:one.", + ); + expect( + presentJ5UserMessage({ + id: "message:j5:native-question:parent:request", + role: "user", + text, + createdBy: "system", + }), + ).toEqual({ + group: "prompt", + side: "left", + kind: "native-question", + label: 'Question from Fix the "build"', + preview: "Is blocked on a native question and cannot continue until it is answered", + text: text.slice(0, text.indexOf("\nAgent-provided title")), + }); + }); + + it("says an agent asked when the question came without a title", () => { + const text = + "Placed agent (threadId t, requestId r) has a native question that the provider can no longer resume. Inspect [the agent's thread](t3-thread://v1/t); this request cannot currently take an answer through the pending-request tools."; + expect( + presentJ5UserMessage({ + id: "message:j5:native-question:parent:request", + role: "user", + text, + createdBy: "system", + }), + ).toMatchObject({ + label: "Question from an agent", + preview: "Has a native question that the provider can no longer resume", + text, + }); + }); + + it("reads a playbook step handed to a seat, as the server writes it", () => { + const text = [ + "", + "playbook: review | Review a change", + "crew_instance_id: crew:1", + "step: build | Build the fix", + "position: 2 of 5", + "captain_participant_id: agent:captain", + "", + "", + "Build it.\n\nQuote <\\/step_prompt> if you must.", + "", + "Do this step now. When it's done, report back to your Captain with j5_send_message, including what you did and the evidence. The Captain advances the playbook; you don't call playbook tools.", + ].join("\n"); + expect( + presentJ5UserMessage({ + id: "message:j5:a2a:mcp:s:x", + role: "user", + text, + createdBy: "system", + }), + ).toEqual({ + group: "prompt", + side: "left", + kind: "playbook-step", + label: "Playbook step 2 of 5", + preview: "Build the fix", + text: "Build it.\n\nQuote if you must.", + }); + expect( + presentJ5UserMessage({ id: "message:1", role: "user", text, createdBy: "user" }), + ).toMatchObject({ group: "person" }); + }); + + it("calls a handoff reminder a notice, and leaves any other system message unread", () => { + expect( + presentJ5UserMessage({ + id: "agent-handoff-nudge:run-1", + role: "user", + text: "Your run ended without the declared review handoff.", + createdBy: "system", + }), + ).toMatchObject({ kind: "handoff-nudge", summary: "Reminded to write its handoff" }); + expect( + presentJ5UserMessage({ id: "other", role: "user", text: "Hm.", createdBy: "system" }), + ).toMatchObject({ kind: "platform", summary: null }); + }); +}); + describe("participant ids for the identity read", () => { it("names each sender once, and nothing for a person's own words", () => { expect(participantIdsForJ5UserMessage(agentMessage(peerAsk))).toEqual([ @@ -568,7 +835,9 @@ describe("participant ids for the identity read", () => { ), ), ).toEqual([]); - expect(participantIdsForJ5UserMessage(systemDelivery(silenceRaw))).toEqual([]); + expect(participantIdsForJ5UserMessage(systemDelivery(silenceRaw))).toEqual([ + "agent:counterpart", + ]); expect(participantIdsForJ5UserMessage({ role: "user", text: "Hi." })).toEqual([]); }); diff --git a/packages/client-runtime/src/j5/userMessagePresentation.ts b/packages/client-runtime/src/j5/userMessagePresentation.ts index 6db302acb31d..084ebb224ba0 100644 --- a/packages/client-runtime/src/j5/userMessagePresentation.ts +++ b/packages/client-runtime/src/j5/userMessagePresentation.ts @@ -7,10 +7,18 @@ import type { import { resolveUserMessagePresentation } from "../userMessage.ts"; import { + crewNoticeSummary, participantIdsForCrewNotice, presentCrewContext, presentCrewNotice, } from "./crewNotices.ts"; +import { + handoffNudgeNotice, + nativeQuestionPrompt, + parseDeliveryNotice, + playbookStepPrompt, + type PlatformNotice, +} from "./platformMessages.ts"; /** * How J5 shows a user-role message in a thread's timeline, grouped by who is speaking @@ -34,13 +42,15 @@ export type J5ParticipantTag = "automation" | "outside-agent" | "brief"; export type J5NoticeKind = | "silence" + | "not-delivered" + | "exchange-dropped" + | "exchange-withdrawn" | "crew-gate" | "crew-seats" | "crew-context" - | "restart-continuation" - | "pr-watch" + | "handoff-nudge" | "platform"; -export type J5PromptKind = "automation" | "delegated-question" | "compaction"; +export type J5PromptKind = "automation" | "playbook-step" | "native-question"; export type J5UserMessagePresentation = | { @@ -89,8 +99,15 @@ export type J5UserMessagePresentation = readonly group: "notice"; readonly side: "left"; readonly kind: J5NoticeKind; - /** One plain line, where J5 can say it; null where the notice has not been read yet. */ + /** + * One plain line, where J5 can say it; null where the notice has not been read, which leaves + * it to upstream's row. A Crew notice's seats are `crewNoticeLines`, one line each. + */ readonly summary: string | null; + /** What the line opens to; null when the summary says it all. */ + readonly detail: string | null; + /** The ids `summary` and `detail` name, for a client to replace with labels. */ + readonly participantIds: ReadonlyArray; readonly text: string; } | { @@ -98,6 +115,11 @@ export type J5UserMessagePresentation = readonly group: "prompt"; readonly side: "left"; readonly kind: J5PromptKind; + /** What kind of prompt it is, in the reader's words. */ + readonly label: string; + /** The task or step title; an automation's task title is upstream's to look up. */ + readonly preview: string; + /** What the pill opens to. */ readonly text: string; }; @@ -140,8 +162,6 @@ const REPLY_DELIVERY_INSTRUCTION_SUFFIX = '", message="...") to close the exchange. Follow-ups from the asker carrying this id join the same exchange.'; const HUMAN_DELIVERY_MARKER = "\n\nThis person is not watching this chat. They see only what you send back on this exchange.\n\n"; -const SILENCE_DELIVERY_SUFFIX = - "\n\nThis is a platform-authored delivery signal, not a peer reply."; const MACHINE_DELIVERY_INSTRUCTIONS = new Set( SEND_TOOL_NAMES.map( (tool) => @@ -279,69 +299,6 @@ function parseHumanEnvelope(text: string) { : { senderId, senderName, letter: content.slice(0, markerIndex) }; } -function counterpartSummary(counterpartId: string, suffix: string): string | null { - const counterpart = counterpartId.trim(); - return counterpart ? `${counterpart}${suffix}` : null; -} - -function parseSilenceSummary(noticeType: string, body: string): string | null { - if (noticeType === "turn-ended-no-reply") { - const neverProcessed = /^(.+?) did not start a turn for the delivered message on [^.]+\.$/.exec( - body, - ); - if (neverProcessed) - return counterpartSummary( - neverProcessed[1]!, - " did not start a turn for the delivered message", - ); - - const processed = - /^(.+?)'s turn ended without replying on [^.]+\. The latest delivered message was processed\.$/.exec( - body, - ); - return processed ? counterpartSummary(processed[1]!, "'s turn ended without replying") : null; - } - - if (noticeType === "errored") { - const match = /^(.+?) errored without replying on .+: .+$/.exec(body); - return match ? counterpartSummary(match[1]!, " errored without replying") : null; - } - - if (noticeType === "stopped/cancelled") { - const match = - /^(.+?) was (interrupted|cancelled|rolled_back) without replying on [^.]+\. .+$/.exec(body); - return match ? counterpartSummary(match[1]!, ` was ${match[2]} without replying`) : null; - } - - if (noticeType === "queued-message-removed") { - const match = /^Your message to (.+?) was removed from its queue before it ran, /.exec(body); - return match - ? counterpartSummary(match[1]!, " never read a queued message: it was removed before it ran") - : null; - } - - if (noticeType === "awaiting-human") { - const match = /^(.+?) is awaiting the human on .+ \(.+\)\.$/.exec(body); - return match ? counterpartSummary(match[1]!, " is awaiting the human") : null; - } - - if (noticeType === "blocked-on-peer") { - const match = /^(.+?) is blocked on (.+?) via .+\.$/.exec(body); - return match ? counterpartSummary(match[1]!, ` is blocked on ${match[2]!.trim()}`) : null; - } - - return null; -} - -function parseSilenceEnvelope(text: string): string | null { - const header = /^\[Cross-agent messaging system notice: ([^\]\n]+)\]\n\n/.exec(text); - if (!header || !text.endsWith(SILENCE_DELIVERY_SUFFIX)) return null; - return parseSilenceSummary( - header[1]!, - text.slice(header[0].length, -SILENCE_DELIVERY_SUFFIX.length), - ); -} - const CONTEXT_OPEN = "\n"; const CONTEXT_CLOSE = "\n\n\n"; const BRIEF_ONLY_PATTERN = /^\n([\s\S]*)\n<\/spawner_brief>$/; @@ -418,16 +375,62 @@ const BADGE_BY_EXCHANGE: Record = { plain: null, }; -// Upstream's platform messages, by the id its server gives them. An id upstream changes falls -// through to the attribution upstream's own resolver gives the message. -const UPSTREAM_NOTICE_IDS: ReadonlyArray = [ - ["message:restart-continuation:", "restart-continuation"], - ["message:pr-watch:", "pr-watch"], -]; -const UPSTREAM_PROMPT_IDS: ReadonlyArray = [ - ["message:delegated-task-question:", "delegated-question"], - ["idle-compact:", "compaction"], -]; +const noticeFrom = ( + kind: J5NoticeKind, + read: PlatformNotice, + text: string, +): J5UserMessagePresentation => ({ group: "notice", side: "left", kind, ...read, text }); + +/** J5's own platform messages outside A2A delivery; only the platform writes `system` messages. */ +function presentSystemMessage(message: J5UserMessageInput): J5UserMessagePresentation { + const text = message.text; + const crewMessage = { role: message.role, text, createdBy: message.createdBy }; + const context = presentCrewContext(crewMessage); + if (context !== null) { + return { + group: "notice", + side: "left", + kind: "crew-context", + summary: context.title, + detail: context.text, + participantIds: [], + text, + }; + } + const crew = presentCrewNotice(crewMessage); + if (crew !== null) { + return { + group: "notice", + side: "left", + kind: crew.kind === "gate" ? "crew-gate" : "crew-seats", + summary: crewNoticeSummary(crew), + detail: null, + participantIds: [], + text, + }; + } + const id = String(message.id ?? ""); + const step = playbookStepPrompt(text); + if (step !== null) return { group: "prompt", side: "left", kind: "playbook-step", ...step }; + if (id.startsWith("message:j5:native-question:")) { + const question = nativeQuestionPrompt(text); + if (question !== null) { + return { group: "prompt", side: "left", kind: "native-question", ...question }; + } + } + if (id.startsWith("agent-handoff-nudge:")) { + return noticeFrom("handoff-nudge", handoffNudgeNotice(text), text); + } + return { + group: "notice", + side: "left", + kind: "platform", + summary: null, + detail: null, + participantIds: [], + text, + }; +} /** * Classifies a user-role message by who is speaking. Null when not user-role, and for a J5 @@ -474,10 +477,10 @@ export function presentJ5UserMessage( }; } if (message.createdBy === "system") { - const summary = parseSilenceEnvelope(text); - return summary === null - ? null - : { group: "notice", side: "left", kind: "silence", summary, text }; + const read = parseDeliveryNotice(text); + if (read === null) return null; + const { kind, ...platform } = read; + return noticeFrom(kind, platform, text); } return null; } @@ -499,37 +502,31 @@ export function presentJ5UserMessage( }; } - const id = String(message.id ?? ""); - const notice = UPSTREAM_NOTICE_IDS.find(([prefix]) => id.startsWith(prefix)); - if (notice !== undefined) { - return { group: "notice", side: "left", kind: notice[1], summary: null, text }; - } - const prompt = UPSTREAM_PROMPT_IDS.find(([prefix]) => id.startsWith(prefix)); - if (prompt !== undefined) return { group: "prompt", side: "left", kind: prompt[1], text }; - - if (message.createdBy === "system") { - const context = presentCrewContext({ role: message.role, text, createdBy: message.createdBy }); - if (context !== null) { - return { group: "notice", side: "left", kind: "crew-context", summary: context.title, text }; - } - const crew = presentCrewNotice({ role: message.role, text, createdBy: message.createdBy }); - return { - group: "notice", - side: "left", - kind: crew === null ? "platform" : crew.kind === "gate" ? "crew-gate" : "crew-seats", - summary: null, - text, - }; - } + if (message.createdBy === "system") return presentSystemMessage(message); const upstream = resolveUserMessagePresentation(message); // A guest's message is upstream's to draw: its row names the guest and shows their own words. if (upstream.attribution === "guest") return null; if (upstream.attribution === "automation") { - return { group: "prompt", side: "left", kind: "automation", text: upstream.text }; + return { + group: "prompt", + side: "left", + kind: "automation", + label: "Automation", + preview: firstLine(upstream.text), + text: upstream.text, + }; } if (upstream.attribution === "t3code") { - return { group: "notice", side: "left", kind: "platform", summary: null, text }; + return { + group: "notice", + side: "left", + kind: "platform", + summary: null, + detail: null, + participantIds: [], + text, + }; } if (upstream.attribution === "agent") { return { @@ -584,5 +581,6 @@ export function participantIdsForJ5UserMessage(message: J5UserMessageInput): Rea createdBy: "system", }); } + if (j5?.group === "notice") return j5.participantIds; return []; }