diff --git a/.env.example b/.env.example index d030045..179aa71 100644 --- a/.env.example +++ b/.env.example @@ -225,6 +225,8 @@ SCREEN_ENABLED=false # The chat project or folder each task is filed under (the chats panel's Tasks face). # TASK_FOLDERS_FILE=data/task-folders.json +# Shared sheet rows the owner marked done or snoozed in Totem (never written to the sheet). +# SHEET_MARKS_FILE=data/sheet-marks.json # --- Source health (docs/source-health.md): the run log every connector writes --- # SOURCE_RUNS_DB=data/source-runs.db diff --git a/AGENTS.md b/AGENTS.md index a1fa6e4..28758d5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,9 +66,9 @@ open-ended work. The default provider and model come from Settings → Providers | Chat access and Claude tools | `providers/claude-tools.mjs`, `web/src/chat/traits.ts`, `web/src/chat/ModelPicker.tsx`, `web/src/components/ClaudeToolsPanel.tsx` | A chat's access (Supervised / Auto-accept edits / Auto / Full access, default Full) maps to each CLI's permission mode or sandbox; it is set from the composer's model chip, whose one picker (T3 Code's) holds the models, the model's reasoning levels, Standard/Fast where the model takes it (Cursor's Composer) and the access dropdown in its footer (`docs/chat.md` → Choosing a model). Settings → Connections › Claude tools pulls the connectors each Claude account has and switches servers and tools on or off (`data/claude-tools.json`); on means allowed, off means denied on every Claude run. `docs/chat.md` → Access. | | AI usage meters | `ai-usage/` | Polls each CLI's quota windows. Claude and Cursor polling are opt-in (`AI_USAGE_CLAUDE_OAUTH`, `AI_USAGE_CURSOR`, or Settings → Usage): Claude's refreshes Claude Code's own login, Cursor's calls a private endpoint. See Gotchas. Agents read usage through `totem_usage_get_current`/`_get_history`/`_limit_report` (`usage__*` in the gateway; `ai-usage/mcp.mjs` over `ai-usage/report.mjs`), read-only: the poller's last snapshot and CLIProxy's 21-day history, names, plans and numbers only. The limit report counts a cap once per window period (readings sharing a reset; with none, until usage falls), blocks from the first reading at the cap to the reset (a window replaced early by a reset credit or grant ends at its last reading), skips the 0% windows an idle Codex login reports on every reading, and states what the readings cover; no reading is no data, never 0%. For scheduling AI work, `totem_usage_forecast` and `totem_usage_plan` (`usage__forecast`/`usage__plan`, `ai-usage/forecast.mjs`) project every login forward with the CLIProxy graphs' model (one pool per provider routed soonest weekly reset first, both windows must have room, a 5-hour window starts on first use, weekly cost at each login's measured weekly-per-5-hour ratio). The default pace is a blend, the last 3 h for 5 h and then the 7-day average, not the graphs' recent pace throughout, so run-out times past a few hours differ from the graphs on purpose. The plan says when and on which login a job of a given size fits (sizes are % of the largest plan's 5-hour window), preferring capacity that would reset unused. | | CLIProxy logins | `cliproxy/`, `ai-usage/pools.mjs`, `web/src/usagePools.ts`, `web/src/chat/UsageChips.tsx` | Off unless `CLIPROXY_URL` and `CLIPROXY_MANAGEMENT_KEY` are set (env or Settings → Providers › CLIProxy, read on every call). Then the logins CLIProxyAPI pools replace this machine's own Claude and Codex logins in the usage snapshot (ids `claude:proxy:`), read through its management API (`/v8/management`): one `GET /credentials` per poll carries each login's last rate-limit headers (passive); a vendor usage read through `/requests/api-call` happens only when those are over 3 minutes old, a window reset since, or Refresh was pressed (≤ 1/min per login watched, 1/10 min idle). Fresh active readings are also recorded to the proxy's `/quota/history` (optional; a missing endpoint or scope leaves quota polling working). Totem never refreshes a proxy login's token. Every account gets a `state` (disabled > error > limited > low > ok) and `headroomPct` (its tightest all-models window), and each provider a pool (best usable headroom, usable count, next back), computed in the poller (`annotateAccount`, `buildPools`) so every surface agrees; the pills show one per provider with a dot per account. A proxy that stops answering keeps its last readings (stale from the second miss) and is never replaced by the local logins. Upstream URLs are constants and `client.upstream` refuses any other (`UPSTREAM_ALLOWED`). Short-window "spent" nudges for a pooled seat are folded into one pool nudge (`usageFacts({ pools })`). Source health: `cliproxy` and `cliproxy:` (a login needing sign-in). The CLIProxy tab (`/cliproxy`, `cliproxy/manage.mjs`, `cliproxy/http.mjs`, `web/src/cliproxy/`) is on the rail only when configured: switch, edit, refresh, cooldown reset, delete, sign in (paste-back of the localhost callback, checked against the `state` Totem started), Claude reset grants and Codex reset credits (high risk; a claim's request id kept in `data/cliproxy.json`). Every change is in `APPROVAL_ROUTES`, names its login in the body, and is resolved against a fresh proxy list. The tab's weekly, 5-hour and combined history/forecast graphs (`web/src/cliproxy/pool/`, ported from CLI Proxy API Management Center; zoomable, one view inside the page's range shared by every card, `pool/poolZoom.ts`) read the proxy's 21-day history through `GET /api/cliproxy/history`; the bridge returns numeric windows matched to current credentials. Claude's card adds its weekly Fable cap as a second line in the weekly and combined views (`fable` in `poolInputs.ts`; history `seven_day_fable`, which the history route also fills from the proxy's passive `seven_day_oi`). Weekly-exhausted seats add no usable 5-hour capacity until their weekly reset, in history, Now, stacks and projection; a projected 5-hour window starts on its first use (also one the API reports with no reset), and the combined hover shows each seat's weekly and 5-hour levels with the binding one underlined; raw burn stays unchanged by lockouts. Recorded capacity begins at each account/window’s first observation; newly added seats are never backfilled or labelled as refills. Together mode suppresses aggregate history when a contributing provider has no recorded readings, preserving current/forecast values and separate-provider history. Team plan sizes come from the profile tier; Claude plans are weighted by price (Pro 1, Max 5x 5, Max 20x 10; `claudePlanWeight`) with the most expensive plan present at 100%. Projection routing is a local forecast setting, not a proxy mutation; it and the other forecast tuning fold under Forecast settings, counted against `FORECAST_DEFAULTS` (`pool/poolSettings.ts`). No credential download, upload or proxy-URL edit. `docs/cliproxy.md`. | -| Tasks | `todos/` | SQLite (`data/todos.db`, `node:sqlite`, WAL, foreign keys, ordered migrations). `service.mjs` is the only business-rule boundary; `commands.mjs` routes every mutation, always local: nothing shares a task out, and `assertSyncTarget` (`todos/errors.mjs`) refuses any `syncTarget` but `local` before a write on every path (create, update, PATCH, share, MCP, inbox proposals): `github` with 400 `GITHUB_SHARING_REMOVED`, `sheet` with `SHEET_SHARING_REMOVED`, anything else `INVALID_SYNC_TARGET`; `http.mjs` and `mcp.mjs` are adapters. Each task is filed under one of the owner's chat projects or folders (`folderId`, migration 013; `todos/folders.mjs` resolves names, the bridge's `folderExists` refuses an unknown id) or none, which every client calls Personal; that replaced Personal/Ventures and venture tags, whose columns stay for old clients (`adoptTaskFolders` in `bridge.mjs` moved existing installs once). A deleted project's tasks move to its parent or become Personal (`refileFolder`). Agents read and set the folder by name; a task an agent makes from a chat in a project is filed there and linked to the chat (`/api/chat/run-context`). A task is open (`todo`) or `done`: no Doing since migration 011, though every input still accepts `doing` and stores `todo`, and nothing returns it. A task may carry one plain GitHub issue link (`PUT /api/todos/:id/issue-link`, `todos/issue-link.mjs`; `issueLink` on the DTO) whose live open/closed state `GET /api/todos/issue-states` reads through the Dev tab's `gh` runner (`todos/issue-states.mjs`: 5 min cache, ≤ 50 issues, last good on error); nothing owns completion (`COMPLETION_OWNERS` and `SYNCING_CONNECTORS` in `service.mjs` are empty), so every task completes locally. `GET /api/todos/board` carries `counts` (archived, snoozed, deleted, by COUNT); `POST /api/todos/board` is the canonical create (the board's DTO; legacy `POST /api/todos` keeps its old shape). `docs/task-issue-links.md`. The list's pure logic is one copy for the web and the app: `web/src/todos/{types,board,format,parse}.ts` (`buildList` groups open tasks and the shared sheet's rows Overdue/Today/Upcoming/No date by local day keys, never instant + 24 h; due words and snooze times; the quick-add parser), mirrored byte for byte to `mobile/src/lib/todos/` and checked by `mobile/src/features/todos/shared.test.mjs`; their tests are the web's. The app's Tasks page draws its rows from it (`mobile/src/features/todos/list.ts`: sheet rows read-only, swipe right = Done, "N left today", Undo inline, never a toast; its tests in `list.test.mjs`). | +| Tasks | `todos/` | SQLite (`data/todos.db`, `node:sqlite`, WAL, foreign keys, ordered migrations). `service.mjs` is the only business-rule boundary; `commands.mjs` routes every mutation, always local: nothing shares a task out, and `assertSyncTarget` (`todos/errors.mjs`) refuses any `syncTarget` but `local` before a write on every path (create, update, PATCH, share, MCP, inbox proposals): `github` with 400 `GITHUB_SHARING_REMOVED`, `sheet` with `SHEET_SHARING_REMOVED`, anything else `INVALID_SYNC_TARGET`; `http.mjs` and `mcp.mjs` are adapters. Each task is filed under one of the owner's chat projects or folders (`folderId`, migration 013; `todos/folders.mjs` resolves names, the bridge's `folderExists` refuses an unknown id) or none, which every client calls Personal; that replaced Personal/Ventures and venture tags, whose columns stay for old clients (`adoptTaskFolders` in `bridge.mjs` moved existing installs once). A deleted project's tasks move to its parent or become Personal (`refileFolder`). Agents read and set the folder by name; a task an agent makes from a chat in a project is filed there and linked to the chat (`/api/chat/run-context`). A task is open (`todo`) or `done`: no Doing since migration 011, though every input still accepts `doing` and stores `todo`, and nothing returns it. A task may carry one plain GitHub issue link (`PUT /api/todos/:id/issue-link`, `todos/issue-link.mjs`; `issueLink` on the DTO) whose live open/closed state `GET /api/todos/issue-states` reads through the Dev tab's `gh` runner (`todos/issue-states.mjs`: 5 min cache, ≤ 50 issues, last good on error); nothing owns completion (`COMPLETION_OWNERS` and `SYNCING_CONNECTORS` in `service.mjs` are empty), so every task completes locally. `GET /api/todos/board` carries `counts` (archived, snoozed, deleted, by COUNT); `POST /api/todos/board` is the canonical create (the board's DTO; legacy `POST /api/todos` keeps its old shape). `docs/task-issue-links.md`. The list's pure logic is one copy for the web and the app: `web/src/todos/{types,board,format,parse}.ts` (`buildList` groups open tasks and the shared sheet's rows Overdue/Today/Upcoming/No date by local day keys, never instant + 24 h; due words and snooze times; the quick-add parser), mirrored byte for byte to `mobile/src/lib/todos/` and checked by `mobile/src/features/todos/shared.test.mjs`; their tests are the web's. The app's Tasks page draws its rows from it (`mobile/src/features/todos/list.ts`: sheet rows read-only but for the owner's own done/snooze marks, swipe right = Done, "N left today", Undo inline, never a toast; its tests in `list.test.mjs`). | | Task connectors | `todos/connectors/` | Only the read-only task sheet feed (next row). Both connectors that wrote were removed: the GitHub task connector (auto-track, watched repos, search/link, outbox, `github-todos-sync`, the GitHub App) with migration 011, which archived the tasks it imported, and the two-way sheet sync with migration 012; their job ids are in the job store's `retiredIds`. A `github` inbox proposal still files its issue when accepted (`todos/inbox-issue.mjs`, through `gh`), and makes no task; `POST /api/todos/:id/external-links` refuses `github`, so the issue-link route is the only way one is set. | -| Task sheet (read-only) | `todos/connectors/task-sheet-feed.mjs`, `GET /api/todos/sheet` in `todos/http.mjs`, `taskSheetFeed` in `bridge.mjs`, Settings → Tasks › Task sheet | The open rows assigned to the owner from one shared Google Sheet of action items, read through the Drive sign-in (`drive/`; `TASK_SHEET_ID`/`_TAB`/`_ASSIGNEES`/`_TITLE`/`_ACCOUNT`/`_FOLDER`, env or Settings → Tasks, read on every fetch). Each row comes filed (`folderId`): its own filing, else `TASK_SHEET_FOLDER` (empty: the project the sheet's name starts with; `none`: Personal), `fileSheetItems` in `todos/folders.mjs`. Header row found by its "Task Name" cell, columns by header text; Done rows dropped; ids `sheet:::<8 hex of the title>`. Cached 120 s, `?refresh=1` at most once per 10 s, a failed read answers the last good items `stale` with a scrubbed error, one `task-sheet` source-health run per read, not ETag-cached. **The feed never writes to the sheet**: it is handed only Drive's `sheetInfo`/`sheetRead`, and its nested Drive calls join its own run (`covers` in `sources/track.mjs`), so a sheet the account cannot open is a `task-sheet` failure, not Drive's. The Drive tools can still edit the sheet when asked; that is deliberate. The two-way service-account sync is retired: `syncTarget: 'sheet'` is a 400 `SHEET_SHARING_REMOVED` (checked before any change), its job id is in `retiredIds`, migration 012 archives the tasks it linked and drops its outbox and connector state, and `syncStateFor` counts only connectors that still sync. `docs/task-sheet.md`. | +| Task sheet (read-only) | `todos/connectors/task-sheet-feed.mjs`, `GET /api/todos/sheet` in `todos/http.mjs`, `taskSheetFeed` in `bridge.mjs`, Settings → Tasks › Task sheet | The open rows assigned to the owner from one shared Google Sheet of action items, read through the Drive sign-in (`drive/`; `TASK_SHEET_ID`/`_TAB`/`_ASSIGNEES`/`_TITLE`/`_ACCOUNT`/`_FOLDER`, env or Settings → Tasks, read on every fetch). Each row comes filed (`folderId`): its own filing, else `TASK_SHEET_FOLDER` (empty: the project the sheet's name starts with; `none`: Personal), `fileSheetItems` in `todos/folders.mjs`. Header row found by its "Task Name" cell, columns by header text; Done rows dropped; ids `sheet:::<8 hex of the title>`. The owner can mark a row done or snoozed, for the owner only (`POST /api/todos/sheet/mark`, `todos/sheet-marks.mjs`, `data/sheet-marks.json`): never written to the sheet; the served feed moves a marked row from `items` to `hidden` with its `mark`, a snooze lapses on its own, and a mark is dropped once its row leaves a good read. Cached 120 s, `?refresh=1` at most once per 10 s, a failed read answers the last good items `stale` with a scrubbed error, one `task-sheet` source-health run per read, not ETag-cached. **The feed never writes to the sheet**: it is handed only Drive's `sheetInfo`/`sheetRead`, and its nested Drive calls join its own run (`covers` in `sources/track.mjs`), so a sheet the account cannot open is a `task-sheet` failure, not Drive's. The Drive tools can still edit the sheet when asked; that is deliberate. The two-way service-account sync is retired: `syncTarget: 'sheet'` is a 400 `SHEET_SHARING_REMOVED` (checked before any change), its job id is in `retiredIds`, migration 012 archives the tasks it linked and drops its outbox and connector state, and `syncStateFor` counts only connectors that still sync. `docs/task-sheet.md`. | | 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. | diff --git a/bridge.mjs b/bridge.mjs index e6ef37c..001fac1 100644 --- a/bridge.mjs +++ b/bridge.mjs @@ -87,6 +87,7 @@ import { fetchFavicon } from './chat/favicon.mjs' import { createConnectionIconStore, validConnectionId } from './connections/icons.mjs' import { createProjectStore, moveMemoryEntries, validProjectId } from './chat/projects.mjs' import { createTaskFolderStore } from './chat/task-folders.mjs' +import { createSheetMarkStore } from './todos/sheet-marks.mjs' import { fileSheetItems as fileSheetFolders, folderAdoption, folderPath, resolveFolder, SHEET_UNFILED } from './todos/folders.mjs' import { linkedTaskBlock, findSheetItem } from './chat/task-link.mjs' import { createChatRuns } from './chat/runs.mjs' @@ -17117,7 +17118,19 @@ const todoCommands = createTodoCommands({ // keeps it out of Settings -> Connections. sourceRuns.forget('github-tasks') const todoIssueStates = createIssueStates({ links: (o) => todoService.issueLinks(o), run: ghCapture }) -todoHttpHandler = createTodoHttpHandler({ service: todoService, commands: todoCommands, sheetFeed: taskSheetFeed, issueStates: todoIssueStates, sheetFolders: fileSheetItems }) +// The owner's own done and snoozed marks on sheet rows: kept here, never written +// to the sheet (todos/sheet-marks.mjs). +const sheetMarks = createSheetMarkStore({ file: process.env.SHEET_MARKS_FILE || join(HERE, 'data', 'sheet-marks.json') }) +todoHttpHandler = createTodoHttpHandler({ service: todoService, commands: todoCommands, sheetFeed: taskSheetFeed, issueStates: todoIssueStates, sheetFolders: fileSheetItems, sheetMarks, + onSheetMark: ({ ref, state, until, title }) => actionLog.record({ + action: state ? `sheet.${state}` : 'sheet.unmark', + actor: 'http', + channel: 'http', + target: ref, + status: 'ok', + summary: `${state === 'done' ? 'Marked done in Totem' : state === 'snoozed' ? `Snoozed until ${until}` : 'Back in the list'}: ${title || ref} (the sheet is unchanged)`, + }), +}) todoMcpTools = createTodoMcpTools({ service: todoService, commands: todoCommands, folders: taskFolderContext }) adoptTaskFolders().catch((e) => log(`task folders: the move from areas to folders failed (${e.message}); it runs again at the next start`)) diff --git a/docs/task-sheet.md b/docs/task-sheet.md index 249dee9..a27bbdd 100644 --- a/docs/task-sheet.md +++ b/docs/task-sheet.md @@ -93,12 +93,43 @@ that is set up with nothing assigned says so once at the foot of the list; one t up adds nothing to the list, and Filter › Show lists it greyed as not set up. The feed is not ETag-cached, so offline the app keeps the rows it last read in memory. +## Done and snooze, for you only + +A row you have finished, or want out of sight for a while, can leave your list without the +sheet changing: nobody else sees anything. The mark is kept in Totem +(`data/sheet-marks.json`, `SHEET_MARKS_FILE`; `todos/sheet-marks.mjs`): + +- **Done for you** hides the row until you put it back, or until the row leaves the feed + (marked Done in the sheet, given to someone else, deleted), when the mark goes with it. +- **Snoozed** hides it until the time you picked (the same presets as a task's snooze, at + most a year out), then it comes back on its own and the mark is dropped. + +`POST /api/todos/sheet/mark` with `{ "id": "", "state": "done" | "snoozed" | null, +"until": "" }` answers the feed as `GET` does. The row must be open +for you on the current read (`404 SHEET_ROW_NOT_FOUND` otherwise); `null` takes a mark off. +Each change is one action-log line (`sheet.done`, `sheet.snoozed`, `sheet.unmark`). Like the +task routes, it takes the bearer as well as a session: an agent holding `BRIDGE_SECRET` could +hide a row from the owner's list, as it could finish a task, but never change the sheet. + +In `GET /api/todos/sheet`, a marked row moves from `items` to `hidden`, carrying its `mark` +(`{ state, at, until? }`); every list draws `items`, so a client that predates marks simply +stops showing marked rows. A mark follows its row when a row above it is inserted or deleted +(it finds the row again by tab and title and is re-keyed, but only if the row still has the +due date and Who it had when marked, so a new row that reuses a title, a weekly "Send the +update", is not hidden by last week's mark); a done row re-dated or reassigned in place loses its +mark the same way and comes back; with two rows of the same title it applies only to the exact id. Marks of rows gone from a good read are dropped; a stale or +failed read keeps them all. A chat linked to a marked row still gets its `LINKED TASK` block. + +Where: the web's Tasks page (the row's mark, `x`, `s`, the pane; the Snoozed and Completed +folds hold marked rows), the chats panel's Tasks face and its task card (check, Snooze, +"Mark done for me" in the row menu), and the iPhone app's Tasks list and row page. + ## What "read-only" covers **The task feed never writes to the sheet.** It is handed only Drive's read calls (`sheetInfo`, `sheetRead`; see `taskSheetFeed` in `bridge.mjs`), and only a GET reaches it. Tests check that every request it makes to Google is a GET to the Sheets API. Nothing in the task list (completing, -snoozing, editing, sharing) changes a sheet row. +snoozing, editing, sharing) changes a sheet row: done and snooze on a row are kept in Totem (above). **The Drive tools are a separate feature and can still edit the sheet.** An agent asked to add a note to a row, or to fill in a cell, does it with the `drive__sheet_*` tools (`docs/drive.md`), as diff --git a/docs/tasks.md b/docs/tasks.md index 0f49115..bf36587 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -50,8 +50,12 @@ mirrored byte for byte to `mobile/src/lib/todos/`. buttons appear on hover and on keyboard focus. At phone width the marks drop under the title, as the app draws them. - **Sheet rows** (the read-only task sheet, `docs/task-sheet.md`) sit in the same groups, - with the sheet's mark (its name, the feed's `title` or "Task sheet", is the mark's - tooltip), no check circle, and an open-in-sheet button. Their flag keeps the + with the sheet's mark where a task has its check circle (its name, the feed's `title` + or "Task sheet", is in the mark's tooltip), and snooze and open-in-sheet buttons. The + mark turns into a check on hover: pressing it, `x` or Space marks the row done **for the + owner only**, and `s` snoozes it; both are kept in Totem and never written to the sheet + (`docs/task-sheet.md` → Done and snooze, for you only). A snoozed row waits in the + Snoozed fold and a done one in Completed, where its check puts it back. Their flag keeps the sheet's word and takes the colour of what it means beside a task's: one mapping, `sheetAsTaskPriority` in `board.ts`, ranks, filters and colours them on the web and in the app: High as P2 (amber), Medium as P3 (blue), Low in the P3 band but muted. Their "In Progress" shows only @@ -84,7 +88,8 @@ mirrored byte for byte to `mobile/src/lib/todos/`. chats linked to the task with New chat, related tasks, and Chat about this. Esc in the title or description puts the saved text back and saves nothing. A refused change puts back only the fields it touched, names them in the toast, and never draws over a later edit. A sheet row opens - read-only with Open in sheet, except its Folder, which files it (`PUT /api/chat/task-folders/`). With nothing selected the pane is today's summary and the + read-only with Open in sheet, except its Folder, which files it (`PUT /api/chat/task-folders/`), and its + check and Snooze, which are the owner's own (`POST /api/todos/sheet/mark`). With nothing selected the pane is today's summary and the keys. Below ~1100 px the pane slides over the list; at phone width it fills the screen. - **Archive and recycle bin** open in the pane from the "…" menu and are read only then; a task opened from either is shown read-only there, with Unarchive or Restore; @@ -113,8 +118,8 @@ The list is one tab stop (a roving focus over its rows). | Key | Does | |---|---| | `j` / `k`, ↓ / ↑, Home / End | Move between rows (the pane follows when open) | -| `x`, Space | Complete or reopen (select mode: select) | -| `s` / `d` / `p` | Snooze / due date / priority menu | +| `x`, Space | Complete or reopen (select mode: select); on a sheet row, done for you or back | +| `s` / `d` / `p` | Snooze / due date / priority menu (a sheet row: snooze only) | | `n` | The quick-add line (New task), from anywhere on the page | | `m` | Open the row with the note composer focused | | `g t t` | The quick-add line, from anywhere in the dashboard | diff --git a/mobile/src/features/productivity/TodosView.tsx b/mobile/src/features/productivity/TodosView.tsx index 1c4fb17..0d95c94 100644 --- a/mobile/src/features/productivity/TodosView.tsx +++ b/mobile/src/features/productivity/TodosView.tsx @@ -8,8 +8,10 @@ // then manual position), and Completed is one folded row (features/todos/list.ts). A // status line says what is left today, what is done today, and how many are snoozed. // Ticking, snoozing, "not doing" and deleting offer Undo in one inline line at the -// foot of the page, never a toast: the phone shows error toasts only. The task -// detail, a sheet row's read-only detail, the composer and the lifecycle panels are +// foot of the page, never a toast: the phone shows error toasts only. A sheet row +// can be done or snoozed for the owner only (kept in Totem, the sheet unchanged): +// a done one sits in Completed, a snoozed one in the Snoozed panel. The task +// detail, a sheet row's detail, the composer and the lifecycle panels are // sheets (src/app/todo/*); the top bar carries the title. import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { RefreshControl, StyleSheet, View } from 'react-native' @@ -23,11 +25,12 @@ import { impact } from '../../ui/haptics' import { Hi, PlusIcon } from '../../lib/icons' import { bulkBoardTodos } from '../../lib/api' import { filterTodos } from '../../lib/todos/state' -import type { Todo } from '../../lib/todos/types' +import type { SheetItem, Todo } from '../../lib/todos/types' +import { sheetDone, sheetDoneToday, sheetMarkOf, sheetSnoozed } from '../../lib/todos/board.ts' import { loadProjects } from '../../lib/chat/store' import { FAB_CLEARANCE } from '../../shell/Screen' import TodoCard from '../todos/TodoCard' -import SheetCard from '../todos/SheetCard' +import SheetCard, { type SheetMarkChange } from '../todos/SheetCard' import TodoToolbar, { type LifecyclePanel } from '../todos/TodoToolbar' import { boardActions } from '../todos/boardActions' import { afterDone, buildList, byWake, doneToday, nextWake, wakeLabel } from '../todos/board' @@ -40,7 +43,7 @@ import { useFolders } from '../todos/useFolders' import { quote, undoText, type UndoKind } from '../todos/undo' import { ArchiveLink, BoardSkeleton, ClearNote, EmptyBoard, LoadError, SectionHeader, SheetLine, ShowMore, StatusLine } from '../todos/BoardParts' import { UndoLine, type UndoState } from '../todos/detail/bits' -import { clearCreated, getBoard, loadBoard, loadIssueStates, loadSheet, setTodos, useBoard } from '../todos/store' +import { clearCreated, getBoard, loadBoard, loadIssueStates, loadSheet, markSheet, setTodos, useBoard } from '../todos/store' import { openTodo } from '../todos/nav' import { dateLabel } from '../todos/format' import { LandFlash, useLandOn } from '../../ui/landing' @@ -108,8 +111,9 @@ export default function TodosView({ active }: { active: boolean }) { const timer = setInterval(() => { const at = new Date() setNow(at) - // A snooze that ran out while the page was open: the bridge lists that task on the board again. + // A snooze that ran out while the page was open: the bridge lists that task (or sheet row) again. if (getBoard().snoozed.some((todo) => todo.snoozedUntil && new Date(todo.snoozedUntil) <= at)) void loadBoard() + if ((getBoard().sheet?.hidden ?? []).some((item) => item.mark.until && new Date(item.mark.until) <= at)) void loadSheet() }, 60_000) return () => clearInterval(timer) }, [active]) @@ -130,6 +134,9 @@ export default function TodosView({ active }: { active: boolean }) { return tasks ? scopedTodos(filterTodos(board.todos, tasks, now), shown, projects) : [] }, [board.todos, shown, now, projects]) const visibleRows = useMemo(() => visibleSheet(sheetItems, shown, now, projects), [sheetItems, shown, now, projects]) + // Rows marked done for the owner follow the same scope and search, in Completed. + const visibleDone = useMemo(() => visibleSheet(sheetDone(sheet), { ...shown, due: undefined }, now, projects), [sheet, shown, now, projects]) + const asleepRows = useMemo(() => sheetSnoozed(sheet, now), [sheet, now]) // The chips count what is open, whatever else is filtered. const scopes = useMemo(() => { const open = buildList(board.todos, sheetItems, { now }).sections.flatMap((section) => section.items) @@ -140,12 +147,15 @@ export default function TodosView({ active }: { active: boolean }) { return label === null ? null : { label, project: folderFor(folderId, projects) } }, [projects, scope]) const rows = useMemo(() => listRows(visible, visibleRows, { - now, completedOpen: view.completedOpen, showAllDone, archiveCount: board.archiveCount, filtered: filtering, - }), [visible, visibleRows, now, view.completedOpen, showAllDone, board.archiveCount, filtering]) + now, completedOpen: view.completedOpen, showAllDone, archiveCount: board.archiveCount, filtered: filtering, sheetDone: visibleDone, + }), [visible, visibleRows, visibleDone, now, view.completedOpen, showAllDone, board.archiveCount, filtering]) const near = useMemo(() => orderNeighbours(rows), [rows]) - const finishedToday = useMemo(() => doneToday(board.todos, now) + doneToday(board.archivedCompletions, now), [board.todos, board.archivedCompletions, now]) + // Sheet rows marked done today count too, as on the web. + const finishedToday = useMemo(() => doneToday(board.todos, now) + doneToday(board.archivedCompletions, now) + sheetDoneToday(board.sheet, now), [board.todos, board.archivedCompletions, board.sheet, now]) const left = useMemo(() => leftToday(board.todos, sheetItems, now), [board.todos, sheetItems, now]) - const wakeAt = useMemo(() => nextWake(board.snoozed, now), [board.snoozed, now]) + // Snoozed tasks and snoozed sheet rows, as one count and one "next back". + const snoozedCount = board.snoozed.length + asleepRows.length + const wakeAt = useMemo(() => nextWake([...board.snoozed, ...asleepRows.map((item) => ({ snoozedUntil: item.mark.until ?? null }))], now), [board.snoozed, asleepRows, now]) const wakeText = wakeAt ? wakeLabel(wakeAt, now) : null const note = sheetNote(sheet, board.sheetError) @@ -225,6 +235,23 @@ export default function TodosView({ active }: { active: boolean }) { offer('delete', todo, () => actions.restore(todo)) } + // A sheet row, done or snoozed for the owner only; Undo puts its mark back as it was. + async function markRow(item: SheetItem, next: SheetMarkChange, until?: Date) { + const prior = sheetMarkOf((getBoard().sheet?.hidden ?? []).find((row) => row.id === item.id), new Date()) + setMoveError('') + try { + await markSheet(item.id, next, until ?? null) + } catch (cause) { + setMoveError(cause instanceof Error && cause.message ? cause.message : next ? 'The row could not be marked.' : 'The row could not be put back.') + return + } + if (!next) return + const text = next === 'done' + ? `Done for you: ${quote(item.title)}. ${source} is unchanged.` + : `Snoozed ${quote(item.title)} until ${until ? wakeLabel(until, new Date()) : 'later'}.` + setUndo({ id: Date.now(), text, action: { label: 'Undo', run: () => { impact(); void markSheet(item.id, prior?.state ?? null, prior?.until ? new Date(prior.until) : null).catch(() => {}) } } }) + } + async function bulk(operation: string, value?: unknown) { if (!selection.size) return const chosen = getBoard().todos.filter((todo) => selection.has(todo.id)) @@ -261,14 +288,14 @@ export default function TodosView({ active }: { active: boolean }) { const fabBottom = Math.max(insets.bottom, 14) + 8 + 5 const error = board.error const todos = board.todos - const snoozedNote = board.snoozed.length - ? `${board.snoozed.length.toLocaleString()} snoozed${wakeText ? `, the next back ${wakeText}` : ''}.` + const snoozedNote = snoozedCount + ? `${snoozedCount.toLocaleString()} snoozed${wakeText ? `, the next back ${wakeText}` : ''}.` : null const upcoming = useMemo(() => { - const ahead = byWake(board.snoozed)[0] + const ahead = byWake([...board.snoozed, ...asleepRows.map((item) => ({ id: item.id, title: item.title, snoozedUntil: item.mark.until ?? null }))])[0] if (!ahead) return null return `Next back: ${quote(ahead.title)}${wakeText ? `, ${wakeText}` : ''}.` - }, [board.snoozed, wakeText]) + }, [board.snoozed, asleepRows, wakeText]) // The first date ahead, for "nothing due today"; the tasks themselves are the cards under the line. const nextUp = useMemo(() => { @@ -286,7 +313,13 @@ export default function TodosView({ active }: { active: boolean }) { if (row.kind === 'sheet') { // A sheet row names its folder only when filed in a project: Personal on every row would be noise beside the sheet's name. const folder = folderOf(row.item.folderId) - return + return ( + markRow(item, next, until)} swipeable={!bulkMode} + /> + ) } const todo = row.todo const pair = row.section !== 'done' ? near.get(todo.id) : undefined @@ -343,7 +376,7 @@ export default function TodosView({ active }: { active: boolean }) { ItemSeparatorComponent={() => } ListHeaderComponent={( <> - openPanel('snoozed')} /> + openPanel('snoozed')} /> {note?.tone === 'problem' ? void loadSheet({ refresh: true })} /> : null} )} @@ -365,7 +398,7 @@ export default function TodosView({ active }: { active: boolean }) { { setBulkMode(value); if (!value) setSelection(new Set()) }} onBulk={(operation, value) => void bulk(operation, value)} diff --git a/mobile/src/features/todos/SheetCard.tsx b/mobile/src/features/todos/SheetCard.tsx index 829d1e5..df65462 100644 --- a/mobile/src/features/todos/SheetCard.tsx +++ b/mobile/src/features/todos/SheetCard.tsx @@ -1,31 +1,66 @@ -// One open row of the shared task sheet, drawn among the tasks (GET /api/todos/sheet). -// Read-only: Totem never writes to the sheet, so the row has no check circle and no -// swipe; the sheet's mark sits where the circle would. Tapping opens its detail (the -// task route, todo/[id], with the row's "sheet:…" id); holding offers Open in sheet. -// VoiceOver reads it as one element, with Open in sheet as an action. -import React from 'react' +// One row of the shared task sheet, drawn among the tasks (GET /api/todos/sheet). +// Totem never writes to the sheet. The owner can still get a row out of the way: +// done for him, or snoozed, kept in Totem only (todos/sheet-marks.mjs; store.ts +// markSheet), and the sheet is unchanged. The sheet's mark sits where a task's +// circle would, so it never reads as something everyone sees ticked. Swipe right +// for Done for me (Put back on a done row), left for Tomorrow and the snooze +// presets; the "…" and a long press hold the same, plus Open in sheet. Tapping +// opens its detail (the task route, todo/[id], with the row's "sheet:…" id). +// VoiceOver reads it as one element, with the actions on it. +import React, { useRef, useState } from 'react' import { StyleSheet, View } from 'react-native' +import { MenuView, type MenuAction } from '@react-native-menu/menu' +import ReanimatedSwipeable, { type SwipeableMethods } from 'react-native-gesture-handler/ReanimatedSwipeable' import IconTable from '@tabler/icons-react-native/dist/esm/icons/IconTable.mjs' +import IconZzz from '@tabler/icons-react-native/dist/esm/icons/IconZzz.mjs' import { colors } from '../../theme' import { T } from '../../ui/Text' import { Press } from '../../ui/kit' -import { showMenu } from '../../ui/menu' +import { showActionTree } from '../../ui/menu' import { tap } from '../../ui/haptics' -import { Hi, CalendarDaysIcon, FlagIcon } from '../../lib/icons' +import { Hi, ArrowUturnLeftIcon, CalendarDaysIcon, CheckIcon, EllipsisHorizontalIcon, FlagIcon, SunIcon } from '../../lib/icons' import { openUrl } from '../../lib/siblingApps' -import type { SheetItem } from '../../lib/todos/types' +import type { SheetHiddenItem, SheetItem } from '../../lib/todos/types' import type { Project } from '../../lib/chat/types' import { ProjectIcon } from '../chat/ThreadIcon' -import { dateLabel, dueText, dueTone } from './format' +import { dateLabel, dueText, dueTone, snoozeTimes } from './format' +import { morningSnooze, sheetMarkOf, wakeLabel } from './board' import { SHEET_PRIORITY_WORD } from './list' import { openTodo } from './nav' import { sheetPriorityColor } from './compose/labels' +import { PickWhenSheet } from './ui' +import { SWIPE_DONE_INK } from './TodoCard' // The sheet's own word, in the colour of the task priority it ranks with (sheetPriorityColor). export const SHEET_GREEN = '#79cf91' -export default function SheetCard({ item, source, now, dueSection, dim, folder }: { - item: SheetItem +export type SheetMarkChange = 'done' | 'snoozed' | null + +/** The row's menu: Done for me or Put back, the snooze presets (one submenu level: Fabric drops deeper), the sheet. */ +export function sheetActions(item: SheetItem | SheetHiddenItem, source: string, now: Date, canMark: boolean): MenuAction[] { + const mark = sheetMarkOf(item, now) + return [ + ...(canMark && mark ? [{ id: 'putback', title: 'Put back on my list', subtitle: mark.state === 'done' ? 'Marked done for you' : mark.until ? `Snoozed until ${wakeLabel(new Date(mark.until), now)}` : undefined, image: 'arrow.uturn.left' }] : []), + ...(canMark && mark?.state !== 'done' ? [{ id: 'done', title: 'Done for me', subtitle: `${source} is unchanged`, image: 'checkmark.circle' }] : []), + ...(canMark && mark?.state !== 'done' ? [{ + id: 'snooze', title: 'Snooze…', subtitle: 'For you only', image: 'moon.zzz', + subactions: [ + ...snoozeTimes(now, item.dueDate).map((option): MenuAction => ({ id: `snooze:${option.value.toISOString()}`, title: option.label, subtitle: option.detail })), + { id: 'snooze:pick', title: 'Pick a date and time', image: 'calendar' }, + ], + } satisfies MenuAction] : []), + { + id: 'more', title: '', displayInline: true, subactions: [ + { id: 'sheet', title: `Open in ${source}`, image: 'arrow.up.right.square' }, + { id: 'details', title: 'Details', image: 'info.circle' }, + ], + }, + ] +} + +export default function SheetCard({ item, source, now, dueSection, dim, folder, onMark, swipeable }: { + /** An open row, or one the owner marked (it carries `mark`: Completed, or the Snoozed panel). */ + item: SheetItem | SheetHiddenItem /** The sheet's name (the feed's title). */ source: string now: Date @@ -35,7 +70,16 @@ export default function SheetCard({ item, source, now, dueSection, dim, folder } dim?: boolean /** The project or folder the row is filed under, when the row should say it (not under its own chip, not Personal). */ folder?: { label: string; project: Pick } | null + /** Done or snoozed for the owner only (the sheet unchanged), or put back with null. */ + onMark?: (item: SheetItem, next: SheetMarkChange, until?: Date) => unknown + /** List rows swipe; nowhere else. */ + swipeable?: boolean }) { + const [pick, setPick] = useState(false) + const swipe = useRef(null) + const mark = sheetMarkOf(item, now) + const done = mark?.state === 'done' + const canMark = Boolean(onMark) && !dim const tone = item.dueDate ? dueTone(item.dueDate, now, 'todo') : '' const dueColor = tone === 'overdue' ? '#ff7f95' : tone === 'today' ? '#efc765' : colors.muted @@ -44,6 +88,7 @@ export default function SheetCard({ item, source, now, dueSection, dim, folder } {source} , ] + if (done) marks.push(Done for you) if (folder) { marks.push( @@ -52,7 +97,7 @@ export default function SheetCard({ item, source, now, dueSection, dim, folder } , ) } - if (item.dueDate && !(dueSection === 'today' && tone === 'today')) { + if (item.dueDate && !done && !(dueSection === 'today' && tone === 'today')) { const text = dueSection === 'overdue' && tone === 'overdue' ? dateLabel(item.dueDate) : dueText(item.dueDate, now) marks.push( @@ -61,7 +106,7 @@ export default function SheetCard({ item, source, now, dueSection, dim, folder } , ) } - if (item.priority) { + if (item.priority && !done) { marks.push( @@ -72,21 +117,50 @@ export default function SheetCard({ item, source, now, dueSection, dim, folder } const spoken = [ item.title, - `from ${source}, read only`, + `from ${source}`, + done ? 'done for you' : null, folder ? `in ${folder.label}` : null, - item.dueDate ? (tone === 'overdue' ? `overdue, ${dateLabel(item.dueDate)}` : `due ${dueText(item.dueDate, now)}`) : null, - item.priority ? `${SHEET_PRIORITY_WORD[item.priority]} priority` : null, + item.dueDate && !done ? (tone === 'overdue' ? `overdue, ${dateLabel(item.dueDate)}` : `due ${dueText(item.dueDate, now)}`) : null, + item.priority && !done ? `${SHEET_PRIORITY_WORD[item.priority]} priority` : null, item.who ? `assigned to ${item.who}` : null, ].filter(Boolean).join(', ') const open = () => openTodo({ id: item.id }) const openSheet = () => void openUrl(item.url) - const hold = () => { tap(); showMenu([{ label: `Open in ${source}`, onPress: openSheet }, { label: 'Details', onPress: open }], { title: item.title }) } + const actions = sheetActions(item, source, now, canMark) - return ( + function act(id: string) { + tap() + if (id === 'done') return void onMark?.(item, 'done') + if (id === 'putback') return void onMark?.(item, null) + // The picker waits for the menu to finish closing: iOS refuses a second presentation mid-animation. + if (id === 'snooze:pick') return void setTimeout(() => setPick(true), 400) + if (id.startsWith('snooze:')) return void onMark?.(item, 'snoozed', new Date(id.slice(7))) + if (id === 'sheet') return openSheet() + if (id === 'details') return open() + } + const hold = () => showActionTree(actions, act, item.title) + + const a11yActions = dim ? undefined : [ + { name: 'activate' }, + ...(canMark && !done ? [{ name: 'done', label: 'Done for me' }] : []), + ...(canMark && mark ? [{ name: 'putback', label: 'Put back on my list' }] : []), + { name: 'longpress', label: 'Actions' }, + { name: 'sheet', label: `Open in ${source}` }, + ] + function a11yAction(name: string) { + if (name === 'done' || name === 'putback') return act(name) + if (name === 'longpress') return hold() + if (name === 'sheet') return openSheet() + return open() + } + + const card = ( - + + {done ? : } + (nativeEvent.actionName === 'sheet' ? openSheet() : open())} + accessibilityHint={dim ? 'Sheet rows cannot be selected.' : canMark ? 'Opens the row. Hold for Done for me, Snooze and Open in sheet.' : 'Opens the row. Hold for Open in sheet.'} + accessibilityActions={a11yActions} + onAccessibilityAction={({ nativeEvent }) => a11yAction(nativeEvent.actionName)} > - {item.title} + {item.title} {marks} - + {canMark ? ( + act(nativeEvent.event)}> + + + + + ) : } + {canMark ? ( + setPick(false)} + onSubmit={(value) => { setPick(false); void onMark?.(item, 'snoozed', value) }} + /> + ) : null} ) + + if (!swipeable || !canMark) return card + + const right = done + ? { icon: ArrowUturnLeftIcon, color: colors.accent, ink: colors.white, label: 'Put back' } + : { icon: CheckIcon, color: colors.green, ink: SWIPE_DONE_INK, label: 'Done for me' } + const morning = !done ? morningSnooze(now) : null + return ( + ( + + + {right.label} + + )} + renderRightActions={done ? undefined : () => ( + + {morning ? ( + { swipe.current?.close(); act(`snooze:${morning.value.toISOString()}`) }} + > + + {morning.label} + + ) : null} + ({ id: `snooze:${option.value.toISOString()}`, title: option.label, subtitle: option.detail })), + { id: 'snooze-more', title: '', displayInline: true, subactions: [{ id: 'snooze:pick', title: 'Pick a date and time', image: 'calendar' }] }, + ]} + themeVariant="dark" + onPressAction={({ nativeEvent }) => { swipe.current?.close(); act(nativeEvent.event) }} + > + + + Snooze + + + + )} + onSwipeableOpen={(direction) => { + // RIGHT means the card travelled right, uncovering the left action. + if (direction !== 'right') return + swipe.current?.close() + act(done ? 'putback' : 'done') + }} + > + {card} + + ) } const st = StyleSheet.create({ @@ -114,9 +264,16 @@ const st = StyleSheet.create({ borderWidth: StyleSheet.hairlineWidth, borderColor: colors.line, borderRadius: 12, backgroundColor: colors.bg2, }, lead: { width: 44, height: 44, marginTop: 6, alignItems: 'center', justifyContent: 'center' }, - // The same 24 pt footprint as a task's ring, square, so it never reads as something to tick. + // The same 24 pt footprint as a task's ring, square, so it never reads as something everyone sees ticked. badge: { width: 24, height: 24, borderRadius: 6, alignItems: 'center', justifyContent: 'center', backgroundColor: '#3fb95018' }, + badgeDone: { backgroundColor: colors.green }, body: { flex: 1, minWidth: 0, gap: 3, paddingTop: 15, paddingBottom: 13, paddingLeft: 2 }, + struck: { textDecorationLine: 'line-through' }, marks: { flexDirection: 'row', flexWrap: 'wrap', alignItems: 'center', columnGap: 12, rowGap: 3, marginTop: 2 }, mark: { flexDirection: 'row', alignItems: 'center', gap: 4, maxWidth: '100%' }, + more: { width: 44, height: 44, marginTop: 6, alignItems: 'center', justifyContent: 'center' }, + swipeLeft: { flex: 1, flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 20, borderRadius: 12, marginRight: -12 }, + swipeRight: { flexDirection: 'row', gap: 6, paddingLeft: 8 }, + swipeBtn: { width: 72, alignItems: 'center', justifyContent: 'center', gap: 4, borderRadius: 12 }, + swipeMenuBtn: { flex: 1 }, }) diff --git a/mobile/src/features/todos/SheetItemPage.tsx b/mobile/src/features/todos/SheetItemPage.tsx index 15ca843..82e539b 100644 --- a/mobile/src/features/todos/SheetItemPage.tsx +++ b/mobile/src/features/todos/SheetItemPage.tsx @@ -1,9 +1,10 @@ // One row of the shared task sheet, opened from the list (the task route, todo/[id], -// with the row's "sheet:…" id). Read-only: Totem never writes to the sheet (a partner -// shares it), so everything here is the sheet's own words, and the one action on the -// row itself is Open in sheet, which opens that row in the browser or the Sheets app. -// The one thing kept in Totem is where the row is filed (a chat project or folder, or -// Personal), set from the Folder row (PUT /api/chat/task-folders/). +// with the row's "sheet:…" id). Totem never writes to the sheet (a partner shares it), +// so everything here is the sheet's own words, and Open in sheet opens that row in the +// browser or the Sheets app. What is kept in Totem, for the owner only: where the row +// is filed (a chat project or folder, or Personal; PUT /api/chat/task-folders/), +// and whether it is done or snoozed for the owner (POST /api/todos/sheet/mark, store.ts +// markSheet), which takes it off the owner's list and leaves the sheet unchanged. import React, { useState } from 'react' import { ScrollView, StyleSheet, View } from 'react-native' import { router } from 'expo-router' @@ -14,9 +15,9 @@ import IconUser from '@tabler/icons-react-native/dist/esm/icons/IconUser.mjs' import { colors, fonts } from '../../theme' import { T } from '../../ui/Text' import { Btn, IconBtn } from '../../ui/kit' -import { Hi, ArrowTopRightOnSquareIcon, CalendarDaysIcon, FlagIcon, FolderIcon, UserIcon, XMarkIcon, type IconType } from '../../lib/icons' +import { Hi, ArrowTopRightOnSquareIcon, ArrowUturnLeftIcon, CalendarDaysIcon, CheckIcon, FlagIcon, FolderIcon, UserIcon, XMarkIcon, type IconType } from '../../lib/icons' import { openUrl } from '../../lib/siblingApps' -import type { SheetItem } from '../../lib/todos/types' +import type { SheetHiddenItem, SheetItem } from '../../lib/todos/types' import { dueText, dueTone } from './format' import { SHEET_PRIORITY_WORD, linkParts } from './list' import { PropertyGroup, PropertyRow } from './detail/PropertyRow' @@ -25,18 +26,26 @@ import { sheetPriorityColor } from './compose/labels' import { InlineError, tone } from './ui' import { folderActions, folderFor, folderLabel, folderPicked } from './folders' import { useFolders } from './useFolders' -import { fileSheet } from './store' +import { fileSheet, markSheet } from './store' +import { snoozeTimes } from './format' +import { sheetMarkOf, wakeLabel } from './board' +import { PickWhenSheet } from './ui' +import { showMenu } from '../../ui/menu' import { ProjectIcon } from '../chat/ThreadIcon' -import { tap, warn } from '../../ui/haptics' +import { success, tap, warn } from '../../ui/haptics' /** A task route's id that names a sheet row rather than a task. */ export const isSheetId = (id: string | undefined) => typeof id === 'string' && id.startsWith('sheet:') -export default function SheetItemPage({ item, source, fetchedAt }: { item: SheetItem | null; source: string; fetchedAt: string | null }) { +export default function SheetItemPage({ item, source, fetchedAt }: { item: SheetItem | SheetHiddenItem | null; source: string; fetchedAt: string | null }) { const insets = useSafeAreaInsets() const { projects } = useFolders() const [fileError, setFileError] = useState('') + const [markError, setMarkError] = useState('') + const [pick, setPick] = useState(false) const now = new Date() + const mark = sheetMarkOf(item, now) + const snoozedUntil = mark?.state === 'snoozed' && mark.until && new Date(mark.until) > now ? mark.until : null const head = ( @@ -44,7 +53,7 @@ export default function SheetItemPage({ item, source, fetchedAt }: { item: Sheet {source} - Read-only + {mark?.state === 'done' ? 'Done for you' : snoozedUntil ? `Snoozed until ${wakeLabel(new Date(snoozedUntil), now)}` : 'Read-only'} router.back()} /> @@ -69,6 +78,18 @@ export default function SheetItemPage({ item, source, fetchedAt }: { item: Sheet setFileError('') fileSheet(item.id, folder).catch((cause) => { warn(); setFileError(cause instanceof Error && cause.message ? cause.message : 'The row could not be filed there.') }) } + const id = item.id + const setMark = (next: 'done' | 'snoozed' | null, until: Date | null = null) => { + tap() + setMarkError('') + markSheet(id, next, until).then(() => { success(); if (next) router.back() }) + .catch((cause) => { warn(); setMarkError(cause instanceof Error && cause.message ? cause.message : 'The row could not be marked.') }) + } + const snoozeMenu = () => showMenu([ + ...snoozeTimes(now, item.dueDate).map((option) => ({ label: `${option.label} (${option.detail})`, onPress: () => setMark('snoozed', option.value) })), + // The picker waits for the action sheet to finish closing: iOS refuses a second presentation mid-animation. + { label: 'Pick a date and time', onPress: () => void setTimeout(() => setPick(true), 400) }, + ], { title: 'Snooze until', message: `For you only; ${source} is unchanged.` }) const due = item.dueDate ? dueTone(item.dueDate, now, 'todo') : '' const dueColor = due === 'overdue' ? tone.red.color : due === 'today' ? tone.amber.color : colors.text return ( @@ -91,6 +112,17 @@ export default function SheetItemPage({ item, source, fetchedAt }: { item: Sheet {`Where ${source}’s rows go until you file them (Settings → Tasks).`} ) : null} {fileError ? {fileError} : null} + {/* Done and snooze are the owner's alone, kept in Totem; the sheet is never written. */} + {mark ? ( + setMark(null)} style={{ minHeight: 48 }} /> + ) : ( + + setMark('done')} style={{ flex: 1, minHeight: 48 }} /> + + + )} + {mark?.state === 'snoozed' ? : null} + {markError ? {markError} : null} {item.notes ? ( Notes & links @@ -111,9 +143,19 @@ export default function SheetItemPage({ item, source, fetchedAt }: { item: Sheet style={{ minHeight: 48 }} /> - {`Row ${item.row}. Change it in the sheet; Totem only reads it${fetchedAt ? `, last read ${new Date(fetchedAt).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}` : ''}.`} + {`Row ${item.row}. Change it in the sheet; Totem only reads it${fetchedAt ? `, last read ${new Date(fetchedAt).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}` : ''}. Done and snooze here are yours alone: the sheet is unchanged.`} + setPick(false)} + onSubmit={(value) => { setPick(false); setMark('snoozed', value) }} + /> ) } @@ -140,5 +182,6 @@ const st = StyleSheet.create({ body: { paddingHorizontal: 16, paddingTop: 10, gap: 14 }, row: { flexDirection: 'row', alignItems: 'center', gap: 12, minHeight: 48, paddingHorizontal: 14 }, notes: { gap: 6 }, + actions: { flexDirection: 'row', gap: 10 }, link: { textDecorationLine: 'underline' }, }) diff --git a/mobile/src/features/todos/TodoDetailScreen.tsx b/mobile/src/features/todos/TodoDetailScreen.tsx index c8a711e..6f72ecf 100644 --- a/mobile/src/features/todos/TodoDetailScreen.tsx +++ b/mobile/src/features/todos/TodoDetailScreen.tsx @@ -4,8 +4,8 @@ // saves that field at once. Nothing waits for a Save button. Below: notes, related // tasks, the linked GitHub issue, and the task's history. // Opened from a card with ?focus=notes it lands on the note field, as "+ Add a note" -// does on the web. A "sheet:…" id is a row of the shared task sheet, which opens the -// read-only SheetItemPage instead. +// does on the web. A "sheet:…" id is a row of the shared task sheet, which opens +// SheetItemPage instead (the sheet's words, read-only; done and snooze for the owner only). import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { StyleSheet, TextInput, View } from 'react-native' import { router, useLocalSearchParams } from 'expo-router' @@ -94,7 +94,8 @@ function SheetRow({ id }: { id: string }) { ) } - const item = sheet.items.find((entry) => entry.id === id) ?? null + // A row the owner marked done or snoozed is in `hidden`, still openable (to put it back). + const item = sheet.items.find((entry) => entry.id === id) ?? sheet.hidden?.find((entry) => entry.id === id) ?? null return } diff --git a/mobile/src/features/todos/TodoLifecycleScreen.tsx b/mobile/src/features/todos/TodoLifecycleScreen.tsx index b133d75..9096981 100644 --- a/mobile/src/features/todos/TodoLifecycleScreen.tsx +++ b/mobile/src/features/todos/TodoLifecycleScreen.tsx @@ -1,7 +1,8 @@ // The board's lifecycle panels (web/src/todos/TodoLifecyclePanels.tsx, plus the Done // column's archive, whose header a phone never shows) as one sheet per panel, opened // from the board's "…" menu, its snoozed chip and its archive link: snoozed tasks -// (soonest back first, each with Wake now), the recycle bin, the archive by +// (soonest back first, each with Wake now; the shared sheet's rows the owner snoozed +// (for the owner only) come after them, with Put back), the recycle bin, the archive by // day/week/month/year, retention. import React, { useEffect, useState } from 'react' import { SectionList, StyleSheet, View } from 'react-native' @@ -18,8 +19,9 @@ import { groupArchive, type ArchivePeriod } from '../../lib/todos/archive' import type { TodoPreferences } from '../../lib/todos/types' import TodoCard from './TodoCard' import { archiveHourLabel } from './format' -import { loadBoard, restoreTodo, showArchive, useBoard, wakeTodo } from './store' +import { loadBoard, markSheet, restoreTodo, showArchive, useBoard, wakeTodo } from './store' import { byWake, wakeLabel } from './board' +import { sheetName, sheetSnoozed } from '../../lib/todos/board.ts' import { DateField, Field, FieldInput, InlineError, InlineNotice, SheetFrame, SheetHead } from './ui' import { openTodo } from './nav' @@ -59,7 +61,14 @@ function Panels({ panel }: { panel: Exclude }) { try { await wakeTodo(id); success() } catch (cause) { setError(cause instanceof Error ? cause.message : 'Task could not be woken.') } } + async function wakeRow(id: string) { + setError('') + try { await markSheet(id, null); success() } + catch (cause) { setError(cause instanceof Error ? cause.message : 'The row could not be put back.') } + } const now = new Date() + const asleepRows = sheetSnoozed(board.sheet, now) + const source = sheetName(board.sheet) async function purge() { const days = prefs.recyclePurgeDays ?? 30 if (!(await confirm('Purge eligible deleted tasks?', { message: `Tasks in the recycle bin for more than ${days} days are removed for good. The task database is backed up first.`, confirmLabel: 'Purge' }))) return @@ -83,7 +92,7 @@ function Panels({ panel }: { panel: Exclude }) { {error} {notice} {panel === 'snoozed' ? ( - board.snoozed.length ? ( + board.snoozed.length || asleepRows.length ? ( {byWake(board.snoozed).map((todo, index) => { const at = todo.snoozedUntil ? new Date(todo.snoozedUntil) : null @@ -103,6 +112,22 @@ function Panels({ panel }: { panel: Exclude }) { ) })} + {asleepRows.map((item, index) => { + const at = item.mark.until ? new Date(item.mark.until) : null + return ( + + openTodo({ id: item.id })} style={{ flex: 1, minHeight: 44, justifyContent: 'center', gap: 2 }} accessibilityRole="button" + accessibilityLabel={`${item.title}, from ${source}, snoozed for you${at ? `, back ${wakeLabel(at, now)}` : ''}`} accessibilityHint="Opens the row"> + {item.title} + + + {`${source}${at ? ` · back ${wakeLabel(at, now)}` : ''}`} + + + void wakeRow(item.id)} style={{ minHeight: 44 }} /> + + ) + })} ) : No snoozed tasks. ) : null} diff --git a/mobile/src/features/todos/board.ts b/mobile/src/features/todos/board.ts index 1d5b879..30f3de4 100644 --- a/mobile/src/features/todos/board.ts +++ b/mobile/src/features/todos/board.ts @@ -3,6 +3,6 @@ // one place. The page's own rows over it (buildList's groups with the sheet's rows, // Completed folded) are in list.ts. export { - afterDone, buildList, byFinished, byWake, dayKey, doneToday, morningSnooze, moveBeside, nextWake, rolledOccurrence, rollsOnCompletion, wakeLabel, + afterDone, buildList, byFinished, byWake, dayKey, doneToday, morningSnooze, moveBeside, nextWake, rolledOccurrence, rollsOnCompletion, sheetMarkOf, wakeLabel, type DoneFollowUp, } from '../../lib/todos/board.ts' diff --git a/mobile/src/features/todos/list.test.mjs b/mobile/src/features/todos/list.test.mjs index 680748e..397cbf1 100644 --- a/mobile/src/features/todos/list.test.mjs +++ b/mobile/src/features/todos/list.test.mjs @@ -264,18 +264,42 @@ test('the sheet alone, with nothing to draw: set up, not set up, failed and stil assert.match(sheetOnlyEmpty('Task sheet', null, '').title, /^Reading Task sheet/) }) -test('sheet rows are read-only: no check circle, no swipe, nothing that writes', () => { +test('sheet rows never write the sheet: done and snooze are the owner’s marks, kept in Totem', () => { const card = read(join(features, 'todos/SheetCard.tsx')) - assert.doesNotMatch(card, /CheckCircle|Swipeable|onMove|moveBoardTodo|updateBoardTodo|lib\/api/) + // No task circle and no task write: a sheet row is never a task. + assert.doesNotMatch(card, /CheckCircle|onMove|moveBoardTodo|updateBoardTodo|lib\/api/) + // Its swipe and menu go through onMark, which the page sends to store.ts markSheet. + assert.match(card, /Swipeable[\s\S]*onSwipeableOpen=\{[\s\S]{0,300}act\(done \? 'putback' : 'done'\)/) + assert.match(card, /is unchanged/) const detail = read(join(features, 'todos/SheetItemPage.tsx')) assert.match(detail, /Open in/) + assert.match(detail, /markSheet\(/) + assert.match(detail, /the sheet is unchanged/) assert.doesNotMatch(detail, /\b(updateBoardTodo|moveBoardTodo|createBoardTodo|sendJSON|TextInput)\b/) - // The page hands a sheet row to SheetCard, never to TodoCard, and the task route sends a sheet id to the read-only page. + // The only write the store makes for a sheet row's state is the mark route, never a task route. + const store = read(join(features, 'todos/store.ts')) + assert.match(store, /export async function markSheet[\s\S]{0,900}markSheetRow\(id, next, until\)/) + // The page hands a sheet row to SheetCard, never to TodoCard, and the task route sends a sheet id to its own page. const view = read(join(features, 'productivity/TodosView.tsx')) - assert.match(view, /row\.kind === 'sheet'[\s\S]{0,200} { + const done = [row({ title: 'HQ done' })] + const fin = todo({ id: 'fin', status: 'done', completedAt: '2026-11-04T09:00:00.000Z' }) + const open = todo({ id: 'open' }) + // The "all clear" note is clearScope's business, not this test's. + const noClear = (rows) => shape(rows).filter((r) => !r.startsWith(', { kind: 'card' }> | { kind: 'card'; key: string; todo: Todo; section: RowSection } - | { kind: 'sheet'; key: string; item: SheetItem; section: SectionKey } + | { kind: 'sheet'; key: string; item: SheetItem; section: RowSection } const TONE: Record = { overdue: 'overdue', today: 'today', upcoming: 'upcoming', nodate: 'quiet' } @@ -86,6 +87,8 @@ export interface RowOptions { /** A search or filter is narrowing the list, so "all clear" would claim more than it can see. */ filtered?: boolean doneLimit?: number + /** Sheet rows marked done for the owner (lib/todos/board.ts sheetDone), drawn first in Completed. */ + sheetDone?: readonly SheetItem[] } /** The page's rows: the "all clear" note when it applies, the due groups with sheet rows mixed in, then Completed. */ @@ -104,10 +107,20 @@ export function listRows(todos: readonly Todo[], sheet: readonly SheetItem[], op : { kind: 'sheet', key: item.item.id, item: item.item, section: section.key }) } } - rows.push(...completedRows(list.completed, { + const done = completedRows(list.completed, { completedOpen: options.completedOpen, showAllDone: options.showAllDone, manual: true, archiveCount: options.archiveCount, doneLimit: options.doneLimit, - }, 'done', 'completed')) + }, 'done', 'completed') + const marked = options.sheetDone ?? [] + if (marked.length) { + // Counted in Completed's heading, and drawn under it before the tasks, the latest mark first. + const head = done[0]?.kind === 'header' + ? { ...done[0], count: done[0].count + marked.length } + : { kind: 'header' as const, key: 'h-done', title: 'Completed', count: marked.length, tone: 'completed' as const, collapsible: true, open: options.completedOpen } + rows.push(head) + if (options.completedOpen) for (const item of marked) rows.push({ kind: 'sheet', key: item.id, item, section: 'done' }) + rows.push(...done.slice(1)) + } else rows.push(...done) return rows } diff --git a/mobile/src/features/todos/store.ts b/mobile/src/features/todos/store.ts index a61747d..af56a42 100644 --- a/mobile/src/features/todos/store.ts +++ b/mobile/src/features/todos/store.ts @@ -4,10 +4,11 @@ // so the state moves into a small external store they all read. import { useSyncExternalStore } from 'react' import { - deleteBoardTodo, fileSheetRow as fileSheetRowApi, getIssueStates, getSheetFeed, getTodoBoard, getTodoPreferences, isAccountChanged, peekTodoBoard, peekTodoPreferences, + deleteBoardTodo, fileSheetRow as fileSheetRowApi, getIssueStates, markSheetRow, getSheetFeed, getTodoBoard, getTodoPreferences, isAccountChanged, peekTodoBoard, peekTodoPreferences, restoreBoardTodo, updateBoardTodo, } from '../../lib/api' import type { IssueState, SheetFeed, Todo, TodoPreferences } from '../../lib/todos/types' +import { withSheetMark } from '../../lib/todos/board.ts' import { freshRead } from './freshRead' import { createIssueStatesLoader } from './issueLink' import { readUntilStable } from './readUntilStable' @@ -238,12 +239,16 @@ export async function restoreTodo(id: string) { * says so once, quietly, under the list. */ let sheetRead: Promise | null = null +// Bumped by each mark (markSheet): a read or a mark's answer from before a later mark is not drawn. +let markSeq = 0 async function readSheet(refresh: boolean) { // A first read that failed: clear the error while trying again, so the page shows it is trying. if (!state.sheet && state.sheetError) set({ sheetError: '' }) try { + const seq = markSeq const feed = await getSheetFeed({ refresh }) - set({ sheet: feed, sheetError: '' }) + // A mark made while this read was out is newer than what it read. + if (seq === markSeq) set({ sheet: feed, sheetError: '' }) } catch (cause) { if (!isAccountChanged(cause)) set({ sheetError: cause instanceof Error ? cause.message : 'The task sheet could not load.' }) } @@ -272,6 +277,30 @@ export async function fileSheet(id: string, folderId: string | null) { } } +/** + * Mark a sheet row done or snoozed for the owner only, or put it back with null. Kept + * in Totem, never written to the sheet (todos/sheet-marks.mjs). Drawn at once; the + * bridge's answer is the feed. Throws when the bridge refuses, after reading the feed again. + */ +export async function markSheet(id: string, next: 'done' | 'snoozed' | null, until: Date | null = null) { + const feed = state.sheet + if (!feed?.configured) return + const mark = next ? { state: next, at: new Date().toISOString(), ...(next === 'snoozed' && until ? { until: until.toISOString() } : {}) } : null + const seq = ++markSeq + set({ sheet: withSheetMark(feed, id, mark) }) + try { + // A read already out began before the mark and would draw the row back: let it land first. + const answer = await markSheetRow(id, next, until) + if (sheetRead) await sheetRead + // Another mark made since answers with it in, so only the latest answer is drawn. + if (seq === markSeq) set({ sheet: answer, sheetError: '' }) + } catch (cause) { + if (sheetRead) await sheetRead + await loadSheet() + throw cause + } +} + /** * The live state of linked issues; only asked for when a task on the board links one. * Failing quietly keeps the last good states. A call while a read is out gets one more diff --git a/mobile/src/lib/api.ts b/mobile/src/lib/api.ts index e563179..103e9b4 100644 --- a/mobile/src/lib/api.ts +++ b/mobile/src/lib/api.ts @@ -503,6 +503,12 @@ export const getSheetFeed = ({ refresh = false }: { refresh?: boolean } = {}) => */ export const fileSheetRow = (id: string, folderId: string | null) => sendJSON(`/api/chat/task-folders/${encodeURIComponent(id)}`, 'PUT', { projectId: folderId }) as Promise<{ folders: Record }> +/** + * Mark a sheet row done or snoozed for the owner only, or put it back with null. Kept + * in Totem, never written to the sheet (todos/sheet-marks.mjs). Answers the feed, as GET does. + */ +export const markSheetRow = (id: string, state: 'done' | 'snoozed' | null, until: Date | null = null) => + sendJSON('/api/todos/sheet/mark', 'POST', { id, state, ...(state === 'snoozed' && until ? { until: until.toISOString() } : {}) }) as Promise /** Set a task's GitHub issue link (https://github.com///issues/), or clear it with null. */ export const setIssueLink = (id: string, url: string | null) => sendJSON(`/api/todos/${encodeURIComponent(id)}/issue-link`, 'PUT', { url }) as Promise<{ todo: Todo }> diff --git a/mobile/src/lib/todos/board.ts b/mobile/src/lib/todos/board.ts index ace15e2..37641cf 100644 --- a/mobile/src/lib/todos/board.ts +++ b/mobile/src/lib/todos/board.ts @@ -3,7 +3,7 @@ // (mobile/src/features/todos/shared.test.mjs checks it). No React, React Native or // DOM, so vitest and node's test runner both load it as is. Nothing here changes a // task; it only decides where each one is drawn. A task is open or done. -import type { SheetFeed, SheetItem, Todo } from './types' +import type { SheetFeed, SheetHiddenItem, SheetItem, SheetMark, Todo } from './types' import { dateKey, isDayKey } from './format.ts' /* ------------------------------------------------------------------ */ @@ -39,6 +39,51 @@ export function sheetName(feed: SheetFeed | null | undefined): string { return title || 'Task sheet' } +/** + * The feed with one row marked done or snoozed for the owner (moved from `items` to + * `hidden`), or put back with null: what the bridge answers, drawn before it does. + * The sheet itself is never changed (todos/sheet-marks.mjs). + */ +export function withSheetMark(feed: SheetFeed, id: string, mark: SheetMark | null): SheetFeed { + if (!feed.configured) return feed + const hidden = feed.hidden ?? [] + const row: SheetItem | undefined = feed.items.find((item) => item.id === id) ?? hidden.find((item) => item.id === id) + if (!row) return feed + const { mark: _old, ...plain } = row as SheetHiddenItem + const items = feed.items.filter((item) => item.id !== id) + const rest = hidden.filter((item) => item.id !== id) + return mark ? { ...feed, items, hidden: [...rest, { ...plain, mark }] } : { ...feed, items: [...items, plain], hidden: rest } +} + +/** + * A sheet row's mark, or null when the owner has not marked it. With `now`, a snooze + * that has run out counts as no mark (what an Undo should put back). + */ +export function sheetMarkOf(item: SheetItem | SheetHiddenItem | null | undefined, now?: Date): SheetMark | null { + const mark = (item as Partial | null | undefined)?.mark ?? null + if (mark && now && mark.state === 'snoozed' && !(mark.until && new Date(mark.until) > now)) return null + return mark +} + +/** The rows the owner snoozed and that are still asleep at `now`, the soonest back first. */ +export function sheetSnoozed(feed: SheetFeed | null | undefined, now: Date): SheetHiddenItem[] { + const at = (item: SheetHiddenItem) => (item.mark.until ? new Date(item.mark.until).getTime() : Number.NaN) + return (feed?.hidden ?? []) + .filter((item) => item.mark.state === 'snoozed' && at(item) > now.getTime()) + .sort((a, b) => at(a) - at(b) || a.id.localeCompare(b.id)) +} + +/** How many sheet rows the owner marked done today: they count toward "done today" beside finished tasks. */ +export function sheetDoneToday(feed: SheetFeed | null | undefined, now: Date): number { + const today = dayKey(now) + return (feed?.hidden ?? []).filter((item) => item.mark.state === 'done' && dayKey(new Date(item.mark.at)) === today).length +} + +/** The rows the owner marked done (the sheet still has them open), the latest first. */ +export function sheetDone(feed: SheetFeed | null | undefined): SheetHiddenItem[] { + return (feed?.hidden ?? []).filter((item) => item.mark.state === 'done').sort((a, b) => b.mark.at.localeCompare(a.mark.at) || a.id.localeCompare(b.id)) +} + /** A sheet row's priority as the sheet says it (the feed's 1, 2, 3). */ export const SHEET_PRIORITY_WORD: Record<1 | 2 | 3, 'High' | 'Medium' | 'Low'> = { 1: 'High', 2: 'Medium', 3: 'Low' } diff --git a/mobile/src/lib/todos/types.ts b/mobile/src/lib/todos/types.ts index a652c94..5c8376e 100644 --- a/mobile/src/lib/todos/types.ts +++ b/mobile/src/lib/todos/types.ts @@ -150,7 +150,8 @@ export interface ConnectorHealth { /** * One open row of the owner's shared action-items sheet (GET /api/todos/sheet): read - * only, drawn among the tasks with no check circle. Only rows whose Who names one of + * only, drawn among the tasks with no check circle; the owner's done and snoozed + * marks stay in Totem (SheetMark). Only rows whose Who names one of * the configured assignees and whose Status is not Done arrive. */ export interface SheetItem { @@ -175,6 +176,24 @@ export interface SheetItem { folderDefault?: boolean } +/** + * The owner's own mark on a sheet row, kept in Totem and never written to the sheet + * (POST /api/todos/sheet/mark, todos/sheet-marks.mjs): `done` until the owner takes it off + * or the row leaves the feed, `snoozed` until `until`. + */ +export interface SheetMark { + state: 'done' | 'snoozed' + /** When it was marked. */ + at: string + /** A snooze's end, an ISO instant. */ + until?: string +} + +/** A row the owner marked: out of `items`, kept here so it can be put back. */ +export interface SheetHiddenItem extends SheetItem { + mark: SheetMark +} + /** GET /api/todos/sheet. A failed read keeps the last good items, `stale: true`, with a scrubbed `error`. */ export type SheetFeed = | { @@ -187,6 +206,8 @@ export type SheetFeed = stale: boolean error: string | null items: SheetItem[] + /** Rows the owner marked done or snoozed in Totem; absent from an older bridge. */ + hidden?: SheetHiddenItem[] /** Where rows land until filed (Settings -> Tasks › Task sheet), or null. */ defaultFolderId?: string | null } @@ -194,6 +215,7 @@ export type SheetFeed = configured: false /** Always empty. */ items: SheetItem[] + hidden?: SheetHiddenItem[] /** What to set to turn it on. */ reason: string } diff --git a/todos/http.mjs b/todos/http.mjs index c3c6697..228763c 100644 --- a/todos/http.mjs +++ b/todos/http.mjs @@ -1,4 +1,5 @@ import { TodoDomainError } from './errors.mjs'; +import { findSheetItem } from '../chat/task-link.mjs'; const JSON_TYPE = { 'content-type': 'application/json; charset=utf-8' }; const LEGACY_PRIORITY = Object.freeze({ 4: 'p1', 3: 'p2', 2: 'p3', 1: 'p4' }); @@ -139,8 +140,19 @@ function queryFrom(url) { // `issueStates`: the live state of linked GitHub issues (issue-states.mjs). // `sheetFolders`: gives each sheet row the folder it is filed under (`folderId`), // its own filing or the sheet's default (fileSheetItems in bridge.mjs). -export function createTodoHttpHandler({ service, commands, sheetFeed = null, issueStates = null, sheetFolders = null, now = () => new Date().toISOString(), maxBodyBytes = 1_000_000 } = {}) { +// `sheetMarks`: the owner's own done and snoozed marks on sheet rows, kept in +// Totem and never written to the sheet (todos/sheet-marks.mjs). `onSheetMark` +// is told each change, for the action log. +export function createTodoHttpHandler({ service, commands, sheetFeed = null, issueStates = null, sheetFolders = null, sheetMarks = null, onSheetMark = null, now = () => new Date().toISOString(), maxBodyBytes = 1_000_000 } = {}) { if (!service || !commands) throw new TypeError('createTodoHttpHandler requires service and commands'); + // The feed as this owner sees it: each row filed under its folder, and the rows + // he marked done or snoozed moved from `items` to `hidden`. + async function ownersSheet(feed) { + if (!Array.isArray(feed?.items)) return feed; + let out = sheetFolders ? await sheetFolders(feed) : feed; + if (sheetMarks) out = await sheetMarks.apply(out); + return out; + } return async function todoHttpHandler(req, res, suppliedUrl) { const url = suppliedUrl instanceof URL ? suppliedUrl : new URL(req.url, 'http://localhost'); const path = url.pathname; @@ -190,7 +202,30 @@ export function createTodoHttpHandler({ service, commands, sheetFeed = null, iss const feed = sheetFeed ? await sheetFeed.read({ refresh: url.searchParams.get('refresh') === '1' }) : { configured: false, items: [], reason: 'The task sheet is not available on this server.' }; - send(res, 200, sheetFolders && Array.isArray(feed?.items) ? await sheetFolders(feed) : feed); + send(res, 200, await ownersSheet(feed)); + return true; + } + // Done or snoozed, for the owner only: the row is untouched in the sheet. + if (req.method === 'POST' && path === '/api/todos/sheet/mark') { + if (!sheetFeed || !sheetMarks) throw bad('SHEET_MARKS_UNAVAILABLE', 'The task sheet is not available on this server.', 503); + const body = await readJson(req, maxBodyBytes); + const state = body.state ?? null; + if (state !== null && state !== 'done' && state !== 'snoozed') throw bad('INVALID_SHEET_MARK', 'state must be "done", "snoozed" or null.'); + if (typeof body.id !== 'string' || !body.id.startsWith('sheet:')) throw bad('INVALID_SHEET_MARK', 'id must be a sheet row id.'); + const feed = await sheetFeed.read(); + // Marked from a list read a minute ago: the row is found again by title if it moved. + const row = findSheetItem(feed?.items, body.id); + if (state && !row) throw bad('SHEET_ROW_NOT_FOUND', 'That row is no longer open on the sheet for you.', 404); + const ref = row?.id ?? body.id; + let saved; + try { + if (!state && body.id !== ref) await sheetMarks.set(body.id, { state: null }); + saved = await sheetMarks.set(ref, { state, until: body.until ?? null, title: row?.title ?? '', row }); + } catch (error) { + throw bad('INVALID_SHEET_MARK', error.message || 'The mark was not saved.', error.status || 400); + } + onSheetMark?.({ ref, state, until: saved?.[ref]?.until ?? null, title: row?.title ?? '' }); + send(res, 200, await ownersSheet(feed)); return true; } if (req.method === 'GET' && path === '/api/todos/venture-tags') { diff --git a/todos/http.test.mjs b/todos/http.test.mjs index 38280c4..52a219e 100644 --- a/todos/http.test.mjs +++ b/todos/http.test.mjs @@ -10,6 +10,7 @@ import { createTodoCommands } from './commands.mjs'; import { closeTodoDatabase, openTodoDatabase } from './db.mjs'; import { createTodoHttpHandler } from './http.mjs'; import { createTodoService } from './service.mjs'; +import { createSheetMarkStore } from './sheet-marks.mjs'; import { seedVentureTags } from './test-support.mjs'; const NOW = '2026-09-11T12:00:00.000Z'; @@ -43,7 +44,9 @@ async function fixture(options = {}) { return { configured: true, title: 'Example HQ', url: 'https://docs.example/s', fetchedAt: NOW, stale: false, error: null, items: [{ id: 'sheet:0:5:0a1b2c3d', row: 5, title: 'Row five' }] }; }, }; - const handler = createTodoHttpHandler({ service, commands, sheetFeed: options.sheetFeed === undefined ? sheetFeed : options.sheetFeed, issueStates: options.issueStates ?? null, now: () => NOW, maxBodyBytes: 128 }); + const sheetMarkLog = []; + const sheetMarks = options.sheetMarks ? createSheetMarkStore({ file: join(directory, 'sheet-marks.json'), now: () => Date.parse(NOW) }) : null; + const handler = createTodoHttpHandler({ service, commands, sheetFeed: options.sheetFeed === undefined ? sheetFeed : options.sheetFeed, issueStates: options.issueStates ?? null, sheetMarks, onSheetMark: (m) => sheetMarkLog.push(m), now: () => NOW, maxBodyBytes: 128 }); const server = createServer(async (req, res) => { try { if (await handler(req, res, new URL(req.url, 'http://localhost'))) return; @@ -72,7 +75,7 @@ async function fixture(options = {}) { const text = await response.text(); return { status: response.status, body: text ? JSON.parse(text) : null }; } - return { service, request, connectorCalls, sheetReads }; + return { service, request, connectorCalls, sheetReads, sheetMarkLog, directory }; } test('legacy list/create/update/close/delete/projects/completed shapes stay compatible', async () => { @@ -190,6 +193,32 @@ test('GET /api/todos/sheet answers the read-only feed, passes refresh=1 through, }); }); +test('POST /api/todos/sheet/mark hides a row for the owner only, and takes the mark off again', async () => { + const { request, sheetMarkLog } = await fixture({ sheetMarks: true }); + const done = await request('POST', '/api/todos/sheet/mark', { id: 'sheet:0:5:0a1b2c3d', state: 'done' }); + assert.equal(done.status, 200); + assert.deepEqual(done.body.items, []); + assert.equal(done.body.hidden[0].mark.state, 'done'); + assert.deepEqual((await request('GET', '/api/todos/sheet')).body.items, []); + // A row that moved (a row inserted above it) is found by its title. + const back = await request('POST', '/api/todos/sheet/mark', { id: 'sheet:0:4:0a1b2c3d', state: null }); + assert.equal(back.body.items.length, 1); + assert.deepEqual(back.body.hidden, []); + const snoozed = await request('POST', '/api/todos/sheet/mark', { id: 'sheet:0:5:0a1b2c3d', state: 'snoozed', until: '2026-09-14T09:00:00Z' }); + assert.equal(snoozed.body.hidden[0].mark.until, '2026-09-14T09:00:00.000Z'); + assert.deepEqual(sheetMarkLog.map((m) => m.state), ['done', null, 'snoozed']); + + const bad = async (body) => (await request('POST', '/api/todos/sheet/mark', body)).body.error.code; + assert.equal(await bad({ id: 'sheet:0:5:0a1b2c3d', state: 'snoozed', until: '2026-09-01T00:00:00Z' }), 'INVALID_SHEET_MARK'); + assert.equal(await bad({ id: 'sheet:0:5:0a1b2c3d', state: 'snoozed' }), 'INVALID_SHEET_MARK'); + assert.equal(await bad({ id: 'sheet:0:5:0a1b2c3d', state: 'archived' }), 'INVALID_SHEET_MARK'); + assert.equal(await bad({ id: 'local-1', state: 'done' }), 'INVALID_SHEET_MARK'); + assert.equal(await bad({ id: 'sheet:0:9:ffffffff', state: 'done' }), 'SHEET_ROW_NOT_FOUND'); + + const bare = await fixture(); + assert.equal((await bare.request('POST', '/api/todos/sheet/mark', { id: 'sheet:0:5:0a1b2c3d', state: 'done' })).status, 503); +}); + test('HTTP refuses syncTarget sheet with 400 SHEET_SHARING_REMOVED, and the sheet admin routes are gone', async () => { const { request, service, connectorCalls } = await fixture(); const removed = { status: 400, code: 'SHEET_SHARING_REMOVED' }; diff --git a/todos/sheet-marks.mjs b/todos/sheet-marks.mjs new file mode 100644 index 0000000..7804204 --- /dev/null +++ b/todos/sheet-marks.mjs @@ -0,0 +1,171 @@ +// todos/sheet-marks.mjs — the owner's own done and snoozed marks on shared sheet rows. +// +// The task sheet is read-only (docs/task-sheet.md): Totem never writes a row. But a +// row the owner has finished, or wants out of sight until next week, should leave +// the owner's list without anyone else seeing a change. So the mark lives here, in Totem, +// and the sheet is untouched: GET /api/todos/sheet moves a marked row from `items` +// to `hidden`, with its `mark`, and every client lists `items` only. +// +// Layout: one JSON file, { "": { state, at, until?, title } }. +// done hidden until the owner takes the mark off, or the row leaves the feed +// (marked Done in the sheet, reassigned, deleted): the mark goes with it. +// snoozed hidden until `until` (an instant); the mark is dropped once it passes. +// A row's ref changes when a row above it is inserted or deleted, so a mark finds +// its row again by tab and title (findSheetItem) and is re-keyed to the new ref, but +// only when the row still has the due date and assignee it had when marked: a new +// row that merely reuses a title (a weekly "Send the update") is not the row marked. +// The mark also keeps `due` and `who` for that check, and a done mark ends when the +// row itself is re-dated or reassigned in place. +import { mkdir, readFile, rename, writeFile } from 'node:fs/promises' +import { dirname } from 'node:path' +import { findSheetItem } from '../chat/task-link.mjs' + +export const SHEET_MARK_STATES = Object.freeze(['done', 'snoozed']) +const SHEET_REF = /^sheet:[A-Za-z0-9_-]{1,40}:\d{1,7}:[0-9a-f]{8}$/ +// A snooze is for days or weeks; a year out is a typo, not a plan. +const MAX_SNOOZE_MS = 366 * 86_400_000 + +export const validSheetRef = (ref) => typeof ref === 'string' && SHEET_REF.test(ref) + +function validMark(mark) { + if (!mark || typeof mark !== 'object' || !SHEET_MARK_STATES.includes(mark.state)) return false + if (typeof mark.at !== 'string' || Number.isNaN(Date.parse(mark.at))) return false + if (mark.state === 'snoozed' && (typeof mark.until !== 'string' || Number.isNaN(Date.parse(mark.until)))) return false + return true +} + +/** + * Split a feed's rows into what the owner sees (`items`) and what he marked + * (`hidden`, each with its `mark`). Returns { feed, changes }: `changes` are the + * edits the store should make ({ ref, to } re-keys a mark, { ref, drop } drops one; + * `at` is the mark's, so a mark set again since is left alone). + * Marks are only dropped for a row gone from a good read; a stale or failed read + * keeps them all. + */ +export function applySheetMarks(feed, marks, now = Date.now()) { + const items = Array.isArray(feed?.items) ? feed.items : [] + const good = feed?.configured === true && !feed.stale && Boolean(feed.fetchedAt) + const byItem = new Map() + const changes = [] + for (const [ref, mark] of Object.entries(marks || {})) { + if (mark.state === 'snoozed' && Date.parse(mark.until) <= now) { changes.push({ ref, drop: 'woke', at: mark.at }); continue } + const found = findSheetItem(items, ref) + // Found by its title alone, the same row moved only if its due date and assignee + // held. A done row re-dated or reassigned in place (a weekly row bumped to next + // week) is the next one to do, so its done mark goes too; a snooze ends anyway. + const item = found && ((found.id === ref && mark.state !== 'done') || sameRow(mark, found)) ? found : null + if (!item) { + // Ambiguous (two rows now share the title) is not gone: keep it, apply nothing. + if (good && !ambiguous(items, ref)) changes.push({ ref, drop: 'gone', at: mark.at }) + continue + } + // The exact ref wins over one that found the row by its title. + const held = byItem.get(item.id) + if (held && held.ref === item.id) continue + byItem.set(item.id, { ref, mark }) + if (ref !== item.id) changes.push({ ref, to: item.id, at: mark.at }) + } + const shown = [] + const hidden = [] + for (const item of items) { + const found = byItem.get(item.id) + if (!found) { shown.push(item); continue } + const { state, at, until } = found.mark + hidden.push({ ...item, mark: { state, at, ...(state === 'snoozed' ? { until } : {}) } }) + } + return { feed: { ...feed, items: shown, hidden }, changes } +} + +function sameRow(mark, item) { + return (mark.due === undefined || mark.due === (item.dueDate ?? null)) && (mark.who === undefined || mark.who === (item.who ?? '')) +} + +function ambiguous(items, ref) { + const tail = (id) => { const p = String(id).split(':'); return `${p[1]}:${p[3]}` } + const want = tail(ref) + return items.filter((i) => tail(i.id) === want).length > 1 +} + +export function createSheetMarkStore({ file, now = Date.now } = {}) { + if (!file) throw new TypeError('createSheetMarkStore requires file') + let queue = Promise.resolve() + + async function all() { + let raw = {} + try { raw = JSON.parse(await readFile(file, 'utf8')) } catch {} + const out = {} + if (raw && typeof raw === 'object' && !Array.isArray(raw)) { + for (const [ref, mark] of Object.entries(raw)) if (validSheetRef(ref) && validMark(mark)) out[ref] = mark + } + return out + } + + async function write(map) { + await mkdir(dirname(file), { recursive: true }) + const tmp = `${file}.${process.pid}.tmp` + await writeFile(tmp, JSON.stringify(map, null, 2) + '\n', { mode: 0o600 }) + await rename(tmp, file) + } + + function change(fn) { + const run = queue.then(async () => { + const map = await all() + const out = fn(map) + if (out !== false) await write(map) + return map + }) + queue = run.catch(() => {}) + return run + } + + /** + * Mark a row done or snoozed (`until`, an ISO instant in the future), or clear + * its mark with state null. `title` is kept only to make the file readable; `row` + * (the feed's item) gives the due date and assignee a moved row is matched on. + */ + function set(ref, { state, until = null, title = '', row = null } = {}) { + if (!validSheetRef(ref)) return Promise.reject(Object.assign(new Error('not a sheet row id'), { status: 400 })) + if (state != null && !SHEET_MARK_STATES.includes(state)) return Promise.reject(Object.assign(new Error('state must be done, snoozed or null'), { status: 400 })) + let wake = null + if (state === 'snoozed') { + const t = Date.parse(until) + if (typeof until !== 'string' || Number.isNaN(t)) return Promise.reject(Object.assign(new Error('a snooze needs until, an ISO date-time'), { status: 400 })) + if (t <= now()) return Promise.reject(Object.assign(new Error('until is in the past'), { status: 400 })) + if (t - now() > MAX_SNOOZE_MS) return Promise.reject(Object.assign(new Error('a snooze is at most a year'), { status: 400 })) + wake = new Date(t).toISOString() + } + return change((map) => { + if (!state) { + if (!(ref in map)) return false + delete map[ref] + return true + } + map[ref] = { + state, at: new Date(now()).toISOString(), ...(wake ? { until: wake } : {}), title: String(title || '').slice(0, 200), + ...(row ? { due: row.dueDate ?? null, who: String(row.who ?? '') } : {}), + } + return true + }) + } + + /** The feed as the owner sees it: marked rows moved to `hidden`; stale marks tidied. */ + async function apply(feed) { + const { feed: out, changes } = applySheetMarks(feed, await all(), now()) + if (changes.length) { + await change((map) => { + let changed = false + for (const c of changes) { + // Marked again since this read: the newer mark stays as it is. + if (!(c.ref in map) || map[c.ref].at !== c.at) continue + if (c.to && !(c.to in map)) map[c.to] = map[c.ref] + delete map[c.ref] + changed = true + } + return changed + }) + } + return out + } + + return { all, set, apply } +} diff --git a/todos/sheet-marks.test.mjs b/todos/sheet-marks.test.mjs new file mode 100644 index 0000000..aa161e7 --- /dev/null +++ b/todos/sheet-marks.test.mjs @@ -0,0 +1,103 @@ +import assert from 'node:assert/strict' +import { mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test } from 'node:test' + +import { applySheetMarks, createSheetMarkStore } from './sheet-marks.mjs' + +const NOW = Date.parse('2026-11-18T12:00:00Z') +const row = (n, hash, title = `Row ${n}`) => ({ id: `sheet:7:${n}:${hash}`, row: n, title }) +const feed = (items, extra = {}) => ({ configured: true, title: 'HQ', fetchedAt: '2026-11-18T11:59:00Z', stale: false, error: null, items, ...extra }) + +test('a done or snoozed row moves to hidden with its mark; the rest stay in order', () => { + const marks = { + 'sheet:7:3:aaaaaaaa': { state: 'done', at: '2026-11-17T10:00:00Z' }, + 'sheet:7:5:cccccccc': { state: 'snoozed', at: '2026-11-17T10:00:00Z', until: '2026-11-20T09:00:00Z' }, + } + const { feed: out, changes } = applySheetMarks(feed([row(3, 'aaaaaaaa'), row(4, 'bbbbbbbb'), row(5, 'cccccccc')]), marks, NOW) + assert.deepEqual(out.items.map((i) => i.row), [4]) + assert.deepEqual(out.hidden.map((i) => [i.row, i.mark.state, i.mark.until]), [[3, 'done', undefined], [5, 'snoozed', '2026-11-20T09:00:00Z']]) + assert.deepEqual(changes, []) +}) + +test('a snooze that has passed lets the row back and drops the mark', () => { + const marks = { 'sheet:7:5:cccccccc': { state: 'snoozed', at: '2026-11-10T10:00:00Z', until: '2026-11-18T09:00:00Z' } } + const { feed: out, changes } = applySheetMarks(feed([row(5, 'cccccccc')]), marks, NOW) + assert.equal(out.items.length, 1) + assert.deepEqual(changes, [{ ref: 'sheet:7:5:cccccccc', drop: 'woke', at: '2026-11-10T10:00:00Z' }]) +}) + +test('a moved row keeps its mark (re-keyed); a row gone from a good read loses it; a stale read keeps every mark', () => { + const marks = { + 'sheet:7:3:aaaaaaaa': { state: 'done', at: 'a' }, + 'sheet:7:9:dddddddd': { state: 'done', at: 'b' }, + } + const items = [row(4, 'aaaaaaaa')] + const { feed: out, changes } = applySheetMarks(feed(items), marks, NOW) + assert.deepEqual(out.items, []) + assert.deepEqual(changes, [{ ref: 'sheet:7:3:aaaaaaaa', to: 'sheet:7:4:aaaaaaaa', at: 'a' }, { ref: 'sheet:7:9:dddddddd', drop: 'gone', at: 'b' }]) + assert.deepEqual(applySheetMarks(feed(items, { stale: true }), marks, NOW).changes, [{ ref: 'sheet:7:3:aaaaaaaa', to: 'sheet:7:4:aaaaaaaa', at: 'a' }]) + assert.deepEqual(applySheetMarks({ configured: false, items: [] }, marks, NOW).changes, []) +}) + +test('two rows with the same title: the exact ref is applied, a moved one is not guessed, and neither is dropped', () => { + const marks = { 'sheet:7:3:aaaaaaaa': { state: 'done', at: 'a' } } + const exact = applySheetMarks(feed([row(3, 'aaaaaaaa'), row(8, 'aaaaaaaa')]), marks, NOW) + assert.deepEqual(exact.feed.items.map((i) => i.row), [8]) + const moved = applySheetMarks(feed([row(4, 'aaaaaaaa'), row(8, 'aaaaaaaa')]), marks, NOW) + assert.equal(moved.feed.items.length, 2) + assert.deepEqual(moved.changes, []) +}) + +test('a new row that only reuses a marked title is not the row marked: it stays in the list, and the mark goes', () => { + // Marked done when it was row 5, due on the 20th; that row was closed and a new one added with the same title. + const marks = { 'sheet:7:5:aaaaaaaa': { state: 'done', at: 'a', due: '2026-11-20', who: 'Sam' } } + const next = { ...row(12, 'aaaaaaaa', 'Send the weekly update'), dueDate: '2026-11-27', who: 'Sam' } + const { feed: out, changes } = applySheetMarks(feed([next]), marks, NOW) + assert.deepEqual(out.items.map((i) => i.row), [12]) + assert.deepEqual(changes, [{ ref: 'sheet:7:5:aaaaaaaa', drop: 'gone', at: 'a' }]) + // Re-dated in place (same row, same title, next week's date): done no longer, back in the list. + const redated = { ...row(5, 'aaaaaaaa', 'Send the weekly update'), dueDate: '2026-11-27', who: 'Sam' } + const again = applySheetMarks(feed([redated]), marks, NOW) + assert.deepEqual(again.feed.items.map((i) => i.row), [5]) + assert.deepEqual(again.changes, [{ ref: 'sheet:7:5:aaaaaaaa', drop: 'gone', at: 'a' }]) + // A snooze on it is left to run out. + assert.deepEqual(applySheetMarks(feed([redated]), { 'sheet:7:5:aaaaaaaa': { state: 'snoozed', at: 'a', until: '2026-11-25T00:00:00Z', due: '2026-11-20', who: 'Sam' } }, NOW).feed.items, []) + // The same row, moved down by an insert above it, keeps its mark. + const moved = { ...row(6, 'aaaaaaaa', 'Send the weekly update'), dueDate: '2026-11-20', who: 'Sam' } + assert.deepEqual(applySheetMarks(feed([moved]), marks, NOW).feed.items, []) +}) + +test('the store validates, writes 0600, applies, and tidies what a read found', async () => { + const dir = mkdtempSync(join(tmpdir(), 'totem-sheet-marks-')) + try { + const file = join(dir, 'sheet-marks.json') + let now = NOW + const store = createSheetMarkStore({ file, now: () => now }) + await assert.rejects(store.set('local-1', { state: 'done' }), /not a sheet row/) + await assert.rejects(store.set('sheet:7:3:aaaaaaaa', { state: 'snoozed', until: '2026-11-01T00:00:00Z' }), /past/) + await assert.rejects(store.set('sheet:7:3:aaaaaaaa', { state: 'snoozed', until: '2028-11-01T00:00:00Z' }), /year/) + await store.set('sheet:7:3:aaaaaaaa', { state: 'done', title: 'Row 3', row: { dueDate: null, who: 'Sam' } }) + assert.deepEqual([JSON.parse(readFileSync(file, 'utf8'))['sheet:7:3:aaaaaaaa'].due, JSON.parse(readFileSync(file, 'utf8'))['sheet:7:3:aaaaaaaa'].who], [null, 'Sam']) + await store.set('sheet:7:5:cccccccc', { state: 'snoozed', until: '2026-11-19T09:00:00-05:00' }) + assert.equal(statSync(file).mode & 0o777, 0o600) + const saved = JSON.parse(readFileSync(file, 'utf8')) + assert.equal(saved['sheet:7:5:cccccccc'].until, '2026-11-19T14:00:00.000Z') + + const out = await store.apply(feed([{ ...row(4, 'aaaaaaaa'), dueDate: null, who: 'Sam' }, row(5, 'cccccccc')])) + assert.deepEqual(out.items, []) + assert.deepEqual(Object.keys(await store.all()).sort(), ['sheet:7:4:aaaaaaaa', 'sheet:7:5:cccccccc']) + + now = Date.parse('2026-11-20T00:00:00Z') + const later = await store.apply(feed([row(5, 'cccccccc')])) + assert.deepEqual(later.items.map((i) => i.row), [5]) + assert.deepEqual(await store.all(), {}) + + await store.set('sheet:7:5:cccccccc', { state: 'done' }) + await store.set('sheet:7:5:cccccccc', { state: null }) + assert.deepEqual(await store.all(), {}) + } finally { + rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/web/src/api.ts b/web/src/api.ts index 58e8c8f..eff583e 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -524,6 +524,12 @@ export const getSheetFeed = ({ refresh = false }: { refresh?: boolean } = {}) => */ export const fileSheetRow = (id: string, folderId: string | null) => sendJSON(`/api/chat/task-folders/${encodeURIComponent(id)}`, 'PUT', { projectId: folderId }) as Promise<{ folders: Record }> +/** + * Mark a sheet row done or snoozed for the owner only, or put it back with null. Kept + * in Totem, never written to the sheet (todos/sheet-marks.mjs). Answers the feed, as GET does. + */ +export const markSheetRow = (id: string, state: 'done' | 'snoozed' | null, until: Date | null = null) => + sendJSON('/api/todos/sheet/mark', 'POST', { id, state, ...(state === 'snoozed' && until ? { until: until.toISOString() } : {}) }) as Promise /** Set a task's GitHub issue link (https://github.com///issues/), or clear it with null. */ export const setIssueLink = (id: string, url: string | null) => sendJSON(`/api/todos/${encodeURIComponent(id)}/issue-link`, 'PUT', { url }) as Promise<{ todo: Todo }> diff --git a/web/src/components/TodosView.tsx b/web/src/components/TodosView.tsx index 49e319a..19be7f1 100644 --- a/web/src/components/TodosView.tsx +++ b/web/src/components/TodosView.tsx @@ -11,10 +11,10 @@ import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useSta import { Hi, ChevronDownIcon, EllipsisHorizontalIcon, MagnifyingGlassIcon, PlusIcon, XMarkIcon, ArchiveBoxIcon, TrashIcon, ArrowPathIcon, AdjustmentsHorizontalIcon, CheckCircleIcon, FlagIcon } from '../icons' import { COMMANDS } from '../shortcuts' import { useCommand, isTypingTarget } from '../useShortcuts' -import { buildList, byWake, nextWake, sectionFor, sheetName as nameOfSheet, wakeLabel, SECTION_TITLE, type ListItem, type SectionKey } from '../todos/board' +import { buildList, byWake, nextWake, sectionFor, sheetDone, sheetDoneToday, sheetMarkOf, sheetName as nameOfSheet, sheetSnoozed, wakeLabel, SECTION_TITLE, type ListItem, type SectionKey } from '../todos/board' import { dateKey } from '../todos/format' import { filterTodos } from '../todos/state' -import type { SheetItem, Todo } from '../todos/types' +import type { SheetHiddenItem, SheetItem, Todo } from '../todos/types' import { useFolders, folderFor, folderLabel } from '../todos/folders' import { groupByFolder, inScope, itemFolder, projectChips, scopeFolder, subfolderChips } from '../todos/byFolder' import ProjectIcon from '../chat/ProjectIcon' @@ -127,7 +127,11 @@ export default function TodosView({ onAuthError, now: clock = () => new Date(), const feed = board.sheet const sheetOn = feed?.configured === true const sheetName = nameOfSheet(feed) - const sheetItems = useMemo(() => (feed?.items ?? []), [feed]) + // A row whose snooze ran out since the feed was read is back, as the bridge will say on its next read. + const sheetItems = useMemo(() => [ + ...(feed?.items ?? []), + ...(feed?.hidden ?? []).filter((item) => item.mark.state === 'snoozed' && !(item.mark.until && new Date(item.mark.until) > now)), + ], [feed, now]) // A saved scope whose chip is gone (no sheet set up, its project deleted) shows everything. const savedFolder = scopeFolder(view.scope) const scope: Scope = (view.scope === 'sheet' && feed && !sheetOn) || (savedFolder && projects.length && !folderFor(savedFolder, projects)) ? 'all' : view.scope @@ -149,6 +153,13 @@ export default function TodosView({ onAuthError, now: clock = () => new Date(), return needle ? scoped.filter((item) => sheetMatches(item, needle)) : scoped }, [sheetItems, shows, needle]) const list = useMemo(() => buildList(todos, sheet, { now }), [todos, sheet, now]) + // Sheet rows the owner snoozed or marked done in Totem, in the folds with the tasks. + const sheetFilter = useCallback((rows: SheetHiddenItem[]) => { + const scoped = rows.filter((item) => shows({ kind: 'sheet', item })) + return needle ? scoped.filter((item) => sheetMatches(item, needle)) : scoped + }, [shows, needle]) + const sheetAsleep = useMemo(() => sheetFilter(sheetSnoozed(feed, now)), [sheetFilter, feed, now]) + const sheetFinished = useMemo(() => sheetFilter(sheetDone(feed)), [sheetFilter, feed]) // What is drawn: the day groups, or (from the "…" menu) one group per folder. const drawn = useMemo(() => (view.groupBy === 'folder' ? groupByFolder(list.sections, projects).map((group) => ({ key: `f:${group.key}`, folder: group, items: group.items, place: null })) @@ -157,8 +168,10 @@ export default function TodosView({ onAuthError, now: clock = () => new Date(), const allSnoozed = useMemo(() => board.todos.filter((todo) => todo.status !== 'done' && todo.snoozedUntil && new Date(todo.snoozedUntil) > now), [board.todos, now]) const today = dateKey(now) const completed = list.completed + const snoozedCount = snoozed.length + sheetAsleep.length + const completedCount = completed.length + sheetFinished.length // Which headings are drawn: the sticky observer below re-runs only when this changes. - const drawnHeadings = `${board.loaded}:${drawn.map((section) => section.key).join(',')}:${snoozed.length > 0}:${completed.length > 0}` + const drawnHeadings = `${board.loaded}:${drawn.map((section) => section.key).join(',')}:${snoozedCount > 0}:${completedCount > 0}` // A section heading is drawn bare at rest and gets its band only while stuck to the // top of the list, so the glow is not cut into slabs. A 1 px sentinel above each @@ -176,19 +189,19 @@ export default function TodosView({ onAuthError, now: clock = () => new Date(), root.querySelectorAll('.tk-sentinel').forEach((el) => observer.observe(el)) return () => observer.disconnect() }, [drawnHeadings]) - const completedTitle = completed.every((todo) => todo.completedAt && dateKey(new Date(todo.completedAt)) === today) ? 'Completed today' : 'Completed' + const completedTitle = completed.every((todo) => todo.completedAt && dateKey(new Date(todo.completedAt)) === today) && sheetFinished.every((item) => dateKey(new Date(item.mark.at)) === today) ? 'Completed today' : 'Completed' // Rows in the order they are drawn: the keyboard walks this. const order = useMemo(() => { const keys: string[] = [] for (const section of drawn) for (const item of section.items) keys.push(keyOf(item)) - if (view.snoozedOpen) for (const todo of snoozed) keys.push(todo.id) - if (view.completedOpen) for (const todo of completed) keys.push(todo.id) + if (view.snoozedOpen) for (const row of [...snoozed, ...sheetAsleep]) keys.push(row.id) + if (view.completedOpen) for (const row of [...completed, ...sheetFinished]) keys.push(row.id) return keys - }, [drawn, snoozed, completed, view.snoozedOpen, view.completedOpen]) + }, [drawn, snoozed, completed, sheetAsleep, sheetFinished, view.snoozedOpen, view.completedOpen]) const todoById = useMemo(() => new Map(board.todos.map((todo) => [todo.id, todo])), [board.todos]) - const sheetById = useMemo(() => new Map(sheetItems.map((item) => [item.id, item])), [sheetItems]) + const sheetById = useMemo(() => new Map([...(feed?.hidden ?? []), ...sheetItems].map((item) => [item.id, item])), [feed, sheetItems]) // The keyboard cursor. When its row leaves (finished, snoozed, binned, moved out of // view), it stays at the same place in the list, on the row that took its spot, never // back at the top. @@ -197,6 +210,8 @@ export default function TodosView({ onAuthError, now: clock = () => new Date(), const active = activeAt >= 0 ? activeKey : order[Math.min(lastIndex.current, order.length - 1)] ?? null useEffect(() => { const at = active ? order.indexOf(active) : -1; if (at >= 0) lastIndex.current = at }, [active, order]) + // Done today: finished tasks plus sheet rows the owner marked done today. + const doneToday = board.doneTodayCount + sheetDoneToday(feed, now) const counts = { overdue: full.sections.find((section) => section.key === 'overdue')?.items.length ?? 0, today: full.sections.find((section) => section.key === 'today')?.items.length ?? 0, @@ -204,21 +219,21 @@ export default function TodosView({ onAuthError, now: clock = () => new Date(), const liveLine = [ counts.overdue ? `${counts.overdue.toLocaleString()} overdue` : null, counts.today ? `${counts.today.toLocaleString()} today` : null, - board.doneTodayCount ? `${board.doneTodayCount.toLocaleString()} done today` : null, + doneToday ? `${doneToday.toLocaleString()} done today` : null, ].filter(Boolean).join(' · ') || (board.loaded ? 'Nothing due today' : '') // The Snoozed fold's "next back" is about the snoozed tasks it holds (this scope and search). - const wakeAt = nextWake(snoozed, now) + const wakeAt = nextWake([...snoozed, ...sheetAsleep.map((item) => ({ snoozedUntil: item.mark.until ?? null }))], now) const summary: Summary = useMemo(() => { const upcoming = full.sections.find((section) => section.key === 'upcoming')?.items[0] const first = byWake(allSnoozed)[0] return { - overdue: counts.overdue, today: counts.today, doneToday: board.doneTodayCount, + overdue: counts.overdue, today: counts.today, doneToday, nextDue: upcoming ? (upcoming.kind === 'task' ? upcoming.todo.dueDate : upcoming.item.dueDate) : null, snoozed: allSnoozed.length, nextBack: first?.snoozedUntil ? { title: first.title, at: new Date(first.snoozedUntil) } : null, } - }, [full, allSnoozed, counts.overdue, counts.today, board.doneTodayCount]) + }, [full, allSnoozed, counts.overdue, counts.today, doneToday]) /* ---------------- focus and the pane ---------------- */ @@ -347,6 +362,13 @@ export default function TodosView({ onAuthError, now: clock = () => new Date(), if (fromKeyboard) stepOff(todo.id) void board.complete(todo) } + /** A sheet row: done for the owner (the sheet unchanged), or a done one put back. */ + // It leaves at once (no beat: nothing is saved to the sheet), so the cursor moves on. + const toggleSheet = (item: SheetItem | SheetHiddenItem) => { + if (sheetMarkOf(item)?.state === 'done') { void board.markSheet(item.id, null); return } + stepOff(item.id) + void board.markSheet(item.id, 'done') + } const toggleSelected = (id: string) => setSelection((current) => { const next = new Set(current) if (next.has(id)) next.delete(id); else next.add(id) @@ -356,7 +378,8 @@ export default function TodosView({ onAuthError, now: clock = () => new Date(), function rowMenuFor(key: string, kind: RowMenu['kind']) { const todo = todoById.get(key) - if (!todo || todo.status === 'done') return + const item = sheetById.get(key) + if (item ? kind !== 'snooze' || sheetMarkOf(item)?.state === 'done' : !todo || todo.status === 'done') return const row = rows.current.get(key) ?? null // The hover tools are hidden on a device without hover; then the menu hangs from the row's marks. const shown = (el: HTMLElement | null | undefined) => (el && el.getClientRects().length ? el : null) @@ -395,9 +418,10 @@ export default function TodosView({ onAuthError, now: clock = () => new Date(), event.preventDefault() if (selectMode && todo) return toggleSelected(key) if (todo) toggle(todo, true) + else if (item && !selectMode) toggleSheet(item) return case 's': case 'd': case 'p': - if (todo && !selectMode) { event.preventDefault(); rowMenuFor(key, event.key === 's' ? 'snooze' : event.key === 'd' ? 'due' : 'priority') } + if ((todo || (item && event.key === 's')) && !selectMode) { event.preventDefault(); rowMenuFor(key, event.key === 's' ? 'snooze' : event.key === 'd' ? 'due' : 'priority') } return case 'n': event.preventDefault() @@ -495,25 +519,28 @@ export default function TodosView({ onAuthError, now: clock = () => new Date(), onTools={(kind, anchor) => { setActiveKey(todo.id); setRowMenu({ kind, id: todo.id, anchor }) }} /> ) - const drawItem = (item: ListItem, place: SectionKey) => item.kind === 'task' ? drawTask(item.todo, place) : ( + const drawSheet = (row: SheetItem | SheetHiddenItem, place: RowPlace) => ( setActiveKey(item.item.id)} - onOpen={() => { setActiveKey(item.item.id); openKey(item.item.id); focusRow(item.item.id, false) }} + rowRef={rowRef(row.id)} + onFocusRow={() => setActiveKey(row.id)} + onOpen={() => { setActiveKey(row.id); openKey(row.id); focusRow(row.id, false) }} + onDone={() => { setActiveKey(row.id); toggleSheet(row) }} + onTools={(kind, anchor) => { setActiveKey(row.id); setRowMenu({ kind, id: row.id, anchor }) }} /> ) + const drawItem = (item: ListItem, place: SectionKey) => item.kind === 'task' ? drawTask(item.todo, place) : drawSheet(item.item, place) const filtering = Boolean(needle) || scope !== 'all' - const nothing = !drawn.length && !snoozed.length && !completed.length + const nothing = !drawn.length && !snoozedCount && !completedCount // The sheet's state, once and quietly, wherever its rows would be drawn: the read // failed (rows gone, or the last good rows shown stale), or nothing is assigned. @@ -544,7 +571,7 @@ export default function TodosView({ onAuthError, now: clock = () => new Date(), const headItems: MenuEntry[] = [ { key: 'select', label: selectMode ? 'Stop selecting' : 'Select tasks', icon: CheckCircleIcon, onSelect: () => (selectMode ? endSelect() : setSelectMode(true)) }, 'separator', - { key: 'snoozed', label: 'Snoozed', detail: allSnoozed.length.toLocaleString(), icon: SnoozeIcon, onSelect: () => { setView((current) => ({ ...current, snoozedOpen: true })); requestAnimationFrame(() => { snoozedHead.current?.scrollIntoView?.({ block: 'start' }); snoozedHead.current?.focus() }) } }, + { key: 'snoozed', label: 'Snoozed', detail: (allSnoozed.length + sheetSnoozed(feed, now).length).toLocaleString(), icon: SnoozeIcon, onSelect: () => { setView((current) => ({ ...current, snoozedOpen: true })); requestAnimationFrame(() => { snoozedHead.current?.scrollIntoView?.({ block: 'start' }); snoozedHead.current?.focus() }) } }, { key: 'archive', label: 'Archive', detail: board.counts.archived.toLocaleString(), icon: ArchiveBoxIcon, onSelect: () => setPane({ kind: 'shelf', shelf: 'archive' }) }, { key: 'deleted', label: 'Recycle bin', detail: board.counts.deleted.toLocaleString(), icon: TrashIcon, onSelect: () => setPane({ kind: 'shelf', shelf: 'deleted' }) }, 'separator', @@ -571,7 +598,13 @@ export default function TodosView({ onAuthError, now: clock = () => new Date(), /> ) } else if (paneSheet) { - paneBody = void board.fileSheet(paneSheet.id, folderId)} /> + paneBody = ( + void board.fileSheet(paneSheet.id, folderId)} + onMark={(next, until) => { if (next) stepOff(paneSheet.id); void board.markSheet(paneSheet.id, next, until) }} + /> + ) } else if (pane?.kind === 'shelf') { paneBody = } else if (!overlay) { @@ -580,6 +613,7 @@ export default function TodosView({ onAuthError, now: clock = () => new Date(), const paneOpen = Boolean(paneTodo || paneSheet || pane?.kind === 'shelf') const menuTodo = rowMenu ? todoById.get(rowMenu.id) : undefined + const menuSheet = rowMenu && !menuTodo ? sheetById.get(rowMenu.id) : undefined const selectedIds = [...selection].filter((id) => todoById.has(id)) return ( @@ -667,32 +701,34 @@ export default function TodosView({ onAuthError, now: clock = () => new Date(), ))} - {snoozed.length > 0 && ( + {snoozedCount > 0 && (
)} - {completed.length > 0 && ( + {completedCount > 0 && (
)}
@@ -702,11 +738,11 @@ export default function TodosView({ onAuthError, now: clock = () => new Date(),
{filtering ? <>

Nothing here{needle ? ` matches “${search.trim()}”` : ''}.

- :

{board.doneTodayCount ? `All clear. ${plural(board.doneTodayCount, 'task')} done today.` : 'Nothing to do. Add a task above.'}

} + :

{doneToday ? `All clear. ${plural(doneToday, 'task')} done today.` : 'Nothing to do. Add a task above.'}

}
)} {board.loaded && !nothing && !drawn.length && !filtering && ( -

{board.doneTodayCount ? `All clear. ${plural(board.doneTodayCount, 'task')} done today.` : 'Nothing open right now.'}

+

{doneToday ? `All clear. ${plural(doneToday, 'task')} done today.` : 'Nothing open right now.'}

)}
@@ -723,6 +759,12 @@ export default function TodosView({ onAuthError, now: clock = () => new Date(), onSnooze={(until) => { stepOff(menuTodo.id); void board.snooze(menuTodo, until) }} onWake={() => void board.wake(menuTodo)} /> )} + {rowMenu && menuSheet && rowMenu.kind === 'snooze' && ( + { setRowMenu(null); backToList() }} + todo={{ id: menuSheet.id, title: menuSheet.title, dueDate: menuSheet.dueDate, snoozedUntil: sheetMarkOf(menuSheet)?.until ?? null }} + onSnooze={(until) => { stepOff(menuSheet.id); void board.markSheet(menuSheet.id, 'snoozed', until) }} + onWake={() => void board.markSheet(menuSheet.id, null)} /> + )} {rowMenu && menuTodo && rowMenu.kind === 'due' && ( { setRowMenu(null); backToList() }} onDue={(dueDate) => { diff --git a/web/src/todos/TaskMenus.tsx b/web/src/todos/TaskMenus.tsx index 306d2a2..d2f2321 100644 --- a/web/src/todos/TaskMenus.tsx +++ b/web/src/todos/TaskMenus.tsx @@ -11,7 +11,8 @@ import { repeatWords } from './TaskRow' interface Common { anchor: HTMLElement | null; onClose: () => void; now: Date } export function SnoozeMenu({ todo, anchor, onClose, now, onSnooze, onWake }: Common & { - todo: Todo + /** A task, or anything snoozed like one (a sheet row, work/groups.ts snoozeSubject). */ + todo: Pick onSnooze: (until: Date) => void onWake: () => void }) { diff --git a/web/src/todos/TaskPane.tsx b/web/src/todos/TaskPane.tsx index 2d808ac..2641d1e 100644 --- a/web/src/todos/TaskPane.tsx +++ b/web/src/todos/TaskPane.tsx @@ -7,7 +7,7 @@ // task to the next. import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { - Hi, ArchiveBoxIcon, ArrowPathIcon, ArrowTopRightOnSquareIcon, CalendarDaysIcon, ChatBubbleLeftRightIcon, + Hi, ArchiveBoxIcon, ArrowPathIcon, ArrowTopRightOnSquareIcon, ArrowUturnLeftIcon, CalendarDaysIcon, ChatBubbleLeftRightIcon, CheckIcon, ChevronDownIcon, ChevronLeftIcon, EllipsisHorizontalIcon, LinkIcon, NoSymbolIcon, PlusIcon, TrashIcon, XMarkIcon, } from '../icons' import { ApiError, getTodoBoard, unarchiveBoardTodo } from '../api' @@ -17,13 +17,13 @@ import ChatAbout from '../chat/about/ChatAbout' import { pushError } from '../toast' import { sheetFeedLine } from '../components/sheetFeedLine' import { groupArchive } from './archive' -import { SHEET_PRIORITY_WORD, sheetName, wakeLabel } from './board' +import { SHEET_PRIORITY_WORD, sheetMarkOf, sheetName, wakeLabel } from './board' import { dateLabel, dueText } from './format' import Menu from './Menu' import { DueMenu, PRIORITIES, priorityName, RepeatMenu, SnoozeMenu } from './TaskMenus' import { CheckCircle, issueKey, repeatWords } from './TaskRow' import type { TaskBoard } from './useTaskBoard' -import type { IssueState, SheetFeed, SheetItem, Todo } from './types' +import type { IssueState, SheetFeed, SheetHiddenItem, SheetItem, Todo } from './types' import { FolderField } from '../work/FolderField' import { TaskChats } from '../work/TaskCard' import { folderLabel } from './folders' @@ -352,14 +352,23 @@ function Related({ todo, all, onOpen, onPick, onRelate }: { todo: Todo; all: Tod ) } -export function SheetDetail({ item, feed, now, onClose, onFile }: { item: SheetItem; feed: SheetFeed | null; now: Date; onClose: () => void; onFile: (folderId: string | null) => void }) { +export function SheetDetail({ item, feed, now, onClose, onFile, onMark }: { + item: SheetItem | SheetHiddenItem; feed: SheetFeed | null; now: Date; onClose: () => void; onFile: (folderId: string | null) => void + /** Done or snoozed for the owner only (the sheet unchanged), or put back with null. */ + onMark?: (next: 'done' | 'snoozed' | null, until?: Date | null) => void +}) { const source = sheetName(feed) const prio = item.priority ? SHEET_PRIORITY_WORD[item.priority] : 'None' + const mark = sheetMarkOf(item) + const snoozedUntil = mark?.state === 'snoozed' && mark.until && new Date(mark.until) > now ? mark.until : null + const [snoozeAt, setSnoozeAt] = useState(null) return (
- - {source} · read-only + {onMark + ? onMark(mark?.state === 'done' ? null : 'done')} /> + : } + {mark?.state === 'done' ? 'Done for you' : snoozedUntil ? `Snoozed until ${wakeLabel(new Date(snoozedUntil), now)}` : `${source} · read-only`}
@@ -374,11 +383,32 @@ export function SheetDetail({ item, feed, now, onClose, onFile }: { item: SheetI {item.folderDefault &&

Where {source}'s rows go until you file them (Settings → Tasks).

} + {onMark && mark?.state !== 'done' && ( + + + + )}
{item.notes &&

Notes & links

{item.notes}

} - Open in sheet -

Totem only reads this sheet. Change the row there; it shows here within two minutes.

+
+ Open in sheet + {onMark && ( + + )} +
+

Totem only reads this sheet. Change the row there; it shows here within two minutes. Done and snooze here are yours alone: the sheet is unchanged.

+ {snoozeAt && onMark && ( + setSnoozeAt(null)} + todo={{ id: item.id, title: item.title, dueDate: item.dueDate, snoozedUntil }} + onSnooze={(until) => onMark('snoozed', until)} onWake={() => onMark(null)} + /> + )} ) } diff --git a/web/src/todos/TaskRow.tsx b/web/src/todos/TaskRow.tsx index a67e0ed..1e8085c 100644 --- a/web/src/todos/TaskRow.tsx +++ b/web/src/todos/TaskRow.tsx @@ -1,16 +1,17 @@ // One ~40 px line of the Tasks list: a check circle, the title, and right-aligned // marks drawn only when they say something (AGENTS.md: mobile's styling, desktop's // value in the pane and the keyboard, not busier rows). A task sheet row -// has no check circle: it is read-only, opened in the sheet. +// wears the sheet's mark where a task has its check circle; pressing it marks the +// row done for the owner only, in Totem (the sheet is never written). import React from 'react' import { Hi, ArrowTopRightOnSquareIcon, CalendarDaysIcon, ChatBubbleLeftIcon, CheckIcon, LinkIcon, MinusIcon, } from '../icons' import ChatAbout from '../chat/about/ChatAbout' import { todoContext } from '../chat/about/context' -import { SHEET_PRIORITY_WORD, sheetAsTaskPriority, wakeLabel, type SectionKey } from './board' +import { SHEET_PRIORITY_WORD, sheetAsTaskPriority, sheetMarkOf, wakeLabel, type SectionKey } from './board' import { dateLabel, dueText } from './format' -import { priorityLabel, type IssueState, type SheetItem, type Todo } from './types' +import { priorityLabel, type IssueState, type SheetHiddenItem, type SheetItem, type Todo } from './types' import { FolderChip } from '../work/FolderField' import { FlagSolidIcon, IssueClosedIcon, IssueOpenIcon, RepeatIcon, SheetIcon, SnoozeIcon } from './taskIcons' @@ -141,39 +142,60 @@ export function TaskRow({ ) } -export function SheetRow({ item, place, source, active, open, now, rowRef, onFocusRow, onOpen, selectMode, showFolder = true }: RowCommon & { - item: SheetItem +export function SheetRow({ item, place, source, active, open, now, rowRef, onFocusRow, onOpen, selectMode, showFolder = true, onDone, onTools }: RowCommon & { + /** An open row, or one the owner marked (it carries `mark`). */ + item: SheetItem | SheetHiddenItem place: RowPlace /** Whether to show the row's folder (not when the view is that folder already). */ showFolder?: boolean /** The feed's name for itself (say "Partner HQ"), else "Task sheet". */ source: string selectMode: boolean + /** Mark it done for the owner, or put a done one back. */ + onDone?: () => void + /** A hover tool was pressed: open that menu against it. */ + onTools?: (menu: 'snooze', anchor: HTMLElement) => void }) { + const mark = sheetMarkOf(item) + const done = mark?.state === 'done' const due = dueMark(item.dueDate, place, now) const prio = item.priority ? SHEET_PRIORITY_WORD[item.priority] : null const prioTone = item.priority ? sheetFlagTone(item.priority) : '' + const back = place === 'snoozed' && mark?.until ? wakeLabel(new Date(mark.until), now) : null return (
{ if (event.target === event.currentTarget) onFocusRow() }} onClick={() => { if (!selectMode) onOpen() }} > - + + {done && onDone + ? + : onDone && !selectMode + ? ( + + ) + : } + {item.title} + {back && {back}} {due && {due.text}} {prio && {prio}} {showFolder && } {!selectMode && ( + {!done && onTools && } event.stopPropagation()}> )} diff --git a/web/src/todos/TodosView.test.tsx b/web/src/todos/TodosView.test.tsx index d7d053d..bcabd52 100644 --- a/web/src/todos/TodosView.test.tsx +++ b/web/src/todos/TodosView.test.tsx @@ -11,6 +11,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import TodosView from '../components/TodosView' import ToastHost from '../components/ToastHost' import type { SheetFeed, Todo } from './types' +import { withSheetMark } from './board' // Monday 9 November 2026, 10:00 local. const NOW = new Date(2026, 10, 9, 10, 0, 0) @@ -67,6 +68,10 @@ function route(url: string, method: string, body: any): Response { } return json({ todos: changed }) } + if (path === '/api/todos/sheet/mark' && method === 'POST') { + fake.sheet = withSheetMark(fake.sheet, body.id, body.state ? { state: body.state, at: NOW.toISOString(), ...(body.until ? { until: body.until } : {}) } : null) + return json(fake.sheet) + } if (path === '/api/todos/sheet') return fake.sheetFails ? json({ error: 'Drive said no' }, 500) : json(fake.sheet) if (path === '/api/todos/completed') return json({ todos: fake.recent ?? [] }) const note = /^\/api\/todos\/([^/]+)\/notes$/.exec(path) @@ -146,10 +151,10 @@ describe('Tasks page', () => { expect(screen.getByRole('button', { name: /Completed today/ })).toHaveAttribute('aria-expanded', 'false') expect(screen.queryByText('Renew passport')).toBeNull() - // A sheet row sits in Today with the feed's name and no check circle. + // A sheet row sits in Today with the feed's mark where a task has its check circle. const sheetRow = row('Order banner stands') - // Named by the icon's tooltip, not repeated as text on every row. - expect(within(sheetRow).getByTitle('Team HQ (read-only)')).toBeVisible() + // Named by the mark's tooltip, not repeated as text on every row. + expect(within(sheetRow).getByRole('button', { name: 'Mark Order banner stands done for you (Team HQ is unchanged)' })).toBeVisible() expect(within(sheetRow).queryByText('Team HQ')).toBeNull() expect(within(sheetRow).queryByText(/in progress/i)).toBeNull() // Its flag is coloured by meaning: the sheet's High is a task's P2 (amber), never P1 red. @@ -397,11 +402,37 @@ describe('Tasks page', () => { const pane = await screen.findByRole('region', { name: 'Team HQ: Order banner stands' }) expect(within(pane).getByRole('link', { name: /Open in sheet/ })).toHaveAttribute('href', SHEET.items[0].url) expect(within(pane).queryByRole('textbox')).toBeNull() - expect(within(pane).queryByRole('checkbox')).toBeNull() - // x does nothing to a row Totem cannot change. + expect(within(pane).getByText(/the sheet is unchanged/)).toBeVisible() + }) + + it('marks a sheet row done for the owner only, with x or its mark, and puts it back from Completed', async () => { + const user = await mount(BOARD()) row('Order banner stands').focus() await user.keyboard('x') + await waitFor(() => expect(sent('POST', /\/api\/todos\/sheet\/mark$/)[0]?.body).toEqual({ id: 'sheet:0:7:abcd1234', state: 'done' })) + // Nothing else is sent: the sheet is never written, and no task moves. expect(sent('POST', /move$/)).toHaveLength(0) + expect(sent('PUT', /task-folders/)).toHaveLength(0) + await waitFor(() => expect(screen.queryByRole('row', { name: /^Order banner stands, Team HQ, (?!done)/ })).toBeNull()) + expect(await screen.findByText(/Done: “Order banner stands”\. The sheet is unchanged\./)).toBeVisible() + // It counts as done today beside the task the fixture finished today. + expect(await screen.findByText(/· 2 done today/)).toBeVisible() + await user.click(screen.getByRole('button', { name: /^Completed/ })) + const done = await screen.findByRole('row', { name: /Order banner stands, Team HQ, done for you/ }) + await user.click(within(done).getByRole('checkbox', { name: 'Put Order banner stands back on your list' })) + await waitFor(() => expect(sent('POST', /\/api\/todos\/sheet\/mark$/)[1]?.body).toEqual({ id: 'sheet:0:7:abcd1234', state: null })) + await waitFor(() => expect(row('Order banner stands')).toBeVisible()) + }) + + it('snoozes a sheet row with s, into the Snoozed fold', async () => { + const user = await mount(BOARD()) + row('Order banner stands').focus() + await user.keyboard('s') + await user.click(await screen.findByRole('menuitem', { name: /Tomorrow/ })) + await waitFor(() => expect(sent('POST', /\/api\/todos\/sheet\/mark$/)[0]?.body).toMatchObject({ id: 'sheet:0:7:abcd1234', state: 'snoozed' })) + expect(new Date(sent('POST', /\/api\/todos\/sheet\/mark$/)[0].body.until).getTime()).toBeGreaterThan(NOW.getTime()) + await user.click(await screen.findByRole('button', { name: /^Snoozed/ })) + expect(await screen.findByRole('row', { name: /Order banner stands, Team HQ, .*back / })).toBeVisible() }) it('takes the archive and bin counts from the board, never downloading the archive to count it', async () => { diff --git a/web/src/todos/board.test.ts b/web/src/todos/board.test.ts index b6d7949..3c42bd3 100644 --- a/web/src/todos/board.test.ts +++ b/web/src/todos/board.test.ts @@ -1,10 +1,10 @@ import { afterEach, describe, expect, it } from 'vitest' import { - afterDone, buildList, clearScope, compareListItems, rollsOnCompletion, sectionFor, sheetAsTaskPriority, sheetName, SHEET_PRIORITY_WORD, urgency, + afterDone, buildList, clearScope, compareListItems, rollsOnCompletion, sectionFor, sheetAsTaskPriority, sheetDone, sheetDoneToday, sheetMarkOf, sheetName, sheetSnoozed, SHEET_PRIORITY_WORD, urgency, withSheetMark, type ListItem, type TaskList, } from './board' -import type { SheetItem, Todo } from './types' +import type { SheetFeed, SheetItem, Todo } from './types' // Wednesday 4 November 2026, 10:00 local. const NOW = new Date(2026, 10, 4, 10, 0) @@ -259,6 +259,48 @@ describe('the task sheet beside tasks', () => { }) }) +describe('the owner’s own marks on sheet rows', () => { + const row = (n: number): SheetItem => ({ id: `sheet:0:${n}:0000000${n}`, row: n, title: `Row ${n}`, who: 'Owner', priority: null, status: '', dueDate: null, notes: '', url: `u#${n}` }) + const feed = (): SheetFeed => ({ configured: true, url: 'x', fetchedAt: null, stale: false, error: null, items: [row(1), row(2), row(3)] }) + + it('moves a marked row to hidden and back, and leaves anything else alone', () => { + const done = withSheetMark(feed(), 'sheet:0:2:00000002', { state: 'done', at: '2026-11-04T09:00:00.000Z' }) + expect(done.items.map((i) => i.row)).toEqual([1, 3]) + expect(done.configured && done.hidden?.map((i) => [i.row, i.mark.state])).toEqual([[2, 'done']]) + const back = withSheetMark(done, 'sheet:0:2:00000002', null) + expect(back.items.map((i) => i.row).sort()).toEqual([1, 2, 3]) + expect(back.items.find((i) => i.row === 2)).not.toHaveProperty('mark') + expect(back.configured && back.hidden).toEqual([]) + expect(withSheetMark(feed(), 'sheet:0:9:00000009', { state: 'done', at: 'x' })).toEqual(feed()) + const off: SheetFeed = { configured: false, items: [], reason: 'Set it' } + expect(withSheetMark(off, 'sheet:0:1:00000001', { state: 'done', at: 'x' })).toBe(off) + }) + + it('reads a row’s mark, and counts a snooze that has run out as none when asked about now', () => { + const asleep = withSheetMark(feed(), 'sheet:0:1:00000001', { state: 'snoozed', at: 'a', until: new Date(2026, 10, 4, 9).toISOString() }) + const row1 = asleep.configured ? asleep.hidden![0] : null + expect(sheetMarkOf(row1)?.state).toBe('snoozed') + expect(sheetMarkOf(row1, NOW)).toBeNull() + expect(sheetMarkOf(row1, new Date(2026, 10, 4, 8))?.state).toBe('snoozed') + expect(sheetMarkOf(row(2))).toBeNull() + expect(sheetMarkOf(undefined)).toBeNull() + }) + + it('lists snoozed rows still asleep, soonest back first, and done rows latest first', () => { + let f = withSheetMark(feed(), 'sheet:0:1:00000001', { state: 'snoozed', at: 'a', until: new Date(2026, 10, 6, 9).toISOString() }) + f = withSheetMark(f, 'sheet:0:2:00000002', { state: 'snoozed', at: 'a', until: new Date(2026, 10, 5, 9).toISOString() }) + f = withSheetMark(f, 'sheet:0:3:00000003', { state: 'snoozed', at: 'a', until: new Date(2026, 10, 4, 9).toISOString() }) + expect(sheetSnoozed(f, NOW).map((i) => i.row)).toEqual([2, 1]) + f = withSheetMark(f, 'sheet:0:1:00000001', { state: 'done', at: '2026-11-03T09:00:00.000Z' }) + f = withSheetMark(f, 'sheet:0:2:00000002', { state: 'done', at: '2026-11-04T09:00:00.000Z' }) + expect(sheetDone(f).map((i) => i.row)).toEqual([2, 1]) + // One marked on the 4th, one on the 3rd: only the 4th's is done today. + expect(sheetDoneToday(f, new Date('2026-11-04T15:00:00.000Z'))).toBe(1) + expect(sheetDoneToday(null, NOW)).toBe(0) + expect(sheetSnoozed(null, NOW)).toEqual([]) + }) +}) + describe('finishing a repeating task', () => { const issueLink = { connector: 'github', externalId: 'acme/site#12', externalUrl: 'https://github.com/acme/site/issues/12', lastSyncedAt: null } as unknown as Todo['externalLinks'][number] diff --git a/web/src/todos/board.ts b/web/src/todos/board.ts index ace15e2..37641cf 100644 --- a/web/src/todos/board.ts +++ b/web/src/todos/board.ts @@ -3,7 +3,7 @@ // (mobile/src/features/todos/shared.test.mjs checks it). No React, React Native or // DOM, so vitest and node's test runner both load it as is. Nothing here changes a // task; it only decides where each one is drawn. A task is open or done. -import type { SheetFeed, SheetItem, Todo } from './types' +import type { SheetFeed, SheetHiddenItem, SheetItem, SheetMark, Todo } from './types' import { dateKey, isDayKey } from './format.ts' /* ------------------------------------------------------------------ */ @@ -39,6 +39,51 @@ export function sheetName(feed: SheetFeed | null | undefined): string { return title || 'Task sheet' } +/** + * The feed with one row marked done or snoozed for the owner (moved from `items` to + * `hidden`), or put back with null: what the bridge answers, drawn before it does. + * The sheet itself is never changed (todos/sheet-marks.mjs). + */ +export function withSheetMark(feed: SheetFeed, id: string, mark: SheetMark | null): SheetFeed { + if (!feed.configured) return feed + const hidden = feed.hidden ?? [] + const row: SheetItem | undefined = feed.items.find((item) => item.id === id) ?? hidden.find((item) => item.id === id) + if (!row) return feed + const { mark: _old, ...plain } = row as SheetHiddenItem + const items = feed.items.filter((item) => item.id !== id) + const rest = hidden.filter((item) => item.id !== id) + return mark ? { ...feed, items, hidden: [...rest, { ...plain, mark }] } : { ...feed, items: [...items, plain], hidden: rest } +} + +/** + * A sheet row's mark, or null when the owner has not marked it. With `now`, a snooze + * that has run out counts as no mark (what an Undo should put back). + */ +export function sheetMarkOf(item: SheetItem | SheetHiddenItem | null | undefined, now?: Date): SheetMark | null { + const mark = (item as Partial | null | undefined)?.mark ?? null + if (mark && now && mark.state === 'snoozed' && !(mark.until && new Date(mark.until) > now)) return null + return mark +} + +/** The rows the owner snoozed and that are still asleep at `now`, the soonest back first. */ +export function sheetSnoozed(feed: SheetFeed | null | undefined, now: Date): SheetHiddenItem[] { + const at = (item: SheetHiddenItem) => (item.mark.until ? new Date(item.mark.until).getTime() : Number.NaN) + return (feed?.hidden ?? []) + .filter((item) => item.mark.state === 'snoozed' && at(item) > now.getTime()) + .sort((a, b) => at(a) - at(b) || a.id.localeCompare(b.id)) +} + +/** How many sheet rows the owner marked done today: they count toward "done today" beside finished tasks. */ +export function sheetDoneToday(feed: SheetFeed | null | undefined, now: Date): number { + const today = dayKey(now) + return (feed?.hidden ?? []).filter((item) => item.mark.state === 'done' && dayKey(new Date(item.mark.at)) === today).length +} + +/** The rows the owner marked done (the sheet still has them open), the latest first. */ +export function sheetDone(feed: SheetFeed | null | undefined): SheetHiddenItem[] { + return (feed?.hidden ?? []).filter((item) => item.mark.state === 'done').sort((a, b) => b.mark.at.localeCompare(a.mark.at) || a.id.localeCompare(b.id)) +} + /** A sheet row's priority as the sheet says it (the feed's 1, 2, 3). */ export const SHEET_PRIORITY_WORD: Record<1 | 2 | 3, 'High' | 'Medium' | 'Low'> = { 1: 'High', 2: 'Medium', 3: 'Low' } diff --git a/web/src/todos/todos.css b/web/src/todos/todos.css index 2016e8f..4fe9c4c 100644 --- a/web/src/todos/todos.css +++ b/web/src/todos/todos.css @@ -158,6 +158,13 @@ button.tk-chip-pick { padding-right: 6px; } .tk-check.not-doing.on { border-color: var(--line-2); background: var(--bg-3); color: var(--muted); } .tk-select { width: 16px; height: 16px; margin: 0; accent-color: var(--accent); cursor: pointer; } .tk-sheet-glyph { color: var(--accent); } +/* A sheet row's mark turns into a check on hover: done for the owner, the sheet unchanged. */ +.tk-sheet-check { display: grid; place-items: center; width: 22px; height: 22px; padding: 0; border: 0; border-radius: 50%; background: none; cursor: pointer; } +.tk-sheet-check > * { grid-area: 1 / 1; transition: opacity .15s ease; } +.tk-sheet-check .tk-check { opacity: 0; cursor: inherit; } +.tk-sheet-check:hover .tk-sheet-glyph, .tk-sheet-check:focus-visible .tk-sheet-glyph { opacity: 0; } +.tk-sheet-check:hover .tk-check, .tk-sheet-check:focus-visible .tk-check { opacity: 1; border-color: var(--green); } +.tk-sheet-check:hover .tk-check-mark { opacity: .55; transform: scale(.9); } .tk-sheet-row.inert { cursor: default; opacity: .55; } .tk-marks { @@ -327,6 +334,8 @@ button.tk-chip-pick { padding-right: 6px; } .tk-pane-meta { margin: auto 0 0; padding-top: 8px; color: var(--muted); font-size: 11.5px; } .tk-sheet-notes { margin: 0; font-size: 13px; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; } .tk-open-sheet { align-self: flex-start; gap: 6px; text-decoration: none; } +.tk-sheet-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } +.tk-sheet-actions .btn { gap: 6px; } /* Nothing selected: the day at a glance, and the keys. */ .tk-summary-day { margin: 2px 0 0; color: var(--muted); font-size: 12.5px; } diff --git a/web/src/todos/types.ts b/web/src/todos/types.ts index a652c94..5c8376e 100644 --- a/web/src/todos/types.ts +++ b/web/src/todos/types.ts @@ -150,7 +150,8 @@ export interface ConnectorHealth { /** * One open row of the owner's shared action-items sheet (GET /api/todos/sheet): read - * only, drawn among the tasks with no check circle. Only rows whose Who names one of + * only, drawn among the tasks with no check circle; the owner's done and snoozed + * marks stay in Totem (SheetMark). Only rows whose Who names one of * the configured assignees and whose Status is not Done arrive. */ export interface SheetItem { @@ -175,6 +176,24 @@ export interface SheetItem { folderDefault?: boolean } +/** + * The owner's own mark on a sheet row, kept in Totem and never written to the sheet + * (POST /api/todos/sheet/mark, todos/sheet-marks.mjs): `done` until the owner takes it off + * or the row leaves the feed, `snoozed` until `until`. + */ +export interface SheetMark { + state: 'done' | 'snoozed' + /** When it was marked. */ + at: string + /** A snooze's end, an ISO instant. */ + until?: string +} + +/** A row the owner marked: out of `items`, kept here so it can be put back. */ +export interface SheetHiddenItem extends SheetItem { + mark: SheetMark +} + /** GET /api/todos/sheet. A failed read keeps the last good items, `stale: true`, with a scrubbed `error`. */ export type SheetFeed = | { @@ -187,6 +206,8 @@ export type SheetFeed = stale: boolean error: string | null items: SheetItem[] + /** Rows the owner marked done or snoozed in Totem; absent from an older bridge. */ + hidden?: SheetHiddenItem[] /** Where rows land until filed (Settings -> Tasks › Task sheet), or null. */ defaultFolderId?: string | null } @@ -194,6 +215,7 @@ export type SheetFeed = configured: false /** Always empty. */ items: SheetItem[] + hidden?: SheetHiddenItem[] /** What to set to turn it on. */ reason: string } diff --git a/web/src/todos/useTaskBoard.ts b/web/src/todos/useTaskBoard.ts index 2293a61..6f66a63 100644 --- a/web/src/todos/useTaskBoard.ts +++ b/web/src/todos/useTaskBoard.ts @@ -12,9 +12,9 @@ import * as todoApi from '../api' import { AuthError, getIssueStates, getRecentCompletions, getSheetFeed, getTodoBoard } from '../api' import { pushError, pushToast } from '../toast' import { announcing, onTasksChanged } from './bus' -import { afterDone, rollsOnCompletion, wakeLabel } from './board' +import { afterDone, rollsOnCompletion, sheetMarkOf, wakeLabel, withSheetMark } from './board' import { dateKey, dateLabel } from './format' -import type { IssueStatesResponse, SheetFeed, Todo, TodoBoardCounts, TodoOutcome, TodoPatch } from './types' +import type { IssueStatesResponse, SheetFeed, SheetHiddenItem, SheetItem, SheetMark, Todo, TodoBoardCounts, TodoOutcome, TodoPatch } from './types' /** How long a ticked row stays in place, checked, before it leaves for Completed. */ export const DONE_BEAT_MS = 650 @@ -33,6 +33,7 @@ const unlinkRelatedTodo = announcing('board', todoApi.unlinkRelatedTodo) const updateBoardTodo = announcing('board', todoApi.updateBoardTodo) const bulkBoardTodos = announcing('board', todoApi.bulkBoardTodos) const fileSheetRow = announcing('board', todoApi.fileSheetRow, { sheet: true }) +const markSheetRow = announcing('board', todoApi.markSheetRow, { sheet: true }) const FIELD: Record = { title: 'title', description: 'description', dueDate: 'due date', priority: 'priority', area: 'area', @@ -114,8 +115,19 @@ export function useTaskBoard({ onAuthError, now = () => new Date(), beatMs = DON } }, [set]) + // Bumped by each mark: a feed read or a mark's answer that began before a later + // mark would draw that mark's row back, so it is dropped and the later one lands. + // A read that starts while a mark is still being saved may read the marks from + // before it, so it is dropped too: the mark's own answer is the fresher feed. + const markSeq = useRef(0) + const marking = useRef(0) const loadSheet = useCallback(async (refresh = false) => { - try { set({ sheet: await getSheetFeed({ refresh }), sheetError: '' }) } catch (cause) { + const seq = markSeq.current + const during = marking.current > 0 + try { + const feed = await getSheetFeed({ refresh }) + if (seq === markSeq.current && !during) set({ sheet: feed, sheetError: '' }) + } catch (cause) { if (cause instanceof AuthError) { authError.current(); return } set({ sheetError: message(cause, 'The task sheet could not be read.') }) } @@ -314,6 +326,31 @@ export function useTaskBoard({ onAuthError, now = () => new Date(), beatMs = DON } }, [replace]) + /** + * Mark a sheet row done or snoozed for the owner only, or put it back with null. + * Kept in Totem, never written to the sheet; drawn at once, with Undo. + */ + const markSheet = useCallback(async function mark(id: string, next: 'done' | 'snoozed' | null, until: Date | null = null): Promise { + const feed = latest.current.sheet + if (!feed?.configured) return + const row: SheetItem | SheetHiddenItem | undefined = feed.items.find((item) => item.id === id) ?? feed.hidden?.find((item) => item.id === id) + if (!row) return + const prior: SheetMark | null = sheetMarkOf(row, nowRef.current()) + const seq = ++markSeq.current + set({ sheet: withSheetMark(feed, id, next ? { state: next, at: new Date().toISOString(), ...(next === 'snoozed' && until ? { until: until.toISOString() } : {}) } : null) }) + marking.current += 1 + try { + const answer = await markSheetRow(id, next, until).finally(() => { marking.current -= 1 }) + if (seq === markSeq.current) set({ sheet: answer, sheetError: '' }) + const undo = () => mark(id, prior?.state ?? null, prior?.until ? new Date(prior.until) : null) + if (next === 'done') undoable(`Done: ${quote(row.title)}. The sheet is unchanged.`, undo) + else if (next === 'snoozed' && until) undoable(`Snoozed until ${wakeLabel(until, nowRef.current())}`, undo) + } catch (cause) { + fail(cause, next ? 'The row could not be marked.' : 'The row could not be put back.') + void loadSheet() + } + }, [fail, loadSheet, set]) + /** File a sheet row under a folder (null: Personal, even when the sheet has a default). */ const fileSheet = useCallback(async (id: string, folderId: string | null) => { const feed = latest.current.sheet @@ -424,7 +461,7 @@ export function useTaskBoard({ onAuthError, now = () => new Date(), beatMs = DON ...state, ticking, revealId, doneTodayCount, clearReveal: () => setRevealId(null), load, loadBoard, loadSheet, - complete, reopen, notDoing, snooze, wake, remove, restore, update, create, linkIssue, addNote, relate, bulk, fileSheet, + complete, reopen, notDoing, snooze, wake, remove, restore, update, create, linkIssue, addNote, relate, bulk, fileSheet, markSheet, noteDraft, setNoteDraft, } } diff --git a/web/src/work/TaskCard.test.tsx b/web/src/work/TaskCard.test.tsx index 0ccf68c..07c2d78 100644 --- a/web/src/work/TaskCard.test.tsx +++ b/web/src/work/TaskCard.test.tsx @@ -9,6 +9,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import TodosView from '../components/TodosView' import ToastHost from '../components/ToastHost' import type { SheetFeed, Todo } from '../todos/types' +import { withSheetMark } from '../todos/board' import TaskCardHost, { PinnedTask } from './TaskCard' import TaskBar from './TaskBar' import TasksPanel from './TasksPanel' @@ -46,6 +47,10 @@ function route(url: string, method: string, body: any): Response { todos = [...todos, created] return json({ todo: created }) } + if (path === '/api/todos/sheet/mark' && method === 'POST') { + sheet = withSheetMark(sheet, body.id, body.state ? { state: body.state, at: NOW.toISOString(), ...(body.until ? { until: body.until } : {}) } : null) + return json(sheet) + } if (path === '/api/todos/sheet') return json(sheet) if (path === '/api/todos/completed') return json({ todos: [] }) if (path === '/api/chat/projects') return json({ projects: PROJECTS }) @@ -281,8 +286,22 @@ describe('the chats panel’s task rows', () => { expect(screen.queryByRole('menu')).toBeNull() await user.click(await screen.findByRole('button', { name: 'Undo' })) await waitFor(() => expect(sent('PATCH', /\/api\/todos\/today$/)[1]?.body).toEqual({ snoozedUntil: null })) - // A sheet row cannot be snoozed, so it gets no button. - expect(screen.queryByRole('button', { name: /Snooze “Order banner stands”/ })).toBeNull() + }) + + it('snoozes or marks a sheet row done for the owner only; the sheet is never written', async () => { + const user = userEvent.setup() + render(<> {}} />) + await user.click(await screen.findByRole('button', { name: 'Snooze “Order banner stands”' })) + await user.click(await screen.findByRole('menuitem', { name: /Tomorrow/ })) + const tomorrow = new Date(2026, 10, 10, 9, 0, 0).toISOString() + await waitFor(() => expect(sent('POST', /\/api\/todos\/sheet\/mark$/)[0]?.body).toEqual({ id: 'sheet:0:7:abcd1234', state: 'snoozed', until: tomorrow })) + await waitFor(() => expect(screen.queryByRole('button', { name: 'Snooze “Order banner stands”' })).toBeNull()) + await user.click(await screen.findByRole('button', { name: 'Undo' })) + await waitFor(() => expect(sent('POST', /\/api\/todos\/sheet\/mark$/)[1]?.body).toEqual({ id: 'sheet:0:7:abcd1234', state: null })) + await user.click(await screen.findByRole('button', { name: 'Mark “Order banner stands” done for you (the sheet is unchanged)' })) + await waitFor(() => expect(sent('POST', /\/api\/todos\/sheet\/mark$/)[2]?.body).toEqual({ id: 'sheet:0:7:abcd1234', state: 'done' })) + await waitFor(() => expect(screen.queryByRole('button', { name: /Order banner stands/ })).toBeNull()) + expect(sent('PUT', /task-folders/)).toHaveLength(0) }) }) diff --git a/web/src/work/TaskCard.tsx b/web/src/work/TaskCard.tsx index 1d8b2ea..03888fe 100644 --- a/web/src/work/TaskCard.tsx +++ b/web/src/work/TaskCard.tsx @@ -4,7 +4,7 @@ import { useChat } from '../chat/store' import { ThreadItem } from '../chat/ThreadList' import { TI } from '../chat/ui' import { - IconArrowUpRight, IconCalendar, IconChevronDown, IconChevronUp, IconCircle, IconCircleCheck, IconExternalLink, IconFlag, IconFolder, + IconArrowBackUp, IconArrowUpRight, IconCalendar, IconChevronDown, IconChevronUp, IconCircle, IconCircleCheck, IconExternalLink, IconFlag, IconFolder, IconMessage, IconPlus, IconRepeat, IconTable, IconTrash, IconX, IconZzz, } from '../chat/icons' import { SHEET_PRIORITY_WORD, wakeLabel } from '../todos/board' @@ -12,7 +12,7 @@ import { dueText } from '../todos/format' import { DueMenu, PriorityMenu, priorityName, RepeatMenu, SnoozeMenu } from '../todos/TaskMenus' import { repeatWords } from '../todos/TaskRow' import '../todos/todos.css' -import { chatsByTask, resolveRef, type WorkTask } from './groups' +import { chatsByTask, resolveRef, snoozeSubject, type WorkTask } from './groups' import { closeTaskCard, newTaskChat, openTaskChat, pinTask, showInTasks, useTaskCard } from './card' import { FolderField } from './FolderField' import { usePhone, usePinFold } from '../chat/pins' @@ -156,7 +156,8 @@ function CardBody({ task, mode, cardRef, onClose, folded = false, onFold, flash const title = useDraft(task.title, (next) => { if (todo && next.trim() && next.trim() !== todo.title) void updateTask(task.ref, { title: next.trim() }) }) const description = useDraft(todo?.description ?? '', (next) => { if (todo && next !== todo.description) void updateTask(task.ref, { description: next }) }) - const snoozed = Boolean(todo?.snoozedUntil && new Date(todo.snoozedUntil) > now) + const snoozeable = snoozeSubject(task) + const snoozed = Boolean(snoozeable.snoozedUntil && new Date(snoozeable.snoozedUntil) > now) // Grows with its text (field-sizing is Chromium-only; the desktop app is WebKit). const titleBox = useRef(null) useLayoutEffect(() => { @@ -174,7 +175,12 @@ function CardBody({ task, mode, cardRef, onClose, folded = false, onFold, flash - ) : } + ) : ( + + )} {folded ? ( ) : todo ? ( @@ -230,7 +236,12 @@ function CardBody({ task, mode, cardRef, onClose, folded = false, onFold, flash <> {sheet.dueDate ? dueText(sheet.dueDate, now) : 'No date'} {sheet.priority ? SHEET_PRIORITY_WORD[sheet.priority] : 'None'} - {sheet.status && {sheet.status}} + {(sheet.status || task.done) && {task.done ? `Done for you${sheet.status ? ` (${sheet.status} on the sheet)` : ''}` : sheet.status}} + {!task.done && ( + + + + )} )}
@@ -251,6 +262,11 @@ function CardBody({ task, mode, cardRef, onClose, folded = false, onFold, flash {todo ? : sheet && Open in the sheet} + {sheet && ( + + )} {todo && ( )} @@ -261,7 +277,7 @@ function CardBody({ task, mode, cardRef, onClose, folded = false, onFold, flash {todo && menu?.kind === 'due' && setMenu(null)} onDue={(dueDate) => void updateTask(task.ref, { dueDate })} />} {todo && menu?.kind === 'priority' && setMenu(null)} onPriority={(priority) => void updateTask(task.ref, { priority })} />} {todo && menu?.kind === 'repeat' && setMenu(null)} onRepeat={(recurrence) => void updateTask(task.ref, { recurrence })} />} - {todo && menu?.kind === 'snooze' && setMenu(null)} onSnooze={(until) => void snoozeTask(task.ref, until)} onWake={() => void snoozeTask(task.ref, null)} />} + {menu?.kind === 'snooze' && setMenu(null)} onSnooze={(until) => void snoozeTask(task.ref, until)} onWake={() => void snoozeTask(task.ref, null)} />} ) } diff --git a/web/src/work/TasksPanel.tsx b/web/src/work/TasksPanel.tsx index b94ef7b..7894ec8 100644 --- a/web/src/work/TasksPanel.tsx +++ b/web/src/work/TasksPanel.tsx @@ -12,7 +12,7 @@ import { useThreadTaskDrop } from '../chat/dnd' import { pushToast } from '../toast' import { SnoozeMenu } from '../todos/TaskMenus' import '../todos/todos.css' -import { buildWork, dueLabel, folderOf, matches, type WorkGroup, type WorkGroupBy, type WorkRow, type WorkShow, type WorkSort, type WorkTask } from './groups' +import { buildWork, dueLabel, folderOf, matches, snoozeSubject, type WorkGroup, type WorkGroupBy, type WorkRow, type WorkShow, type WorkSort, type WorkTask } from './groups' import { FolderPicker } from './pickers' import AddTask from './AddTask' import { completeTask, findTask, setTaskFolder, snoozeTask, taskHome, useWork } from './state' @@ -108,7 +108,7 @@ function ViewMenu({ view, onView, hasSheet, sheetName }: { view: View; onView: ( function RowMenu({ row, anchor, onClose, onNewChat, onFile, onEdit }: { row: WorkRow; anchor: React.RefObject; onClose: () => void; onNewChat: () => void; onFile: () => void; onEdit: () => void }) { const pop = useRef(null) useDismiss(true, [pop, anchor] as React.RefObject[], onClose) - const placement = usePopoverPlacement(true, anchor, { width: 220, height: 220, gap: 2, align: 'end', narrow: 0, fit: true, minHeight: 120 }) + const placement = usePopoverPlacement(true, anchor, { width: 220, height: 260, gap: 2, align: 'end', narrow: 0, fit: true, minHeight: 120 }) if (!placement) return null const { task } = row return createPortal( @@ -116,9 +116,8 @@ function RowMenu({ row, anchor, onClose, onNewChat, onFile, onEdit }: { row: Wor - {task.kind === 'local' - ? - : task.url && } + + {task.kind === 'sheet' && task.url && } , document.body, ) @@ -163,7 +162,13 @@ function TaskRow({ row, open, onToggle, onOpenChat, activeId, runs }: { ) - : } + : ( + // The sheet's mark until hovered: done here is the owner's alone, the sheet is unchanged. + + )} )}
- {task.todo && } + {(task.todo || task.kind === 'sheet') && }
{menu && setMenu(false)} onNewChat={newChat} onFile={() => setFiling(true)} onEdit={() => openTaskCard(task.ref)} />} - {snoozing && task.todo && setSnoozing(false)} + {snoozing && setSnoozing(false)} onSnooze={(until) => void snoozeTask(task.ref, until)} onWake={() => void snoozeTask(task.ref, null)} />} {filing && { + return task.todo ?? { id: task.ref, title: task.title, dueDate: task.dueDate, snoozedUntil: task.mark?.state === 'snoozed' ? task.mark.until ?? null : null } +} + /** Open, not snoozed, not archived or deleted: what belongs on the panel. */ export function isOpenTodo(t: Todo, now: Date): boolean { if (t.status === 'done' || t.archivedAt || t.deletedAt) return false diff --git a/web/src/work/state.ts b/web/src/work/state.ts index ff17bd4..eed6121 100644 --- a/web/src/work/state.ts +++ b/web/src/work/state.ts @@ -22,6 +22,7 @@ const moveBoardTodo = announcing('work', todoApi.moveBoardTodo) const deleteBoardTodo = announcing('work', todoApi.deleteBoardTodo) const restoreBoardTodo = announcing('work', todoApi.restoreBoardTodo) const fileSheetRow = announcing('work', todoApi.fileSheetRow, { sheet: true }) +const markSheetRow = announcing('work', todoApi.markSheetRow, { sheet: true }) export interface WorkState { /** Local tasks on the board (open, done and snoozed) plus sheet rows, by ref. */ @@ -109,7 +110,8 @@ export function loadWork(): Promise { const now = new Date() const todos = board.todos.filter((t) => !t.deletedAt).map((t) => local(t, now)) const keep = state.tasks.filter((t) => t.kind === 'local' && fetchedExtra.has(t.ref) && !todos.some((l) => l.ref === t.ref)) - const rows = sheet?.configured ? sheet.items.map(fromSheet) : [] + // Rows marked done or snoozed come too, so a chat can still name its row and the card can put it back. + const rows = sheet?.configured ? [...sheet.items, ...(sheet.hidden ?? [])].map(fromSheet) : [] set({ tasks: [...todos, ...keep, ...rows], sheetName: sheet?.configured ? sheet.title || 'Shared sheet' : '', @@ -189,9 +191,34 @@ export async function setTaskFolder(ref: string, projectId: string | null) { } } -/** Mark a local task done, with Undo. Sheet rows are finished in the sheet. */ +/** + * Mark a sheet row done or snoozed for the owner only, or put it back with null: + * kept in Totem, never written to the sheet. Drawn at once, with Undo. + */ +export async function markSheet(ref: string, next: 'done' | 'snoozed' | null, until: Date | null = null) { + const before = state.tasks.find((t) => t.ref === resolveRef(ref, state.tasks)) + if (!before || before.kind !== 'sheet') return + const mark = next ? { state: next, at: new Date().toISOString(), ...(next === 'snoozed' && until ? { until: until.toISOString() } : {}) } : undefined + const { mark: _old, hidden: _hidden, ...plain } = before + replaceTask({ ...plain, done: next === 'done', ...(next === 'snoozed' ? { hidden: true } : {}), ...(mark ? { mark } : {}) }) + try { + await markSheetRow(before.ref, next, until) + // A snooze that has run out since is no mark to put back. + const prior = before.mark?.state === 'snoozed' && !(before.mark.until && new Date(before.mark.until) > new Date()) ? null : before.mark ?? null + const undo = { label: 'Undo', onClick: () => { void markSheet(before.ref, prior?.state ?? null, prior?.until ? new Date(prior.until) : null) } } + if (next === 'done') pushToast(`Done: ${quote(before.title)}. The sheet is unchanged.`, 'info', { action: undo }) + else if (next === 'snoozed' && until) pushToast(`Snoozed until ${wakeLabel(until, new Date())}`, 'info', { action: undo }) + void loadWork() + } catch (e) { + replaceTask(before) + fail(e, next ? 'The row could not be marked.' : 'The row could not be put back.') + } +} + +/** Mark a task done, with Undo; a sheet row is done for the owner only (markSheet). */ export async function completeTask(ref: string) { const before = state.tasks.find((t) => t.ref === ref) + if (before?.kind === 'sheet' && !before.done) { await markSheet(ref, 'done'); return } if (!before || before.kind !== 'local' || before.done) return replaceTask({ ...before, done: true }) try { @@ -208,6 +235,7 @@ export async function completeTask(ref: string) { export async function reopenTask(ref: string) { const before = state.tasks.find((t) => t.ref === ref) + if (before?.kind === 'sheet') { await markSheet(ref, null); return } if (!before || before.kind !== 'local') return replaceTask({ ...before, done: false }) try { @@ -219,8 +247,9 @@ export async function reopenTask(ref: string) { } } -/** Snooze a local task until `until`, or wake it with null; Undo puts the old snooze back. */ +/** Snooze a task until `until`, or wake it with null; Undo puts the old snooze back. */ export async function snoozeTask(ref: string, until: Date | null) { + if (state.tasks.find((t) => t.ref === ref)?.kind === 'sheet') { await markSheet(ref, until ? 'snoozed' : null, until); return } const before = state.tasks.find((t) => t.ref === ref)?.todo if (!before) return const saved = await updateTask(ref, { snoozedUntil: until ? until.toISOString() : null })