From 27b324990e1034c37f7b7188833d5bd68bd98f24 Mon Sep 17 00:00:00 2001 From: ehonis Date: Wed, 25 Nov 2026 09:59:29 -0500 Subject: [PATCH] Sub-habits, and the web's Productivity tabs drawn like the iPhone app Published from the private repository by oss-sync. - Sub-habits, and the web's Productivity tabs drawn like the iPhone app 61 files changed, 5944 insertions(+), 1707 deletions(-) --- AGENTS.md | 4 +- bridge.mjs | 203 ++- habits/groups-bridge.test.mjs | 243 ++++ mobile/AGENTS.md | 8 + mobile/src/features/habits/Check.tsx | 73 +- mobile/src/features/habits/CheckinSheet.tsx | 1 + mobile/src/features/habits/HabitFormSheet.tsx | 237 ++-- mobile/src/features/habits/HabitRow.tsx | 113 +- mobile/src/features/habits/logic.test.mjs | 65 +- mobile/src/features/habits/logic.ts | 37 + mobile/src/features/habits/store.ts | 16 +- mobile/src/features/overview/HabitRow.tsx | 82 +- .../src/features/overview/OverviewScreen.tsx | 93 +- .../src/features/productivity/HabitsView.tsx | 142 ++- .../src/features/productivity/glance.test.mjs | 24 + mobile/src/features/productivity/glance.ts | 16 +- mobile/src/lib/habitCheckin.ts | 15 +- mobile/src/lib/habits/groups.test.mjs | 142 +++ mobile/src/lib/habits/groups.ts | 235 ++++ package.json | 2 +- web/src/calendar/agenda.test.ts | 38 + web/src/calendar/agenda.ts | 136 +++ web/src/calendar/calendar.css | 104 ++ web/src/components/CalendarView.tsx | 216 ++-- web/src/components/GoalsView.tsx | 293 ++--- web/src/components/HabitCheckin.tsx | 1 + web/src/components/HabitsView.tsx | 1085 ++++++++++++----- web/src/components/JournalView.tsx | 90 +- web/src/components/ListsView.tsx | 556 +++++++-- web/src/components/OverviewView.tsx | 93 +- web/src/components/ProductivityView.tsx | 1 + web/src/components/RecsView.tsx | 460 +++++-- web/src/components/TodosView.tsx | 24 +- web/src/components/overview/overview.css | 7 + web/src/goals/GoalCard.done.test.tsx | 2 +- web/src/goals/GoalCard.tsx | 40 +- web/src/goals/GoalsOverview.tsx | 40 +- web/src/goals/PeriodHero.tsx | 98 ++ web/src/goals/goals.css | 544 +++++++++ web/src/goals/summary.test.ts | 28 + web/src/goals/summary.ts | 31 + web/src/habitCheckin.test.ts | 18 + web/src/habitCheckin.ts | 15 +- web/src/habits/HabitsView.groups.test.tsx | 69 ++ web/src/habits/groups.ts | 235 ++++ web/src/habits/habits.css | 185 +++ web/src/journal/journal.css | 108 ++ web/src/lists/items.test.ts | 38 + web/src/lists/items.ts | 48 + web/src/lists/lists.css | 183 +++ web/src/productivity/Ring.tsx | 37 + web/src/productivity/kit.css | 161 +++ web/src/recs/card.test.ts | 44 + web/src/recs/card.ts | 52 + web/src/recs/recs.css | 143 +++ web/src/styles.css | 548 +-------- web/src/todos/Menu.tsx | 1 + web/src/todos/TodosView.test.tsx | 6 +- web/src/todos/menu.css | 31 + web/src/todos/todos.css | 89 +- web/vitest.config.ts | 2 +- 61 files changed, 5944 insertions(+), 1707 deletions(-) create mode 100644 habits/groups-bridge.test.mjs create mode 100644 mobile/src/lib/habits/groups.test.mjs create mode 100644 mobile/src/lib/habits/groups.ts create mode 100644 web/src/calendar/agenda.test.ts create mode 100644 web/src/calendar/agenda.ts create mode 100644 web/src/calendar/calendar.css create mode 100644 web/src/goals/PeriodHero.tsx create mode 100644 web/src/goals/goals.css create mode 100644 web/src/goals/summary.test.ts create mode 100644 web/src/goals/summary.ts create mode 100644 web/src/habits/HabitsView.groups.test.tsx create mode 100644 web/src/habits/groups.ts create mode 100644 web/src/habits/habits.css create mode 100644 web/src/journal/journal.css create mode 100644 web/src/lists/items.test.ts create mode 100644 web/src/lists/items.ts create mode 100644 web/src/lists/lists.css create mode 100644 web/src/productivity/Ring.tsx create mode 100644 web/src/productivity/kit.css create mode 100644 web/src/recs/card.test.ts create mode 100644 web/src/recs/card.ts create mode 100644 web/src/recs/recs.css create mode 100644 web/src/todos/menu.css diff --git a/AGENTS.md b/AGENTS.md index 3338e0b..3e173e0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -72,7 +72,7 @@ open-ended work. The default provider and model come from Settings → Providers | Tasks page (web) | `web/src/components/TodosView.tsx`, `web/src/todos/{useTaskBoard.ts,TaskRow,TaskPane,QuickAdd,TaskMenus,Menu}.tsx`, `web/src/todos/todos.css` | One grouped list (`buildList`: Overdue, Today, Upcoming, No date; Snoozed and Completed folded; or Group by folder, `web/src/todos/byFolder.ts`) with the task sheet's rows mixed in, beside a detail pane; no status board, no modals. Chips: All, Personal, one per chat project in use (a second row for its folders), the sheet; a row names its folder; the pane has a Folder picker and the task's chats. A change here, in the chats panel or by a chat's agent reaches the other view at once (`web/src/todos/bus.ts`: writes are wrapped in `announcing`, readers listen with `onTasksChanged`); a new writer of tasks on the web must announce too. One-click complete (`x`/Space) with a beat and Undo; snooze, not doing and delete with Undo (the toast deck); an inline quick-add line (`parseQuickAdd`, chips) that creates through `POST /api/todos/board` and reveals the row; pane fields save as they change (put back on refusal), keyed by task id; a sheet row opens read-only. The list is one roving tab stop with j/k, x, s, d, p, m (note), n (new task), Enter, Esc, `/`; the cursor keeps its place when its row leaves, menus are portalled and give focus back, and page keys stand down under a dialog. Archive and bin counts come from the board's `counts`; they are fetched only when opened in the pane. "Done today" adds `GET /api/todos/completed?days=1` (which carries each task's `outcome`; not doing never counts) so the archive hour does not reset it. Below 1100 px the pane overlays; at phone width it fills the screen and marks drop under the title. Retention is in Settings → Tasks (web and app). `docs/tasks.md`. | | Goals | `goals/` | Weekly/monthly/yearly goals with metrics and one level of steps, in the task database. `docs/goals.md`. | | Search | `search/`, the "Search" block in `bridge.mjs`, `web/src/components/SearchView.tsx` | Keyword search (in-memory SQLite FTS5, no model) over notes, journal, chats, tasks, goals, lists and project/totem memory, rebuilt lazily when 30 s stale. The Search tab's "Add to chat" saves a result as a text upload and drops it into the composer (`web/src/chat/pendingContext.ts`). Opening a result lands on the match: the page it opens scrolls to the message, row, card, list item, heading or section and flashes it for a second (a still outline with less motion); `web/src/landing.ts` (`requestLanding`/`useLandOn`, rows marked `data-land`), the app's `mobile/src/lib/landing.ts` and `mobile/src/ui/landing.tsx`; in memory, never in the URL; a list hit's matched item comes from the index (`parts`, `matchPart`). Settings search shares the flash. Agents get `totem_search_everything`/`totem_search_read` (`search__*` in the gateway). `docs/search.md` → Landing on the match. | -| Habits | the "Habit tracker" block in `bridge.mjs`, `web/src/components/HabitsView.tsx`, `web/src/habitCheckin.ts` | One JSON file (`data/habits.json`), daily/weekly/monthly. A habit has `when` (`any`, `morning`, or `night`, which is logged the next morning against the day before) and may be `linkedApp` (`krakatoa`/`bushido`): that app posts to `/api/habits/log` itself, so the dashboard shows an "Open …" link (`KRAKATOA_URL`, `BUSHIDO_URL`) instead of a check mark. The morning check-in (`components/HabitCheckin.tsx`, the app's `CheckinSheet`) opens on the first open of the day after 4am, once across devices (`checkin.lastShown`); on the web, focus or the first click of a new morning counts as an open, since a desktop window may never turn hidden (never a timer: an unattended screen would use up the one pop-up). It asks about every hand-answered habit for yesterday (night ones included) and morning ones for today; a weekly or monthly habit until its quota for the period is met (`stillOwed`, not counting the day being answered), with its progress beside it ("2/4 this week"). The web Overview's habits card has a "Check in · N to answer" row while anything is unanswered. A "No" is stored as `skipped: true`. | +| Habits | the "Habit tracker" block in `bridge.mjs`, `web/src/components/HabitsView.tsx`, `web/src/habitCheckin.ts` | One JSON file (`data/habits.json`), daily/weekly/monthly. A habit has `when` (`any`, `morning`, or `night`, which is logged the next morning against the day before) and may be `linkedApp` (`krakatoa`/`bushido`): that app posts to `/api/habits/log` itself, so the dashboard shows an "Open …" link (`KRAKATOA_URL`, `BUSHIDO_URL`) instead of a check mark. The morning check-in (`components/HabitCheckin.tsx`, the app's `CheckinSheet`) opens on the first open of the day after 4am, once across devices (`checkin.lastShown`); on the web, focus or the first click of a new morning counts as an open, since a desktop window may never turn hidden (never a timer: an unattended screen would use up the one pop-up). It asks about every hand-answered habit for yesterday (night ones included) and morning ones for today; a weekly or monthly habit until its quota for the period is met (`stillOwed`, not counting the day being answered), with its progress beside it ("2/4 this week"). The web Overview's habits card has a "Check in · N to answer" row while anything is unanswered. A "No" is stored as `skipped: true`. Sub-habits: a habit may sit under one other habit (`parentId`, one level deep, like chat folders; `normalizeHabitParents`/`checkHabitParent` in `bridge.mjs`); a habit with active sub-habits is a group with no entry of its own, done for a day when every sub-habit is, and logging it (`complete` true/false, or exact `counts` for undo) marks or clears its hand-logged sub-habits. An app- or WHOOP-filled habit is never a group; the payload marks each one `autoFilled` (the WHOOP fallback id `WHOOP_SLEEP_HABIT_ID` included, which only the bridge knows) and the clients' group check skips them. Habit ids are read in file order as they always were (slug, `-2` on a clash), except an id the bridge itself saved (`idFixed: true`, set on every habit it writes), which is kept as written: re-slugging cuts at 40 characters, so a `-2` would otherwise come back after a reorder as the habit before it, entries and all. A record without the mark (an older file, a habit an agent added) reads as before until the bridge next saves it. The clients read groups through one shared file, `web/src/habits/groups.ts` (byte for byte at `mobile/src/lib/habits/groups.ts`): `foldGroups` turns each group into a daily habit whose target is its sub-habit count with made-up day entries, so streaks, strips, grids and progress need no group code; rows come from `habitTree`, and the check-in asks sub-habits, never the group (`item.group` names it). Productivity → Habits on the web is drawn as the iPhone app draws it (`web/src/habits/habits.css`, the shared `web/src/productivity/kit.css`): a Today card, one card per habit, a group's sub-habits inside its card. `habits/groups-bridge.test.mjs`. | | Lists | `lists/` | Simple checklists with optional links to tasks. | | Recommendations | `recs/`, `web/src/components/RecsView.tsx`, `mobile/src/features/productivity/RecsView.tsx` | A ledger of what agents recommend: evidence, cost, source, the owner's decision (pending, accepted, declined, deferred) and the measured outcome, in the task database (migration 010). Agents get `recs__record` (refused for something declined in the last 30 days unless `changed` says what changed, and for a duplicate of an open one), `recs__list` (the declined-similar lookup: `similarTo` + `declinedWithinDays`) and `recs__set_outcome` (labelled agent-reported; never over the owner's). No agent tool can decide: only `recs/http.mjs` sets `via: 'dashboard'` (`OWNER_VIA`), though holders of `BRIDGE_SECRET` reach it too, so the audit logs them as the owner with the auth method in `detail.auth`. The gateway's and `/mcp`'s instructions carry the rule (`recPromptRule`). A deferral is `deferDays`, resolved in the bridge's time zone, and returns to pending on that day on the job tick (`resurfaceDeferredRecs`, one `rec.review` notification each). Productivity → Recs loads every open rec plus pages of decided history (`/api/recs/ledger`) under a hit-rate line; the app's notification routes (`destination.ts`, `nav.ts`) list `recs` too. `docs/recs.md`. | | Away spans | `away/`, `web/src/away.ts`, `web/src/components/AwayEditor.tsx`, `mobile/src/features/overview/AwaySheet.tsx` | Trips and days off in `data/away.json` (`AWAY_FILE`): inclusive local day keys, edited by the owner from the Overview's schedule card (`/api/away`). Every prompt's date block marks away days in its 14-day table and names the current and coming spans, capped at five, and always says to propose a trip found in email (`away/grounding.mjs`); the calendar draws them as a band; a queued notification whose category's `away` column is `'hold'` waits one night at a time (`heldBy: 'away'`) and goes out the first morning the owner is back, older digest copies dropped and nothing distinct lost (`away/hold.mjs` through `gate.addHold`, `notify/categories.mjs`). Agents get `totem_away_list` and `totem_away_propose` (`away__*` in the gateway): propose stages an `away` inbox item once per set of dates, only the dashboard accepts it, and there is no write tool. Agents never edit `data/away.json`; the store re-reads it when it changes on disk and drops rows that fail validation. `docs/away.md`. | @@ -114,7 +114,7 @@ open-ended work. The default provider and model come from Settings → Providers | Fleet | `fleet/`, `web/src/fleet/`, `mobile/src/features/fleet/` | The owner's machines as a health page: up/down, uptime (reconstructed from boot times across gaps), CPU per core, memory, disks, network, GPU, temperatures, a btop-style process list, watts at the wall (measured by macmon on Apple Silicon, RAPL and nvidia-smi on Linux, estimated otherwise) and what that costs at the ZIP code's state average price (EIA table in `fleet/pricing.mjs`) or a typed ¢/kWh. The bridge reads its own machine; others run `fleet/agent.mjs --install` (systemd user unit) and POST to `/api/fleet/report` with the Fleet token, before the auth gate. Processes are only sent while a machine's page is open. Off until switched on in the tab; `data/fleet.json`, `data/fleet-history.json`. A machine silent for five minutes notifies (`fleet.offline`). `docs/fleet.md`. | | Web terminal | `terminal/` | Optional PTY shell over a WebSocket, off unless `TERMINAL_ENABLED=true`. `docs/terminal.md`. | | Screen | `screen/`, `web/src/screen/` | The machine's desktop in a desktop-only tab: noVNC in the browser, a byte relay at `/api/screen/ws` to the VNC server (macOS Screen Sharing on 127.0.0.1:5900) with the terminal's handshake auth, and the Mac's own login inside VNC, which "Remember for" (30 min to 5 h) seals server-side under `data/screen-credentials.key` so the browser holds only an expiring token (`screen/credentials.mjs`). Agents get `screen__screenshot`/`screen__get_status` (look only; `screencapture` needs Screen Recording for the node binary). Off unless `SCREEN_ENABLED=true`. `docs/screen.md`. | -| Dashboard | `web/` | Vite + React + TypeScript + Tailwind, built to `web/dist`. Paths are real routes (`web/src/router.ts`). The shell (`components/Shell.tsx`, `shell.css`) is an icon rail plus a collapsible chats panel on desktop and a top bar with a swipe-in drawer on a phone (Settings is an icon pinned at the bottom of both: the rail's foot, the drawer's bottom right; on desktop the rail's foot also carries the chat header's AI usage pills, `chat/UsageChips.tsx` with `rail`, on every page but the chat, and under Settings the running version, `..` plus that commit's date, stamped by `web/build-version.mjs` at build time so it goes up by one with every merge and nobody bumps it; a copy without git history shows `.`); every docked side panel (the chats panel, the terminal, and the chat's canvas, Files, Browser and Agents panels) is drag-resizable through one handle, `components/ResizeHandle.tsx`: the width is a CSS variable the panel's own CSS reads as a grid track or flex basis with its minimums there, so the stylesheet holds the limits, a narrower window squeezes panels before the page, and each width is kept per panel in localStorage; phones have no handle (`docs/chat.md` → Side panel widths, checked by `scripts/web-layout.test.mjs`); desktop chats and main surfaces have a subtle border and one 22px top-left curve, on the chats panel or, when it is hidden, on the page (`shell.css`, above 720px), while phone surfaces stay edge to edge; the Overview (`components/OverviewView.tsx`, `components/overview/`) is a single page of today's schedule, tasks, goals and habits. The page, sidebar, rail and raised surfaces take their colours from CSS variables (`--bg`, `--bg-2`, `--rail`, `--surface`, `--raise`, … in `styles.css`), which Settings → Appearance › Background recolours per device from the palettes in `web/src/backgrounds.ts` (default True black; Original is the stylesheet's own values); a new surface should use those variables rather than a hex value, or it keeps the old colour under every palette. Pages in `GLOW_TABS` (`App.tsx`) sit over a slow-drifting colour glow, one pair of colours per page (`glow.css`; the iPhone app's `PageGlow` mirrors it). A chat draws its own glow, coloured per thread (`chat/glow.ts`), that wobbles and brightens while a reply runs; streaming text gives a haptic tick per burst (`chat/ticks.ts`; vibration on Android browsers, real haptics in the app). Toasts are T3 Code's deck (`components/ToastHost.tsx`): a repeated message joins the toast showing it (×N), hovering or tapping spreads the deck and holds every timer, and on a phone they sit under the top bar. Logo assets are generated by `scripts/build-logo-assets.mjs` from three masters in `web/assets-src/`: `totem-logo.svg` (the mark: sidebar, 256px favicon, app icons), `totem-logo-small.svg` (its horizontal edges on the 32px grid: `favicon-32.png` and the Totems rail icon, `components/TotemsIcon.tsx`) and `totem-logo-16.svg` (a 16×16 pixel drawing for `favicon-16.png`); a change to the mark changes all three. The same script writes the iPhone app's icon, splash and brand images (`mobile/assets/`); the desktop app's icons come from `cd desktop && npm run icons`. Edit the masters, not the outputs. | +| Dashboard | `web/` | Vite + React + TypeScript + Tailwind, built to `web/dist`. Paths are real routes (`web/src/router.ts`). The shell (`components/Shell.tsx`, `shell.css`) is an icon rail plus a collapsible chats panel on desktop and a top bar with a swipe-in drawer on a phone (Settings is an icon pinned at the bottom of both: the rail's foot, the drawer's bottom right; on desktop the rail's foot also carries the chat header's AI usage pills, `chat/UsageChips.tsx` with `rail`, on every page but the chat, and under Settings the running version, `..` plus that commit's date, stamped by `web/build-version.mjs` at build time so it goes up by one with every merge and nobody bumps it; a copy without git history shows `.`); every docked side panel (the chats panel, the terminal, and the chat's canvas, Files, Browser and Agents panels) is drag-resizable through one handle, `components/ResizeHandle.tsx`: the width is a CSS variable the panel's own CSS reads as a grid track or flex basis with its minimums there, so the stylesheet holds the limits, a narrower window squeezes panels before the page, and each width is kept per panel in localStorage; phones have no handle (`docs/chat.md` → Side panel widths, checked by `scripts/web-layout.test.mjs`); desktop chats and main surfaces have a subtle border and one 22px top-left curve, on the chats panel or, when it is hidden, on the page (`shell.css`, above 720px), while phone surfaces stay edge to edge; the Overview (`components/OverviewView.tsx`, `components/overview/`) is a single page of today's schedule, tasks, goals and habits. The Productivity tabs are drawn as the iPhone app draws them, wider: `web/src/productivity/kit.css` holds the app's cards, chips, buttons, stat tiles and bars as `.pk-*` classes and `productivity/Ring.tsx` its progress ring; a tab's own look goes in its own CSS file over those, and a change to a tab's look is made in the app too (or the other way round). The page, sidebar, rail and raised surfaces take their colours from CSS variables (`--bg`, `--bg-2`, `--rail`, `--surface`, `--raise`, … in `styles.css`), which Settings → Appearance › Background recolours per device from the palettes in `web/src/backgrounds.ts` (default True black; Original is the stylesheet's own values); a new surface should use those variables rather than a hex value, or it keeps the old colour under every palette. Pages in `GLOW_TABS` (`App.tsx`) sit over a slow-drifting colour glow, one pair of colours per page (`glow.css`; the iPhone app's `PageGlow` mirrors it). A chat draws its own glow, coloured per thread (`chat/glow.ts`), that wobbles and brightens while a reply runs; streaming text gives a haptic tick per burst (`chat/ticks.ts`; vibration on Android browsers, real haptics in the app). Toasts are T3 Code's deck (`components/ToastHost.tsx`): a repeated message joins the toast showing it (×N), hovering or tapping spreads the deck and holds every timer, and on a phone they sit under the top bar. Logo assets are generated by `scripts/build-logo-assets.mjs` from three masters in `web/assets-src/`: `totem-logo.svg` (the mark: sidebar, 256px favicon, app icons), `totem-logo-small.svg` (its horizontal edges on the 32px grid: `favicon-32.png` and the Totems rail icon, `components/TotemsIcon.tsx`) and `totem-logo-16.svg` (a 16×16 pixel drawing for `favicon-16.png`); a change to the mark changes all three. The same script writes the iPhone app's icon, splash and brand images (`mobile/assets/`); the desktop app's icons come from `cd desktop && npm run icons`. Edit the masters, not the outputs. | | GET cache and ETags | `http/etag.mjs`, `mobile/src/lib/httpCache.ts` | Allow-listed JSON read routes (`ETAG_PATHS`: tasks, goals, lists, habits, calendar, the inbox count, notifications, threads (the list, and one chat's window at `/api/threads/`), the chat projects list (not one project, which carries its memory and file list; the list's picture link has no expiry), productivity; not search, the inbox or the journal) get a weak ETag (SHA-1 of the body) and `cache-control: private, no-cache`, and answer `If-None-Match` with a 304; a body of 8 KB or more goes gzipped to a client that takes it (`acceptsGzip`; the chat list is hundreds of KB, polled every 30 s). One call at the `/api/` gate, after sign-in, wraps every module's `send()`; a body streamed with `write()`, a non-200, non-JSON or `no-store` answer passes through untouched. The browser revalidates on its own; the iPhone app keeps every tagged answer on disk per bridge and secret (200 entries, least recently used out first), draws it first, and falls back to it when the bridge is out of reach, except the chat list and the projects list, which never take their stored copy over the store's newer one (`{ stored: false }`; the projects list seeds the drawer's folders from it on a cold start, `mobile/src/lib/chat/projectList.ts`). See Gotchas. | | iPhone app | `mobile/` | Expo / React Native rebuild of the dashboard's phone layout, with native sheets, menus, swipes and push. Its own `package.json`, not a workspace: the bridge's install and build never touch it. Ports `web/src` logic into `mobile/src/lib/` at the same paths, so a change to `web/src/api.ts` or `chat/store.ts` is ported there too. Read `mobile/AGENTS.md` before changing it. | | Desktop app | `desktop/`, `web/src/desktop.ts` | Tauri 2 app for macOS and Windows: one window that loads the owner's Totem server (set on first run, kept in `desktop.json` in the app's config dir), global hotkeys, tray, start at login. Hotkeys call `window.totemDesktop.run(id)`, defined in `web/src/desktop.ts`. Links that leave the server or open a new tab go to the system browser through a `totem-external://` navigation it cancels, except what the dashboard takes first: `installLinkRouting` (`web/src/links.ts`) listens in the window's capture phase, ahead of that shim, and keeps every file, Totem resource and dashboard page in the window (canvas, in-app download, in-window navigation; `window.open` too, but only during the owner's own click, so a chart posting `totem-visual:open` cannot drive the app), so only other sites reach the system browser. That is a dashboard change: the shim already skips a prevented click, so no desktop rebuild. No title bar on the server's pages (`nativeTitleBar` in `desktop.json` brings it back): on Windows the page draws minimize/maximize/close top right (`components/WindowControls.tsx`) and every page leaves them room (`shell.css`), on macOS the traffic lights sit in a 40px title strip in the rail's colour, above the chats panel and the page (gone in full screen, `wc-fullscreen`); drag regions and the window calls are in `installWindowChrome` (`web/src/desktop.ts`), reached over IPC the app grants the server's origin for those window commands only (`grant_window_controls` in `lib.rs`). Any other page (a sign-in in between, an older server that doesn't set `html[data-desktop]`) gets the system title bar back. Cloudflare Access does not sign in inside the window (only the owner's "Sign in in this window instead" lets its page load there, for 10 minutes, `INSIDE_FOR`): `on_navigation` cancels the hop to `.cloudflareaccess.com/cdn-cgi/access/login/`, shows the bundled `setup/signin.html`, opens Access's command-line sign-in in the default browser, collects the app token from Cloudflare's transfer service (NaCl box to a one-time key, as `mobile/src/lib/cfAccess.ts` does) and sets it as the window's `CF_Authorization` cookie (`src-tauri/src/access/`); a second hop within 30 s of a hand-over is reported, never retried in a loop. Updates itself (`src-tauri/src/update.rs`, tauri-plugin-updater): checks the public repo's latest release, downloads in the background, then the rail shows Restart to update (`components/DesktopUpdate.tsx`), told through `window.__TOTEM_DESKTOP__.update` and asked through a cancelled `totem-desktop://update/install` navigation, so still no IPC beyond the window commands. Releases are signed; each CI build is `0.2.`. Its own `package.json`; built for both platforms by `.github/workflows/desktop.yml`, not by `ci.yml`. No Web Push in a webview. `desktop/README.md`. | diff --git a/bridge.mjs b/bridge.mjs index 4f545c4..0cb72f2 100644 --- a/bridge.mjs +++ b/bridge.mjs @@ -637,7 +637,8 @@ const HABIT_RULES = '"createdAt": "", "archived": false, "metric": , ' + '"when": "any"|"morning"|"night" (when he answers it: "night" habits are done late and logged the next ' + 'morning against the day before), "linkedApp": null|"krakatoa"|"bushido" (that app fills the habit in itself: ' + - 'never log, tick or undo a linked habit; say it comes from that app) } ], ' + + 'never log, tick or undo a linked habit; say it comes from that app), "parentId": null|"", ' + + '"idFixed": true (written by the dashboard: keep it, never change an existing habit\'s id, and leave it off a habit you add) } ], ' + '"entries": { "YYYY-MM-DD": { "": { "count": = 1>, ' + '"note": "", "value": , "parts": ": number}>, ' + '"skipped": } } }, ' + @@ -651,6 +652,12 @@ const HABIT_RULES = 'When the owner reports that number ("slept 84 last night", "82 sleep score, 1h10 deep"), write it to that day\'s ' + 'entry as "value" (and "parts" in the metric\'s own unit, e.g. minutes), and set "count": 1 as well — logging ' + 'the number means the habit happened. Never invent a number he did not give. ' + + 'SUB-HABITS: a habit may sit under one other habit ("parentId"), one level deep (a "Nightly routine" holding ' + + '"Sleep hygiene" and "No screens"). A habit with sub-habits is a group: it has no entries of its own and is done ' + + 'for a day when every sub-habit is, so never write an entry for a group; log its sub-habits. "Did my whole ' + + 'nightly routine" means logging each of its sub-habits (or totem_log_habit with the group id and complete: true). ' + + 'A linked or WHOOP-filled habit can never be a group, and a group cannot sit under another habit. ' + + 'A new sub-habit goes in the habits array right after its group\'s last sub-habit. ' + 'Completions are ALWAYS logged under the local calendar date they happened, whatever the cadence; the cadence ' + 'only changes what counts as on-track (weeks run Monday-Sunday, months are calendar months). ' + 'When the owner reports doing (or skipping) habits — especially in a nightly day-in-review — read the file, ' + @@ -1443,7 +1450,7 @@ function sanitizeDataConnectionPatch(id, body = {}) { // One JSON file (HABITS_FILE) is the single source of truth for both the // dashboard (/api/habits*) and the agent (HABIT_RULES has it edit the file // directly), so state never lives in two places. Shape: -// { habits: [{ id, name, description, color, target, createdAt, archived }], +// { habits: [{ id, name, description, color, target, createdAt, archived, parentId }], // entries: { "YYYY-MM-DD": { "": { count, note } } } } // The order of active objects in `habits` is the user's check-in order. // `target` is how many completions make a "full-intensity" day (GitHub-style @@ -1601,6 +1608,70 @@ function nextHabitColor(habits) { return HABIT_COLORS.find((c) => !used.has(c)) || HABIT_COLORS[habits.length % HABIT_COLORS.length] } +// Sub-habits: a habit may sit under one other habit (`parentId`), one level deep, +// like chat folders. A habit with sub-habits is a group: it has no check of its own, +// its day is done when every sub-habit's is (worked out by the clients from the +// children's entries, habits/groups in web/src/habitGroups.ts), and logging it marks +// its hand-logged sub-habits (doLogHabitRecord). An app or WHOOP fills a habit by +// logging its id, so such a habit can never be a group. The file is hand-edited by +// agents, so a parent that is missing, itself, nested, or app-filled is dropped here. +// The habit the WHOOP sleep sync falls back on when none is marked whoop-sleep. +// Up here because the habit helpers below read it. +const WHOOP_SLEEP_HABIT_ID = process.env.WHOOP_SLEEP_HABIT_ID || 'wear-garmin-to-sleep' +function habitFilledElsewhere(h) { + return Boolean(h?.linkedApp) || h?.metric?.source === 'whoop-sleep' || h?.id === WHOOP_SLEEP_HABIT_ID +} +// A habit's completions over the period holding `day`: its week (Monday to +// Sunday, as the clients count) or calendar month; the day itself when daily. +function habitPeriodTotal(entries, habit, day) { + const count = (d) => entries[d]?.[habit.id]?.count || 0 + if (habit.cadence === 'monthly') { + const ym = day.slice(0, 7) + return Object.keys(entries).filter((d) => d.startsWith(ym)).reduce((t, d) => t + count(d), 0) + } + if (habit.cadence === 'weekly') { + const [y, m, d] = day.split('-').map(Number) + const start = new Date(y, m - 1, d - ((new Date(y, m - 1, d).getDay() + 6) % 7)) + let t = 0 + for (let i = 0; i < 7; i++) { + const at = new Date(start.getFullYear(), start.getMonth(), start.getDate() + i) + t += count(`${at.getFullYear()}-${String(at.getMonth() + 1).padStart(2, '0')}-${String(at.getDate()).padStart(2, '0')}`) + } + return t + } + return count(day) +} +function normalizeHabitParents(habits, storedIds = new Map()) { + const byId = new Map(habits.map((h) => [h.id, h])) + for (const h of habits) { + if (h.parentId) h.parentId = storedIds.get(h.parentId) ?? (byId.has(h.parentId) ? h.parentId : habitSlug(h.parentId)) + const p = h.parentId ? byId.get(h.parentId) : null + if (!p || p === h || habitFilledElsewhere(p)) h.parentId = null + } + // One level: a parent that has a parent of its own keeps its place, its children + // come out to the top. Only ever clears, so an edge kept here stays valid. + for (const h of habits) { + if (h.parentId && byId.get(h.parentId).parentId) h.parentId = null + } +} +// The habits sitting under `id` that still count (archived ones are history only). +function habitChildren(habits, id) { + return habits.filter((h) => h.parentId === id && !h.archived) +} +// Refuses a parent the rules above would drop, before anything is written. +function checkHabitParent(habits, habit, rawParent) { + if (rawParent === null || rawParent === undefined || rawParent === '') return null + if (typeof rawParent !== 'string') throw new Error('parentId must be a habit id or null') + const parent = habits.find((h) => h.id === rawParent) + if (!parent) throw new Error('unknown parent habit') + if (habit && parent.id === habit.id) throw new Error('a habit cannot sit under itself') + if (parent.archived) throw new Error(`"${parent.name}" is archived`) + if (parent.parentId) throw new Error(`"${parent.name}" is itself a sub-habit; sub-habits go one level deep`) + if (habitFilledElsewhere(parent)) throw new Error(`"${parent.name}" is filled in by an app, so it cannot hold sub-habits`) + if (habit && habits.some((h) => h.parentId === habit.id)) throw new Error(`"${habit.name}" has sub-habits of its own, so it cannot go under another habit`) + return parent.id +} + // Read + normalize. Tolerates a missing file, and (since the agent hand-edits // this JSON) coerces every field to a sane value instead of trusting it. async function readHabitsState() { @@ -1608,12 +1679,22 @@ async function readHabitsState() { try { raw = JSON.parse(await readFile(HABITS_FILE, 'utf8')) } catch {} const habits = [] const seen = new Set() - for (const h of Array.isArray(raw.habits) ? raw.habits : []) { - const name = typeof h?.name === 'string' ? h.name.trim() : '' - if (!name) continue - let id = typeof h?.id === 'string' && h.id.trim() ? habitSlug(h.id) : habitSlug(name) + // Each habit's id as written in the file → the id it reads as, for parentId. + const storedIds = new Map() + // Ids are read in file order exactly as they always were (slug, then "-2" on a + // clash), except an id the bridge itself wrote (`idFixed`, set on every habit it + // saves), which is kept as written. Re-slugging cuts at 40 characters, so a + // "-2" would otherwise come back after a reorder as the habit before it, + // entries and all. A record without the mark (a file from before it, a habit an + // agent added by hand) reads as it always did until the bridge next saves it. + const rawHabits = (Array.isArray(raw.habits) ? raw.habits : []).filter((h) => typeof h?.name === 'string' && h.name.trim()) + for (const h of rawHabits) { + const name = h.name.trim() + const fixed = h.idFixed === true && typeof h.id === 'string' && /^[a-z0-9-]{1,64}$/.test(h.id) + let id = fixed ? h.id : habitSlug(typeof h?.id === 'string' && h.id.trim() ? h.id : name) while (seen.has(id)) id = `${id}-2` seen.add(id) + if (typeof h?.id === 'string' && h.id.trim() && !storedIds.has(h.id.trim())) storedIds.set(h.id.trim(), id) const target = Math.min(Math.max(Math.round(Number(h?.target)) || 1, 1), 50) habits.push({ id, @@ -1625,11 +1706,15 @@ async function readHabitsState() { metric: normalizeHabitMetric(h?.metric), when: HABIT_WHEN.includes(h?.when) ? h.when : 'any', linkedApp: HABIT_APPS.includes(h?.linkedApp) ? h.linkedApp : null, + // Resolved against the final ids below (normalizeHabitParents), never slugged here: + // a slug cuts at 40 characters, so "…-2" would point at the habit without it. + parentId: typeof h?.parentId === 'string' && h.parentId.trim() ? h.parentId.trim() : null, createdAt: typeof h?.createdAt === 'string' ? h.createdAt : new Date().toISOString(), archived: h?.archived === true, }) } for (const h of habits) if (!h.color) h.color = nextHabitColor(habits.filter((x) => x.color)) + normalizeHabitParents(habits, storedIds) const entries = {} if (raw.entries && typeof raw.entries === 'object') { for (const [date, day] of Object.entries(raw.entries)) { @@ -1666,7 +1751,8 @@ async function readHabitsState() { async function writeHabitsState(state) { await mkdir(dirname(HABITS_FILE), { recursive: true }) await writeJsonAtomic(HABITS_FILE, { - habits: state.habits, + // Every id written here is one the bridge settled on; readHabitsState keeps it as is. + habits: state.habits.map((h) => ({ ...h, idFixed: true })), entries: state.entries, checkin: state.checkin || { lastShown: null }, updatedAt: new Date().toISOString(), @@ -1709,7 +1795,15 @@ async function buildHabitsPayload({ days = 371 } = {}) { } const apps = habitAppUrls() // A linked habit carries its app's address, so any view can link to it. - const shown = habits.map((h) => (h.linkedApp ? { ...h, appUrl: apps[h.linkedApp] || null } : h)) + // A sub-habit of an archived group shows at the top level until the group returns. + const archivedIds = new Set(habits.filter((h) => h.archived).map((h) => h.id)) + const shown = habits.map((h) => { + let out = h.parentId && archivedIds.has(h.parentId) ? { ...h, parentId: null } : h + // Filled by an app or the WHOOP sync (the fallback id included, which only the + // bridge knows): a group's check skips it, and the clients read that from here. + if (habitFilledElsewhere(out)) out = { ...out, autoFilled: true } + return out.linkedApp ? { ...out, appUrl: apps[out.linkedApp] || null } : out + }) // No clock and no file path in it: the same habits answer the same body, so // the app's GET cache gets a 304 (http/etag.mjs). return { today, habits: shown, entries: visibleEntries, palette: HABIT_COLORS, apps, checkin } @@ -1728,6 +1822,7 @@ async function doCreateHabitRecord(body = {}) { if (body.cadence !== undefined && !HABIT_CADENCES.includes(body.cadence)) { throw new Error('cadence must be daily, weekly, or monthly') } + const parentId = checkHabitParent(state.habits, null, body.parentId) state.habits.push({ id, name: name.slice(0, 80), @@ -1738,9 +1833,17 @@ async function doCreateHabitRecord(body = {}) { metric: normalizeHabitMetric(body.metric), when: HABIT_WHEN.includes(body.when) ? body.when : 'any', linkedApp: HABIT_APPS.includes(body.linkedApp) ? body.linkedApp : null, + parentId, createdAt: new Date().toISOString(), archived: false, }) + // A new sub-habit goes right after its group's last one, so the group stays together. + if (parentId) { + const made = state.habits.pop() + let at = state.habits.findIndex((h) => h.id === parentId) + state.habits.forEach((h, i) => { if (h.parentId === parentId) at = Math.max(at, i) }) + state.habits.splice(at + 1, 0, made) + } await writeHabitsState(state) recordActivity('habit.create', { label: name }) return buildHabitsPayload() @@ -1777,6 +1880,10 @@ async function doUpdateHabitRecord(id, fields = {}) { habit.linkedApp = fields.linkedApp } if (fields.archived !== undefined) habit.archived = fields.archived === true + if (fields.parentId !== undefined) habit.parentId = checkHabitParent(state.habits, habit, fields.parentId) + if (habitFilledElsewhere(habit) && habitChildren(state.habits, habit.id).length) { + throw new Error(`"${habit.name}" has sub-habits, so an app cannot fill it in`) + } await writeHabitsState(state) return buildHabitsPayload() } @@ -1814,6 +1921,8 @@ async function doDeleteHabitRecord(id) { const state = await readHabitsState() if (!state.habits.some((h) => h.id === id)) throw new Error('unknown habit') state.habits = state.habits.filter((h) => h.id !== id) + // Its sub-habits keep their history and move to the top level. + for (const h of state.habits) if (h.parentId === id) h.parentId = null for (const [date, day] of Object.entries(state.entries)) { delete day[id] if (!Object.keys(day).length) delete state.entries[date] @@ -1830,14 +1939,74 @@ async function doDeleteHabitRecord(id) { // scraper and a nightly check-in write through exactly the same path. // `complete: true` ticks the habit off when a number arrives without a count — // the number is itself the evidence the habit happened. -async function doLogHabitRecord({ id, date, count, delta, note, value, parts, stats, window, complete, source, skipped } = {}) { +// +// A group (a habit with sub-habits) has no entry of its own. `complete: true` marks +// each of its hand-logged sub-habits done (its target for a daily one, at least one +// for a weekly or monthly one), `complete: false` clears them, and `counts` +// ({ "": n }) sets them exactly, which is how a client undoes either. +// App-filled sub-habits are never touched. One read, one write, one queue slot. +async function doLogHabitRecord(args = {}) { const state = await readHabitsState() - const habit = state.habits.find((h) => h.id === id) + const habit = state.habits.find((h) => h.id === args.id) if (!habit) throw new Error('unknown habit') + const day = habitLogDay(args.date) + const children = habitChildren(state.habits, habit.id) + let logged = false + if (children.length) { + // An app or WHOOP fills its own sub-habits; a group's check never writes them. + const handLogged = children.filter((c) => !habitFilledElsewhere(c)) + // A group has no number, note or count of its own; a metric posted to one (an app + // or the sleep sync pointed at it) is refused rather than dropped on the floor. + const own = ['count', 'delta', 'note', 'value', 'parts', 'stats', 'window', 'source', 'skipped'].filter((k) => args[k] !== undefined) + if (own.length) throw new Error(`"${habit.name}" is a group, so it takes no ${own.join(', ')}: log one of its sub-habits`) + const child = (childId) => { + const found = handLogged.find((c) => c.id === childId) + if (!found) throw new Error(`"${childId}" is not a hand-logged sub-habit of "${habit.name}"`) + return found + } + if (args.counts !== undefined) { + if (!args.counts || typeof args.counts !== 'object' || Array.isArray(args.counts)) throw new Error('counts must be an object of sub-habit ids to counts') + // `skips` lists the sub-habits whose day was a check-in "No", so an undo puts that back too. + if (args.skips !== undefined && !Array.isArray(args.skips)) throw new Error('skips must be an array of sub-habit ids') + const skips = new Set((args.skips || []).map((id) => child(String(id)).id)) + for (const [childId, n] of Object.entries(args.counts)) { + const c = child(childId) + const no = skips.has(c.id) && !(Number(n) > 0) + logged = applyHabitLog(state, c, day, no ? { count: 0, skipped: true } : { count: n, skipped: false }) || logged + } + } else if (args.complete === true || args.complete === false) { + for (const child of handLogged) { + const have = state.entries[day]?.[child.id]?.count || 0 + // A weekly or monthly sub-habit whose quota is already met stays as it is: + // marking the group done must not add to its tally. + const met = child.cadence !== 'daily' && habitPeriodTotal(state.entries, child, day) >= child.target + const full = child.cadence === 'daily' ? child.target : met ? have : 1 + const count = args.complete ? Math.max(have, full) : 0 + if (count !== have || (args.complete && state.entries[day]?.[child.id]?.skipped)) logged = applyHabitLog(state, child, day, { count }) || logged + } + } else { + throw new Error(`"${habit.name}" is a group: log one of its sub-habits, or pass complete true or false`) + } + } else { + logged = applyHabitLog(state, habit, day, args) + } + await writeHabitsState(state) + // Count only real completions (a bumped-up count), never undos or note-only edits. + if (logged) recordActivity('habit.log', { label: habit.name }) + return buildHabitsPayload() +} + +// The day a log is for: today when not given; never a future day. +function habitLogDay(date) { const today = localISODate() const day = date === undefined || date === null || date === '' ? today : String(date) if (!HABIT_DATE_RE.test(day)) throw new Error('date must be YYYY-MM-DD') if (day > today) throw new Error('cannot log a habit for a future date') + return day +} + +// One habit-day's change, applied to `state` in memory. True when the count went up. +function applyHabitLog(state, habit, day, { count, delta, note, value, parts, stats, window, complete, source, skipped } = {}) { const existing = state.entries[day]?.[habit.id] || { count: 0 } let nextCount = existing.count if (count !== undefined) nextCount = Math.round(Number(count)) @@ -1923,10 +2092,7 @@ async function doLogHabitRecord({ id, date, count, delta, note, value, parts, st delete state.entries[day][habit.id] if (!Object.keys(state.entries[day]).length) delete state.entries[day] } - await writeHabitsState(state) - // Count only real completions (a bumped-up count), never undos or note-only edits. - if (nextCount > existing.count) recordActivity('habit.log', { label: habit.name }) - return buildHabitsPayload() + return nextCount > existing.count } // --------------------------------------------------------------------------- @@ -1965,7 +2131,6 @@ const whoop = createRemoteWhoopClient({ publicUrl: BUSHIDO_URL, runs: sourceRuns, }) -const WHOOP_SLEEP_HABIT_ID = process.env.WHOOP_SLEEP_HABIT_ID || 'wear-garmin-to-sleep' // WHOOP timestamps a sleep with the moment it started, so the local date of // `start` is already "the night of". 'wake' files it under the morning instead. const WHOOP_SLEEP_DATE_MODE = process.env.WHOOP_SLEEP_DATE_MODE === 'wake' ? 'wake' : 'night' @@ -13012,7 +13177,9 @@ const MCP_TOOLS = [ description: 'Log a habit for a day. Get habit ids from totem_get_habits. Pass count to set an absolute value or ' + 'delta to add to what is already there — delta is what you want for "I did one more". Defaults to ' - + 'today; future dates are rejected.', + + 'today; future dates are rejected. A habit with sub-habits (others whose parentId is its id) is a group ' + + 'with no count of its own: pass complete true to mark all its hand-logged sub-habits done, false to clear ' + + 'them, or log a sub-habit by its own id.', inputSchema: { type: 'object', properties: { @@ -13020,7 +13187,9 @@ const MCP_TOOLS = [ date: { type: 'string', description: 'YYYY-MM-DD. Defaults to today. Cannot be in the future.' }, count: { type: 'number', description: 'Set the count for that day to this absolute value.' }, delta: { type: 'number', description: 'Add this to the existing count. Use a negative number to undo.' }, - complete: { type: 'boolean', description: 'Mark the habit done for the day, whatever its target is.' }, + complete: { type: 'boolean', description: 'Mark the habit done for the day, whatever its target is. On a group: true marks every hand-logged sub-habit done, false clears them.' }, + counts: { type: 'object', additionalProperties: { type: 'number' }, description: 'Groups only: set these sub-habits\' counts exactly, { "": n }.' }, + skips: { type: 'array', items: { type: 'string' }, description: 'Groups only, with counts: sub-habits whose day is a check-in "No" (count 0, answered).' }, note: { type: 'string', description: 'A short note on the day\'s entry.' }, value: { type: 'number', description: 'Numeric value for habits that track an amount rather than a count.' }, }, diff --git a/habits/groups-bridge.test.mjs b/habits/groups-bridge.test.mjs new file mode 100644 index 0000000..ef984cc --- /dev/null +++ b/habits/groups-bridge.test.mjs @@ -0,0 +1,243 @@ +// Run with: node --test habits/groups-bridge.test.mjs +// +// Sub-habits against a real bridge.mjs: a habit may sit under one other habit +// (`parentId`), one level deep; a habit with sub-habits is a group with no entry of +// its own, and logging it marks (or clears, or sets) its hand-logged sub-habits. +// The bridge runs from a shadow checkout with its own data/, on its own port, with +// no scheduler, and is stopped at the end. + +import test, { before, after } from 'node:test' +import assert from 'node:assert/strict' +import { spawn } from 'node:child_process' +import { connect, createServer } from 'node:net' +import { mkdtempSync, mkdirSync, readdirSync, writeFileSync, readFileSync, symlinkSync, rmSync, realpathSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, dirname } from 'node:path' +import { fileURLToPath } from 'node:url' + +const REPO = dirname(dirname(fileURLToPath(import.meta.url))) +const SECRET = 'habit-groups-test-secret' + +const freePort = () => new Promise((resolve) => { + const server = createServer() + server.listen(0, '127.0.0.1', () => { const { port } = server.address(); server.close(() => resolve(port)) }) +}) +const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) +const canConnect = (port) => new Promise((resolve) => { + const socket = connect(port, '127.0.0.1') + socket.once('connect', () => { socket.destroy(); resolve(true) }) + socket.once('error', () => resolve(false)) +}) + +const B = {} +async function call(method, path, body) { + const res = await fetch(`${B.base}${path}`, { + method, + headers: { authorization: `Bearer ${SECRET}`, 'content-type': 'application/json' }, + body: body ? JSON.stringify(body) : undefined, + }) + const json = await res.json().catch(() => ({})) + return { status: res.status, json } +} +const habit = (payload, id) => payload.habits.find((h) => h.id === id) +const onDisk = () => JSON.parse(readFileSync(B.file, 'utf8')) + +before(async () => { + const root = realpathSync(mkdtempSync(join(tmpdir(), 'totem-habit-groups-'))) + for (const entry of readdirSync(REPO)) { + if (entry === 'data' || entry === '.env' || entry === '.git' || entry === 'AGENTS.local.md') continue + symlinkSync(join(REPO, entry), join(root, entry)) + } + B.root = root + mkdirSync(join(root, 'data'), { recursive: true }) + mkdirSync(join(root, 'home')) + writeFileSync(join(root, 'data', 'auth.json'), '{}') + B.file = join(root, 'data', 'habits.json') + // Hand-written the way an agent might: a nested parent, a self-parent, a missing + // one, and a group under an app-filled habit, which the bridge must all drop. + writeFileSync(B.file, JSON.stringify({ + habits: [ + { id: 'food', name: 'Food', linkedApp: 'krakatoa' }, + { id: 'eat-greens', name: 'Eat greens', parentId: 'food' }, + { id: 'a', name: 'A', parentId: 'b' }, + { id: 'b', name: 'B', parentId: 'c' }, + { id: 'c', name: 'C' }, + { id: 'self', name: 'Self', parentId: 'self' }, + { id: 'lost', name: 'Lost', parentId: 'nowhere' }, + // Hand-written, not a slug: it has always read as "read-books", where its history is. + { id: 'read--books', name: 'Read books' }, + // Two hand-written spellings of one slug: the first in the file has always had it. + { id: 'read--fiction', name: 'Read fiction' }, + { id: 'read-fiction', name: 'Read more fiction' }, + // Hand-written past 40 characters, not a bridge "-N": read as its slug. + { id: `${'a'.repeat(40)}-reading`, name: 'Long one' }, + // Hand-written with a number on the end: only an id the bridge saved (idFixed) is kept as written. + { id: `${'r'.repeat(40)}-1`, name: 'Numbered one' }, + ], + entries: { '2026-01-05': { 'read-books': { count: 1 }, 'read-fiction': { count: 1 }, [`${'a'.repeat(40)}`]: { count: 1 }, [`${'r'.repeat(40)}`]: { count: 1 } } }, + })) + + const port = await freePort() + B.base = `http://127.0.0.1:${port}` + let output = '' + const child = spawn(process.execPath, ['--preserve-symlinks', '--preserve-symlinks-main', join(root, 'bridge.mjs')], { + cwd: root, + env: { PATH: process.env.PATH, HOME: join(root, 'home'), BRIDGE_PORT: String(port), BRIDGE_SECRET: SECRET, BRIDGE_NO_SCHEDULER: '1', AGENT_CWD: root }, + stdio: ['ignore', 'pipe', 'pipe'], + }) + child.stdout.on('data', (d) => { output += d }) + child.stderr.on('data', (d) => { output += d }) + B.stop = () => new Promise((resolve) => { + if (child.exitCode !== null) return resolve() + child.once('exit', resolve) + child.kill('SIGTERM') + setTimeout(() => { child.kill('SIGKILL'); resolve() }, 3000) + }) + const deadline = Date.now() + 30_000 + while (!(await canConnect(port))) { + if (child.exitCode !== null) throw new Error(`bridge exited early:\n${output}`) + if (Date.now() > deadline) throw new Error(`bridge never listened:\n${output}`) + await wait(20) + } +}) + +after(async () => { + await B.stop?.() + if (B.root) rmSync(B.root, { recursive: true, force: true }) +}) + +test('a hand-edited file keeps only valid one-level parents', async () => { + const { json } = await call('GET', '/api/habits') + assert.equal(habit(json, 'eat-greens').parentId, null, 'an app-filled habit cannot be a group') + assert.equal(habit(json, 'a').parentId, null, 'a parent that has a parent is not a group') + assert.equal(habit(json, 'b').parentId, 'c') + assert.equal(habit(json, 'self').parentId, null) + assert.equal(habit(json, 'lost').parentId, null) +}) + +test('a hand-written id that is not a slug still reads as its slug, history and all', async () => { + const { json } = await call('GET', '/api/habits?days=1100') + assert.ok(habit(json, 'read-books')) + assert.equal(habit(json, 'read--books'), undefined) + // Ids as the bridge has always read them, so each habit keeps its own entries. + assert.equal(json.habits.find((h) => h.name === 'Read fiction').id, 'read-fiction') + assert.equal(json.habits.find((h) => h.name === 'Read more fiction').id, 'read-fiction-2') + assert.equal(json.habits.find((h) => h.name === 'Long one').id, 'a'.repeat(40)) + assert.equal(json.habits.find((h) => h.name === 'Numbered one').id, 'r'.repeat(40)) +}) + +test('creating and moving sub-habits checks the parent', async () => { + let r = await call('POST', '/api/habits', { name: 'Nightly routine' }) + assert.equal(r.status, 200) + r = await call('POST', '/api/habits', { name: 'Sleep hygiene', parentId: 'nightly-routine' }) + assert.equal(r.status, 200) + r = await call('POST', '/api/habits', { name: 'Water', target: 4 }) + r = await call('POST', '/api/habits', { name: 'Stretch', parentId: 'nightly-routine' }) + // A new sub-habit lands right after its group's last one, not at the end. + const order = r.json.habits.map((h) => h.id) + assert.deepEqual(order.slice(order.indexOf('nightly-routine'), order.indexOf('nightly-routine') + 4), ['nightly-routine', 'sleep-hygiene', 'stretch', 'water']) + + r = await call('PATCH', '/api/habits', { id: 'water', parentId: 'nightly-routine' }) + assert.equal(r.status, 200) + assert.equal(habit(r.json, 'water').parentId, 'nightly-routine') + + assert.match((await call('PATCH', '/api/habits', { id: 'nightly-routine', parentId: 'c' })).json.error, /has sub-habits/) + assert.match((await call('POST', '/api/habits', { name: 'Deep', parentId: 'sleep-hygiene' })).json.error, /one level deep/) + assert.match((await call('POST', '/api/habits', { name: 'Fruit', parentId: 'food' })).json.error, /filled in by an app/) + assert.match((await call('PATCH', '/api/habits', { id: 'stretch', parentId: 'stretch' })).json.error, /under itself/) + assert.match((await call('PATCH', '/api/habits', { id: 'nightly-routine', linkedApp: 'bushido' })).json.error, /has sub-habits/) +}) + +test('logging a group marks, clears and sets its sub-habits; it never gets an entry of its own', async () => { + const day = (await call('GET', '/api/habits')).json.today + await call('POST', '/api/habits/log', { id: 'stretch', date: day, skipped: true }) + let r = await call('POST', '/api/habits/log', { id: 'nightly-routine', date: day, complete: true }) + assert.equal(r.status, 200) + const e = r.json.entries[day] + assert.equal(e['sleep-hygiene'].count, 1) + assert.equal(e.stretch.count, 1) + assert.equal(e.stretch.skipped, undefined, 'done clears the check-in no') + assert.equal(e.water.count, 4, 'a daily sub-habit is filled to its target') + assert.equal(e['nightly-routine'], undefined) + assert.equal(onDisk().entries[day]['nightly-routine'], undefined) + + r = await call('POST', '/api/habits/log', { id: 'nightly-routine', date: day, counts: { water: 2, stretch: 0 } }) + assert.equal(r.json.entries[day].water.count, 2) + assert.equal(r.json.entries[day].stretch, undefined) + assert.equal(r.json.entries[day]['sleep-hygiene'].count, 1) + + r = await call('POST', '/api/habits/log', { id: 'nightly-routine', date: day, complete: false }) + assert.equal(r.json.entries[day], undefined) + + assert.match((await call('POST', '/api/habits/log', { id: 'nightly-routine', date: day, delta: 1 })).json.error, /is a group/) + assert.match((await call('POST', '/api/habits/log', { id: 'nightly-routine', date: day, counts: { c: 1 } })).json.error, /not a hand-logged sub-habit/) +}) + +test('a group takes no count or note of its own, and its undo puts back a check-in "No"', async () => { + const day = (await call('GET', '/api/habits')).json.today + await call('POST', '/api/habits', { name: 'Morning' }) + await call('POST', '/api/habits', { name: 'Journal', parentId: 'morning' }) + await call('POST', '/api/habits', { name: 'Walk the dog', parentId: 'morning' }) + assert.match((await call('POST', '/api/habits/log', { id: 'morning', date: day, note: 'x' })).json.error, /takes no note/) + assert.match((await call('POST', '/api/habits/log', { id: 'morning', date: day, complete: true, value: 80 })).json.error, /takes no value/) + await call('POST', '/api/habits/log', { id: 'journal', date: day, skipped: true }) + await call('POST', '/api/habits/log', { id: 'morning', date: day, complete: true }) + const r = await call('POST', '/api/habits/log', { id: 'morning', date: day, counts: { journal: 0, 'walk-the-dog': 0 }, skips: ['journal'] }) + assert.deepEqual(r.json.entries[day].journal, { count: 0, skipped: true }) + assert.equal(r.json.entries[day]['walk-the-dog'], undefined) +}) + +test("a group's check leaves a met weekly quota alone and never writes an app-filled sub-habit", async () => { + const day = (await call('GET', '/api/habits')).json.today + await call('POST', '/api/habits', { name: 'Training' }) + await call('POST', '/api/habits', { name: 'Lift', cadence: 'weekly', target: 1, parentId: 'training' }) + await call('POST', '/api/habits', { name: 'Walk', parentId: 'training' }) + await call('POST', '/api/habits', { name: 'Protein', parentId: 'training', linkedApp: 'krakatoa' }) + await call('POST', '/api/habits/log', { id: 'lift', date: day, count: 1 }) + let r = await call('POST', '/api/habits/log', { id: 'training', date: day, complete: true }) + assert.equal(r.json.entries[day].lift.count, 1, 'already met: not bumped to 2') + assert.equal(r.json.entries[day].walk.count, 1) + assert.equal(r.json.entries[day].protein, undefined, 'its app fills it') + assert.match((await call('POST', '/api/habits/log', { id: 'training', date: day, counts: { protein: 1 } })).json.error, /not a hand-logged sub-habit/) +}) + +test('a parent id longer than a slug still names its own habit', async () => { + // Its slug is exactly 40 characters, so a second one is "-2", which slugs back to the first. + const long = 'Wind down before bed with lights out byx' + let r = await call('POST', '/api/habits', { name: `${long} one` }) + r = await call('POST', '/api/habits', { name: `${long} two` }) + const second = r.json.habits.find((h) => h.name === `${long} two`).id + assert.ok(second.length > 40, 'the second id carries a suffix past the slug length') + r = await call('POST', '/api/habits', { name: 'Lock the doors', parentId: second }) + assert.equal(r.status, 200) + r = await call('GET', '/api/habits') + const parent = habit(r.json, habit(r.json, 'lock-the-doors').parentId) + assert.equal(parent?.name, `${long} two`) +}) + +test('ids stay put across a reorder, so each habit keeps its own history', async () => { + const day = (await call('GET', '/api/habits')).json.today + const long = 'Stretch hamstrings and calves after runs' + await call('POST', '/api/habits', { name: `${long} a` }) + let r = await call('POST', '/api/habits', { name: `${long} b` }) + const first = r.json.habits.find((h) => h.name === `${long} a`).id + const second = r.json.habits.find((h) => h.name === `${long} b`).id + await call('POST', '/api/habits/log', { id: first, date: day, count: 1 }) + const active = r.json.habits.filter((h) => !h.archived).map((h) => h.id) + r = await call('POST', '/api/habits/reorder', { ids: [second, ...active.filter((id) => id !== second)] }) + assert.equal(r.status, 200) + const byName = (n) => r.json.habits.find((h) => h.name === n).id + assert.equal(r.json.entries[day][byName(`${long} a`)]?.count, 1) + assert.equal(r.json.entries[day][byName(`${long} b`)], undefined) +}) + +test('an archived group lets its sub-habits out; deleting it frees them for good', async () => { + let r = await call('PATCH', '/api/habits', { id: 'nightly-routine', archived: true }) + assert.equal(habit(r.json, 'stretch').parentId, null) + assert.equal(onDisk().habits.find((h) => h.id === 'stretch').parentId, 'nightly-routine', 'restoring the group brings them back') + r = await call('PATCH', '/api/habits', { id: 'nightly-routine', archived: false }) + assert.equal(habit(r.json, 'stretch').parentId, 'nightly-routine') + r = await call('DELETE', '/api/habits', { id: 'nightly-routine' }) + assert.equal(habit(r.json, 'stretch').parentId, null) + assert.equal(onDisk().habits.find((h) => h.id === 'stretch').parentId, null) +}) diff --git a/mobile/AGENTS.md b/mobile/AGENTS.md index 32a8e66..94c9ca8 100644 --- a/mobile/AGENTS.md +++ b/mobile/AGENTS.md @@ -162,6 +162,14 @@ Use `npx expo install ` for dependencies so versions match the SDK. `features/work/shared.test.mjs`). A task opens its page (`todo/[id]`), whose Chats section is the web card's; a chat's task strip and Link to task… sheet (`chat/task`) link chats to tasks through `linkTask`/`startTaskDraft` in `lib/chat/store.ts`. The drawer's Undo line is docked in its foot (`undoDock.tsx`). +- **Sub-habits**: `lib/habits/groups.ts` is the web's file byte for byte + (`lib/habits/groups.test.mjs`). A habit with sub-habits is a group: every view reads the payload through + `foldGroups` (a group becomes a daily habit counting its sub-habits done) and lists rows with `habitTree`, so a group + is one row in every count (the Habits page's Today bar, `rowsProgress`; the Overview; the hub tile, `glance.ts`). Its + card holds its sub-habits' rows (`features/habits/HabitRow.tsx` `group`/`nested`), its check (`GroupCheck`) logs + `complete` and its undo line sends `groupToggle(...).undo`; its streaks count whole days (`wholeDays`), and a day + picked in its grid steps the page to that day. The form's "Part of" files a habit under one; `/habit/new?parentId=` + starts one there. The morning check-in asks a group's sub-habits, never the group. - **Settings** (`src/features/settings/`) is the web's sections in its groups and order (`lib/components/settings/sections.ts` and `searchIndex.ts` are byte-for-byte copies of the web's), drawn as iOS grouped lists from `features/settings/ui.tsx` (`Section`, `Row`, `Switch`, `Picker`, `Field`, `Notice`): a row keeps the web's id, so a search hit or a diff --git a/mobile/src/features/habits/Check.tsx b/mobile/src/features/habits/Check.tsx index 06269ac..1e76d93 100644 --- a/mobile/src/features/habits/Check.tsx +++ b/mobile/src/features/habits/Check.tsx @@ -52,17 +52,11 @@ export function CheckFace({ habit, count, periodCount, size = CHECK }: { habit: ) } -export function HabitCheck({ habit, count, periodCount, onLog, disabled }: { - habit: Habit - count: number - periodCount: number - onLog: (habit: Habit, delta: number) => void - disabled?: boolean -}) { +/** The press that gives, and a ring thrown outward when it turns done. */ +function useCheckMotion(done: boolean, size: number) { const reduced = useCalm() const scale = useSharedValue(1) const burst = useSharedValue(0) - const done = count > 0 // The flourish follows the transition into done (a tap here, or the check-in // sheet), never a payload that loads already done. const was = useRef(done) @@ -84,7 +78,21 @@ export function HabitCheck({ habit, count, periodCount, onLog, disabled }: { opacity: burst.value > 0 && burst.value < 1 ? 0.6 * (1 - burst.value) : 0, transform: [{ scale: 1 + burst.value * 0.4 }], })) + const box = { width: size, height: size } + return { faceStyle, ringStyle, box, ring: { ...box, borderRadius: size / 2 } } +} +export function HabitCheck({ habit, count, periodCount, onLog, disabled, size = CHECK }: { + habit: Habit + count: number + periodCount: number + onLog: (habit: Habit, delta: number) => void + disabled?: boolean + /** A sub-habit's row inside its group draws it a little smaller. */ + size?: number +}) { + const done = count > 0 + const { faceStyle, ringStyle, box, ring } = useCheckMotion(done, size) const capped = habit.cadence !== 'daily' const target = Math.max(1, habit.target) const progress = capped ? `, ${periodCount} of ${target} ${periodLabel(habit.cadence)}` : '' @@ -97,18 +105,55 @@ export function HabitCheck({ habit, count, periodCount, onLog, disabled }: { accessibilityLabel={`${habit.name}${progress}`} accessibilityHint={done ? 'Double-tap to undo' : 'Double-tap to mark done'} hitSlop={6} - style={st.box} + style={box} + > + + + + + + ) +} + +/** + * A group's own check (lib/habits/groups.ts): a pie of its sub-habits done today, + * the mark once all are. A tap marks every hand-logged one done, or clears them + * once all are; the page owns the write and its undo. + */ +export function GroupCheck({ habit, done, total, action, onLog, disabled, size = CHECK }: { + habit: Habit + done: number + total: number + /** What a tap does, in words (groups.ts groupWords). */ + action: string + onLog: () => void + disabled?: boolean + size?: number +}) { + const all = total > 0 && done >= total + const { faceStyle, ringStyle, box, ring } = useCheckMotion(all, size) + // The pie is CheckFace's weekly face: one slice per sub-habit done. + const face = { ...habit, cadence: 'weekly' as const, target: Math.max(1, total) } + return ( + - - - + + + ) } const st = StyleSheet.create({ - box: { width: CHECK, height: CHECK }, mark: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, alignItems: 'center', justifyContent: 'center' }, - burst: { position: 'absolute', top: 0, left: 0, width: CHECK, height: CHECK, borderRadius: CHECK / 2, borderWidth: 3 }, + burst: { position: 'absolute', top: 0, left: 0, borderWidth: 3 }, }) diff --git a/mobile/src/features/habits/CheckinSheet.tsx b/mobile/src/features/habits/CheckinSheet.tsx index f1f50ba..37a1222 100644 --- a/mobile/src/features/habits/CheckinSheet.tsx +++ b/mobile/src/features/habits/CheckinSheet.tsx @@ -114,6 +114,7 @@ function CheckinRow({ item, entry, note, busy, first, onAnswer }: { + {item.group ? {item.group} : null} {habit.name} {item.part === 'yesterday' && habit.when === 'night' ? last night : null} {note ? {note} : null} diff --git a/mobile/src/features/habits/HabitFormSheet.tsx b/mobile/src/features/habits/HabitFormSheet.tsx index d880c04..e1fb74f 100644 --- a/mobile/src/features/habits/HabitFormSheet.tsx +++ b/mobile/src/features/habits/HabitFormSheet.tsx @@ -1,35 +1,64 @@ // New / edit habit (HabitsView.tsx HabitFormModal) as a formSheet. Same fields, // hints and copy; selects are native menus, the delete confirm is the platform alert. +// "Part of" files a habit under a group (lib/habits/groups.ts); a group itself says +// so instead and offers to add a sub-habit. `/habit/new?parentId=` starts one there. import React, { useState } from 'react' import { StyleSheet, View } from 'react-native' -import { useLocalSearchParams } from 'expo-router' +import { router, useLocalSearchParams } from 'expo-router' import { colors } from '../../theme' import { T } from '../../ui/Text' import { Btn, Empty, Press, Segmented } from '../../ui/kit' import { confirm } from '../../ui/menu' import { success } from '../../ui/haptics' -import { TrashIcon } from '../../lib/icons' +import { PlusIcon, TrashIcon } from '../../lib/icons' import { createHabit, deleteHabit, updateHabit } from '../../lib/api' import { pushToast } from '../../lib/toast' import { CheckField, Field, FieldInput, FieldRow, Select, Sheet, closeSheet } from './form' import { APP_NAME, CADENCE_NOUN, metricDraftFrom, metricFromDraft, periodLabel, - type Cadence, type HabitWhen, type LinkedApp, type MetricDraft, + type Cadence, type Habit, type HabitWhen, type LinkedApp, type MetricDraft, } from './logic' import { mutate, useHabits } from './store' +import { handLogged } from '../../lib/habits/groups' export default function HabitFormSheet({ editing }: { editing?: boolean }) { - const { id } = useLocalSearchParams<{ id?: string }>() + const { id, parentId } = useLocalSearchParams<{ id?: string; parentId?: string }>() const { data } = useHabits() - const found = editing ? data?.habits.find((h) => h.id === id) ?? null : null + const all = data?.habits ?? [] + const found = editing ? all.find((h) => h.id === id) ?? null : null // Held from the first render: a delete swaps in a payload without the habit, and // the sheet should close on the form rather than flash "gone" on the way out. const [initial] = useState(found) if (editing && !initial) return - return h.color)} /> + // Habits this one may sit under: active, top-level, filled by hand, not itself. + // A group's own check is derived, so only a habit ticked by hand can hold sub-habits (the bridge's rule). + const parents = all.filter((h) => !h.archived && !h.parentId && handLogged(h) && h.id !== initial?.id) + const hasChildren = Boolean(initial && all.some((h) => h.parentId === initial.id && !h.archived)) + // An edit keeps its group; a new habit takes the one it was started from. Either only if it can still hold it. + const want = initial ? initial.parentId : parentId + return ( + h.color)} + parents={parents} + defaultParent={want && parents.some((h) => h.id === want) ? want : ''} + hasChildren={hasChildren} + /> + ) } -function HabitForm({ initial, palette, usedColors }: { initial: import('./logic').Habit | null; palette: string[]; usedColors: string[] }) { +function HabitForm({ initial, palette, usedColors, parents, defaultParent, hasChildren }: { + initial: Habit | null + palette: string[] + usedColors: string[] + parents: Habit[] + /** The group the form starts on ('' for none). */ + defaultParent: string + /** It is a group already, so it cannot go under another habit. */ + hasChildren: boolean +}) { const [form, setForm] = useState({ name: initial?.name || '', description: initial?.description || '', @@ -39,11 +68,16 @@ function HabitForm({ initial, palette, usedColors }: { initial: import('./logic' archived: initial?.archived || false, when: (initial?.when || 'any') as HabitWhen, linkedApp: (initial?.linkedApp || '') as LinkedApp | '', // '' = filled in by hand + parentId: defaultParent, // '' = a habit of its own }) const [metric, setMetric] = useState(() => metricDraftFrom(initial?.metric)) const setM = (k: K, v: MetricDraft[K]) => setMetric((m) => ({ ...m, [k]: v })) const set = (k: K, v: (typeof form)[K]) => setForm((f) => ({ ...f, [k]: v })) const [busy, setBusy] = useState(null) + // A habit an app or WHOOP fills in cannot sit in a group: its check is never tapped. + // An app- or WHOOP-filled habit can sit in a group (its check skips it); it just can't hold one. + const canGroup = !hasChildren + const parentName = parents.find((h) => h.id === form.parentId)?.name const submit = async () => { if (!form.name.trim()) { pushToast('A name is required.'); return } @@ -59,6 +93,11 @@ function HabitForm({ initial, palette, usedColors }: { initial: import('./logic' linkedApp: form.linkedApp || null, metric: metricFromDraft(metric, initial?.metric?.parts), } + // Only when it changed: a sub-habit of an archived group arrives with no parent + // (the bridge lets it out until the group returns), and saving that back would + // detach it for good. + const parentNow = form.parentId || null + if (parentNow !== (initial?.parentId || null)) fields.parentId = parentNow if (form.color) fields.color = form.color await mutate(() => (initial ? updateHabit(initial.id, fields) : createHabit(fields))) success() @@ -78,7 +117,7 @@ function HabitForm({ initial, palette, usedColors }: { initial: import('./logic' return ( @@ -97,43 +136,72 @@ function HabitForm({ initial, palette, usedColors }: { initial: import('./logic' set('description', v)} placeholder="What counts as done?" returnKeyType="done" /> - - - {sel(form.cadence, [{ value: 'daily', label: 'Daily' }, { value: 'weekly', label: 'Weekly' }, { value: 'monthly', label: 'Monthly' }], (v) => set('cadence', v), 'How often')} + {hasChildren ? ( + + + {initial?.name} is a group: it is done for a day when all its sub-habits are, and its check marks the ones you tick by hand (an app fills in its own). + + router.replace({ pathname: '/habit/new', params: { parentId: initial!.id } })} + /> + + ) : canGroup && (parents.length > 0 || form.parentId) ? ( + + {sel( + form.parentId, + [{ value: '', label: 'Nothing, a habit of its own' }, ...parents.map((h) => ({ value: h.id, label: h.name }))], + (v) => set('parentId', v), + 'Part of', + )} - - set('target', v.replace(/[^0-9]/g, ''))} keyboardType="numbers-and-punctuation" returnKeyType="done" maxLength={2} /> + ) : null} + {/* A group's day is its sub-habits': how often, when, who fills it and a number are theirs. */} + {!hasChildren && (<> + + + {sel(form.cadence, [{ value: 'daily', label: 'Daily' }, { value: 'weekly', label: 'Weekly' }, { value: 'monthly', label: 'Monthly' }], (v) => set('cadence', v), 'How often')} + + + set('target', v.replace(/[^0-9]/g, ''))} keyboardType="numbers-and-punctuation" returnKeyType="done" maxLength={2} /> + + + {/* The web's two selects; three short choices each read better as segments on a phone. */} + + set('when', v)} + options={[{ value: 'any', label: 'Any time' }, { value: 'morning', label: 'Morning' }, { value: 'night', label: 'Night' }]} + /> - - {/* The web's two selects; three short choices each read better as segments on a phone. */} - - set('when', v)} - options={[{ value: 'any', label: 'Any time' }, { value: 'morning', label: 'Morning' }, { value: 'night', label: 'Night' }]} - /> - - - set('linkedApp', v === 'me' ? '' : v)} - options={[{ value: 'me', label: 'Me' }, { value: 'krakatoa', label: 'Krakatoa' }, { value: 'bushido', label: 'Bushido' }]} - /> - - - {form.linkedApp - ? `${APP_NAME[form.linkedApp]} fills this in on its own; here it links to the app instead of a check mark.` - : form.when === 'night' - ? 'Night: logged the next morning. The morning check-in asks about it the next day and logs it to the night before.' - : form.when === 'morning' - ? 'The morning check-in asks about it for that day.' - : 'The morning check-in asks about it if yesterday went unanswered.'} - - - {form.cadence === 'daily' - ? '1 = simple yes/no. Higher (e.g. 8 glasses of water) shades the day darker the closer you get.' - : `e.g. gym 3× a week, or deep-clean once a month. You still check it off on the day you do it; the check-in shows ${periodLabel(form.cadence)}’s progress.`} - + + set('linkedApp', v === 'me' ? '' : v)} + options={[{ value: 'me', label: 'Me' }, { value: 'krakatoa', label: 'Krakatoa' }, { value: 'bushido', label: 'Bushido' }]} + /> + + + {form.linkedApp + ? `${APP_NAME[form.linkedApp]} fills this in on its own; here it links to the app instead of a check mark.` + : form.when === 'night' + ? 'Night: logged the next morning. The morning check-in asks about it the next day and logs it to the night before.' + : form.when === 'morning' + ? 'The morning check-in asks about it for that day.' + : 'The morning check-in asks about it if yesterday went unanswered.'} + + + {form.cadence === 'daily' + ? '1 = simple yes/no. Higher (e.g. 8 glasses of water) shades the day darker the closer you get.' + : `e.g. gym 3× a week, or deep-clean once a month. You still check it off on the day you do it; the check-in shows ${periodLabel(form.cadence)}’s progress.`} + + )} {!initial && ( @@ -157,48 +225,50 @@ function HabitForm({ initial, palette, usedColors }: { initial: import('./logic' - {/* Optional metric: the number this habit is really about. */} - - setM('on', v)}>Track a number with this habit - {metric.on && ( - <> - - - setM('label', v)} placeholder="e.g. Sleep score" /> + {!hasChildren && (<> + {/* Optional metric: the number this habit is really about. */} + + setM('on', v)}>Track a number with this habit + {metric.on && ( + <> + + + setM('label', v)} placeholder="e.g. Sleep score" /> + + + setM('unit', v)} placeholder="e.g. min, kg, %" /> + + + + setM('min', v)} placeholder="auto" keyboardType="numbers-and-punctuation" returnKeyType="done" /> + setM('max', v)} placeholder="auto" keyboardType="numbers-and-punctuation" returnKeyType="done" /> + setM('goal', v)} placeholder="none" keyboardType="numbers-and-punctuation" returnKeyType="done" /> + + + {sel(metric.direction, [{ value: 'higher', label: 'Higher' }, { value: 'lower', label: 'Lower' }], (v) => setM('direction', v), 'Better when')} + {sel(metric.chart, [{ value: 'line', label: 'Line' }, { value: 'bar', label: 'Bars' }], (v) => setM('chart', v), 'Graph')} + {sel(metric.decimals, [{ value: '0', label: '0' }, { value: '1', label: '0.0' }, { value: '2', label: '0.00' }], (v) => setM('decimals', v), 'Decimals')} + + + {sel(metric.source, [{ value: 'manual', label: 'Me (or Totem, when I tell it)' }, { value: 'whoop-sleep', label: 'WHOOP sleep sync' }], (v) => setM('source', v), 'Filled by')} - - setM('unit', v)} placeholder="e.g. min, kg, %" /> + {metric.source === 'whoop-sleep' && ( + + A scheduled job pulls last night's sleep performance and stages from WHOOP (through Bushido) each late + morning (Studio → Workflows → WHOOP sleep sync). Nights you've already filled in are left alone. + + )} + + setM('parts', v)} placeholder="e.g. Deep, Light, REM, Awake" /> - - - setM('min', v)} placeholder="auto" keyboardType="numbers-and-punctuation" returnKeyType="done" /> - setM('max', v)} placeholder="auto" keyboardType="numbers-and-punctuation" returnKeyType="done" /> - setM('goal', v)} placeholder="none" keyboardType="numbers-and-punctuation" returnKeyType="done" /> - - - {sel(metric.direction, [{ value: 'higher', label: 'Higher' }, { value: 'lower', label: 'Lower' }], (v) => setM('direction', v), 'Better when')} - {sel(metric.chart, [{ value: 'line', label: 'Line' }, { value: 'bar', label: 'Bars' }], (v) => setM('chart', v), 'Graph')} - {sel(metric.decimals, [{ value: '0', label: '0' }, { value: '1', label: '0.0' }, { value: '2', label: '0.00' }], (v) => setM('decimals', v), 'Decimals')} - - - {sel(metric.source, [{ value: 'manual', label: 'Me (or Totem, when I tell it)' }, { value: 'whoop-sleep', label: 'WHOOP sleep sync' }], (v) => setM('source', v), 'Filled by')} - - {metric.source === 'whoop-sleep' && ( - - A scheduled job pulls last night's sleep performance and stages from WHOOP (through Bushido) each late - morning (Studio → Workflows → WHOOP sleep sync). Nights you've already filled in are left alone. - - )} - - setM('parts', v)} placeholder="e.g. Deep, Light, REM, Awake" /> - - setM('pinned', v)}>Pin this graph to the Home board - - )} - + setM('pinned', v)}>Pin this graph to the Home board + + )} + + )} {initial && ( set('archived', v)}>Archived (hidden from check-in, history kept) )} @@ -211,5 +281,6 @@ const s = StyleSheet.create({ swatch: { width: 30, height: 30, borderRadius: 8, borderWidth: 2, borderColor: 'transparent' }, auto: { width: 'auto', paddingHorizontal: 10, backgroundColor: colors.bg3, borderWidth: 1, borderColor: colors.line, alignItems: 'center', justifyContent: 'center' }, selected: { borderColor: colors.text }, + groupNote: { gap: 10, padding: 12, borderRadius: 10, backgroundColor: colors.bg3 }, metricForm: { marginTop: 4, padding: 12, borderWidth: 1, borderColor: colors.line, borderRadius: 12, backgroundColor: colors.bg3, gap: 10 }, }) diff --git a/mobile/src/features/habits/HabitRow.tsx b/mobile/src/features/habits/HabitRow.tsx index bd923ba..56b2de5 100644 --- a/mobile/src/features/habits/HabitRow.tsx +++ b/mobile/src/features/habits/HabitRow.tsx @@ -3,6 +3,10 @@ // in place (stats, the year grid, the number chart); long-press is the menu. This // replaces the old page's two lists (a check-in card, then a history card per habit // further down) with one. +// +// A group (a habit with sub-habits, lib/habits/groups.ts) is one card holding its +// sub-habits' rows, indented along a line in its colour: its own check is a pie of +// them done and marks them all; each sub-habit's row works as any other. import React, { useMemo } from 'react' import { StyleSheet, View } from 'react-native' import Animated, { FadeIn, FadeOut, LinearTransition } from 'react-native-reanimated' @@ -13,20 +17,39 @@ import { Hi, ChatBubbleLeftEllipsisIcon, ChatBubbleLeftRightIcon, ChevronDownIcon, FireIcon, MoonIcon, PencilSquareIcon, SunIcon, } from '../../lib/icons' import { - CADENCE_NOUN, LEVEL_MIX, bestStreakOf, mixHex, periodLabel, periodTotal, recentDays, streakOf, totalFor, + CADENCE_NOUN, LEVEL_MIX, bestStreakOf, mixHex, periodLabel, periodTotal, recentDays, streakOf, totalFor, wholeDays, type Entries, type Habit, } from './logic' import { HabitMetricInput, QuotaDots, Stepper } from './parts' -import { CheckFace, CHECK, HabitCheck } from './Check' +import { CheckFace, CHECK, GroupCheck, HabitCheck } from './Check' import { useCalm } from './motion' import { LinkedAppButton } from './LinkedApp' import HabitGrid from './HabitGrid' import { HabitMetricSection } from './MetricChart' +/** What a group's card draws besides its own line. */ +export interface GroupInfo { + /** Sub-habits done on the day being answered, of how many. */ + done: number + total: number + /** What its check does, in words (groups.ts groupWords). */ + action: string + /** Its check is waiting on the bridge. */ + busy: boolean + onLog: () => void + /** The sub-habits' rows. */ + children: React.ReactNode + /** The undo line after its check was used, drawn under the sub-habits. */ + undo?: React.ReactNode +} + +/** A sub-habit's row is drawn a little smaller, inside its group's card. */ +const NESTED_CHECK = 42 + export interface HabitRowProps { habit: Habit - /** The entries with in-flight taps folded in. */ + /** The entries with in-flight taps and groups folded in (foldGroups). */ entries: Entries /** The check-in day the row is answering for. */ date: string @@ -43,6 +66,10 @@ export interface HabitRowProps { onChat: (habit: Habit) => void onPickDay: (habit: Habit, date: string) => void onPickPeriod: (habit: Habit, period: { start: string; end: string; title: string }) => void + /** A sub-habit's row inside its group's card. */ + nested?: boolean + /** Set for a group. */ + group?: GroupInfo } function WhenMark({ habit }: { habit: Habit }) { @@ -106,10 +133,16 @@ function Stat({ value, label, accent }: { value: string; label: string; accent?: ) } -function History({ habit, entries, today, onEdit, onChat, onPickDay, onPickPeriod }: Pick) { - const streak = streakOf(habit, entries, today) - const best = bestStreakOf(habit, entries, today) +/** A group's streaks and totals count whole days only (wholeDays); anything else its own. */ +function counted(habit: Habit, entries: Entries, group: boolean): { shape: Habit; entries: Entries } { + return group ? { shape: { ...habit, target: 1 }, entries: wholeDays(habit, entries) } : { shape: habit, entries } +} + +function History({ habit, entries, today, group, onEdit, onChat, onPickDay, onPickPeriod }: Pick & { group: boolean }) { + const whole = counted(habit, entries, group) + const streak = streakOf(whole.shape, whole.entries, today) + const best = bestStreakOf(whole.shape, whole.entries, today) const unit = CADENCE_NOUN[habit.cadence] const calm = useCalm() return ( @@ -117,7 +150,7 @@ function History({ habit, entries, today, onEdit, onChat, onPickDay, onPickPerio 1 ? colors.amber : undefined} /> - + {habit.cadence !== 'daily' && ( @@ -129,9 +162,10 @@ function History({ habit, entries, today, onEdit, onChat, onPickDay, onPickPerio onPick={(date) => onPickDay(habit, date)} onPickPeriod={(period) => onPickPeriod(habit, period)} /> + {group && Pick a day to answer its sub-habits for that day.} {habit.metric && } - onEdit(habit)} style={s.historyBtn} /> + onEdit(habit)} style={s.historyBtn} /> onChat(habit)} style={s.historyBtn} /> @@ -139,58 +173,66 @@ function History({ habit, entries, today, onEdit, onChat, onPickDay, onPickPerio } export default function HabitRow(props: HabitRowProps) { - const { habit, entries, date, today, expanded, busy, onToggle, onLog, onValue, onNote, onMore } = props + const { habit, entries, date, today, expanded, busy, nested, group, onToggle, onLog, onValue, onNote, onMore } = props const entry = entries[date]?.[habit.id] const count = entry?.count || 0 const periodCount = periodTotal(habit, entries, date) - const streak = streakOf(habit, entries, today) - const multi = habit.cadence === 'daily' && habit.target > 1 - const sub = entry?.note || habit.description - const finished = habit.cadence === 'daily' ? count >= Math.max(1, habit.target) : periodCount >= Math.max(1, habit.target) + const whole = counted(habit, entries, Boolean(group)) + const streak = streakOf(whole.shape, whole.entries, today) + const multi = !group && habit.cadence === 'daily' && habit.target > 1 + const sub = (!group && entry?.note) || habit.description + const finished = group + ? group.done >= group.total + : habit.cadence === 'daily' ? count >= Math.max(1, habit.target) : periodCount >= Math.max(1, habit.target) const calm = useCalm() // A number box beside the row's other controls leaves the name no room on a // phone, so a habit with one puts its controls on a line of their own. - const crowded = Boolean(habit.metric) - const recent = recentDays(habit, entries, date).filter((d) => d.level > 0).length + const crowded = Boolean(habit.metric) && !group + // A group's strip shades partial days; only full ones count as done. + const recent = recentDays(habit, entries, date).filter((d) => d.level >= (group ? 4 : 1)).length const unit = CADENCE_NOUN[habit.cadence] // The row is one VoiceOver element, so it says everything its pieces show. const spoken = [ habit.name, + group ? `a group of ${group.total}, ${group.done} done` : '', habit.when === 'night' ? 'a night habit, logged the next morning' : habit.when === 'morning' ? 'a morning habit' : '', sub, streak > 1 ? `${streak}-${unit} streak` : '', - habit.cadence !== 'daily' ? `${periodCount} of ${habit.target} ${periodLabel(habit.cadence)}` : '', + !group && habit.cadence !== 'daily' ? `${periodCount} of ${habit.target} ${periodLabel(habit.cadence)}` : '', `done ${recent} of the last 7 days`, ].filter(Boolean).join(', ') + const checkSize = nested ? NESTED_CHECK : CHECK let control: React.ReactNode - if (habit.linkedApp) { + if (group) { + control = + } else if (habit.linkedApp) { // An app fills this one in: the same face, filling as it does, but not a // button; the link beside it goes to the app. control = ( - 0 ? 'done' : 'not yet'}, filled in by its app`} style={{ width: CHECK, height: CHECK }}> - + 0 ? 'done' : 'not yet'}, filled in by its app`} style={{ width: checkSize, height: checkSize }}> + ) } else if (multi) { control = ( onLog(habit, d)} labelLess={`Undo one ${habit.name}`} labelMore={`Log one ${habit.name}`} /> ) } else { - control = + control = } const controls = ( <> {habit.metric && } - {!habit.linkedApp && ( + {!habit.linkedApp && !group && ( onNote(habit)} @@ -206,7 +248,10 @@ export default function HabitRow(props: HabitRowProps) { ) return ( - + onToggle(habit)} @@ -219,10 +264,13 @@ export default function HabitRow(props: HabitRowProps) { > - {habit.name} + {habit.name} - {habit.cadence !== 'daily' && } + {group && ( + {group.done}/{group.total} + )} + {!group && habit.cadence !== 'daily' && } @@ -244,7 +292,16 @@ export default function HabitRow(props: HabitRowProps) { {controls} )} - {expanded && } + {group && ( + + {group.children} + + )} + {group?.undo ? {group.undo} : null} + {expanded && } ) } @@ -268,6 +325,8 @@ const s = StyleSheet.create({ stripDot: { width: 12, height: 12, borderRadius: 3, backgroundColor: colors.bg3, borderWidth: 1, borderColor: alpha('#ffffff', 0.14) }, stripSkipped: { borderStyle: 'dashed', borderColor: colors.muted }, chev: { width: 18, alignItems: 'center' }, + nested: { paddingVertical: 8, paddingLeft: 12 }, + subs: { marginTop: 10, marginLeft: 4, borderLeftWidth: 2 }, controlsLine: { flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', gap: 8, marginTop: 8 }, noteBtn: { width: 36, height: 44, alignItems: 'center', justifyContent: 'center' }, linked: { flexDirection: 'row', alignItems: 'center', gap: 8 }, diff --git a/mobile/src/features/habits/logic.test.mjs b/mobile/src/features/habits/logic.test.mjs index 746f750..0816ce9 100644 --- a/mobile/src/features/habits/logic.test.mjs +++ b/mobile/src/features/habits/logic.test.mjs @@ -2,7 +2,20 @@ // `node --test mobile/src/features/habits/logic.test.mjs`; node strips the types. import test from 'node:test' import assert from 'node:assert/strict' -import { bestStreakOf, dayProgress, doneOn, recentDays, streakOf, withPending } from './logic.ts' +import { registerHooks } from 'node:module' + +// logic.ts imports the shared groups file the way Metro resolves it, without an +// extension; let node find the .ts file the same way. +registerHooks({ + resolve(specifier, context, next) { + try { return next(specifier, context) } catch (err) { + if (specifier.startsWith('.') && !/\.[cm]?[jt]s$/.test(specifier)) return next(`${specifier}.ts`, context) + throw err + } + }, +}) +const { bestStreakOf, dayProgress, diffDays, doneOn, recentDays, rowsProgress, streakOf, wholeDays, withPending } = await import('./logic.ts') +const { foldGroups, habitTree } = await import('../../lib/habits/groups.ts') const habit = (over = {}) => ({ id: 'h1', name: 'Read', description: '', color: '#5b8cff', cadence: 'daily', target: 1, @@ -113,3 +126,53 @@ test('withPending: an id with a colon in it still splits on the date', () => { const next = withPending({}, { 'a:b:2026-10-05': 1 }) assert.equal(next['2026-10-05']['a:b'].count, 1) }) + +// ---- sub-habits ---- +const routine = () => [ + habit({ id: 'g', name: 'Nightly routine', color: '#8b5cf6' }), + habit({ id: 'a', name: 'Stretch', parentId: 'g' }), + habit({ id: 'b', name: 'No screens', parentId: 'g' }), + habit({ id: 'r', name: 'Read', color: '#22c55e' }), +] + +test('rowsProgress: a group is one segment, done only once every sub-habit is', () => { + const habits = routine() + const rows = habitTree(habits) + const day = '2026-10-05' + const half = { [day]: { a: { count: 1 }, r: { count: 1 } } } + assert.deepEqual(rowsProgress(habits, rows, half, day), { + done: 1, total: 2, + segments: [{ id: 'g', color: '#8b5cf6', done: false }, { id: 'r', color: '#22c55e', done: true }], + }) + const all = { [day]: { a: { count: 1 }, b: { count: 1 } } } + assert.deepEqual(rowsProgress(habits, rows, all, day).segments.map((s) => s.done), [true, false]) +}) + +test('wholeDays: a folded group counts only the days every sub-habit was done', () => { + const habits = routine() + const entries = { + '2026-10-03': { a: { count: 1 }, b: { count: 1 } }, + '2026-10-04': { a: { count: 1 }, b: { count: 1 } }, + '2026-10-05': { a: { count: 1 } }, + } + const folded = foldGroups(habits, entries) + const group = folded.habits.find((h) => h.id === 'g') + assert.equal(group.target, 2) + // Read as an ordinary daily habit, a partial day keeps the streak alive … + assert.equal(streakOf(group, folded.entries, '2026-10-05'), 3) + // … counted in whole days it does not: today is still open, and two full days stand. + const whole = wholeDays(group, folded.entries) + const one = { ...group, target: 1 } + assert.equal(whole['2026-10-05'].g.count, 0) + assert.equal(streakOf(one, whole, '2026-10-05'), 2) + assert.equal(bestStreakOf(one, whole, '2026-10-05'), 2) + // Other habits' entries are left as they were. + assert.deepEqual(whole['2026-10-03'].a, { count: 1 }) +}) + +test('diffDays: whole days back, across a clock change', () => { + assert.equal(diffDays('2026-11-25', '2026-11-25'), 0) + assert.equal(diffDays('2026-11-25', '2026-11-20'), 5) + assert.equal(diffDays('2026-11-03', '2026-10-30'), 4) + assert.equal(diffDays('2026-03-10', '2026-03-07'), 3) +}) diff --git a/mobile/src/features/habits/logic.ts b/mobile/src/features/habits/logic.ts index 2516af2..3c41f56 100644 --- a/mobile/src/features/habits/logic.ts +++ b/mobile/src/features/habits/logic.ts @@ -3,6 +3,7 @@ // thermometer gauge. Everything works on the bridge's local "YYYY-MM-DD" strings — // the bridge decides what "today" is, so nothing here calls new Date() for a day key. import type { MetricConfig, MetricPart } from '../../lib/components/metricChart' +import { groupProgress, type HabitNode } from '../../lib/habits/groups' export type Cadence = 'daily' | 'weekly' | 'monthly' @@ -22,6 +23,8 @@ export interface Habit { appUrl?: string | null createdAt: string archived: boolean + /** The group it sits under (lib/habits/groups.ts); one level deep. */ + parentId?: string | null } export type HabitWhen = 'any' | 'morning' | 'night' @@ -196,6 +199,26 @@ export function doneOn(habit: Habit, entries: Entries, date: string): boolean { return count > 0 || periodTotal(habit, entries, date) >= Math.max(1, habit.target) } +/** + * A group's streaks and totals count whole days only: a day with every sub-habit + * done. Reads entries already folded (foldGroups), where a group's count is its + * sub-habits done that day and its target is how many it has. (Its strip and grid + * still shade partial days.) Pair it with the group at target 1. + */ +export function wholeDays(group: Habit, entries: Entries): Entries { + const out: Entries = {} + for (const [date, day] of Object.entries(entries)) { + const count = day[group.id]?.count || 0 + out[date] = { ...day, [group.id]: { count: count >= Math.max(1, group.target) ? 1 : 0 } } + } + return out +} + +/** Whole days from `from` back to `to` (positive when `to` is earlier). */ +export function diffDays(from: string, to: string): number { + return Math.round((toDate(from).getTime() - toDate(to).getTime()) / 86_400_000) +} + export interface DayProgress { done: number; total: number; segments: { id: string; color: string; done: boolean }[] } /** The Today panel's bar: one segment per habit, in list order. */ @@ -204,6 +227,20 @@ export function dayProgress(habits: Habit[], entries: Entries, date: string): Da return { done: segments.filter((s) => s.done).length, total: segments.length, segments } } +/** + * The Today panel's bar over the page's rows (habitTree): a group is one segment, + * done once every sub-habit is. `entries` are the raw ones (taps folded in), not + * foldGroups' copy. + */ +export function rowsProgress(habits: Habit[], rows: HabitNode[], entries: Entries, date: string): DayProgress { + const segments = rows.map(({ habit, children }) => { + if (!children.length) return { id: habit.id, color: habit.color, done: doneOn(habit, entries, date) } + const p = groupProgress(habits, habit.id, entries, date) + return { id: habit.id, color: habit.color, done: p.total > 0 && p.done >= p.total } + }) + return { done: segments.filter((s) => s.done).length, total: segments.length, segments } +} + /** * The entries with not-yet-answered taps folded in, so a check fills the moment * it is pressed. `pending` maps `habitId:date` to the delta still in flight. diff --git a/mobile/src/features/habits/store.ts b/mobile/src/features/habits/store.ts index c1312b7..e6aaddc 100644 --- a/mobile/src/features/habits/store.ts +++ b/mobile/src/features/habits/store.ts @@ -40,9 +40,14 @@ function shift(key: string, delta: number) { pending = next ? { ...rest, [key]: next } : rest } +type Settle = { key: string; delta: number } + /** Draw a tap now; `mutate(run, { key, delta })` takes it back out when it settles. */ export function addPending(key: string, delta: number) { shift(key, delta); emit() } +/** Several at once (a group's check moves each of its sub-habits), in one emit. */ +export function addPendings(list: Settle[]) { for (const p of list) shift(p.key, p.delta); emit() } + /** A 401 means the stored secret is dead: back to Connect, as the web's onAuthError does. */ export function failed(e: unknown): string { if (e instanceof AuthError) { clearSecret(); return 'Session expired' } @@ -68,15 +73,18 @@ export async function loadHabits(): Promise { /** * Run a mutation that answers with the full payload. Throws the message on failure. - * `settles` is a tap drawn with addPending, removed in the same emit as the answer. + * `settles` is a tap (or a group's taps) drawn with addPending(s), removed in the + * same emit as the answer. */ -export async function mutate(run: () => Promise, settles?: { key: string; delta: number }): Promise { +export async function mutate(run: () => Promise, settles?: Settle | Settle[]): Promise { + const list = settles ? (Array.isArray(settles) ? settles : [settles]) : [] + const settle = () => { for (const p of list) shift(p.key, -p.delta) } try { const next = await run() - if (settles) shift(settles.key, -settles.delta) + settle() setHabits(next) } catch (e) { - if (settles) { shift(settles.key, -settles.delta); emit() } + if (list.length) { settle(); emit() } throw new Error(failed(e)) } } diff --git a/mobile/src/features/overview/HabitRow.tsx b/mobile/src/features/overview/HabitRow.tsx index a3970cd..29b720f 100644 --- a/mobile/src/features/overview/HabitRow.tsx +++ b/mobile/src/features/overview/HabitRow.tsx @@ -1,6 +1,8 @@ // One habit in the Overview's inline check-in: the same controls as the Habits // tab (HabitsView.tsx: HabitCheckButton, QuotaDots, HabitMetricInput) at the -// sizes overview.css gives them on a phone. +// sizes overview.css gives them on a phone. A group (lib/habits/groups.ts) is a +// GroupRow, its progress and one check that marks them all, with its sub-habits' +// rows under it, indented along a line. import React, { useState } from 'react' import { StyleSheet, TextInput, View } from 'react-native' import Svg, { Circle, Path } from 'react-native-svg' @@ -31,39 +33,43 @@ function QuotaNum({ habit, count }: { habit: any; count: number }) { ) } -// The one big round toggle. Daily habits fill solid once logged; capped weekly or -// monthly ones fill as a pie, one slice per completion in the period. The check is -// about today and shows as soon as the day is logged. -function HabitCheckButton({ habit, count, periodCount, busy, onLog }: { - habit: any; count: number; periodCount: number; busy: boolean; onLog: (h: any, d: number) => void -}) { - const capped = habit.cadence !== 'daily' - const target = Math.max(1, habit.target) - const ratio = capped ? Math.min(1, periodCount / target) : count > 0 ? 1 : 0 +/** The round check's face: solid once done, or a pie for a quota (`capped`). */ +function CheckCircle({ color, capped, ratio, done, size }: { color: string; capped: boolean; ratio: number; done: boolean; size: number }) { const full = ratio >= 1 - const done = count > 0 - const size = 34 const r = (size - 1.5) / 2 const c = size / 2 - const progress = capped ? `, ${periodCount} of ${target} ${periodLabel(habit.cadence)}` : '' - const border = !capped ? (done ? habit.color : 'rgba(255, 255, 255, 0.16)') : full ? habit.color : mix(habit.color, colors.line, 0.4) + const border = !capped ? (done ? color : 'rgba(255, 255, 255, 0.16)') : full ? color : mix(color, colors.line, 0.4) // A wedge from 12 o'clock, clockwise. const angle = ratio * 2 * Math.PI const ex = c + r * Math.sin(angle), ey = c - r * Math.cos(angle) const wedge = `M${c},${c}L${c},${c - r}A${r},${r} 0 ${angle > Math.PI ? 1 : 0} 1 ${ex},${ey}Z` - const circle = ( + return ( <> - {capped && ratio > 0 && !full && } + {capped && ratio > 0 && !full && } - {done && } + {done && } ) +} + +// The one big round toggle. Daily habits fill solid once logged; capped weekly or +// monthly ones fill as a pie, one slice per completion in the period. The check is +// about today and shows as soon as the day is logged. +function HabitCheckButton({ habit, count, periodCount, busy, onLog, size = 34 }: { + habit: any; count: number; periodCount: number; busy: boolean; onLog: (h: any, d: number) => void; size?: number +}) { + const capped = habit.cadence !== 'daily' + const target = Math.max(1, habit.target) + const ratio = capped ? Math.min(1, periodCount / target) : count > 0 ? 1 : 0 + const done = count > 0 + const progress = capped ? `, ${periodCount} of ${target} ${periodLabel(habit.cadence)}` : '' + const circle = // An app fills this one in: the same circle, but not a button (the link sits beside it). if (habit.linkedApp) { return ( @@ -127,18 +133,49 @@ function HabitMetricInput({ habit, entry, busy, onValue }: { ) } -export function HabitRow({ habit, entry, count, periodCount, busy, onLog, onValue, onNote, first }: { +/** A group: its sub-habits done today and one check that marks them all, or clears them once all are. */ +export function GroupRow({ habit, done, total, action, busy, first, onLog }: { + habit: any; done: number; total: number + /** What the check does, in words (groups.ts groupWords). */ + action: string + busy: boolean; first?: boolean; onLog: () => void +}) { + const all = total > 0 && done >= total + return ( + + + + {habit.name} + {done}/{total} + + + + + + ) +} + +export function HabitRow({ habit, entry, count, periodCount, busy, onLog, onValue, onNote, first, nested }: { habit: any; entry: any; count: number; periodCount: number; busy: boolean; first?: boolean + /** A sub-habit, drawn under its group; `first` is the one right under the group's row. */ + nested?: boolean onLog: (habit: any, delta: number) => void onValue: (habit: any, value: number | null) => void onNote: (habit: any) => void }) { const done = periodCount >= habit.target return ( - + - {habit.name} + {habit.name} {entry?.note ? {entry.note} : null} {habit.cadence !== 'daily' && } @@ -169,7 +206,7 @@ export function HabitRow({ habit, entry, count, periodCount, busy, onLog, onValu ) : ( - + )} ) @@ -178,6 +215,7 @@ export function HabitRow({ habit, entry, count, periodCount, busy, onLog, onValu const st = StyleSheet.create({ row: { flexDirection: 'row', alignItems: 'center', gap: 10, minHeight: 52, paddingVertical: 6 }, rule: { borderTopWidth: 1, borderTopColor: ov.rowLine }, + nested: { marginLeft: 3, paddingLeft: 16, borderLeftWidth: 2, borderLeftColor: ov.line, minHeight: 46 }, dot: { width: 8, height: 8, borderRadius: 4 }, iconBtn: { width: 32, height: 32, borderRadius: 10, alignItems: 'center', justifyContent: 'center' }, stepper: { flexDirection: 'row', alignItems: 'center', gap: 2 }, diff --git a/mobile/src/features/overview/OverviewScreen.tsx b/mobile/src/features/overview/OverviewScreen.tsx index 0ea4614..a70cc78 100644 --- a/mobile/src/features/overview/OverviewScreen.tsx +++ b/mobile/src/features/overview/OverviewScreen.tsx @@ -33,7 +33,9 @@ import { import { NAV_ICONS } from '../../lib/navIcons' import { clock, dueDiff, dueLabel, periodTotal, startOfDay, until } from '../../lib/components/overview/time' import { ov, TI, Section, Quiet, Failed, Loading, Bar, Subhead, More } from './parts' -import { HabitRow } from './HabitRow' +import { GroupRow, HabitRow } from './HabitRow' +import { foldGroups, groupProgress, groupToggle, groupWords, habitTree, rowDone as habitRowDone } from '../../lib/habits/groups' +import { UndoLine, type UndoState } from '../todos/detail/bits' import { HabitMetricSection } from './MetricTile' import { openHabitDay, type DaySave } from './HabitDaySheet' import { goalsContext, habitMetricContext, habitsContext, scheduleContext, systemContext, tasksContext } from '../../lib/chat/about/context' @@ -254,15 +256,18 @@ export default function OverviewScreen() { } }, []) - const habitWrite = useCallback(async (habitId: string, fields: any) => { - if (habitBusy.has(habitId)) return + /** Log one habit-day; says whether it went through. */ + const habitWrite = useCallback(async (habitId: string, fields: any): Promise => { + if (habitBusy.has(habitId)) return false setHabitBusy((s) => new Set(s).add(habitId)) try { const payload = await logHabit({ id: habitId, ...fields }) setData((d: any) => ({ ...d, habits: payload })) + return true } catch (e: any) { if (e instanceof AuthError) onAuthError() else pushError(e?.message || 'Could not log that habit') + return false } finally { setHabitBusy((s) => { const n = new Set(s); n.delete(habitId); return n }) } @@ -278,6 +283,23 @@ export default function OverviewScreen() { const logValue = useCallback((h: any, value: number | null) => { if (habitDay && !h.linkedApp) habitWrite(h.id, { date: habitDay, value, complete: value !== null }) }, [habitDay, habitWrite]) + // A group's check marks its hand-logged sub-habits done, or clears them once all + // are; the line under the group puts the day back exactly. + const [groupUndo, setGroupUndo] = useState<(UndoState & { groupId: string }) | null>(null) + const dropGroupUndo = useCallback(() => setGroupUndo(null), []) + const logGroup = useCallback(async (group: any) => { + if (!habitDay || !data.habits || habitBusy.has(group.id)) return + const t = groupToggle(data.habits.habits || [], group.id, data.habits.entries || {}, habitDay) + if (!t.changes) { tap(); return } + if (t.complete) success(); else tap() + if (!(await habitWrite(group.id, { date: habitDay, complete: t.complete }))) return + setGroupUndo({ + id: Date.now(), + groupId: group.id, + text: groupWords(group.name, t, 0, 0).result, + action: { label: 'Undo', run: () => { void habitWrite(group.id, t.undo) } }, + }) + }, [habitDay, data.habits, habitBusy, habitWrite]) const openNote = useCallback((habit: any) => { if (!habitDay || habit.linkedApp) return openHabitDay({ @@ -337,10 +359,17 @@ export default function OverviewScreen() { const taskShown = (focus.length ? focus : upNext).slice(0, 6) // ---- habits ---------------------------------------------------------- - const entries = data.habits?.entries || {} - const habits: any[] = (data.habits?.habits || []).filter((h: any) => !h.archived && !isSyncedSleep(h)) - const habitsLeft = habits.filter((h) => periodTotal(h, entries, habitDay) < h.target && !(entries[habitDay]?.[h.id]?.count > 0)) - const habitsDoneToday = habits.length - habitsLeft.length + const rawEntries = data.habits?.entries || {} + const rawHabits: any[] = data.habits?.habits || [] + // Groups read as daily habits counting their sub-habits (lib/habits/groups.ts). + const folded = foldGroups(rawHabits, rawEntries, data.habits?.today) + const entries = folded.entries + const habits: any[] = folded.habits.filter((h: any) => !h.archived && !isSyncedSleep(h)) + // One row per top-level habit, a group's sub-habits under it; the counts are of rows. + const habitRows = habitTree(folded.habits).filter((r) => !isSyncedSleep(r.habit)) + // Done as the Habits page counts it (lib/habits/groups.ts rowDone), so the counts agree. + const habitsLeft = habitRows.filter((r) => !habitRowDone(rawHabits, r, rawEntries, habitDay)) + const habitsDoneToday = habitRows.length - habitsLeft.length const pinned = habits.filter((h) => h.metric?.pinned) // ---- goals ----------------------------------------------------------- @@ -388,7 +417,7 @@ export default function OverviewScreen() { if (awayNow) summary.push(`away: ${awayNow.label}`) if (data.cal) summary.push(remaining.length ? `${remaining.length} ${remaining.length === 1 ? 'event' : 'events'} left today` : 'No more events today') if (data.todos) summary.push(focus.length ? `${focus.length} ${focus.length === 1 ? 'task' : 'tasks'} due` : 'nothing due') - if (data.habits && habits.length) summary.push(habitsLeft.length ? `${habitsLeft.length} ${habitsLeft.length === 1 ? 'habit' : 'habits'} to go` : 'habits done') + if (data.habits && habitRows.length) summary.push(habitsLeft.length ? `${habitsLeft.length} ${habitsLeft.length === 1 ? 'habit' : 'habits'} to go` : 'habits done') const B = ({ children }: { children: React.ReactNode }) => {children} const attention: { key: string; icon: Tabler; text: React.ReactNode; tone: 'warn' | 'info'; to: NavTarget }[] = [] @@ -632,7 +661,7 @@ export default function OverviewScreen() {
habits.length ? habitsContext(habits, entries, habitDay, (h) => periodTotal(h, entries, habitDay)) : null} > @@ -641,21 +670,37 @@ export default function OverviewScreen() { : !habits.length ? No habits yet. Add one in Habits, or ask Totem. : ( - {habits.slice(0, 8).map((h, i) => ( - - ))} - {habits.length > 8 && } + {habitRows.slice(0, 8).map(({ habit: h, children }, i) => { + const row = (x: any, first: boolean, nested = false) => ( + + ) + if (!children.length) return row(h, i === 0) + const { done, total } = groupProgress(rawHabits, h.id, rawEntries, habitDay) + // Nothing for the check to write (all filled by apps, or nothing to clear): it rests. + const gt = groupToggle(rawHabits, h.id, rawEntries, habitDay) + return ( + + { void logGroup(h) }} /> + {children.map((c, j) => row(c, j === 0, true))} + {groupUndo?.groupId === h.id && ( + + )} + + ) + })} + {habitRows.length > 8 && } )}
diff --git a/mobile/src/features/productivity/HabitsView.tsx b/mobile/src/features/productivity/HabitsView.tsx index f89bcb7..2ab9e94 100644 --- a/mobile/src/features/productivity/HabitsView.tsx +++ b/mobile/src/features/productivity/HabitsView.tsx @@ -1,10 +1,12 @@ // Productivity → Habits, a full page under its own top bar (#180). The Today panel // (the day being answered, a bar that fills per habit, check-in and new), then one -// row per habit: tick today under the thumb, open the row for its history. The +// row per habit: tick today under the thumb, open the row for its history. A +// group (a habit with sub-habits, lib/habits/groups.ts) is one row whose card holds +// its sub-habits' rows; every view reads it through foldGroups. The // web's dialogs (new/edit habit, one day, a whole week or month, the morning // check-in) are formSheet routes under app/habit/*, sharing the payload through // features/habits/store. -import React, { useEffect, useMemo, useRef, useState } from 'react' +import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { RefreshControl, ScrollView, StyleSheet, View } from 'react-native' import Animated, { FadeIn, LinearTransition } from 'react-native-reanimated' import { router } from 'expo-router' @@ -18,9 +20,11 @@ import { Hi, ArchiveBoxIcon, ArrowPathIcon, ChevronDownIcon, ExclamationCircleIc import { logHabit, updateHabit } from '../../lib/api' import { pushToast } from '../../lib/toast' import { - APP_NAME, addDays, dayProgress, doneOn, isSyncedSleep, periodTotal, streakOf, withPending, type Habit, + APP_NAME, addDays, diffDays, doneOn, isSyncedSleep, periodTotal, rowsProgress, streakOf, wholeDays, withPending, type Habit, } from '../habits/logic' -import { addPending, loadHabits, mutate, useHabits } from '../habits/store' +import { foldGroups, groupProgress, groupToggle, groupWords, habitTree } from '../../lib/habits/groups' +import { addPending, addPendings, loadHabits, mutate, useHabits } from '../habits/store' +import { UndoLine, type UndoState } from '../todos/detail/bits' import HabitRow from '../habits/HabitRow' import TodayPanel from '../habits/TodayPanel' import { useCalm } from '../habits/motion' @@ -54,19 +58,28 @@ export default function HabitsView({ active: shown }: { active: boolean }) { const [open, setOpen] = useState(readOpen) const [showArchived, setShowArchived] = useState(false) const [pulling, setPulling] = useState(false) + // The line after a group's check was used, drawn in that group's card. + const [undo, setUndo] = useState<(UndoState & { groupId: string }) | null>(null) + const dropUndo = useCallback(() => setUndo(null), []) // Load whenever the page comes on screen, so a habit ticked off elsewhere (the // Overview, an agent) is current without a pull. useEffect(() => { if (shown) void loadHabits() }, [shown]) - const habits = data?.habits || [] - const active = habits.filter((h) => !h.archived && !isSyncedSleep(h)) + const habits = useMemo(() => data?.habits || [], [data?.habits]) const archived = habits.filter((h) => h.archived) const sleepHidden = habits.some((h) => !h.archived && isSyncedSleep(h)) const today = data?.today || '' const checkinDate = today ? addDays(today, -daysBack) : '' + // The day's entries as logged, with taps still on their way folded in: what every write reads. const entries = useMemo(() => withPending(data?.entries || {}, pending), [data?.entries, pending]) - const progress = useMemo(() => dayProgress(active, entries, checkinDate), [active, entries, checkinDate]) + // What the rows draw: each group a daily habit counting its sub-habits done. + const folded = useMemo(() => foldGroups(habits, entries, today), [habits, entries, today]) + const shownOf = useMemo(() => new Map(folded.habits.map((h) => [h.id, h])), [folded.habits]) + // One row per top-level habit, a group's sub-habits under it. + const rows = useMemo(() => habitTree(habits).filter((r) => !isSyncedSleep(r.habit)), [habits]) + const groupIds = useMemo(() => new Set(rows.filter((r) => r.children.length).map((r) => r.habit.id)), [rows]) + const progress = useMemo(() => rowsProgress(habits, rows, entries, checkinDate), [habits, rows, entries, checkinDate]) // One-tap logging, drawn before the bridge answers. A refusal takes the tap // back out and says why. A habit an app fills in never gets here. @@ -116,14 +129,42 @@ export default function HabitsView({ active: shown }: { active: boolean }) { if (finishes) success() }) + // A group's check marks every hand-logged sub-habit done, or clears them once all + // are. Drawn at once (each sub-habit's change as a tap in flight); the line under + // the group puts the day back exactly. + const logGroup = (group: Habit) => withBusy(group, async () => { + const date = checkinDate + const t = groupToggle(habits, group.id, entries, date) + // Nothing logged that day to clear (a group of weekly sub-habits met on other days). + if (!t.changes) { tap(); return } + const moves = Object.entries(t.next) + .map(([id, n]) => ({ key: `${id}:${date}`, delta: n - (entries[date]?.[id]?.count || 0) })) + .filter((m) => m.delta) + if (t.complete) success() + else tap() + addPendings(moves) + await mutate(() => logHabit({ id: group.id, date, complete: t.complete }), moves) + setUndo({ + id: Date.now(), + groupId: group.id, + text: groupWords(group.name, t, 0, 0).result, + action: { label: 'Undo', run: () => { mutate(() => logHabit(t.undo)).catch((e) => pushToast(e.message)) } }, + }) + }) + const openDay = (habit: Habit, date: string) => router.push({ pathname: '/habit/day', params: { id: habit.id, date } }) const openEdit = (habit: Habit) => router.push({ pathname: '/habit/edit', params: { id: habit.id } }) const openPeriod = (habit: Habit, p: { start: string; end: string; title: string }) => (habit.linkedApp ? openLinkedApp(habit) : router.push({ pathname: '/habit/period', params: { id: habit.id, ...p } })) - const chat = (habit: Habit) => data && chatAbout(() => habitContext(habit, data.entries, today, { - streak: streakOf(habit, data.entries, today), periodCount: periodTotal(habit, data.entries, today), - })) + const chat = (habit: Habit) => data && chatAbout(() => { + const shown = shownOf.get(habit.id) || habit + // A group's streak counts whole days, as its card does. + const streak = groupIds.has(habit.id) + ? streakOf({ ...shown, target: 1 }, wholeDays(shown, folded.entries), today) + : streakOf(shown, folded.entries, today) + return habitContext(shown, folded.entries, today, { streak, periodCount: periodTotal(shown, folded.entries, today) }) + }) const toggleOpen = (habit: Habit) => { tap() @@ -140,8 +181,15 @@ export default function HabitsView({ active: shown }: { active: boolean }) { }) .catch((e) => pushToast(e.message)) + const addSub = (group: Habit) => router.push({ pathname: '/habit/new', params: { parentId: group.id } }) + // Long-press on a row: everything else the row can do, as a native sheet. - const rowMenu = (habit: Habit) => showMenu([ + const rowMenu = (habit: Habit) => groupIds.has(habit.id) ? showMenu([ + { label: 'Edit group', onPress: () => openEdit(habit) }, + { label: 'Add a sub-habit', onPress: () => addSub(habit) }, + { label: 'Chat about this', onPress: () => chat(habit) }, + { label: 'Archive', onPress: () => void setArchived(habit, true) }, + ], { title: habit.name }) : showMenu([ { label: 'Edit habit', onPress: () => openEdit(habit) }, habit.linkedApp ? { label: `Open ${APP_NAME[habit.linkedApp]}`, onPress: () => openLinkedApp(habit) } @@ -150,6 +198,54 @@ export default function HabitsView({ active: shown }: { active: boolean }) { { label: 'Archive', onPress: () => void setArchived(habit, true) }, ], { title: habit.name }) + // A group's days are its sub-habits': picking one steps the page to that day. + const pickDay = (habit: Habit, date: string) => { + if (groupIds.has(habit.id)) { tap(); setDaysBack(Math.max(0, Math.min(MAX_DAYS_BACK, diffDays(today, date)))); return } + if (habit.linkedApp) openLinkedApp(habit) + else openDay(habit, date) + } + const pickPeriod = (habit: Habit, period: { start: string; end: string; title: string }) => { + if (!groupIds.has(habit.id)) openPeriod(habit, period) + } + + const card = (h: Habit, nested: boolean, children: Habit[] = []): React.ReactNode => { + const busy = Boolean(busyKeys[`${h.id}:${checkinDate}`]) + const p = children.length ? groupProgress(habits, h.id, entries, checkinDate) : null + const gt = children.length ? groupToggle(habits, h.id, entries, checkinDate) : null + return ( + { void logGroup(h) }, + children: children.map((c, i) => 0 && s.subRule}>{card(c, true)}), + undo: undo?.groupId === h.id ? : null, + } : undefined} + onToggle={toggleOpen} + onLog={(habit, delta) => logAt(habit, checkinDate, delta)} + onValue={logValue} + onNote={(habit) => openDay(habit, checkinDate)} + onEdit={openEdit} + onMore={rowMenu} + onChat={chat} + onPickDay={pickDay} + onPickPeriod={pickPeriod} + /> + ) + } + const refresh = async () => { setPulling(true); await loadHabits(); setPulling(false) } let body: React.ReactNode @@ -164,7 +260,7 @@ export default function HabitsView({ active: shown }: { active: boolean }) { void loadHabits()} style={{ marginTop: 6 }} /> ) - } else if (!active.length) { + } else if (!rows.length) { body = ( @@ -194,26 +290,7 @@ export default function HabitsView({ active: shown }: { active: boolean }) { onNew={() => router.push('/habit/new')} /> - {active.map((h) => ( - logAt(habit, checkinDate, delta)} - onValue={logValue} - onNote={(habit) => openDay(habit, checkinDate)} - onEdit={openEdit} - onMore={rowMenu} - onChat={chat} - onPickDay={(habit, date) => (habit.linkedApp ? openLinkedApp(habit) : openDay(habit, date))} - onPickPeriod={openPeriod} - /> - ))} + {rows.map((r) => card(r.habit, false, r.children))} {sleepHidden && ( Sleep syncs from WHOOP on its own and shows in Bushido. @@ -278,5 +355,6 @@ const s = StyleSheet.create({ archivedRow: { flexDirection: 'row', alignItems: 'center', gap: 8, paddingVertical: 8, paddingLeft: 14, paddingRight: 10 }, archivedName: { flex: 1, minWidth: 0, flexDirection: 'row', alignItems: 'center', gap: 8, minHeight: 44 }, rule: { borderTopWidth: 1, borderTopColor: colors.line }, + subRule: { borderTopWidth: 1, borderTopColor: colors.line }, dot: { width: 10, height: 10, borderRadius: 3 }, }) diff --git a/mobile/src/features/productivity/glance.test.mjs b/mobile/src/features/productivity/glance.test.mjs index cb362a1..ad61e6d 100644 --- a/mobile/src/features/productivity/glance.test.mjs +++ b/mobile/src/features/productivity/glance.test.mjs @@ -102,6 +102,30 @@ test('habits: Overview’s rule for done, without archived or WHOOP-synced ones' assert.equal(habitsGlance(null, NOW), null) // Yesterday's answer, read from disk the next morning, is not today's tally. assert.equal(habitsGlance({ ...payload, today: '2026-11-03' }, NOW), null) + // A daily habit with a target counts once it reaches it, as on the Habits page. + const water = { today: '2026-11-04', habits: [{ id: 'w', cadence: 'daily', target: 6 }], entries: { '2026-11-04': { w: { count: 3 } } } } + assert.deepEqual(habitsGlance(water, NOW), { done: 0, total: 1 }) +}) + +test('habits: a group is one row, done only once all its sub-habits are', () => { + const habits = [ + { id: 'g', cadence: 'daily', target: 1 }, + { id: 'g1', cadence: 'daily', target: 1, parentId: 'g' }, + { id: 'g2', cadence: 'weekly', target: 3, parentId: 'g' }, + { id: 'g3', cadence: 'daily', target: 1, parentId: 'g', archived: true }, // not counted in the group + { id: 'r', cadence: 'daily', target: 1 }, + ] + const day = (entries) => habitsGlance({ today: '2026-11-04', habits, entries }, NOW) + // One sub-habit of two: the group is not done, though something in it was logged. + assert.deepEqual(day({ '2026-11-04': { g1: { count: 1 }, r: { count: 1 } } }), { done: 1, total: 2 }) + // A weekly sub-habit logged today counts, as on the Habits page. + assert.deepEqual(day({ '2026-11-04': { g1: { count: 1 }, g2: { count: 1 } } }), { done: 1, total: 2 }) + assert.deepEqual(day({ '2026-11-04': { g1: { count: 1 }, g2: { count: 1 }, r: { count: 1 } } }), { done: 2, total: 2 }) + // A group's own old entry does not make it done. + assert.deepEqual(day({ '2026-11-04': { g: { count: 1 } } }), { done: 0, total: 2 }) + // A sub-habit whose group is archived is a row of its own. + const orphan = habits.map((h) => (h.id === 'g' ? { ...h, archived: true } : h)) + assert.deepEqual(habitsGlance({ today: '2026-11-04', habits: orphan, entries: { '2026-11-04': { g1: { count: 1 } } } }, NOW), { done: 1, total: 3 }) }) test('goals: done of those still in play, only for the week it is', () => { diff --git a/mobile/src/features/productivity/glance.ts b/mobile/src/features/productivity/glance.ts index 27e0c07..a473b0c 100644 --- a/mobile/src/features/productivity/glance.ts +++ b/mobile/src/features/productivity/glance.ts @@ -7,7 +7,7 @@ // a write made on Overview reaches a tool's store only when that page next loads, // and a calendar answer carries no date range, so a days-old one can't be told apart. // Pure, so glance.test.mjs can run it. -import { periodTotal } from '../../lib/components/overview/time' +import { habitTree, rowDone } from '../../lib/habits/groups' /** Local "YYYY-MM-DD" for a moment. */ export function dayKeyOf(d: Date): string { @@ -87,16 +87,22 @@ export function calendarGlance(payload: any, now: Date): CalendarGlance | null { export interface RatioGlance { done: number; total: number } -/** Habits done today, of those the owner logs by hand (the WHOOP sleep habit fills itself). */ +/** + * Habits done today, of those the owner logs by hand (the WHOOP sleep habit fills + * itself), counted as rows: a group (lib/habits/groups.ts) is one, done once every + * one of its sub-habits is. + */ export function habitsGlance(payload: any, now: Date): RatioGlance | null { if (!Array.isArray(payload?.habits)) return null // The bridge names its own today; an answer from an earlier day is not today's tally. if (payload.today && payload.today !== dayKeyOf(now)) return null const day: string = payload.today || dayKeyOf(now) const entries = payload.entries || {} - const habits = payload.habits.filter((h: any) => h && !h.archived && h.metric?.source !== 'whoop-sleep') - const left = habits.filter((h: any) => periodTotal(h, entries, day) < h.target && !(entries[day]?.[h.id]?.count > 0)) - return { done: habits.length - left.length, total: habits.length } + const all = payload.habits.filter(Boolean) + const rows = habitTree(all).filter((r) => r.habit.metric?.source !== 'whoop-sleep') + // The Habits page's rule (rowDone): a daily habit at its target, a group with every sub-habit done. + const done = rows.filter((row) => rowDone(all, row, entries, day)).length + return { done, total: rows.length } } /** This week's goals done, of those still in play; nothing if the answer is for another week. */ diff --git a/mobile/src/lib/habitCheckin.ts b/mobile/src/lib/habitCheckin.ts index f8ce129..34ea33a 100644 --- a/mobile/src/lib/habitCheckin.ts +++ b/mobile/src/lib/habitCheckin.ts @@ -10,6 +10,8 @@ export interface CheckinItem { /** The day the answer is logged against. */ date: string part: 'yesterday' | 'today' + /** The group a sub-habit sits in, so the sheet can say "Nightly routine · Stretch". */ + group?: string } export function shiftDate(iso: string, days: number): string { @@ -86,22 +88,29 @@ export function askable(h: any): boolean { export function checkinItems(payload: any, includeAnswered = false): { today: string; yesterday: string; items: CheckinItem[] } { const today: string = payload?.today || '' const yesterday = today ? shiftDate(today, -1) : '' - const habits: any[] = (payload?.habits || []).filter(askable) + const all: any[] = payload?.habits || [] + // A group (a habit with active sub-habits) has no check of its own: its sub-habits are asked. + const groupIds = new Set(all.filter((h) => !h.archived && h.parentId).map((h) => h.parentId)) + const names = new Map(all.map((h) => [h.id, h.name])) + const habits: any[] = all.filter((h) => askable(h) && !groupIds.has(h.id)) const entries = payload?.entries || {} const items: CheckinItem[] = [] if (!today) return { today, yesterday, items } + const item = (h: any, date: string, part: 'yesterday' | 'today'): CheckinItem => ( + h.parentId && names.has(h.parentId) ? { habit: h, date, part, group: names.get(h.parentId) } : { habit: h, date, part } + ) for (const h of habits) { // A morning habit belongs to its own morning, asked below; yesterday's was yesterday's question. if (h.when === 'morning') continue if (String(h.createdAt || '').slice(0, 10) > yesterday) continue // A weekly or monthly habit is asked about until its quota for the period is met. if (!stillOwed(h, entries, yesterday)) continue - if (includeAnswered || !answered(entries, yesterday, h.id)) items.push({ habit: h, date: yesterday, part: 'yesterday' }) + if (includeAnswered || !answered(entries, yesterday, h.id)) items.push(item(h, yesterday, 'yesterday')) } for (const h of habits) { if (h.when !== 'morning') continue if (!stillOwed(h, entries, today)) continue - if (includeAnswered || !answered(entries, today, h.id)) items.push({ habit: h, date: today, part: 'today' }) + if (includeAnswered || !answered(entries, today, h.id)) items.push(item(h, today, 'today')) } return { today, yesterday, items } } diff --git a/mobile/src/lib/habits/groups.test.mjs b/mobile/src/lib/habits/groups.test.mjs new file mode 100644 index 0000000..b6ed848 --- /dev/null +++ b/mobile/src/lib/habits/groups.test.mjs @@ -0,0 +1,142 @@ +// Sub-habits (web/src/habits/groups.ts, mirrored byte for byte here). Behaviour is +// tested on the app's copy, which node loads with its types stripped. +// Run with `node --test mobile/src/lib/habits/groups.test.mjs` (also in the root test). +import test from 'node:test' +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { flattenTree, foldGroups, groupProgress, groupToggle, groupWords, habitTree, handLogged, isGroup, rowDone, subHabitDone } from './groups.ts' + +const repo = join(dirname(fileURLToPath(import.meta.url)), '../../../..') +const read = (path) => readFileSync(join(repo, path), 'utf8') + +test('the app’s copy is the web’s, byte for byte, and imports nothing', () => { + const web = read('web/src/habits/groups.ts') + assert.equal(read('mobile/src/lib/habits/groups.ts'), web, 'mobile/src/lib/habits/groups.ts has drifted from web/src/habits/groups.ts') + assert.doesNotMatch(web, /^\s*import\b/m) +}) + +const h = (id, over = {}) => ({ id, archived: false, cadence: 'daily', target: 1, parentId: null, ...over }) +const HABITS = [ + h('night'), + h('sleep', { parentId: 'night' }), + h('screens', { parentId: 'night' }), + h('read'), + h('water', { parentId: 'night', target: 4 }), + h('old', { parentId: 'night', archived: true }), + h('orphan', { parentId: 'gone' }), +] + +test('habitTree: groups hold their sub-habits in list order; archived and orphaned ones are handled', () => { + const rows = habitTree(HABITS) + assert.deepEqual(rows.map((r) => [r.habit.id, r.children.map((c) => c.id)]), [ + ['night', ['sleep', 'screens', 'water']], + ['read', []], + ['orphan', []], + ]) + assert.deepEqual(flattenTree(rows), ['night', 'sleep', 'screens', 'water', 'read', 'orphan']) + assert.equal(isGroup(HABITS, 'night'), true) + assert.equal(isGroup(HABITS, 'read'), false) + assert.equal(isGroup([h('a'), h('b', { parentId: 'a', archived: true })], 'a'), false, 'only archived sub-habits: not a group') +}) + +test('foldGroups: a group reads as a daily habit counting its sub-habits done', () => { + const entries = { + '2026-11-24': { sleep: { count: 1 }, screens: { count: 1 }, water: { count: 4 }, night: { count: 9 } }, + '2026-11-25': { sleep: { count: 1 }, water: { count: 2 } }, + '2026-11-26': { sleep: { count: 0, skipped: true }, screens: { count: 0, skipped: true }, water: { count: 0, skipped: true } }, + '2026-11-27': { read: { count: 1 } }, + } + const { habits, entries: folded } = foldGroups(HABITS, entries) + const night = habits.find((x) => x.id === 'night') + assert.equal(night.target, 3) + assert.equal(night.cadence, 'daily') + assert.deepEqual(folded['2026-11-24'].night, { count: 3 }, 'its own old entry is replaced') + assert.deepEqual(folded['2026-11-25'].night, { count: 1 }, 'water at 2 of 4 is not done') + assert.deepEqual(folded['2026-11-26'].night, { count: 0, skipped: true }) + assert.equal(folded['2026-11-27'].night, undefined) + assert.deepEqual(groupProgress(HABITS, 'night', entries, '2026-11-25'), { done: 1, total: 3 }) + assert.strictEqual(foldGroups([h('a')], entries).entries, entries, 'nothing to fold: same object') +}) + +test('subHabitDone: a weekly sub-habit is done on a logged day or once its quota is met', () => { + const gym = h('gym', { cadence: 'weekly', target: 2 }) + const entries = { '2026-11-23': { gym: { count: 1 } }, '2026-11-25': { gym: { count: 1 } } } + assert.equal(subHabitDone(gym, entries, '2026-11-23'), true) + assert.equal(subHabitDone(gym, {}, '2026-11-24'), false) + assert.equal(subHabitDone(gym, entries, '2026-11-26'), true, 'quota met for the week') +}) + +test('groupToggle: marks every hand-logged sub-habit while any is open, clears them once all are done', () => { + const habits = [h('g'), h('a', { parentId: 'g' }), h('b', { parentId: 'g', target: 3 }), h('app', { parentId: 'g', linkedApp: 'krakatoa' })] + let t = groupToggle(habits, 'g', { d: { a: { count: 1 } } }, 'd') + assert.equal(t.complete, true) + assert.deepEqual(t.next, { a: 1, b: 3 }) + assert.deepEqual(t.undo, { id: 'g', date: 'd', counts: { a: 1, b: 0 } }) + t = groupToggle(habits, 'g', { d: { a: { count: 1 }, b: { count: 3 } } }, 'd') + assert.equal(t.complete, false) + assert.deepEqual(t.next, { a: 0, b: 0 }) +}) + +test('groupToggle: leaves a met weekly quota alone, says when a tap would change nothing, skips app- and WHOOP-filled ones', () => { + const habits = [ + h('g'), + h('gym', { parentId: 'g', cadence: 'weekly', target: 1 }), + h('sleep', { parentId: 'g', metric: { source: 'whoop-sleep' } }), + h('food', { parentId: 'g', linkedApp: 'krakatoa' }), + ] + // Gym met on Monday; Wednesday's tap has nothing of its own to clear. + const met = { '2026-11-23': { gym: { count: 1 } } } + const t = groupToggle(habits, 'g', met, '2026-11-25') + assert.equal(t.complete, false) + assert.equal(t.changes, false) + assert.deepEqual(t.next, { gym: 0 }) + // Not met yet: marking adds one. + assert.deepEqual(groupToggle(habits, 'g', {}, '2026-11-25').next, { gym: 1 }) + assert.equal(handLogged(habits[2]), false) + assert.equal(handLogged(habits[3]), false) + assert.equal(groupToggle([h('a'), h('b', { parentId: 'a', linkedApp: 'bushido' })], 'a', {}, 'd').loggable, false) +}) + +test('rowDone: a daily habit at its target, a group once every sub-habit is', () => { + const habits = [h('g'), h('a', { parentId: 'g' }), h('w', { target: 6 })] + const rows = habitTree(habits) + assert.equal(rowDone(habits, rows[0], { d: { a: { count: 1 } } }, 'd'), true) + assert.equal(rowDone(habits, rows[1], { d: { w: { count: 3 } } }, 'd'), false) + assert.equal(rowDone(habits, rows[1], { d: { w: { count: 6 } } }, 'd'), true) +}) + +test('groupToggle: the undo puts back a check-in "No"', () => { + const habits = [h('g'), h('a', { parentId: 'g' }), h('b', { parentId: 'g' })] + const t = groupToggle(habits, 'g', { d: { a: { count: 0, skipped: true } } }, 'd') + assert.deepEqual(t.undo, { id: 'g', date: 'd', counts: { a: 0, b: 0 }, skips: ['a'] }) +}) + +test('foldGroups: a day done only by a met weekly quota shows on the group, through today', () => { + const habits = [h('g'), h('gym', { parentId: 'g', cadence: 'weekly', target: 1 }), h('walk', { parentId: 'g', cadence: 'weekly', target: 1 })] + const entries = { '2026-11-23': { gym: { count: 1 } }, '2026-11-24': { walk: { count: 1 } } } + const { entries: folded } = foldGroups(habits, entries, '2026-11-26') + assert.deepEqual(folded['2026-11-26'].g, { count: 2 }, 'Thursday: both quotas met, no entry of its own') + assert.deepEqual(folded['2026-11-23'].g, { count: 2 }, 'a met quota counts on every day of its week, as doneOn does') + assert.equal(folded['2026-11-27'], undefined, 'nothing past today') + // The first entry is Tuesday the 24th; its week starts Monday the 23rd. + const late = foldGroups(habits, { '2026-11-25': { gym: { count: 1 } }, '2026-11-24': { walk: { count: 1 } } }, '2026-11-26').entries + assert.deepEqual(late['2026-11-23'].g, { count: 2 }, 'Monday, before either log: the week quotas are met') + assert.equal(foldGroups(habits, entries).entries['2026-11-26'], undefined, 'without today, entry days only') +}) + +test('handLogged: the bridge’s autoFilled mark wins', () => { + assert.equal(handLogged(h('x', { autoFilled: true })), false) +}) + +test('groupWords: never promises "done" when an app still fills a sub-habit', () => { + const habits = [h('g'), h('a', { parentId: 'g' }), h('app', { parentId: 'g', linkedApp: 'krakatoa' })] + const t = groupToggle(habits, 'g', {}, 'd') + assert.equal(t.others, 1) + const w = groupWords('Morning', t, 0, 2) + assert.match(w.action, /^Tick the rest of Morning, 0 of 2 so far; 1 fills in from its app$/) + assert.doesNotMatch(w.result, /done/) + assert.equal(groupWords('Morning', { complete: true, others: 0 }, 1, 2).result, 'Marked Morning done.') + assert.equal(groupWords('Morning', { complete: false, others: 0 }, 2, 2).result, 'Cleared Morning.') +}) diff --git a/mobile/src/lib/habits/groups.ts b/mobile/src/lib/habits/groups.ts new file mode 100644 index 0000000..6b31f41 --- /dev/null +++ b/mobile/src/lib/habits/groups.ts @@ -0,0 +1,235 @@ +// Sub-habits: one copy for the web and the iPhone app. This file is mirrored byte +// for byte to mobile/src/lib/habits/groups.ts (mobile/src/lib/habits/groups.test.mjs +// checks it), so it imports nothing and touches no DOM or React Native. +// +// A habit may sit under one other habit (`parentId`, one level deep, checked by the +// bridge). A habit with sub-habits is a group: it has no check of its own, and its +// day is done when every sub-habit's is. Rather than teach every streak, strip, +// grid and progress bar about groups, `foldGroups` hands each group a made-up entry +// per day (`count` = sub-habits done that day) and a daily target of its sub-habit +// count, so a group reads as an ordinary daily habit everywhere it is drawn: +// full when all are done, shaded by how many, a streak of complete days. Only the +// writes differ: a group is logged with `complete` or `counts`, never a delta +// (bridge doLogHabitRecord), and the check-in asks its sub-habits, not it. + +export interface GroupableHabit { + id: string + parentId?: string | null + archived: boolean + cadence: 'daily' | 'weekly' | 'monthly' + target: number + linkedApp?: string | null + metric?: { source?: string } | null + /** Set by the bridge on a habit an app or the WHOOP sync fills (its fallback id included). */ + autoFilled?: boolean +} + +export interface GroupableEntry { count: number; skipped?: boolean } +export type GroupableEntries = Record> + +/** A row as lists draw it: a habit and, for a group, its sub-habits in order. */ +export interface HabitNode { habit: H; children: H[] } + +const toDate = (iso: string): Date => { + const [y, m, d] = iso.split('-').map(Number) + return new Date(y, m - 1, d) +} +const toISO = (d: Date): string => + `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}` +const addDays = (iso: string, n: number): string => { + const d = toDate(iso) + d.setDate(d.getDate() + n) + return toISO(d) +} +// Weeks run Monday–Sunday, as everywhere else in the habit tracker. +const weekStartOf = (iso: string): string => addDays(iso, -((toDate(iso).getDay() + 6) % 7)) + +/** The active sub-habits of `id`, in list order. */ +export function subHabitsOf(habits: H[], id: string): H[] { + return habits.filter((h) => !h.archived && h.parentId === id) +} + +/** Whether `habit` is a group: it has at least one active sub-habit. */ +export function isGroup(habits: H[], habit: H | string): boolean { + const id = typeof habit === 'string' ? habit : habit.id + return habits.some((h) => !h.archived && h.parentId === id) +} + +/** + * The active habits as rows, in list order: each group with its sub-habits under it, + * ungrouped habits on their own. A sub-habit whose group is missing or archived is a + * row of its own (the bridge already sends those with no parent). + */ +export function habitTree(habits: H[]): HabitNode[] { + const active = habits.filter((h) => !h.archived) + const ids = new Set(active.map((h) => h.id)) + const rows: HabitNode[] = [] + for (const h of active) { + if (h.parentId && ids.has(h.parentId)) continue + rows.push({ habit: h, children: active.filter((c) => c.parentId === h.id) }) + } + return rows +} + +/** The ids to send to POST /api/habits/reorder after moving top-level rows: each group's sub-habits follow it. */ +export function flattenTree(rows: HabitNode[]): string[] { + return rows.flatMap((r) => [r.habit.id, ...r.children.map((c) => c.id)]) +} + +function periodTotal(h: GroupableHabit, entries: GroupableEntries, date: string): number { + if (h.cadence === 'weekly') { + const start = weekStartOf(date) + let t = 0 + for (let i = 0; i < 7; i++) t += entries[addDays(start, i)]?.[h.id]?.count || 0 + return t + } + if (h.cadence === 'monthly') { + const ym = date.slice(0, 7) + let t = 0 + for (const [d, day] of Object.entries(entries)) if (d.startsWith(ym)) t += day[h.id]?.count || 0 + return t + } + return entries[date]?.[h.id]?.count || 0 +} + +/** + * Whether a sub-habit counts as done on `date`: a daily one at its target that day; + * a weekly or monthly one on a day it was logged, or once its period's quota is met. + */ +export function subHabitDone(h: GroupableHabit, entries: GroupableEntries, date: string): boolean { + const count = entries[date]?.[h.id]?.count || 0 + if (h.cadence === 'daily') return count >= Math.max(1, h.target) + return count > 0 || periodTotal(h, entries, date) >= Math.max(1, h.target) +} + +/** Ticked by hand: not filled in by an app or by the WHOOP sleep sync, so a group's check may write it. */ +export function handLogged(h: GroupableHabit): boolean { + return !h.autoFilled && !h.linkedApp && h.metric?.source !== 'whoop-sleep' +} + +/** + * Whether a row is done on `date`: a group once every sub-habit is, any other + * habit as subHabitDone says. Every count of "N of M done" uses this, so the + * Habits page, the Overview and the app's hub tile agree. + */ +export function rowDone(habits: H[], row: HabitNode, entries: GroupableEntries, date: string): boolean { + if (!row.children.length) return subHabitDone(row.habit, entries, date) + const { done, total } = groupProgress(habits, row.habit.id, entries, date) + return total > 0 && done >= total +} + +/** How many of a group's sub-habits are done on `date`, of how many. */ +export function groupProgress(habits: H[], groupId: string, entries: GroupableEntries, date: string): { done: number; total: number } { + const subs = subHabitsOf(habits, groupId) + return { done: subs.filter((s) => subHabitDone(s, entries, date)).length, total: subs.length } +} + +/** + * The payload as every view reads it. Each group becomes a daily habit whose target + * is its sub-habit count, and gets one entry per day it has anything to show: `count` + * sub-habits done (subHabitDone, so a weekly one counts on every day its quota is + * met), `skipped` when every sub-habit was answered and none was done. Pass the + * bridge's `today` as `through` so a day done only by a met quota, with no entry of + * its own, still shows. A group's own entries in the file (from before it had + * sub-habits) are replaced. Returns the same objects when there are no groups. + */ +export function foldGroups(habits: H[], entries: E, through?: string): { habits: H[]; entries: E } { + const groups = habits.filter((h) => !h.archived && isGroup(habits, h)) + if (!groups.length) return { habits, entries } + const subsOf = new Map(groups.map((g) => [g.id, subHabitsOf(habits, g.id)])) + const folded = habits.map((h) => { + const subs = subsOf.get(h.id) + return subs ? { ...h, cadence: 'daily' as const, target: subs.length } : h + }) + // Days a met weekly or monthly quota can complete without an entry: from the period + // holding the first entry of such a sub-habit to `through`. + const dates = new Set(Object.keys(entries)) + const periodic = new Set(groups.flatMap((g) => subsOf.get(g.id)!.filter((s) => s.cadence !== 'daily').map((s) => s.id))) + const firsts = Object.keys(entries).filter((d) => Object.keys(entries[d]).some((id) => periodic.has(id))).sort() + // From the start of that entry's week or month, whichever is earlier: a quota met + // on Wednesday completes the Monday and Tuesday before it too. + const from = firsts.length ? [weekStartOf(firsts[0]), `${firsts[0].slice(0, 7)}-01`].sort()[0] : '' + if (through && from) for (let d = from; d <= through; d = addDays(d, 1)) dates.add(d) + // subHabitDone, with each week's or month's total worked out once: a year of days + // otherwise re-adds the same period for every day of it. + const totals = new Map() + const doneThen = (s: GroupableHabit, date: string): boolean => { + const count = entries[date]?.[s.id]?.count || 0 + if (s.cadence === 'daily') return count >= Math.max(1, s.target) + if (count > 0) return true + const key = `${s.id}|${s.cadence === 'weekly' ? weekStartOf(date) : date.slice(0, 7)}` + if (!totals.has(key)) totals.set(key, periodTotal(s, entries, date)) + return totals.get(key)! >= Math.max(1, s.target) + } + const out: GroupableEntries = {} + for (const date of dates) { + const day = entries[date] || {} + const next: Record = { ...day } + for (const g of groups) { + delete next[g.id] + const subs = subsOf.get(g.id)! + const done = subs.filter((s) => doneThen(s, date)).length + if (!done && !subs.some((s) => day[s.id])) continue + const allNo = !done && subs.every((s) => day[s.id]?.skipped) + next[g.id] = allNo ? { count: 0, skipped: true } : { count: done } + } + if (Object.keys(next).length) out[date] = next + } + return { habits: folded, entries: out as E } +} + +/** + * What logging a group's check does on `date`: mark every hand-logged sub-habit done + * when any is still open, else clear what they logged that day. `complete` is also + * what the check says it will do, so its label and its tap never disagree. A weekly or monthly + * sub-habit whose quota is already met is left as it is (the bridge does the same). + * `undo` is the body that puts the day back; `changes` is false when the tap would + * write nothing, and `loggable` false when no sub-habit is ticked by hand. + */ +export function groupToggle(habits: H[], groupId: string, entries: GroupableEntries, date: string): { + complete: boolean + /** POST /api/habits/log body that undoes this tap, a check-in "No" included. */ + undo: { id: string; date: string; counts: Record; skips?: string[] } + /** The counts the tap leaves, per hand-logged sub-habit, for drawing it at once. */ + next: Record + changes: boolean + loggable: boolean + /** Sub-habits an app or the WHOOP sync fills, which the tap leaves alone. */ + others: number +} { + const subs = subHabitsOf(habits, groupId).filter(handLogged) + const complete = subs.some((s) => !subHabitDone(s, entries, date)) + const counts: Record = {} + const next: Record = {} + for (const s of subs) { + const have = entries[date]?.[s.id]?.count || 0 + const met = s.cadence !== 'daily' && periodTotal(s, entries, date) >= Math.max(1, s.target) + counts[s.id] = have + next[s.id] = complete ? Math.max(have, s.cadence === 'daily' ? Math.max(1, s.target) : met ? have : 1) : 0 + } + const changes = subs.some((s) => next[s.id] !== counts[s.id]) + const skips = subs.filter((s) => !counts[s.id] && entries[date]?.[s.id]?.skipped).map((s) => s.id) + const undo = skips.length ? { id: groupId, date, counts, skips } : { id: groupId, date, counts } + const others = subHabitsOf(habits, groupId).length - subs.length + return { complete, undo, next, changes, loggable: subs.length > 0, others } +} + +/** + * The words for a group's check, one copy for every screen: what a tap will do, and + * what it did. When some sub-habits fill in from their apps, both say so, so a tap + * that leaves the group at 1 of 2 never claims it was marked done. + */ +export function groupWords(name: string, t: { complete: boolean; others: number; loggable?: boolean; changes?: boolean }, done: number, total: number): { action: string; result: string } { + const apps = t.others === 1 ? 'its app' : 'their apps' + if (t.loggable === false) return { action: `${name}: ${done} of ${total} done, filled in by ${apps}`, result: '' } + // Done by quotas met on other days: nothing of that day's to clear. + if (!t.complete && t.changes === false) { + return { action: done >= total ? `${name}: all ${total} done` : `${name}: ${done} of ${total} done; ${t.others} fill${t.others === 1 ? 's' : ''} in from ${apps}`, result: '' } + } + if (!t.complete) return { action: `${name}: ${done} of ${total} done. Clear what was ticked`, result: `Cleared ${name}.` } + if (!t.others) return { action: `Mark all of ${name} done, ${done} of ${total} so far`, result: `Marked ${name} done.` } + return { + action: `Tick the rest of ${name}, ${done} of ${total} so far; ${t.others} fill${t.others === 1 ? 's' : ''} in from ${apps}`, + result: `Ticked ${name}; ${t.others} still fill${t.others === 1 ? 's' : ''} in from ${apps}.`, + } +} diff --git a/package.json b/package.json index beb0d9d..224ee8a 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,7 @@ "approval-code": "node auth/approval-code-cli.mjs", "build": "node scripts/pnpm.mjs --dir web run build", "postinstall": "node scripts/pnpm.mjs --dir web install", - "test": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON --test mcp-gateway.test.mjs auth/*.test.mjs ai/*.test.mjs providers/*.test.mjs ai-usage/*.test.mjs jobs/*.test.mjs notify/*.test.mjs skills/*.test.mjs terminal/*.test.mjs logs/*.test.mjs whoop/*.test.mjs strava/*.test.mjs camera/*.test.mjs todos/*.test.mjs todos/connectors/*.test.mjs goals/*.test.mjs lists/*.test.mjs recs/*.test.mjs away/*.test.mjs journal/*.test.mjs chat/*.test.mjs connections/*.test.mjs totems/*.test.mjs browser/*.test.mjs search/*.test.mjs scripts/*.test.mjs apple/*.test.mjs screen/*.test.mjs gmail/*.test.mjs dev/*.test.mjs fleet/*.test.mjs cliproxy/*.test.mjs sources/*.test.mjs http/*.test.mjs drive/*.test.mjs linkedin/*.test.mjs mobile/src/lib/*.test.mjs mobile/src/lib/*/*.test.mjs mobile/src/shell/*.test.mjs mobile/src/features/*/*.test.mjs mobile/src/features/*/*/*.test.mjs", + "test": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON --test mcp-gateway.test.mjs auth/*.test.mjs ai/*.test.mjs providers/*.test.mjs ai-usage/*.test.mjs jobs/*.test.mjs notify/*.test.mjs skills/*.test.mjs terminal/*.test.mjs logs/*.test.mjs whoop/*.test.mjs strava/*.test.mjs camera/*.test.mjs habits/*.test.mjs todos/*.test.mjs todos/connectors/*.test.mjs goals/*.test.mjs lists/*.test.mjs recs/*.test.mjs away/*.test.mjs journal/*.test.mjs chat/*.test.mjs connections/*.test.mjs totems/*.test.mjs browser/*.test.mjs search/*.test.mjs scripts/*.test.mjs apple/*.test.mjs screen/*.test.mjs gmail/*.test.mjs dev/*.test.mjs fleet/*.test.mjs cliproxy/*.test.mjs sources/*.test.mjs http/*.test.mjs drive/*.test.mjs linkedin/*.test.mjs mobile/src/lib/*.test.mjs mobile/src/lib/*/*.test.mjs mobile/src/shell/*.test.mjs mobile/src/features/*/*.test.mjs mobile/src/features/*/*/*.test.mjs", "test:watch": "node --test --watch jobs/*.test.mjs skills/*.test.mjs terminal/*.test.mjs", "service:start": "systemctl --user start assistant-bridge", "service:stop": "systemctl --user stop assistant-bridge", diff --git a/web/src/calendar/agenda.test.ts b/web/src/calendar/agenda.test.ts new file mode 100644 index 0000000..fa84fa4 --- /dev/null +++ b/web/src/calendar/agenda.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest' +import { agendaDays, compactTitle, rangeTitle } from './agenda' + +const at = (y: number, m: number, d: number, h = 0, min = 0) => new Date(y, m - 1, d, h, min) + +describe('calendar titles', () => { + it('names a week inside one month without Intl’s "(day: 28)"', () => { + const title = rangeTitle('week', at(2026, 11, 25)) + expect(title).not.toMatch(/day:/) + expect(title).toMatch(/22 – 28, 2026$/) + }) + it('names a week across months and years in full', () => { + expect(rangeTitle('week', at(2026, 12, 30))).toMatch(/27, 2026 – Jan 2, 2027$/) + }) + it('keeps the phone title short and drops this year', () => { + expect(compactTitle('week', at(2026, 11, 25), at(2026, 11, 25))).toMatch(/22 – 28$/) + expect(compactTitle('month', at(2027, 1, 5), at(2026, 11, 25))).toMatch(/2027/) + }) +}) + +describe('agenda days', () => { + const now = at(2026, 11, 25, 10, 0) + const range: [Date, Date] = [at(2026, 11, 25), at(2026, 12, 9)] + it('always heads today and tomorrow, and a day away', () => { + const days = agendaDays([], [{ id: 'a', start: '2026-11-28', end: '2026-11-28', label: 'Trip', kind: 'trip' }], range, now) + expect(days.map((d) => d.heading).slice(0, 2)).toEqual(['Today', 'Tomorrow']) + expect(days[2].away?.label).toBe('Trip') + }) + it('dims what is over and puts the now line before the next event', () => { + const events = [ + { id: '1', title: 'Standup', start: at(2026, 11, 25, 9).toISOString(), end: at(2026, 11, 25, 9, 30).toISOString() }, + { id: '2', title: 'Review', start: at(2026, 11, 25, 13).toISOString(), end: at(2026, 11, 25, 14).toISOString() }, + ] + const [today] = agendaDays(events, [], range, now) + expect(today.events.map((e) => e.past)).toEqual([true, false]) + expect(today.nowAt).toBe(1) + }) +}) diff --git a/web/src/calendar/agenda.ts b/web/src/calendar/agenda.ts new file mode 100644 index 0000000..187bee8 --- /dev/null +++ b/web/src/calendar/agenda.ts @@ -0,0 +1,136 @@ +// The calendar's agenda days and toolbar titles, as the iPhone app builds them +// (mobile/src/features/calendar/agenda.ts and time.ts). Pure, so vitest runs it. +// +// An event goes under the day it starts, or under the range's first day when it +// started before. Today and tomorrow always get a heading when they are in range, +// even with nothing on them ("Nothing scheduled" is an answer), and so does any day +// away (being away is the news). Today's finished events are marked past, and +// `nowAt` says where the now line goes among them. +import { awayOn, dayKey, type AwaySpan } from '../away' + +export type CalViewId = 'day' | 'workweek' | 'week' | 'month' | 'year' | 'agenda' +export const VIEW_IDS: CalViewId[] = ['day', 'workweek', 'week', 'month', 'year', 'agenda'] + +export const parseDate = (s: string | number | Date): Date => { + if (typeof s === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(s)) { + const [y, m, d] = s.split('-').map(Number) + return new Date(y, m - 1, d) + } + return new Date(s) +} +const startOfDay = (d: Date) => { const x = new Date(d); x.setHours(0, 0, 0, 0); return x } +const addDays = (d: Date, n: number) => { const x = new Date(d); x.setDate(x.getDate() + n); return x } +const sameDay = (a: Date, b: Date) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate() +const startOfWeek = (d: Date, weekStart: number) => { + const x = startOfDay(d) + x.setDate(x.getDate() - ((x.getDay() - weekStart + 7) % 7)) + return x +} + +export interface AgendaEvent { + ev: any + /** Over: an earlier day's, or today's that has ended. */ + past: boolean + /** Happening now. */ + ongoing: boolean +} + +export interface AgendaDay { + key: string + date: Date + heading: string + today: boolean + away: AwaySpan | null + events: AgendaEvent[] + /** Today only: the index the now line goes before (events.length = after all). -1 for none. */ + nowAt: number +} + +export function dayHeading(d: Date, now = new Date()): string { + if (sameDay(d, now)) return 'Today' + if (sameDay(d, addDays(now, 1))) return 'Tomorrow' + return d.toLocaleDateString([], { weekday: 'long' }) +} + +const order = (a: any, b: any) => { + if (Boolean(a.allDay) !== Boolean(b.allDay)) return a.allDay ? -1 : 1 + const s = +parseDate(a.start) - +parseDate(b.start) + return s || String(a.title ?? '').localeCompare(String(b.title ?? '')) +} + +export function agendaDays(events: any[], away: AwaySpan[], range: [Date, Date], now = new Date()): AgendaDay[] { + const [from, to] = range + const byKey = new Map() + const ensure = (d: Date) => { + const key = dayKey(d) + if (!byKey.has(key)) byKey.set(key, []) + return byKey.get(key)! + } + const first = startOfDay(from) + for (const ev of events) { + const start = parseDate(ev.start) + ensure(start < first ? first : start).push(ev) + } + for (let d = first; d < to; d = addDays(d, 1)) { + if (awayOn(away, dayKey(d))) ensure(d) + } + const today = startOfDay(now) + for (const d of [today, addDays(today, 1)]) if (d >= first && d < to) ensure(d) + + const todayKey = dayKey(now) + return [...byKey.keys()].sort().map((key) => { + const [y, m, dd] = key.split('-').map(Number) + const date = new Date(y, m - 1, dd) + const isToday = key === todayKey + const before = key < todayKey + const list: AgendaEvent[] = byKey.get(key)!.sort(order).map((ev) => { + if (before) return { ev, past: true, ongoing: false } + if (!isToday || ev.allDay) return { ev, past: false, ongoing: isToday && Boolean(ev.allDay) } + const start = parseDate(ev.start) + const end = ev.end ? parseDate(ev.end) : start + return { ev, past: end <= now, ongoing: start <= now && now < end } + }) + let nowAt = -1 + if (isToday && list.some((e) => !e.ev.allDay)) { + const next = list.findIndex((e) => !e.ev.allDay && !e.past) + nowAt = next === -1 ? list.length : next + } + return { key, date, heading: dayHeading(date, now), today: isToday, away: awayOn(away, key), events: list, nowAt } + }) +} + +/** The first and last day a week-shaped view shows. */ +function spanOf(view: CalViewId, anchor: Date, weekStart: number): [Date, Date] { + const sow = startOfWeek(anchor, weekStart) + const s = view === 'agenda' ? startOfDay(anchor) : view === 'workweek' ? addDays(sow, weekStart === 0 ? 1 : 0) : sow + return [s, addDays(s, view === 'workweek' ? 4 : view === 'agenda' ? 13 : 6)] +} + +/** + * The toolbar's title on a wide screen: "Nov 22 – 28, 2026". (Intl renders + * `{ day, year }` without a month as "2026 (day: 28)", which the title once showed.) + */ +export function rangeTitle(view: CalViewId, anchor: Date, weekStart = 0): string { + if (view === 'day') return anchor.toLocaleDateString([], { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' }) + if (view === 'year') return String(anchor.getFullYear()) + if (view === 'month') return anchor.toLocaleDateString([], { month: 'long', year: 'numeric' }) + const [s, e] = spanOf(view, anchor, weekStart) + const sameYear = s.getFullYear() === e.getFullYear() + const sFmt = s.toLocaleDateString([], { month: 'short', day: 'numeric', ...(sameYear ? {} : { year: 'numeric' }) }) + const eFmt = s.getMonth() === e.getMonth() && sameYear + ? `${e.getDate()}, ${e.getFullYear()}` + : e.toLocaleDateString([], { month: 'short', day: 'numeric', year: 'numeric' }) + return `${sFmt} – ${eFmt}` +} + +/** The title at phone width, short enough to sit beside the controls (the app's). The year only when it is not this one. */ +export function compactTitle(view: CalViewId, anchor: Date, now = new Date(), weekStart = 0): string { + const yearOf = (d: Date) => (d.getFullYear() !== now.getFullYear() ? `, ${d.getFullYear()}` : '') + const md = (d: Date) => d.toLocaleDateString([], { month: 'short', day: 'numeric' }) + if (view === 'year') return String(anchor.getFullYear()) + if (view === 'month') return anchor.toLocaleDateString([], { month: 'long', ...(anchor.getFullYear() !== now.getFullYear() ? { year: 'numeric' } : {}) }) + if (view === 'day') return `${anchor.toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' })}${yearOf(anchor)}` + const [s, e] = spanOf(view, anchor, weekStart) + const end = s.getMonth() === e.getMonth() ? String(e.getDate()) : md(e) + return `${md(s)} – ${end}${yearOf(e)}` +} diff --git a/web/src/calendar/calendar.css b/web/src/calendar/calendar.css new file mode 100644 index 0000000..1988f0d --- /dev/null +++ b/web/src/calendar/calendar.css @@ -0,0 +1,104 @@ +/* Productivity → Calendar (components/CalendarView.tsx) in the iPhone app's look + (mobile/src/features/productivity/CalendarView.tsx, features/calendar/): one toolbar + row (the period, ‹ ›, Today, the view as a menu), the grids and the agenda in + cards with a 16px corner. The desktop keeps its week grid; a phone opens on the + agenda. Palette variables only. */ + +.view.cal-view { + width: 100%; + max-width: 1120px; + margin: 0 auto; + padding: 18px 24px 0; + box-sizing: border-box; +} + +/* ---------- Toolbar ---------- */ +.cal-head { flex: none; display: flex; align-items: center; gap: 2px; min-height: 44px; margin-bottom: 12px; } +.cal-head .cal-title { + flex: 1; min-width: 0; margin: 0; font-size: 22px; font-weight: 700; letter-spacing: -0.01em; line-height: 1.2; + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; +} +.cal-title-short { display: none; } +.cal-head .cal-loading { color: var(--muted); margin: 0 6px; animation: spin 0.9s linear infinite; } +.cal-controls { display: flex; align-items: center; gap: 2px; flex: none; } +.cal-controls .pk-icon-btn { color: var(--text); } +.cal-today { margin-left: 4px; } +.cal-view-btn { margin-left: 6px; gap: 5px; min-width: 104px; justify-content: space-between; background: var(--bg-2); } +.cal-view-btn svg { width: 14px; height: 14px; color: var(--muted); } +.cal-view-btn[aria-expanded='true'] { border-color: var(--line-strong); background: var(--bg-hover); } +.cal-warn { display: flex; align-items: center; gap: 6px; margin: 0 0 8px; color: var(--muted); font-size: 13px; } + +/* ---------- Grids as cards ---------- */ +.cal-view .tg, .cal-view .month { + border-radius: 16px; background: var(--surface); margin-bottom: 22px; +} +.cal-view .tg-hour span { background: var(--surface); } +.cal-view .tg-daycol-h { padding: 10px 4px 8px; } +.cal-view .tg-dow { font-size: 11px; font-weight: 500; } +.cal-view .tg-dnum { font-size: 20px; line-height: 30px; } +.cal-view .tg-daycol-h.today .tg-dnum { width: 30px; height: 30px; line-height: 30px; font-size: 16px; } +.cal-view .tg-event { border-radius: 6px; padding: 3px 6px; } +/* Half an hour has room for one line: the title, then the time beside it. */ +.cal-view .tg-event.short { display: flex; align-items: baseline; gap: 5px; padding-top: 2px; padding-bottom: 0; } +.cal-view .tg-event.short .tg-event-t { flex: 0 1 auto; min-width: 0; } +.cal-view .tg-event.short .tg-event-time { flex: none; } +.cal-view .month-cell.off { background: color-mix(in srgb, var(--bg) 60%, transparent); } +.cal-view .year { padding: 2px 2px 22px; } +.cal-view .mini-month { border-radius: 16px; background: var(--surface); padding: 12px; } +.cal-view .mini-title { font-size: 14px; } + +/* ---------- Agenda ---------- */ +.cal-view .cal-agenda { padding: 0 0 28px; } +/* The agenda reads as one column, its toolbar included. */ +.view.cal-view.cal-v-agenda { max-width: 808px; } +.ag-day { margin-bottom: 18px; } +.ag-day-h { display: flex; align-items: baseline; gap: 8px; margin: 0 0 8px; font-size: 16px; font-weight: 600; color: var(--text); } +.ag-today { color: var(--accent); } +.ag-date { font-size: 13px; font-weight: 400; color: var(--muted); } +.ag-away { + margin-left: auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; + padding: 2px 8px; border-radius: 999px; background: color-mix(in srgb, var(--away) 16%, transparent); + color: var(--away); font-size: 12px; font-weight: 600; +} +.ag-card { background: var(--surface); border: 1px solid var(--line); border-radius: 16px; overflow: hidden; } +.ag-row { + display: flex; align-items: center; gap: 12px; width: 100%; min-height: 56px; padding: 10px 14px; + border: 0; border-bottom: 1px solid var(--line); background: none; color: var(--text); + font: inherit; text-align: left; cursor: pointer; +} +.ag-row:last-child { border-bottom: 0; } +.ag-row:hover { background: var(--bg-3); } +.ag-row:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } +.ag-row.past { opacity: 0.5; } +.ag-time { width: 70px; flex: none; display: flex; flex-direction: column; font-variant-numeric: tabular-nums; } +.ag-time > span:first-child { font-size: 14px; font-weight: 600; } +.ag-end { font-size: 12px; color: var(--muted); } +.ag-bar { width: 3px; align-self: stretch; border-radius: 3px; flex: none; } +.ag-text { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; } +.ag-title { font-size: 15px; font-weight: 500; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } +.ag-loc { font-size: 13px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.ag-now-tag { flex: none; padding: 2px 6px; border-radius: 6px; background: color-mix(in srgb, var(--red) 14%, transparent); color: var(--red); font-size: 11px; font-weight: 700; } +.ag-now { position: relative; height: 2px; margin: -1px 0; background: var(--red); z-index: 2; } +.ag-now i { position: absolute; left: -2px; top: -3px; width: 8px; height: 8px; border-radius: 50%; background: var(--red); } +.ag-free { + margin: 0; padding: 12px 14px; border: 1px dashed var(--line); border-radius: 16px; + color: var(--muted); font-size: 14px; +} +.ag-more { display: flex; margin: 4px auto 0; min-height: 44px; } + +/* ---------- Phone: the app's toolbar ---------- */ +@media (max-width: 720px) { + .view.cal-view { padding: 10px 16px 0; } + /* The range takes its own line, so its end date is never cut off behind the controls. */ + .cal-head { flex-wrap: wrap; row-gap: 4px; } + .cal-head .cal-title { font-size: 20px; flex: 1 0 100%; } + .cal-controls { flex: 1; } + .cal-today { margin-left: auto; } + .cal-title-full { display: none; } + .cal-title-short { display: inline; } + .cal-controls .pk-icon-btn { width: 36px; height: 44px; } + .cal-today, .cal-view-btn { min-height: 44px; padding: 0 12px; } + .cal-view-btn { min-width: 0; padding: 0 11px; } + .cal-view .year { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; } + .cal-view .tg-gutter, .cal-view .tg-gutter-col { width: 44px; } +} diff --git a/web/src/components/CalendarView.tsx b/web/src/components/CalendarView.tsx index 673c66c..168a68f 100644 --- a/web/src/components/CalendarView.tsx +++ b/web/src/components/CalendarView.tsx @@ -1,8 +1,11 @@ import React, { useEffect, useMemo, useRef, useState, useCallback } from 'react' import { getAway, getCalendarRange, updateCalendarEvent, AuthError } from '../api' import { awayDaysIn, awayOn, dayKey, type AwaySpan } from '../away' -import { Hi, XMarkIcon, WarnIcon } from '../icons' +import { ArrowPathIcon, ChevronDownIcon, ChevronLeftIcon, ChevronRightIcon, Hi, XMarkIcon, WarnIcon } from '../icons' import { useErrorToast } from '../toast' +import Menu from '../todos/Menu' +import { agendaDays, compactTitle, rangeTitle, VIEW_IDS, type AgendaEvent, type CalViewId } from '../calendar/agenda' +import '../calendar/calendar.css' // Loosely-shaped bridge JSON. type CalEvent = any @@ -36,7 +39,7 @@ const sameDay = (a: Date, b: Date) => a.getFullYear() === b.getFullYear() && a.g const isToday = (d: Date) => sameDay(d, new Date()) const minsOfDay = (d: Date) => d.getHours() * 60 + d.getMinutes() -const VIEWS = [ +const VIEWS: { id: CalViewId; label: string }[] = [ { id: 'day', label: 'Day' }, { id: 'workweek', label: 'Work Week' }, { id: 'week', label: 'Week' }, @@ -83,23 +86,6 @@ function fetchRange(view: string, anchor: Date): [Date, Date] { return [s, new Date(anchor.getFullYear() + 1, 0, 1)] } -// Title shown in the toolbar for the current view + anchor. -function rangeTitle(view: string, anchor: Date) { - if (view === 'day') return anchor.toLocaleDateString([], { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' }) - if (view === 'year') return String(anchor.getFullYear()) - if (view === 'month') return anchor.toLocaleDateString([], { month: 'long', year: 'numeric' }) - // week / workweek / agenda - const s = view === 'agenda' ? startOfDay(anchor) - : view === 'workweek' ? addDays(startOfWeek(anchor), WEEK_START === 0 ? 1 : 0) - : startOfWeek(anchor) - const e = view === 'workweek' ? addDays(s, 4) : addDays(s, view === 'agenda' ? 13 : 6) - const sameMonth = s.getMonth() === e.getMonth() - const sameYear = s.getFullYear() === e.getFullYear() - const sFmt = s.toLocaleDateString([], { month: 'short', day: 'numeric', year: sameYear ? undefined : 'numeric' }) - const eFmt = e.toLocaleDateString([], { month: sameMonth ? undefined : 'short', day: 'numeric', year: 'numeric' }) - return `${sFmt} – ${eFmt}` -} - // Greedy column packing for overlapping timed events within one day. function packDay(items: CalEvent[]) { const evs: any[] = items @@ -213,7 +199,7 @@ function TimeGrid({ days, away, events, onPickDay, onSelectEvent }: TimeGridProp {packed.map(({ ev, s, e, col, cols }) => ( - ))} - } - - ) - })} + ) : !day.away ? ( +

Nothing scheduled

+ ) : null} + + ))} + ) } +function AgendaRow({ item, onClick }: { item: AgendaEvent; onClick: () => void }) { + const { ev, past, ongoing } = item + const start = ev.allDay ? null : parseDate(ev.start) + const end = ev.allDay || !ev.end ? null : parseDate(ev.end) + const time = start ? fmtTime(start) : 'All day' + return ( + + ) +} + +function NowLine({ now }: { now: Date }) { + return
+} + interface EventModalProps { event: CalEvent onClose: () => void @@ -514,9 +539,27 @@ interface CalendarViewProps { onAuthError: () => void } +// The view last picked on this device; with none, a phone opens on the agenda (as the +// app does) and a wider screen on the week grid. Storage may be missing (a private +// window), and then the default is simply used every time. +const VIEW_KEY = 'totem.calendar.view' +const PHONE = '(max-width: 720px)' +function startView(): CalViewId { + try { + const raw = localStorage.getItem(VIEW_KEY) + if (raw && (VIEW_IDS as string[]).includes(raw)) return raw as CalViewId + } catch { /* not kept */ } + return typeof window !== 'undefined' && window.matchMedia?.(PHONE).matches ? 'agenda' : 'week' +} + // ---------- main ---------- export default function CalendarView({ onAuthError }: CalendarViewProps) { - const [view, setView] = useState('week') + const [view, setViewState] = useState(startView) + const setView = (next: CalViewId) => { + setViewState(next) + try { localStorage.setItem(VIEW_KEY, next) } catch { /* not kept; nothing depends on it */ } + } + const [viewMenu, setViewMenu] = useState(null) const [anchor, setAnchor] = useState(() => new Date()) const [events, setEvents] = useState([]) const [errors, setErrors] = useState([]) @@ -570,37 +613,52 @@ export default function CalendarView({ onAuthError }: CalendarViewProps) { return [] }, [view, anchor]) + const agendaRange = useMemo<[Date, Date]>(() => [rStart, rEnd], [rStart, rEnd]) + const viewLabel = VIEWS.find((v) => v.id === view)?.label ?? 'Week' + const fullTitle = rangeTitle(view, anchor) + return ( -
-
-
- - - -

{rangeTitle(view, anchor)}

- {loading && ·} -
-
- {VIEWS.map((v) => ( - - ))} +
+
+

+ {fullTitle} + +

+ {loading && } +
+ + + +
-
+ + {viewMenu && ( + setViewMenu(null)} + items={VIEWS.map((v) => ({ key: v.id, label: v.label, checked: v.id === view, onSelect: () => setView(v.id) }))} + /> + )} - {errors.map((e) =>
{e}
)} + {errors.map((e) =>
{e}
)} {(view === 'day' || view === 'week' || view === 'workweek') && ( )} {view === 'month' && } {view === 'year' && } - {view === 'agenda' && } + {view === 'agenda' && step(1)} />} {selectedEvent && ( > = { overview: 'All', this_week: 'Week', next_week: 'Next wk', this_month: 'Month', this_year: 'Year' } /** * The strip across the top is one control, not two. @@ -207,159 +212,173 @@ export default function GoalsView({ onAuthError }: { onAuthError: () => void }) * place is the whole point: the decision is visible next to the week it was made * about, and it is one click to take back. It still is not counted among the done. */ - const { open, done, stopped } = useMemo(() => ({ + const { open, done } = useMemo(() => ({ open: goals.filter((g) => !g.complete), done: goals.filter((g) => g.complete), - stopped: goals.filter((g) => g.abandoned && !g.complete), }), [goals]) const unit = typeOf(period) + const summary = useMemo(() => periodSummary(goals), [goals]) + const addGoal = useCallback(() => { setError(''); setComposing(true) }, []) + // A load that failed with nothing to show: say so in the body, with a retry, + // rather than drawing an empty week the error may not be about. + const failedEmpty = Boolean(error) && goals.length === 0 && !loading && showing && !composing + + const card = (goal: Goal) => ( + apply(() => setGoalComplete(goal.id, !goal.complete))} + onToggleStep={(id, complete) => apply(() => setGoalComplete(id, complete))} + onLog={(metricId, patch) => apply(() => logGoalMetric(metricId, patch))} + onPostpone={() => apply(async () => { await postponeGoal(goal.id); await load(); return {} })} + onDelete={() => apply(async () => { await deleteGoal(goal.id); await load(); return {} })} + onEdit={(patch) => apply(() => updateGoal(goal.id, patch))} + onAbandon={(abandoned) => apply(() => updateGoal(goal.id, { abandoned }))} + onAbandonStep={(id, abandoned) => apply(() => updateGoal(id, { abandoned }))} + onRenameStep={(id, title) => apply(() => updateGoal(id, { title }))} + onAddStep={(title) => apply(() => addGoalStep(goal.id, { title }))} + onSaveMetrics={(changes) => saveMetrics(goal.id, changes)} + onSaveStepMetrics={(stepId, changes) => saveMetrics(stepId, changes)} + onToggleBushido={bushido ? (current) => toggleBushido(goal, current) : undefined} + bushidoHosts={bushido?.hosts} + /> + ) + + const tabButton = (value: GoalTab) => { + const on = value === tab + const long = value === 'overview' ? 'Overview' : PERIOD_LABELS[value] + return ( + + ) + } return (
-
-
- - {PERIODS.map((p) => ( - - ))} +
+
+ {tabButton('overview')} + {PERIODS.map(tabButton)}
- - - -
- {window && showing && ( -

- {/* The arrows walk to any period of this type — last week, the week before, - the month before that — so a finished week stays somewhere it can be - read, not just somewhere it once was. */} - - {window.label} - - {anchored && ( - + - )} - {goals.length > 0 && · {done.length} of {goals.length} done} - {stopped.length > 0 && · {stopped.length} not doing} -

- )} +
+ )} - {error &&

{error}

} + {error && !failedEmpty && !composing && ( +
+ + {error} + +
+ )} - {composing && ( - setComposing(false)} - onCreate={(input) => { - void (async () => { - setBusy(true); setError('') - try { - await createGoal(input) - setComposing(false) - setOverviewKey((n) => n + 1) - // Land on the period the goal was filed under, so it is visible rather - // than filed somewhere you have to go looking for it — which includes - // walking back from an older week the arrows had opened. - const target = input.period ?? period - if (anchored || target !== tab) pick(target) - else await load() - } catch (cause) { - if (cause instanceof AuthError) onAuthError() - else setError(cause instanceof Error ? cause.message : 'That goal could not be added.') - } finally { setBusy(false) } - })() - }} - /> - )} + {composing && ( + { setComposing(false); setError('') }} + onCreate={(input) => { + void (async () => { + setBusy(true); setError('') + try { + await createGoal(input) + setComposing(false) + setOverviewKey((n) => n + 1) + // Land on the period the goal was filed under, so it is visible rather + // than filed somewhere you have to go looking for it — which includes + // walking back from an older week the arrows had opened. + const target = input.period ?? period + if (anchored || target !== tab) pick(target) + else await load() + } catch (cause) { + if (cause instanceof AuthError) onAuthError() + else setError(cause instanceof Error ? cause.message : 'That goal could not be added.') + } finally { setBusy(false) } + })() + }} + /> + )} - {!showing ? ( - - ) : loading ?

Loading…

: goals.length === 0 ? ( -
- -

Nothing set for {anchored && window ? window.label : PERIOD_LABELS[period].toLowerCase()}.

-
- ) : ( - <> -
- {open.map((goal) => ( - apply(() => setGoalComplete(goal.id, !goal.complete))} - onToggleStep={(id, complete) => apply(() => setGoalComplete(id, complete))} - onLog={(metricId, patch) => apply(() => logGoalMetric(metricId, patch))} - onPostpone={() => apply(async () => { await postponeGoal(goal.id); await load(); return {} })} - onDelete={() => apply(async () => { await deleteGoal(goal.id); await load(); return {} })} - onEdit={(patch) => apply(() => updateGoal(goal.id, patch))} - onAbandon={(abandoned) => apply(() => updateGoal(goal.id, { abandoned }))} - onAbandonStep={(id, abandoned) => apply(() => updateGoal(id, { abandoned }))} - onRenameStep={(id, title) => apply(() => updateGoal(id, { title }))} - onAddStep={(title) => apply(() => addGoalStep(goal.id, { title }))} - onSaveMetrics={(changes) => saveMetrics(goal.id, changes)} - onSaveStepMetrics={(stepId, changes) => saveMetrics(stepId, changes)} - onToggleBushido={bushido ? (current) => toggleBushido(goal, current) : undefined} - bushidoHosts={bushido?.hosts} - /> - ))} + {!showing ? ( + + ) : loading && goals.length === 0 ? ( +

Loading goals…

+ ) : failedEmpty ? ( +
+ +

Goals didn’t load

+

{error}

+
+ ) : goals.length === 0 ? ( +
+ +

Nothing set for {anchored && window ? window.label : PERIOD_LABELS[period].toLowerCase()}

+

Name what you want to be true by the end of it. A number is optional.

+ +
+ ) : ( + <> +
{open.map(card)}
- {done.length > 0 && ( -
- {/* "Achieved", not "Done": the same list, named after what it is worth - rather than after the fact that it is no longer in the way. Only - finished goals land here — one you stopped is not an achievement, and - it stays up in the list crossed off. */} -

- - Achieved -

-
- {done.map((goal) => ( - apply(() => setGoalComplete(goal.id, !goal.complete))} - onToggleStep={(id, complete) => apply(() => setGoalComplete(id, complete))} - onLog={(metricId, patch) => apply(() => logGoalMetric(metricId, patch))} - onPostpone={() => apply(async () => { await postponeGoal(goal.id); await load(); return {} })} - onDelete={() => apply(async () => { await deleteGoal(goal.id); await load(); return {} })} - onEdit={(patch) => apply(() => updateGoal(goal.id, patch))} - onAbandon={(abandoned) => apply(() => updateGoal(goal.id, { abandoned }))} - onAbandonStep={(id, abandoned) => apply(() => updateGoal(id, { abandoned }))} - onRenameStep={(id, title) => apply(() => updateGoal(id, { title }))} - onAddStep={(title) => apply(() => addGoalStep(goal.id, { title }))} - onSaveMetrics={(changes) => saveMetrics(goal.id, changes)} - onSaveStepMetrics={(stepId, changes) => saveMetrics(stepId, changes)} - onToggleBushido={bushido ? (current) => toggleBushido(goal, current) : undefined} - bushidoHosts={bushido?.hosts} - /> - ))} -
-
- )} - - )} + {done.length > 0 && ( +
+ {/* "Achieved", not "Done": the same list, named after what it is worth + rather than after the fact that it is no longer in the way. Only + finished goals land here — one you stopped is not an achievement, and + it stays up in the list crossed off. */} +

+ + Achieved · {done.length} +

+
{done.map(card)}
+
+ )} + + )} +
) } diff --git a/web/src/components/HabitCheckin.tsx b/web/src/components/HabitCheckin.tsx index 96d89c5..b349631 100644 --- a/web/src/components/HabitCheckin.tsx +++ b/web/src/components/HabitCheckin.tsx @@ -38,6 +38,7 @@ function Row({ item, entry, note, busy, onAnswer }: {
+ {item.group && {item.group}} {h.name} {item.part === 'yesterday' && h.when === 'night' && last night} {note && {note}} diff --git a/web/src/components/HabitsView.tsx b/web/src/components/HabitsView.tsx index 562106f..b0b2449 100644 --- a/web/src/components/HabitsView.tsx +++ b/web/src/components/HabitsView.tsx @@ -9,8 +9,11 @@ import { useCommand } from '../useShortcuts' import { Hi, PlusIcon, MinusIcon, ArrowPathIcon, XMarkIcon, TrashIcon, PencilSquareIcon, CheckIcon, ChatBubbleLeftEllipsisIcon, FireIcon, ArchiveBoxIcon, Bars3Icon, ArrowTopRightOnSquareIcon, - ChevronLeftIcon, ChevronRightIcon, + ChevronLeftIcon, ChevronRightIcon, ChevronDownIcon, ChatBubbleLeftRightIcon, MoonIcon, SunIcon, CheckBadgeSolidIcon, } from '../icons' +import { foldGroups, flattenTree, groupProgress, groupToggle, groupWords, habitTree, handLogged, rowDone } from '../habits/groups' +import { startChatAbout } from '../chat/about/start' +import '../habits/habits.css' import { useErrorToast, pushToast } from '../toast' import { OPEN_HABIT_CHECKIN } from './HabitCheckin' import ChatAbout from '../chat/about/ChatAbout' @@ -36,6 +39,8 @@ interface Habit { linkedApp?: LinkedApp | null /** That app's address, from the bridge's env. */ appUrl?: string | null + /** The group it sits under (web/src/habits/groups.ts); one level deep. */ + parentId?: string | null createdAt: string archived: boolean } @@ -63,7 +68,7 @@ export function LinkedAppButton({ habit, compact }: { habit: Pick h.metric?.source === 'whoop-sleep' -interface Entry { count: number; note?: string; value?: number | null; parts?: Record } +interface Entry { count: number; skipped?: boolean; note?: string; value?: number | null; parts?: Record } type Entries = Record> // date -> habitId -> entry interface HabitsPayload { @@ -167,6 +172,14 @@ interface HabitFormModalProps { onClose: () => void onSubmit: (fields: any) => Promise onDelete?: () => Promise + /** Habits this one may sit under: active, top-level, filled by hand. */ + parents?: Habit[] + /** The group a new habit starts in. */ + defaultParent?: string | null + /** It is a group already, so it cannot go under another habit. */ + hasChildren?: boolean + /** Close this and start a new habit inside it. */ + onAddSub?: () => void } // The metric half of the habit form, kept as loose strings so a half-typed @@ -241,7 +254,7 @@ function metricFromDraft(draft: MetricDraft, existing: MetricPart[] = []): Metri } } -function HabitFormModal({ initial, palette, usedColors, onClose, onSubmit, onDelete }: HabitFormModalProps) { +function HabitFormModal({ initial, palette, usedColors, onClose, onSubmit, onDelete, parents = [], defaultParent = null, hasChildren = false, onAddSub }: HabitFormModalProps) { const [form, setForm] = useState({ name: initial?.name || '', description: initial?.description || '', @@ -251,6 +264,7 @@ function HabitFormModal({ initial, palette, usedColors, onClose, onSubmit, onDel archived: initial?.archived || false, when: (initial?.when || 'any') as HabitWhen, linkedApp: (initial?.linkedApp || '') as LinkedApp | '', + parentId: (initial ? initial.parentId : defaultParent) || '', }) const [metric, setMetric] = useState(() => metricDraftFrom(initial?.metric)) const setMetricField = (k: keyof MetricDraft, v: any) => setMetric((m) => ({ ...m, [k]: v })) @@ -282,6 +296,11 @@ function HabitFormModal({ initial, palette, usedColors, onClose, onSubmit, onDel when: form.when, linkedApp: form.linkedApp || null, } + // Only when it changed: a sub-habit of an archived group arrives with no parent + // (the bridge lets it out until the group returns), and saving that back would + // detach it for good. + const parentNow = form.parentId || null + if (parentNow !== ((initial && initial.parentId) || null)) fields.parentId = parentNow if (form.color) fields.color = form.color await onSubmit(fields) } catch (err: any) { setError(err.message); setBusy(null) } @@ -299,7 +318,7 @@ function HabitFormModal({ initial, palette, usedColors, onClose, onSubmit, onDel
e.stopPropagation()}>
-
{initial ? 'Edit habit' : 'New habit'}
+
{initial ? (hasChildren ? 'Edit group' : 'Edit habit') : 'New habit'}

{initial ? initial.name : 'Track something daily'}

@@ -313,52 +332,76 @@ function HabitFormModal({ initial, palette, usedColors, onClose, onSubmit, onDel Description (optional) set('description', e.target.value)} placeholder="What counts as done?" /> -
- - -
-
- + {hasChildren ? ( +
+ + {initial?.name} is a group: it is done for a day when all its sub-habits are, and its check marks the ones you tick by hand (an app fills in its own). + + {onAddSub && } +
+ ) : parents.length > 0 || form.parentId ? ( -
- - {form.linkedApp - ? `${APP_NAME[form.linkedApp as LinkedApp]} fills this in on its own; here it links to the app instead of a check mark.` - : form.when === 'night' - ? 'The morning check-in asks about it the next day and logs it to the night before.' - : form.when === 'morning' - ? 'The morning check-in asks about it for that day.' - : 'The morning check-in asks about it if yesterday went unanswered.'} - - - {form.cadence === 'daily' - ? '1 = simple yes/no. Higher (e.g. 8 glasses of water) shades the day darker the closer you get.' - : `e.g. gym 3× a week, or deep-clean once a month. You still check it off on the day you do it; the check-in shows ${periodLabel(form.cadence)}’s progress.`} - + ) : null} + {/* A group's day is its sub-habits': how often, when, who fills it and a number are theirs. */} + {!hasChildren && (<> +
+ + +
+
+ + +
+ + {form.linkedApp + ? `${APP_NAME[form.linkedApp as LinkedApp]} fills this in on its own; here it links to the app instead of a check mark.` + : form.when === 'night' + ? 'The morning check-in asks about it the next day and logs it to the night before.' + : form.when === 'morning' + ? 'The morning check-in asks about it for that day.' + : 'The morning check-in asks about it if yesterday went unanswered.'} + + + {form.cadence === 'daily' + ? '1 = simple yes/no. Higher (e.g. 8 glasses of water) shades the day darker the closer you get.' + : `e.g. gym 3× a week, or deep-clean once a month. You still check it off on the day you do it; the check-in shows ${periodLabel(form.cadence)}’s progress.`} + + )}
Color
@@ -383,90 +426,92 @@ function HabitFormModal({ initial, palette, usedColors, onClose, onSubmit, onDel ))}
- {/* Optional metric: the number this habit is really about. */} -
- - {metric.on && ( - <> -
- - -
-
- - - -
-
- + {!hasChildren && (<> + {/* Optional metric: the number this habit is really about. */} +
+ + {metric.on && ( + <> +
+ + +
+
+ + + +
+
+ + + +
+ {metric.source === 'whoop-sleep' && ( + + A scheduled job pulls last night's sleep performance and stages from WHOOP (through Bushido) each late + morning (Studio → Workflows → WHOOP sleep sync). Nights you've already filled in are left alone. + + )} -
- - {metric.source === 'whoop-sleep' && ( - A scheduled job pulls last night's sleep performance and stages from WHOOP (through Bushido) each late - morning (Studio → Workflows → WHOOP sleep sync). Nights you've already filled in are left alone. + Comma-separated components, logged in the metric's unit and stacked as bars under the line — + sleep stages in minutes, say. Leave empty for a single number. - )} - - - Comma-separated components, logged in the metric's unit and stacked as bars under the line — - sleep stages in minutes, say. Leave empty for a single number. - - - - )} -
+ + + )} +
+ )} {initial && (