> For the complete documentation index, see [llms.txt](https://faction-os.gitbook.io/faction-os-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://faction-os.gitbook.io/faction-os-docs/.spec_system/archive/sessions/phase03-session05-web-orchestration-cockpit-controls/spec.md).

# Session Specification

**Session ID**: `phase03-session05-web-orchestration-cockpit-controls` **Phase**: 03 - Agent Orchestration **Status**: Complete **Created**: 2026-05-29 **Package**: Cross-cutting (`apps/web`, `apps/server`, `packages/protocol`) **Package Stack**: React 18, Vite, TypeScript, Zustand, Express, WebSocket, protocol contracts, Vitest, Playwright

***

## 1. Session Overview

This session exposes the Phase 03 local orchestration runtime inside the web cockpit. Sessions 02, 03, and 04 already shipped local task queue, agent template, subagent lineage, mission graph, and guarded-action contracts in protocol and server code; this session makes those states inspectable and actionable from `apps/web` without implying hosted queues, War Room federation, inbound chat commands, analytics, public replay hosting, or remote execution.

The work adds web state, copy helpers, REST helpers, WebSocket reducers, and cockpit UI for queue inspection, local agent templates, lineage/mission graph context, and guarded-action decisions. The UI must preserve current cockpit density, selection synchronization, local-first privacy boundaries, keyboard/pointer access, and explicit loading, empty, disconnected, unavailable, expired, rejected, failed, and accepted states.

The session is next because the analyzer reports Phase 03 Sessions 01-04 complete, and Session 05 is the first incomplete Phase 03 candidate. It unlocks Session 06 CLI diagnostics and Session 07 validation by giving the browser surface a concrete local orchestration view that can be tested and documented.

***

## 2. Objectives

1. Hydrate and reduce local task queue, agent template, subagent lineage, mission graph, and guarded-action update frames in the web store.
2. Add cockpit orchestration controls that expose queue, template, lineage, and guarded-action states with accessible controls and explicit fallback states.
3. Allow guarded-action approve and reject decisions from the cockpit with duplicate-trigger prevention, revision checks, bounded failure copy, and local auth headers.
4. Preserve local-first privacy by redacting broad UI copy and avoiding hosted, War Room, inbound-command, public-sharing, analytics, or remote-execution claims.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase03-session02-task-queue-and-agent-template-contracts` - provides task queue and agent template protocol, REST, and WebSocket contracts.
* [x] `phase03-session03-subagent-lineage-and-mission-graph-runtime` - provides subagent lineage and mission graph contracts and runtime frames.
* [x] `phase03-session04-guarded-local-action-runtime` - provides guarded-action contracts, REST routes, WebSocket decision handling, and unavailable result states.
* [x] `phase02-session02-cockpit-shell-and-navigation-cohesion` - provides shell surface metadata and fallback-state patterns.
* [x] `phase02-session03-hero-and-mission-workflow-completion` - provides shared hero and mission selection actions.

### Required Tools/Knowledge

* Node 20+, npm workspaces, TypeScript, React 18, Vite, Zustand, Tailwind, Express, WebSocket, Biome, Vitest, Testing Library, and Playwright.
* Existing web state patterns in `apps/web/src/store/useGameStore.ts` and `apps/web/src/store/useWsClient.ts`.
* Existing shell and component patterns in `apps/web/src/App.tsx`, `apps/web/src/lib/cockpitShell.ts`, `apps/web/src/components/PermissionModal.tsx`, and `apps/web/src/components/PlanWorkpad.tsx`.
* Existing protocol contracts in `packages/protocol/src/taskQueue.ts`, `packages/protocol/src/agentTemplates.ts`, `packages/protocol/src/lineage.ts`, `packages/protocol/src/guardedActions.ts`, and `packages/protocol/src/events.ts`.
* Existing server hydration and WebSocket patterns in `apps/server/src/server.ts` and `apps/server/src/ws/handlers.ts`.

### Environment Requirements

* No hosted service credentials are required.
* The local server remains loopback-first and inherits existing auth, CORS, Origin, rate-limit, and body-size defaults.
* Historical `EXAMPLES/` material remains evidence only and must not be copied into UI copy, fixtures, docs, or test snapshots.

***

## 4. Scope

### In Scope (MVP)

* Operators can inspect local queue state and task counts from the cockpit - implement queue summaries, bounded entry rows, unavailable/failed/rejected states, and selected hero/mission references.
* Operators can inspect source-owned local agent templates - show role, tags, local-only constraints, empty/unavailable states, and template suggestion context without historical template bodies.
* Operators can inspect subagent lineage and mission graph context - show parent-child mission relationships, degraded states, and missing-reference fallbacks while keeping transcript-derived identifiers bounded.
* Operators can approve or reject guarded-action proposals from the cockpit - disable duplicate decisions, preserve revision/idempotency metadata, and show pending, approved, rejected, expired, unavailable, and failed states.
* The web store can consume Phase 03 orchestration frames - handle task queue, agent template, lineage, mission graph, and guarded-action updates without breaking replay, export, notification, or settings privacy boundaries.
* The local server can hydrate orchestration state on WebSocket connect - send compact queue, template, mission graph, and guarded-action snapshots without raw prompts, commands, terminal output, tokens, file contents, or broad absolute paths.
* Tests cover reducers, copy helpers, controls, duplicate decisions, disconnected states, and responsive browser smoke paths.

### Out of Scope (Deferred)

* War Room web-to-Worker federation - *Reason: Phase 05 owns Worker room integration and trust boundaries.*
* Hosted queues, shared queues, hosted identity, hosted persistence, analytics dashboards, or public replay hosting - *Reason: Phase 03 remains local-first and non-hosted.*
* Inbound chat or webhook command controls - *Reason: adapters remain outbound-only until a separate permission and audit model exists.*
* Hidden file, git, terminal, remote, Docker, or container execution - *Reason: current guarded actions are explicit local proposals and approved actions fail closed when no safe executor exists.*
* Public demo orchestration controls - *Reason: the demo stays synthetic and no-build unless a later session approves limited copy-only changes.*
* CLI diagnostics or recovery commands - *Reason: Session 06 owns CLI and hook diagnostics after the web surface lands.*

***

## 5. Technical Approach

### Architecture

Keep protocol-owned types as the source of truth. `apps/web` should import queue, template, lineage, mission graph, guarded-action, and event types from `@factionos/protocol` instead of duplicating contracts. Any web-specific view models should live in helper files and preserve exhaustive handling of protocol state enums.

Extend the server WebSocket attach path to hydrate compact orchestration snapshots for queue, templates, mission graph, and guarded actions. This gives the browser an initial local state without requiring hosted persistence or broad raw payload transfer. Hydration frames must use the same compact event shapes already emitted by mutation paths.

In `apps/web`, add store fields and reducers for orchestration snapshots, selected queue/action/lineage context, and in-flight guarded-action decisions. Add REST helpers for initial fetches and guarded-action decisions that use the existing local auth helper, bounded timeouts where practical, compact error mapping, and no raw payload echo in toasts.

Add a cockpit orchestration panel as a dense operational surface, not a marketing page. It should fit within the existing shell, use native controls, preserve keyboard access, expose visible state chips and captions, and keep hero/mission selection synchronized through existing store actions. The panel should show disconnected and empty states clearly when no server or orchestration data is available.

### Design Patterns

* Protocol-first consumption: web state and UI import shared protocol types and keep local view models helper-owned.
* Snapshot plus live updates: initial HTTP/WebSocket hydration establishes state; live frames patch compact state afterward.
* Boundary copy helpers: sensitive or unavailable states map through tested copy helpers rather than raw server messages.
* Duplicate decision guard: guarded-action decisions track local in-flight IDs and ignore or disable repeated approve/reject triggers.
* Selection synchronization: queue, lineage, and guarded-action references call existing hero and mission openers instead of duplicating selection logic.

### Technology Stack

* TypeScript 5.9, React 18, Vite, Tailwind, and Zustand in `apps/web`.
* Express and `ws` in `apps/server`.
* Shared protocol contracts in `packages/protocol`.
* Vitest, Testing Library, Playwright, Biome, and package-local TypeScript checks.

***

## 6. Deliverables

### Files to Create

| File                                             | Purpose                                                                                                              | Est. Lines |
| ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- | ---------- |
| `apps/web/src/lib/orchestrationApi.ts`           | Local REST helpers for queue, template, guarded-action snapshots, decisions, auth headers, and bounded error mapping | \~180      |
| `apps/web/src/lib/orchestrationUi.ts`            | View-model and copy helpers for queue, templates, lineage, guarded actions, privacy, and status tones                | \~260      |
| `apps/web/src/components/OrchestrationPanel.tsx` | Cockpit panel for task queue, templates, lineage, and guarded-action decisions                                       | \~360      |
| `apps/web/tests/orchestrationUi.test.ts`         | Unit tests for copy helpers, state mapping, privacy boundaries, and enum coverage                                    | \~180      |
| `apps/web/tests/OrchestrationPanel.test.tsx`     | Component tests for visible states, selection sync, decisions, duplicate-trigger prevention, and accessibility names | \~260      |
| `apps/web/tests/orchestrationStore.test.ts`      | Store reducer tests for Phase 03 orchestration WebSocket frames and replay-safe behavior                             | \~180      |

### Files to Modify

| File                                                                                              | Changes                                                                                                                       | Est. Lines |
| ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `apps/server/src/ws/handlers.ts`                                                                  | Send compact orchestration hydration frames on WebSocket connect                                                              | \~80       |
| `apps/server/src/server.ts`                                                                       | Pass task queue, agent template, and mission graph managers into WebSocket handlers                                           | \~20       |
| `apps/server/tests/websocket.test.ts`                                                             | Cover initial orchestration hydration and compact sensitive-field boundaries                                                  | \~120      |
| `apps/web/src/store/useGameStore.ts`                                                              | Add orchestration snapshots, selected references, guarded-action decision state, and event reducers                           | \~220      |
| `apps/web/src/store/useWsClient.ts`                                                               | Preserve typed orchestration frame parsing and connection cleanup behavior                                                    | \~30       |
| `apps/web/src/App.tsx`                                                                            | Mount the orchestration cockpit panel in the existing shell without hiding current mission, roster, or War Room stub surfaces | \~45       |
| `apps/web/src/lib/cockpitShell.ts`                                                                | Add orchestration surface metadata and explicit loading, empty, offline, error, and unavailable copy                          | \~100      |
| `apps/web/tests/CockpitShell.test.tsx`                                                            | Cover orchestration surface metadata and fallback states                                                                      | \~80       |
| `apps/web/tests/wsClientPrivacy.test.ts`                                                          | Assert malformed or sensitive orchestration frames do not leak broad raw values into replay/share paths                       | \~80       |
| `apps/web/tests/HeroMissionWorkflow.test.tsx`                                                     | Cover selection synchronization from queue, lineage, and guarded-action references                                            | \~100      |
| `apps/web/README_web.md`                                                                          | Update Phase 03 web orchestration contract and local-only boundaries after implementation                                     | \~70       |
| `docs/api/README_api.md`                                                                          | Mention web cockpit consumption of shipped orchestration frames without overstating hosted or Worker scope                    | \~35       |
| `.spec_system/specs/phase03-session05-web-orchestration-cockpit-controls/implementation-notes.md` | Implementation log, commands, and validation notes                                                                            | \~120      |
| `.spec_system/specs/phase03-session05-web-orchestration-cockpit-controls/security-compliance.md`  | Session privacy, security, and GDPR posture                                                                                   | \~100      |

***

## 7. Success Criteria

### Functional Requirements

* [ ] WebSocket connect hydrates compact queue, template, mission graph, and guarded-action state without sensitive raw payloads.
* [ ] The web store reduces task queue, agent template, subagent lineage, mission graph, and guarded-action update frames.
* [ ] The cockpit shows orchestration loading, empty, disconnected, unavailable, failed, rejected, expired, accepted, and pending states with accessible names.
* [ ] Guarded-action approve and reject controls prevent duplicate triggers while in-flight and revalidate on state changes.
* [ ] Queue, lineage, and guarded-action references synchronize selected hero and mission context through existing store actions.
* [ ] UI copy keeps War Room federation, hosted queues, inbound commands, analytics, public replay hosting, and remote execution out of shipped claims.

### Testing Requirements

* [ ] `npm --workspace apps/web run typecheck` passes.
* [ ] `npm --workspace apps/server run typecheck` passes.
* [ ] Focused web store, UI helper, component, WebSocket, and shell tests pass.
* [ ] Focused server WebSocket hydration tests pass.
* [ ] Browser smoke validation covers desktop and mobile cockpit reachability for the new orchestration panel.

### Non-Functional Requirements

* [ ] Orchestration controls remain local-first, in-memory, bounded, and non-hosted.
* [ ] UI text does not expose raw prompts, command bodies, terminal output, file contents, tokens, transcript paths, or broad absolute paths.
* [ ] Interactive controls have accessible names, visible focus states, and keyboard/pointer support.
* [ ] Responsive layouts keep orchestration content reachable without overlapping text or controls.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.

***

## 8. Implementation Notes

### Key Considerations

* The browser panel must stay honest about current capabilities. It can expose local task queue, template, lineage, and guarded-action states, but it must not imply hosted collaboration, remote control, Worker federation, inbound chat commands, or public sharing.
* Guarded-action event proposals are compact. The UI should prefer compact proposal metadata for broad lists and fetch detail only when needed, preserving privacy and bounded rendering.
* Current queue and template routes can emit updates, while mission graph state primarily arrives through WebSocket frames. The UI must handle missing graph state as unavailable rather than blank.
* The War Room panel remains a separate deferred surface; do not replace its stub with orchestration wording.

### Potential Challenges

* Balancing density and reachability: use concise grouped sections, stable dimensions, and internal scrolling instead of expanding the whole cockpit.
* Missing initial lineage state: hydrate mission graph if available from server managers, otherwise show clear unavailable or waiting copy.
* Duplicate decisions across REST and WebSocket: track in-flight IDs locally and clear them only when a matching update or bounded failure is observed.
* Sensitive copy drift: route all status and error text through `orchestrationUi.ts` so tests can assert raw prompts, commands, paths, tokens, and transcript strings are not displayed broadly.

### Relevant Considerations

* \[P01] **Redaction is boundary-specific**: Web orchestration views must preserve replay, export, adapter, and future sharing privacy boundaries before any data leaves the local browser or server.
* \[P01-apps/server] **Local server boundary must stay conservative**: Web hydration and decisions must inherit local auth, Origin/CORS, rate limits, validation, and explicit failure behavior.
* \[P01-packages/protocol] **Protocol leads cross-package work**: Web view models must consume `@factionos/protocol` contracts instead of duplicating queue, template, lineage, or guarded-action shapes.
* \[P01-apps/warroom+apps/web] **War Room is not wired into the web runtime yet**: Keep local orchestration controls separate from Worker federation and room-sharing copy.
* \[P00-apps/web] **Responsive and accessibility debt**: New controls need mobile, focus, dialog/region semantics, reduced-motion, contrast, and no-overlap validation.
* \[P02] **Honest stub wording matters for deferred surfaces**: Preserve explicit unavailable/deferred wording for anything outside the local Phase 03 MVP.

### Behavioral Quality Focus

Checklist active: Yes

Top behavioral risks for this session:

* Duplicate guarded-action approve or reject clicks causing repeated local decisions.
* Blank or misleading orchestration panels when the server is disconnected, empty, or missing lineage state.
* Raw prompts, commands, paths, transcript identifiers, tokens, or failure payloads leaking into broad UI, replay, or export-adjacent surfaces.
* Responsive cockpit overlap or unreachable controls after adding another dense panel.

***

## 9. Testing Strategy

### Unit Tests

* Test `orchestrationUi.ts` state mapping, copy, redaction, missing-reference fallback, enum coverage, and status tones.
* Test `orchestrationApi.ts` auth headers, compact error mapping, malformed JSON handling, and bounded failure messages.
* Test `useGameStore.ts` reducers for `task_queue_update`, `agent_template_update`, `subagent_lineage_update`, `mission_graph_update`, and `guarded_action_update`.

### Integration Tests

* Test `OrchestrationPanel.tsx` renders queue, template, lineage, guarded-action, empty, offline, failed, expired, unavailable, and duplicate-decision states.
* Test `apps/server/src/ws/handlers.ts` sends compact orchestration hydration frames on connect.
* Test selection synchronization from queue, lineage, and guarded-action references into existing hero and mission detail flows.

### Manual Testing

* Start the local dev stack, create queue and guarded-action fixtures through REST or WebSocket tests, and inspect the cockpit on desktop and mobile widths.
* Verify keyboard navigation reaches orchestration controls, decision buttons, and referenced hero/mission open actions.
* Verify disconnected state by stopping the local server and confirming the panel keeps bounded fallback copy.

### Edge Cases

* Empty queue/template/action snapshots.
* Missing hero, mission, plan, template, queue entry, or subagent references.
* Expired guarded actions while the panel is open.
* Duplicate guarded-action decisions and stale revisions.
* Malformed WebSocket frames or compact server errors.
* Very long labels, summaries, requester names, and failure messages.
* Offline server, local auth failures, and denied browser storage access.

***

## 10. Dependencies

### External Libraries

* React 18.3.1 and React DOM 18.3.1.
* Zustand 4.5.4.
* Vite 6.4.2.
* TypeScript 5.9.3.
* Vitest 4.1.7, Testing Library, and Playwright.

### Other Sessions

* **Depends on**: `phase03-session02-task-queue-and-agent-template-contracts`, `phase03-session03-subagent-lineage-and-mission-graph-runtime`, `phase03-session04-guarded-local-action-runtime`, Phase 02 shell and workflow sessions.
* **Depended by**: `phase03-session06-cli-diagnostics-and-recovery-controls`, `phase03-session07-orchestration-validation-and-documentation-closeout`.

***

## Next Steps

Run the implement workflow step to begin AI-led implementation.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://faction-os.gitbook.io/faction-os-docs/.spec_system/archive/sessions/phase03-session05-web-orchestration-cockpit-controls/spec.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
