Skip to content

feat(fetcher): add deariary_* family for diary entries - #176

Merged
unhappychoice merged 7 commits into
mainfrom
feat/deariary-fetcher-family
Apr 28, 2026
Merged

unhappychoice merged 7 commits into
mainfrom
feat/deariary-fetcher-family

Conversation

@unhappychoice

@unhappychoice unhappychoice commented Apr 27, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Adds three deariary_* fetchers (Safe, cached, host-pinned to api.deariary.com) backed by a shared HTTP client that dedups concurrent calls, caches responses for 60s, caps in-flight requests at 4, and honors Retry-After once on 429.
  • deariary_today — most recent entry (today's, falling back to yesterday's when today's hasn't generated yet). 6 shapes.
  • deariary_recent — newest-first list with limit (1..=100) + tag options. 8 shapes including a Calendar that highlights this month's entry days.
  • deariary_on_this_day — same calendar day anchors at 1m / 3m / 6m / 1y / 2y / 3y / 4y / 5y ago fetched in parallel; missing anchors silently skipped. 7 shapes.
  • LinkedTextBlock rows produce OSC 8 hyperlinks pointing at https://app.deariary.com/entries/YYYY/MM/DD.
  • Side fix: list_links gains a without_osc8 thread-local guard, applied in runtime::render_full_into_buffer so off-screen TestBackend captures don't bake OSC 8 escape sequences into the snapshot buffer (real-terminal output is unchanged).

Ticks the deariary_* checkbox in #68.

deariary_today

The most recent auto-generated deariary.com entry — typically today's, falling back to yesterday's when today's hasn't generated yet. Aggregated from external tools (GitHub, Calendar, Slack, Linear, ...); requires the Advanced plan.

Kind Safety Shapes
cached Safe text_block, text, markdown_text_block, linked_text_block, entries, badge

Options

Option Type Required Default Description
token string no — Deariary API token (Bearer). Falls back to the DEARIARY_TOKEN env var.

Compatible renderers

Shape Renderers
text_block animated_boot, animated_postfx, animated_scanlines, animated_splitflap, animated_wave, list_plain
text animated_boot, animated_figlet_morph, animated_postfx, animated_scanlines, animated_splitflap, animated_typewriter, animated_wave, text_ascii, text_plain
markdown_text_block text_markdown
linked_text_block list_links
entries grid_table, animated wrappers
badge status_badge, animated wrappers

deariary_recent

Recent auto-generated deariary.com entries, newest first. Timeline (default) carries the chronological ranking; TextBlock / Entries / MarkdownTextBlock / LinkedTextBlock carry the same ranking in their respective row formats; Calendar highlights this month's entry days; Text and Badge summarise the headline.

Kind Safety Shapes
cached Safe timeline, text, text_block, markdown_text_block, linked_text_block, entries, badge, calendar

Options

Option Type Required Default Description
token string no — Deariary API token. Falls back to the DEARIARY_TOKEN env var.
limit integer (1..=100) no 10 Maximum number of entries to render in row-shaped views.
tag string no — Restrict results to a single tag slug.

Compatible renderers

Shape Renderers
timeline list_timeline, animated wrappers
text text_plain, text_ascii, animated_typewriter, animated wrappers
text_block list_plain, animated wrappers
markdown_text_block text_markdown
linked_text_block list_links
entries grid_table, animated wrappers
badge status_badge, animated wrappers
calendar grid_calendar, animated wrappers

deariary_on_this_day

Past auto-generated deariary.com entries from the same calendar day, fetched in parallel for 1m / 3m / 6m / 1y / 2y / 3y / 4y / 5y ago. Anchors with no entry are silently skipped.

Kind Safety Shapes
cached Safe text_block, timeline, text, markdown_text_block, linked_text_block, entries, badge

Options

Option Type Required Default Description
token string no — Deariary API token. Falls back to the DEARIARY_TOKEN env var.

Compatible renderers

Same shape × renderer matrix as deariary_today, plus timeline → list_timeline.

Test plan

  • cargo fmt --all -- --check
  • cargo clippy --all-targets -- -D warnings
  • cargo test (1056 + 12 passed, 9 ignored)
  • User smoke-test: 17-widget dashboard exercising every shape × renderer combination renders without panic; OSC 8 hyperlinks clickable in the real terminal.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Deariary integration: three fetchers (today, recent, on-this-day) exposing multiple output shapes (text, markdown, timeline, calendar, linked entries).
    • Structured error payload/shape so failures render as clear inline error messages.
  • Improvements

    • Token handling, per-account caching, deduplicated in-flight requests, and polite retry behavior for more reliable fetching.
    • Off-screen hyperlink suppression to prevent escape-sequence noise in captures while keeping on-screen links.
  • Tests

    • Expanded unit tests for parsing, rendering, caching, error cases, and edge conditions.

Three Safe / cached / api.deariary.com fetchers covering the auto-generated
diary surface:

- deariary_today — most recent entry (today's, falling back to yesterday's
  when today's hasn't generated yet); 6 shapes (TextBlock / Text /
  MarkdownTextBlock / LinkedTextBlock / Entries / Badge).
- deariary_recent — newest-first list with `limit` (1..=100) + `tag`
  options; 8 shapes (Timeline default + Text / TextBlock /
  MarkdownTextBlock / LinkedTextBlock / Entries / Badge / Calendar with
  current month's entry days highlighted).
- deariary_on_this_day — past entries from the same calendar day at
  1m/3m/6m/1y/2y/3y/4y/5y anchors fetched in parallel via JoinSet, missing
  anchors silently skipped; 7 shapes (TextBlock default + Timeline / Text
  / MarkdownTextBlock / LinkedTextBlock / Entries / Badge).

Shared HTTP client (`src/fetcher/deariary/client.rs`) dedups concurrent
requests, caches responses for 60s, caps in-flight calls to 4, and honors
Retry-After once on 429. `entry_url(date)` produces
https://app.deariary.com/entries/YYYY/MM/DD for LinkedTextBlock rows.

list_links rendering: add a `without_osc8` thread-local guard and apply it
in runtime::render_full_into_buffer so off-screen TestBackend captures
don't bake OSC 8 escape sequences into the buffer (real terminal output is
unchanged).

Ticks #68.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Apr 27, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@unhappychoice has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 40 minutes and 56 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ea34e73c-8ab2-4bbb-b5ce-d45143f973f6

📥 Commits

Reviewing files that changed from the base of the PR and between 761c1d1 and 2b2e655.

📒 Files selected for processing (3)
  • src/fetcher/deariary/client.rs
  • src/fetcher/deariary/recent.rs
  • src/fetcher/deariary/today.rs
📝 Walkthrough

Walkthrough

Adds a deariary.com fetcher family with a shared HTTP client, token/caching/dedup helpers, three fetchers (today, recent, on_this_day), structured error payloads and short-circuit error rendering, off-screen OSC8 suppression, and registers the new fetchers in the fetcher registry.

Changes

Cohort / File(s) Summary
Deariary HTTP/Client
src/fetcher/deariary/client.rs
New shared client: API_BASE, MAX_LIST_LIMIT, singleton reqwest client, process semaphore (max 4), bounded concurrent requests, 60s memo cache with in-flight dedup, entry_url, resolve_token, token_scope/cache_extra, send_with_retry (404 success, 1x retry on 429 using Retry-After capped), cached_get_entry, cached_get_entries, DTOs and unit tests.
Deariary Fetchers
src/fetcher/deariary/mod.rs, src/fetcher/deariary/today.rs, src/fetcher/deariary/recent.rs, src/fetcher/deariary/on_this_day.rs
Adds three Fetcher implementations (Today, Recent, OnThisDay). Each parses options (token/limit/tag), resolves token, calls shared client, constructs shape-specific Payloads (Text/TextBlock/Markdown/LinkedTextBlock/Entries/Badge/Timeline/Calendar), includes sample bodies and comprehensive unit tests.
Fetcher Registry & Fetcher API
src/fetcher/mod.rs
Registers deariary module and returns the new fetchers via fetchers(); replaces prior placeholder-body mechanism with a shape-independent error_payload/placeholders and updates related signatures/tests.
Structured Error Payloads
src/payload.rs, src/render/mod.rs, src/samples.rs
Adds Body::Error(ErrorData), ErrorData, ErrorKind, Shape::Error; maps Body::Error→Shape::Error; render_payload short-circuits to render_error_body; treats error bodies as non-empty; samples skip Shape::Error; serde tests updated.
OSC8 Suppression & list_links
src/render/list_links.rs, src/render/mod.rs, src/runtime.rs
Adds without_osc8 (thread-local suppression, RAII restore, panic-safe, re-entrant), makes list_links public, wraps off-screen TestBackend draws in without_osc8 to avoid OSC8 escapes in off-screen capture; tests updated.
Runtime & Trust
src/runtime.rs, src/trust.rs
Runtime uses new shape-independent placeholders; requires_trust_placeholder() now returns an Error payload (ErrorKind::RequiresTrust) and sets status to Error; tests adjusted.
Misc tests / fixtures
src/...
Extensive unit tests added/updated across client, fetchers, rendering, placeholders, OSC8 suppression, and payload serde round-trips.

Sequence Diagrams

sequenceDiagram
    participant Fetcher as Deariary<br/>Fetcher
    participant Cache as In-process<br/>Cache (dedup, TTL)
    participant Sem as Semaphore<br/>(max 4)
    participant HTTP as Reqwest<br/>Client
    participant API as deariary<br/>API

    Fetcher->>Cache: cached_get_entry(token, date)
    Cache->>Cache: Check cached value & in-flight slot
    alt Cached hit
        Cache-->>Fetcher: Return cached value
    else Miss
        Cache->>Sem: Acquire permit
        Sem->>HTTP: send_with_retry(GET /entries/{date} with Bearer)
        HTTP->>API: HTTP GET
        API-->>HTTP: 200 / 404 / 429 / 5xx
        alt 429
            HTTP->>HTTP: Parse Retry-After (cap), sleep, retry once
            HTTP->>API: Retry GET
            API-->>HTTP: Response
        end
        alt 200
            HTTP->>Cache: Store result (60s) and return
        else 404
            HTTP->>Cache: Store None and return
        else error
            HTTP-->>Fetcher: Return FetchError
        end
        Sem->>Sem: Release permit
    end
Loading
sequenceDiagram
    participant Runtime as Runtime
    participant Render as render_full_into_buffer
    participant OSC8 as without_osc8<br/>suppressor
    participant Layout as layout::draw
    participant Writer as write_row<br/>(list_links)
    participant Buffer as TestBackend<br/>Buffer

    Runtime->>Render: Render off-screen
    Render->>OSC8: Call closure
    OSC8->>OSC8: Set thread-local flag (true)
    OSC8->>Layout: layout::draw()
    Layout->>Writer: write_row(...)
    Writer->>Writer: Check thread-local flag
    alt true
        Writer->>Buffer: Write text without OSC8
    else false
        Writer->>Buffer: Write OSC8-wrapped hyperlink
    end
    Layout-->>OSC8: Done
    OSC8->>OSC8: Restore previous flag
    OSC8-->>Render: Return
    Render-->>Runtime: Off-screen buffer
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐇 I hopped through APIs and cached each treat,

retried once when rate limits skipped a beat.
Three fetchers sprang—today, recent, on-this-day,
off-screen I hush my links so tests can play.
Hop on, dear diary, your memories I keep.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the primary change: adding three deariary_* fetchers (deariary_today, deariary_recent, deariary_on_this_day) for diary entries. It is concise, specific, and directly reflects the main objective.
Docstring Coverage ✅ Passed Docstring coverage is 97.38% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/deariary-fetcher-family

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented Apr 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.42254% with 278 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.09%. Comparing base (969168b) to head (2b2e655).
⚠️ Report is 20 commits behind head on main.

Files with missing lines Patch % Lines
src/fetcher/deariary/client.rs 60.76% 133 Missing ⚠️
src/fetcher/deariary/on_this_day.rs 78.87% 60 Missing ⚠️
src/fetcher/deariary/today.rs 83.46% 42 Missing ⚠️
src/fetcher/deariary/recent.rs 91.12% 26 Missing ⚠️
src/runtime.rs 78.57% 6 Missing ⚠️
src/fetcher/mod.rs 94.59% 4 Missing ⚠️
src/render/mod.rs 89.74% 4 Missing ⚠️
src/render/list_links.rs 97.50% 1 Missing ⚠️
src/samples.rs 0.00% 1 Missing ⚠️
src/trust.rs 94.44% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #176      +/-   ##
==========================================
+ Coverage   78.73%   79.09%   +0.36%     
==========================================
  Files         132      137       +5     
  Lines       26018    27838    +1820     
==========================================
+ Hits        20485    22019    +1534     
- Misses       5533     5819     +286     
Files with missing lines Coverage Δ
src/fetcher/deariary/mod.rs 100.00% <100.00%> (ø)
src/payload.rs 100.00% <100.00%> (ø)
src/render/list_links.rs 95.12% <97.50%> (+0.46%) ⬆️
src/samples.rs 65.60% <0.00%> (+9.14%) ⬆️
src/trust.rs 81.75% <94.44%> (+0.21%) ⬆️
src/fetcher/mod.rs 84.97% <94.59%> (+3.13%) ⬆️
src/render/mod.rs 90.49% <89.74%> (-0.10%) ⬇️
src/runtime.rs 80.52% <78.57%> (+0.23%) ⬆️
src/fetcher/deariary/recent.rs 91.12% <91.12%> (ø)
src/fetcher/deariary/today.rs 83.46% <83.46%> (ø)
... and 2 more

... and 23 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

- client.rs: doc said semaphore lets "2 in flight" but the const is 4.
- recent.rs: drop the local `MAX_LIMIT` const and clamp via the shared
  `client::MAX_LIST_LIMIT` so the list-page upper bound has one source of
  truth.
- today.rs: render_badge labelled the entry "today" unconditionally, which
  lied when today's hadn't generated yet and the fetcher fell back to
  yesterday's. Pass `today` from `Local::now()` into render and resolve the
  label as `today` / `yesterday` / raw ISO date based on `entry.date`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/fetcher/deariary/client.rs`:
- Around line 84-108: Cache slots are currently keyed only by date/tag (via
entry_slot(date) and list_slot(tag)) which allows cross-account leakage; update
the slot key to include the token so caches are scoped per-token: change
entry_slot and list_slot to take the token (e.g., entry_slot(token, date) and
list_slot(token, tag_key)) and update all call sites (including
cached_get_entries and the single-entry path that calls entry_slot) to pass the
token; ensure the internal key/hash used by those functions incorporates the
token string (not a pointer) so entries are isolated per account.
- Around line 72-79: In resolve_token, trim whitespace from both the provided
config_token and the environment variable value before checking emptiness and
converting to String; replace the current filter(|v| !v.is_empty()) with logic
that maps config_token through str::trim and treats it as empty if trimmed is
empty, and when falling back to std::env::var("DEARIARY_TOKEN") call
.ok().map(|s| s.trim().to_string()) (or trim before is_empty check) so that
whitespace-only tokens are rejected and the function still returns
FetchError::Failed with the same message when no non-empty trimmed token exists.

In `@src/fetcher/deariary/on_this_day.rs`:
- Around line 174-183: The loop handling set.join_next() is silently ignoring
JoinSet join failures (the Err(_) arm), which can hide panics/cancellations;
update the Err(_) branch to increment error_count and set last_error (e.g., to
Some(join_err)) similar to how task-level Err(err) is handled so join failures
are surfaced—modify the match in the while let Some(joined) =
set.join_next().await block to record the join error into error_count and
last_error instead of discarding it, referencing the set.join_next() match,
hits.push((idx, entry)), error_count, and last_error symbols.

In `@src/render/list_links.rs`:
- Around line 127-134: The current without_osc8 sets OSC8_SUPPRESSED but only
restores it after f() returns, so a panic inside f() leaves the thread-local
suppressed; make it panic-safe by creating an RAII guard local to without_osc8
that captures the prior value and restores OSC8_SUPPRESSED in its Drop impl (use
the same OSC8_SUPPRESSED.with(|cell| ...) calls to save prior and set back),
then call f() while the guard is live so that if f() panics the Drop will always
run and reset the state; reference the without_osc8 function and OSC8_SUPPRESSED
variable when locating where to add the guard.

In `@src/render/mod.rs`:
- Around line 446-453: The current code always prefers
body_as_text(&payload.body) as the error message which masks real renderer/shape
mismatches for normal TextBlock payloads; change the logic in the render error
path so that you only substitute the body text when the payload actually
represents a placeholder/error/timeout (e.g., a trust placeholder) and otherwise
keep the explicit "renderer {name} cannot display {shape:?}" message.
Concretely, replace the unwrap_or_else(...) call around
body_as_text(&payload.body) with a conditional that matches payload.body (or
uses whatever is_placeholder/is_placeholder_text helper exists) to detect
placeholder cases and only then use the body text; if not a placeholder, call
render_error(frame, area, &format!("renderer {name} cannot display {shape:?}"),
theme). Ensure you reference and preserve the existing symbols body_as_text,
payload.body, TextBlock (or the placeholder variant), render_error, shape, and
name.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7a4c82cd-4a6f-46fd-9159-7cd01e8e6015

📥 Commits

Reviewing files that changed from the base of the PR and between 848b9c5 and 75c1668.

📒 Files selected for processing (9)
  • src/fetcher/deariary/client.rs
  • src/fetcher/deariary/mod.rs
  • src/fetcher/deariary/on_this_day.rs
  • src/fetcher/deariary/recent.rs
  • src/fetcher/deariary/today.rs
  • src/fetcher/mod.rs
  • src/render/list_links.rs
  • src/render/mod.rs
  • src/runtime.rs

Comment thread src/fetcher/deariary/client.rs Resolved
Comment thread src/fetcher/deariary/client.rs Resolved
Comment thread src/fetcher/deariary/on_this_day.rs Resolved
Comment thread src/render/list_links.rs Resolved
Comment thread src/render/mod.rs Resolved
- client.rs: scope cache slots per-token so a process holding multiple
  deariary tokens doesn't serve account A's entries to account B's widget.
  The token participates in the in-process key only — never written to
  disk or logs.
- client.rs: trim whitespace in `resolve_token` for both the config value
  and the env var, and reject whitespace-only tokens. Avoids accidental
  blank-token requests when a copy/paste includes a trailing newline.
- on_this_day.rs: surface JoinSet `Err(_)` (panic / cancellation) like a
  fetch error rather than silently dropping it. A fully-panicking task set
  used to return `Ok(empty)`; it now propagates the JoinError.
- list_links.rs: make `without_osc8` panic-safe via a `Drop`-based RAII
  guard so a panic inside the closure doesn't leak the suppressed
  thread-local into subsequent unrelated draws on the same thread. Adds
  panic-restore + nested-call regression tests.

CodeRabbit's fifth finding (render/mod.rs body-as-text fallback masking
explicit "cannot display" warnings) is the deliberate trade-off
documented in `placeholder_body`: surfacing 429 / timeout / trust
placeholder text beats a generic "cannot display" warning when the
mismatch is caused by a placeholder, and a real misconfiguration still
shows the body inline rather than blank. Keeping current behaviour.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@unhappychoice

Copy link
Copy Markdown
Owner Author

Addressed in 451a53c:

  • client.rs cache key per-token — entry_slot / list_slot now key on (token, date) and (token, tag). Added two regression tests asserting different tokens never share an Arc<…> slot.
  • client.rs resolve_token trims whitespace — both the config value and DEARIARY_TOKEN env var are trimmed before the empty-check, so a copy/paste with trailing newline no longer authenticates as a blank token.
  • on_this_day.rs JoinSet Err(_) — JoinError (panic / cancellation) now increments error_count and stores last_error like a fetch error. A fully-panicking task set used to return Ok(empty); it now propagates.
  • list_links.rs without_osc8 panic-safety — RAII guard via Drop. Two regression tests: state restored after panic, nested-call exit doesn't flip outer suppression off.

On the fifth finding (render/mod.rs body-as-text fallback): keeping current behaviour. It's the deliberate trade-off documented in placeholder_body — when the mismatch is caused by a 429 / timeout / trust placeholder (the dominant case in practice), users get the actionable message instead of a generic "cannot display" warning. Real misconfigurations still surface the body text inline rather than rendering blank, so the path is recoverable from the user's side. Happy to revisit if a placeholder-vs-real-payload discriminator becomes available.

… contract

CodeRabbit pushed back on the body-as-text fallback in render_payload —
masking the "renderer X cannot display Y" warning hides genuine
misconfigurations and breaks the AGENTS.md contract that "users must be
able to see what's misconfigured without crashing the splash."

Revert that fallback. Instead, extend `placeholder_body` to produce
shape-matching bodies for the shapes whose primary renderers carry a
free-form text slot — Badge (Status::Error pill with the message as
label), Ratio (gauge label slot, value=0), and Timeline (one event per
line, Status::Error). 429 / timeout / trust messages now reach
`status_badge` / gauges / `list_timeline` inline without going through
the mismatch path.

Shape-only renderers that genuinely can't carry text (chart_*, grid_*,
media_*, plus Calendar / Bars) keep falling through to TextBlock; for
those, `render_payload` shows the explicit "cannot display" warning,
which is the right answer per the contract.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@unhappychoice

Copy link
Copy Markdown
Owner Author

On reflection, you're right — the AGENTS.md contract is clear ("users must see what's misconfigured") and the body-as-text fallback was too willing to hide it. Reverted in dba8572.

To keep the original placeholder-visibility benefit (the 429 / trust message reaching status_badge, gauges, etc.), I extended placeholder_body so shapes whose primary renderers have a free-form text slot get a shape-matching body:

  • Badge → BadgeData { status: Status::Error, label: msg }
  • Ratio → RatioData { value: 0.0, label: Some(msg), denominator: None }
  • Timeline → one TimelineEvent per line, status: Some(Status::Error)

Shapes whose primary renderers genuinely have no slot for free-form text (Bars, Calendar, NumberSeries, PointSeries, Heatmap, Image) keep falling through to TextBlock; in those cases the explicit "renderer X cannot display TextBlock" warning fires per the contract — which is the right answer there. Tests in placeholder_body_adapts_to_shape cover all three new branches plus the shape-only fallback set.

Restructures the placeholder pipeline so error / timeout / unknown-fetcher
/ shape-mismatch / trust-required widgets carry structured error data all
the way to render, instead of squeezing the message into a shape-coerced
TextBlock and hoping the configured renderer can read it.

Why this was needed: with the previous design, a placeholder targeting a
shape-only renderer (chart_bar, grid_calendar, grid_heatmap, media_image,
chart_sparkline, chart_line) fell through to a TextBlock body and tripped
the AGENTS.md "renderer X cannot display Y" warning — so a 429 / timeout
/ trust message reached the user only via $HOME/.splashboard/logs, not on
screen. CodeRabbit was right that surfacing the body text on every
mismatch masked genuine misconfigurations; the fix is to make the
placeholder its own first-class body variant rather than special-casing
the dispatch path.

Changes:

- payload.rs: new `Body::Error(ErrorData)` variant + `ErrorData` (kind,
  message, detail) + `ErrorKind { Fetch, Timeout, UnknownFetcher,
  ShapeMismatch, RequiresTrust }`.
- render/mod.rs: `Shape::Error` pseudo-shape so `shape_of` stays total.
  `render_payload` short-circuits `Body::Error` to a dedicated
  `render_error_body` that draws the message inline regardless of the
  configured renderer, bypassing the shape × renderer dispatch entirely.
  The explicit "renderer X cannot display Y" warning still fires for
  genuine non-Error mismatches per the AGENTS contract.
- fetcher/mod.rs: `placeholder_body` removed. `error_placeholder` /
  `timeout_placeholder` / `unknown_fetcher_placeholder` /
  `shape_mismatch_placeholder` shrink to `error_payload` calls; the
  `shape` parameter drops from the four signatures since the body type
  no longer varies by target shape.
- trust.rs: `requires_trust_placeholder` matches the new constructor
  shape and emits `Body::Error` directly.
- runtime.rs: drop the now-unused `shape` argument at every placeholder
  call site (gated / unknown / fetch error / fetch timeout).
- Tests: payload round-trip, fetcher constructor coverage by ErrorKind,
  runtime placeholder paths, trust placeholder, and an integration
  regression that drives a Body::Error through chart_bar (the
  pre-refactor failure case) to confirm the actionable message reaches
  the user.

Out of scope (per discussion with the user): wrapping renderer dispatch
in `catch_unwind`. A renderer panic still aborts the splash; that's a
separate concern from how placeholders propagate.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/payload.rs (1)

68-109: Add a payload-local serde regression for Body::Error.

This changes the cached payload wire format, but this file doesn’t yet lock its own shape = "error" / snake_case kind contract. A small round-trip test here would catch format regressions without depending on placeholder constructors in other modules.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/payload.rs` around lines 68 - 109, Add a focused round-trip serde test
for the payload-local wire format of Body::Error to lock the shape="error"
contract and snake_case ErrorKind serialization: construct an ErrorData instance
(populating kind, message, optional detail), wrap it in the Body::Error variant,
serialize to the canonical payload wire format used elsewhere (e.g., JSON), then
deserialize and assert equality; this test should live near the
ErrorData/ErrorKind definitions so it exercises serde derives on ErrorData,
ErrorKind and will detect regressions to their serialized shape.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/fetcher/deariary/client.rs`:
- Around line 176-195: The cache key built by entry_slot and list_slot using
format!("{token}|{date}") / format!("{token}|{tag}") can collide if token or
value contain '|' — update entry_slot and list_slot to produce collision-safe
keys by hashing the token scope (e.g., SHA-256 or HMAC of token) and combining
the fixed-length hash with the date/tag (or use a tuple/struct key type for
entry_cache/list_cache), so the token is never concatenated raw; change the key
generation in entry_slot and list_slot and keep references to entry_cache() and
list_cache() intact.

In `@src/fetcher/deariary/on_this_day.rs`:
- Around line 83-90: The cache_key implementation for on_this_day (fn
cache_key(&self, ctx: &FetchContext)) only serializes ctx.options and ignores
env-backed auth, so disk caches can be reused across different DEARIARY_TOKEN
values; update cache_key to include a stable token scope string used by the
fetcher’s env fallback (e.g., derive the token identifier from ctx.auth or read
the same env-backed auth scope used by the fetch logic) and append it to the
extra string before calling cache_key(self.name(), ctx, &extra) so different
DEARIARY_TOKEN values produce distinct keys.

---

Nitpick comments:
In `@src/payload.rs`:
- Around line 68-109: Add a focused round-trip serde test for the payload-local
wire format of Body::Error to lock the shape="error" contract and snake_case
ErrorKind serialization: construct an ErrorData instance (populating kind,
message, optional detail), wrap it in the Body::Error variant, serialize to the
canonical payload wire format used elsewhere (e.g., JSON), then deserialize and
assert equality; this test should live near the ErrorData/ErrorKind definitions
so it exercises serde derives on ErrorData, ErrorKind and will detect
regressions to their serialized shape.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: fb662afe-f06f-4fef-8777-abe0a5105ea6

📥 Commits

Reviewing files that changed from the base of the PR and between 75c1668 and 530d143.

📒 Files selected for processing (9)
  • src/fetcher/deariary/client.rs
  • src/fetcher/deariary/on_this_day.rs
  • src/fetcher/mod.rs
  • src/payload.rs
  • src/render/list_links.rs
  • src/render/mod.rs
  • src/runtime.rs
  • src/samples.rs
  • src/trust.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/runtime.rs

Comment thread src/fetcher/deariary/client.rs Resolved
Comment thread src/fetcher/deariary/on_this_day.rs Resolved
…::Error wire format

CodeRabbit review on 530d143:

1. Disk cache leaked across DEARIARY_TOKEN values. Each fetcher's
   cache_key only mixed in ctx.options, so a process that read its
   token from env (rather than [widget.options]) wrote to a cache key
   shared across accounts. Added client::cache_extra that resolves the
   token via the same precedence as fetch (option > env), folds it
   through token_scope (truncated SHA-256), and prefixes the options
   blob. All three fetchers now route through it.

2. entry_slot / list_slot keys built via format!("{token}|{date}")
   could collide if a token contained `|`. Switched to token_scope
   (16-hex-char SHA-256 prefix) so the in-memory slot keys can't
   collide regardless of token content, and the raw token doesn't
   appear in any cache-key string (which surfaces in tracing logs).

3. Body::Error wire format had no payload-local round-trip test,
   leaving cache deserialisation regressions to surface only via
   integration paths. Added round-trips for the full / detail-less /
   shape-tag / kind-naming axes in payload::tests.

Token scope is intentionally a hash, not the raw token: keeps secrets
out of cache filenames and tracing output without compromising the
per-account partitioning. The fetch path still uses the resolved token
itself; only the cache scoping is hashed.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@unhappychoice

Copy link
Copy Markdown
Owner Author

Addressed in 761c1d1:

  • Disk cache leaked across DEARIARY_TOKEN values (the more serious finding): each fetcher's cache_key was only mixing ctx.options, so a process that read the token from env shared the cache slot across accounts. Added client::cache_extra that resolves the token via the same precedence as fetch (option > env), folds it through token_scope (truncated SHA-256), and prefixes the options blob. All three fetchers route through it. Regression test: cache_extra_partitions_disk_cache_per_resolved_token.
  • format!("{token}|{date}") collision risk: switched the in-memory slot keys to use token_scope(token) instead of the raw token. Hash also keeps the bearer out of cache-key strings (which surface in tracing logs and on-disk filenames). Regression test: token_scope_dodges_naive_pipe_separator_collision.
  • Body::Error payload-local round-trip (nitpick): added four tests in payload::tests covering full / detail-less / shape-tag / ErrorKind snake_case naming so wire-format regressions surface without depending on placeholder constructors elsewhere.

Token scope is intentionally a 64-bit truncation of SHA-256 (16 hex chars): plenty of entropy for distinguishing local accounts, short enough to keep cache filenames reasonable, and never the raw token.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/fetcher/deariary/client.rs`:
- Around line 92-105: cache_extra currently serializes the full raw_opts so any
options.token value leaks into cache keys; instead strip/redact the token field
from the options before serialization. Modify cache_extra to resolve the token
using resolve_token and keep the token_scope call, but deep-clone or mutate the
toml::Value from raw_opts to remove the "token" key (or replace it with a
constant placeholder) prior to toml::to_string, then format the cache string as
before; reference cache_extra, resolve_token and token_scope when locating the
change.

In `@src/fetcher/deariary/recent.rs`:
- Around line 156-166: render_body currently truncates entries to `limited`
before dispatching to all shapes, causing headline shapes (Shape::Text,
Shape::Badge, etc.) to report the truncated count; change the match so only
list/timeline renderers use the truncated `limited` slice (e.g., Shape::Entries,
Shape::TextBlock, Shape::MarkdownTextBlock, Shape::LinkedTextBlock,
Shape::Calendar? keep Calendar using full entries as it already does, and
render_timeline use limited), and pass the full entries slice or entries.len()
into headline renderers (`render_text`, `render_badge`) so they can show the
real total; update the render_body match arms to call render_text(&entries) /
render_badge(&entries) (or render_text(&limited, total_count)) and adjust those
renderers' signatures if needed.

In `@src/fetcher/deariary/today.rs`:
- Around line 117-123: latest_entry currently returns the newest available entry
unconditionally, causing stale entries to be treated as "today"; change
latest_entry (and its use of latest.date) to parse the entry date and only
accept it if it equals today or yesterday, otherwise return Ok(None).
Specifically, in latest_entry parse latest.date (e.g.,
NaiveDate::parse_from_str(&latest.date, "%Y-%m-%d") or use the existing date
type), compute Utc::today() and yesterday (or Local if the codebase uses Local),
and if parsed_date == today || parsed_date == yesterday then call
cached_get_entry(token, &latest.date).await and return that result; otherwise
return Ok(None). Ensure to handle parse errors by treating them as Ok(None) or
mapping to FetchError consistently.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: bb40592f-dfe1-4ce3-a7df-babb96b3b275

📥 Commits

Reviewing files that changed from the base of the PR and between 530d143 and 761c1d1.

📒 Files selected for processing (5)
  • src/fetcher/deariary/client.rs
  • src/fetcher/deariary/on_this_day.rs
  • src/fetcher/deariary/recent.rs
  • src/fetcher/deariary/today.rs
  • src/payload.rs
✅ Files skipped from review due to trivial changes (1)
  • src/fetcher/deariary/on_this_day.rs

Comment thread src/fetcher/deariary/client.rs Resolved
Comment thread src/fetcher/deariary/recent.rs Resolved
Comment thread src/fetcher/deariary/today.rs Resolved
… today freshness

CodeRabbit on 761c1d1:

1. cache_extra serialised the whole options blob — including options.token —
   into the intermediate string before hashing. The bearer wouldn't survive
   into the on-disk cache key (sha256-truncated downstream), but it would
   live in panic-backtrace / tracing intermediates. Strip the top-level
   `token` field before serialisation; the hash prefix already partitions
   per account.

2. recent.rs::render_body fed the truncated `limited` slice to every shape,
   so a `limit = 5` widget on a 23-entry cache reported "📔 5 recent" /
   "5 entries · latest: …" instead of the real total. limit governs how
   many ROWS render — not the headline count. Routed Text and Badge to the
   full `entries` slice; row-shaped renderers keep using `limited`.

3. today.rs::latest_entry surfaced the freshest available entry
   unconditionally, so a 5-day-old entry could appear under the "today"
   label. The fetcher's description promises "typically today's, falling
   back to yesterday's" — gate the lookup on a 0/1-day delta from local
   today and return Ok(None) past that, letting the empty-state
   placeholder render instead. Future-dated entries (clock skew) are also
   rejected.

Tests:
- cache_extra_strips_token_from_options_blob asserts the bearer never
  survives serialisation while non-token options still partition.
- text_headline_reports_total_count_not_limit and the matching badge case
  pin the headline-vs-row count distinction.
- freshness_gate_accepts_today_and_yesterday_only enumerates the
  (-1, 0, +1, +N) day deltas.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@unhappychoice

Copy link
Copy Markdown
Owner Author

Addressed in 2b2e655 — all three are real bugs / leak surfaces, not just style:

  • cache_extra serialised options.token into the intermediate: the bearer didn't survive into the final on-disk key (downstream sha256), but it lived in the panic-backtrace / tracing intermediate. Strip the top-level token field from the options blob before serialisation; the hash prefix already partitions per account, so non-token options (tag, limit) still distinguish cache entries. Test: cache_extra_strips_token_from_options_blob.
  • recent.rs headline used the truncated count: a limit = 5 widget on a 23-entry cache reported "📔 5 recent" / "5 entries · latest: …" — limit governs row count, not the total. Routed Shape::Text and Shape::Badge to the full entries slice; row-shaped renderers (TextBlock / Markdown / Linked / Entries / Timeline) keep using limited. Tests: text_headline_reports_total_count_not_limit, badge_headline_reports_total_count_not_limit.
  • today.rs::latest_entry surfaced stale entries as "today": the fetcher's description promises "typically today's, falling back to yesterday's", but the code accepted whatever was newest. Added an is_today_or_yesterday gate (0/1-day delta from local today, also rejecting future dates from clock skew) — older surrogates fall through to Ok(None) and the empty-state placeholder renders. Test: freshness_gate_accepts_today_and_yesterday_only covers (-1, 0, +1, +N, unparseable) day deltas.

@unhappychoice
unhappychoice merged commit b240517 into main Apr 28, 2026
7 checks passed
@unhappychoice
unhappychoice deleted the feat/deariary-fetcher-family branch April 28, 2026 02:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant