From 4dd3f1e07110cd138da2c9ba6bb666ca950ee1c9 Mon Sep 17 00:00:00 2001 From: John Taylor Date: Sat, 22 Aug 2026 07:27:25 -0400 Subject: [PATCH 01/15] docs: tracking-merge design spec (threads+tracks+rumors, sub-project 1 of consolidation epic) Co-Authored-By: Claude Fable 5 --- .../specs/2026-08-22-tracking-merge-design.md | 145 ++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 docs/superpowers/specs/2026-08-22-tracking-merge-design.md diff --git a/docs/superpowers/specs/2026-08-22-tracking-merge-design.md b/docs/superpowers/specs/2026-08-22-tracking-merge-design.md new file mode 100644 index 0000000..26e4ba8 --- /dev/null +++ b/docs/superpowers/specs/2026-08-22-tracking-merge-design.md @@ -0,0 +1,145 @@ +# Tracking Merge — Threads + Tracks + Rumors Become One Entity + +**Date:** 2026-08-22 +**Status:** Approved design, pre-implementation +**Sub-project:** 1 of 7 in the tool-consolidation epic (see "Epic context" below) + +## Problem + +The Track verb offers three ways to track a thing the player cares about: + +- **Threads** (`Thread`, `juice.threads.v1`, `ThreadsPane`) — title, note, open flag, + pinned flag, progress clock (`progress`/`progressMax`), optional bidirectional + `Tally`, journal backlinks via `JournalEntry.threadId`, `@[title](thread:ID)` + mentions. +- **Tracks** (`Track`, `tracksProvider`, `TracksPane`) — name, filled/max progress + bar, note. A strict subset of a thread's clock. +- **Rumors** (`Rumor`, `rumorsProvider`, `RumorsPane`) — text, resolved flag, note, + AI flesh-out. Narratively "a thread that isn't confirmed yet". + +Three panes, three models, three providers — one job. The user chose a true merge: +one integrated entity taking the best of each, old tools deleted. + +## Decisions already made (user-confirmed) + +1. **True merge** — one entity, one pane; separate tools deleted (not just UI unification). +2. **All three merge** — a rumor is a thread in a pre-confirmation stage; a track is a + thread with only a clock. +3. **Fresh start for rumors/tracks data** — existing `Rumor`/`Track` persisted data is + not migrated. Existing threads keep loading (tolerant JSON). +4. **Model approach A** — a stage enum on `Thread` (not a frozen kind, not a new entity). + +## Design + +### 1. Model (`lib/engine/models/journal.dart`) + +`Thread` gains a stage: + +```dart +enum ThreadStage { rumor, active, done } +``` + +- New field `ThreadStage stage`, default `active`. JSON key `stage`, omitted at default. +- The `open` bool is **replaced** by stage. Tolerant `fromJson`: when no `stage` key is + present, `open == false` reads as `done`, anything else as `active` — so existing + persisted threads load unchanged in meaning. +- `copyWith` gains `stage`. `toJson` writes `stage` only when not `active` and stops + writing `open`. +- Rumor absorption: rumor text maps to `title`, rumor note to `note`. "Resolve true" + is a promotion to `active`; "resolve false" is `done` (or delete). +- Track absorption: `filled`/`max` map to the existing `progress`/`progressMax`. + Nothing remains — `Track` is a strict subset. +- `Rumor` and `Track` classes are deleted. +- Unchanged: `pinned`, progress clock, optional `Tally`, `note`, backlinks, mentions. + +### 2. Persistence + providers (`lib/state/providers.dart`) + +- Threads stay under `juice.threads.v1`. No new key, no re-keying. +- `ThreadNotifier` gains `setStage(String id, ThreadStage stage)`. +- `rumorsProvider`, `tracksProvider`, `RumorNotifier`, `TrackNotifier`, and their + storage keys are deleted. Keys are removed from `sessionScopedKeys` (they stop + being exported). Campaign import stays tolerant: old files that carry rumor/track + keys import fine; those keys are ignored. + +### 3. UI — one pane (`lib/features/tracker_screen.dart`) + +`ThreadsPane` becomes the single tracking pane: + +- Stage filter chips above the list: All / Rumors / Active / Done. +- A rumor-stage card shows a **Confirm** button that promotes the thread to `active`. +- Every card keeps the existing affordances: clock stepper, tally row + (`ThreadTallyRow`), pin, entries backlink chip, edit/delete with undo. +- New-thread creation defaults to `active`; a second "New rumor" button beside + "New" creates at `rumor` stage. No stage choice inside the create dialog. +- The AI flesh-out affordance that lived on rumor cards (`flesh-out-rumor-`) + moves onto rumor-stage thread rows (same `buildFleshOutSeed` + + `showFleshOutReview` flow, appending to `note`). +- `RumorsPane` (`lib/features/rumors_pane.dart`) and `TracksPane` + (`lib/features/tracks_pane.dart`) are deleted. +- In `lib/features/tracking_tab.dart`: the `rumors` and `tracks` subtabs are removed; + the `threads` subtab's aliases grow to `['tasks', 'rumors', 'tracks']` so legacy + routes land on the unified pane. + +### 4. Touch points + +All readers re-point to `threadsProvider`: + +- **Run screen** `_ThreadsRumorsPanel` (`lib/features/run_screen.dart`): renders + active threads plus a rumor-stage section from the one provider; row taps navigate + to the `threads` subtab. +- **Suggestions** (`lib/engine/suggestions.dart`): `develop-rumor` navigates to the + `threads` subtab; `hasTally` logic is unchanged. +- **Campaign search** (`lib/engine/campaign_search.dart`): `SearchResultKind.rumor` + and `.track` are removed along with the `rumors`/`tracks` list parameters; + thread results carry the stage. `campaign_search_sheet.dart` follows. +- **Provider consumers** (verified by grep): only `rumors_pane.dart`, + `run_screen.dart`, and `campaign_search_sheet.dart` consume `rumorsProvider` — + all covered above. No other surface writes rumors. +- **Track-verb help card** (`track_home_pane.dart` `_helpCard`): the + Rumors/Tracks/Tasks lines collapse into the Threads line. +- **Unchanged by design** (same provider, same semantics): the encounter + end-of-fight thread clock stepper, HUD pinned-thread chips, Loop pane tally step, + thread mentions and journal backlinks. +- **Counts/overviews**: `track_home_pane.dart` and `session_resume_screen.dart` + update their rumor/track references to stage-filtered thread queries. + +### 5. Testing + success criteria + +Tests: + +- Unit: `ThreadStage` JSON round-trip; legacy `open:false` fallback to `done`; + default-omission byte-compatibility for an `active` thread. +- Widget: unified `ThreadsPane` — stage filtering, rumor Confirm promotion, tally + roll still works; campaign search returns staged threads and no rumor/track kinds; + Run panel renders both sections from one provider. +- Existing thread tests stay green. + +Success criteria: + +- `flutter analyze` clean; full test suite green. +- `RumorsPane`, `TracksPane`, `Rumor`, `Track`, `rumorsProvider`, `tracksProvider` + no longer exist in `lib/`. +- Legacy `rumors`/`tracks` subtab routes resolve to the unified Threads pane. +- One pane answers "what am I tracking?" with rumors, goals, and clocks in one list. + +## Epic context — tool-consolidation roadmap (model-first order) + +User-selected clusters, one sub-project each, in order: + +1. **Tracking merge** — this spec. +2. **Combat merge** — Encounter screen + Run initiative panel become one encounter + surface. +3. **Rolling merge** — one shared roll surface (dice + default oracle + likelihood + + interpret) used by HUD, Run, Loop, composer. +4. **Inspiration browse merge** — one catalog browser widget behind both the + composer inspire sheet and Ask → Tables. +5. **Tables unify** — residual editor/roll-path unification after PR #332. +6. **Party tool merge** — one integrated companion tool from emulator (Triple-O) + + behavior (Pettish) + sidekick; the radio picker retires. +7. **Map generation merge** — one hex-travel tool (generic hexcrawl engine with + Verdant flavor inside) and one dungeon generator; licensing + (CC-BY-NC-SA Roll 4 Ruin, Verdant attribution) rides along. + +Oracles are explicitly excluded from consolidation per the user. + +Each subsequent sub-project gets its own brainstorm, spec, and plan. From 62f31f71eb4fa7c9ef8505ec1219cd5294d87b62 Mon Sep 17 00:00:00 2001 From: John Taylor Date: Sat, 22 Aug 2026 07:46:17 -0400 Subject: [PATCH 02/15] docs: tracking-merge implementation plan (9 TDD tasks) Co-Authored-By: Claude Fable 5 --- .../plans/2026-08-22-tracking-merge.md | 863 ++++++++++++++++++ 1 file changed, 863 insertions(+) create mode 100644 docs/superpowers/plans/2026-08-22-tracking-merge.md diff --git a/docs/superpowers/plans/2026-08-22-tracking-merge.md b/docs/superpowers/plans/2026-08-22-tracking-merge.md new file mode 100644 index 0000000..923a1d6 --- /dev/null +++ b/docs/superpowers/plans/2026-08-22-tracking-merge.md @@ -0,0 +1,863 @@ +# Tracking Merge Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Merge Threads, Tracks, and Rumors into one `Thread` entity with a `ThreadStage`, rendered by one unified pane; the Rumors and Tracks panes, models, and providers are deleted. + +**Architecture:** `Thread` gains a `stage` enum (`rumor`/`active`/`done`) that replaces its `open` bool as source of truth; a derived `bool get open` keeps the ~15 existing readers compiling unchanged. `Rumor` and `Track` are absorbed (rumor text→title, track filled/max→progress/progressMax) and deleted along with their providers, panes, and storage keys. All consumers (Run panel, search, suggestions, lonelog import/export, home/help cards) re-point to `threadsProvider`. + +**Tech Stack:** Flutter + flutter_riverpod + shared_preferences. Tests: `flutter test` (widget + unit), `flutter analyze`. + +**Spec:** `docs/superpowers/specs/2026-08-22-tracking-merge-design.md` + +## Global Constraints + +- Prefs keys are `loreseer.*` (the spec's `juice.*` names are the legacy spelling; the code uses `loreseer.threads.v1`, `loreseer.rumors.v1`, `loreseer.tracks.v1`). +- Threads stay under `loreseer.threads.v1`. No new storage key. +- Fresh start: `loreseer.rumors.v1` / `loreseer.tracks.v1` data is NOT migrated. The keys leave `sessionScopedKeys`. +- Existing persisted threads must keep loading: legacy JSON `open:false` reads as stage `done`, otherwise `active`. +- An `active`-stage thread's `toJson` must omit the `stage` key (repo convention: JSON omits defaults). +- Colors come from `JuiceTokens` via `context.lore` — never add `ColorScheme` uses (design ratchet). +- Format only the files you edit (`dart format `), never the whole repo. +- Tests never construct `GemmaInterpreterService`; widget tests pumping providers need `SharedPreferences.setMockInitialValues`. +- Each task ends with `flutter analyze` clean on touched files and its tests green, then a commit. + +--- + +### Task 1: `ThreadStage` on the model + +**Files:** +- Modify: `lib/engine/models/journal.dart:190-262` (class `Thread`) +- Test: `test/thread_stage_test.dart` (create) + +**Interfaces:** +- Produces: `enum ThreadStage { rumor, active, done }`; `Thread.stage` (`ThreadStage`, default `active`); derived `bool get open => stage != ThreadStage.done;`; `Thread.copyWith({... ThreadStage? stage ...})`. The `open` constructor parameter and stored field are gone. +- Consumers keep using `t.open` (read-only) everywhere; only `lib/engine/lonelog_import.dart:159-163` and `lib/state/providers.dart:400-405` (`toggleOpen`) construct with `open:` — they are fixed in Tasks 2 and 8. To keep the repo compiling after this task, Task 1 also updates those two call sites (see Step 3). + +- [ ] **Step 1: Write the failing test** + +Create `test/thread_stage_test.dart`: + +```dart +import 'package:flutter_test/flutter_test.dart'; +import 'package:juice_oracle/engine/models.dart'; + +void main() { + test('stage round-trips through JSON and omits the default', () { + final rumor = Thread(id: 't1', title: 'Heard a noise', stage: ThreadStage.rumor); + final json = rumor.toJson(); + expect(json['stage'], 'rumor'); + expect(Thread.fromJson(json).stage, ThreadStage.rumor); + + final active = Thread(id: 't2', title: 'Find the sword'); + expect(active.toJson().containsKey('stage'), isFalse); + expect(active.toJson().containsKey('open'), isFalse); + expect(Thread.fromJson(active.toJson()).stage, ThreadStage.active); + }); + + test('legacy open:false reads as done, open:true as active', () { + expect( + Thread.fromJson({'id': 'a', 'title': 'x', 'open': false}).stage, + ThreadStage.done); + expect( + Thread.fromJson({'id': 'b', 'title': 'y', 'open': true}).stage, + ThreadStage.active); + }); + + test('open getter derives from stage', () { + expect(Thread(id: 'a', title: 'x', stage: ThreadStage.rumor).open, isTrue); + expect(Thread(id: 'b', title: 'y').open, isTrue); + expect(Thread(id: 'c', title: 'z', stage: ThreadStage.done).open, isFalse); + }); + + test('copyWith changes stage and keeps everything else', () { + final t = Thread(id: 'a', title: 'x', note: 'n', pinned: true, progress: 3); + final done = t.copyWith(stage: ThreadStage.done); + expect(done.stage, ThreadStage.done); + expect(done.note, 'n'); + expect(done.pinned, isTrue); + expect(done.progress, 3); + }); +} +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `flutter test test/thread_stage_test.dart` +Expected: compile FAIL — `ThreadStage` undefined, no `stage` parameter. + +- [ ] **Step 3: Implement the model change** + +In `lib/engine/models/journal.dart`, immediately above `class Thread`: + +```dart +/// Lifecycle stage of a tracked thread. A rumor is an unconfirmed lead +/// (the old Rumor entity); active is a live storyline or clock (the old +/// Thread/Track); done is finished either way. +enum ThreadStage { rumor, active, done } + +ThreadStage _threadStageFromJson(Map j) { + switch (j['stage']) { + case 'rumor': + return ThreadStage.rumor; + case 'done': + return ThreadStage.done; + case 'active': + return ThreadStage.active; + } + // Legacy shape: an explicit open:false was a closed thread. + return (j['open'] as bool?) == false ? ThreadStage.done : ThreadStage.active; +} +``` + +Change `Thread` itself: + +- Constructor: remove `this.open = true`, add `this.stage = ThreadStage.active`. +- Fields: remove `final bool open;`, add `final ThreadStage stage;` and the derived getter: + +```dart + final ThreadStage stage; + + /// Derived: true while the thread is not finished (rumor or active). + bool get open => stage != ThreadStage.done; +``` + +- `copyWith`: remove `bool? open`, add `ThreadStage? stage`; body maps `stage: stage ?? this.stage` (drop the `open` line). +- `toJson`: remove `'open': open,`; add `if (stage != ThreadStage.active) 'stage': stage.name,`. +- `fromJson`: remove the `open:` line; add `stage: _threadStageFromJson(j),`. + +Fix the two `open:`-constructing call sites so the repo compiles: + +`lib/state/providers.dart:400-405` — replace `toggleOpen` body: + +```dart + Future toggleOpen(String id) async { + await _persist([ + for (final t in await _ready) + if (t.id == id) + t.copyWith( + stage: t.stage == ThreadStage.done + ? ThreadStage.active + : ThreadStage.done) + else + t, + ]); + } +``` + +`lib/engine/lonelog_import.dart:159-163` — replace the `open:` argument: + +```dart + threads.add(Thread( + id: 'll-thread-${threads.length}', + title: th.group(1)!.trim(), + stage: th.group(2) == 'Open' ? ThreadStage.active : ThreadStage.done, + )); +``` + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `flutter test test/thread_stage_test.dart && flutter analyze lib/engine/models/journal.dart lib/state/providers.dart lib/engine/lonelog_import.dart` +Expected: PASS, no analyzer issues. + +Also run the neighbors that exercise threads: `flutter test test/thread_tally_test.dart test/thread_backlink_test.dart` +Expected: PASS (the derived `open` getter keeps them green). + +- [ ] **Step 5: Commit** + +```bash +git add lib/engine/models/journal.dart lib/state/providers.dart lib/engine/lonelog_import.dart test/thread_stage_test.dart +git commit -m "feat(track): ThreadStage on Thread; open becomes a derived getter" +``` + +--- + +### Task 2: Notifier stage operations + +**Files:** +- Modify: `lib/state/providers.dart:372-449` (class `ThreadNotifier`) +- Test: `test/thread_stage_notifier_test.dart` (create) + +**Interfaces:** +- Consumes: `ThreadStage`, `Thread.copyWith(stage:)` from Task 1. +- Produces: `ThreadNotifier.add(String title, {ThreadStage stage = ThreadStage.active})`; `ThreadNotifier.addReturningId(String title, {ThreadStage stage = ThreadStage.active})`; `ThreadNotifier.setStage(String id, ThreadStage stage)`. Existing methods (`replace`, `toggleOpen`, `togglePinned`, `setProgress`, tally methods, `remove`, `restoreAt`) unchanged. + +- [ ] **Step 1: Write the failing test** + +Create `test/thread_stage_notifier_test.dart`: + +```dart +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:juice_oracle/engine/models.dart'; +import 'package:juice_oracle/state/providers.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('add with stage, setStage promotes a rumor', () async { + SharedPreferences.setMockInitialValues({}); + final container = ProviderContainer(); + addTearDown(container.dispose); + final notifier = container.read(threadsProvider.notifier); + + final id = await notifier.addReturningId('Strange lights', + stage: ThreadStage.rumor); + var threads = await container.read(threadsProvider.future); + expect(threads.single.stage, ThreadStage.rumor); + + await notifier.setStage(id, ThreadStage.active); + threads = await container.read(threadsProvider.future); + expect(threads.single.stage, ThreadStage.active); + }); + + test('toggleOpen flips active<->done and closes a rumor', () async { + SharedPreferences.setMockInitialValues({}); + final container = ProviderContainer(); + addTearDown(container.dispose); + final notifier = container.read(threadsProvider.notifier); + + final id = + await notifier.addReturningId('Lead', stage: ThreadStage.rumor); + await notifier.toggleOpen(id); + var threads = await container.read(threadsProvider.future); + expect(threads.single.stage, ThreadStage.done); + + await notifier.toggleOpen(id); + threads = await container.read(threadsProvider.future); + expect(threads.single.stage, ThreadStage.active); + }); +} +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `flutter test test/thread_stage_notifier_test.dart` +Expected: compile FAIL — `add`/`addReturningId` take no `stage`, `setStage` undefined. + +- [ ] **Step 3: Implement** + +In `ThreadNotifier` (`lib/state/providers.dart:380-391`), change the two adders and append `setStage`: + +```dart + Future add(String title, + {ThreadStage stage = ThreadStage.active}) async { + await _persist([ + Thread(id: _newId(), title: title, stage: stage), + ...await _ready, + ]); + } + + Future addReturningId(String title, + {ThreadStage stage = ThreadStage.active}) async { + final id = _newId(); + await _persist( + [Thread(id: id, title: title, stage: stage), ...await _ready]); + return id; + } + + /// Moves thread [id] to [stage] (rumor confirmation, completion, reopen). + Future setStage(String id, ThreadStage stage) async { + final thread = (await _ready).where((t) => t.id == id).firstOrNull; + if (thread == null) return; + await replace(thread.copyWith(stage: stage)); + } +``` + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `flutter test test/thread_stage_notifier_test.dart test/thread_tally_test.dart && flutter analyze lib/state/providers.dart` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add lib/state/providers.dart test/thread_stage_notifier_test.dart +git commit -m "feat(track): ThreadNotifier stage ops (add stage, setStage)" +``` + +--- + +### Task 3: Unified ThreadsPane + +**Files:** +- Modify: `lib/features/tracker_screen.dart:75-395` (class `ThreadsPane`) +- Test: `test/threads_pane_stage_test.dart` (create) + +**Interfaces:** +- Consumes: `ThreadStage`, `setStage`, `add(stage:)` from Tasks 1–2; existing `ThreadTallyRow`, `_EditDialog`, `buildFleshOutSeed`, `showUndoSnackbar`. +- Produces: widget keys other tasks/tests rely on — filter chips `thread-stage-all` / `thread-stage-rumor` / `thread-stage-active` / `thread-stage-done`; per-row confirm `thread-confirm-`; header button `rumor-new`. Existing keys (`task-new`, `thread-prog-dec/inc-`, `thread-entries-`, `flesh-out-thread-`, `pin-thread-`) unchanged. + +- [ ] **Step 1: Write the failing widget test** + +Create `test/threads_pane_stage_test.dart`. Follow the harness style of `test/thread_tally_test.dart` (mock prefs seeded with a threads list, `ProviderScope` + `MaterialApp(home: ThreadsPane())`); seed `loreseer.sessions.v1` the same way that file does (copy its setup block verbatim). + +```dart +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:juice_oracle/engine/models.dart'; +import 'package:juice_oracle/features/tracker_screen.dart'; +import 'package:juice_oracle/state/providers.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + Future pump(WidgetTester tester) async { + await tester.pumpWidget(const ProviderScope( + child: MaterialApp(home: Scaffold(body: ThreadsPane())))); + await tester.pumpAndSettle(); + } + + void seed(List threads) { + SharedPreferences.setMockInitialValues({ + 'loreseer.threads.v1.default': + jsonEncode(threads.map((t) => t.toJson()).toList()), + 'loreseer.sessions.v1': jsonEncode({ + 'active': 'default', + 'sessions': [ + {'id': 'default', 'name': 'Campaign 1'} + ], + }), + }); + } + + testWidgets('stage filter chips narrow the list', (tester) async { + seed([ + Thread(id: 'r1', title: 'Whispered lead', stage: ThreadStage.rumor), + Thread(id: 'a1', title: 'Main quest'), + Thread(id: 'd1', title: 'Old business', stage: ThreadStage.done), + ]); + await pump(tester); + + expect(find.text('Whispered lead'), findsOneWidget); + expect(find.text('Main quest'), findsOneWidget); + + await tester.tap(find.byKey(const Key('thread-stage-rumor'))); + await tester.pumpAndSettle(); + expect(find.text('Whispered lead'), findsOneWidget); + expect(find.text('Main quest'), findsNothing); + expect(find.text('Old business'), findsNothing); + }); + + testWidgets('confirm promotes a rumor to active', (tester) async { + seed([Thread(id: 'r1', title: 'Whispered lead', stage: ThreadStage.rumor)]); + await pump(tester); + + await tester.tap(find.byKey(const Key('thread-confirm-r1'))); + await tester.pumpAndSettle(); + + final container = ProviderScope.containerOf( + tester.element(find.byType(ThreadsPane))); + final threads = await container.read(threadsProvider.future); + expect(threads.single.stage, ThreadStage.active); + expect(find.byKey(const Key('thread-confirm-r1')), findsNothing); + }); + + testWidgets('New rumor button creates a rumor-stage thread', + (tester) async { + seed([]); + await pump(tester); + + await tester.tap(find.byKey(const Key('rumor-new'))); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField).first, 'Heard in the tavern'); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + + final container = ProviderScope.containerOf( + tester.element(find.byType(ThreadsPane))); + final threads = await container.read(threadsProvider.future); + expect(threads.single.stage, ThreadStage.rumor); + expect(threads.single.title, 'Heard in the tavern'); + }); +} +``` + +Adjust the dialog-save tap (`find.text('Save')`) to the actual `_EditDialog` confirm label after reading it (`lib/features/tracker_screen.dart`, class `_EditDialog`) — use its real button text. + +- [ ] **Step 2: Run test to verify it fails** + +Run: `flutter test test/threads_pane_stage_test.dart` +Expected: FAIL — keys `thread-stage-*`, `thread-confirm-*`, `rumor-new` not found. + +- [ ] **Step 3: Implement pane changes** + +In `ThreadsPane` (`lib/features/tracker_screen.dart`): + +1. Convert to `ConsumerStatefulWidget` holding `ThreadStage? _filter` (null = All). (State is view-only; no persistence.) +2. Header row (currently only `task-new`, lines 96-115): add a `rumor-new` tonal button before `task-new` and a filter `Wrap` of `ChoiceChip`s under the header: + +```dart +FilledButton.tonalIcon( + key: const Key('rumor-new'), + style: FilledButton.styleFrom(minimumSize: const Size(0, 40)), + icon: const Icon(Icons.hearing_outlined), + label: const Text('New rumor'), + onPressed: () => _editThread(context, ref, null, stage: ThreadStage.rumor), +), +``` + +```dart +Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), + child: Wrap( + spacing: 8, + children: [ + for (final (label, stage) in [ + ('All', null), + ('Rumors', ThreadStage.rumor), + ('Active', ThreadStage.active), + ('Done', ThreadStage.done), + ]) + ChoiceChip( + key: Key('thread-stage-${stage?.name ?? 'all'}'), + label: Text(label), + selected: _filter == stage, + onSelected: (_) => setState(() => _filter = stage), + ), + ], + ), +), +``` + +(Selection logic: `_filter == stage` covers the All chip too, because All's `stage` is null.) + +3. List filtering: `final shown = _filter == null ? threads : threads.where((t) => t.stage == _filter).toList();` — build rows from `shown`. Keep the empty-list early-return only for `threads.isEmpty`; when the FILTER empties the list, show a centered `Text('Nothing at this stage.')` under the chips instead of the whole-pane empty state (the chips must stay tappable). +4. Row changes: + - Rumor badge: when `t.stage == ThreadStage.rumor`, prefix the title row with a compact chip-like label `Text('RUMOR', style: TextStyle(fontSize: 10, fontWeight: FontWeight.w800, color: tk.inkMuted))` (simplest: a `Row` of the label + title). + - Confirm button in the trailing icon row, first position, only for rumor-stage: + +```dart +if (t.stage == ThreadStage.rumor) + IconButton( + key: Key('thread-confirm-${t.id}'), + visualDensity: VisualDensity.compact, + icon: const Icon(Icons.check_circle_outline), + tooltip: 'Confirm — promote to active', + onPressed: () => + ref.read(threadsProvider.notifier).setStage(t.id, ThreadStage.active), + ), +``` + + - The leading `Checkbox` keeps working (`value: !t.open`, `toggleOpen`) — no change. +5. `_editThread` gains `{ThreadStage stage = ThreadStage.active}`; the create branch (line 381-389) becomes: + +```dart + if (existing == null) { + final id = await notifier.addReturningId(result.title.trim(), stage: stage); + if (result.note.trim().isNotEmpty) { + final added = (ref.read(threadsProvider).valueOrNull ?? const []) + .where((t) => t.id == id) + .firstOrNull; + if (added != null) { + await notifier.replace(added.copyWith(note: result.note.trim())); + } + } + } +``` + + (This also fixes the latent `.first` bug — the old code grabbed the list head instead of the added id. Dialog heading: `stage == ThreadStage.rumor ? 'New rumor' : 'New Thread'` when creating.) +6. `_fleshOutThread` (line 335-338): seed `entityKind: t.stage == ThreadStage.rumor ? 'rumor' : 'story thread'` — the rumor flesh-out affordance now lives here. +7. FAB unchanged (creates an active thread). + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `flutter test test/threads_pane_stage_test.dart test/thread_tally_test.dart test/thread_backlink_test.dart test/track_consolidation_test.dart && flutter analyze lib/features/tracker_screen.dart` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add lib/features/tracker_screen.dart test/threads_pane_stage_test.dart +git commit -m "feat(track): unified ThreadsPane — stage filter, rumor create/confirm" +``` + +--- + +### Task 4: Retire the Rumors and Tracks panes + +**Files:** +- Modify: `lib/features/tracking_tab.dart` +- Delete: `lib/features/rumors_pane.dart`, `lib/features/tracks_pane.dart` +- Delete: `test/rumors_pane_test.dart`, `test/tracks_pane_test.dart` +- Modify: `test/tracking_tab_test.dart` + +**Interfaces:** +- Consumes: unified `ThreadsPane` from Task 3. +- Produces: Track verb subtab set without `rumors`/`tracks`; `threads` subtab aliases `['tasks', 'rumors', 'tracks']`. + +- [ ] **Step 1: Update the failing tab test first** + +In `test/tracking_tab_test.dart`: remove assertions that a `Rumors`/`Tracks` tab exists; add: + +```dart + testWidgets('legacy rumors/tracks routes land on Threads', (tester) async { + // Use this file's existing pump harness. Navigate via + // shellRouteProvider.goTo(Destination.track, subtab: 'rumors') and expect + // the ThreadsPane to be the visible child; repeat for 'tracks'. + }); +``` + +Model the navigation assertions on how this test file already drives subtabs (it exercises `SubtabDef.aliases` for `tasks`/`people`/`places`); clone that pattern for `rumors` and `tracks`. + +- [ ] **Step 2: Run to verify it fails** + +Run: `flutter test test/tracking_tab_test.dart` +Expected: FAIL (aliases not present yet). + +- [ ] **Step 3: Implement** + +`lib/features/tracking_tab.dart`: + +- Delete imports of `rumors_pane.dart` and `tracks_pane.dart`. +- Delete `const rumors = true;` (line 26). +- Tabs list: remove `if (rumors) const SubtabDef('rumors', 'Rumors'),` and `const SubtabDef('tracks', 'Tracks'),`; change the threads entry to: + +```dart + const SubtabDef('threads', 'Threads', + aliases: ['tasks', 'rumors', 'tracks']), +``` + +- Children list: remove `if (rumors) const RumorsPane(),` and `const TracksPane(),`. + +Delete the four files: + +```bash +git rm lib/features/rumors_pane.dart lib/features/tracks_pane.dart test/rumors_pane_test.dart test/tracks_pane_test.dart +``` + +If anything else still imports the deleted panes, `flutter analyze` names it — those consumers are handled in Tasks 5–7; if one bites now (it should not — grep showed only `tracking_tab.dart` imports them), fix the import in this task. + +- [ ] **Step 4: Run tests** + +Run: `flutter test test/tracking_tab_test.dart && flutter analyze lib/features/tracking_tab.dart` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add -A lib/features/tracking_tab.dart test/tracking_tab_test.dart +git commit -m "feat(track): retire Rumors + Tracks panes; legacy routes alias to Threads" +``` + +--- + +### Task 5: Campaign search drops rumor/track kinds + +**Files:** +- Modify: `lib/engine/campaign_search.dart` +- Modify: `lib/features/campaign_search_sheet.dart` +- Modify: `test/campaign_search_test.dart`, `test/campaign_search_sheet_test.dart` + +**Interfaces:** +- Consumes: `Thread.stage` from Task 1. +- Produces: `SearchResultKind` without `rumor`/`track`; `searchCampaign` without the `rumors:`/`tracks:` parameters. Thread hits carry subtab `threads` (unchanged). + +- [ ] **Step 1: Update the failing engine test** + +In `test/campaign_search_test.dart`: delete cases that pass `rumors:`/`tracks:` lists and assert `SearchResultKind.rumor`/`.track`. Add: + +```dart + test('rumor-stage threads are found as threads', () { + final results = searchCampaign('whisper', threads: [ + Thread(id: 'r1', title: 'Whispered lead', stage: ThreadStage.rumor), + ]); + expect(results.single.kind, SearchResultKind.thread); + expect(results.single.subtab, 'threads'); + }); +``` + +- [ ] **Step 2: Run to verify it fails** + +Run: `flutter test test/campaign_search_test.dart` +Expected: FAIL (old cases removed, engine still exposes the kinds — the new test compiles but the file's removed params force the engine change). + +- [ ] **Step 3: Implement** + +`lib/engine/campaign_search.dart`: + +- `SearchResultKind`: remove `rumor,` and `track,` (line 15-16). +- `searchCampaign`: remove the `rumors`/`tracks` parameters (lines 56-57) and both loops (lines 100-124). Update the doc comment (line 51) to "then threads, characters, places, NPCs". + +`lib/features/campaign_search_sheet.dart`: + +- Remove the `rumorsProvider`/`tracksProvider` watches (lines 56-57) and the `rumors:`/`tracks:` arguments (lines 66-67). +- `_kindLabel` / `_kindIcon` switches: delete the `rumor` and `track` arms (the enum shrank; the analyzer flags leftover arms). +- Update the class doc comment (line 19) and the "five entity lists" comment (line 108). + +- [ ] **Step 4: Run tests** + +Run: `flutter test test/campaign_search_test.dart test/campaign_search_sheet_test.dart && flutter analyze lib/engine/campaign_search.dart lib/features/campaign_search_sheet.dart` +Expected: PASS after pruning the sheet test's rumor/track rows the same way. + +- [ ] **Step 5: Commit** + +```bash +git add lib/engine/campaign_search.dart lib/features/campaign_search_sheet.dart test/campaign_search_test.dart test/campaign_search_sheet_test.dart +git commit -m "feat(track): campaign search — staged threads only, rumor/track kinds retired" +``` + +--- + +### Task 6: Run screen threads panel + +**Files:** +- Modify: `lib/features/run_screen.dart:496-562` (`_ThreadsRumorsPanel`) +- Modify: `test/run_screen_test.dart` + +**Interfaces:** +- Consumes: `Thread.stage` from Task 1. +- Produces: `_ThreadsPanel` (renamed) reading only `threadsProvider`; keys `run-thread-` (active) and `run-rumor-` (rumor-stage) kept; both navigate to subtab `threads`. + +- [ ] **Step 1: Update the failing test** + +In `test/run_screen_test.dart`, find the threads-panel cases. Replace rumor seeding (`loreseer.rumors.v1...`) with rumor-stage threads in `loreseer.threads.v1...`; assert `run-rumor-` rows render under the RUMORS header and tapping one navigates to Track subtab `threads`. + +- [ ] **Step 2: Run to verify it fails** + +Run: `flutter test test/run_screen_test.dart` +Expected: FAIL — panel still reads `rumorsProvider`, rumor rows navigate to `rumors`. + +- [ ] **Step 3: Implement** + +In `_ThreadsRumorsPanel.build` (rename class to `_ThreadsPanel`; update the construction site at line 46): + +```dart + final all = ref.watch(threadsProvider).valueOrNull ?? const []; + final threads = + all.where((t) => t.stage == ThreadStage.active).toList(); + final rumors = all.where((t) => t.stage == ThreadStage.rumor).toList(); +``` + +- Remove the `rumorsProvider` watch. +- The rumor rows keep `key: Key('run-rumor-${r.id}')` but display `r.title` and navigate `subtab: 'threads'`. +- Doc comment (line 496-497): "Read-only glance at the live plot: active threads plus unconfirmed rumors." + +- [ ] **Step 4: Run tests** + +Run: `flutter test test/run_screen_test.dart && flutter analyze lib/features/run_screen.dart` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add lib/features/run_screen.dart test/run_screen_test.dart +git commit -m "feat(run): threads panel reads staged threads only" +``` + +--- + +### Task 7: Home card, help card, suggestions target + +**Files:** +- Modify: `lib/features/track_home_pane.dart` +- Modify: `lib/features/assistant_rail.dart:149-150` +- Modify: `test/track_home_pane_test.dart`, `test/suggestion_chips_test.dart` (only if it asserts the `develop-rumor` target subtab) + +**Interfaces:** +- Consumes: `Thread.stage` from Task 1. +- Produces: no tracks card on Track home; `develop-rumor` chip navigates to subtab `threads`. + +- [ ] **Step 1: Update the failing tests** + +`test/track_home_pane_test.dart`: remove tracks-card assertions (`track-home-tracks`-style keys — read the file for the exact key, it is built by `_tracksCard`); keep threads-card cases. If the help card lines are asserted, update to the new copy below. + +- [ ] **Step 2: Run to verify it fails** + +Run: `flutter test test/track_home_pane_test.dart` +Expected: FAIL. + +- [ ] **Step 3: Implement** + +`lib/features/track_home_pane.dart`: + +- Remove the `tracksProvider` watch (line 29) and `_tracksCard(context, ref, tracks),` (line 40); delete the `_tracksCard` method. +- Help-card `lines` (lines 74-81) become: + +```dart + const lines = <(String, String)>[ + ('Scenes', 'story beats'), + ('Threads', 'rumors, storylines, tasks, clocks'), + ('Encounter', 'combat'), + ('World', 'people and places'), + ]; +``` + +- Update the class doc comment (line 12) to drop "tracks". + +`lib/features/assistant_rail.dart:149-150`: + +```dart + case 'develop-rumor': + route.goTo(Destination.track, subtab: 'threads'); +``` + +(The `rumors` alias would still resolve, but pointing at the real subtab keeps grep honest.) + +- [ ] **Step 4: Run tests** + +Run: `flutter test test/track_home_pane_test.dart test/suggestion_chips_test.dart test/suggestions_test.dart test/suggestions_provider_test.dart && flutter analyze lib/features/track_home_pane.dart lib/features/assistant_rail.dart` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add lib/features/track_home_pane.dart lib/features/assistant_rail.dart test/track_home_pane_test.dart test/suggestion_chips_test.dart +git commit -m "feat(track): home + suggestions point at unified Threads" +``` + +--- + +### Task 8: Lonelog notation maps to staged threads + +**Files:** +- Modify: `lib/engine/lonelog_export.dart` +- Modify: `lib/engine/lonelog_import.dart` +- Modify: `lib/state/providers.dart:2873+` (`exportActiveAsLonelog`), `:2970-2995` (lonelog import writer) +- Modify: `lib/shared/home_shell.dart` (lonelog export/import call sites — grep `campaignToLonelog` / `LonelogDoc`) +- Modify: `test/lonelog_export_test.dart`, `test/lonelog_import_test.dart` + +**Interfaces:** +- Consumes: `ThreadStage` from Task 1. +- Produces: `campaignToLonelog` without the `tracks:` parameter — `[Track:title n/m]` lines are emitted from threads with `progress > 0`; `LonelogDoc` without the `tracks` field — an imported `[Track:name n/m]` becomes a clock thread, merged by title onto an already-parsed `[Thread:]` when titles match. + +The `[Thread:]` / `[Track:]` notation itself is EXTERNAL and unchanged — only the mapping to the model changes. + +- [ ] **Step 1: Update the failing tests** + +`test/lonelog_export_test.dart`: drop the `tracks:` argument; add a thread with `progress: 3, progressMax: 6` and expect BOTH lines for it: + +```dart + expect(out, contains('[Thread:Main quest|Open]')); + expect(out, contains('[Track:Main quest 3/6]')); +``` + +And a plain thread (progress 0) emits only its `[Thread:]` line. + +`test/lonelog_import_test.dart`: remove `doc.tracks` expectations. `[Track:Supplies 2/6]` alone imports as a thread with `progress 2 / progressMax 6`; a doc containing both `[Thread:Main quest|Open]` and `[Track:Main quest 3/6]` imports as ONE thread with the clock set. + +- [ ] **Step 2: Run to verify they fail** + +Run: `flutter test test/lonelog_export_test.dart test/lonelog_import_test.dart` +Expected: FAIL. + +- [ ] **Step 3: Implement** + +`lib/engine/lonelog_export.dart`: + +- Remove `required List tracks,` from `campaignToLonelog`. +- Replace the tracks loop (lines 40-42) with: + +```dart + for (final t in threads.where((t) => t.progress > 0)) { + buf.writeln('[Track:${_tag(t.title)} ${t.progress}/${t.progressMax}]'); + } +``` + +`lib/engine/lonelog_import.dart`: + +- `LonelogDoc`: remove the `tracks` field and constructor param. +- `_parseTag`: drop the `List tracks` parameter. The `[Track:]` branch becomes: + +```dart + final tr = _trackRe.firstMatch(line); + if (tr != null) { + final name = tr.group(1)!.trim(); + final filled = int.parse(tr.group(2)!); + final max = int.parse(tr.group(3)!); + final i = threads.indexWhere((t) => t.title == name); + if (i >= 0) { + threads[i] = + threads[i].copyWith(progress: filled, progressMax: max); + } else { + threads.add(Thread( + id: 'll-track-${threads.length}', + title: name, + progress: filled, + progressMax: max, + )); + } + return; + } +``` + + (`copyWith` order matters: `Thread`'s constructor clamps progress against `progressMax`, and `copyWith` passes both together — setting them in one call is safe.) +- Remove the now-unused `tracks` locals and argument threading in the parse loop. + +`lib/state/providers.dart`: + +- `exportActiveAsLonelog` (line 2873+): delete the `tracksProvider` read (line 2878) and the `tracks:` argument. +- Lonelog import writer (lines 2981-2989): delete the `'loreseer.tracks.v1'` entry. + +`lib/shared/home_shell.dart`: fix any call sites the analyzer flags for the changed signatures. + +- [ ] **Step 4: Run tests** + +Run: `flutter test test/lonelog_export_test.dart test/lonelog_import_test.dart test/lonelog_campaign_ui_test.dart && flutter analyze lib/engine/lonelog_export.dart lib/engine/lonelog_import.dart lib/state/providers.dart lib/shared/home_shell.dart` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add lib/engine/lonelog_export.dart lib/engine/lonelog_import.dart lib/state/providers.dart lib/shared/home_shell.dart test/lonelog_export_test.dart test/lonelog_import_test.dart +git commit -m "feat(lonelog): [Track:] notation maps to clock threads" +``` + +--- + +### Task 9: Delete Rumor/Track models + providers; final sweep + +**Files:** +- Modify: `lib/engine/models/world.dart` (delete class `Rumor`, lines 84-118; delete class `Track`, lines 294+) +- Modify: `lib/state/providers.dart` (delete `RumorNotifier` at 677+, `TrackNotifier` at 863+, `rumorsProvider`, `tracksProvider`; remove `loreseer.rumors.v1` and `loreseer.tracks.v1` from `sessionScopedKeys` at 2650/2653) +- Delete: `test/models_rumor_track_test.dart`, `test/rumors_provider_test.dart`, `test/tracks_provider_test.dart` +- Modify: `CLAUDE.md` (project notes) + +**Interfaces:** +- Consumes: Tasks 4–8 having removed every reader. This task is pure deletion; nothing new is produced. + +- [ ] **Step 1: Delete models and providers** + +- `lib/engine/models/world.dart`: remove class `Rumor` (with its doc comment) and class `Track`. +- `lib/state/providers.dart`: remove `RumorNotifier` + `rumorsProvider`, `TrackNotifier` + `tracksProvider`, and the two keys from `sessionScopedKeys`. (Leaving the keys out of `sessionScopedKeys` means campaign delete/export no longer touches them — fresh-start posture; stale per-session blobs are inert.) + +```bash +git rm test/models_rumor_track_test.dart test/rumors_provider_test.dart test/tracks_provider_test.dart +``` + +- [ ] **Step 2: Prove zero references** + +Run: `grep -rn "Rumor\b\|rumorsProvider\|\bTrack(\|tracksProvider\|RumorsPane\|TracksPane" lib test --include="*.dart" | grep -v "ProgressTrack\|CharTrack\|track_home\|TrackingTab\|Destination.track\|SubtabDef\|subtab\|thread"` +Expected: no hits in `lib/` (eyeball any residue — comments mentioning the old panes are fine to update, code references are not). Then: + +Run: `flutter analyze` +Expected: clean. + +- [ ] **Step 3: Full suite** + +Run: `flutter test` +Expected: green. If a test fails, read the final "Failing tests:" block (never the `+P -F:` progress lines) to attribute it; any failure here is caused by this work until a worktree baseline proves otherwise. + +- [ ] **Step 4: Update CLAUDE.md** + +In `CLAUDE.md` Project notes, add one bullet at the top (normal prose, follow the existing bullet style): + +> **Tracking merge (2026-08-22, consolidation epic sub-project 1)** — Threads, Tracks, and Rumors are ONE entity: `Thread` carries `ThreadStage {rumor, active, done}` (JSON `stage`, omitted at active; legacy `open:false` reads as done; `open` is now a derived getter). `Rumor`/`Track` models, `rumorsProvider`/`tracksProvider`, `RumorsPane`/`TracksPane`, and the `loreseer.rumors.v1`/`loreseer.tracks.v1` keys are DELETED (fresh start, no data migration). Unified `ThreadsPane`: stage filter chips, `rumor-new`, `thread-confirm-` promotion; legacy `rumors`/`tracks` subtab routes alias to `threads`. Lonelog `[Track:name n/m]` now maps to clock threads (export emits it from `progress > 0`, import merges by title). See `docs/superpowers/specs/2026-08-22-tracking-merge-design.md`. + +- [ ] **Step 5: Commit** + +```bash +git add -A +git commit -m "feat(track): delete Rumor/Track models + providers — merge complete" +``` + +--- + +## Post-plan verification (before PR) + +- `flutter analyze` clean, `flutter test` green (Task 9 already proves this). +- Manual smoke on macOS (`flutter run -d macos`): create a rumor, confirm it, step its clock, mark done, filter chips, search finds it, Run panel shows both sections, campaign export/import round-trips. +- Ship via the repo's `/ship-pr` flow as one PR titled `feat(track): unified threads — tracking merge (consolidation epic 1/7)`. From 15ff7ff93af3c11f636c6d2ce571e93b622ec1d2 Mon Sep 17 00:00:00 2001 From: John Taylor Date: Sat, 22 Aug 2026 08:17:17 -0400 Subject: [PATCH 03/15] feat(track): ThreadStage on Thread; open becomes a derived getter --- lib/engine/lonelog_import.dart | 2 +- lib/engine/models/journal.dart | 33 ++++++++++++++++++++++------ lib/state/providers.dart | 8 ++++++- test/thread_stage_test.dart | 39 ++++++++++++++++++++++++++++++++++ 4 files changed, 74 insertions(+), 8 deletions(-) create mode 100644 test/thread_stage_test.dart diff --git a/lib/engine/lonelog_import.dart b/lib/engine/lonelog_import.dart index 6928fb2..b7c0ef5 100644 --- a/lib/engine/lonelog_import.dart +++ b/lib/engine/lonelog_import.dart @@ -159,7 +159,7 @@ void _parseTag(String line, List threads, List characters, threads.add(Thread( id: 'll-thread-${threads.length}', title: th.group(1)!.trim(), - open: th.group(2) == 'Open', + stage: th.group(2) == 'Open' ? ThreadStage.active : ThreadStage.done, )); return; } diff --git a/lib/engine/models/journal.dart b/lib/engine/models/journal.dart index 09b14d0..6d7a757 100644 --- a/lib/engine/models/journal.dart +++ b/lib/engine/models/journal.dart @@ -187,13 +187,31 @@ class JournalEntry { ); } +/// Lifecycle stage of a tracked thread. A rumor is an unconfirmed lead +/// (the old Rumor entity); active is a live storyline or clock (the old +/// Thread/Track); done is finished either way. +enum ThreadStage { rumor, active, done } + +ThreadStage _threadStageFromJson(Map j) { + switch (j['stage']) { + case 'rumor': + return ThreadStage.rumor; + case 'done': + return ThreadStage.done; + case 'active': + return ThreadStage.active; + } + // Legacy shape: an explicit open:false was a closed thread. + return (j['open'] as bool?) == false ? ThreadStage.done : ThreadStage.active; +} + /// Persisted thread (Mythic-style "thread"/vow the player tracks). class Thread { Thread({ required this.id, required this.title, this.note = '', - this.open = true, + this.stage = ThreadStage.active, this.pinned = false, int progress = 0, int progressMax = 10, @@ -203,7 +221,10 @@ class Thread { final String id; final String title; final String note; - final bool open; + final ThreadStage stage; + + /// Derived: true while the thread is not finished (rumor or active). + bool get open => stage != ThreadStage.done; final bool pinned; /// Numeric progress clock (n/[progressMax]); always clamped into 0..max. @@ -219,7 +240,7 @@ class Thread { Thread copyWith({ String? title, String? note, - bool? open, + ThreadStage? stage, bool? pinned, int? progress, int? progressMax, @@ -230,7 +251,7 @@ class Thread { id: id, title: title ?? this.title, note: note ?? this.note, - open: open ?? this.open, + stage: stage ?? this.stage, pinned: pinned ?? this.pinned, progress: progress ?? this.progress, progressMax: progressMax ?? this.progressMax, @@ -241,7 +262,7 @@ class Thread { 'id': id, 'title': title, 'note': note, - 'open': open, + if (stage != ThreadStage.active) 'stage': stage.name, if (pinned) 'pinned': true, if (progress > 0) 'progress': progress, if (progressMax != 10) 'progressMax': progressMax, @@ -252,7 +273,7 @@ class Thread { id: j['id'] as String, title: j['title'] as String, note: (j['note'] as String?) ?? '', - open: (j['open'] as bool?) ?? true, + stage: _threadStageFromJson(j), pinned: (j['pinned'] as bool?) ?? false, progress: (j['progress'] as int?) ?? 0, progressMax: (j['progressMax'] as int?) ?? 10, diff --git a/lib/state/providers.dart b/lib/state/providers.dart index 056a4dd..ca4d571 100644 --- a/lib/state/providers.dart +++ b/lib/state/providers.dart @@ -400,7 +400,13 @@ class ThreadNotifier extends _PersistedList { Future toggleOpen(String id) async { await _persist([ for (final t in await _ready) - if (t.id == id) t.copyWith(open: !t.open) else t, + if (t.id == id) + t.copyWith( + stage: t.stage == ThreadStage.done + ? ThreadStage.active + : ThreadStage.done) + else + t, ]); } diff --git a/test/thread_stage_test.dart b/test/thread_stage_test.dart new file mode 100644 index 0000000..702e1ac --- /dev/null +++ b/test/thread_stage_test.dart @@ -0,0 +1,39 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:loreseer/engine/models.dart'; + +void main() { + test('stage round-trips through JSON and omits the default', () { + final rumor = + Thread(id: 't1', title: 'Heard a noise', stage: ThreadStage.rumor); + final json = rumor.toJson(); + expect(json['stage'], 'rumor'); + expect(Thread.fromJson(json).stage, ThreadStage.rumor); + + final active = Thread(id: 't2', title: 'Find the sword'); + expect(active.toJson().containsKey('stage'), isFalse); + expect(active.toJson().containsKey('open'), isFalse); + expect(Thread.fromJson(active.toJson()).stage, ThreadStage.active); + }); + + test('legacy open:false reads as done, open:true as active', () { + expect(Thread.fromJson({'id': 'a', 'title': 'x', 'open': false}).stage, + ThreadStage.done); + expect(Thread.fromJson({'id': 'b', 'title': 'y', 'open': true}).stage, + ThreadStage.active); + }); + + test('open getter derives from stage', () { + expect(Thread(id: 'a', title: 'x', stage: ThreadStage.rumor).open, isTrue); + expect(Thread(id: 'b', title: 'y').open, isTrue); + expect(Thread(id: 'c', title: 'z', stage: ThreadStage.done).open, isFalse); + }); + + test('copyWith changes stage and keeps everything else', () { + final t = Thread(id: 'a', title: 'x', note: 'n', pinned: true, progress: 3); + final done = t.copyWith(stage: ThreadStage.done); + expect(done.stage, ThreadStage.done); + expect(done.note, 'n'); + expect(done.pinned, isTrue); + expect(done.progress, 3); + }); +} From e3eb1520f07b0adde273a19b29bce9b58bc64f3a Mon Sep 17 00:00:00 2001 From: John Taylor Date: Sat, 22 Aug 2026 08:22:49 -0400 Subject: [PATCH 04/15] feat(track): ThreadNotifier stage ops (add stage, setStage) --- lib/state/providers.dart | 18 +++++++++--- test/thread_stage_notifier_test.dart | 41 ++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 4 deletions(-) create mode 100644 test/thread_stage_notifier_test.dart diff --git a/lib/state/providers.dart b/lib/state/providers.dart index ca4d571..e8dd355 100644 --- a/lib/state/providers.dart +++ b/lib/state/providers.dart @@ -377,16 +377,19 @@ class ThreadNotifier extends _PersistedList { @override Map toJsonMap(Thread item) => item.toJson(); - Future add(String title) async { + Future add(String title, + {ThreadStage stage = ThreadStage.active}) async { await _persist([ - Thread(id: _newId(), title: title), + Thread(id: _newId(), title: title, stage: stage), ...await _ready, ]); } - Future addReturningId(String title) async { + Future addReturningId(String title, + {ThreadStage stage = ThreadStage.active}) async { final id = _newId(); - await _persist([Thread(id: id, title: title), ...await _ready]); + await _persist( + [Thread(id: id, title: title, stage: stage), ...await _ready]); return id; } @@ -417,6 +420,13 @@ class ThreadNotifier extends _PersistedList { ]); } + /// Moves thread [id] to [stage] (rumor confirmation, completion, reopen). + Future setStage(String id, ThreadStage stage) async { + final thread = (await _ready).where((t) => t.id == id).firstOrNull; + if (thread == null) return; + await replace(thread.copyWith(stage: stage)); + } + /// Sets the numeric progress clock for thread [id], clamped to /// `0..thread.progressMax`, persisting the single updated thread. Future setProgress(String id, int value) async { diff --git a/test/thread_stage_notifier_test.dart b/test/thread_stage_notifier_test.dart new file mode 100644 index 0000000..afb034e --- /dev/null +++ b/test/thread_stage_notifier_test.dart @@ -0,0 +1,41 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:loreseer/engine/models.dart'; +import 'package:loreseer/state/providers.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('add with stage, setStage promotes a rumor', () async { + SharedPreferences.setMockInitialValues({}); + final container = ProviderContainer(); + addTearDown(container.dispose); + final notifier = container.read(threadsProvider.notifier); + + final id = await notifier.addReturningId('Strange lights', + stage: ThreadStage.rumor); + var threads = await container.read(threadsProvider.future); + expect(threads.single.stage, ThreadStage.rumor); + + await notifier.setStage(id, ThreadStage.active); + threads = await container.read(threadsProvider.future); + expect(threads.single.stage, ThreadStage.active); + }); + + test('toggleOpen flips active<->done and closes a rumor', () async { + SharedPreferences.setMockInitialValues({}); + final container = ProviderContainer(); + addTearDown(container.dispose); + final notifier = container.read(threadsProvider.notifier); + + final id = await notifier.addReturningId('Lead', stage: ThreadStage.rumor); + await notifier.toggleOpen(id); + var threads = await container.read(threadsProvider.future); + expect(threads.single.stage, ThreadStage.done); + + await notifier.toggleOpen(id); + threads = await container.read(threadsProvider.future); + expect(threads.single.stage, ThreadStage.active); + }); +} From a30855395dbde54ab8b88d51caa1e204357069ed Mon Sep 17 00:00:00 2001 From: John Taylor Date: Sat, 22 Aug 2026 08:28:46 -0400 Subject: [PATCH 05/15] =?UTF-8?q?feat(track):=20unified=20ThreadsPane=20?= =?UTF-8?q?=E2=80=94=20stage=20filter,=20rumor=20create/confirm?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/features/tracker_screen.dart | 403 ++++++++++++++++++------------ test/threads_pane_stage_test.dart | 79 ++++++ 2 files changed, 316 insertions(+), 166 deletions(-) create mode 100644 test/threads_pane_stage_test.dart diff --git a/lib/features/tracker_screen.dart b/lib/features/tracker_screen.dart index 5346dff..e2b34b7 100644 --- a/lib/features/tracker_screen.dart +++ b/lib/features/tracker_screen.dart @@ -72,11 +72,19 @@ Future _showThreadEntries( ); } -class ThreadsPane extends ConsumerWidget { +class ThreadsPane extends ConsumerStatefulWidget { const ThreadsPane({super.key}); @override - Widget build(BuildContext context, WidgetRef ref) { + ConsumerState createState() => _ThreadsPaneState(); +} + +class _ThreadsPaneState extends ConsumerState { + /// Stage filter chip selection; null = All. View-only, not persisted. + ThreadStage? _filter; + + @override + Widget build(BuildContext context) { final theme = Theme.of(context); final journal = ref.watch(journalProvider).valueOrNull ?? const []; @@ -86,10 +94,13 @@ class ThreadsPane extends ConsumerWidget { loading: () => const Center(child: CircularProgressIndicator()), error: (e, _) => Center(child: Text('Error: $e')), data: (threads) { - if (threads.isEmpty) { - return const _Empty( - 'No threads yet. Track quests, vows, mysteries.'); - } + // The header (New rumor / New task) + filter chips must stay + // reachable even with zero threads, so there is no whole-pane + // early return any more — an empty `shown` list renders a + // centered message in the list area instead. + final shown = _filter == null + ? threads + : threads.where((t) => t.stage == _filter).toList(); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ @@ -98,6 +109,19 @@ class ThreadsPane extends ConsumerWidget { child: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ + // Rumor create sits alongside task create: a rumor is an + // unconfirmed lead (stage rumor), a task an active thread + // with a tally. + FilledButton.tonalIcon( + key: const Key('rumor-new'), + style: FilledButton.styleFrom( + minimumSize: const Size(0, 40)), + icon: const Icon(Icons.hearing_outlined), + label: const Text('New rumor'), + onPressed: () => _editThread(context, ref, null, + stage: ThreadStage.rumor), + ), + const SizedBox(width: 8), // Tasks live here now (a task IS a thread with a tally; // the standalone Tasks subtab was folded in). FilledButton.tonalIcon( @@ -113,155 +137,213 @@ class ThreadsPane extends ConsumerWidget { ], ), ), - Expanded( - child: ListView.builder( - padding: const EdgeInsets.all(12), - itemCount: threads.length, - itemBuilder: (context, i) { - final t = threads[i]; - final tk = context.lore; - return Card( - child: ListTile( - isThreeLine: true, - leading: Checkbox( - value: !t.open, - onChanged: (_) => ref - .read(threadsProvider.notifier) - .toggleOpen(t.id), - ), - title: Text( - t.title, - style: t.open - ? null - : TextStyle( - decoration: TextDecoration.lineThrough, - color: theme.colorScheme.onSurfaceVariant), - ), - subtitle: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - if (t.note.isNotEmpty) Text(t.note), - const SizedBox(height: 6), - Row( - children: [ - IconButton( - key: Key('thread-prog-dec-${t.id}'), - visualDensity: VisualDensity.compact, - padding: EdgeInsets.zero, - constraints: const BoxConstraints( - minWidth: 32, minHeight: 32), - icon: const Icon(Icons.remove, size: 18), - tooltip: 'Less progress', - onPressed: () => ref - .read(threadsProvider.notifier) - .setProgress(t.id, t.progress - 1), + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), + child: Wrap( + spacing: 8, + children: [ + for (final (label, stage) in [ + ('All', null), + ('Rumors', ThreadStage.rumor), + ('Active', ThreadStage.active), + ('Done', ThreadStage.done), + ]) + ChoiceChip( + key: Key('thread-stage-${stage?.name ?? 'all'}'), + label: Text(label), + selected: _filter == stage, + onSelected: (_) => setState(() => _filter = stage), + ), + ], + ), + ), + if (shown.isEmpty) + Expanded( + child: Center( + child: Text(threads.isEmpty + ? 'No threads yet. Track quests, vows, mysteries.' + : 'Nothing at this stage.'), + ), + ) + else + Expanded( + child: ListView.builder( + padding: const EdgeInsets.all(12), + itemCount: shown.length, + itemBuilder: (context, i) { + final t = shown[i]; + final tk = context.lore; + return Card( + child: ListTile( + isThreeLine: true, + leading: Checkbox( + value: !t.open, + onChanged: (_) => ref + .read(threadsProvider.notifier) + .toggleOpen(t.id), + ), + title: Row( + children: [ + if (t.stage == ThreadStage.rumor) ...[ + Text('RUMOR', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w800, + color: tk.inkMuted)), + const SizedBox(width: 6), + ], + Expanded( + child: Text( + t.title, + style: t.open + ? null + : TextStyle( + decoration: + TextDecoration.lineThrough, + color: theme + .colorScheme.onSurfaceVariant), ), - Expanded( - child: ClipRRect( - borderRadius: BorderRadius.circular(3), - child: LinearProgressIndicator( - value: t.progressMax <= 0 - ? 0.0 - : (t.progress / t.progressMax) - .clamp(0.0, 1.0), - minHeight: 5, - backgroundColor: tk.hairline, - valueColor: AlwaysStoppedAnimation( - tk.terracotta), + ), + ], + ), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (t.note.isNotEmpty) Text(t.note), + const SizedBox(height: 6), + Row( + children: [ + IconButton( + key: Key('thread-prog-dec-${t.id}'), + visualDensity: VisualDensity.compact, + padding: EdgeInsets.zero, + constraints: const BoxConstraints( + minWidth: 32, minHeight: 32), + icon: const Icon(Icons.remove, size: 18), + tooltip: 'Less progress', + onPressed: () => ref + .read(threadsProvider.notifier) + .setProgress(t.id, t.progress - 1), + ), + Expanded( + child: ClipRRect( + borderRadius: BorderRadius.circular(3), + child: LinearProgressIndicator( + value: t.progressMax <= 0 + ? 0.0 + : (t.progress / t.progressMax) + .clamp(0.0, 1.0), + minHeight: 5, + backgroundColor: tk.hairline, + valueColor: + AlwaysStoppedAnimation( + tk.terracotta), + ), ), ), - ), + IconButton( + key: Key('thread-prog-inc-${t.id}'), + visualDensity: VisualDensity.compact, + padding: EdgeInsets.zero, + constraints: const BoxConstraints( + minWidth: 32, minHeight: 32), + icon: const Icon(Icons.add, size: 18), + tooltip: 'More progress', + onPressed: () => ref + .read(threadsProvider.notifier) + .setProgress(t.id, t.progress + 1), + ), + const SizedBox(width: 4), + Text('${t.progress}/${t.progressMax}', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + color: tk.inkMuted)), + ], + ), + ThreadTallyRow(t), + Builder(builder: (ctx) { + final linked = journal + .where((e) => e.threadId == t.id) + .toList(); + if (linked.isEmpty) { + return const SizedBox.shrink(); + } + return Padding( + padding: const EdgeInsets.only(top: 4), + child: ActionChip( + key: Key('thread-entries-${t.id}'), + avatar: const Icon(Icons.link, size: 14), + label: Text( + '${linked.length} entr${linked.length == 1 ? 'y' : 'ies'}'), + visualDensity: VisualDensity.compact, + onPressed: () => + _showThreadEntries(ctx, t, linked), + ), + ); + }), + ], + ), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (t.stage == ThreadStage.rumor) IconButton( - key: Key('thread-prog-inc-${t.id}'), + key: Key('thread-confirm-${t.id}'), visualDensity: VisualDensity.compact, - padding: EdgeInsets.zero, - constraints: const BoxConstraints( - minWidth: 32, minHeight: 32), - icon: const Icon(Icons.add, size: 18), - tooltip: 'More progress', + icon: const Icon(Icons.check_circle_outline), + tooltip: 'Confirm — promote to active', onPressed: () => ref .read(threadsProvider.notifier) - .setProgress(t.id, t.progress + 1), + .setStage(t.id, ThreadStage.active), ), - const SizedBox(width: 4), - Text('${t.progress}/${t.progressMax}', - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.w700, - color: tk.inkMuted)), - ], - ), - ThreadTallyRow(t), - Builder(builder: (ctx) { - final linked = journal - .where((e) => e.threadId == t.id) - .toList(); - if (linked.isEmpty) { - return const SizedBox.shrink(); - } - return Padding( - padding: const EdgeInsets.only(top: 4), - child: ActionChip( - key: Key('thread-entries-${t.id}'), - avatar: const Icon(Icons.link, size: 14), - label: Text( - '${linked.length} entr${linked.length == 1 ? 'y' : 'ies'}'), + if (ref.watch(aiReadyProvider)) + IconButton( + key: Key('flesh-out-thread-${t.id}'), visualDensity: VisualDensity.compact, + icon: const AiBadge(), + tooltip: 'Flesh out (AI)', onPressed: () => - _showThreadEntries(ctx, t, linked), + _fleshOutThread(context, ref, t), ), - ); - }), - ], - ), - trailing: Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (ref.watch(aiReadyProvider)) IconButton( - key: Key('flesh-out-thread-${t.id}'), + key: Key('pin-thread-${t.id}'), visualDensity: VisualDensity.compact, - icon: const AiBadge(), - tooltip: 'Flesh out (AI)', - onPressed: () => - _fleshOutThread(context, ref, t), + icon: Icon(t.pinned + ? Icons.push_pin + : Icons.push_pin_outlined), + tooltip: t.pinned ? 'Unpin' : 'Pin', + onPressed: () => ref + .read(threadsProvider.notifier) + .togglePinned(t.id), ), - IconButton( - key: Key('pin-thread-${t.id}'), - visualDensity: VisualDensity.compact, - icon: Icon(t.pinned - ? Icons.push_pin - : Icons.push_pin_outlined), - tooltip: t.pinned ? 'Unpin' : 'Pin', - onPressed: () => ref - .read(threadsProvider.notifier) - .togglePinned(t.id), - ), - IconButton( - icon: const Icon(Icons.delete_outline), - onPressed: () { - final list = - ref.read(threadsProvider).valueOrNull ?? - const []; - final idx = - list.indexWhere((x) => x.id == t.id); - ref.read(threadsProvider.notifier).remove(t.id); - showUndoSnackbar( - context, - 'Thread deleted', - () => ref - .read(threadsProvider.notifier) - .restoreAt(idx < 0 ? 0 : idx, t)); - }, - ), - ], + IconButton( + icon: const Icon(Icons.delete_outline), + onPressed: () { + final list = + ref.read(threadsProvider).valueOrNull ?? + const []; + final idx = + list.indexWhere((x) => x.id == t.id); + ref + .read(threadsProvider.notifier) + .remove(t.id); + showUndoSnackbar( + context, + 'Thread deleted', + () => ref + .read(threadsProvider.notifier) + .restoreAt(idx < 0 ? 0 : idx, t)); + }, + ), + ], + ), + onTap: () => _editThread(context, ref, t), ), - onTap: () => _editThread(context, ref, t), - ), - ); - }, + ); + }, + ), ), - ), ], ); }, @@ -335,7 +417,9 @@ class ThreadsPane extends ConsumerWidget { Future _fleshOutThread( BuildContext context, WidgetRef ref, Thread t) async { final seed = buildFleshOutSeed(ref, - entityKind: 'story thread', name: t.title, existingDetail: t.note); + entityKind: t.stage == ThreadStage.rumor ? 'rumor' : 'story thread', + name: t.title, + existingDetail: t.note); final String detail; try { detail = await ref.read(interpreterServiceProvider).fleshOut(seed); @@ -365,11 +449,16 @@ class ThreadsPane extends ConsumerWidget { } Future _editThread( - BuildContext context, WidgetRef ref, Thread? existing) async { + BuildContext context, WidgetRef ref, Thread? existing, + {ThreadStage stage = ThreadStage.active}) async { final result = await showDialog<({String title, String note})>( context: context, builder: (_) => _EditDialog( - heading: existing == null ? 'New Thread' : 'Edit Thread', + heading: existing != null + ? 'Edit Thread' + : stage == ThreadStage.rumor + ? 'New rumor' + : 'New Thread', labelA: 'Title', labelB: 'Note (optional)', initialA: existing?.title ?? '', @@ -379,10 +468,13 @@ class ThreadsPane extends ConsumerWidget { if (result == null || result.title.trim().isEmpty) return; final notifier = ref.read(threadsProvider.notifier); if (existing == null) { - await notifier.add(result.title.trim()); - // apply note if provided + final id = + await notifier.addReturningId(result.title.trim(), stage: stage); if (result.note.trim().isNotEmpty) { - final added = ref.read(threadsProvider).valueOrNull?.first; + final added = + (ref.read(threadsProvider).valueOrNull ?? const []) + .where((t) => t.id == id) + .firstOrNull; if (added != null) { await notifier.replace(added.copyWith(note: result.note.trim())); } @@ -2211,27 +2303,6 @@ class _EditDialogState extends State<_EditDialog> { } } -class _Empty extends StatelessWidget { - const _Empty(this.message); - final String message; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - return Center( - child: Padding( - padding: const EdgeInsets.all(32), - child: Text( - message, - textAlign: TextAlign.center, - style: theme.textTheme.bodyLarge - ?.copyWith(color: theme.colorScheme.onSurfaceVariant), - ), - ), - ); - } -} - // -- Thread tally row ----------------------------------------------------- class ThreadTallyRow extends ConsumerWidget { const ThreadTallyRow(this.thread, {super.key}); diff --git a/test/threads_pane_stage_test.dart b/test/threads_pane_stage_test.dart new file mode 100644 index 0000000..0eebb0c --- /dev/null +++ b/test/threads_pane_stage_test.dart @@ -0,0 +1,79 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:loreseer/engine/models.dart'; +import 'package:loreseer/features/tracker_screen.dart'; +import 'package:loreseer/state/providers.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + Future pump(WidgetTester tester) async { + await tester.pumpWidget(const ProviderScope( + child: MaterialApp(home: Scaffold(body: ThreadsPane())))); + await tester.pumpAndSettle(); + } + + void seed(List threads) { + SharedPreferences.setMockInitialValues({ + 'loreseer.threads.v1.default': + jsonEncode(threads.map((t) => t.toJson()).toList()), + 'loreseer.sessions.v1': jsonEncode({ + 'active': 'default', + 'sessions': [ + {'id': 'default', 'name': 'Campaign 1'} + ], + }), + }); + } + + testWidgets('stage filter chips narrow the list', (tester) async { + seed([ + Thread(id: 'r1', title: 'Whispered lead', stage: ThreadStage.rumor), + Thread(id: 'a1', title: 'Main quest'), + Thread(id: 'd1', title: 'Old business', stage: ThreadStage.done), + ]); + await pump(tester); + + expect(find.text('Whispered lead'), findsOneWidget); + expect(find.text('Main quest'), findsOneWidget); + + await tester.tap(find.byKey(const Key('thread-stage-rumor'))); + await tester.pumpAndSettle(); + expect(find.text('Whispered lead'), findsOneWidget); + expect(find.text('Main quest'), findsNothing); + expect(find.text('Old business'), findsNothing); + }); + + testWidgets('confirm promotes a rumor to active', (tester) async { + seed([Thread(id: 'r1', title: 'Whispered lead', stage: ThreadStage.rumor)]); + await pump(tester); + + await tester.tap(find.byKey(const Key('thread-confirm-r1'))); + await tester.pumpAndSettle(); + + final container = + ProviderScope.containerOf(tester.element(find.byType(ThreadsPane))); + final threads = await container.read(threadsProvider.future); + expect(threads.single.stage, ThreadStage.active); + expect(find.byKey(const Key('thread-confirm-r1')), findsNothing); + }); + + testWidgets('New rumor button creates a rumor-stage thread', (tester) async { + seed([]); + await pump(tester); + + await tester.tap(find.byKey(const Key('rumor-new'))); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField).first, 'Heard in the tavern'); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + + final container = + ProviderScope.containerOf(tester.element(find.byType(ThreadsPane))); + final threads = await container.read(threadsProvider.future); + expect(threads.single.stage, ThreadStage.rumor); + expect(threads.single.title, 'Heard in the tavern'); + }); +} From 2a043f7d6dd00e197a42282709480afa09d6aea6 Mon Sep 17 00:00:00 2001 From: John Taylor Date: Sat, 22 Aug 2026 08:37:33 -0400 Subject: [PATCH 06/15] feat(track): retire Rumors + Tracks panes; legacy routes alias to Threads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RumorsPane/TracksPane deleted; the threads subtab now aliases tasks/rumors/tracks. Also fixed two test files (delete_undo_test.dart, world_flesh_out_test.dart) that imported the deleted panes directly — not caught by the brief's lib-only grep. The Track-delete-undo widget case had no surviving UI to test and was dropped; the Rumor flesh-out case was migrated onto ThreadsPane's rumor-stage thread flesh-out button (already shipped in Task 3). --- lib/features/rumors_pane.dart | 149 --------------------------- lib/features/tracking_tab.dart | 13 +-- lib/features/tracks_pane.dart | 182 --------------------------------- test/delete_undo_test.dart | 30 ------ test/rumors_pane_test.dart | 41 -------- test/tracking_tab_test.dart | 45 ++++++-- test/tracks_pane_test.dart | 52 ---------- test/world_flesh_out_test.dart | 40 +++++--- 8 files changed, 68 insertions(+), 484 deletions(-) delete mode 100644 lib/features/rumors_pane.dart delete mode 100644 lib/features/tracks_pane.dart delete mode 100644 test/rumors_pane_test.dart delete mode 100644 test/tracks_pane_test.dart diff --git a/lib/features/rumors_pane.dart b/lib/features/rumors_pane.dart deleted file mode 100644 index ad8342f..0000000 --- a/lib/features/rumors_pane.dart +++ /dev/null @@ -1,149 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import '../engine/models.dart'; -import '../shared/ai_badge.dart'; -import '../shared/undo_snackbar.dart'; -import '../state/interpreter.dart'; -import '../state/play_context.dart'; -import '../state/providers.dart'; -import 'flesh_out_review.dart'; - -/// Tracking → Rumors: a per-campaign list of leads/rumors to resolve. -class RumorsPane extends ConsumerWidget { - const RumorsPane({super.key}); - - @override - Widget build(BuildContext context, WidgetRef ref) { - final rumors = ref.watch(rumorsProvider).valueOrNull ?? const []; - final theme = Theme.of(context); - return Column( - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), - child: Row( - children: [ - Expanded( - child: Text('Rumors', style: theme.textTheme.titleMedium), - ), - // Flexible bounds the button under the loose host width - // constraints (freeze rule). - Flexible( - child: FilledButton.tonalIcon( - key: const Key('rumors-add'), - icon: const Icon(Icons.add), - label: const Text('New'), - onPressed: () => _add(context, ref), - ), - ), - ], - ), - ), - Expanded( - child: rumors.isEmpty - ? const Center(child: Text('No rumors yet.')) - : ListView( - children: [ - for (final r in rumors) - CheckboxListTile( - key: Key('rumor-${r.id}'), - value: r.resolved, - onChanged: (_) => ref - .read(rumorsProvider.notifier) - .toggleResolved(r.id), - title: Text( - r.text, - style: r.resolved - ? TextStyle( - decoration: TextDecoration.lineThrough, - color: theme.colorScheme.onSurfaceVariant) - : null, - ), - subtitle: r.note.isEmpty ? null : Text(r.note), - secondary: Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (ref.watch(aiReadyProvider)) - IconButton( - key: Key('flesh-out-rumor-${r.id}'), - visualDensity: VisualDensity.compact, - icon: const AiBadge(), - tooltip: 'Flesh out (AI)', - onPressed: () => _fleshOut(context, ref, r), - ), - IconButton( - icon: const Icon(Icons.delete_outline), - tooltip: 'Delete', - onPressed: () { - final list = - ref.read(rumorsProvider).valueOrNull ?? - const []; - final idx = - list.indexWhere((x) => x.id == r.id); - ref.read(rumorsProvider.notifier).remove(r.id); - showUndoSnackbar( - context, - 'Rumor deleted', - () => ref - .read(rumorsProvider.notifier) - .restoreAt(idx < 0 ? 0 : idx, r)); - }, - ), - ], - ), - ), - ], - ), - ), - ], - ); - } - - /// AI flesh-out: generate → Append/Cancel review → append to the rumor's - /// note (same arc as the world trackers' flesh-outs). - Future _fleshOut(BuildContext context, WidgetRef ref, Rumor r) async { - final seed = buildFleshOutSeed(ref, - entityKind: 'rumor', name: r.text, existingDetail: r.note); - final String detail; - try { - detail = await ref.read(interpreterServiceProvider).fleshOut(seed); - } catch (e) { - if (context.mounted) { - ScaffoldMessenger.of(context) - .showSnackBar(SnackBar(content: Text('Flesh out failed: $e'))); - } - return; - } - if (!context.mounted) return; - if (!await showFleshOutReview(context, detail)) return; - final note = - [r.note, detail].where((s) => s.trim().isNotEmpty).join('\n\n'); - await ref.read(rumorsProvider.notifier).replace(r.copyWith(note: note)); - } - - Future _add(BuildContext context, WidgetRef ref) async { - final controller = TextEditingController(); - final text = await showDialog( - context: context, - builder: (context) => AlertDialog( - title: const Text('Add rumor'), - content: TextField( - controller: controller, - autofocus: true, - decoration: const InputDecoration(labelText: 'Rumor'), - onSubmitted: (v) => Navigator.pop(context, v), - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(context), - child: const Text('Cancel')), - FilledButton( - onPressed: () => Navigator.pop(context, controller.text), - child: const Text('Add')), - ], - ), - ); - WidgetsBinding.instance.addPostFrameCallback((_) => controller.dispose()); - if (text == null || text.trim().isEmpty) return; - await ref.read(rumorsProvider.notifier).add(text.trim()); - } -} diff --git a/lib/features/tracking_tab.dart b/lib/features/tracking_tab.dart index de23e73..68cc599 100644 --- a/lib/features/tracking_tab.dart +++ b/lib/features/tracking_tab.dart @@ -8,11 +8,9 @@ import 'battle_pane.dart'; import 'encounter_screen.dart'; import 'party_tools_pane.dart'; import 'resources_pane.dart'; -import 'rumors_pane.dart'; import 'scenes_pane.dart'; import 'track_home_pane.dart'; import 'tracker_screen.dart'; -import 'tracks_pane.dart'; import 'world_pane.dart'; class TrackingTab extends ConsumerWidget { @@ -23,22 +21,21 @@ class TrackingTab extends ConsumerWidget { Widget build(BuildContext context, WidgetRef ref) { final lonelog = systems.contains('lonelog'); final party = systems.contains('party'); - const rumors = true; final partyTools = party; return SubtabHost( destination: Destination.track, scrollable: true, // Consolidated (was 11+ same-weight tabs): a task IS a thread with a // tally, so Tasks routes into Threads; People + Places share the World - // pane. Legacy subtab keys keep working via SubtabDef aliases. + // pane; Rumors + Tracks are threads with a stage, so they route into + // Threads too. Legacy subtab keys keep working via SubtabDef aliases. tabs: [ const SubtabDef('home', 'Home'), const SubtabDef('scenes', 'Scenes'), - const SubtabDef('threads', 'Threads', aliases: ['tasks']), + const SubtabDef('threads', 'Threads', + aliases: ['tasks', 'rumors', 'tracks']), const SubtabDef('world', 'World', aliases: ['people', 'places']), const SubtabDef('encounter', 'Encounter'), - if (rumors) const SubtabDef('rumors', 'Rumors'), - const SubtabDef('tracks', 'Tracks'), // One party paradigm renders per SessionMeta.partyTool (Emulator / // Behavior / Sidekick are mutually exclusive, not stacked). The // aliases only keep legacy routes ('emulator'/'sidekick'/'behavior') @@ -55,8 +52,6 @@ class TrackingTab extends ConsumerWidget { const ThreadsPane(), const WorldPane(), const EncounterScreen(), - if (rumors) const RumorsPane(), - const TracksPane(), if (partyTools) const PartyToolsPane(), if (lonelog) const ResourcesPane(), if (lonelog) const BattlePane(), diff --git a/lib/features/tracks_pane.dart b/lib/features/tracks_pane.dart deleted file mode 100644 index d9b667f..0000000 --- a/lib/features/tracks_pane.dart +++ /dev/null @@ -1,182 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import '../engine/models.dart'; -import '../shared/undo_snackbar.dart'; -import '../state/providers.dart'; - -/// Tracking → Tracks: simple capped progress tracks (clocks) for solo play. -class TracksPane extends ConsumerWidget { - const TracksPane({super.key}); - - @override - Widget build(BuildContext context, WidgetRef ref) { - final tracks = ref.watch(tracksProvider).valueOrNull ?? const []; - final theme = Theme.of(context); - return Column( - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), - child: Row( - children: [ - Expanded( - child: Text('Tracks', style: theme.textTheme.titleMedium), - ), - Flexible( - child: FilledButton.tonalIcon( - key: const Key('tracks-add'), - icon: const Icon(Icons.add), - label: const Text('New'), - onPressed: () => _add(context, ref), - ), - ), - ], - ), - ), - Expanded( - child: tracks.isEmpty - ? const Center(child: Text('No tracks yet.')) - : ListView.builder( - padding: const EdgeInsets.fromLTRB(12, 0, 12, 12), - itemCount: tracks.length, - itemBuilder: (context, i) { - final t = tracks[i]; - return Card( - child: Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 8, 8), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Expanded( - child: Text(t.name, - style: theme.textTheme.titleSmall), - ), - IconButton( - key: Key('track-dec-$i'), - icon: const Icon(Icons.remove), - tooltip: 'Decrease', - onPressed: t.filled > 0 - ? () => ref - .read(tracksProvider.notifier) - .adjust(t.id, -1) - : null, - ), - Text('${t.filled} / ${t.max}', - style: theme.textTheme.bodyMedium), - IconButton( - key: Key('track-inc-$i'), - icon: const Icon(Icons.add), - tooltip: 'Increase', - onPressed: t.filled < t.max - ? () => _increment(context, ref, t) - : null, - ), - PopupMenuButton( - onSelected: (v) { - if (v == 'rename') { - _rename(context, ref, t); - } else if (v == 'delete') { - final list = ref - .read(tracksProvider) - .valueOrNull ?? - const []; - final idx = - list.indexWhere((x) => x.id == t.id); - ref - .read(tracksProvider.notifier) - .remove(t.id); - showUndoSnackbar( - context, - 'Track deleted', - () => ref - .read(tracksProvider.notifier) - .restoreAt(idx < 0 ? 0 : idx, t)); - } - }, - itemBuilder: (_) => const [ - PopupMenuItem( - value: 'rename', child: Text('Rename')), - PopupMenuItem( - value: 'delete', child: Text('Delete')), - ], - ), - ], - ), - const SizedBox(height: 4), - LinearProgressIndicator( - value: t.max == 0 ? 0 : t.filled / t.max, - ), - ], - ), - ), - ); - }, - ), - ), - ], - ); - } - - Future _add(BuildContext context, WidgetRef ref) async { - final name = await _nameDialog(context, title: 'New track'); - if (name == null || name.trim().isEmpty) return; - await ref.read(tracksProvider.notifier).add(name.trim()); - } - - /// Ticks a clock up one; when that completes it (reaches max), logs a journal - /// entry so the fill isn't a silent dead dial (the fill→fire→journal closure). - Future _increment(BuildContext context, WidgetRef ref, Track t) async { - await ref.read(tracksProvider.notifier).adjust(t.id, 1); - // Decide off the fresh post-adjust state, not the pre-tap snapshot. - final updated = (await ref.read(tracksProvider.future)) - .where((tr) => tr.id == t.id) - .firstOrNull; - if (updated != null && updated.max > 0 && updated.filled >= updated.max) { - await ref.read(journalProvider.notifier).add( - 'Clock filled: ${updated.name}', - '${updated.name} reached ${updated.max}/${updated.max}.', - ); - if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('Clock filled: ${updated.name}'))); - } - } - } - - Future _rename(BuildContext context, WidgetRef ref, Track t) async { - final name = - await _nameDialog(context, title: 'Rename track', initial: t.name); - if (name == null || name.trim().isEmpty) return; - await ref.read(tracksProvider.notifier).rename(t.id, name.trim()); - } - - Future _nameDialog(BuildContext context, - {required String title, String initial = ''}) async { - final controller = TextEditingController(text: initial); - try { - return await showDialog( - context: context, - builder: (context) => AlertDialog( - title: Text(title), - content: TextField( - controller: controller, - autofocus: true, - decoration: const InputDecoration(labelText: 'Name'), - onSubmitted: (v) => Navigator.pop(context, v), - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(context), - child: const Text('Cancel')), - FilledButton( - onPressed: () => Navigator.pop(context, controller.text), - child: const Text('Save')), - ], - ), - ); - } finally { - controller.dispose(); - } - } -} diff --git a/test/delete_undo_test.dart b/test/delete_undo_test.dart index 760d5a7..e9ed18e 100644 --- a/test/delete_undo_test.dart +++ b/test/delete_undo_test.dart @@ -1,8 +1,6 @@ -import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:shared_preferences/shared_preferences.dart'; -import 'package:loreseer/features/tracks_pane.dart'; import 'package:loreseer/state/providers.dart'; void _seed(Map scoped) { @@ -57,32 +55,4 @@ void main() { expect(c.read(dismissedSuggestionsProvider).value, isNot(contains('char:Kara'))); }); - - testWidgets('track delete shows an Undo snackbar that restores the track', - (t) async { - _seed({ - 'loreseer.tracks.v1.default': '[{"id":"tk","name":"Doom clock"}]', - }); - final c = ProviderContainer(); - addTearDown(c.dispose); - await c.read(tracksProvider.future); - await t.pumpWidget(UncontrolledProviderScope( - container: c, - child: const MaterialApp(home: Scaffold(body: TracksPane())), - )); - await t.pumpAndSettle(); - - // Delete via the row's popup menu. - await t.tap(find.byType(PopupMenuButton).first); - await t.pumpAndSettle(); - await t.tap(find.text('Delete')); - await t.pumpAndSettle(); - expect(c.read(tracksProvider).value, isEmpty); - expect(find.text('Track deleted'), findsOneWidget); - - // Undo brings it back. - await t.tap(find.text('Undo')); - await t.pumpAndSettle(); - expect(c.read(tracksProvider).value!.single.name, 'Doom clock'); - }); } diff --git a/test/rumors_pane_test.dart b/test/rumors_pane_test.dart deleted file mode 100644 index 0abc31a..0000000 --- a/test/rumors_pane_test.dart +++ /dev/null @@ -1,41 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:shared_preferences/shared_preferences.dart'; -import 'package:loreseer/features/rumors_pane.dart'; -import 'package:loreseer/state/providers.dart'; - -void main() { - setUp(() => SharedPreferences.setMockInitialValues({})); - - testWidgets('adds a rumor through the UI', (t) async { - final c = ProviderContainer(); - addTearDown(c.dispose); - await c.read(rumorsProvider.future); - await t.pumpWidget(UncontrolledProviderScope( - container: c, - child: const MaterialApp(home: Scaffold(body: RumorsPane())), - )); - await t.tap(find.byKey(const Key('rumors-add'))); - await t.pumpAndSettle(); - await t.enterText(find.byType(TextField).last, 'Bridge is watched'); - await t.tap(find.text('Add')); - await t.pumpAndSettle(); - expect(find.text('Bridge is watched'), findsOneWidget); - }); - - testWidgets('toggling a rumor marks it resolved', (t) async { - final c = ProviderContainer(); - addTearDown(c.dispose); - await c.read(rumorsProvider.future); - await c.read(rumorsProvider.notifier).add('North gate'); - await t.pumpWidget(UncontrolledProviderScope( - container: c, - child: const MaterialApp(home: Scaffold(body: RumorsPane())), - )); - await t.pumpAndSettle(); - await t.tap(find.byType(Checkbox).first); - await t.pumpAndSettle(); - expect(c.read(rumorsProvider).value!.single.resolved, isTrue); - }); -} diff --git a/test/tracking_tab_test.dart b/test/tracking_tab_test.dart index 65b9c21..a076d66 100644 --- a/test/tracking_tab_test.dart +++ b/test/tracking_tab_test.dart @@ -5,7 +5,10 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:loreseer/engine/emulator_data.dart'; +import 'package:loreseer/features/tracker_screen.dart'; import 'package:loreseer/features/tracking_tab.dart'; +import 'package:loreseer/shared/destination.dart'; +import 'package:loreseer/shared/shell_route.dart'; import 'package:loreseer/shared/theme.dart'; import 'package:loreseer/state/interpreter.dart'; import 'package:loreseer/state/providers.dart'; @@ -22,8 +25,7 @@ final _emulatorOverride = void main() { setUp(() => SharedPreferences.setMockInitialValues({})); - testWidgets('Track shows the core subtabs including Rumors always', - (t) async { + testWidgets('Track shows the core subtabs', (t) async { SharedPreferences.setMockInitialValues({ 'loreseer.sessions.v1': '{"active":"default","sessions":[{"id":"default","name":"C1"}]}', @@ -41,18 +43,48 @@ void main() { for (final label in [ 'Scenes', 'Threads', - 'Rumors', - 'Tracks', 'Encounter', ]) { expect(find.widgetWithText(Tab, label), findsOneWidget); } + // Rumors/Tracks tabs are retired; Threads absorbs them via aliases. + expect(find.widgetWithText(Tab, 'Rumors'), findsNothing); + expect(find.widgetWithText(Tab, 'Tracks'), findsNothing); // NPCs (CharactersPane) moved to the Sheet verb; party subtabs are gated. expect(find.widgetWithText(Tab, 'NPCs'), findsNothing); expect(find.widgetWithText(Tab, 'Party'), findsNothing); }); - testWidgets('Rumors always shown regardless of mode', (tester) async { + testWidgets('legacy rumors/tracks routes land on Threads', (t) async { + SharedPreferences.setMockInitialValues({ + 'loreseer.sessions.v1': + '{"active":"default","sessions":[{"id":"default","name":"C1"}]}', + }); + final c = ProviderContainer(); + addTearDown(c.dispose); + await c.read(sessionsProvider.future); + await t.pumpWidget(UncontrolledProviderScope( + container: c, + child: MaterialApp( + theme: AppTheme.light(), + home: const Scaffold(body: TrackingTab(systems: {}))), + )); + await t.pumpAndSettle(); + + c + .read(shellRouteProvider.notifier) + .goTo(Destination.track, subtab: 'rumors'); + await t.pumpAndSettle(); + expect(find.byType(ThreadsPane), findsOneWidget); + + c + .read(shellRouteProvider.notifier) + .goTo(Destination.track, subtab: 'tracks'); + await t.pumpAndSettle(); + expect(find.byType(ThreadsPane), findsOneWidget); + }); + + testWidgets('Party tools shown when party system is enabled', (tester) async { SharedPreferences.setMockInitialValues({ 'loreseer.sessions.v1': '{"active":"default","sessions":[{"id":"default","name":"C1",' @@ -67,8 +99,6 @@ void main() { theme: AppTheme.light(), home: const Scaffold(body: TrackingTab(systems: {'party'}))))); await tester.pumpAndSettle(); - // Rumors always present (no mode gate). - expect(find.text('Rumors'), findsOneWidget); // Party tools present when party system is enabled. expect(find.widgetWithText(Tab, 'Party'), findsOneWidget); }); @@ -122,7 +152,6 @@ void main() { home: const Scaffold(body: TrackingTab(systems: {'party'}))))); await tester.pumpAndSettle(); // Party tools present because party system is enabled (mode doesn't gate). - expect(find.text('Rumors'), findsOneWidget); expect(find.widgetWithText(Tab, 'Party'), findsOneWidget); }); } diff --git a/test/tracks_pane_test.dart b/test/tracks_pane_test.dart deleted file mode 100644 index f2a6888..0000000 --- a/test/tracks_pane_test.dart +++ /dev/null @@ -1,52 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:shared_preferences/shared_preferences.dart'; -import 'package:loreseer/features/tracks_pane.dart'; -import 'package:loreseer/state/providers.dart'; - -void main() { - setUp(() => SharedPreferences.setMockInitialValues({})); - - testWidgets('add a track and increment it', (t) async { - final c = ProviderContainer(); - addTearDown(c.dispose); - await c.read(tracksProvider.future); - await c.read(tracksProvider.notifier).add('Escape'); - await t.pumpWidget(UncontrolledProviderScope( - container: c, - child: const MaterialApp(home: Scaffold(body: TracksPane())), - )); - await t.pumpAndSettle(); - expect(find.text('Escape'), findsOneWidget); - await t.tap(find.byKey(const Key('track-inc-0'))); - await t.pumpAndSettle(); - expect(c.read(tracksProvider).value!.single.filled, 1); - }); - - testWidgets('filling a clock to its max logs a journal entry', (t) async { - SharedPreferences.setMockInitialValues({ - 'loreseer.sessions.v1': - '{"active":"default","sessions":[{"id":"default","name":"C1"}]}', - 'loreseer.tracks.v1.default': - '[{"id":"k1","name":"Pursuit","filled":1,"max":2}]', - 'loreseer.journal.v2.default': '[]', - }); - final c = ProviderContainer(); - addTearDown(c.dispose); - await c.read(tracksProvider.future); - await c.read(journalProvider.future); - await t.pumpWidget(UncontrolledProviderScope( - container: c, - child: const MaterialApp(home: Scaffold(body: TracksPane())), - )); - await t.pumpAndSettle(); - // One tick completes the 1/2 clock → fires a journal note. - await t.tap(find.byKey(const Key('track-inc-0'))); - await t.pumpAndSettle(); - expect(c.read(tracksProvider).value!.single.filled, 2); - final entries = await c.read(journalProvider.future); - expect( - entries.where((e) => e.title == 'Clock filled: Pursuit'), hasLength(1)); - }); -} diff --git a/test/world_flesh_out_test.dart b/test/world_flesh_out_test.dart index 5d142c9..d652c42 100644 --- a/test/world_flesh_out_test.dart +++ b/test/world_flesh_out_test.dart @@ -1,13 +1,15 @@ -// Flesh-out coverage on the world trackers: People, Places, and Rumors cards -// carry an aiReady-gated AI button that generates detail, reviews it in the -// shared Append/Cancel dialog, and appends to the entity's note. +// Flesh-out coverage on the world trackers: People and Places cards carry an +// aiReady-gated AI button that generates detail, reviews it in the shared +// Append/Cancel dialog, and appends to the entity's note. Rumors are now +// rumor-stage Threads, fleshed out via ThreadsPane's own flesh-out button +// (see the tracking-merge consolidation — RumorsPane is retired). import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:loreseer/engine/models.dart'; import 'package:loreseer/features/people_pane.dart'; import 'package:loreseer/features/places_pane.dart'; -import 'package:loreseer/features/rumors_pane.dart'; +import 'package:loreseer/features/tracker_screen.dart'; import 'package:loreseer/state/interpreter.dart'; import 'package:loreseer/state/providers.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -99,21 +101,33 @@ void main() { expect(place.note, 'Burned once.\n\nFleshed-out detail.'); }); - testWidgets('Rumors: flesh-out appends detail to the rumor note', (t) async { + testWidgets( + 'Rumors: flesh-out appends detail to a rumor-stage thread\'s note', + (t) async { final fake = _fake(); - final c = await _container(fake); - await c.read(rumorsProvider.notifier).add('The mine is haunted.'); - await _pump(t, c, const RumorsPane()); - - final rumor = c.read(rumorsProvider).value!.single; - await t.tap(find.byKey(Key('flesh-out-rumor-${rumor.id}'))); + SharedPreferences.setMockInitialValues({ + 'loreseer.sessions.v1': + '{"active":"default","sessions":[{"id":"default","name":"C1"}]}', + 'loreseer.ai_enabled.v1': true, + 'loreseer.threads.v1.default': + '[{"id":"r1","title":"The mine is haunted.","stage":"rumor"}]', + }); + final c = ProviderContainer(overrides: [ + interpreterServiceProvider.overrideWithValue(fake), + ]); + addTearDown(c.dispose); + await c.read(sessionsProvider.future); + await _pump(t, c, const ThreadsPane()); + + await t.tap(find.byKey(const Key('flesh-out-thread-r1'))); await t.pumpAndSettle(); - await t.tap(find.byKey(const Key('flesh-out-append'))); + await t.tap(find.text('Save')); await t.pumpAndSettle(); expect(fake.lastFleshOutSeed?.entityKind, 'rumor'); expect(fake.lastFleshOutSeed?.name, 'The mine is haunted.'); - expect(c.read(rumorsProvider).value!.single.note, 'Fleshed-out detail.'); + final thread = c.read(threadsProvider).value!.single; + expect(thread.note, 'Fleshed-out detail.'); }); testWidgets('AI off hides every world-tracker flesh-out button', (t) async { From 81befc030e36e3aac3897c52e873ad66055af467 Mon Sep 17 00:00:00 2001 From: John Taylor Date: Sat, 22 Aug 2026 08:38:58 -0400 Subject: [PATCH 07/15] test: migrate session-resume thread seeding to ThreadStage --- test/session_resume_screen_test.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/session_resume_screen_test.dart b/test/session_resume_screen_test.dart index 566c03b..9453114 100644 --- a/test/session_resume_screen_test.dart +++ b/test/session_resume_screen_test.dart @@ -70,7 +70,7 @@ void main() { final scene = entry('s1', 'The Vault', '', kind: JournalKind.scene); final threads = [ Thread(id: 't1', title: 'Find the Relic'), - Thread(id: 't2', title: 'Escape the keep', open: false), + Thread(id: 't2', title: 'Escape the keep', stage: ThreadStage.done), ]; // Storage is newest-first; recap should read most-recent few. final entries = [ From a881244ea192af17a50f4fd1d39dc8e9b95e7acc Mon Sep 17 00:00:00 2001 From: John Taylor Date: Sat, 22 Aug 2026 08:46:28 -0400 Subject: [PATCH 08/15] =?UTF-8?q?feat(track):=20campaign=20search=20?= =?UTF-8?q?=E2=80=94=20staged=20threads=20only,=20rumor/track=20kinds=20re?= =?UTF-8?q?tired?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/engine/campaign_search.dart | 43 +--------- lib/features/campaign_search_sheet.dart | 16 +--- test/campaign_search_test.dart | 100 ++++++++---------------- 3 files changed, 40 insertions(+), 119 deletions(-) diff --git a/lib/engine/campaign_search.dart b/lib/engine/campaign_search.dart index 3e36cb4..ddffd05 100644 --- a/lib/engine/campaign_search.dart +++ b/lib/engine/campaign_search.dart @@ -9,15 +9,7 @@ import 'models.dart'; enum SearchDestination { journal, track, sheet } /// Which entity type produced a hit. -enum SearchResultKind { - journalEntry, - thread, - rumor, - track, - character, - place, - npc -} +enum SearchResultKind { journalEntry, thread, character, place, npc } /// A single search hit with the display text, a snippet, and where to navigate. class CampaignSearchResult { @@ -47,14 +39,13 @@ class CampaignSearchResult { } /// Case-insensitive, multi-term AND search over all provided entity lists. -/// Blank [query] returns every entity. Order: journal entries first, then -/// threads, rumors, tracks, characters — preserves input order within each kind. +/// Blank [query] returns every entity. Order: journal entries first, +/// then threads, characters, places, NPCs — preserves input order within +/// each kind. List searchCampaign( String query, { List entries = const [], List threads = const [], - List rumors = const [], - List tracks = const [], List characters = const [], List places = const [], List npcs = const [], @@ -97,32 +88,6 @@ List searchCampaign( } } - for (final r in rumors) { - if (matches('${r.text}\n${r.note}')) { - results.add(CampaignSearchResult( - kind: SearchResultKind.rumor, - id: r.id, - title: r.text.length > 60 ? '${r.text.substring(0, 60)}…' : r.text, - snippet: r.note, - destination: SearchDestination.track, - subtab: 'rumors', - )); - } - } - - for (final t in tracks) { - if (matches('${t.name}\n${t.note}')) { - results.add(CampaignSearchResult( - kind: SearchResultKind.track, - id: t.id, - title: t.name, - snippet: t.note.length > 80 ? '${t.note.substring(0, 80)}…' : t.note, - destination: SearchDestination.track, - subtab: 'tracks', - )); - } - } - for (final c in characters) { if (matches('${c.name}\n${c.note}')) { results.add(CampaignSearchResult( diff --git a/lib/features/campaign_search_sheet.dart b/lib/features/campaign_search_sheet.dart index cb5ecdc..bfc0743 100644 --- a/lib/features/campaign_search_sheet.dart +++ b/lib/features/campaign_search_sheet.dart @@ -16,9 +16,9 @@ Future showCampaignSearchSheet(BuildContext context) => builder: (_) => const CampaignSearchSheet(), ); -/// Modal search sheet that queries journal entries, threads, rumors, tracks, -/// and characters in one pass. Results group by entity type; tapping navigates -/// via [shellRouteProvider]. +/// Modal search sheet that queries journal entries, threads, characters, +/// places, and NPCs in one pass. Results group by entity type; tapping +/// navigates via [shellRouteProvider]. class CampaignSearchSheet extends ConsumerStatefulWidget { const CampaignSearchSheet({super.key}); @@ -53,8 +53,6 @@ class _CampaignSearchSheetState extends ConsumerState { Widget build(BuildContext context) { final entries = ref.watch(journalProvider).valueOrNull ?? const []; final threads = ref.watch(threadsProvider).valueOrNull ?? const []; - final rumors = ref.watch(rumorsProvider).valueOrNull ?? const []; - final tracks = ref.watch(tracksProvider).valueOrNull ?? const []; final characters = ref.watch(charactersProvider).valueOrNull ?? const []; final places = ref.watch(placesProvider).valueOrNull ?? const []; final npcs = ref.watch(npcsProvider).valueOrNull ?? const []; @@ -63,8 +61,6 @@ class _CampaignSearchSheetState extends ConsumerState { _query, entries: entries, threads: threads, - rumors: rumors, - tracks: tracks, characters: characters, places: places, npcs: npcs, @@ -105,7 +101,7 @@ class _CampaignSearchSheetState extends ConsumerState { isDense: true, ), onChanged: (v) { - // Debounced: searchCampaign re-scans all five entity lists + // Debounced: searchCampaign re-scans all entity lists // in build(), so don't rebuild on every keystroke. _debounce?.cancel(); _debounce = Timer(const Duration(milliseconds: 250), () { @@ -162,8 +158,6 @@ class _CampaignSearchSheetState extends ConsumerState { String _kindLabel(SearchResultKind kind) => switch (kind) { SearchResultKind.journalEntry => 'Journal', SearchResultKind.thread => 'Threads', - SearchResultKind.rumor => 'Rumors', - SearchResultKind.track => 'Progress Tracks', SearchResultKind.character => 'Characters', SearchResultKind.place => 'Places', SearchResultKind.npc => 'People', @@ -172,8 +166,6 @@ String _kindLabel(SearchResultKind kind) => switch (kind) { IconData _kindIcon(SearchResultKind kind) => switch (kind) { SearchResultKind.journalEntry => Icons.book_outlined, SearchResultKind.thread => Icons.label_outline, - SearchResultKind.rumor => Icons.chat_bubble_outline, - SearchResultKind.track => Icons.track_changes, SearchResultKind.character => Icons.person_outline, SearchResultKind.place => Icons.place_outlined, SearchResultKind.npc => Icons.groups_outlined, diff --git a/test/campaign_search_test.dart b/test/campaign_search_test.dart index 89ac72a..6c9b064 100644 --- a/test/campaign_search_test.dart +++ b/test/campaign_search_test.dart @@ -10,14 +10,9 @@ JournalEntry _entry(String id, String title, String body) => JournalEntry( body: body, ); -Thread _thread(String id, String title, {String note = ''}) => - Thread(id: id, title: title, note: note); - -Rumor _rumor(String id, String text, {String note = ''}) => - Rumor(id: id, text: text, note: note); - -Track _track(String id, String name, {String note = ''}) => - Track(id: id, name: name, note: note); +Thread _thread(String id, String title, + {String note = '', ThreadStage stage = ThreadStage.active}) => + Thread(id: id, title: title, note: note, stage: stage); Character _char(String id, String name, {String note = ''}) => Character(id: id, name: name, note: note); @@ -29,18 +24,18 @@ void main() { '', entries: [_entry('j1', 'Village', 'burning')], threads: [_thread('t1', 'The Curse')], - rumors: [_rumor('r1', 'Strange lights')], - tracks: [_track('tr1', 'Doom clock')], characters: [_char('c1', 'Aldric')], ); - expect(results, hasLength(5)); + expect(results, hasLength(3)); }); }); group('searchCampaign — journal entries', () { test('matches title', () { - final r = searchCampaign('village', - entries: [_entry('j1', 'Village raid', ''), _entry('j2', 'Camp', '')]); + final r = searchCampaign('village', entries: [ + _entry('j1', 'Village raid', ''), + _entry('j2', 'Camp', '') + ]); expect(r, hasLength(1)); expect(r.first.id, 'j1'); expect(r.first.kind, SearchResultKind.journalEntry); @@ -55,9 +50,10 @@ void main() { group('searchCampaign — threads', () { test('matches title', () { - final r = searchCampaign('curse', - threads: [_thread('t1', 'The Curse of Eld', note: ''), - _thread('t2', 'Find the king')]); + final r = searchCampaign('curse', threads: [ + _thread('t1', 'The Curse of Eld', note: ''), + _thread('t2', 'Find the king') + ]); expect(r.single.id, 't1'); expect(r.single.kind, SearchResultKind.thread); }); @@ -67,27 +63,13 @@ void main() { threads: [_thread('t1', 'Mystery', note: 'Something shadow lurks')]); expect(r.single.kind, SearchResultKind.thread); }); - }); - group('searchCampaign — rumors', () { - test('matches text', () { - final r = searchCampaign('lights', - rumors: [_rumor('r1', 'Strange lights seen'), _rumor('r2', 'Lost merchant')]); - expect(r.single.id, 'r1'); - }); - - test('matches note', () { - final r = searchCampaign('goblin', - rumors: [_rumor('r1', 'Old rumor', note: 'goblin sighting')]); - expect(r.single.kind, SearchResultKind.rumor); - }); - }); - - group('searchCampaign — tracks', () { - test('matches name', () { - final r = searchCampaign('doom', - tracks: [_track('tr1', 'Doom Clock'), _track('tr2', 'Reputation')]); - expect(r.single.id, 'tr1'); + test('rumor-stage threads are found as threads', () { + final results = searchCampaign('whisper', threads: [ + Thread(id: 'r1', title: 'Whispered lead', stage: ThreadStage.rumor), + ]); + expect(results.single.kind, SearchResultKind.thread); + expect(results.single.subtab, 'threads'); }); }); @@ -108,33 +90,28 @@ void main() { group('searchCampaign — multi-term AND', () { test('requires all terms to match', () { - final r = searchCampaign('cursed sword', - entries: [ - _entry('j1', 'Cursed sword found', ''), - _entry('j2', 'Cursed ring', ''), - _entry('j3', 'Old sword', ''), - ]); + final r = searchCampaign('cursed sword', entries: [ + _entry('j1', 'Cursed sword found', ''), + _entry('j2', 'Cursed ring', ''), + _entry('j3', 'Old sword', ''), + ]); expect(r.single.id, 'j1'); }); }); group('searchCampaign — cross-entity', () { - test('returns results from all five kinds in one call', () { + test('returns results from all three kinds in one call', () { final r = searchCampaign( 'dragon', entries: [_entry('j1', 'Dragon spotted', '')], threads: [_thread('t1', 'Slay the dragon')], - rumors: [_rumor('r1', 'Dragon gold')], - tracks: [_track('tr1', 'Dragon threat')], characters: [_char('c1', 'Dragonborn warrior')], ); - expect(r, hasLength(5)); + expect(r, hasLength(3)); final kinds = r.map((x) => x.kind).toSet(); expect(kinds, { SearchResultKind.journalEntry, SearchResultKind.thread, - SearchResultKind.rumor, - SearchResultKind.track, SearchResultKind.character, }); }); @@ -142,35 +119,22 @@ void main() { group('CampaignSearchResult navigation', () { test('journal entry navigates to journal', () { - final r = searchCampaign('village', - entries: [_entry('j1', 'Village', '')]).single; + final r = + searchCampaign('village', entries: [_entry('j1', 'Village', '')]) + .single; expect(r.destination, SearchDestination.journal); }); test('thread navigates to track/threads', () { - final r = searchCampaign('curse', - threads: [_thread('t1', 'The Curse')]).single; + final r = + searchCampaign('curse', threads: [_thread('t1', 'The Curse')]).single; expect(r.destination, SearchDestination.track); expect(r.subtab, 'threads'); }); - test('rumor navigates to track/rumors', () { - final r = searchCampaign('lights', - rumors: [_rumor('r1', 'Strange lights')]).single; - expect(r.destination, SearchDestination.track); - expect(r.subtab, 'rumors'); - }); - - test('track navigates to track/tracks', () { - final r = searchCampaign('doom', - tracks: [_track('tr1', 'Doom Clock')]).single; - expect(r.destination, SearchDestination.track); - expect(r.subtab, 'tracks'); - }); - test('character navigates to sheet/characters', () { - final r = searchCampaign('aldric', - characters: [_char('c1', 'Aldric')]).single; + final r = + searchCampaign('aldric', characters: [_char('c1', 'Aldric')]).single; expect(r.destination, SearchDestination.sheet); expect(r.subtab, 'characters'); }); From f8c6c7db6427dcba0e80bd36bf4f755aca363d7e Mon Sep 17 00:00:00 2001 From: John Taylor Date: Sat, 22 Aug 2026 08:50:37 -0400 Subject: [PATCH 09/15] feat(run): threads panel reads staged threads only --- lib/features/run_screen.dart | 23 ++++++++++------------- test/run_screen_test.dart | 25 ++++++++++++++++--------- 2 files changed, 26 insertions(+), 22 deletions(-) diff --git a/lib/features/run_screen.dart b/lib/features/run_screen.dart index 0461598..d70ecc4 100644 --- a/lib/features/run_screen.dart +++ b/lib/features/run_screen.dart @@ -43,7 +43,7 @@ class RunScreen extends ConsumerWidget { const quickref = _QuickRefPanel(); const party = _PartyPanel(); const scene = _ScenePanel(); - const threads = _ThreadsRumorsPanel(); + const threads = _ThreadsPanel(); const dice = _DiceOraclePanel(); const capture = _CapturePanel(); const reference = _ReferencePanel(); @@ -493,20 +493,17 @@ class _ScenePanel extends ConsumerWidget { } } -/// Read-only glance at the live plot: open threads (+ unresolved rumors in GM -/// mode). Tapping a row jumps to the matching Track subtab. -class _ThreadsRumorsPanel extends ConsumerWidget { - const _ThreadsRumorsPanel(); +/// Read-only glance at the live plot: active threads plus unconfirmed +/// rumors. Tapping a row jumps to the matching Track subtab. +class _ThreadsPanel extends ConsumerWidget { + const _ThreadsPanel(); @override Widget build(BuildContext context, WidgetRef ref) { final theme = Theme.of(context); - final threads = (ref.watch(threadsProvider).valueOrNull ?? const []) - .where((t) => t.open) - .toList(); - final rumors = (ref.watch(rumorsProvider).valueOrNull ?? const []) - .where((r) => !r.resolved) - .toList(); + final all = ref.watch(threadsProvider).valueOrNull ?? const []; + final threads = all.where((t) => t.stage == ThreadStage.active).toList(); + final rumors = all.where((t) => t.stage == ThreadStage.rumor).toList(); final nav = ref.read(shellRouteProvider.notifier); if (threads.isEmpty && rumors.isEmpty) { @@ -548,10 +545,10 @@ class _ThreadsRumorsPanel extends ConsumerWidget { for (final r in rumors.take(5)) InkWell( key: Key('run-rumor-${r.id}'), - onTap: () => nav.goTo(Destination.track, subtab: 'rumors'), + onTap: () => nav.goTo(Destination.track, subtab: 'threads'), child: Padding( padding: const EdgeInsets.symmetric(vertical: 3), - child: Text(r.text, style: theme.textTheme.bodySmall), + child: Text(r.title, style: theme.textTheme.bodySmall), ), ), ], diff --git a/test/run_screen_test.dart b/test/run_screen_test.dart index a07f1b0..0e19a82 100644 --- a/test/run_screen_test.dart +++ b/test/run_screen_test.dart @@ -34,7 +34,6 @@ Map _prefs({ String? crawlJson, String? contextJson, String? threadsJson, - String? rumorsJson, }) => { 'loreseer.sessions.v1': @@ -45,7 +44,6 @@ Map _prefs({ if (crawlJson != null) 'loreseer.crawl.v1.$_sid': crawlJson, if (contextJson != null) 'loreseer.context.v1.$_sid': contextJson, if (threadsJson != null) 'loreseer.threads.v1.$_sid': threadsJson, - if (rumorsJson != null) 'loreseer.rumors.v1.$_sid': rumorsJson, }; Future _pump( @@ -260,22 +258,31 @@ void main() { expect(sceneN.dy, greaterThan(initN.dy)); }); - testWidgets('threads panel: shows open threads and unresolved rumors; routes', + testWidgets( + 'threads panel: shows active threads and rumor-stage threads; routes', (tester) async { - const threads = - '[{"id":"t1","title":"Find the Relic","open":true,"pinned":false,"progress":3,"progressMax":8}]'; - const rumors = '[{"id":"r1","text":"The mayor lies","resolved":false}]'; - final c = await _pump( - tester, data, _prefs(threadsJson: threads, rumorsJson: rumors)); + const threads = '[' + '{"id":"t1","title":"Find the Relic","stage":"active","pinned":false,"progress":3,"progressMax":8},' + '{"id":"r1","title":"The mayor lies","stage":"rumor"}' + ']'; + final c = await _pump(tester, data, _prefs(threadsJson: threads)); expect(find.byKey(const Key('run-thread-t1')), findsOneWidget); expect(find.text('Find the Relic'), findsOneWidget); - // Rumors show without any mode gate (solo-only). + // Rumor-stage threads render under the RUMORS header. expect(find.byKey(const Key('run-rumor-r1')), findsOneWidget); + expect(find.text('The mayor lies'), findsOneWidget); + expect(find.text('RUMORS'), findsOneWidget); // Tap a thread → routes to Track/threads. await tester.tap(find.byKey(const Key('run-thread-t1'))); await tester.pumpAndSettle(); expect(c.read(shellRouteProvider).destination, Destination.track); expect(c.read(shellRouteProvider).subtab, 'threads'); + + // Tap a rumor → also routes to Track/threads (unified subtab). + await tester.tap(find.byKey(const Key('run-rumor-r1'))); + await tester.pumpAndSettle(); + expect(c.read(shellRouteProvider).destination, Destination.track); + expect(c.read(shellRouteProvider).subtab, 'threads'); }); testWidgets('threads panel: empty state', (tester) async { From 35843dbe1f1e90961e4102295350320f22277b29 Mon Sep 17 00:00:00 2001 From: John Taylor Date: Sat, 22 Aug 2026 08:56:01 -0400 Subject: [PATCH 10/15] feat(track): home + suggestions point at unified Threads --- lib/features/assistant_rail.dart | 2 +- lib/features/track_home_pane.dart | 76 +++---------------------------- test/track_home_pane_test.dart | 4 +- 3 files changed, 9 insertions(+), 73 deletions(-) diff --git a/lib/features/assistant_rail.dart b/lib/features/assistant_rail.dart index 8d36f78..fd64c95 100644 --- a/lib/features/assistant_rail.dart +++ b/lib/features/assistant_rail.dart @@ -147,7 +147,7 @@ class _AssistantSectionState extends ConsumerState { case 'make-move': route.goTo(Destination.sheet, subtab: 'moves'); case 'develop-rumor': - route.goTo(Destination.track, subtab: 'rumors'); + route.goTo(Destination.track, subtab: 'threads'); case 'seed-npc': route.goTo(Destination.sheet); } diff --git a/lib/features/track_home_pane.dart b/lib/features/track_home_pane.dart index a6adc6d..1ffbfb5 100644 --- a/lib/features/track_home_pane.dart +++ b/lib/features/track_home_pane.dart @@ -9,7 +9,7 @@ import '../state/play_context.dart'; import '../state/providers.dart'; /// Track → Home: a "Where am I?" dashboard. Summary cards for the campaign's -/// live state (scene / threads / tracks / party / encounter) that double as +/// live state (scene / threads / party / encounter) that double as /// navigation into the matching subtab (or the Sheet verb for the roster). /// /// Every card is defensive against empty/loading provider states — it shows a @@ -26,7 +26,6 @@ class TrackHomePane extends ConsumerWidget { final scene = activeSceneEntry(journal, activeSceneId); final threads = ref.watch(threadsProvider).valueOrNull ?? const []; - final tracks = ref.watch(tracksProvider).valueOrNull ?? const []; final chars = ref.watch(charactersProvider).valueOrNull ?? const []; final encounter = @@ -37,7 +36,6 @@ class TrackHomePane extends ConsumerWidget { final otherCards = [ _nowCard(context, ref, scene), _threadsCard(context, ref, threads), - _tracksCard(context, ref, tracks), _partyCard(context, ref, chars), ]; @@ -72,12 +70,10 @@ class TrackHomePane extends ConsumerWidget { final tk = context.lore; const radius = BorderRadius.all(Radius.circular(14)); const lines = <(String, String)>[ - ('Tasks', 'tally-tracked goals'), ('Scenes', 'story beats'), - ('Threads', 'open storylines'), + ('Threads', 'rumors, storylines, tasks, clocks'), ('Encounter', 'combat'), - ('Rumors', 'leads'), - ('Tracks', 'clocks'), + ('World', 'people and places'), ]; return Material( key: const Key('track-help-card'), @@ -126,7 +122,9 @@ class TrackHomePane extends ConsumerWidget { text: '$label ', style: const TextStyle(fontWeight: FontWeight.w600), ), - TextSpan(text: '— $desc', style: TextStyle(color: tk.inkMuted)), + TextSpan( + text: '— $desc', + style: TextStyle(color: tk.inkMuted)), ], ), ), @@ -258,68 +256,6 @@ class TrackHomePane extends ConsumerWidget { ); } - Widget _tracksCard(BuildContext context, WidgetRef ref, List tracks) { - final tk = context.lore; - return _card( - context, - cardKey: const Key('track-home-tracks'), - eyebrow: 'TRACKS', - headline: tracks.isEmpty ? 'None yet' : '${tracks.length}', - onTap: () => ref - .read(shellRouteProvider.notifier) - .goTo(Destination.track, subtab: 'tracks'), - child: tracks.isEmpty - ? Text('Clocks for tension and time.', - style: TextStyle(color: tk.inkMuted)) - : Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - for (final t in tracks.take(3)) - Padding( - padding: const EdgeInsets.only(top: 6), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Expanded( - child: Text( - t.name, - style: TextStyle(color: tk.inkBody), - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - Text('${t.filled} / ${t.max}', - style: tk.uiLabel.copyWith( - fontSize: 12, color: tk.inkMuted)), - ], - ), - const SizedBox(height: 3), - ClipRRect( - borderRadius: BorderRadius.circular(4), - child: LinearProgressIndicator( - value: t.max == 0 ? 0 : (t.filled / t.max), - minHeight: 5, - backgroundColor: tk.hairline, - valueColor: - AlwaysStoppedAnimation(tk.terracotta), - ), - ), - ], - ), - ), - if (tracks.length > 3) - Padding( - padding: const EdgeInsets.only(top: 6), - child: Text('+${tracks.length - 3} more', - style: TextStyle(color: tk.inkMuted, fontSize: 12)), - ), - ], - ), - ); - } - Widget _partyCard( BuildContext context, WidgetRef ref, List chars) { final tk = context.lore; diff --git a/test/track_home_pane_test.dart b/test/track_home_pane_test.dart index 38d9dee..10be3a9 100644 --- a/test/track_home_pane_test.dart +++ b/test/track_home_pane_test.dart @@ -52,7 +52,8 @@ void main() { 'loreseer.characters.v1.default': '[{"id":"c1","name":"Ash","stats":[],' '"tracks":[{"label":"HP","current":4,"max":5}],"tags":[]}]', // Idle encounter: no combatants. - 'loreseer.encounter.v1.default': '{"combatants":[],"turnIndex":0,"round":1}', + 'loreseer.encounter.v1.default': + '{"combatants":[],"turnIndex":0,"round":1}', }); // NOW card shows the active scene title. @@ -145,7 +146,6 @@ void main() { // Every card still renders. expect(find.byKey(const Key('track-home-now')), findsOneWidget); expect(find.byKey(const Key('track-home-threads')), findsOneWidget); - expect(find.byKey(const Key('track-home-tracks')), findsOneWidget); expect(find.byKey(const Key('track-home-party')), findsOneWidget); expect(find.byKey(const Key('track-home-encounter')), findsOneWidget); }); From fdc2569a34e80417b8506e256b5238cdc2a42f79 Mon Sep 17 00:00:00 2001 From: John Taylor Date: Sat, 22 Aug 2026 09:00:56 -0400 Subject: [PATCH 11/15] test: develop-rumor chip routes to Threads --- test/assistant_rail_test.dart | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/test/assistant_rail_test.dart b/test/assistant_rail_test.dart index efff91e..cf9efcf 100644 --- a/test/assistant_rail_test.dart +++ b/test/assistant_rail_test.dart @@ -90,14 +90,14 @@ void main() { expect(route.subtab, 'scenes'); }); - testWidgets('shows Develop a rumor and routes to Rumors', (tester) async { + testWidgets('shows Develop a rumor and routes to Threads', (tester) async { final c = await pumpSection(tester); expect(find.text('Develop a rumor'), findsOneWidget); await tester.tap(find.text('Develop a rumor')); await tester.pumpAndSettle(); final route = c.read(shellRouteProvider); expect(route.destination, Destination.track); - expect(route.subtab, 'rumors'); + expect(route.subtab, 'threads'); }); testWidgets('develop-rumor and seed-npc are always present (no mode gate)', @@ -107,7 +107,8 @@ void main() { expect(find.text('Add an NPC'), findsOneWidget); }); - testWidgets('ask-the-Oracle box opens the multi-turn GM chat', (tester) async { + testWidgets('ask-the-Oracle box opens the multi-turn GM chat', + (tester) async { SharedPreferences.setMockInitialValues({ 'loreseer.sessions.v1': '{"active":"default","sessions":[{"id":"default","name":"C1"}]}', From 539a67d321bef56c9304a59de7a0cbb5fef710fa Mon Sep 17 00:00:00 2001 From: John Taylor Date: Sat, 22 Aug 2026 09:09:20 -0400 Subject: [PATCH 12/15] feat(lonelog): [Track:] notation maps to clock threads --- lib/engine/lonelog_export.dart | 5 ++-- lib/engine/lonelog_import.dart | 29 ++++++++++++---------- lib/state/providers.dart | 4 --- test/lonelog_export_test.dart | 37 +++++++++++++++++++++------- test/lonelog_import_test.dart | 45 +++++++++++++++++++++++++--------- 5 files changed, 80 insertions(+), 40 deletions(-) diff --git a/lib/engine/lonelog_export.dart b/lib/engine/lonelog_export.dart index d2d3d2a..cec7e4f 100644 --- a/lib/engine/lonelog_export.dart +++ b/lib/engine/lonelog_export.dart @@ -13,7 +13,6 @@ String campaignToLonelog({ String tone = '', required List threads, required List characters, - required List tracks, required List entriesNewestFirst, required Map threadTitles, required DateTime exportedAt, @@ -37,8 +36,8 @@ String campaignToLonelog({ final name = _tag(c.name); buf.writeln(tags.isEmpty ? '[N:$name]' : '[N:$name|$tags]'); } - for (final k in tracks) { - buf.writeln('[Track:${_tag(k.name)} ${k.filled}/${k.max}]'); + for (final t in threads.where((t) => t.progress > 0)) { + buf.writeln('[Track:${_tag(t.title)} ${t.progress}/${t.progressMax}]'); } buf ..writeln('[/STATE]') diff --git a/lib/engine/lonelog_import.dart b/lib/engine/lonelog_import.dart index b7c0ef5..bdbabd5 100644 --- a/lib/engine/lonelog_import.dart +++ b/lib/engine/lonelog_import.dart @@ -13,7 +13,6 @@ class LonelogImport { required this.tone, required this.threads, required this.characters, - required this.tracks, required this.entries, }); final String campaignName; @@ -21,7 +20,6 @@ class LonelogImport { final String tone; final List threads; final List characters; - final List tracks; final List entries; // newest-first (loreseer convention) } @@ -64,7 +62,6 @@ LonelogImport parseLonelog(String md, {required DateTime importedAt}) { final threads = []; final characters = []; - final tracks = []; final entries = []; final beat = []; var inState = false; @@ -99,7 +96,7 @@ LonelogImport parseLonelog(String md, {required DateTime importedAt}) { continue; } if (inState) { - _parseTag(line, threads, characters, tracks); + _parseTag(line, threads, characters); i++; continue; } @@ -147,13 +144,11 @@ LonelogImport parseLonelog(String md, {required DateTime importedAt}) { tone: tone, threads: threads, characters: characters, - tracks: tracks, entries: entries.reversed.toList(), // newest-first ); } -void _parseTag(String line, List threads, List characters, - List tracks) { +void _parseTag(String line, List threads, List characters) { final th = _threadRe.firstMatch(line); if (th != null) { threads.add(Thread( @@ -165,12 +160,20 @@ void _parseTag(String line, List threads, List characters, } final tr = _trackRe.firstMatch(line); if (tr != null) { - tracks.add(Track( - id: 'll-track-${tracks.length}', - name: tr.group(1)!.trim(), - filled: int.parse(tr.group(2)!), - max: int.parse(tr.group(3)!), - )); + final name = tr.group(1)!.trim(); + final filled = int.parse(tr.group(2)!); + final max = int.parse(tr.group(3)!); + final i = threads.indexWhere((t) => t.title == name); + if (i >= 0) { + threads[i] = threads[i].copyWith(progress: filled, progressMax: max); + } else { + threads.add(Thread( + id: 'll-track-${threads.length}', + title: name, + progress: filled, + progressMax: max, + )); + } return; } final n = _npcRe.firstMatch(line); diff --git a/lib/state/providers.dart b/lib/state/providers.dart index e8dd355..98a8363 100644 --- a/lib/state/providers.dart +++ b/lib/state/providers.dart @@ -2891,7 +2891,6 @@ class SessionsNotifier extends AsyncNotifier { final journal = await ref.read(journalProvider.future); final threads = await ref.read(threadsProvider.future); final characters = await ref.read(charactersProvider.future); - final tracks = await ref.read(tracksProvider.future); final settings = await ref.read(settingsProvider.future); return campaignToLonelog( campaignName: s.activeMeta.name, @@ -2899,7 +2898,6 @@ class SessionsNotifier extends AsyncNotifier { tone: settings.tone, threads: threads, characters: characters, - tracks: tracks, entriesNewestFirst: journal, threadTitles: {for (final t in threads) t.id: t.title}, exportedAt: DateTime.now(), @@ -2998,8 +2996,6 @@ class SessionsNotifier extends AsyncNotifier { jsonEncode(doc.threads.map((t) => t.toJson()).toList()), 'loreseer.characters.v1': jsonEncode(doc.characters.map((c) => c.toJson()).toList()), - 'loreseer.tracks.v1': - jsonEncode(doc.tracks.map((t) => t.toJson()).toList()), 'loreseer.settings.v1': jsonEncode( CampaignSettings(genre: doc.genre, tone: doc.tone).toJson()), }; diff --git a/test/lonelog_export_test.dart b/test/lonelog_export_test.dart index 8ae0390..c331dd6 100644 --- a/test/lonelog_export_test.dart +++ b/test/lonelog_export_test.dart @@ -8,7 +8,6 @@ String _export({ String tone = '', List threads = const [], List characters = const [], - List tracks = const [], List entries = const [], }) => campaignToLonelog( @@ -17,7 +16,6 @@ String _export({ tone: tone, threads: threads, characters: characters, - tracks: tracks, entriesNewestFirst: entries, threadTitles: {for (final t in threads) t.id: t.title}, exportedAt: DateTime(2026, 6, 14), @@ -52,7 +50,7 @@ void main() { final out = _export( name: 'Camp: Alpha', threads: [ - Thread(id: 't1', title: 'Rescue | [the] prisoner', open: true), + Thread(id: 't1', title: 'Rescue | [the] prisoner', stage: ThreadStage.active), ], characters: [const Character(id: 'c1', name: 'Vance|ally')], ); @@ -64,27 +62,48 @@ void main() { expect(out, contains('[N:Vance/ally]')); }); - test('STATE block lists threads, characters, tracks as tags', () { + test('STATE block lists threads and characters as tags', () { final out = _export( threads: [ - Thread(id: 't1', title: 'Slay the wyrm', open: true), - Thread(id: 't2', title: 'Find the heir', open: false), + Thread(id: 't1', title: 'Slay the wyrm', stage: ThreadStage.active), + Thread(id: 't2', title: 'Find the heir', stage: ThreadStage.done), ], characters: [ const Character(id: 'c1', name: 'Vance', tags: ['gruff', 'ally']), const Character(id: 'c2', name: 'Mute'), ], - tracks: [const Track(id: 'k1', name: 'Ritual', filled: 3, max: 6)], ); expect(out, contains('[STATE]')); expect(out, contains('[Thread:Slay the wyrm|Open]')); expect(out, contains('[Thread:Find the heir|Closed]')); expect(out, contains('[N:Vance|gruff, ally]')); expect(out, contains('[N:Mute]')); - expect(out, contains('[Track:Ritual 3/6]')); expect(out, contains('[/STATE]')); }); + test('a thread with progress emits both [Thread:] and [Track:] lines', () { + final out = _export( + threads: [ + Thread( + id: 't1', + title: 'Main quest', + stage: ThreadStage.active, + progress: 3, + progressMax: 6), + ], + ); + expect(out, contains('[Thread:Main quest|Open]')); + expect(out, contains('[Track:Main quest 3/6]')); + }); + + test('a plain thread (progress 0) emits only its [Thread:] line', () { + final out = _export( + threads: [Thread(id: 't1', title: 'Side quest', stage: ThreadStage.active)], + ); + expect(out, contains('[Thread:Side quest|Open]')); + expect(out, isNot(contains('[Track:'))); + }); + test('scene numbering increments and renders chaos note', () { final out = _export(entries: [ _entry(JournalKind.scene, 'Second', '', chaos: 5), @@ -114,7 +133,7 @@ void main() { test('text beat renders prose; threadId and tags render as trailers', () { final out = _export( - threads: [Thread(id: 't1', title: 'Rescue Jonah', open: true)], + threads: [Thread(id: 't1', title: 'Rescue Jonah', stage: ThreadStage.active)], entries: [ _entry(JournalKind.text, 'note', 'The door creaks open.', threadId: 't1', tags: ['quiet', 'night']), diff --git a/test/lonelog_import_test.dart b/test/lonelog_import_test.dart index 945cb21..b8b1587 100644 --- a/test/lonelog_import_test.dart +++ b/test/lonelog_import_test.dart @@ -15,13 +15,12 @@ void main() { expect(b.campaignName, 'Imported Lonelog'); }); - test('parses the STATE block into threads, characters, tracks', () { + test('parses the STATE block into threads and characters', () { const md = '---\ntitle: "C"\n---\n\n[STATE]\n' '[Thread:Slay the wyrm|Open]\n' '[Thread:Find the heir|Closed]\n' '[N:Vance|gruff, ally]\n' '[N:Mute]\n' - '[Track:Ritual 3/6]\n' '[/STATE]\n'; final imp = parseLonelog(md, importedAt: _t); expect(imp.threads.map((t) => t.title), ['Slay the wyrm', 'Find the heir']); @@ -31,9 +30,27 @@ void main() { expect(imp.characters[0].tags, ['gruff', 'ally']); expect(imp.characters[1].name, 'Mute'); expect(imp.characters[1].tags, isEmpty); - expect(imp.tracks.single.name, 'Ritual'); - expect(imp.tracks.single.filled, 3); - expect(imp.tracks.single.max, 6); + }); + + test('a lone [Track:] line imports as a thread with the clock set', () { + const md = '[STATE]\n[Track:Supplies 2/6]\n[/STATE]\n'; + final imp = parseLonelog(md, importedAt: _t); + expect(imp.threads.single.title, 'Supplies'); + expect(imp.threads.single.progress, 2); + expect(imp.threads.single.progressMax, 6); + }); + + test('a [Track:] with a matching [Thread:] title merges onto one thread', () { + const md = '[STATE]\n' + '[Thread:Main quest|Open]\n' + '[Track:Main quest 3/6]\n' + '[/STATE]\n'; + final imp = parseLonelog(md, importedAt: _t); + expect(imp.threads.length, 1); + expect(imp.threads.single.title, 'Main quest'); + expect(imp.threads.single.open, isTrue); + expect(imp.threads.single.progress, 3); + expect(imp.threads.single.progressMax, 6); }); test('the first | is the thread delimiter; a malformed pipe-title is skipped', @@ -84,13 +101,18 @@ void main() { final exported = campaignToLonelog( campaignName: 'Round Trip', threads: [ - Thread(id: 'a', title: 'Open quest', open: true), - Thread(id: 'b', title: 'Done quest', open: false), + Thread(id: 'a', title: 'Open quest', stage: ThreadStage.active), + Thread(id: 'b', title: 'Done quest', stage: ThreadStage.done), + Thread( + id: 'd', + title: 'Doom', + stage: ThreadStage.active, + progress: 2, + progressMax: 8), ], characters: [ const Character(id: 'c', name: 'Bob', tags: ['friendly']) ], - tracks: [const Track(id: 'd', name: 'Doom', filled: 2, max: 8)], entriesNewestFirst: [ JournalEntry( id: '3', @@ -116,12 +138,13 @@ void main() { ); final imp = parseLonelog(exported, importedAt: _t); expect(imp.campaignName, 'Round Trip'); - expect(imp.threads.length, 2); + expect(imp.threads.length, 3); expect(imp.threads.firstWhere((t) => t.title == 'Open quest').open, isTrue); expect( imp.threads.firstWhere((t) => t.title == 'Done quest').open, isFalse); - expect(imp.tracks.single.name, 'Doom'); - expect(imp.tracks.single.filled, 2); + final doom = imp.threads.firstWhere((t) => t.title == 'Doom'); + expect(doom.progress, 2); + expect(doom.progressMax, 8); expect(imp.characters.single.name, 'Bob'); expect(imp.entries.length, 3); // scene + result-as-text + text final scenes = From 91987182ff13fc8b1d2a739916183ff9d90a9561 Mon Sep 17 00:00:00 2001 From: John Taylor Date: Sat, 22 Aug 2026 09:09:37 -0400 Subject: [PATCH 13/15] style: dart format lonelog_export_test.dart --- test/lonelog_export_test.dart | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/test/lonelog_export_test.dart b/test/lonelog_export_test.dart index c331dd6..f0d116a 100644 --- a/test/lonelog_export_test.dart +++ b/test/lonelog_export_test.dart @@ -50,7 +50,10 @@ void main() { final out = _export( name: 'Camp: Alpha', threads: [ - Thread(id: 't1', title: 'Rescue | [the] prisoner', stage: ThreadStage.active), + Thread( + id: 't1', + title: 'Rescue | [the] prisoner', + stage: ThreadStage.active), ], characters: [const Character(id: 'c1', name: 'Vance|ally')], ); @@ -98,7 +101,9 @@ void main() { test('a plain thread (progress 0) emits only its [Thread:] line', () { final out = _export( - threads: [Thread(id: 't1', title: 'Side quest', stage: ThreadStage.active)], + threads: [ + Thread(id: 't1', title: 'Side quest', stage: ThreadStage.active) + ], ); expect(out, contains('[Thread:Side quest|Open]')); expect(out, isNot(contains('[Track:'))); @@ -133,7 +138,9 @@ void main() { test('text beat renders prose; threadId and tags render as trailers', () { final out = _export( - threads: [Thread(id: 't1', title: 'Rescue Jonah', stage: ThreadStage.active)], + threads: [ + Thread(id: 't1', title: 'Rescue Jonah', stage: ThreadStage.active) + ], entries: [ _entry(JournalKind.text, 'note', 'The door creaks open.', threadId: 't1', tags: ['quiet', 'night']), From b04e7c93b4b8aa4496acf9cbb2588c8fb891d10b Mon Sep 17 00:00:00 2001 From: John Taylor Date: Sat, 22 Aug 2026 09:19:39 -0400 Subject: [PATCH 14/15] =?UTF-8?q?feat(track):=20delete=20Rumor/Track=20mod?= =?UTF-8?q?els=20+=20providers=20=E2=80=94=20merge=20complete?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CLAUDE.md | 12 +++++ lib/engine/models/world.dart | 79 +------------------------------ lib/state/campaign_io.dart | 8 ---- lib/state/providers.dart | 76 ----------------------------- test/campaign_io_test.dart | 36 -------------- test/models_rumor_track_test.dart | 30 ------------ test/rumors_provider_test.dart | 21 -------- test/tracks_provider_test.dart | 22 --------- 8 files changed, 13 insertions(+), 271 deletions(-) delete mode 100644 test/models_rumor_track_test.dart delete mode 100644 test/rumors_provider_test.dart delete mode 100644 test/tracks_provider_test.dart diff --git a/CLAUDE.md b/CLAUDE.md index 8a8ec11..b8f9241 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -19,6 +19,18 @@ Working rules for this repo: ## Project notes +- **Tracking merge (2026-08-22, consolidation epic sub-project 1)** — + Threads, Tracks, and Rumors are ONE entity: `Thread` carries `ThreadStage + {rumor, active, done}` (JSON `stage`, omitted at active; legacy + `open:false` reads as done; `open` is now a derived getter). `Rumor`/ + `Track` models, `rumorsProvider`/`tracksProvider`, `RumorsPane`/ + `TracksPane`, and the `loreseer.rumors.v1`/`loreseer.tracks.v1` keys are + DELETED (fresh start, no data migration). Unified `ThreadsPane`: stage + filter chips, `rumor-new`, `thread-confirm-` promotion; legacy + `rumors`/`tracks` subtab routes alias to `threads`. Lonelog + `[Track:name n/m]` now maps to clock threads (export emits it from + `progress > 0`, import merges by title). See + `docs/superpowers/specs/2026-08-22-tracking-merge-design.md`. - **Unified inspiration catalog (2026-08-13, PR 3 of the streamline epic)** — one browsable catalog over three sources: flavor generators + bundled starter tables + My Tables. Pure `lib/engine/inspiration_catalog.dart` diff --git a/lib/engine/models/world.dart b/lib/engine/models/world.dart index 7184bf4..dc34b48 100644 --- a/lib/engine/models/world.dart +++ b/lib/engine/models/world.dart @@ -81,42 +81,6 @@ class InvItem { ); } -/// A rumor: something heard but not yet confirmed. Distinct from a thread — -/// a rumor resolves true or false, a thread progresses. -class Rumor { - const Rumor({ - required this.id, - required this.text, - this.resolved = false, - this.note = '', - }); - final String id; - final String text; - final bool resolved; - final String note; - - Rumor copyWith({String? text, bool? resolved, String? note}) => Rumor( - id: id, - text: text ?? this.text, - resolved: resolved ?? this.resolved, - note: note ?? this.note, - ); - - Map toJson() => { - 'id': id, - 'text': text, - if (resolved) 'resolved': true, - if (note.isNotEmpty) 'note': note, - }; - - factory Rumor.fromJson(Map j) => Rumor( - id: j['id'] as String, - text: j['text'] as String, - resolved: (j['resolved'] as bool?) ?? false, - note: (j['note'] as String?) ?? '', - ); -} - /// Kind of a tracked [Place] (a named world location, distinct from the map's /// coordinate cells — a Place may pin to one via [Place.location] but need not). enum PlaceKind { settlement, dungeon, wilderness, landmark, other } @@ -130,7 +94,7 @@ PlaceKind _placeKindFromName(String? n) => switch (n) { }; /// A named place in the world the party knows about — the Places tracker's -/// entity (session-scoped, like [Thread]/[Rumor]). Optionally pinned to a map +/// entity (session-scoped, like [Thread]). Optionally pinned to a map /// cell via [location] so journal entries logged there back-link to it. class Place { const Place({ @@ -289,47 +253,6 @@ class Npc { ); } -/// A generic filled/max progress track — the system-agnostic clock behind -/// the Tracks pane. -class Track { - const Track({ - required this.id, - required this.name, - this.filled = 0, - this.max = 10, - this.note = '', - }); - final String id; - final String name; - final int filled; - final int max; - final String note; - - Track copyWith({String? name, int? filled, int? max, String? note}) => Track( - id: id, - name: name ?? this.name, - filled: filled ?? this.filled, - max: max ?? this.max, - note: note ?? this.note, - ); - - Map toJson() => { - 'id': id, - 'name': name, - 'filled': filled, - 'max': max, - if (note.isNotEmpty) 'note': note, - }; - - factory Track.fromJson(Map j) => Track( - id: j['id'] as String, - name: j['name'] as String, - filled: (j['filled'] as int?) ?? 0, - max: (j['max'] as int?) ?? 10, - note: (j['note'] as String?) ?? '', - ); -} - // -- Ironsworn-family foe entries (from ruleset npc_collections) -------------- /// Rank label by 1-based index (Ironsworn 1=Troublesome … 5=Epic). diff --git a/lib/state/campaign_io.dart b/lib/state/campaign_io.dart index 22aba4c..b892abb 100644 --- a/lib/state/campaign_io.dart +++ b/lib/state/campaign_io.dart @@ -101,10 +101,6 @@ CampaignImport parseCampaign(String raw) { EncounterState.fromJson(value as Map); } else if (key == 'loreseer.map.v1') { MapState.fromJson(value as Map); - } else if (key == 'loreseer.rumors.v1') { - (value as List) - .map((e) => Rumor.fromJson(e as Map)) - .toList(); } else if (key == 'loreseer.places.v1') { (value as List) .map((e) => Place.fromJson(e as Map)) @@ -113,10 +109,6 @@ CampaignImport parseCampaign(String raw) { (value as List) .map((e) => Npc.fromJson(e as Map)) .toList(); - } else if (key == 'loreseer.tracks.v1') { - (value as List) - .map((e) => Track.fromJson(e as Map)) - .toList(); } else if (key == 'loreseer.inventory.v1') { (value as List) .map((e) => InvItem.fromJson(e as Map)) diff --git a/lib/state/providers.dart b/lib/state/providers.dart index 98a8363..9b08616 100644 --- a/lib/state/providers.dart +++ b/lib/state/providers.dart @@ -689,41 +689,6 @@ final charactersProvider = AsyncNotifierProvider>( CharacterNotifier.new); -// -- Rumors ----------------------------------------------------------------- -class RumorNotifier extends _PersistedList { - @override - String get prefsKey => 'loreseer.rumors.v1'; - @override - Rumor fromJson(Map json) => Rumor.fromJson(json); - @override - Map toJsonMap(Rumor item) => item.toJson(); - - Future add(String text) async { - await _persist([Rumor(id: _newId(), text: text), ...await _ready]); - } - - Future replace(Rumor rumor) async { - await _persist([ - for (final r in await _ready) - if (r.id == rumor.id) rumor else r, - ]); - } - - Future toggleResolved(String id) async { - await _persist([ - for (final r in await _ready) - if (r.id == id) r.copyWith(resolved: !r.resolved) else r, - ]); - } - - Future remove(String id) async { - await _persist((await _ready).where((r) => r.id != id).toList()); - } -} - -final rumorsProvider = - AsyncNotifierProvider>(RumorNotifier.new); - // -- Places (named world locations) ----------------------------------------- class PlaceNotifier extends _PersistedList { @override @@ -875,45 +840,6 @@ class UnitNotifier extends _PersistedList { final unitsProvider = AsyncNotifierProvider>(UnitNotifier.new); -// -- Tracks ----------------------------------------------------------------- -class TrackNotifier extends _PersistedList { - @override - String get prefsKey => 'loreseer.tracks.v1'; - @override - Track fromJson(Map json) => Track.fromJson(json); - @override - Map toJsonMap(Track item) => item.toJson(); - - Future add(String name, {int max = 10}) async { - await _persist( - [Track(id: _newId(), name: name, max: max), ...await _ready]); - } - - Future adjust(String id, int delta) async { - await _persist([ - for (final t in await _ready) - if (t.id == id) - t.copyWith(filled: (t.filled + delta).clamp(0, t.max)) - else - t, - ]); - } - - Future rename(String id, String name) async { - await _persist([ - for (final t in await _ready) - if (t.id == id) t.copyWith(name: name) else t, - ]); - } - - Future remove(String id) async { - await _persist((await _ready).where((t) => t.id != id).toList()); - } -} - -final tracksProvider = - AsyncNotifierProvider>(TrackNotifier.new); - // -- Crawl state (wilderness + dialog marker) ------------------------------- class CrawlNotifier extends AsyncNotifier { static const _baseKey = 'loreseer.crawl.v1'; @@ -2663,10 +2589,8 @@ const sessionScopedKeys = [ 'loreseer.map.v1', 'loreseer.dungeon_factions.v1', 'loreseer.verdant.v1', - 'loreseer.rumors.v1', 'loreseer.places.v1', 'loreseer.npcs.v1', - 'loreseer.tracks.v1', 'loreseer.inventory.v1', 'loreseer.units.v1', 'loreseer.settings.v1', diff --git a/test/campaign_io_test.dart b/test/campaign_io_test.dart index 37da9be..d433b90 100644 --- a/test/campaign_io_test.dart +++ b/test/campaign_io_test.dart @@ -168,42 +168,6 @@ void main() { expect(decoded['data'], contains('loreseer.journal.v2')); }); - test('rumors round-trip through campaign files', () { - const rumors = '[{"id":"r1","text":"North gate","resolved":true}]'; - final out = encodeCampaign( - name: 'C1', - savedAt: DateTime(2026, 6, 11), - rawByKey: {'loreseer.rumors.v1': rumors}, - ); - final parsed = parseCampaign(out); - expect(parsed.rawByKey, contains('loreseer.rumors.v1')); - final back = (jsonDecode(parsed.rawByKey['loreseer.rumors.v1']!) as List) - .cast>() - .map(Rumor.fromJson) - .single; - expect(back.text, 'North gate'); - expect(back.resolved, isTrue); - }); - - test('tracks round-trip through campaign files', () { - const tracks = - '[{"id":"tr1","name":"Find the heir","filled":3,"max":10}]'; - final out = encodeCampaign( - name: 'C1', - savedAt: DateTime(2026, 6, 11), - rawByKey: {'loreseer.tracks.v1': tracks}, - ); - final parsed = parseCampaign(out); - expect(parsed.rawByKey, contains('loreseer.tracks.v1')); - final back = (jsonDecode(parsed.rawByKey['loreseer.tracks.v1']!) as List) - .cast>() - .map(Track.fromJson) - .single; - expect(back.name, 'Find the heir'); - expect(back.filled, 3); - expect(back.max, 10); - }); - test('v2 file without rumors key imports fine', () { final v2 = jsonEncode({ 'app': 'loreseer', diff --git a/test/models_rumor_track_test.dart b/test/models_rumor_track_test.dart deleted file mode 100644 index 1b93b6b..0000000 --- a/test/models_rumor_track_test.dart +++ /dev/null @@ -1,30 +0,0 @@ -import 'package:flutter_test/flutter_test.dart'; -import 'package:loreseer/engine/models.dart'; - -void main() { - test('Rumor round-trips through json', () { - const r = Rumor( - id: '1', - text: 'Smugglers use the north gate', - note: 'from the barkeep'); - final back = Rumor.fromJson(r.toJson()); - expect(back.id, '1'); - expect(back.text, r.text); - expect(back.note, r.note); - expect(back.resolved, isFalse); - }); - - test('Rumor copyWith toggles resolved', () { - const r = Rumor(id: '1', text: 'x'); - expect(r.copyWith(resolved: true).resolved, isTrue); - }); - - test('Track round-trips and clamps via copyWith', () { - const tr = Track(id: '1', name: 'Reach the keep', filled: 3, max: 10); - final back = Track.fromJson(tr.toJson()); - expect(back.name, 'Reach the keep'); - expect(back.filled, 3); - expect(back.max, 10); - expect(tr.copyWith(filled: 5).filled, 5); - }); -} diff --git a/test/rumors_provider_test.dart b/test/rumors_provider_test.dart deleted file mode 100644 index 12d9043..0000000 --- a/test/rumors_provider_test.dart +++ /dev/null @@ -1,21 +0,0 @@ -import 'package:flutter_test/flutter_test.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:shared_preferences/shared_preferences.dart'; -import 'package:loreseer/state/providers.dart'; - -void main() { - setUp(() => SharedPreferences.setMockInitialValues({})); - - test('add, toggle, remove rumors persist', () async { - final c = ProviderContainer(); - addTearDown(c.dispose); - await c.read(rumorsProvider.future); - await c.read(rumorsProvider.notifier).add('North gate'); - final list = c.read(rumorsProvider).value!; - expect(list.single.text, 'North gate'); - await c.read(rumorsProvider.notifier).toggleResolved(list.single.id); - expect(c.read(rumorsProvider).value!.single.resolved, isTrue); - await c.read(rumorsProvider.notifier).remove(list.single.id); - expect(c.read(rumorsProvider).value, isEmpty); - }); -} diff --git a/test/tracks_provider_test.dart b/test/tracks_provider_test.dart deleted file mode 100644 index 580871e..0000000 --- a/test/tracks_provider_test.dart +++ /dev/null @@ -1,22 +0,0 @@ -import 'package:flutter_test/flutter_test.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:shared_preferences/shared_preferences.dart'; -import 'package:loreseer/state/providers.dart'; - -void main() { - setUp(() => SharedPreferences.setMockInitialValues({})); - - test('add and adjust clamps within [0, max]', () async { - final c = ProviderContainer(); - addTearDown(c.dispose); - await c.read(tracksProvider.future); - await c.read(tracksProvider.notifier).add('Find the heir'); - final id = c.read(tracksProvider).value!.single.id; - await c.read(tracksProvider.notifier).adjust(id, 3); - expect(c.read(tracksProvider).value!.single.filled, 3); - await c.read(tracksProvider.notifier).adjust(id, -10); - expect(c.read(tracksProvider).value!.single.filled, 0); - await c.read(tracksProvider.notifier).adjust(id, 999); - expect(c.read(tracksProvider).value!.single.filled, 10); - }); -} From 1fdf9a699c517e33efd2037cc9fb4baf37c4afc9 Mon Sep 17 00:00:00 2001 From: John Taylor Date: Sat, 22 Aug 2026 09:34:58 -0400 Subject: [PATCH 15/15] fix(track): restore clock-fill journal closure + legacy-import test + heading case - Progress clock + button on ThreadsPane now logs "Clock filled: " and shows a matching SnackBar the first time a tap crosses into max, porting the fill closure the retired standalone TracksPane had. A further tap while already at max does not requalify. - Add a campaign_io test proving legacy loreseer.rumors.v1/tracks.v1 keys parse without throwing and are dropped from the import. - Sentence-case the New thread / Edit thread dialog headings. --- lib/features/tracker_screen.dart | 38 +++++++++++++++++++++++++++---- test/campaign_io_test.dart | 22 ++++++++++++++++++ test/threads_pane_stage_test.dart | 22 ++++++++++++++++++ 3 files changed, 77 insertions(+), 5 deletions(-) diff --git a/lib/features/tracker_screen.dart b/lib/features/tracker_screen.dart index e2b34b7..ca2a4b7 100644 --- a/lib/features/tracker_screen.dart +++ b/lib/features/tracker_screen.dart @@ -249,9 +249,8 @@ class _ThreadsPaneState extends ConsumerState<ThreadsPane> { minWidth: 32, minHeight: 32), icon: const Icon(Icons.add, size: 18), tooltip: 'More progress', - onPressed: () => ref - .read(threadsProvider.notifier) - .setProgress(t.id, t.progress + 1), + onPressed: () => + _incrementProgress(context, ref, t), ), const SizedBox(width: 4), Text('${t.progress}/${t.progressMax}', @@ -355,6 +354,35 @@ class _ThreadsPaneState extends ConsumerState<ThreadsPane> { ); } + /// Ticks a thread's progress clock up one; when that crossing completes it + /// (reaches progressMax), logs a journal entry so the fill isn't a silent + /// dead dial — the fill→fire→journal closure ported from the retired + /// standalone Tracks pane. Fires exactly once, on the crossing: a further + /// tap while already at max does not requalify (guarded by [before]). + Future<void> _incrementProgress( + BuildContext context, WidgetRef ref, Thread t) async { + final before = t.progress; + final notifier = ref.read(threadsProvider.notifier); + await notifier.setProgress(t.id, t.progress + 1); + if (before >= t.progressMax) return; + final updated = (await ref.read(threadsProvider.future)) + .where((th) => th.id == t.id) + .firstOrNull; + if (updated == null || + updated.progressMax <= 0 || + updated.progress < updated.progressMax) { + return; + } + await ref.read(journalProvider.notifier).add( + 'Clock filled: ${updated.title}', + '${updated.title} reached ${updated.progressMax}/${updated.progressMax}.', + ); + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Clock filled: ${updated.title}'))); + } + } + /// Ported from the retired Tasks subtab: name → tally-preset picker → /// a thread carrying that tally (a "task"). Future<void> _newTask(BuildContext context, WidgetRef ref) async { @@ -455,10 +483,10 @@ class _ThreadsPaneState extends ConsumerState<ThreadsPane> { context: context, builder: (_) => _EditDialog( heading: existing != null - ? 'Edit Thread' + ? 'Edit thread' : stage == ThreadStage.rumor ? 'New rumor' - : 'New Thread', + : 'New thread', labelA: 'Title', labelB: 'Note (optional)', initialA: existing?.title ?? '', diff --git a/test/campaign_io_test.dart b/test/campaign_io_test.dart index d433b90..7288227 100644 --- a/test/campaign_io_test.dart +++ b/test/campaign_io_test.dart @@ -185,6 +185,28 @@ void main() { expect(parsed.rawByKey, contains('loreseer.threads.v1')); }); + test('legacy rumors/tracks keys are dropped on import', () { + // Pre-merge files may carry the retired standalone Rumor/Track stores + // (superseded by the unified Thread) — they must parse without + // throwing and simply not survive into rawByKey. + final legacy = jsonEncode({ + 'app': 'loreseer', + 'schemaVersion': 3, + 'name': 'Old campaign', + 'data': { + 'loreseer.rumors.v1': [ + {'id': 'r1', 'title': 'A whisper'}, + ], + 'loreseer.tracks.v1': [ + {'id': 'tr1', 'name': 'Doom clock', 'filled': 2, 'max': 6}, + ], + }, + }); + final parsed = parseCampaign(legacy); + expect(parsed.rawByKey.containsKey('loreseer.rumors.v1'), isFalse); + expect(parsed.rawByKey.containsKey('loreseer.tracks.v1'), isFalse); + }); + test('character sheets round-trip through campaign files', () { const sheet = '[{"id":"c1","name":"Ash","note":"ranger",' '"stats":[{"label":"Iron","value":"+2"}],' diff --git a/test/threads_pane_stage_test.dart b/test/threads_pane_stage_test.dart index 0eebb0c..09db262 100644 --- a/test/threads_pane_stage_test.dart +++ b/test/threads_pane_stage_test.dart @@ -76,4 +76,26 @@ void main() { expect(threads.single.stage, ThreadStage.rumor); expect(threads.single.title, 'Heard in the tavern'); }); + + testWidgets('progress clock fill logs a journal entry once', (tester) async { + seed([ + Thread(id: 't1', title: 'Siege clock', progress: 2, progressMax: 3), + ]); + await pump(tester); + + final container = + ProviderScope.containerOf(tester.element(find.byType(ThreadsPane))); + + await tester.tap(find.byKey(const Key('thread-prog-inc-t1'))); + await tester.pumpAndSettle(); + + var journal = await container.read(journalProvider.future); + expect(journal.where((e) => e.title.contains('Clock filled')).length, 1); + + // A further tap at max must not duplicate the closure. + await tester.tap(find.byKey(const Key('thread-prog-inc-t1'))); + await tester.pumpAndSettle(); + journal = await container.read(journalProvider.future); + expect(journal.where((e) => e.title.contains('Clock filled')).length, 1); + }); }