> For the complete documentation index, see [llms.txt](https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/.spec_system/archive/sessions/phase19-session02-documents-gallery-write/spec.md).

# Session Specification

**Session ID**: `phase19-session02-documents-gallery-write` **Phase**: 19 - Hermes Orchestration And Documents **Status**: Not Started **Created**: 2026-06-02

***

## 1. Session Overview

This session adds the Documents Gallery tab to the Hermes page in `/agents/hermes`. The work ports the v2.3 artifact gallery into the existing AI OS Hermes architecture instead of copying the v2.3 monolith. The UI consumes the existing `useHermes` document list, trash, and file-access views plus `useHermesAdmin` document mutations, so reads and writes stay routed through the Phase 16 bridge contracts.

Documents Gallery is a write-capable local filesystem surface. It lists and previews artifacts from the configured Hermes documents root, supports soft-delete and restore, and performs permanent purge only behind an explicit confirmation. This session also finishes the v2.3 5 second polling requirement by adding hook-layer refetch intervals for document list and trash reads rather than introducing raw component timers.

This is the second and final Phase 19 session. It follows the completed Mission Control session and enables Phase 20 to focus on long-tail Hermes sections, cleanup, and side-by-side parity sign-off.

***

## 2. Objectives

1. Add a `Documents` tab to the Hermes page with live and demo document states.
2. Build a modular Documents Gallery component that handles loading, empty, error, offline, token-failure, success, demo, preview, and trash states.
3. Wire delete, restore, and purge through `useHermesAdmin` with admin gating, duplicate-trigger prevention, path-confined identifiers, confirmation, and state reset on close.
4. Add hook-layer 5 second polling for document list and trash reads without raw `setInterval` or raw list/trash fetches in the component.
5. Extend focused component, hook, page mode-matrix, and browser route coverage for the Documents tab.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase16-session01-guardrails-architecture-parity-baseline` - Provides the Hermes architecture decision and write-path safety contract.
* [x] `phase16-session02-backend-endpoint-parity-write-safety` - Provides documents read/file/trash endpoints and delete/restore/purge write safety tests.
* [x] `phase16-session03-data-layer-demo-fixtures` - Provides typed document query/admin contracts and demo document fixtures.
* [x] `phase17-session01-visual-system-shell-status-pill` - Provides the Hermes shell, tab framework, visual primitives, and status affordances.
* [x] `phase17-session02-chat-tab-write` - Provides the established admin write UI pattern and duplicate-trigger guard expectations.
* [x] `phase17-session03-pantheon-upgrade-write` - Provides admin-gated form, validation, and mutation feedback patterns.
* [x] `phase18-session01-memory-upgrade-write` - Provides bounded local-path feedback patterns for sensitive local surfaces.
* [x] `phase18-session02-mnemosyne-constellation-readonly` - Provides the latest Hermes tab composition and mode-matrix coverage pattern.
* [x] `phase19-session01-mission-control-write` - Provides the current Phase 19 write-surface pattern in the Hermes page.

### Required Tools/Knowledge

* React 19, TanStack Query, Radix Tabs, Tailwind CSS 4, lucide-react.
* Existing Hermes hooks in `src/hooks/use-hermes.ts` and `src/hooks/use-hermes-admin.ts`.
* Existing document contracts in `src/lib/hermes-types.ts` and `src/lib/hermes-admin-types.ts`.
* Existing Hermes visual primitives in `src/components/hermes/hermes-page-primitives.tsx`.
* File-type art under `src/assets/hermes-art/file-types/*.webp`.
* v2.3 source anchor: `/home/aiwithapex/projects/claudeos/claude-os-v2.3/src/components/hermes-documents-gallery.tsx`.

### Environment Requirements

* Bun 1.3.14 project environment.
* No live Hermes installation or admin token is required for automated tests.
* Live writes require local dev, loopback access, a successful token handshake, and `HERMES_DASHBOARD_ADMIN=1`.
* Documents root decision for v1: keep the bridge default of `~/Documents/Hermes/` with the existing `HERMES_DOCUMENTS_DIR` override for local development; all file and trash identifiers remain bridge-confined.

***

## 4. Scope

### In Scope (MVP)

* Operator can open a `Documents` tab in `/agents/hermes` - add a tab trigger and content panel in `src/components/hermes/hermes-read-only-page.tsx`.
* Operator can inspect document cards and trash state - render `HermesDocumentsBody` and `HermesDocumentTrashBody` with sorted artifact cards, safe metadata, trash count, and explicit empty/error states.
* Operator can preview a selected artifact - use `hermes.documentFile` URL and fetch helpers with safe names, explicit loading/error states, and preview fallbacks for unsupported file types.
* Operator can soft-delete a document - use `admin.documents.deleteByName` with selected-name validation, admin/demo gating, duplicate-trigger prevention while in-flight, and success feedback.
* Operator can restore a trash item - use `admin.documents.restoreFromTrash` with trashId validation, duplicate-trigger prevention, and restored-name feedback.
* Operator can permanently purge trash - use `admin.documents.purgeTrash` only after explicit confirmation, supporting both targeted trashId purge and full trash purge if the existing admin contract allows it.
* Hook-layer polling refreshes list and trash reads every 5 seconds in live mode, while preserving existing offline/demo/setup-disabled behavior.
* Demo mode shows document and trash fixtures but keeps all write and file preview affordances disabled with a demo or admin-mode-required hint.
* Tests cover live/demo rendering, file-type art fallback, preview states, admin-disabled states, mutation validation, duplicate-trigger prevention, confirmation, polling configuration, and mode-matrix tab wiring.

### Out of Scope (Deferred)

* Mission Control - Reason: completed in Phase 19 Session 01.
* Long-tail stats, connections, roles, activity, CLI, and final cleanup - Reason: owned by Phase 20.
* New server endpoint implementation - Reason: Phase 16 Session 02 already landed document endpoints and security tests.
* Setup UI for choosing the documents root - Reason: v1 uses the existing bridge default plus `HERMES_DOCUMENTS_DIR`; a broader setup/config surface belongs in a later explicit session.
* Raw v2.3 component/file parity - Reason: AI OS ports features into modular typed components rather than copying the v2.3 monolith.
* Raw `setInterval` or raw list/trash fetch bypasses - Reason: polling belongs in `useHermes` through TanStack Query.

***

## 5. Technical Approach

### Architecture

Create `src/components/hermes/hermes-documents-gallery.tsx` as a focused tab component. It receives `documents: HermesQueryView<HermesDocumentsBody>`, `documentTrash: HermesQueryView<HermesDocumentTrashBody>`, `documentFile: HermesDocumentFileAccess`, `admin: UseHermesAdminResult`, and `demoMode: boolean`. It derives display state locally, maps file types to the existing WebP art set, and routes every write through `admin.documents`.

`HermesReadOnlyPage` will expose `hermes.documents` and `hermes.documentTrash` in live mode and `HERMES_DEMO_DOCUMENTS` / `HERMES_DEMO_DOCUMENT_TRASH` in demo mode, then add a Documents tab near the other write-capable tabs. The page continues to own demo/live mode and the admin hook, while Documents Gallery owns only document-specific UI and write controls.

For refresh behavior, `useHermes` will configure 5 second refetch intervals for documents and trash queries when live public Hermes reads are enabled. The component may use query invalidation for manual refresh, but it must not call `/__hermes_documents` or `/__hermes_documents/trash` directly. Direct network calls remain limited to the hook-layer file preview helper.

### Design Patterns

* Existing hook contract: consume `useHermes` and `useHermesAdmin` views rather than adding endpoint clients.
* Admin boundary: writes are disabled unless `admin.canUseAdmin` is true and demo mode is false.
* Stateful write safety: prevent duplicate submits while a document mutation is pending, clear selection when the selected item leaves the list, and reset confirmation state on close.
* Exhaustive states: render explicit loading, empty, error, offline, token-failure, success, demo, preview-loading, preview-error, and unsupported preview states.
* Bounded output: display sanitized, length-capped errors and never render raw local paths, document contents beyond the selected preview body, tokens, or bridge internals.

### Technology Stack

* React 19 with TypeScript.
* TanStack Query refetch intervals and invalidation through existing query keys.
* Radix Tabs plus existing local UI primitives.
* File-type art assets from `src/assets/hermes-art/file-types/`.
* Vitest, Testing Library, and Playwright for validation.

***

## 6. Deliverables

### Files to Create

| File                                                                                   | Purpose                                                                                                  | Est. Lines |
| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ---------- |
| `src/components/hermes/hermes-documents-gallery.tsx`                                   | Documents Gallery tab UI, state rendering, preview panel, trash panel, and delete/restore/purge controls | \~620      |
| `src/components/hermes/__tests__/hermes-documents-gallery.test.tsx`                    | Focused component tests for document states, preview, admin gating, writes, confirmation, and demo mode  | \~320      |
| `.spec_system/specs/phase19-session02-documents-gallery-write/implementation-notes.md` | Implementation evidence, root decision, source anchors, safety decisions, and validation commands        | \~90       |

### Files to Modify

| File                                                       | Changes                                                                                                              | Est. Lines |
| ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | ---------- |
| `src/hooks/use-hermes.ts`                                  | Add 5 second live refetch intervals for documents and trash queries; preserve offline/demo/setup-disabled behavior   | \~20       |
| `src/components/hermes/hermes-read-only-page.tsx`          | Add Documents tab, demo document/trash view, icon import, and component wiring                                       | \~70       |
| `src/components/hermes/__tests__/hermes-sections.test.tsx` | Extend page mode-matrix fixtures and assertions for Documents tab live/demo transitions                              | \~110      |
| `tests/e2e/hermes-agent.spec.ts`                           | Add mocked browser route coverage for the Documents tab, admin-disabled affordance, preview, and responsive overflow | \~80       |
| `src/hooks/__tests__/use-hermes.test.tsx`                  | Cover document/trash query polling configuration and no polling in demo/offline-disabled modes                       | \~80       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] `Documents` appears as a Hermes tab and renders live/demo document data.
* [ ] Loading, empty, error, offline, token-failure, success, demo, preview loading/error, and unsupported preview states render explicit, user-visible states.
* [ ] Document list and trash reads use the existing `useHermes` query views, with 5 second live polling through TanStack Query.
* [ ] File previews use `documentFile.getUrl` or `documentFile.fetchFile`; no raw list or trash `fetch` calls are introduced in the component.
* [ ] Delete, restore, and purge writes all go through `useHermesAdmin`.
* [ ] Write controls are disabled in demo mode, without admin mode, while offline, while token-gated, and while the relevant mutation is pending.
* [ ] Purge requires explicit confirmation and resets confirmation state when dismissed.
* [ ] File-type art renders from the copied WebP assets, including an `other.webp` fallback for unsupported or image-like types.

### Testing Requirements

* [ ] Focused component tests cover document rendering, sorting, preview states, file-type art fallback, admin-disabled hints, mutation validation, duplicate-trigger prevention, confirmation, and demo mode.
* [ ] `use-hermes.test.tsx` covers 5 second polling for document list and trash queries and verifies disabled modes do not poll.
* [ ] `hermes-sections.test.tsx` covers Documents tab wiring through live and demo transitions.
* [ ] E2E coverage opens `/agents/hermes`, switches to Documents, verifies the mocked read/admin-disabled path, exercises a preview, and checks for responsive overflow.
* [ ] Focused bridge/admin tests for document path confinement and purge confirmation are run or existing coverage is documented in implementation notes.

### Non-Functional Requirements

* [ ] No new bridge endpoint, personal-data store, third-party transfer, or production write surface is introduced.
* [ ] Browser-visible errors are redacted, bounded, and do not expose raw local paths, tokens, credentials, or bridge internals.
* [ ] UI controls have platform-appropriate accessibility labels, keyboard support, focus management, and stable responsive dimensions.
* [ ] No new heavyweight dependency is added.
* [ ] Base Hermes route bundle does not import extra 3D or unrelated vendor code.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] No new global `findtrend` identifiers.
* [ ] Focused tests, typecheck, lint, and relevant browser proof pass or any unrelated pre-existing failure is documented.

***

## 8. Implementation Notes

### Key Considerations

* The v2.3 component directly polls and token-fetches document writes. The AI OS port must use `useHermes` and `useHermesAdmin` instead.
* `HERMES_DEMO_DOCUMENTS` and `HERMES_DEMO_DOCUMENT_TRASH` already exist and should be wired into demo mode.
* `src/hooks/use-hermes-admin.ts` already invalidates documents and trash after successful mutations, so the component should avoid duplicate cache ownership.
* The bridge exposes `HERMES_DOCUMENTS_DIR` as the local override while keeping `~/Documents/Hermes/` as the v1 default. Record this decision in `implementation-notes.md`.
* Document preview is the only place file bytes are fetched. Keep the preview bounded, cancellable, and tied to safe document names.

### Potential Challenges

* The v2.3 component is large and includes many visual states: port the core artifact, preview, and trash behaviors first, then preserve useful visual cues without copying the full file structure.
* Document purge is permanent: require confirmation, make the destructive state visually distinct, and keep restore as the default recovery path.
* File previews can be slow or unsupported: provide explicit loading, error, and unsupported states and clean up pending preview work on selection change.
* File type `image` exists in the parser but the copied art set has no `image.webp`: map it to `other.webp` unless implementation finds an existing suitable asset.

### Relevant Considerations

* \[P04] **Hermes bridge guardrails must stay intact**: writes stay behind loopback, token, and admin mode; destructive purge requires confirmation.
* \[P08] **Local agent privacy/readiness boundary**: never expose raw local paths, prompts, transcripts, logs, credentials, command output, workspace content, or auth payloads.
* \[P17] **Do not split one write capability across multiple tabs or panels**: keep document delete, restore, and purge in the Documents tab only.
* \[P18] **Do not collapse non-success query states into empty UI**: loading, error, offline, and token-failure states must stay explicit.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Permanent purge can destroy local files if confirmation and trashId confinement are bypassed.
* Raw polling, raw fetches, or uncleared preview work could bypass hook contracts or leak state after tab changes.
* Browser-visible path, token, or file-content errors could expose private local information.

***

## 9. Testing Strategy

### Unit Tests

* Test document sorting, card metadata, file-type art mapping, trash rendering, preview loading/error/unsupported states, and selected-item reset.
* Test admin gates for delete, restore, and purge in enabled, disabled, demo, offline, token-failure, and pending states.
* Test hook polling configuration for document and trash queries.

### Integration Tests

* Extend the Hermes page mode-matrix test so Documents appears in live and demo modes and existing tabs remain accessible.
* Run existing bridge/admin tests that cover document file reads, symlink rejection, path traversal rejection, soft-delete, restore, and purge confirmation.

### Manual Testing

* Open `/agents/hermes`, switch to Documents, inspect live or mocked document cards, open a preview, verify admin-disabled hints, and confirm no horizontal overflow on mobile and desktop widths.
* In an admin-enabled local environment, soft-delete a disposable document, restore it, then purge a disposable trash item only after explicit confirmation.

### Edge Cases

* Empty documents root with non-empty trash.
* Non-empty documents root with empty trash.
* Unsupported preview MIME/type or failed file fetch.
* Selected document disappears after polling or deletion.
* Restore collision where backend returns a renamed `restoredAs` value.
* Purge with missing confirmation, missing trash item, or partial purge errors.
* Demo mode, offline mode, setup-required mode, and token failure mode.

***

## 10. Dependencies

### External Libraries

* No new external libraries.

### Internal Dependencies

* `src/hooks/use-hermes.ts`
* `src/hooks/use-hermes-admin.ts`
* `src/lib/hermes-types.ts`
* `src/lib/hermes-admin-types.ts`
* `src/lib/hermes-demo-data.ts`
* `src/components/hermes/hermes-page-primitives.tsx`
* `src/assets/hermes-art/file-types/*.webp`

### Other Sessions

* Depends on: `phase16-session01-guardrails-architecture-parity-baseline`, `phase16-session02-backend-endpoint-parity-write-safety`, `phase16-session03-data-layer-demo-fixtures`, `phase17-session01-visual-system-shell-status-pill`, `phase17-session02-chat-tab-write`, `phase17-session03-pantheon-upgrade-write`, `phase18-session01-memory-upgrade-write`, `phase18-session02-mnemosyne-constellation-readonly`, `phase19-session01-mission-control-write`
* Depended by: Phase 20 Hermes Long-Tail And Parity Sign-off

***

## 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://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/.spec_system/archive/sessions/phase19-session02-documents-gallery-write/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.
