diff --git a/FORK.md b/FORK.md index 9396e8ee48361..bb5006a3a31dd 100644 --- a/FORK.md +++ b/FORK.md @@ -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` mounts J5-owned `CrewRosterGate` (`apps/web/src/j5/crew/CrewRosterGate.tsx`) immediately above `ChatComposer`, outside its form so roster focus does not expand the composer: the initial roster proposal is answered inline above the Captain's composer like a planning question, while mid-run seat additions stay on the inbox bell (`crewProposals.logic.ts` decides which is which). 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; membership still waits for the platform's human roster or Inbox decision. 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 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 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; membership still waits for the platform's human roster or Inbox decision. 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/server/src/j5/a2a/AgentCrewProposalService.ts b/apps/server/src/j5/a2a/AgentCrewProposalService.ts index 9037fc4b7dc95..af25c4de14406 100644 --- a/apps/server/src/j5/a2a/AgentCrewProposalService.ts +++ b/apps/server/src/j5/a2a/AgentCrewProposalService.ts @@ -1,4 +1,9 @@ -import { ModelSelection, RuntimeMode, ThreadId } from "@t3tools/contracts"; +import { + AGENT_PERSONA_INSTRUCTIONS_MAX_LENGTH, + ModelSelection, + RuntimeMode, + ThreadId, +} from "@t3tools/contracts"; import { CrewPersonaSwap, PLAYBOOK_MAX_STEPS } from "@t3tools/contracts/j5"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -23,6 +28,8 @@ export const CrewProposalSeat = Schema.Struct({ agentId: Schema.NullOr(bounded(CREW_NAME_MAX_CHARS)), reason: bounded(CREW_REASON_MAX_CHARS), instructions: Schema.optional(bounded(CREW_TEXT_MAX_CHARS)), + /** Set only by the person's roster card, never by an agent's request: the persona's text, replaced. */ + personaInstructions: Schema.optional(bounded(AGENT_PERSONA_INSTRUCTIONS_MAX_LENGTH)), modelSelection: Schema.optional(ModelSelection), runtimeMode: Schema.optional(RuntimeMode), /** diff --git a/apps/server/src/j5/a2a/CrewLaunchService.test.ts b/apps/server/src/j5/a2a/CrewLaunchService.test.ts index 41d4ddf2bc5f6..4c54f18464564 100644 --- a/apps/server/src/j5/a2a/CrewLaunchService.test.ts +++ b/apps/server/src/j5/a2a/CrewLaunchService.test.ts @@ -1182,6 +1182,66 @@ it.effect("a full-access persona seat runs full access unless the seat overrides }).pipe(Effect.scoped), ); +it.effect("a persona seat's edited instructions replace the persona's own at launch", () => + Effect.gen(function* () { + const { context, commands, captain } = yield* fixture; + const layer = crewLaunchLayer.pipe( + Layer.provideMerge( + dependencies(commands, [ + provider("codex", "codex", [{ slug: "gpt-5.6-terra", options: ["high"] }]), + ]), + ), + Layer.provideMerge(Layer.succeedContext(context)), + Layer.provideMerge( + personaLibraryLayer("j5-edited-persona-", Object.values(BUILT_IN_AGENT_PERSONAS)), + ), + Layer.provideMerge(NodeServices.layer), + ); + yield* Effect.gen(function* () { + const launcher = yield* CrewLaunchService; + const library = yield* makeAgentPersonaLibrary; + const seat = { + name: "scout", + agentId: "scout", + reason: "Look around", + workspace: { type: "shared" as const }, + }; + const instructionsOf = (resolved: (typeof plain)[number]) => + resolveAgentPersonaRuntime( + { agentPersonaAssignment: resolved.assignment!, runtimeMode: resolved.runtimeMode }, + library, + ).pipe(Effect.map(({ agentPersonaInstructions }) => agentPersonaInstructions!)); + const plain = yield* launcher.resolveSeats(captain, [seat]); + const edited = yield* launcher.resolveSeats(captain, [ + { ...seat, personaInstructions: "Only read the README." }, + ]); + const original = BUILT_IN_AGENT_PERSONAS.scout.instructions; + assert.include(yield* instructionsOf(plain[0]!), original); + const replaced = yield* instructionsOf(edited[0]!); + assert.include(replaced, "Only read the README."); + assert.notInclude(replaced, original); + assert.equal(edited[0]!.assignment!.personaId, plain[0]!.assignment!.personaId); + assert.equal(edited[0]!.assignment!.instructionsEdited, true); + assert.notProperty(plain[0]!.assignment!, "instructionsEdited"); + assert.notEqual( + edited[0]!.assignment!.definitionDigest, + plain[0]!.assignment!.definitionDigest, + ); + // A seat with no edit resolves exactly as it always did, so its approval token is unchanged. + assert.deepStrictEqual(yield* launcher.resolveSeats(captain, [seat]), plain); + const proposal = { + id: "proposal:edit", + brief: "Look around.", + displayName: "Edit", + } as unknown as Parameters[0]; + assert.notEqual( + crewApprovalToken(proposal, captain, plain), + crewApprovalToken(proposal, captain, edited), + ); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + it.effect("refuses persona seats whose effective ACP access the harness cannot enforce", () => Effect.gen(function* () { const { context, commands, captain } = yield* fixture; diff --git a/apps/server/src/j5/a2a/CrewLaunchService.ts b/apps/server/src/j5/a2a/CrewLaunchService.ts index a426763d76c01..d1cea8264bd3b 100644 --- a/apps/server/src/j5/a2a/CrewLaunchService.ts +++ b/apps/server/src/j5/a2a/CrewLaunchService.ts @@ -22,7 +22,10 @@ import { ThreadManagementService } from "../../orchestration-v2/ThreadManagement import { ProviderRegistry } from "../../provider/ProviderRegistry.ts"; import { prepareAgentPersonaLaunch } from "../agents/agentPersonaLaunch.ts"; import { agentHandoffArtifactPath } from "../agents/agentPersonaArtifacts.ts"; -import { makeAgentPersonaLibrary } from "../agents/agentPersonaLibrary.ts"; +import { + AgentPersonaLibraryError, + makeAgentPersonaLibrary, +} from "../agents/agentPersonaLibrary.ts"; import { providerCanEnforceAgentPersonaAuthority, translateAgentPersonaProviderPolicy, @@ -69,6 +72,8 @@ export interface CrewLaunchSeat { readonly agentId: string | null; readonly reason: string | null; readonly instructions?: string | undefined; + /** Replaces the persona's own instructions for this seat; set only by the person's roster card. */ + readonly personaInstructions?: string | undefined; readonly modelSelection?: ModelSelection | undefined; readonly runtimeMode?: RuntimeMode | undefined; /** Ids of the playbook steps the seat owns; recorded on its member row. */ @@ -377,7 +382,7 @@ export const layer = Layer.effect( }); continue; } - const assignment = yield* Effect.gen(function* () { + const prepared = yield* Effect.gen(function* () { if (seat.modelSelection === undefined) { const prepared = yield* prepareAgentPersonaLaunch( { personaId: agentId }, @@ -437,6 +442,33 @@ export const layer = Layer.effect( }), ), ); + // The person's edited text runs instead of the persona's, never beside it: the seat's + // assignment points at a snapshot of the persona with that text. + const assignment = + seat.personaInstructions === undefined + ? prepared + : yield* agents.readSnapshot(prepared).pipe( + Effect.flatMap((definition) => + agents.snapshot({ ...definition, instructions: seat.personaInstructions! }), + ), + Effect.flatMap((definitionDigest) => + definitionDigest === undefined + ? Effect.fail( + new AgentPersonaLibraryError({ + message: "Persona snapshot storage is unavailable.", + }), + ) + : Effect.succeed({ ...prepared, definitionDigest, instructionsEdited: true }), + ), + Effect.mapError( + (error) => + new CrewLaunchSeatUnavailableError({ + seatName: seat.name, + agentId, + detail: error.message, + }), + ), + ); // Every seat reaching this point was approved by a human, and that approval is the // authority: explicit runtime choices override the persona sandbox while its behavior // instructions remain pinned to the original snapshot. diff --git a/apps/server/src/j5/a2a/CrewProposalService.test.ts b/apps/server/src/j5/a2a/CrewProposalService.test.ts index 817e432728cf2..95f9c366bab86 100644 --- a/apps/server/src/j5/a2a/CrewProposalService.test.ts +++ b/apps/server/src/j5/a2a/CrewProposalService.test.ts @@ -37,7 +37,11 @@ import { } from "../../orchestration-v2/ProjectionStore.ts"; import { ThreadManagementService } from "../../orchestration-v2/ThreadManagementService.ts"; import { ProviderRegistry } from "../../provider/ProviderRegistry.ts"; -import { createAgentPersonaLibrary } from "../agents/agentPersonaLibrary.ts"; +import { + createAgentPersonaLibrary, + makeAgentPersonaLibrary, +} from "../agents/agentPersonaLibrary.ts"; +import { resolveAgentPersonaRuntime } from "../agents/agentPersonaRuntime.ts"; import { BUILT_IN_AGENT_PERSONAS } from "../agents/agentPersonas.ts"; import { personaLibraryLayer } from "../test-support/personaLibrary.ts"; import { buildAgentPersonaCatalog } from "../agents/agentPersonaRouting.ts"; @@ -3163,3 +3167,82 @@ it.effect.each(["roster", "addition"] as const)( }).pipe(Effect.provide(layer)); }), ); + +it.effect( + "an approved edit replaces the persona's instructions and leaves what the agent filed alone", + () => + Effect.gen(function* () { + const { layer, commands } = yield* playbookFixture; + yield* Effect.gen(function* () { + const gate = withPreview(yield* CrewProposalService); + const library = yield* makeAgentPersonaLibrary; + const { stateDir } = yield* ServerConfig; + yield* createAgentPersonaLibrary({ + fs: yield* FileSystem.FileSystem, + path: yield* Path.Path, + stateDir, + }).createPersona({ + id: "surveyor", + displayName: "Surveyor", + description: "Looks around.", + instructions: "Survey the whole repository.", + authorityPolicy: "read-only", + modelRoute: [ + { + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.6-sol", + reasoningEffort: "high", + }, + { + driver: ProviderDriverKind.make("claudeAgent"), + model: "claude-opus-5-5", + reasoningEffort: "high", + }, + ], + }); + const filed = { + workspace: { type: "shared" as const }, + seat: "surveyor", + agentId: "surveyor", + reason: "Looks around", + }; + const request = { + requestKey: "persona-edit", + captain, + displayName: "Persona edit", + brief: "Look around.", + seats: [filed], + }; + const opened = yield* gate.propose(request); + yield* gate.resolve({ + proposalId: opened.proposal.id, + decision: "approve", + seats: [{ ...filed, personaInstructions: "Only read the README." }], + }); + + const stored = yield* (yield* AgentCrewProposalService).read(opened.proposal.id); + assert.notProperty(stored!.requestedSeats[0]!, "personaInstructions"); + assert.equal(stored!.approvedSeats![0]!.personaInstructions, "Only read the README."); + // What the agent filed still replays, whatever the person later changed. + assert.equal((yield* gate.propose(request)).proposal.id, opened.proposal.id); + + const created = (yield* Ref.get(commands)).find( + (command) => command.type === "thread.create", + ); + assert.equal(created?.type, "thread.create"); + const runtime = yield* resolveAgentPersonaRuntime( + { agentPersonaAssignment: created!.agentPersonaAssignment!, runtimeMode: "full-access" }, + library, + ); + assert.include(runtime.agentPersonaInstructions!, "Only read the README."); + assert.notInclude(runtime.agentPersonaInstructions!, "Survey the whole repository."); + const brief = (yield* Ref.get(commands)).find( + (command) => command.type === "message.dispatch", + ); + assert.notInclude( + brief?.type === "message.dispatch" ? brief.text : "", + "", + ); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); diff --git a/apps/server/src/j5/a2a/CrewProposalService.ts b/apps/server/src/j5/a2a/CrewProposalService.ts index 9be3bd48dad88..37d982360d272 100644 --- a/apps/server/src/j5/a2a/CrewProposalService.ts +++ b/apps/server/src/j5/a2a/CrewProposalService.ts @@ -64,6 +64,7 @@ const launchSeatOf = (seat: CrewProposalSeat): CrewLaunchSeat => { agentId: seat.agentId, reason: seat.reason, instructions: seat.instructions, + personaInstructions: seat.personaInstructions, modelSelection: seat.modelSelection, runtimeMode: seat.runtimeMode, steps: seat.steps, diff --git a/apps/server/src/j5/a2a/crewGateNotice.ts b/apps/server/src/j5/a2a/crewGateNotice.ts index 5f96d67592d17..0cc5dde917b04 100644 --- a/apps/server/src/j5/a2a/crewGateNotice.ts +++ b/apps/server/src/j5/a2a/crewGateNotice.ts @@ -79,7 +79,11 @@ export const crewRosterChanges = ( renamed, runtimeChanged, instructionsChanged: retained - .filter(({ previous, seat }) => previous.instructions !== seat.instructions) + .filter( + ({ previous, seat }) => + previous.instructions !== seat.instructions || + previous.personaInstructions !== seat.personaInstructions, + ) .map(({ seat }) => seat.seat), }; }; diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 7b6f4101d8d3a..22a35480b98cc 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -3482,10 +3482,6 @@ export default function ChatView(props: ChatViewProps) { } /> ) : null} - {!composerMounted ? null : ( + <> + + + ) : null } bannerItems={composerBannerItems} diff --git a/apps/web/src/j5/a2a/HumanInboxPage.tsx b/apps/web/src/j5/a2a/HumanInboxPage.tsx index e8e4687bfe7bf..87d857d6b5e14 100644 --- a/apps/web/src/j5/a2a/HumanInboxPage.tsx +++ b/apps/web/src/j5/a2a/HumanInboxPage.tsx @@ -47,6 +47,7 @@ import { answerHumanExchange } from "./humanInboxClient"; import { useScopedParticipantLabels } from "./ParticipantIdentitiesClient"; import { presentParticipantIdentity } from "@t3tools/client-runtime/j5/participant-identity"; import { CrewProposalCard } from "../crew/CrewProposalCard"; +import { clearCrewProposalDraft } from "../crew/crewProposalDraftStore"; import { CrewRuntimeRequestsSection } from "../crew/CrewRuntimeRequestsSection"; import type { ScopedCrewRuntimeRequest } from "../crew/crewRuntimeRequests.logic"; import { @@ -609,7 +610,8 @@ export function HumanInboxPage() { setResolvingProposalId(proposal.id); setError(null); const failure = await resolveInboxProposal(proposal, decision, seats, approvalToken); - if (failure !== null) setError(failure); + if (failure === null) clearCrewProposalDraft(proposal.environmentId, proposal.id); + else setError(failure); setResolvingProposalId(null); }; const openCaptain = (proposal: ScopedCrewProposal) => { diff --git a/apps/web/src/j5/crew/CrewNoticeRenderer.tsx b/apps/web/src/j5/crew/CrewNoticeRenderer.tsx index 05d0f07f3dc43..37cf0c2c47cce 100644 --- a/apps/web/src/j5/crew/CrewNoticeRenderer.tsx +++ b/apps/web/src/j5/crew/CrewNoticeRenderer.tsx @@ -12,7 +12,12 @@ import { type CrewNoticePresentation, } from "@t3tools/client-runtime/j5/crew-notices"; -import { crewGateTitle, crewNoticeLines, type CrewNoticeLine } from "./crewNotices.logic"; +import { + crewApprovalSummary, + crewGateTitle, + crewNoticeLines, + type CrewNoticeLine, +} from "./crewNotices.logic"; export interface CrewNoticeRenderInput { readonly message: CrewNoticeMessage & { @@ -139,12 +144,24 @@ function CrewNoticeLines(props: { /** * Null for anything that is not a Crew notice; the caller then falls through to its own rendering. - * A notice with no lines never reaches here: the timeline's entries leave it out. + * Approval summaries remain visible; completed finishes without a warning take no timeline row. */ export function renderCrewNotice(input: CrewNoticeRenderInput): ReactNode { const notice = presentCrewNotice(input.message); if (notice === null) return null; if (notice.kind === "gate" && notice.decision === "declined") return ; - return ; + const summary = crewApprovalSummary(notice); + return ( + <> + {summary === null ? null : ( +

+ {summary} +

+ )} + {crewNoticeLines(notice).length === 0 ? null : ( + + )} + + ); } diff --git a/apps/web/src/j5/crew/CrewProposalCard.browser.test.tsx b/apps/web/src/j5/crew/CrewProposalCard.browser.test.tsx new file mode 100644 index 0000000000000..1985acf73afbd --- /dev/null +++ b/apps/web/src/j5/crew/CrewProposalCard.browser.test.tsx @@ -0,0 +1,617 @@ +import { + EnvironmentId, + ProviderDriverKind, + ProviderInstanceId, + type ServerProvider, +} from "@t3tools/contracts"; +import type { + CrewProposal, + CrewProposalPreviewRequest, + CrewProposalPreviewResponse, +} from "@t3tools/contracts/j5"; +import { expect, it, vi } from "vite-plus/test"; + +const state = vi.hoisted(() => ({ permitted: true, preview: vi.fn(), read: vi.fn() })); +vi.mock(import("@effect/atom-react"), async (importOriginal) => ({ + ...(await importOriginal()), + useAtomValue: ((atom: unknown) => atom) as never, +})); +vi.mock("../state", () => ({ + j5Environment: { resolveCrewProposal: { permissionAtom: () => state.permitted } }, + crewProposalsQueryAtom: () => "crew-proposals", +})); +vi.mock("../a2a/ParticipantIdentitiesClient", () => ({ + useParticipantLabels: () => new Map([["captain", "Release Captain"]]), +})); +vi.mock("../sharing/access", () => ({ useCanOperateThread: () => state.permitted })); +vi.mock("../../state/query", () => ({ + useEnvironmentQuery: (query: unknown) => ({ data: query === "crew-proposals" ? [proposal] : {} }), +})); +vi.mock("../a2a/humanInboxRefresh", () => ({ notifyHumanInboxChanged: vi.fn() })); +vi.mock("@t3tools/client-runtime/j5/agent-personas", () => ({ + presentAgentPersonaCatalog: () => [ + { personaId: "sentry", displayName: "Sentry", availability: "available" }, + { personaId: "critic", displayName: "Critic", availability: "available" }, + ], +})); +vi.mock("../agents/agentPersonaAtoms", () => ({ + agentPersonaEnvironment: { catalog: () => null, readAgentPersona: {} }, +})); +vi.mock("./crewProposalsClient", () => ({ + previewCrewProposal: (...args: unknown[]) => state.preview(...args), + useCrewProposalsRefresh: () => undefined, + refreshCrewProposals: vi.fn(), + resolveCrewProposal: vi.fn(), +})); +vi.mock("../../state/server", () => ({ + serverEnvironment: { providersValueAtom: () => providers }, +})); +vi.mock("../../components/WorktreeBaseBranchPicker", () => ({ + WorktreeBaseBranchPicker: () => null, +})); +vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => state.read })); + +import { act, render } from "../../../test/render"; +import { CrewProposalCard } from "./CrewProposalCard"; +import { CrewRosterGate } from "./CrewRosterGate"; +import { clearCrewProposalDraft } from "./crewProposalDraftStore"; +import { resolveCrewProposal } from "./crewProposalsClient"; +import { ThreadId } from "@t3tools/contracts"; + +const codexProvider: ServerProvider = { + instanceId: ProviderInstanceId.make("codex"), + driver: ProviderDriverKind.make("codex"), + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-10-27T00:00:00Z", + slashCommands: [], + skills: [], + models: [ + { slug: "gpt-6", name: "GPT-6", isCustom: false, capabilities: null }, + { slug: "other-model", name: "Other model", isCustom: false, capabilities: null }, + ], +}; +const providers: ReadonlyArray = [ + codexProvider, + { + ...codexProvider, + instanceId: ProviderInstanceId.make("claude"), + driver: ProviderDriverKind.make("claudeAgent"), + models: [{ slug: "haiku", name: "Claude Haiku 5.5", isCustom: false, capabilities: null }], + }, +]; +const proposal: CrewProposal = { + id: "proposal:1", + projectId: "project:1", + captainParticipantId: "captain", + captainThreadId: "captain-thread", + crewInstanceId: null, + kind: "roster", + status: "open", + displayName: "Ship a fix", + brief: "Implement and review the fix.", + requestedSeats: [ + { seat: "builder", agentId: null, instructions: "Implement", reason: "Build the fix" }, + { seat: "reviewer", agentId: "sentry", reason: "Review independently" }, + ], + approvedSeats: null, + createdAt: "2026-10-27T00:00:00Z", + resolvedAt: null, +}; +const preview = ( + _environment: EnvironmentId, + input: CrewProposalPreviewRequest, +): Promise => + Promise.resolve({ + proposalId: input.proposalId, + workspaceOptions: { cwd: "/repo", currentBranch: "main", worktrees: [] }, + approvalToken: "token:" + JSON.stringify(input.seats), + seats: (input.seats ?? proposal.requestedSeats).map((seat) => ({ + seat: seat.seat, + provider: "OpenAI", + harness: "Codex", + model: seat.modelSelection?.model ?? "GPT-6", + reasoning: "High", + access: seat.runtimeMode === "approval-required" ? "Supervised" : "Full access", + runtimeMode: seat.runtimeMode ?? "full-access", + modelSelection: seat.modelSelection ?? { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-6", + }, + workspace: seat.workspace ?? { type: "shared" }, + })), + }); +const resolve = vi.fn(); +function setup() { + state.permitted = true; + state.preview.mockReset().mockImplementation(preview); + state.read.mockReset().mockImplementation(({ input }: { input: { personaId: string } }) => + Promise.resolve({ + _tag: "Success", + value: { definition: { instructions: `${input.personaId} default instructions` } }, + }), + ); + resolve.mockReset(); + clearCrewProposalDraft(EnvironmentId.make("test"), proposal.id); +} +const card = (overrides: Partial> = {}) => ( +
    + +
+); +const button = (label: string) => + [...document.querySelectorAll("button")].findLast( + (item) => item.getAttribute("aria-label") === label || item.textContent === label, + )!; +const option = (trigger: string, text: string) => { + const popup = document.getElementById(button(trigger).getAttribute("aria-controls")!)!; + return [...popup.querySelectorAll('[role="option"]')].find((item) => + item.textContent?.startsWith(text), + )!; +}; +const approve = () => + [...document.querySelectorAll("button")].find((item) => + item.textContent?.startsWith("Approve "), + )!; +async function click(element: HTMLElement) { + await act(async () => { + element.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true, button: 0 })); + element.dispatchEvent(new MouseEvent("pointerup", { bubbles: true, button: 0 })); + element.click(); + }); +} +async function input(label: string, value: string) { + const element = document.querySelector( + `[aria-label="${label}"]`, + )!; + await act(async () => { + const prototype = + element instanceof HTMLTextAreaElement + ? HTMLTextAreaElement.prototype + : HTMLInputElement.prototype; + Object.getOwnPropertyDescriptor(prototype, "value")!.set!.call(element, value); + element.dispatchEvent(new Event("input", { bubbles: true })); + }); +} + +it("saves modal edits atomically and preserves the Captain's reason", async () => { + setup(); + await using screen = await render(card(), { router: false }); + await click(button("Edit seat builder")); + expect(approve().disabled).toBe(true); + await input("Member instructions", "Implement carefully"); + expect(state.preview.mock.calls.at(-1)?.[1].seats[0].instructions).not.toBe( + "Implement carefully", + ); + await click(button("Save changes")); + expect(screen.container.textContent).toContain("Edited"); + await click(approve()); + expect(resolve).toHaveBeenCalledWith( + "approve", + [ + expect.objectContaining({ instructions: "Implement carefully", reason: "Build the fix" }), + proposal.requestedSeats[1], + ], + expect.stringContaining("token:"), + ); +}); + +it("Cancel discards edits without changing the approval roster", async () => { + setup(); + await using screen = await render(card(), { router: false }); + await click(button("Edit seat builder")); + await input("Member instructions", "Discard this edit"); + await click(button("Cancel")); + expect(screen.container.textContent).not.toContain("Edited"); + await click(approve()); + expect(resolve.mock.calls[0]?.[1]).toEqual(proposal.requestedSeats); +}); + +it("adds only a complete member and Cancel does not add an empty row", async () => { + setup(); + await using screen = await render(card(), { router: false }); + await click(button("Add crew member")); + expect(button("Add member").disabled).toBe(true); + await input("Member name", "tester"); + expect(button("Add member").disabled).toBe(true); + await click(button("Cancel")); + expect(approve().textContent).toBe("Approve Crew"); + await click(button("Add crew member")); + await input("Member name", "tester"); + await input("Member instructions", "Test the filters"); + await click(button("Add member")); + expect(screen.container.querySelectorAll('[data-testid^="crew-member-"]')).toHaveLength(3); + expect(approve().textContent).toBe("Approve Crew"); + await click(button("Remove seat tester")); + expect(screen.container.querySelectorAll('[data-testid^="crew-member-"]')).toHaveLength(2); + expect(approve().textContent).toBe("Approve Crew"); +}); + +it("populates persona name and instructions and uses the persona runtime defaults", async () => { + setup(); + await using _screen = await render(card(), { router: false }); + await click(button("Edit seat builder")); + await click(button("Member persona")); + await click(option("Member persona", "Sentry")); + expect(document.querySelector('[aria-label="Member name"]')?.value).toBe( + "Sentry", + ); + expect( + document.querySelector('[aria-label="Member instructions"]')?.value, + ).toBe("sentry default instructions"); + await click(button("Save changes")); + await click(approve()); + expect(resolve.mock.calls[0]?.[1][0]).toEqual({ + seat: "sentry", + agentId: "sentry", + reason: "Build the fix", + }); +}); + +it("opening a persona member preserves its name and additional instructions without duplicating defaults", async () => { + setup(); + await using _screen = await render( + card({ + proposal: { + ...proposal, + requestedSeats: [{ ...proposal.requestedSeats[1]!, instructions: "Check auth" }], + }, + }), + { router: false }, + ); + await click(button("Edit seat reviewer")); + expect(document.querySelector('[aria-label="Member name"]')?.value).toBe( + "reviewer", + ); + expect( + document.querySelector('[aria-label="Member instructions"]')?.value, + ).toBe("sentry default instructions\n\nCheck auth"); + await click(button("Save changes")); + await click(approve()); + expect(resolve.mock.calls[0]?.[1][0]).toEqual({ + ...proposal.requestedSeats[1], + instructions: "Check auth", + }); +}); + +it("ignores a late persona read after switching back to a custom member", async () => { + setup(); + let finish!: (value: unknown) => void; + state.read.mockImplementation( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + await using _screen = await render(card(), { router: false }); + await click(button("Edit seat builder")); + await click(button("Member persona")); + await click(option("Member persona", "Sentry")); + expect(button("Save changes").disabled).toBe(true); + await click(button("Member persona")); + await click(option("Member persona", "Custom member")); + await input("Member name", "custom-review"); + await input("Member instructions", "Keep this custom brief"); + await act(async () => + finish({ _tag: "Success", value: { definition: { instructions: "Late persona text" } } }), + ); + expect( + document.querySelector('[aria-label="Member instructions"]')?.value, + ).toBe("Keep this custom brief"); + await click(button("Save changes")); + await click(approve()); + expect(resolve.mock.calls[0]?.[1][0]).toEqual( + expect.objectContaining({ agentId: null, instructions: "Keep this custom brief" }), + ); +}); + +it("blocks saving a duplicate name and offers recovery after a persona read fails", async () => { + setup(); + await using _screen = await render(card(), { router: false }); + await click(button("Edit seat builder")); + await input("Member name", "reviewer"); + expect(button("Save changes").disabled).toBe(true); + expect(document.body.textContent).toContain("already exists"); + state.read.mockRejectedValueOnce(new Error("Persona unavailable")); + await click(button("Member persona")); + await click(option("Member persona", "Sentry")); + expect(document.body.textContent).toContain("Persona unavailable"); + expect(button("Save changes").disabled).toBe(true); + await click(button("Retry persona")); + expect(button("Save changes").disabled).toBe(false); +}); + +it("keeps edits and approval disabled without permission", async () => { + setup(); + state.permitted = false; + await using _screen = await render(card(), { router: false }); + expect(approve().disabled).toBe(true); + expect(button("Edit seat builder").disabled).toBe(true); + expect(button("Add crew member").disabled).toBe(true); +}); + +it("uses only a fresh full-roster token after saving a member", async () => { + setup(); + await using _screen = await render(card(), { router: false }); + await click(button("Edit seat builder")); + await input("Member instructions", "Changed brief"); + let finish!: () => void; + state.preview.mockImplementation( + (_environment: EnvironmentId, request: CrewProposalPreviewRequest) => + new Promise((resolve) => { + finish = () => { + void preview(EnvironmentId.make("test"), request).then(resolve); + }; + }), + ); + await click(button("Save changes")); + expect(approve().disabled).toBe(true); + await act(async () => finish()); + expect(approve().disabled).toBe(false); + await click(approve()); + const [decision, seats, token] = resolve.mock.calls[0]!; + expect(decision).toBe("approve"); + expect(token).toBe("token:" + JSON.stringify(seats)); +}); + +it("keeps a portalled picker inside the modal and saves its chosen model", async () => { + setup(); + await using _screen = await render(card(), { router: false }); + await click(button("Edit seat builder")); + await click(button("builder model")); + await click(option("builder model", "Other model")); + expect(button("Save changes")).toBeDefined(); + await click(button("Save changes")); + await click(approve()); + expect(resolve.mock.calls[0]?.[1][0].modelSelection.model).toBe("other-model"); +}); + +it("allows workspace repair in the modal when the full-roster preview fails", async () => { + setup(); + state.preview.mockImplementation( + (environment: EnvironmentId, request: CrewProposalPreviewRequest) => { + if (request.seats?.some((seat) => seat.workspace?.type === "existing_worktree")) + return Promise.reject(new Error("Worktree no longer exists")); + return preview(environment, request); + }, + ); + await using _screen = await render( + card({ + proposal: { + ...proposal, + requestedSeats: [ + { + ...proposal.requestedSeats[0]!, + workspace: { type: "existing_worktree", worktreePath: "/gone" }, + }, + proposal.requestedSeats[1]!, + ], + }, + }), + { router: false }, + ); + expect(approve().disabled).toBe(true); + await click(button("Edit seat builder")); + await click(button("builder workspace")); + await click(option("builder workspace", "Captain's checkout")); + await click(button("Save changes")); + expect(approve().disabled).toBe(false); + await click(approve()); + expect(resolve.mock.calls[0]?.[1][0].workspace).toEqual({ type: "shared" }); +}); + +it("Escape discards modal edits and returns focus to the member's edit control", async () => { + setup(); + await using _screen = await render(card(), { router: false }); + await click(button("Edit seat builder")); + await input("Member instructions", "Discard on escape"); + const field = document.querySelector('[aria-label="Member instructions"]')!; + await act(async () => { + field.dispatchEvent( + new KeyboardEvent("keydown", { key: "Escape", code: "Escape", bubbles: true }), + ); + }); + expect(document.querySelector('[role="dialog"]')).toBeNull(); + expect(document.activeElement).toBe(button("Edit seat builder")); + await click(approve()); + expect(resolve.mock.calls[0]?.[1]).toEqual(proposal.requestedSeats); +}); + +it("starts as a compact strip and keeps member edits when collapsed and reopened", async () => { + setup(); + await using screen = await render( + , + { router: false }, + ); + const region = () => + screen.container.querySelector('[aria-label="Crew proposal roster"]')!; + expect(button("Expand Crew proposal").getAttribute("aria-expanded")).toBe("false"); + expect(button("Expand Crew proposal").textContent).toContain("2 members"); + expect(region().hidden).toBe(true); + expect(button("Expand Crew proposal").getAttribute("aria-controls")).toBe(region().id); + await click(button("Expand Crew proposal")); + expect(region().hidden).toBe(false); + await click(button("Edit seat builder")); + await input("Member instructions", "Keep this draft when folded"); + await click(button("Save changes")); + await click(button("Collapse Crew proposal")); + expect(region().hidden).toBe(true); + await click(button("Expand Crew proposal")); + await click(button("Edit seat builder")); + expect( + document.querySelector('[aria-label="Member instructions"]')?.value, + ).toBe("Keep this draft when folded"); +}); + +it("remembers disclosure for each environment and thread when the composer remounts", async () => { + setup(); + const gate = (environment: string) => ( + + ); + await using screen = await render(gate("remember-test"), { router: false }); + await click(button("Expand Crew proposal")); + await screen.rerender(null); + await screen.rerender(gate("remember-test")); + expect(button("Collapse Crew proposal").getAttribute("aria-expanded")).toBe("true"); + await screen.rerender(gate("different-environment")); + expect(button("Expand Crew proposal").getAttribute("aria-expanded")).toBe("false"); + await screen.rerender(gate("remember-test")); + await click(button("Collapse Crew proposal")); + await screen.rerender(null); + await screen.rerender(gate("remember-test")); + expect(button("Expand Crew proposal").getAttribute("aria-expanded")).toBe("false"); +}); + +it("switches provider with its model defaults and keeps the model menu scoped to that provider", async () => { + setup(); + await using _screen = await render(card(), { router: false }); + await click(button("Edit seat builder")); + await click(button("builder provider")); + await click(option("builder provider", "Claude")); + expect(button("builder model").textContent).toContain("Haiku 5.5"); + await click(button("builder model")); + expect(option("builder model", "Other model")).toBeUndefined(); + await click(option("builder model", "Haiku 5.5")); + await click(button("Save changes")); + await click(approve()); + expect(resolve.mock.calls[0]?.[1][0].modelSelection).toEqual( + expect.objectContaining({ + instanceId: "claude", + model: "haiku", + }), + ); +}); + +it("restores saved roster edits when the card returns, for that proposal only", async () => { + setup(); + const environmentId = EnvironmentId.make("draft-restore"); + await using screen = await render(card({ environmentId }), { router: false }); + await click(button("Edit seat builder")); + await input("Member instructions", "Edited before the composer asked a question"); + await click(button("Save changes")); + await click(button("Remove seat reviewer")); + await screen.rerender(null); + + await screen.rerender(card({ environmentId })); + expect(screen.container.querySelectorAll('[data-testid^="crew-member-"]')).toHaveLength(1); + await click(approve()); + expect(resolve.mock.calls[0]?.[1]).toEqual([ + expect.objectContaining({ instructions: "Edited before the composer asked a question" }), + ]); + + await screen.rerender(null); + await screen.rerender(card({ environmentId, proposal: { ...proposal, id: "proposal:2" } })); + expect(screen.container.querySelectorAll('[data-testid^="crew-member-"]')).toHaveLength(2); + await screen.rerender(null); + await screen.rerender(card({ environmentId: EnvironmentId.make("other-draft-environment") })); + expect(screen.container.querySelectorAll('[data-testid^="crew-member-"]')).toHaveLength(2); +}); + +it("a new member added after a restore does not reuse an earlier added row", async () => { + setup(); + const environmentId = EnvironmentId.make("draft-added-rows"); + const addMember = async (name: string) => { + await click(button("Add crew member")); + await input("Member name", name); + await input("Member instructions", `${name} instructions`); + await click(button("Add member")); + }; + await using screen = await render(card({ environmentId }), { router: false }); + await addMember("first"); + await screen.rerender(null); + await screen.rerender(card({ environmentId })); + await addMember("second"); + expect(screen.container.querySelectorAll('[data-testid^="crew-member-"]')).toHaveLength(4); +}); + +it("drops a proposal's saved edits once it is approved or declined", async () => { + setup(); + const environmentId = EnvironmentId.make("draft-resolved"); + const gate = ( + + ); + await using screen = await render(gate, { router: false }); + await click(button("Expand Crew proposal")); + await click(button("Remove seat reviewer")); + await screen.rerender(null); + await screen.rerender(gate); + expect(screen.container.querySelectorAll('[data-testid^="crew-member-"]')).toHaveLength(1); + + await click(approve()); + expect(resolveCrewProposal).toHaveBeenCalledTimes(1); + await screen.rerender(null); + await screen.rerender(gate); + expect(screen.container.querySelectorAll('[data-testid^="crew-member-"]')).toHaveLength(2); +}); + +const instructionsBox = () => + document.querySelector('[aria-label="Member instructions"]')!.value; + +it("an edited persona text replaces the persona's and returns when the member is reopened", async () => { + setup(); + const environmentId = EnvironmentId.make("persona-replace"); + await using screen = await render(card({ environmentId }), { router: false }); + await click(button("Edit seat reviewer")); + expect(instructionsBox()).toBe("sentry default instructions"); + await input("Member instructions", "Only review the auth code."); + await click(button("Save changes")); + expect(screen.container.textContent).toContain("Edited"); + await screen.rerender(null); + + await screen.rerender(card({ environmentId })); + await click(button("Edit seat reviewer")); + expect(instructionsBox()).toBe("Only review the auth code."); + await click(button("Cancel")); + await click(approve()); + const seat = resolve.mock.calls[0]?.[1][1]; + expect(seat).toEqual({ + ...proposal.requestedSeats[1], + personaInstructions: "Only review the auth code.", + }); + expect(seat).not.toHaveProperty("instructions"); +}); + +it("a cleared persona text blocks Save until it is reset", async () => { + setup(); + await using _screen = await render(card(), { router: false }); + await click(button("Edit seat reviewer")); + await input("Member instructions", ""); + expect(document.body.textContent).toContain("Member instructions can't be empty"); + expect(button("Save changes")?.disabled).toBe(true); + await click(button("Reset to persona text")); + expect(document.body.textContent).not.toContain("Member instructions can't be empty"); + await click(button("Save changes")); + await click(approve()); + expect(resolve.mock.calls[0]?.[1][1]).toEqual(proposal.requestedSeats[1]); +}); + +it("Reset to persona text restores the persona's own and sends no replacement", async () => { + setup(); + await using screen = await render(card(), { router: false }); + await click(button("Edit seat reviewer")); + expect(button("Reset to persona text")).toBeUndefined(); + await input("Member instructions", "Something else entirely."); + await click(button("Reset to persona text")); + expect(instructionsBox()).toBe("sentry default instructions"); + expect(button("Reset to persona text")).toBeUndefined(); + await click(button("Save changes")); + expect(screen.container.textContent).not.toContain("Edited"); + await click(approve()); + expect(resolve.mock.calls[0]?.[1][1]).toEqual(proposal.requestedSeats[1]); +}); diff --git a/apps/web/src/j5/crew/CrewProposalCard.tsx b/apps/web/src/j5/crew/CrewProposalCard.tsx index 9b3efa8b33caf..e306c1cbf4104 100644 --- a/apps/web/src/j5/crew/CrewProposalCard.tsx +++ b/apps/web/src/j5/crew/CrewProposalCard.tsx @@ -1,60 +1,55 @@ import { useAtomValue } from "@effect/atom-react"; import { presentAgentPersonaCatalog } from "@t3tools/client-runtime/j5/agent-personas"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; -import { PencilIcon, PlusIcon, XIcon } from "lucide-react"; -import { useState } from "react"; +import { PlusIcon, UsersIcon } from "lucide-react"; +import { useId, useRef, useState } from "react"; -import { Badge } from "../../components/ui/badge"; import { Tooltip, TooltipTrigger, TooltipPopup } from "../../components/ui/tooltip"; +import { useParticipantLabels } from "../a2a/ParticipantIdentitiesClient"; import { Button } from "../../components/ui/button"; import { j5Environment } from "../state"; import { useEnvironmentQuery } from "../../state/query"; import { agentPersonaEnvironment } from "../agents/agentPersonaAtoms"; import type { CrewProposal, CrewProposalSeat } from "./crewProposalsClient"; -import { addSeat, describeSeatAgent, removeSeat, saveSeat } from "./crewProposalDraft"; +import { readCrewProposalDraft, saveCrewProposalDraft } from "./crewProposalDraftStore"; +import { crewProposalRows, crewProposalRoster, newCrewProposalRow } from "./crewProposalDraft"; import { describePersonaSwap, removedSeatSteps, stepTitle, unownedSteps } from "./crewPlaybookPlan"; -import { CrewSeatDialog } from "./CrewSeatDialog"; -import { crewSeatStopsForApprovals, describeCrewSeatWorkspace } from "./crewSeatRuntime"; -import type { CrewProposalSeatRuntime } from "@t3tools/contracts/j5"; -import { useParticipantLabels } from "../a2a/ParticipantIdentitiesClient"; +import { CrewProposalMemberDialog } from "./CrewProposalMemberDialog"; +import type { CrewProposalRow } from "./crewProposalDraft"; +import { CrewProposalMemberRow } from "./CrewProposalMemberRow"; import { useCrewProposalPreview } from "./useCrewProposalPreview"; +import { ComposerBanner } from "../../components/chat/ComposerBanner"; import { useCanOperateThread } from "../sharing/access"; -function CaptainLabel(props: { - readonly environmentId: EnvironmentId; - readonly participantId: string; -}) { +function CaptainLabel(props: { environmentId: EnvironmentId; participantId: string }) { const labels = useParticipantLabels(props.environmentId, [props.participantId]); return ( - }> - {labels.get(props.participantId) ?? "Captain"} + }> + Captain: {labels.get(props.participantId) ?? props.participantId} {props.participantId} ); } -/** - * The human gate for one Crew request. The Captain's seats arrive with reasons; the user may drop - * seats, add personas from the library or a custom seat with its own instructions, then approve the - * final roster or decline the whole request. - */ export function CrewProposalCard(props: { readonly proposal: CrewProposal; readonly environmentId: EnvironmentId | null; readonly busy: boolean; + readonly disclosure?: { + readonly expanded: boolean; + readonly contentId: string; + readonly onToggle: () => void; + }; readonly onResolve: ( decision: "approve" | "decline", seats: ReadonlyArray, approvalToken?: string, ) => void; - /** Omitted when the card already sits in the Captain's thread. */ readonly onOpenCaptain?: (() => void) | undefined; }) { const { proposal } = props; - // Resolving a roster launches or refuses agents; the command says whether this session may, - // and anyone who can write to the Captain's thread may (Shared conversations AC9). const permitted = useAtomValue( j5Environment.resolveCrewProposal.permissionAtom(props.environmentId), ); @@ -63,278 +58,290 @@ export function CrewProposalCard(props: { proposal.captainThreadId as ThreadId, ); const canResolve = permitted && writesToCaptain; - const [seats, setSeats] = useState>(proposal.requestedSeats); - const [editor, setEditor] = useState<{ - readonly seat: CrewProposalSeat | null; - readonly runtime?: CrewProposalSeatRuntime | undefined; - } | null>(null); + const [rows, setRows] = useState( + () => + readCrewProposalDraft(props.environmentId, proposal.id) ?? + crewProposalRows(proposal.requestedSeats), + ); + const changeRows = (next: typeof rows) => { + saveCrewProposalDraft(props.environmentId, proposal.id, next); + setRows(next); + }; + const [editing, setEditing] = useState(null); + const [fullBrief, setFullBrief] = useState(false); + const briefId = useId(); + const nextRow = useRef( + rows.reduce( + (next, row) => + row.id.startsWith("added:") ? Math.max(next, Number(row.id.slice(6)) + 1) : next, + 0, + ), + ); + const addButton = useRef(null); + const editorTrigger = useRef(null); const catalog = useEnvironmentQuery( props.environmentId === null ? null : agentPersonaEnvironment.catalog({ environmentId: props.environmentId, input: {} }), ); - const rows = - catalog.data === null || catalog.data === undefined + const agents = + catalog.data == null ? [] - : presentAgentPersonaCatalog(catalog.data); - const agents = rows.filter((agent) => agent.availability === "available"); - const preview = useCrewProposalPreview(props.environmentId, proposal.id, seats, props.busy); - const runtimeFor = (seat: CrewProposalSeat) => - preview.runtimeSeats?.find((row) => row.seat === seat.seat); - const stopping = seats.filter((seat) => crewSeatStopsForApprovals(seat, runtimeFor(seat))).length; - // The preview carries the plan the approval token binds; the list's copy is only a first paint. + : presentAgentPersonaCatalog(catalog.data).filter( + (agent) => agent.availability === "available", + ); + const roster = crewProposalRoster(rows); + const { seats, errors } = roster; + const preview = useCrewProposalPreview( + props.environmentId, + proposal.id, + seats, + props.busy, + errors.size === 0, + ); const playbook = preview.data?.playbook ?? proposal.playbook ?? null; const unowned = - preview.data?.unownedSteps ?? - // An addition's other steps belong to live members only the server knows about. - (proposal.kind === "roster" ? unownedSteps(playbook, seats) : []); + preview.data?.unownedSteps ?? (proposal.kind === "roster" ? unownedSteps(playbook, seats) : []); const titles = (ids: ReadonlyArray) => ids.map((id) => stepTitle(playbook, id)).join(", "); + const canApprove = + !props.busy && + canResolve && + editing === null && + rows.length > 0 && + errors.size === 0 && + preview.data !== null; return (
  • -
    -
    -
    - - - {proposal.kind === "roster" ? "New crew" : "Add a seat"} - - - {props.environmentId === null ? ( - Captain - ) : ( - - )} + {props.disclosure ? ( + } + aria-label={props.disclosure.expanded ? "Collapse Crew proposal" : "Expand Crew proposal"} + aria-expanded={props.disclosure.expanded} + aria-controls={props.disclosure.contentId} + onClick={props.disclosure.onToggle} + onPointerDown={(event) => event.preventDefault()} + > + + + + Crew proposal + + + {rows.length} {rows.length === 1 ? "member" : "members"} + + + + + ) : ( +
    +
    +

    {proposal.displayName}

    + {props.onOpenCaptain && props.environmentId !== null ? ( +
    + +
    + ) : null}
    -

    {proposal.displayName}

    -
    - {props.onOpenCaptain === undefined ? null : ( - - )} -
    - {/* The brief is context, not the decision: a clamped excerpt sits in the summary so the - seats and Approve stay in view, and the full text opens in place before approving. */} -
    - - Brief - - -

    {proposal.brief}

    -
    - {playbook === null ? null : ( -
    -

    - Follows playbook: {playbook.title} -

    - {playbook.issue === null ? null : ( -

    - {playbook.issue} -

    - )} + {props.onOpenCaptain ? ( + + ) : null}
    )} -
      - {seats.map((seat) => { - const runtime = runtimeFor(seat); - return ( - - ); - })} -
    - {playbook === null ? null : ( -
    - {removedSeatSteps(proposal.requestedSeats, seats).map(({ seat, steps }) => ( -

    - Removing {seat} leaves {titles(steps)} unowned. -

    - ))} - {unowned.length === 0 ? null : ( -

    Unowned steps, done by the Captain: {titles(unowned)}

    + + ); + })} + + {playbook === null ? null : ( +
    + {removedSeatSteps(proposal.requestedSeats, seats).map(({ seat, steps }) => ( +

    + Removing {seat} leaves {titles(steps)} unowned. +

    + ))} + {unowned.length ? ( +

    Unowned steps, done by the Captain: {titles(unowned)}

    + ) : null} +
    )} -
    - )} - - {/* Someone who cannot write to the Captain's thread, or no longer can, edits no seat. */} - {editor !== null && canResolve ? ( - setEditor(null)} - onSave={(draft) => { - const next = - editor.seat === null - ? addSeat(seats, draft) - : saveSeat(seats, editor.seat.seat, draft); - if (next.error === null) setSeats(next.seats); - return next.error; - }} - /> - ) : null} - {preview.error ? ( -
    -

    - {preview.error} -

    + {preview.error ? ( +
    +

    + {preview.error} +

    + +
    + ) : null} + +
    +
    + + +
    - ) : null} - {stopping > 0 ? ( -

    - {stopping === 1 - ? "1 seat will stop for approvals in its own thread." - : `${stopping} seats will stop for approvals in their own threads.`} -

    - ) : null} -
    - -
    + {editing && canResolve ? ( + setEditing(null)} + onSave={(value) => { + changeRows( + editing.original === null + ? [...rows, { ...editing, value }] + : rows.map((row) => (row.id === editing.id ? { ...row, value } : row)), + ); + setEditing(null); + }} + /> + ) : null}
  • ); } diff --git a/apps/web/src/j5/crew/CrewProposalMemberDialog.tsx b/apps/web/src/j5/crew/CrewProposalMemberDialog.tsx new file mode 100644 index 0000000000000..3a4c3a1ecd248 --- /dev/null +++ b/apps/web/src/j5/crew/CrewProposalMemberDialog.tsx @@ -0,0 +1,225 @@ +import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"; +import { XIcon } from "lucide-react"; +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentId } from "@t3tools/contracts"; +import type { CrewWorkspaceOptions } from "@t3tools/contracts/j5"; +import { useEffect, useEffectEvent, useState, type RefObject } from "react"; + +import { Button } from "../../components/ui/button"; +import { + Dialog, + DialogClose, + DialogFooter, + DialogPanel, + DialogPopup, +} from "../../components/ui/dialog"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { agentPersonaEnvironment } from "../agents/agentPersonaAtoms"; +import { + CUSTOM_AGENT, + crewMemberInstructions, + crewProposalRoster, + type CrewProposalRow, +} from "./crewProposalDraft"; +import { CrewSeatEditor } from "./CrewSeatEditor"; +import { chooseCrewSeatPersona, type CrewSeatDraft } from "./crewSeatRuntime"; +import { useCrewProposalPreview } from "./useCrewProposalPreview"; + +export function CrewProposalMemberDialog(props: { + row: CrewProposalRow; + returnFocus: RefObject; + rows: ReadonlyArray; + proposalId: string; + previewSeatName: string; + environmentId: EnvironmentId | null; + workspaceOptions?: CrewWorkspaceOptions | undefined; + agents: ReadonlyArray<{ personaId: string; displayName: string }>; + disabled: boolean; + onClose: () => void; + onSave: (value: CrewSeatDraft) => void; +}) { + const [value, setValue] = useState(props.row.value); + const [personaInstructions, setPersonaInstructions] = useState(null); + const [seed, setSeed] = useState[2]>(null); + const [loadedPersona, setLoadedPersona] = useState(null); + const [personaError, setPersonaError] = useState(null); + const read = useAtomCommand(agentPersonaEnvironment.readAgentPersona, { reportFailure: false }); + const personaId = value.agentId; + const custom = personaId === CUSTOM_AGENT; + const loadingPersona = !custom && loadedPersona !== personaId; + const currentDraft = useEffectEvent(() => value); + + // oxlint-disable-next-line t3code/react-effect-budget -- reads the chosen persona from the server whenever the choice changes, and drops a stale answer. + useEffect(() => { + if (custom || props.environmentId === null || personaError !== null) return; + let current = true; + const { instructions: extra, personaInstructions: edited } = currentDraft(); + void read({ environmentId: props.environmentId, input: { personaId } }).then( + (result) => { + if (!current) return; + if (result._tag === "Failure") { + const cause = squashAtomCommandFailure(result); + setPersonaError(cause instanceof Error ? cause.message : "Could not load persona."); + return; + } + const instructions = result.value.definition.instructions; + const text = edited ?? (extra ? `${instructions}\n\n${extra}` : instructions); + setPersonaInstructions(instructions); + setSeed({ text, instructions: extra, personaInstructions: edited }); + setValue((draft) => ({ ...draft, instructions: text })); + setLoadedPersona(personaId); + setPersonaError(null); + }, + (cause: unknown) => { + if (current) + setPersonaError(cause instanceof Error ? cause.message : "Could not load persona."); + }, + ); + return () => { + current = false; + }; + }, [custom, personaId, props.environmentId, read, personaError]); + + const { personaInstructions: _edited, ...rest } = value; + const saved: CrewSeatDraft = { + ...rest, + ...crewMemberInstructions(value.instructions, personaInstructions, seed), + }; + const roster = crewProposalRoster([ + ...props.rows.filter((row) => row.id !== props.row.id), + { ...props.row, value: saved }, + ]); + const error = roster.errors.get(props.row.id); + // Runtime defaults can be repaired independently of invalid names, instructions, or workspaces. + // Only the card's complete roster preview can authorize approval. + const seats = [ + { + seat: props.previewSeatName, + agentId: custom ? null : personaId, + reason: "Member runtime preview", + workspace: { type: "shared" as const }, + ...(value.modelSelection ? { modelSelection: value.modelSelection } : {}), + ...(value.runtimeMode ? { runtimeMode: value.runtimeMode } : {}), + ...(custom ? { instructions: "Crew member" } : {}), + }, + ]; + const preview = useCrewProposalPreview( + props.environmentId, + props.proposalId, + seats, + props.disabled, + ); + const runtime = preview.runtimeSeats?.[0]; + const blocked = props.disabled || loadingPersona || personaError !== null; + + return ( + { + if (!open) props.onClose(); + }} + > + +
    +
    + + {props.row.original === null ? "Add member" : "Edit member"} + + + {props.row.original === null + ? "Define a new member for the proposed Crew." + : "Update this member in the proposed Crew."} + +
    + }> + + +
    + + undefined} + onPersonaChange={(agentId) => { + setPersonaInstructions(null); + setSeed(null); + setLoadedPersona(null); + setPersonaError(null); + const agent = props.agents.find((agent) => agent.personaId === agentId); + setValue((draft) => ({ + ...chooseCrewSeatPersona(draft, agentId), + ...(agent ? { seat: agent.displayName, instructions: "" } : {}), + })); + }} + /> + {personaInstructions !== null && + value.instructions.trim() !== personaInstructions.trim() ? ( + + ) : null} + {loadingPersona && !personaError ? ( +

    + Loading persona instructions… +

    + ) : null} + {personaError ? ( +
    +

    + {personaError} +

    + +
    + ) : null} + {error ? ( +

    + {error} +

    + ) : null} + {preview.error ? ( +

    + {preview.error} +

    + ) : null} +
    + +

    + Changes apply to the proposal. Nobody starts yet. +

    + + +
    +
    +
    + ); +} diff --git a/apps/web/src/j5/crew/CrewProposalMemberRow.tsx b/apps/web/src/j5/crew/CrewProposalMemberRow.tsx new file mode 100644 index 0000000000000..6f09b933e1e92 --- /dev/null +++ b/apps/web/src/j5/crew/CrewProposalMemberRow.tsx @@ -0,0 +1,135 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { EnvironmentId } from "@t3tools/contracts"; +import type { CrewProposalSeatRuntime } from "@t3tools/contracts/j5"; +import { PencilIcon, Trash2Icon } from "lucide-react"; +import { type ReactNode } from "react"; + +import { ProviderInstanceIcon } from "../../components/chat/ProviderInstanceIcon"; +import { Tooltip, TooltipTrigger, TooltipPopup } from "../../components/ui/tooltip"; +import { Button } from "../../components/ui/button"; +import { serverEnvironment } from "../../state/server"; +import { deriveProviderInstanceEntries } from "../../providerInstances"; +import { CUSTOM_AGENT, crewProposalRowChange, type CrewProposalRow } from "./crewProposalDraft"; +import { crewSeatStopsForApprovals, describeCrewSeatWorkspace } from "./crewSeatRuntime"; + +function MemberProvider(props: { + environmentId: EnvironmentId; + runtime?: CrewProposalSeatRuntime | undefined; +}) { + const providers = useAtomValue(serverEnvironment.providersValueAtom(props.environmentId)) ?? []; + const entry = deriveProviderInstanceEntries(providers).find( + (provider) => provider.instanceId === props.runtime?.modelSelection.instanceId, + ); + return entry ? ( + + + } + > + + + {entry.displayName} + + ) : ( + + ); +} + +export function CrewProposalMemberRow(props: { + readonly row: CrewProposalRow; + readonly environmentId: EnvironmentId | null; + readonly runtime?: CrewProposalSeatRuntime | undefined; + readonly disabled: boolean; + readonly canRemove: boolean; + readonly runtimeLoading: boolean; + readonly error?: string | undefined; + readonly children?: ReactNode; + readonly onOpen: (trigger: HTMLButtonElement) => void; + readonly onRemove: () => void; +}) { + const { row, runtime } = props; + const change = crewProposalRowChange(row); + const seat = { + agentId: row.value.agentId === CUSTOM_AGENT ? null : row.value.agentId, + runtimeMode: row.value.runtimeMode, + }; + return ( +
  • +
    + {props.environmentId === null ? null : ( + + )} +
    +
    +
    +

    + {row.value.seat + ? row.value.seat[0]!.toUpperCase() + row.value.seat.slice(1) + : "New member"} +

    + + {runtime + ? [runtime.model.replace(/^Claude\s+/u, ""), runtime.reasoning, runtime.access].join( + " · ", + ) + : props.runtimeLoading + ? "Resolving runtime…" + : "Runtime unavailable"} + + {change ? {change} : null} +
    +

    + {row.original?.reason ?? "Added by the user"} +

    + {runtime?.workspace && runtime.workspace.type !== "shared" ? ( +

    + {describeCrewSeatWorkspace(runtime.workspace)} +

    + ) : null} + {crewSeatStopsForApprovals(seat, runtime) ? ( +

    Asks for approvals

    + ) : null} + {props.children} + {props.error ? ( +

    + {props.error} +

    + ) : null} +
    +
    + + +
    +
  • + ); +} diff --git a/apps/web/src/j5/crew/CrewRosterGate.tsx b/apps/web/src/j5/crew/CrewRosterGate.tsx index 9b30ce717b915..819b2a93ddf59 100644 --- a/apps/web/src/j5/crew/CrewRosterGate.tsx +++ b/apps/web/src/j5/crew/CrewRosterGate.tsx @@ -1,10 +1,12 @@ import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; -import { useState } from "react"; +import { useId, useState } from "react"; +import { ComposerBanner } from "../../components/chat/ComposerBanner"; import { useEnvironmentQuery } from "../../state/query"; import { notifyHumanInboxChanged } from "../a2a/humanInboxRefresh"; import { crewProposalsQueryAtom } from "../state"; import { CrewProposalCard } from "./CrewProposalCard"; +import { clearCrewProposalDraft } from "./crewProposalDraftStore"; import { rosterGatesForThread } from "./crewProposals.logic"; import { refreshCrewProposals, @@ -14,11 +16,8 @@ import { type CrewProposalSeat, } from "./crewProposalsClient"; -/** - * The Captain's roster proposal, answered where it was asked: above the composer of the thread - * that launched the crew, like a planning question. Reads the thread's own environment and shares - * the crew-gate read with the bell, so ordinary threads pay nothing extra. - */ +const proposalViews = new Map(); + export function CrewRosterGate(props: { readonly environmentId: EnvironmentId | undefined; readonly threadId: ThreadId | null | undefined; @@ -28,6 +27,9 @@ export function CrewRosterGate(props: { environmentId !== undefined && threadId != null ? crewProposalsQueryAtom(environmentId) : null, ); useCrewProposalsRefresh(); + const viewKey = JSON.stringify([environmentId, threadId]); + const [expanded, setExpanded] = useState(() => proposalViews.get(viewKey) ?? false); + const contentId = useId(); const [busyId, setBusyId] = useState(null); const [error, setError] = useState(null); @@ -52,6 +54,7 @@ export function CrewRosterGate(props: { ? { proposalId: proposal.id, decision, seats, approvalToken: approvalToken! } : { proposalId: proposal.id, decision }, ); + clearCrewProposalDraft(environmentId, proposal.id); notifyHumanInboxChanged(environmentId); await refreshCrewProposals(environmentId).catch(() => undefined); } catch (cause) { @@ -63,28 +66,36 @@ export function CrewRosterGate(props: { const gates = rosterGatesForThread(query.data ?? [], threadId); if (gates.length === 0 || environmentId === undefined) return null; return ( -
    - {error ? ( -

    - {error} -

    - ) : null} -
      - {gates.map((proposal) => ( - - void resolve(proposal, decision, seats, approvalToken) - } - /> - ))} -
    -
    + + + {error ? ( +

    + {error} +

    + ) : null} +
      + {gates.map((proposal) => ( + { + const next = !expanded; + proposalViews.set(viewKey, next); + setExpanded(next); + }, + }} + onResolve={(decision, seats, approvalToken) => + void resolve(proposal, decision, seats, approvalToken) + } + /> + ))} +
    +
    +
    ); } diff --git a/apps/web/src/j5/crew/CrewSeatDialog.browser.test.tsx b/apps/web/src/j5/crew/CrewSeatDialog.browser.test.tsx deleted file mode 100644 index d3eb35cb47d84..0000000000000 --- a/apps/web/src/j5/crew/CrewSeatDialog.browser.test.tsx +++ /dev/null @@ -1,285 +0,0 @@ -import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts"; -import type { CrewProposalSeatRuntime } from "@t3tools/contracts/j5"; -import type { ComponentProps } from "react"; -import { describe, expect, it, vi } from "vite-plus/test"; -import { page } from "vite-plus/test/browser"; - -const editorState = vi.hoisted(() => ({ props: null as unknown })); - -vi.mock(import("./crewProposalsClient"), async (importOriginal) => ({ - ...(await importOriginal()), - previewCrewProposal: vi.fn(), -})); -// The dialog owns the draft; the editor only reports changes, so tests drive it through its props. -vi.mock(import("./CrewSeatEditor"), async (importOriginal) => ({ - ...(await importOriginal()), - CrewSeatEditor: ((props: unknown) => { - editorState.props = props; - return null; - }) as never, -})); - -import { act, render } from "../../../test/render"; -import { CrewSeatDialog } from "./CrewSeatDialog"; -import type { CrewSeatEditor } from "./CrewSeatEditor"; -import { previewCrewProposal } from "./crewProposalsClient"; -import { chooseCrewSeatPersona, resolvedCrewSeatDraft } from "./crewSeatRuntime"; -import { addSeat, saveSeat } from "./crewProposalDraft"; - -const seat = { - seat: "reviewer", - agentId: null, - reason: "Review", - instructions: "Review the patch", -}; -const runtime: CrewProposalSeatRuntime = { - workspace: { type: "shared" }, - seat: "reviewer", - provider: "OpenAI", - harness: "Codex", - model: "GPT-6-Astra", - reasoning: "High", - access: "Full access", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-6-astra", - options: [{ id: "reasoningEffort", value: "high" }], - }, - runtimeMode: "full-access", -}; -function setup() { - editorState.props = null; - vi.mocked(previewCrewProposal).mockReset(); -} - -const editor = () => editorState.props as ComponentProps; -const change = (value: ComponentProps["value"]) => - act(() => editor().onChange(value)); -// Dispatched directly: Playwright's click waits for the popup's open animation to settle. -const click = (name: string) => - act(() => (page.getByRole("button", { name, exact: true }).element() as HTMLElement).click()); -const submit = (name: "Save changes" | "Add member" = "Save changes") => click(name); - -describe("crew member dialog draft lifecycle", () => { - it("keeps runtime changes local and discards them when cancelled", async () => { - setup(); - const onSave = vi.fn(); - const onClose = vi.fn(); - await using _screen = await render( - , - ); - expect(editor().value.modelSelection).toEqual(runtime.modelSelection); - await change({ - ...editor().value, - runtimeMode: "approval-required", - instructions: "Unsaved edits", - }); - expect(editor().value.instructions).toBe("Unsaved edits"); - expect(onSave).not.toHaveBeenCalled(); - expect(seat.instructions).toBe("Review the patch"); - await click("Cancel"); - expect(onClose).toHaveBeenCalledOnce(); - expect(onSave).not.toHaveBeenCalled(); - }); - - it("leaves invalid edits open, then publishes one validated roster update on Save", async () => { - setup(); - const onClose = vi.fn(); - const onSave = vi.fn((draft) => saveSeat([seat], seat.seat, draft).error); - await using _screen = await render( - , - ); - await change({ ...editor().value, instructions: "" }); - await submit(); - expect(onClose).not.toHaveBeenCalled(); - expect(document.querySelector('[role="alert"]')?.textContent).toContain("instructions"); - await change({ - ...editor().value, - instructions: "Check authentication", - runtimeMode: "approval-required", - }); - await submit(); - expect(onClose).toHaveBeenCalledOnce(); - expect(onSave).toHaveBeenLastCalledWith( - expect.objectContaining({ - instructions: "Check authentication", - modelSelection: runtime.modelSelection, - runtimeMode: "approval-required", - }), - ); - }); - - it("prefills a proposed saved persona and saves its edited runtime without changing its identity", async () => { - setup(); - const saved = { ...seat, agentId: "sentry" }; - let roster = [saved]; - await using _screen = await render( - {}} - onSave={(draft) => { - const result = saveSeat(roster, saved.seat, draft); - roster = result.seats as typeof roster; - return result.error; - }} - />, - ); - await change({ - ...resolvedCrewSeatDraft(editor().value, editor().runtime), - runtimeMode: "approval-required", - }); - expect(roster[0]).toEqual(saved); - await submit(); - expect(roster[0]).toEqual({ - ...saved, - modelSelection: runtime.modelSelection, - runtimeMode: "approval-required", - }); - }); - - it("keeps persona defaults when saving only instructions", async () => { - setup(); - const onSave = vi.fn( - (_draft: Parameters["onSave"]>[0]) => null, - ); - await using _screen = await render( - {}} - onSave={onSave} - />, - ); - await change({ ...editor().value, instructions: "Check auth" }); - await submit(); - expect(onSave.mock.calls[0]?.[0]).not.toHaveProperty("modelSelection"); - expect(onSave.mock.calls[0]?.[0]).not.toHaveProperty("runtimeMode"); - }); - - it("loads a manually selected persona's defaults and ignores an older response", async () => { - setup(); - const pending: Array<(value: Awaited>) => void> = []; - vi.mocked(previewCrewProposal).mockImplementation( - () => new Promise((resolve) => pending.push(resolve)), - ); - const onSave = vi.fn((draft) => addSeat([], draft).error); - await using _screen = await render( - {}} - onSave={onSave} - />, - ); - await change(chooseCrewSeatPersona({ ...editor().value, seat: "manual" }, "sentry")); - await act(async () => - pending[0]!({ - workspaceOptions: { - currentBranch: "main", - cwd: "/repo", - worktrees: [], - }, - proposalId: "proposal:1", - approvalToken: "old", - seats: [{ ...runtime, model: "Wrong custom default" }], - }), - ); - expect(editor().runtime).toBeUndefined(); - await act(async () => - pending[1]!({ - workspaceOptions: { - currentBranch: "main", - cwd: "/repo", - worktrees: [], - }, - proposalId: "proposal:1", - approvalToken: "new", - seats: [runtime], - }), - ); - expect(editor().runtime).toEqual(runtime); - await change({ - ...resolvedCrewSeatDraft(editor().value, editor().runtime), - runtimeMode: "approval-required", - }); - await submit("Add member"); - expect(onSave).toHaveBeenCalledWith( - expect.objectContaining({ - agentId: "sentry", - modelSelection: runtime.modelSelection, - runtimeMode: "approval-required", - }), - ); - }); - - it("starts additions as custom and requires a valid name before publishing", async () => { - setup(); - const onClose = vi.fn(); - const onSave = vi.fn((draft) => addSeat([seat], draft).error); - await using _screen = await render( - , - ); - await change({ - ...editor().value, - instructions: "Review security", - modelSelection: runtime.modelSelection, - runtimeMode: "approval-required", - }); - await submit("Add member"); - expect(onClose).not.toHaveBeenCalled(); - await change({ ...editor().value, seat: "security" }); - await submit("Add member"); - expect(onClose).toHaveBeenCalledOnce(); - expect(onSave).toHaveBeenLastCalledWith( - expect.objectContaining({ - seat: "security", - modelSelection: runtime.modelSelection, - runtimeMode: "approval-required", - }), - ); - }); -}); diff --git a/apps/web/src/j5/crew/CrewSeatDialog.tsx b/apps/web/src/j5/crew/CrewSeatDialog.tsx deleted file mode 100644 index 72e6e5a7d16dc..0000000000000 --- a/apps/web/src/j5/crew/CrewSeatDialog.tsx +++ /dev/null @@ -1,158 +0,0 @@ -import type { EnvironmentId } from "@t3tools/contracts"; -import type { - CrewProposalSeat, - CrewProposalSeatRuntime, - CrewWorkspaceOptions, -} from "@t3tools/contracts/j5"; -import { useState } from "react"; - -import { Button } from "../../components/ui/button"; -import { - Dialog, - DialogDescription, - DialogFooter, - DialogHeader, - DialogPanel, - DialogPopup, - DialogTitle, -} from "../../components/ui/dialog"; -import { useCrewProposalPreview } from "./useCrewProposalPreview"; -import { CUSTOM_AGENT } from "./crewProposalDraft"; -import { CrewSeatEditor } from "./CrewSeatEditor"; -import { crewSeatDraft, resolvedCrewSeatDraft, type CrewSeatDraft } from "./crewSeatRuntime"; - -/** Local drafts are published only by Save/Add; closing the dialog leaves approval unchanged. */ -export function CrewSeatDialog(props: { - readonly seat: CrewProposalSeat | null; - readonly proposalId: string; - readonly previewSeatName: string; - readonly runtime?: CrewProposalSeatRuntime | undefined; - /** What the Captain's repository offers a seat's workspace, from the roster's preview. */ - readonly workspaceOptions?: CrewWorkspaceOptions | undefined; - readonly environmentId: EnvironmentId | null; - readonly agents: ReadonlyArray<{ readonly personaId: string; readonly displayName: string }>; - readonly disabled: boolean; - readonly onSave: (draft: CrewSeatDraft) => string | null; - readonly onClose: () => void; -}) { - const [draft, setDraft] = useState(() => { - if (props.seat === null) - return { - seat: "", - agentId: CUSTOM_AGENT, - instructions: "", - // A seat the person adds starts in the Captain's checkout. - workspace: { type: "shared" }, - }; - const initial = crewSeatDraft(props.seat); - return props.seat.agentId === null ? resolvedCrewSeatDraft(initial, props.runtime) : initial; - }); - const [error, setError] = useState(null); - const originalRuntime = - props.seat !== null && draft.agentId === (props.seat.agentId ?? CUSTOM_AGENT) - ? props.runtime - : undefined; - // Resolve persona defaults before editing a new selection. This does not save the draft or - // authorize approval; the full roster gets a fresh preview when the user saves the member. - const previewSeats = [ - { - seat: props.previewSeatName, - agentId: draft.agentId === CUSTOM_AGENT ? null : draft.agentId, - reason: "Member runtime preview", - workspace: { type: "shared" as const }, - ...(draft.agentId === CUSTOM_AGENT ? { instructions: "Crew member" } : {}), - }, - ]; - const preview = useCrewProposalPreview( - props.environmentId, - props.proposalId, - previewSeats, - props.disabled || originalRuntime !== undefined, - ); - const matchingRuntime = originalRuntime ?? preview.data?.seats[0]; - const adding = props.seat === null; - return ( - { - if (!open && !props.disabled) props.onClose(); - }} - > - -
    { - event.preventDefault(); - if (props.disabled) return; - const nextError = props.onSave(draft); - setError(nextError); - if (nextError === null) props.onClose(); - }} - > - - {adding ? "Add crew member" : `Edit ${props.seat!.seat}`} - - {adding - ? "Choose a saved persona or configure a custom crew member." - : "Update this member’s instructions and runtime settings."}{" "} - Runtime settings are checked before you approve the crew. - - - - {/* The Captain's reason is why this seat exists. It is read here, never edited: the - roster keeps the original reason when the member is saved (see saveSeat). */} - {props.seat?.reason ? ( -

    - Reason{" "} - {props.seat.reason} -

    - ) : null} - - {originalRuntime === undefined && preview.error ? ( -
    -

    - {preview.error} -

    - -
    - ) : null} - {error ? ( -

    - {error} -

    - ) : null} -
    - - - - -
    -
    -
    - ); -} diff --git a/apps/web/src/j5/crew/CrewSeatEditor.tsx b/apps/web/src/j5/crew/CrewSeatEditor.tsx index 13aa20f2a659d..9af351395ae59 100644 --- a/apps/web/src/j5/crew/CrewSeatEditor.tsx +++ b/apps/web/src/j5/crew/CrewSeatEditor.tsx @@ -13,19 +13,18 @@ import { SelectValue, } from "../../components/ui/select"; import { Textarea } from "../../components/ui/textarea"; -import { formatProviderDriverKindLabel } from "../../providerModels"; +import { ProviderInstanceIcon } from "../../components/chat/ProviderInstanceIcon"; +import { deriveProviderInstanceEntries } from "../../providerInstances"; import { serverEnvironment } from "../../state/server"; import { CUSTOM_AGENT, describeSeatAgent } from "./crewProposalDraft"; import { CREW_ACCESS_OPTIONS, CREW_WORKSPACE_OPTIONS, - chooseCrewSeatPersona, chooseCrewSeatWorkspace, setCrewSeatBaseRef, setCrewSeatStartFromOrigin, setCrewSeatWorktree, chooseCrewHarness, - crewModelSelection, crewReasoningDescriptor, resolvedCrewSeatDraft, setCrewReasoning, @@ -40,7 +39,9 @@ interface CrewSeatEditorProps { /** What the Captain's repository offers a seat's workspace, from the latest preview. */ readonly workspaceOptions?: CrewWorkspaceOptions | undefined; readonly disabled: boolean; - readonly existing?: boolean; + readonly loadingInstructions?: boolean; + readonly onPersonaChange: (personaId: string) => void; + readonly onMenuOpenChange: (open: boolean) => void; readonly onChange: (value: CrewSeatDraft) => void; } @@ -48,40 +49,38 @@ interface CrewSeatEditorProps { export function CrewSeatEditor(props: CrewSeatEditorProps) { const { value, disabled } = props; const custom = value.agentId === CUSTOM_AGENT; - const changeInstructions = (instructions: string) => - props.onChange({ - ...value, - instructions, - }); return ( -
    -
    -