Skip to content

Technical Design TD-0008 — Journal: voice notes and guided reflection

Field Value
ID TD-0008
Title Journal: voice notes and guided reflection
Status Approved
Owner Kostas Alexopoulos
Audience contributors
Created 2026-10-30
Last Updated 2026-10-30
Reviewers —
Approvers Kostas Alexopoulos
Tracking —
Related PRD-003, US-JRN, ADR-0014, server/services/loryth-journal/docs/spec.md

1. Summary

  • Loryth has a complete journal backend (journals, entries, typed items, flows, insights) but no journal UI, no voice input, and no guided writing. The Mindful Planner persona journals daily on a phone or laptop and wants a 3-minute morning routine, not a blank page.
  • This design ports the two features that work in the standalone souperk-voice-to-text desktop app into Loryth:
  • Voice notes: press the microphone, speak, stop, read the transcript, edit, save. The transcript becomes a journal entry; the audio is kept alongside it.
  • Guided reflection: a chat-first interviewer (DeepSeek through loryth-ai) opens with a preset question, asks one follow-up at a time, and on "End the page" rewrites the conversation as a first-person prose entry the user edits and keeps. Replies can be typed or spoken.
  • Transcription uses Deepgram (pre-recorded /v1/listen), with the API key and model managed on the admin Settings page next to DeepSeek. Interview and synthesis use the DeepSeek configuration that chat already uses.
  • The journal service becomes the system of record for reflection sessions (per-turn durable rows, like the desktop app's diary_messages). The AI service stays stateless for journaling: it exposes one transcription endpoint and two text endpoints (next question, synthesis).
  • A new Journal section in the web app: a Today page with a capture bar (type, speak, or reflect), a calendar heatmap, recent entries, "on this day", a reflection page, a day page, and an entry page. Wisteria Craft design language, shared workspace components, Lucide icons.

2. Context and Problem Statement

What exists

Area State today
loryth-journal Journals, entries with typed items (note, rating, attachment_ref, …), flows, projections, media endpoints that hand out presigned MinIO URLs. No UI uses it.
loryth-ai DeepSeek chat with reasoning, run orchestration, admin settings (ai_settings: model, encrypted API key). Modality.AUDIO exists in the enum but nothing implements it.
Web app Chat is the home screen. Notes, Wallet, Issues, Grocery share workspace components (PageHeader, Panel, Field, FormDialog, Notice, Empty, daily.css rail/split layout). No microphone or file upload anywhere.
Mobile app Login, register, theme demo only.

What souperk-voice-to-text taught us

The desktop app (GTK, SQLite, single user) has been in daily use. Its design docs (TD-003 Diary subsystem, TD-004 Recording pipeline) record what worked:

  • Chat-first beats blank page. Landing in a live conversation with a concrete opening question produces material fast. Every preset repeats: "Always reply with a question; do not wrap up yourself".
  • Synthesis as a one-shot task, with the transcript wrapped in <conversation> tags and [Interviewer]/[Me] lines, keeps the model from asking another question instead of writing prose.
  • Durability per turn. Eager draft creation plus one row per turn survives crashes; a draft left untouched is swept.
  • Voice is a composer affordance, not a mode. Push to talk, transcript lands in the composer, the user edits, then sends.
  • Acknowledge slow models. Escalating copy ("Thinking…" → "Still thinking…" → "Taking longer than usual") and a cancel button make waits tolerable.
  • Six presets cover most days: Open check-in, Morning pages, Gratitude x 3, Stoic evening, Worry dump, Weekly review.
  • Recording-side details that do not transfer: pw-record, live Whisper preview, local Ollama, desktop notifications, clipboard paste.

Why now

The journal backend is idle, the Mindful Planner is the primary persona for PRD-003, and the DeepSeek and settings plumbing in loryth-ai makes the interviewer a thin addition.

2.1 Goals

  • A user can create a journal entry by speaking, in under a minute, from the Today page.
  • A user can complete a guided reflection (typed or spoken replies) and keep the result as an entry, with the conversation and audio preserved.
  • Admins configure Deepgram on the Settings page; when it is not configured, the microphone explains why and typing still works.
  • Entries are browsable by day (heatmap, recent, on this day) and readable on an entry page with audio playback.
  • A reflection draft survives reloads and crashes; the Today page offers to resume it.
  • Everything ships with the project's test conventions: integration tests for both services, Vitest for UI logic, a Playwright demo flow for the text-only path.

2.2 Out of Scope

  • Separate phone screens. Capacitor Android renders the shared React DOM UI.
  • Live transcription while speaking.
  • Reminders and notifications (follow-up through loryth-notifications).
  • User-defined interview presets and editing built-in prompts.
  • "Continue conversation" on a kept entry.
  • Structured flows and metric capture inside the capture bar. Flows remain available through the existing API.
  • Local or self-hosted speech-to-text providers. The provider abstraction allows one later; Deepgram is the only shipped provider.
  • Multiple journals in the UI. The UI uses one default journal per user.

2.3 Assumptions and Constraints

  • Browser recording uses MediaRecorder. Chromium and Firefox produce audio/webm;codecs=opus; Safari produces audio/mp4. Deepgram accepts both as raw bodies with the matching Content-Type.
  • Audio is stored in MinIO bucket journal-media through the journal service. The browser never talks to MinIO: presigned URLs point at the internal minio:9000 host, so the existing presigned endpoints are replaced with streaming upload and download through the service.
  • The web app uses userId as spaceId, as Notes does. The journal service continues to take user_id in request bodies and query strings.
  • The journal service calls the AI service over the Docker network at LORYTH_AI_URL (default http://loryth-ai-api:8000), the way loryth-ai already calls grocery. It forwards x-user-id and the incoming bearer token so the AI service can use its existing IAM check.
  • DeepSeek requests take seconds. Requests from the browser to the journal service for a turn or a synthesis can take up to 120 s; the nginx proxy_read_timeout for /api/v1/journal must allow that (set it to 300 s like the AI block).
  • Audio uploads are capped at 25 MB per file (nginx already allows 100 MB bodies).

3. Design Overview

graph TB
    subgraph Browser
        Today[Today page: capture bar, heatmap, recents]
        Reflect[Reflection page: thread, composer, review]
        Entry[Entry page]
        Rec[useVoiceRecorder: MediaRecorder]
    end
    subgraph loryth-ai
        STT[POST /audio/transcriptions]
        Interview[POST /journal/interview]
        Synth[POST /journal/synthesis]
        Settings[ai_settings: DeepSeek + Deepgram]
        Deepgram[(Deepgram API)]
        DeepSeek[(DeepSeek API)]
    end
    subgraph loryth-journal
        Media[POST/GET /journals/:id/media]
        Sessions[reflection_session + reflection_turn]
        Entries[entry + entry_item]
        Days[GET /journals/:id/days, /on-this-day]
        MinIO[(MinIO journal-media)]
    end
    Rec -->|audio blob| STT
    STT --> Deepgram
    Rec -->|audio blob| Media
    Media --> MinIO
    Today -->|quick note| Entries
    Reflect -->|turn| Sessions
    Sessions -->|next question| Interview
    Sessions -->|prose| Synth
    Interview --> DeepSeek
    Synth --> DeepSeek
    Sessions -->|keep| Entries
    Today --> Days
    Entry --> Media

3.1 Key Components

Component Purpose
loryth-ai TranscriptionProvider + DeepgramTranscriptionProvider Turn an uploaded audio blob into text.
loryth-ai ReflectionService Stateless interviewer: next question from a transcript; prose synthesis from a transcript. Resolves DeepSeek like ChatService.
loryth-ai SettingsService (extended) Stores Deepgram model and encrypted key next to DeepSeek.
loryth-journal MediaService (reworked) Streams uploads into MinIO and downloads out of it.
loryth-journal ReflectionService Owns sessions, turns, presets, synthesis, keep. Calls AiGateway.
loryth-journal AiGateway Thin HTTP client to loryth-ai; swapped for a stub in tests.
loryth-journal DaysService Per-day entry counts for the heatmap and "on this day" lookups.
Web modules/journal/* Today, Day, Reflection, Entry pages plus rail.
Web shared/voice/* useVoiceRecorder hook and RecordButton, reusable by chat later.
Web admin Settings Deepgram card.

3.2 Interface Impact (Before → After)

Area Before After
/api/v1/journal/journals/{id}/media/upload-url, .../download-url Presigned MinIO URLs (unreachable from browsers) Removed. POST /journals/{id}/media (multipart) and GET /journals/{id}/media/{asset_id} (stream) added. DELETE unchanged.
/api/v1/ai/admin/settings DeepSeek fields Adds deepgram_model, deepgram_configured, deepgram_stored_key, deepgram_stored_key_unreadable; PUT accepts a non-empty subset of provider fields; deepseek_model is optional so each provider card updates only its own settings.
Web navigation Dashboard, Grocery, Notes, Wallet, Issues Adds Journal (/journal, Lucide NotebookPen) after Notes.
attachment_ref payload {asset_id, kind, caption?} Unchanged schema; audio items also carry mime_type, duration_seconds, transcript (optional keys, validator stays permissive on extras).

4. User Experience

All screens follow the Wisteria Craft rules in .claude/rules/design-language.md: tokens only, Fraunces for the page title and the prose of a kept entry, Inter everywhere else, Lucide icons at 1.75 px stroke, radii.md, purple primary and moss secondary accent, purple-tinted shadows in dark mode. Reuse PageHeader, Panel, Field, FormDialog, Notice, Loading, Empty, and the shared workspace primitives. The Journal uses its own reading-width split and rail styles. Every interactive element has an accessible name; state changes (recording, transcribing, thinking) are announced through aria-live="polite" regions. Honour prefers-reduced-motion for the recording pulse.

4.1 Journal layout and rail

/journal renders JournalLayout: a centered layout with a 14 rem left rail and an Outlet, capped at 64 rem overall and 68ch for the reading column. On screens under 850 px the rail collapses under a "Browse journal" toggle button above the content. Calendar paging keeps Browse open; following a day or entry link closes it.

Rail contents, top to bottom:

  1. Today link with a notebook icon and a purple left indicator when on /journal (aria-current="page").
  2. Calendar heatmap (HeatmapCalendar): eight visible weeks as Monday-first, seven-row columns, with Earlier weeks and Later weeks controls covering the last 26 weeks. A localized date range replaces month labels. Each cell links to /journal/days/:date and has an accessible date, entry count, and unfinished-reflection label. Cells use spacing[4], enlarged to spacing[6] on phones, with spacing[1] gaps. Intensity tiers show 0, 1, 2, or 3+ entries, with a matching numbered legend. Today has a primary-color outline; unfinished reflections have a moss (colorVars.secondary) dot and a legend when present. Future dates are omitted.
  3. Recent (daily.railSection with daily.label heading): the latest 10 entries across all days, each a link showing the localized day and time and the first Markdown block as readable text, clamped to two lines. Heading markers, emphasis markers, and link destinations are removed from this label. Empty: "Your first entry will appear here."
  4. On this day (only when non-empty): entries from the same month and day in earlier years, labelled "1 year ago", "2 years ago".

4.2 Today page (/journal)

PageHeader with eyebrow = full date ("Thursday, 30 October 2026"), title "Journal", and a compact count beside the title: "3 entries this week" (or "Nothing this week yet").

Resume banner. If a draft reflection exists for this user (any date), show a Notice tone="info": "You have an unfinished reflection from {dateLabel}. [Continue] [Discard]". Continue opens /journal/reflections/:id. Discard asks for confirmation through FormDialog (danger, submit "Discard reflection") then deletes the session and its audio.

Capture bar (aria-label="Capture"), a bordered writing surface labelled "New entry":

  • A textarea placeholder "What's on your mind?" that grows with the text (same useLayoutEffect sizing as ChatComposer, max 240 px). Enter inserts a newline. Ctrl+Enter or ⌘+Enter saves, as described by the Save button hint.
  • A microphone button (RecordButton) at the left of the toolbar, labelled "Record a voice note". When Deepgram is not configured it is disabled with title and a visually-hidden description "Ask an admin to set up Deepgram in Settings to use voice notes"; admins see a link to /settings in that text.
  • A separate guidance row below the writing toolbar: a secondary Reflect text button and the current preset ("Open check-in"). Choosing the preset opens a PresetPicker menu (native details/summary menu from daily.menu, or Radix dropdown) listing the six presets with name and opening question. The last-used preset is remembered in localStorage under journal.preset.
  • A Save button at the far right of the writing toolbar. It becomes purple when text can be saved and uses neutral colors while disabled. Reflect and preset selection sit below a divider.

Recording state inside the capture bar (also used by the reflection composer; implemented once as RecordingStrip):

State What the user sees Controls
Idle textarea + mic Mic starts recording.
Requesting permission mic shows a spinner, status "Allow microphone access to record" —
Permission denied / no device Notice tone="warning" "Loryth can't reach your microphone. Check browser permissions." Dismiss.
Recording strip replaces the toolbar: red pulsing dot (static dot under reduced motion), "Recording", live timer m:ss, a simple level meter (8 bars driven by AnalyserNode) Stop (primary, Space or Enter), Cancel (ghost, Escape). Recording caps at 10 minutes with a 30 s warning.
Transcribing strip shows "Transcribing…" with Loading Cancel aborts the request and keeps the audio chip.
Transcript ready transcript appended to the textarea (editable); an audio chip under the textarea: waveform icon, "Voice note · 0:42", a Play/Pause button, a "Keep audio" checkbox checked by default, and a remove ✕ Save.
Transcription failed Notice tone="error" with the API detail ("Deepgram could not transcribe this recording") and Retry and Type instead Retry resends the same blob. The audio chip stays so the user can still save audio with a typed note.

Save creates one entry: occurred_at = now, items [note(md, text)] plus, when audio is kept, attachment_ref(kind=audio, asset_id, mime_type, duration_seconds, transcript=text, caption="Voice note"). The audio uploads first (POST /journals/{id}/media), then the entry is created; if upload fails the user sees "Could not store the audio. Save without it?" with Save text only and Retry upload. After a successful save the textarea clears, a toast (daily.toast) says "Saved to your journal · View" and dismisses after six seconds, and the Today list and rail refresh.

Today's entries (below the capture bar): a counted EntryCard list newest first, separated by fine rules. Each entry shows the locale-formatted time, reflection preset or voice label when applicable, and a compact Read entry link. Notes have no type chip. Previews reuse the chat Markdown renderer, showing up to three complete blocks and omitting a trailing heading whose content is outside the preview. Preview headings use Inter semibold; paragraphs retain the normal body font. Audio items retain their inline AudioPlayer. Empty state uses Empty with the NotebookPen icon: "Nothing written today yet" / "Say a few words, type a line, or start a reflection."

4.3 Reflection page (/journal/reflections/:sessionId)

Full-height two-part surface sized from the viewport minus the shell header, content padding, and mobile Browse control: a flexible scrollable thread and a composer at the bottom of the column. The rail stays visible on wide screens.

Header row: back link "Journal" with an ArrowLeft icon; preset chip (same PresetPicker, enabled only until the first "me" turn, afterwards rendered as a static badge); date pill dateLabel(session_date); on the right End the page (primary, Ctrl+Enter) and an overflow menu with Discard (confirm when any "me" turn exists).

Thread (role="log", aria-live="polite"): interviewer turns render as plain text with a small "Loryth" label in daily.label style; "me" turns render in a colorVars.primarySubtle bubble aligned right with a Play/Pause chip when the turn has audio. Timestamps are not shown. The thread autoscrolls on new content unless the user has scrolled up.

Thinking indicator (ThinkingRow): shown after a "me" turn is sent, in the interviewer position: a breathing dot, copy that escalates with elapsed time, an elapsed m:ss, and Stop:

Elapsed Copy
< 5 s "Thinking…"
5–15 s "Still thinking…"
15–30 s "Taking longer than usual"
≥ 30 s "DeepSeek is slow right now. You can keep waiting or stop."

Stop aborts the browser request. The server still stores the "me" turn; the thread then shows the saved turn with a Ask again button (calls the retry endpoint). The same applies when the request fails: Notice tone="error" inline with the detail and Ask again.

Composer (ReflectionComposer): textarea "Your reply…", mic button (Ctrl+M toggles), Send (Enter; Shift+Enter newline). The RecordingStrip behaves as in 4.2; the transcript is appended to the composer text. Send while transcribing is disabled with title "Wait for the transcript". Sending a turn that has an audio chip uploads the audio first, then posts the turn with audio_asset_id and audio_duration_seconds. The composer is disabled while a question is pending and shows “Waiting for the next question…” in place of “Your reply…”.

Preset switch before the first reply replaces turn 0 with the new preset's opening question (server endpoint PATCH /reflections/{id} with preset_key).

End the page switches the surface to Review (ReflectionReview):

  • Heading "Your page" in Fraunces, date pill.
  • While synthesising: the same thinking row with copy "Writing your page…" and a Stop that returns to the conversation.
  • When prose arrives: an autosizing textarea in Fraunces at fontSizes.lg, line-height 1.7, editable. Buttons: Keep (primary), Try again (ghost, re-synthesises; the current text is restored if the user stops), Back to conversation (ghost). Edits are debounced (800 ms) to PATCH /reflections/{id} so a reload keeps them. The action row shows Saving…, Saved, or Not saved with Retry. Pending edits are saved before leaving review through its buttons.
  • Keep posts /reflections/{id}/keep with the edited prose, then navigates to /journal/entries/:entryId and shows the toast "Saved to your journal".

Ending with no "me" turns is blocked: the End button is disabled with title "Reply at least once first".

4.4 Day page (/journal/days/:date)

PageHeader with back "Today", title dateLabel(date) ("Yesterday", "Tue 14 Oct"), eyebrow "Journal", actions: previous day / next day icon buttons (next disabled for today). Lists that day's EntryCards newest first. Empty: "Nothing on this day" with action Add a note for this day, which reveals the capture bar in text-only mode with occurred_at set to noon local time of that day.

4.5 Entry page (/journal/entries/:entryId)

PageHeader back "Today" (or the day page it came from), eyebrow "Journal · Stoic evening" (preset or "Voice note" or "Note"), title = dateLabel with time ("Today · 14:05"). Actions: Edit, overflow Delete (confirm).

Body: the prose or note rendered as Markdown with the existing chat Markdown renderer (modules/chat/markdown), set in Fraunces at fontSizes.lg and max-width 68ch. Under it, an AudioPlayer per audio item ("Voice note · 0:42" or "Reply 2 · 0:18"). For reflections, a collapsible "See how this began" (details) lists the interviewer and "me" turns in order, each "me" turn with its audio chip. Edit turns the prose into a textarea with Save and Cancel, using the entry revision for optimistic concurrency; a 409 shows "This entry changed elsewhere. Reload to see the latest." Delete removes the entry and its audio assets and returns to Today.

4.6 Admin Settings: Deepgram card

Mirror the DeepSeek card: title "Deepgram", badge "Configured"/"Not configured", description "Speech-to-text for voice notes and spoken replies in Journal.", fields Model (default nova-3) and API key (password, "Leave blank to keep the current key"), the "Remove the saved API key" checkbox when a key is stored, and the unreadable-key alert. One form, one Save. Saving invalidates the journal status query so the microphone enables without a reload.

4.7 Keyboard summary

Where Key Action
Capture bar Enter / Shift+Enter Newline
Capture bar Ctrl+Enter / ⌘+Enter Save
Reflection composer Enter Send
Reflection composer Shift+Enter Newline
Capture bar, composer Ctrl+M Start or stop recording
Recording Space / Enter Stop
Recording Escape Cancel and discard the recording
Reflection Ctrl+Enter End the page
Review Escape Back to conversation

5. Implementation Details

5.1 loryth-ai

Settings

Migration v11-deepgram-settings.sql:

ALTER TABLE ai_settings ADD COLUMN deepgram_model VARCHAR(255) NOT NULL DEFAULT 'nova-3';
ALTER TABLE ai_settings ADD COLUMN deepgram_api_key_encrypted TEXT;

SettingsService gains get_deepgram() -> DeepgramSettings(model, api_key, stored_key, can_store_key, stored_key_unreadable) and update_deepgram(model, api_key, remove_key), following get_deepseek/update_deepseek exactly (same Fernet cipher, env fallback DEEPGRAM_API_KEY, DEEPGRAM_MODEL). Split settings_service.py if it passes ~200 lines: deepseek_settings.py, deepgram_settings.py, shared cipher.py.

Admin router: GET /admin/settings returns both blocks in one SettingsModel; PUT /admin/settings body gets deepgram_model: str | None, deepgram_api_key: SecretStr | None, remove_deepgram_api_key: bool = False. Only the fields present are updated (DeepSeek stays required as today to avoid changing its contract).

Compose: pass DEEPGRAM_API_KEY: ${DEEPGRAM_API_KEY:-} and DEEPGRAM_MODEL: ${DEEPGRAM_MODEL:-nova-3} to loryth-ai-api and loryth-ai-worker.

Transcription provider

domain/provider/transcription.py:

@dataclass(frozen=True)
class Transcription:
    text: str
    language: str | None
    duration_seconds: float | None
    confidence: float | None

class TranscriptionProvider(ABC):
    @abstractmethod
    def transcribe(self, audio: bytes, *, mime_type: str, language: str | None) -> Transcription: ...

domain/provider/deepgram_transcription_provider.py: DeepgramTranscriptionProvider(model, api_key, base_url="https://api.deepgram.com") using httpx (timeout 60 s): POST {base_url}/v1/listen with query model, smart_format=true, punctuate=true, and language when given else detect_language=true (skip smart_format for whisper* models as the desktop app does); headers Authorization: Token <key>, Content-Type: <mime_type>; body = raw audio. Parse results.channels[0].alternatives[0] for transcript and confidence, metadata.duration, and results.channels[0].detected_language. Wrap failures in TranscriptionProviderError with a safe message; never log the key or the audio. StubTranscriptionProvider returns Transcription("stub transcript", "en", 1.0, 0.99) and is registered in the test DI container.

domain/transcription/transcription_service.py (TranscriptionService): status() -> bool (key present), transcribe(user_id, audio, mime_type, language). It resolves the provider from settings on each call (so a saved key applies to the next request), raising TranscriptionNotConfiguredError when there is no key. Keep resolve_transcription_provider(settings) -> TranscriptionProvider in provider_factory.py. TranscriptionService receives a TranscriptionProvider through DI: production uses a small settings-backed adapter that calls the factory on each request; tests inject StubTranscriptionProvider. This keeps provider construction independent of container bootstrap.

Router api/audio/router.py, prefix /audio:

  • POST /audio/transcriptions — multipart file (UploadFile), optional form field language. Header x-user-id required (as chat). Rejects files over 25 MB (413) and content types outside audio/* and video/webm (415). Returns SuccessResponse[TranscriptionModel] with text, language, duration_seconds, confidence. Errors: 503 "Ask an admin to configure Deepgram in Settings first", 502 on provider failure.

Reflection endpoints

domain/reflection/reflection_service.py (ReflectionService), stateless:

  • next_question(user_id, system_prompt, turns) -> str: builds [system] + alternating assistant/user provider messages from turns (interviewer → assistant, me → user), calls provider.complete(messages, tools=[]), returns stripped content. Reject empty content with ReflectionProviderError.
  • synthesize(user_id, turns) -> str: system prompt = the synthesis prompt below; one user message built by build_synthesis_user_message (port from the desktop app: [Interviewer]: … / [Me]: … lines wrapped in <conversation> tags). Drops a trailing interviewer turn.

The provider comes from a new ModelProviderResolver service (domain/provider/model_provider_resolver.py) that extracts _get_or_create_binding + resolve_model_provider + DeepSeek key handling from ChatService so both services share it. Reflection tests mock the DeepSeek HTTP boundary, as existing chat tests do. The production container already registers a stub fallback for unrelated run paths, so the shared resolver always resolves the configured binding rather than treating that fallback as a reflection override. ChatService switches to the resolver as part of this change; its behaviour must not change (existing chat tests stay green).

Prompts live in domain/reflection/prompts.py: SYNTHESIS_SYSTEM_PROMPT ported verbatim from souperk-voice-to-text/src/voice_to_text/diary/prompts.py, and build_synthesis_user_message. The per-preset interviewer prompts are stored in the journal service (they are user-facing content), so the interview endpoint receives the system prompt in the request.

Router api/journal/router.py, prefix /journal, header x-user-id required:

  • GET /journal/status → { interview_configured: bool, transcription_configured: bool, transcription_provider: "deepgram", transcription_model: str }. Used by the web app to enable the mic and the Reflect button.
  • POST /journal/interview body { system_prompt: str, turns: [{role: "interviewer"|"me", content: str}] } → { question: str }.
  • POST /journal/synthesis body { turns: [...] } → { prose: str }.
  • Errors: 503 when DeepSeek is not configured, 502 on provider failure, 422 when turns has no me turn (synthesis) or is empty (interview).

5.2 loryth-journal

Media

Replace the presigned endpoints:

  • POST /journals/{journal_id}/media — multipart file, form kind (audio|photo|video|file). Validates the journal exists, size ≤ 25 MB (413), audio mime for kind=audio (415). MediaService.store(space_id, journal_uuid, kind, mime_type, data) -> MediaAssetDto(asset_id, kind, mime_type, byte_size) writes {space_id}/{journal_uuid}/{asset_id} with put_object(..., content_type=mime_type); asset_id is a server-generated UUID string. Returns 201 with the DTO.
  • GET /journals/{journal_id}/media/{asset_id} — StreamingResponse from get_object, with the stored Content-Type, Content-Length when known, Cache-Control: private, max-age=3600, and Accept-Ranges: none. 404 when missing.
  • DELETE /journals/{journal_id}/media/{asset_id} — unchanged.

Remove generate_upload_url/generate_download_url and their schema models; update tests/api/test_media.py to the new endpoints (the conftest's MagicMock(spec=Minio) can return a small object for get_object with .stream() and .headers).

Audio assets are referenced from attachment_ref items and from reflection_turn.audio_asset_id. Deleting an entry or discarding a session deletes its assets (best effort, logged on failure).

Reflection sessions

Migration v06-reflection.sql:

CREATE TYPE reflection_status AS ENUM ('draft', 'complete');
CREATE TYPE reflection_role AS ENUM ('interviewer', 'me');

CREATE TABLE reflection_preset (
    id               BIGSERIAL PRIMARY KEY,
    uuid             uuid         NOT NULL DEFAULT uuid_generate_v4(),
    key              VARCHAR(64)  NOT NULL,
    name             VARCHAR(128) NOT NULL,
    opening_question TEXT         NOT NULL,
    system_prompt    TEXT         NOT NULL,
    position         INT          NOT NULL DEFAULT 0,
    created_at       TIMESTAMP    NOT NULL DEFAULT NOW(),
    updated_at       TIMESTAMP    NOT NULL DEFAULT NOW()
);
CREATE UNIQUE INDEX uq_reflection_preset__key ON reflection_preset (key);

CREATE TABLE reflection_session (
    id           BIGSERIAL PRIMARY KEY,
    uuid         uuid              NOT NULL DEFAULT uuid_generate_v4(),
    journal_id   BIGINT            NOT NULL REFERENCES journal (id) ON DELETE CASCADE,
    space_id     uuid              NOT NULL,
    user_id      uuid              NOT NULL,
    preset_id    BIGINT            NOT NULL REFERENCES reflection_preset (id),
    entry_id     BIGINT            NULL REFERENCES entry (id) ON DELETE SET NULL,
    status       reflection_status NOT NULL DEFAULT 'draft',
    session_date DATE              NOT NULL,
    timezone     VARCHAR(64)       NOT NULL DEFAULT 'UTC',
    prose        TEXT              NULL,
    created_at   TIMESTAMP         NOT NULL DEFAULT NOW(),
    updated_at   TIMESTAMP         NOT NULL DEFAULT NOW()
);
CREATE UNIQUE INDEX uq_reflection_session__uuid ON reflection_session (uuid);
CREATE INDEX idx_reflection_session__journal_status ON reflection_session (journal_id, status);
CREATE INDEX idx_reflection_session__user_status ON reflection_session (user_id, status);

CREATE TABLE reflection_turn (
    id                     BIGSERIAL PRIMARY KEY,
    uuid                   uuid            NOT NULL DEFAULT uuid_generate_v4(),
    session_id             BIGINT          NOT NULL REFERENCES reflection_session (id) ON DELETE CASCADE,
    position               INT             NOT NULL,
    role                   reflection_role NOT NULL,
    content                TEXT            NOT NULL,
    audio_asset_id         VARCHAR(64)     NULL,
    audio_mime_type        VARCHAR(128)    NULL,
    audio_duration_seconds DOUBLE PRECISION NULL,
    created_at             TIMESTAMP       NOT NULL DEFAULT NOW(),
    updated_at             TIMESTAMP       NOT NULL DEFAULT NOW()
);
CREATE UNIQUE INDEX uq_reflection_turn__session_position ON reflection_turn (session_id, position);

Seed the six presets in the same migration with the prompts ported verbatim from souperk-voice-to-text/src/voice_to_text/diary/prompts.py (keys open-check-in, morning-pages, gratitude-x3, stoic-evening, worry-dump, weekly-review; positions 0–5). Change the phrase "clicking Done" in the ported prompts to "clicking End the page" so the model's instructions match the UI.

Domain: domain/reflection/ with reflection_session.py (aggregate, child ReflectionTurn with cascade="all, delete-orphan", order_by position), reflection_preset.py, repositories, DTOs, enums.py, exceptions.py (ReflectionNotFoundError, PresetNotFoundError, ReflectionStateError, AiUnavailableError), prompts.py (transcript formatting helpers shared with keep), and reflection_service.py. Keep each file focused; the service may be split into reflection_service.py (sessions and turns) and reflection_keep_service.py (synthesis and keep) if it grows past ~300 lines.

domain/ai_gateway.py: AiGateway protocol with next_question(user_id, system_prompt, turns) -> str and synthesize(user_id, turns) -> str; HttpAiGateway(base_url=env LORYTH_AI_URL) uses httpx.Client(timeout=130) and forwards x-user-id and the incoming bearer token; maps 503 to AiUnavailableError("Ask an admin to configure DeepSeek in Settings first") and other failures to AiUnavailableError("DeepSeek could not answer right now"). Registered through InfrastructureConfig; tests register StubAiGateway (returns "Stub question?" and "Stub prose.") in the test container.

Rules enforced by the service:

  • Creating a session writes turn 0 (the preset's opening question) in the same transaction.
  • add_turn appends the "me" turn and commits before calling the gateway; the interviewer turn is appended in a second transaction after the gateway returns. If the gateway fails, the "me" turn stays and the API returns 502 with the saved turn in the body so the client can show "Ask again".
  • retry_question requires the last turn to be "me".
  • change_preset only while no "me" turn exists; replaces turn 0.
  • synthesize requires at least one "me" turn; stores prose and returns the session.
  • update_prose stores user edits on a draft.
  • keep(prose): creates the entry through EntryService.create_entry with occurred_at = now(UTC) (or noon of session_date in the session timezone when session_date is not today), items: note(format=md, text=prose, position 0) then one attachment_ref(kind=audio, asset_id, mime_type, duration_seconds, transcript=<turn content>, caption="Reply N") per "me" turn with audio; links entry_id, sets status=complete.
  • discard deletes a draft session, its turns, and its audio assets. Complete sessions cannot be discarded (delete the entry instead; the session is kept for the transcript expander).
  • sweep_empty_drafts: drafts older than 24 h with no "me" turn are deleted when the user lists drafts (cheap, no scheduler).

Router api/reflections/router.py:

Method and path Body / query Returns
GET /reflection/presets — [PresetModel{id, key, name, opening_question, position}]
POST /journals/{journal_id}/reflections {user_id, preset_key, session_date, timezone} ReflectionModel (201)
GET /journals/{journal_id}/reflections?user_id&status=draft — [ReflectionModel]
GET /reflections/{id} — ReflectionModel
PATCH /reflections/{id} {preset_key?} or {prose?} ReflectionModel (409 when preset change is no longer allowed)
POST /reflections/{id}/turns {content, audio_asset_id?, audio_mime_type?, audio_duration_seconds?} ReflectionModel; 502 {detail, data: ReflectionModel} when the AI call fails after saving the turn
POST /reflections/{id}/turns/retry — ReflectionModel
POST /reflections/{id}/synthesis — ReflectionModel with prose
POST /reflections/{id}/keep {prose} { session: ReflectionModel, entry: EntryModel }
DELETE /reflections/{id} — 204
GET /entries/{entry_id}/reflection — ReflectionModel (404 when the entry did not come from a reflection)

ReflectionModel: id, journal_id, user_id, preset {key, name}, status, session_date, timezone, prose, entry_id, turns [{id, position, role, content, audio_asset_id, audio_mime_type, audio_duration_seconds}], created_at, updated_at.

Days and on this day

domain/days_service.py (DaysService) with two repository queries on entry:

  • GET /journals/{journal_id}/days?from=YYYY-MM-DD&to=YYYY-MM-DD&tz=Europe/Athens&user_id= → [{date, entry_count, draft_reflection_count}], grouping the existing TIMESTAMPTZ occurred_at AT TIME ZONE :tz by date; includes draft sessions by session_date. Range capped at 400 days.
  • GET /journals/{journal_id}/on-this-day?date=YYYY-MM-DD&tz=&user_id= → [EntryModel] for the same month and day in earlier years (ordered newest first, max 10).

Entries already support since/until; the Day page uses them with the local day boundaries converted to UTC on the client.

Compose and gateway

  • loryth-journal-api and loryth-journal-worker environment gains LORYTH_AI_URL: http://loryth-ai-api:8000.
  • nginx /api/v1/journal block: add proxy_read_timeout 300s; and client_max_body_size 30M;.

5.3 Web app

Files (keep each under ~250 lines; split further when a file grows):

packages/app/src/shared/voice/
  useVoiceRecorder.ts        # MediaRecorder + AnalyserNode; states idle|requesting|recording|stopped|denied|unsupported
  RecordButton.tsx           # mic button with disabled reason
  RecordingStrip.tsx         # dot, timer, level meter, Stop/Cancel, Transcribing state
  AudioChip.tsx              # "Voice note · 0:42", play/pause, keep-audio, remove
  AudioPlayer.tsx            # <audio> wrapper with play/pause button and duration
  voice.css.ts
  formatDuration.ts
packages/app/src/modules/journal/
  JournalLayout.tsx          # rail + outlet; default journal bootstrap
  TodayPage.tsx
  DayPage.tsx
  ReflectionPage.tsx
  EntryPage.tsx
  index.ts
  journal.css.ts, rail.css.ts, reflection.css.ts, entry.css.ts
  api/journal-api.ts         # customFetch functions (journals, entries, media, days, reflections)
  api/ai-journal-api.ts      # /api/v1/ai/journal/status, /api/v1/ai/audio/transcriptions
  api/queries.ts             # TanStack hooks + journalKeys
  api/types.ts
  hooks/useDefaultJournal.ts # list `/spaces/{userId}/journals?user_id=` → create "Journal" (private) when empty
  hooks/useJournalStatus.ts
  hooks/useReflectionSession.ts  # thread state machine: awaitingUser|askingQuestion|synthesizing|review; abort handling
  components/CaptureBar.tsx
  components/PresetPicker.tsx
  components/HeatmapCalendar.tsx + heatmapGrid.ts (pure grid math, unit tested)
  components/RecentEntries.tsx, OnThisDay.tsx
  components/EntryCard.tsx
  components/ReflectionThread.tsx, ReflectionComposer.tsx, ReflectionReview.tsx, ThinkingRow.tsx
  components/TranscriptExpander.tsx
  lib/entryText.ts           # prose/note extraction, snippet, badges from items
  lib/dayRange.ts            # local day → UTC since/until; YYYY-MM-DD helpers

Navigation: add { label: 'Journal', path: '/journal', icon: NotebookPen } after Notes in config/navigation.ts and '/journal': 'Journal' in routeTitles. Routes in App.tsx:

<Route path="journal" element={<JournalLayout />}>
  <Route index element={<TodayPage />} />
  <Route path="days/:date" element={<DayPage />} />
  <Route path="reflections/:sessionId" element={<ReflectionPage />} />
  <Route path="entries/:entryId" element={<EntryPage />} />
</Route>

API package: packages/api/src/admin-settings.ts gains the Deepgram fields. Journal fetchers live in the app (like Notes) because the backend has no OpenAPI yet.

Uploads use customFetch with a FormData body; extend customFetch so it does not set Content-Type or JSON.stringify when data instanceof FormData.

useVoiceRecorder picks the first supported of audio/webm;codecs=opus, audio/webm, audio/mp4, audio/ogg;codecs=opus; exposes { state, duration, level, start, stop, cancel, blob, mimeType, error }; stops all tracks on stop/cancel/unmount; collects chunks every 1 s so a tab crash loses at most a second.

The admin SettingsPage gets a DeepgramForm next to DeepSeekForm; extract the shared key-field behaviour into ProviderKeyFields.tsx rather than duplicating the DeepSeek form.

5.4 Error Handling and Edge Cases

Situation Behaviour
Deepgram not configured GET /ai/journal/status says so; mic disabled with explanation; typing and reflection still work.
DeepSeek not configured Reflect button disabled with "Ask an admin to configure DeepSeek in Settings"; voice notes still work.
Browser without MediaRecorder Mic hidden; capture bar hint "Voice notes need a browser with microphone recording."
Transcript empty (silence) Deepgram returns ""; show Notice tone="warning" "No speech detected" and keep the audio chip.
Turn saved but question failed 502 with the session in the body; thread shows the turn and Ask again.
User navigates away mid-recording beforeunload prompt while recording or transcribing; recorder stopped on unmount.
Two tabs on the same draft Server appends by position; a 409 on a position clash makes the client refetch and show the latest thread.
Keep fails after synthesis Prose is already saved on the session; the user can retry Keep.
Entry deleted while open 404 → Notice tone="error" "This entry no longer exists" with a link to Today.

6. Test Matrix

6.1 loryth-ai

  • tests/test_loryth_ai/api/test_audio_transcriptions.py: happy path with the stub provider; 503 when no key; 413 oversize; 415 wrong type.
  • tests/test_loryth_ai/domain/test_deepgram_transcription_provider.py: request shape (model, smart_format, headers, body passthrough) and response parsing using respx; whisper models skip smart_format; error wrapping without leaking the key.
  • tests/test_loryth_ai/api/test_journal_reflection.py: interview builds alternating messages and returns the stub answer; synthesis wraps the transcript and drops a trailing interviewer turn; 422 on empty turns; 503 when DeepSeek unconfigured.
  • tests/test_loryth_ai/api/test_settings.py: extended for Deepgram fields, key replace and remove.
  • Existing chat tests unchanged and green after the resolver extraction.

6.2 loryth-journal

  • tests/api/test_media.py: upload stores with the right key and content type; download streams headers and body; 413/415; delete.
  • tests/api/test_reflections.py: presets listed in order; create writes turn 0; add turn appends me + interviewer; gateway failure keeps the me turn and returns 502 with the session; retry; preset change allowed only before the first reply; synthesis stores prose; keep creates an entry with note and audio items and links it; discard removes audio; GET /entries/{id}/reflection.
  • tests/api/test_days.py: counts respect timezone boundaries; draft counts; on-this-day across years.
  • conftest.py: register StubAiGateway; add new tables to cleanup_db in FK order (reflection_turn, reflection_session; presets are seed data and are kept).

6.3 Web

  • Vitest: heatmapGrid (columns, month labels, intensity tiers, today, future days excluded); entryText (snippet, badges); dayRange; useVoiceRecorder with a mocked MediaRecorder and getUserMedia (states, cancel discards, unsupported); useReflectionSession reducer transitions including abort and retry; CaptureBar renders disabled mic with the explanation when transcription is not configured; DeepgramForm save payload.
  • Playwright demo tests/demo/journal.e2e.ts: sign in, open Journal, type a quick note, see it on Today and in Recent, open the entry page, edit, go to the day page, delete, confirm the heatmap cell count, and check the 390 px viewport has no horizontal scroll. The AI paths are not exercised in e2e (they need DeepSeek and Deepgram credentials).
  • pnpm typecheck and pnpm lint clean.

7. Acceptance Criteria

  • Journal appears in the sidebar; /journal bootstraps a default private journal for the user.
  • Typing a line and pressing Enter saves an entry that appears in Today, Recent, and the heatmap.
  • With Deepgram configured, recording a voice note produces an editable transcript and saves text plus audio; the entry page plays the audio.
  • Without Deepgram, the mic is disabled with a clear explanation and admins get a link to Settings.
  • A reflection can be started from any of the six presets, replied to by typing or speaking, ended, edited, and kept; the kept entry shows the prose, the audio, and the transcript expander.
  • Reloading during a reflection resumes it; Today offers to continue or discard a draft.
  • A failed question leaves the reply in the thread with "Ask again".
  • Admins can save and remove the Deepgram key and change the model on Settings.
  • All new and existing service tests pass; web typecheck, lint, and unit tests pass; the journal Playwright demo passes against a running stack.

8. Rollout

Phase 1 — services: AI settings + Deepgram provider + transcription endpoint; AI reflection endpoints and provider resolver extraction; journal media rework; reflection schema, services, router; days endpoints; compose and nginx changes; tests.

Phase 2 — web: voice feature module; journal pages and rail; admin Deepgram card; API fetchers; unit tests; Playwright demo.

Phase 3 — docs: update server/services/loryth-journal/CLAUDE.md and docs/ (domain areas, migrations), server/services/loryth-ai/CLAUDE.md, the journal service docs/spec.md (reflection aggregate), and ui/packages/app/src/testing/mocks/handlers.ts only if the web tests need it.

No migration of existing data is needed; the presigned media endpoints had no UI consumers.

9. Risks and Mitigations

Risk Mitigation
DeepSeek latency makes the interview feel broken Escalating thinking copy, Stop, and "Ask again"; the turn is never lost.
Safari audio/mp4 recordings Deepgram accepts mp4; the recorder picks the first supported mime; the chip shows duration from the recorder, not the container.
Large audio through the gateway 25 MB cap per file, 10 min recording cap, nginx body limit raised for the journal block.
Journal → AI coupling AiGateway is one small class with a stub; failures degrade to typed-only.
Prompt drift between desktop app and Loryth Prompts are ported verbatim and kept in one place per service.

Implementation notes

  • Settings share key encryption/validation in cipher.py and provider_settings.py; the two small provider read/write methods stay in settings_service.py. An outer transaction updates both provider blocks together.
  • Run provider selection now also calls ModelProviderResolver.resolve_binding, keeping saved DeepSeek key handling in one place.
  • QueryClient-seeded Storybook stories live in ui/packages/app/src/stories/journal/. Their MemoryRouter and audio-source decorator use no service requests on render; the review audio uses a local data URL. Stories cover every requested recording/reflection/browsing/settings state. Today and Reflection include Phone stories at 390 × 844. The Theme toolbar applies the app’s light or dark CSS variables and theme attribute to every story; light is the default.
  • The text-only Playwright demo uses an existing approved account (LORYTH_TEST_USERNAME, LORYTH_TEST_PASSWORD), since new signups require approval. It does not require provider credentials.
  • The heatmap and reflection thread use thin, token-colored scrollbars. Short reflection conversations sit at the bottom of the scroll area; longer conversations retain scrolling and auto-follow until the reader scrolls away. The wrapped phone header keeps spacing[2] between rows and a content-sized End the page button.
  • The resume-draft banner uses small ghost actions for Continue and Discard, with “today” and “yesterday” lower-cased inside the sentence.
  • Direct local development can set LORYTH_JOURNAL_URL for Vite's journal proxy, like the existing per-service proxies.

10. Changelog

Date Change
2026-10-30 Initial version

11. Glossary

Term Definition
Voice note An entry created from a recording: a note item with the transcript and an attachment_ref audio item.
Reflection A guided interview session that ends in a prose entry.
Turn One message in a reflection: interviewer (model) or me (user).
Preset A named interviewer style: opening question plus system prompt.
Keep The action that turns a reflection's prose into a journal entry.