From 017dd043060c9909528846e8c91d6bff3637801d Mon Sep 17 00:00:00 2001 From: ehonis Date: Wed, 25 Nov 2026 09:46:47 -0500 Subject: [PATCH] Archive projects and folders instead of deleting them (+1 more) Published from the private repository by oss-sync. - Composer: $ghost, $ folders, $opus models, $pin and $snooze - Archive projects and folders instead of deleting them 51 files changed, 1129 insertions(+), 202 deletions(-) --- AGENTS.md | 8 +- bridge.mjs | 100 +++++++++----- chat/projects.mjs | 59 ++++++-- chat/projects.test.mjs | 47 ++++++- chat/settle-bridge.test.mjs | 35 ++++- chat/store.mjs | 10 +- chat/task-folders-bridge.test.mjs | 46 +++++-- chat/thread-tools.mjs | 2 +- docs/chat.md | 78 +++++++++-- docs/tasks.md | 6 +- mobile/src/features/chat/ChatScreen.tsx | 10 +- mobile/src/features/chat/ModelPicker.tsx | 2 +- .../src/features/settings/paneRoutes.test.mjs | 1 + mobile/src/features/settings/panes.ts | 3 + .../features/settings/panes/ArchivePane.tsx | 78 +++++++++++ mobile/src/lib/chat/api.ts | 6 +- mobile/src/lib/chat/draftsShared.ts | 2 +- mobile/src/lib/chat/settle.ts | 8 ++ mobile/src/lib/chat/sidebar.ts | 3 +- mobile/src/lib/chat/store.ts | 45 +++--- mobile/src/lib/chat/storeDrafts.test.mjs | 2 +- mobile/src/lib/chat/types.ts | 12 ++ .../lib/components/settings/searchIndex.ts | 3 + .../src/lib/components/settings/sections.ts | 3 +- web/src/chat/ChatHeader.tsx | 4 +- web/src/chat/Composer.tsx | 57 ++++++-- web/src/chat/ModelPicker.tsx | 2 +- web/src/chat/ProjectCard.tsx | 27 ++-- web/src/chat/api.ts | 10 +- web/src/chat/chat.css | 2 + web/src/chat/composerDestinations.test.tsx | 69 +++++++++- web/src/chat/destinations.test.ts | 105 +++++++++++++- web/src/chat/destinations.ts | 128 ++++++++++++++++-- web/src/chat/draftsShared.test.ts | 2 +- web/src/chat/draftsShared.ts | 2 +- web/src/chat/icons.ts | 1 + web/src/chat/settle.test.ts | 14 ++ web/src/chat/settle.ts | 8 ++ web/src/chat/sidebar.test.ts | 9 ++ web/src/chat/sidebar.ts | 3 +- web/src/chat/store.ts | 74 ++++++---- web/src/chat/types.ts | 12 ++ web/src/chat/useChatDrafts.test.ts | 45 ++++++ web/src/chat/useChatDrafts.ts | 34 ++++- web/src/components/ChatView.tsx | 60 ++++++-- web/src/components/SettingsView.tsx | 4 + web/src/components/settings/ArchivePane.tsx | 78 +++++++++++ web/src/components/settings/searchIndex.ts | 3 + web/src/components/settings/sections.ts | 3 +- web/src/components/settings/settings.css | 5 + web/src/settingsSections.test.ts | 1 + 51 files changed, 1129 insertions(+), 202 deletions(-) create mode 100644 mobile/src/features/settings/panes/ArchivePane.tsx create mode 100644 web/src/components/settings/ArchivePane.tsx diff --git a/AGENTS.md b/AGENTS.md index ea5d8d2..3338e0b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,7 +66,7 @@ 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 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`). | +| 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). Projects are archived, never deleted: a task filed in an archived one keeps its `folderId` and reads as Personal until it is restored. 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>`. 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`. | @@ -86,15 +86,15 @@ open-ended work. The default provider and model come from Settings → Providers | Action log, approvals, runs | `logs/` | Every mutation is audited; MCP clients act through owner-approved, time-boxed leases (their 6-digit code only counts on a `legacy` install). Inbox approval checks: `logs/approval-proposals.mjs` turns the one reading of a proposal (`loadInboxProposal` in `bridge.mjs`, through the accept's own readers, handed to `actionInboxItem` as is) into the screened fields, the hold fingerprint and the digest the dashboard sends back (a changed proposal is refused, 409); a proposal unreadable when listed is refused on accept (409) and never read again to be sent, and its Accept is disabled; `logs/approval-hardening.mjs` refuses hidden characters (bidi controls, tags, zero-width, soft hyphen, stray variation selectors, all of `\p{Cf}`, blank fillers; allowed in RTL text, emoji and the three RGI subdivision flags only; 422 and logged) and holds a proposal identical to a dashboard denial of the last 7 days until "Show anyway" (enforced on accept, MCP sessions included); `logs/approval-inflight.mjs` records each accept before it runs and settles leftovers as `uncertain` before the port opens, as it does a send that failed after it may have gone out. Totem's own log lines use the `system` actor. `docs/logs.md`. | | Inbound MCP server | `POST /mcp` in `bridge.mjs` | For ChatGPT / Claude / Claude Code. Every tool has a title, all four annotation hints and an output schema (`MCP_TOOL_META`); a boot assertion enforces it. A sentence meant for the owner is `tellOwner`; `tellEthan` is sent alongside as a deprecated alias. `docs/totem-mcp-server.md`. | | Connections pane | `web/src/components/McpSettingsView.tsx`, `web/src/connections/state.ts`, `web/src/sources/SourceHealthPanel.tsx` | Settings → Connections, in this order: a "Needs you" line (`attentionItems`: failing or erroring sources, servers needing a sign-in or not working, Accounts rows needing the owner; each a jump to its section; never an all-clear before the gateway and the source log have answered), Data sources, MCP servers (the gateway switch and Re-sync in the section head; installed servers only, sorted needs sign-in → not working → live → off under small labels (`serverState`, `sortServers`), Sign in on the row itself; Totem's own tool sets folded into one "Built into Totem" row), Accounts (Gmail, Drive, WHOOP, Strava), Built-in data, Claude tools, then Add a connection (the catalog folded into one row, and a custom server). Sections are flush rows in one bordered list (`.conn-list`); keep new ones that way, lead with what needs the owner, and keep explanations to one line. A server's or Google service's open row has an Icon section, as a chat folder's: its own logo, a chat icon (`CONNECTION_ICON_CHOICES` in `web/src/connections/icons.ts`), an uploaded picture or a website's icon (`chat/favicon.mjs`), kept in `data/connection-icons.json` (`connections/icons.mjs`, `/api/connections/icons`); `ConnectionIcon` wears it everywhere, the iPhone app draws it but does not edit it, removing a server drops it, and its pictures count as kept uploads (`keptUploadIds`). | -| Settings | `web/src/components/SettingsView.tsx`, `web/src/components/settings/` | T3 Code's settings dialog, drawn over the page that opened it; Esc, × or the backdrop go back to that page (`behind` and `closeSettings` in `App.tsx`; moving between panes replaces history). Sections in groups (`sections.ts`): General, Appearance, Chat, Voice, Notifications, Keyboard; AI: Providers, Usage, Skills; Data: Connections, Tasks; Account: Security, Activity. A search over every row (`searchIndex.ts`; `/` or Ctrl/⌘+F) opens `/settings/
#` and flashes the row. On a phone the dialog fills the screen as a list that opens one pane. Panes are built from `settings/ui.tsx`: a `SettingsSection` is a heading over one bordered group, a `SettingsRow` a title, one line of description and its control on the right (a device setting shows a reset arrow once changed); keep new settings that way. Retired panes redirect (`MOVED_SECTIONS`): AI → Providers (defaults, accounts, API keys, CLIProxy), Integrations → General (public URL; the read-only task sheet is under Tasks), Jobs → the Totems page, `/logs` → Activity, `providers#usage` → Usage. A new row that search should find adds its id to `searchIndex.ts` (`settingsSections.test.ts` checks every id is drawn somewhere). The iPhone app draws the same sections natively (`mobile/src/features/settings/`, all but Keyboard), with byte-for-byte copies of `sections.ts` and `searchIndex.ts` in `mobile/src/lib/components/settings/`; a new row or id is added to the app's pane too (`paneRoutes.test.mjs` checks it). | +| Settings | `web/src/components/SettingsView.tsx`, `web/src/components/settings/` | T3 Code's settings dialog, drawn over the page that opened it; Esc, × or the backdrop go back to that page (`behind` and `closeSettings` in `App.tsx`; moving between panes replaces history). Sections in groups (`sections.ts`): General, Appearance, Chat, Voice, Notifications, Keyboard; AI: Providers, Usage, Skills; Data: Connections, Tasks, Archive; Account: Security, Activity. A search over every row (`searchIndex.ts`; `/` or Ctrl/⌘+F) opens `/settings/
#` and flashes the row. On a phone the dialog fills the screen as a list that opens one pane. Panes are built from `settings/ui.tsx`: a `SettingsSection` is a heading over one bordered group, a `SettingsRow` a title, one line of description and its control on the right (a device setting shows a reset arrow once changed); keep new settings that way. Retired panes redirect (`MOVED_SECTIONS`): AI → Providers (defaults, accounts, API keys, CLIProxy), Integrations → General (public URL; the read-only task sheet is under Tasks), Jobs → the Totems page, `/logs` → Activity, `providers#usage` → Usage. A new row that search should find adds its id to `searchIndex.ts` (`settingsSections.test.ts` checks every id is drawn somewhere). The iPhone app draws the same sections natively (`mobile/src/features/settings/`, all but Keyboard), with byte-for-byte copies of `sections.ts` and `searchIndex.ts` in `mobile/src/lib/components/settings/`; a new row or id is added to the app's pane too (`paneRoutes.test.mjs` checks it). | | Outbound MCP gateway | `mcp-gateway.mjs` | One stdio MCP server each agent CLI registers; exposes built-in `tasks__*`, `goals__*`, `lists__*`, `strava__*` plus every manifest server. Not the same thing as `/mcp`. A manifest server's `oauth` sets the name and `software_id` Totem registers with; a server with `route` lists no tools and takes the calls to another server that name its target (`serverRoute`), which is how each T3 Code machine is reached directly and labels Totem's threads "Totem" (`docs/t3code.md`). | | Integrations | `strava/`, `whoop/`, the WHOOP sleep sync and Calendar blocks in `bridge.mjs`, `camera/` | Strava (`docs/strava.md`; the grant is Bushido's, read through `strava/remote.mjs` with `BUSHIDO_URL`/`BUSHIDO_API_URL` and `BUSHIDO_API_TOKEN`; Totem holds no Strava credentials), WHOOP sleep (`docs/whoop-sleep-ingest.md`; the grant is Bushido's too, read through `whoop/remote.mjs` with the same settings; Totem holds no WHOOP credentials; the nights fill a habit hidden from the dashboard), photo sync from a camera card (`docs/camera-sync.md`). | | Source health | `sources/`, `web/src/sources/`, `mobile/src/features/settings/panes/ConnectionsPane.tsx` | One sync-run log every connector writes to (`data/source-runs.db`, `SOURCE_RUNS_DB`), one run per operation, not per request: a connector takes `runs` and wraps each operation in `tracker(runs)(id, fn)` (`sources/track.mjs`; calls nested inside join it). Strava and WHOOP calls that reach the provider through Bushido (not Bushido's cache reads; its `status` is noted), Calendar, Gmail and Drive per account, the task sheet feed (`task-sheet`), feed scans and MCP servers in the gateway status check. Health is folded from the runs (`sources/health.mjs`): degraded, then failing after three failures in a row over ten minutes; not set up; last OK, failing since, error, rows. Errors are scrubbed in layers before they are stored, runs kept 30 days. A run log that cannot be opened turns health off instead of stopping the bridge (`openSourceRuns`). `GET /api/sources` names the goals each source feeds (`GOAL_SOURCE_IDS`, `goalService.sourcedGoals()`); Settings → Connections › Data sources shows only failing and erroring sources in full (with the goals they feed) and folds working and not-set-up ones into a count each (`sortSources`), leaving MCP servers to the MCP section on the web, and a metric whose source is failing says so on its goal card. The owner is told once per outage, with no error text (`sources/notice.mjs`, key `source::failing:`, marked sent only once queued, dropped at delivery if the source recovered). `docs/source-health.md`. | | Apple data | `apple/`, the "Apple" block in `bridge.mjs`, the Messages view in `web/src/messages/` | macOS only, off unless `APPLE_ENABLED=true`. Reads Messages (`chat.db`), Contacts and Photos (`Photos.sqlite` plus Photos' own search index) read-only; sends through the Messages app with `osascript`. The owner sends from the Messages tab (last on the desktop rail, not on the phone drawer; `/messages` still opens); agents only stage an `imessage` inbox proposal (`totem_apple_propose_message`), which only the dashboard can accept. `docs/apple.md`. | | Chat | `chat/`, the "Web chat" block in `bridge.mjs`, `web/src/chat/` | Server-owned threads and runs that outlive the browser, listed as summaries and read a window at a time with Load earlier (`GET /api/threads?view=summary`, `GET /api/threads/?turns=10&before=`; one merge file shared by web and app, `web/src/chat/history.ts`; each chat reopens where it was left, `scrollMemory.ts`; docs/chat.md → Loading chats) (`POST /api/chat` streams SSE; `GET /api/chat/runs//stream?since=` re-attaches; only `POST /api/chat/stop` ends a run early; `POST /api/chat/steer` sends the owner's words and files into a running reply, live for Claude, interrupt-and-resume for the rest, `chat/steer.mjs`; or the message waits in the thread's queue, which the bridge drains itself when a run ends and holds after a stop or failure, `chat/queue.mjs`, `POST /api/chat/queue`; Settings → Chat › Follow-up behaviour picks which Enter does, Ctrl/⌘ the other). T3 Code's saved drafts: one per chat, several per place for chats not started yet (`new:`), each its words and finished uploads, rows atop the chats list and a pencil on a chat with unsent words; pure store `web/src/chat/drafts.ts` and what both clients do with it in `draftsShared.ts` (both copied byte for byte to `mobile/src/lib/chat/`, whose storage side is `draftsApp.ts`: a record per bridge, the drawer's "Unsent" rows, swipe or long-press to discard with the drawer's Undo line, saved as the app leaves the foreground) with the web's storage, other tabs and Undo in `draftsWeb.ts` and the chat view's wiring in `useChatDrafts.ts`, and the bridge holds a draft's uploads past the orphan sweep for 30 days from the last renewal (`POST /api/chat/uploads/hold`, `createUploadHolds`); docs/chat.md → Drafts. Native per-provider session resume, attachments (in the tray and inline in the text as T3 Code-style chips: the composer is a minimal TipTap editor over the message string, `web/src/chat/editor/`, its own chunk; a chip is `![name](totem-ref://upload/)` or `[name](…)` in the text, `web/src/chat/refs.ts`, copied byte for byte to the app; the bridge turns each into `[Image: …; ref=upload_]` plus one `` block with paths, resolving only the message's own uploads, `chat/refs.mjs`; lists, titles and search show plain names; docs/chat.md → Attachments), Markdown formatted as it is typed (numbered, bullet and task lists and code fences as real nodes that keep the prefix each line was typed with; Return, Tab and Shift+Tab in a list are edits of the string, `web/src/chat/editor/markdown.ts`, so the message is exactly the Markdown typed; Settings → Chat › Format Markdown as you type turns the drawing off per device; docs/chat.md → Lists and code in the message box), named tool cards folded with the reply's in-between text into one line above the answer, led by the connectors' own logos stacked (`web/src/chat/workFold.ts`; Claude's `tool_use_meta`, `connectorLook` in `chat/tools.mjs`); a picture a tool returned (an image the agent read, a screenshot) stays on its card as a thumbnail (`images` on the tool part, from a `tool_image` event), and the reply shows one only when the agent writes `![…](path)`, from its outputs folder, the temp dir or an image Claude read that turn (which reuses the card's upload); the upload sweep keeps ids a message's text names (docs/chat.md → Pictures the agent looks at), per-reply stats (setting, effort, tokens, tok/s, cost; `chat/stats.mjs`, shown on hover by `TurnStats.tsx`), no modes (every chat run gets the browser, computer use where the account has it, and an hour; the agent decides, `chat/reach.mjs`), the model picker (`ModelPicker.tsx`; no automatic routing since Auto/Instant/Thinking were retired; picking another account mid-chat hands the chat over with what it missed, `handoffReplay`, docs/chat.md → Switching accounts), thread titles and icons, local whisper.cpp dictation and an optional OpenAI Realtime voice mode. `docs/chat.md`. | -| Chat projects | `chat/projects.mjs`, `chat/memory-ref.mjs`, `web/src/chat/Project*.tsx` | A project's page is its composer (centred on desktop) and chats (the first five, then Show more: `FIRST_CHATS` in `ProjectHome.tsx`); its files, instructions, memory, model and settings are a T3 Code-style card pinned top right (`ProjectCard.tsx`, stacked over a task's pinned card in `.vc-pins`; in the page on a phone). Chats grouped with a shared default model (a new chat takes its own pick, else the folder's, else the project's, else Settings → Providers: `threadChoice`/`projectDefault` in `web/src/chat/store.ts`, `projectModelDefault` on the bridge; a pick in a draft never carries to another chat), owner-written instructions, an agent-kept `memory.md` and shared files (`data/chat-projects/`). Each turn names the memory file with a one-line summary (size, entries, last updated, headings) and the agent reads it on demand, again when the summary changed; only the owner's instructions are pasted (memory used to be, once per turn of a resumed session). OpenCode, which cannot read outside `AGENT_CWD` unattended, gets the file's start instead. One level of folders (`parentId`) that read the parent read-only and keep their own memory; a chat can turn project context off (`projectContextOff`); an uploaded image or a website's icon can stand in for the Tabler icon (`image`, `chat/favicon.mjs`); finished chats wait on the owner (`needsReply`) until the owner opens one, replies or marks it read; "Mark as unread" sets `keepUnread`, which opening does not clear. The chats panel has one Snoozed and one Settled shelf, a project's page its own, T3 Code style (`web/src/chat/settle.ts`; auto-settle and wake-up are computed on read, never written). An agent that finished a one-off request calls `mark_chat_done` (`chat/done.mjs`, on `/agent-mcp`): the row offers a one-tap Settle until the reply is read, then the chat settles itself once he moves off it (`doneAt`; dropped by a failed or stopped reply, or by anything he writes in the chat: `wakeOnOwnerMessage` in `chat/store.mjs`, which also takes it off the Settled shelf and ends a snooze). `docs/chat.md` → Projects. | +| Chat projects | `chat/projects.mjs`, `chat/memory-ref.mjs`, `web/src/chat/Project*.tsx` | A project's page is its composer (centred on desktop) and chats (the first five, then Show more: `FIRST_CHATS` in `ProjectHome.tsx`); its files, instructions, memory, model and settings are a T3 Code-style card pinned top right (`ProjectCard.tsx`, stacked over a task's pinned card in `.vc-pins`; in the page on a phone). Chats grouped with a shared default model (a new chat takes its own pick, else the folder's, else the project's, else Settings → Providers: `threadChoice`/`projectDefault` in `web/src/chat/store.ts`, `projectModelDefault` on the bridge; a pick in a draft never carries to another chat), owner-written instructions, an agent-kept `memory.md` and shared files (`data/chat-projects/`). Each turn names the memory file with a one-line summary (size, entries, last updated, headings) and the agent reads it on demand, again when the summary changed; only the owner's instructions are pasted (memory used to be, once per turn of a resumed session). OpenCode, which cannot read outside `AGENT_CWD` unattended, gets the file's start instead. One level of folders (`parentId`) that read the parent read-only and keep their own memory; nothing deletes a project or folder: archiving one (`archivedAt`; `archive`/`restore` in the store, `list()` leaving it out, `active(id)` for every route that files into one) hides it with its folders and chats until Settings → Archive restores it (`GET /api/chat/projects/archived`; `docs/chat.md` → Projects); a chat can turn project context off (`projectContextOff`); an uploaded image or a website's icon can stand in for the Tabler icon (`image`, `chat/favicon.mjs`); finished chats wait on the owner (`needsReply`) until the owner opens one, replies or marks it read; "Mark as unread" sets `keepUnread`, which opening does not clear. The chats panel has one Snoozed and one Settled shelf, a project's page its own, T3 Code style (`web/src/chat/settle.ts`; auto-settle and wake-up are computed on read, never written). An agent that finished a one-off request calls `mark_chat_done` (`chat/done.mjs`, on `/agent-mcp`): the row offers a one-tap Settle until the reply is read, then the chat settles itself once he moves off it (`doneAt`; dropped by a failed or stopped reply, or by anything he writes in the chat: `wakeOnOwnerMessage` in `chat/store.mjs`, which also takes it off the Settled shelf and ends a snooze). `docs/chat.md` → Projects. | | Chats panel | `web/src/chat/ChatsNav.tsx`, `web/src/chat/sidebar.ts`, `web/src/chat/ThreadList.tsx` (`ThreadItem`, `ShelfSection`), `web/src/work/TaskBadge.tsx` | Since 1.1, T3 Code's sidebar: one list of every chat in every project and folder (no tabs, no drilling into projects), as `sidebarLists` sorts it: unsent drafts, Pinned, everything still in play latest first, then Working (running and not waiting on him; starts open), Snoozed and one Settled shelf at the bottom. Recent / By task at the top (`totem.chats.order`, By task by default; `web/src/tasksnav/`): By task folds Working in, gathers chats on one open task under its row (`playByTask`), and lists the scope's next tasks below by due day, folding, with Snooze (Tomorrow, 3 days, a week) and New chat on hover and a click that starts a chat for the task, carrying a new chat's typed words (`pickTask`, `useChatDrafts.startForTask`). Live chats are cards: place ("Project › Folder" or Home) and status words (Awaiting input/approval, Your turn, Working, Woke, Done, else age), title, and the linked task as T3 shows a PR (`TaskBadge`: glyph coloured by due/done, title, due day; a click opens its task card, never the chat). A scope button (All chats, Home, a project or folder; `totem.chats.scope`) narrows the list without moving the page, with ↗ to the project's page and a dot for waiting chats it hides; New chat starts in the scoped project (`newChatInScope`). Totems' own chats are not listed (Totems is a rail item). The iPhone drawer is the same list (`mobile/src/features/chat/ChatsNav.tsx`, `mobile/AGENTS.md`). `docs/chat.md` → The chats panel. | -| Linked tasks | `web/src/work/`, `chat/task-folders.mjs`, `chat/task-link.mjs`, `/api/chat/task-folders` in `bridge.mjs` | A chat's task, shown on its card in the chats panel (above). Tasks and sheet rows are filed under a chat project or folder (a task's `folderId`; a sheet row's filing in `data/task-folders.json`, `TASK_FOLDERS_FILE`, `none` meaning Personal on purpose). The web panel's Tasks face (a list of every task with its chats, its add line and sort menu) was removed in 1.1; its By task order lists tasks with their chats now (Chats panel row), and the Tasks page edits them. A task's card (`web/src/work/TaskCard.tsx`: folder, due, priority, repeat, snooze, description, chats, Open in Tasks) is pinned at the open chat's top right for that chat's own task (`PinnedTask` in `ChatView`; folds, never closes, the log moves left to clear it; opening that task anywhere unfolds it, `pinTask` in `card.ts`), and any other task opens it as a modal dialog (`TaskCardHost`, mounted once in `App.tsx`; a bottom sheet on a phone), from a chat card's task badge. A chat names at most one task (`thread.taskId`: a task id or a sheet row id), linked from its "…", the `$` menu, or by starting a chat from the task (`startTaskDraft`; the first send carries `taskId`, kept by `startChatTurn` on a new chat only). A chat whose task is finished (a local task done, a sheet row the owner marked done) settles as a `mark_chat_done` chat does, the way T3 Code settles a thread when its pull request merges: the bridge adds `taskDoneAt` to every chat it reads out (`chat/task-done.mjs`, worked out per read, never stored, so a task reopened brings the chat back and a task finished from the gateway counts), and `settle.ts` `taskDoneSince` counts it only when the task was finished after the owner last wrote in the chat (`docs/chat.md` → Settled and snoozed). A linked chat's composer shows the task (Done, change, unlink; `TaskBar.tsx`) and every non-voice turn carries a `LINKED TASK.` block (`linkedTaskBlock`). Filing a task, Move to… and Link to task… share one T3 Code-style project-selector popover (`ComboPicker.tsx`: search, arrows, Enter, "New folder/project/task …" from what was typed). Tasks load while the chats panel, a card's task badge, a strip or the composer's `$` menu is on screen. A chat not started yet is placed from its composer with `$` (Home, a project or folder, or a task, which starts it through `startTaskDraft` in the task's folder; `web/src/chat/destinations.ts`, `destinations` on `Composer`), and `$task` makes a new task right there: the box becomes its quick-add line (`parseQuickAdd`, filed where the chat is unless `#folder`), Return creates it and starts the chat for it (`web/src/chat/newTask.ts`, `NewTaskBar.tsx`, `newTask` in `useChatDrafts.ts`), and ⌘/Ctrl+Shift+O starts a blank chat at Home from any page (a hotkey: `hotkeys` in `web/src/shortcuts.ts`, Settings → Keyboard › Hotkeys; `docs/shortcuts.md` → Hotkeys). The iPhone drawer is the same list since 1.1 (`mobile/src/features/chat/ChatsNav.tsx`, `lib/chat/sidebar.ts` byte for byte, `features/work/TaskBadge.tsx`; no Tasks face): a task opens its own page, which lists its chats, in place of the card; no `$` menu. `docs/chat.md` → Linked tasks, → Placing a new chat with `$`, → Making a task with `$task`. | +| Linked tasks | `web/src/work/`, `chat/task-folders.mjs`, `chat/task-link.mjs`, `/api/chat/task-folders` in `bridge.mjs` | A chat's task, shown on its card in the chats panel (above). Tasks and sheet rows are filed under a chat project or folder (a task's `folderId`; a sheet row's filing in `data/task-folders.json`, `TASK_FOLDERS_FILE`, `none` meaning Personal on purpose). The web panel's Tasks face (a list of every task with its chats, its add line and sort menu) was removed in 1.1; its By task order lists tasks with their chats now (Chats panel row), and the Tasks page edits them. A task's card (`web/src/work/TaskCard.tsx`: folder, due, priority, repeat, snooze, description, chats, Open in Tasks) is pinned at the open chat's top right for that chat's own task (`PinnedTask` in `ChatView`; folds, never closes, the log moves left to clear it; opening that task anywhere unfolds it, `pinTask` in `card.ts`), and any other task opens it as a modal dialog (`TaskCardHost`, mounted once in `App.tsx`; a bottom sheet on a phone), from a chat card's task badge. A chat names at most one task (`thread.taskId`: a task id or a sheet row id), linked from its "…", the `$` menu, or by starting a chat from the task (`startTaskDraft`; the first send carries `taskId`, kept by `startChatTurn` on a new chat only). A chat whose task is finished (a local task done, a sheet row the owner marked done) settles as a `mark_chat_done` chat does, the way T3 Code settles a thread when its pull request merges: the bridge adds `taskDoneAt` to every chat it reads out (`chat/task-done.mjs`, worked out per read, never stored, so a task reopened brings the chat back and a task finished from the gateway counts), and `settle.ts` `taskDoneSince` counts it only when the task was finished after the owner last wrote in the chat (`docs/chat.md` → Settled and snoozed). A linked chat's composer shows the task (Done, change, unlink; `TaskBar.tsx`) and every non-voice turn carries a `LINKED TASK.` block (`linkedTaskBlock`). Filing a task, Move to… and Link to task… share one T3 Code-style project-selector popover (`ComboPicker.tsx`: search, arrows, Enter, "New folder/project/task …" from what was typed). Tasks load while the chats panel, a card's task badge, a strip or the composer's `$` menu is on screen. A chat not started yet is placed from its composer with `$` (Home, a project or folder, or a task, which starts it through `startTaskDraft` in the task's folder; `web/src/chat/destinations.ts`, `destinations` on `Composer`), `$ghost` makes it a ghost chat (a `temporary` chat at Home: gone at midnight, and listed nowhere once settled, `ghostGone` in `settle.ts`; settled by hand on the web it is deleted when its Undo toast passes), a name no place has (`$tax-returns`) offers New folder/New project by that name and starts the chat in it, `$opus` (any model or account name) picks the new chat's model, `$pin` pins it from the start and `$snooze` sends it and keeps it in Snoozed until a time even once answered (`snoozeHeld`, bridge-set, so its reply neither wakes it nor pushes), and `$task` makes a new task right there: the box becomes its quick-add line (`parseQuickAdd`, filed where the chat is unless `#folder`), Return creates it and starts the chat for it (`web/src/chat/newTask.ts`, `NewTaskBar.tsx`, `newTask` in `useChatDrafts.ts`), and ⌘/Ctrl+Shift+O starts a blank chat at Home from any page (a hotkey: `hotkeys` in `web/src/shortcuts.ts`, Settings → Keyboard › Hotkeys; `docs/shortcuts.md` → Hotkeys). The iPhone drawer is the same list since 1.1 (`mobile/src/features/chat/ChatsNav.tsx`, `lib/chat/sidebar.ts` byte for byte, `features/work/TaskBadge.tsx`; no Tasks face): a task opens its own page, which lists its chats, in place of the card; no `$` menu. `docs/chat.md` → Linked tasks, → Placing a new chat with `$`, → Making a task with `$task`, → More `$` actions. | | Chat files | `chat/files.mjs`, `web/src/chat/FilesPanel.tsx`, `/api/chat/files*` in `bridge.mjs`, `openFile` in `web/src/chat/store.ts`, `web/src/links.ts` | T3 Code's files viewer: the chat's outputs folder as a tree beside the chat, every file openable in the canvas and downloadable from any device. It, the canvas, Browser and Agents panels share one slot, drag-resizable per panel (`docs/chat.md` → Side panel widths). Serves `CHAT_OUTPUTS_DIR` plus `FILES_ROOTS`, by real path, never Totem's `data/`, `secrets/` or `.env`. A reply's link to an absolute path opens there, and the same path opened as a URL redirects to the chat (`?file=`). Every opener goes through `openFile(path)`: `GET /api/chat/files/link` checks the path and returns a signed link (real path + 12 h expiry + HMAC under a random per-process key), which the canvas, its frames and the native download read without the bearer (a Files row's Download signs on the click; the listing carries no links); only the exact spelling `/api/chat/files/raw?…&sig=` skips the sign-in gate, and the roots/deny check runs on every read. A bearer-only dashboard read the bare raw URL with no header and showed `{"error":"unauthorized"}`; `chat/files-bridge.test.mjs` boots a bridge to hold this. `docs/chat.md` → Files panel. | | Download activity | `web/src/downloads.ts`, `web/src/components/DownloadActivity.tsx`, `desktop/src-tauri/src/lib.rs` | App-wide activity for download links, chat and question attachments, generated files, previews, project files, Messages files and journal audio. Active repeats join one transfer; different files have separate progress, cancel/retry and dismiss controls. Browsers offering a save-file picker stream directly to the chosen file; otherwise transfers buffer at most 32 MiB before handing larger files to the browser. Browser handoff and application transfer completion explicitly tell the owner to check Downloads, never claim an OS save. Native wrappers advertising `downloads` stream through Tauri and report real saved/failed events (indeterminate: Tauri has no byte progress); this requires a new desktop build. A saved native download gets Show in folder (Show in Finder on a Mac): the app keeps the path (`Downloads` in `lib.rs`, the last 50) and the page asks by the download's URL through a cancelled `totem-desktop://reveal?u=` navigation, never seeing a path; older wrappers do not send `reveal`, so no button. Raw chat files and signed uploads accept authenticated HEAD preflights without reading file bodies; bearer-only users need a session or a signed URL (an upload's `?sig=`, a chat file's signed link) for native/browser navigation handoff. | | Sub-agents | `chat/subagents.mjs`, `web/src/chat/AgentsPanel.tsx` | Agents a chat's agent starts: Claude's Agent/Task sub-agents (events tagged `parent_tool_use_id`), Codex collab children, and another CLI run from a shell (`codex exec`, `claude -p`, …), whose own session log is found by start time and prompt and tailed. Each folds into its tool card as `part.agent` (status, model, tokens, steps). The Agents panel beside the chat lists them and opens each one's live log. Each writes an `agent.delegate` line to the action log. `docs/chat.md` → Agents panel. | diff --git a/bridge.mjs b/bridge.mjs index dde885b..4f545c4 100644 --- a/bridge.mjs +++ b/bridge.mjs @@ -85,7 +85,7 @@ import { redactTokens } from './chat/redact.mjs' import { createFileAccess, chatFileRedirect, mimeFor as fileMime } from './chat/files.mjs' import { fetchFavicon } from './chat/favicon.mjs' import { createConnectionIconStore, validConnectionId } from './connections/icons.mjs' -import { createProjectStore, moveMemoryEntries, validProjectId } from './chat/projects.mjs' +import { archivedIn, 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' @@ -4728,7 +4728,7 @@ async function handleAskText(text, channel, options = {}) { requestId, summarize: false, }).catch((e) => log('shortcut answer push failed', e?.message || e)) - return `I need more info to finish that. I started a temporary web chat for the follow-up:\n${url}` + return `I need more info to finish that. I started a ghost chat for the follow-up (gone at midnight):\n${url}` } catch (e) { log('shortcut clarification thread write failed', e) return `I need more info to finish that:\n${question}` @@ -9107,11 +9107,22 @@ const taskDone = createTaskDone({ return feed?.configured ? (feed.items || []).map((r) => r.id) : null }, }) -const listThreads = async () => (await taskDone.decorate(await threadStore.list())).map(signThread) +// Chats in an archived project or folder are put away with it (chat/projects.mjs), +// so the lists leave them out until it is restored; each one still opens by its id. +async function archivedProjectIds() { + const all = await projectStore.listAll().catch(() => []) + return new Set(all.filter((p) => archivedIn(all, p)).map((p) => p.id)) +} +const inUse = (hidden) => (t) => !t.projectId || !hidden.has(t.projectId) +const listThreads = async () => { + const hidden = await archivedProjectIds() + return (await taskDone.decorate((await threadStore.list()).filter(inUse(hidden)))).map(signThread) +} // The list carries a browser handoff still waiting on the owner (browser/handoff.mjs). const listThreadSummaries = async () => { const open = new Set(browserManager.sessionKeys()) - return (await taskDone.decorate(await threadStore.summaries())).map((t) => withHandoff(signThread(t), browserHandoffs, open)) + const hidden = await archivedProjectIds() + return (await taskDone.decorate((await threadStore.summaries()).filter(inUse(hidden)))).map((t) => withHandoff(signThread(t), browserHandoffs, open)) } const readThread = async (id) => signThread(await taskDone.one(await threadStore.get(id))) const readThreadPage = async (id, opts) => signThread(await taskDone.one(await threadStore.page(id, opts))) @@ -9918,13 +9929,17 @@ async function startChatTurn(body, { idle = null } = {}) { const existing = await threadStore.get(threadId) // A new chat may start inside a project; an existing one stays where it is. const projectId = existing ? (existing.projectId || null) - : (validProjectId(body.projectId) && await projectStore.get(body.projectId) ? body.projectId : null) + : (validProjectId(body.projectId) && await projectStore.active(body.projectId) ? body.projectId : null) const kind = projectId ? 'regular' : existing?.kind || (body.kind === 'temporary' ? 'temporary' : 'regular') // A project chat can leave the project's context out, from its first turn or any later one. const contextOff = !!projectId && (existing ? !!existing.projectContextOff : body.projectContextOff === true) const shareWithProject = projectId && !contextOff // A new chat started from a task (Chats panel → Tasks) is linked to it from its first turn. const newTaskId = !existing && validTaskRef(body.taskId) ? body.taskId : null + // `$pin` and `$snooze` in a new chat's composer: pinned from the start, or out of the + // way until a time (at most a year) even once its first reply lands (`snoozeHeld`). + const newPinned = !existing && body.pinned === true + const snoozeUntil = !existing && Number.isFinite(body.snoozeUntil) && body.snoozeUntil > Date.now() && body.snoozeUntil < Date.now() + 366 * 86_400_000 ? Math.round(body.snoozeUntil) : 0 // Older clients still send `mode` ('task' | 'computer') and `browser`: read // only as hints (chatReach), never an error. const voice = body.voice === true @@ -10013,8 +10028,9 @@ async function startChatTurn(body, { idle = null } = {}) { delete t.needsReply delete t.keepUnread wakeOnOwnerMessage(t, now) + if (snoozeUntil) Object.assign(t, { snoozedUntil: snoozeUntil, snoozedAt: now, snoozeHeld: true }) t.updatedAt = now - }, { create: { id: threadId, kind, provider, modelSettings: body.modelSettings, createdAt: now, updatedAt: now, ...(projectId ? { projectId } : {}), ...(contextOff ? { projectContextOff: true } : {}), ...(newTaskId ? { taskId: newTaskId } : {}), ...(kind === 'temporary' ? { expiresAt: endOfTodayMs() } : {}) } }) + }, { create: { id: threadId, kind, provider, modelSettings: body.modelSettings, createdAt: now, updatedAt: now, ...(projectId ? { projectId } : {}), ...(contextOff ? { projectContextOff: true } : {}), ...(newTaskId ? { taskId: newTaskId } : {}), ...(newPinned ? { pinned: true } : {}), ...(kind === 'temporary' ? { expiresAt: endOfTodayMs() } : {}) } }) const files = await loadChatFiles(userMessage.attachments) // What he attaches in a project chat is shared with the whole project. @@ -10546,6 +10562,7 @@ async function startChatTurn(body, { idle = null } = {}) { assistant.parts = (assistant.parts || []).filter((p) => p.type !== 'text' || p.text) for (const p of found) assistant.parts.push({ type: 'totem-proposal', id: randomUUID().slice(0, 12), status: 'pending', totemName: known.get(p.totemId)?.name, ...p }) } + let heldSnooze = false await save((t) => { if (sessionId && status !== 'error') { // Through this reply only: an inbox outcome recorded while it ran (chat/inbox-outcome.mjs) @@ -10564,8 +10581,12 @@ async function startChatTurn(body, { idle = null } = {}) { if (status !== 'stopped' && !t.totemId) t.needsReply = true // Marked done (chat/done.mjs) only counts for a reply that finished. if (status !== 'done') delete t.doneAt - // A reply that lands while the chat is snoozed wakes it early. - if (status !== 'stopped' && Number(t.snoozedUntil) > Date.now()) t.snoozedUntil = Date.now() + // A reply that lands while the chat is snoozed wakes it early, unless he + // snoozed it as he started it (`$snooze`): then it waits for its time. + if (status !== 'stopped' && Number(t.snoozedUntil) > Date.now()) { + if (t.snoozeHeld) heldSnooze = true + else t.snoozedUntil = Date.now() + } }) // Only now: until this save, an inbox card decided meanwhile must reach this // reply's own copy (inboxCard), or the save would write it back as pending. @@ -10582,7 +10603,8 @@ async function startChatTurn(body, { idle = null } = {}) { recordUse('web', { text, startedAt: t0, ok: status !== 'error', provider }) // Nobody looking at this chat (phone locked, app in the background, another // chat open): tell the phone it's done. Skipped only while someone is on it. - if (status !== 'stopped' && !someoneViewing(threadId)) { + // Snoozed by him from the start: nothing to push now; the chat comes back at its time. + if (status !== 'stopped' && !heldSnooze && !someoneViewing(threadId)) { const latest = await threadStore.get(threadId).catch(() => null) notifier.deliver({ title: status === 'error' ? `Totem couldn't finish: ${latest?.title || 'your chat'}` : (latest?.title || 'Totem answered'), @@ -11414,7 +11436,7 @@ async function handleTaskFoldersApi(req, res, path) { try { task = decodeURIComponent(path.slice('/api/chat/task-folders/'.length)) } catch { return send(res, 400, { error: 'bad task id' }) } const body = await readJsonBody(req) const projectId = body.projectId == null || body.projectId === '' ? null : body.projectId - if (projectId && !(validProjectId(projectId) && await projectStore.get(projectId))) return send(res, 404, { error: 'project not found' }) + if (projectId && !(validProjectId(projectId) && await projectStore.active(projectId))) return send(res, 404, { error: 'project not found' }) // A local task carries its folder. A dashboard still open from before this // change (it reloads itself within minutes) files tasks here: put it on the task. if (!task.startsWith('sheet:') && todoService.get(task)) { @@ -11439,7 +11461,7 @@ async function handleChatProjectsApi(req, res, path) { if (!String(body.name || '').trim()) return send(res, 400, { error: 'a project needs a name' }) // A folder goes one level deep: its parent must be a top-level project. if (body.parentId != null) { - const parent = validProjectId(body.parentId) ? await projectStore.get(body.parentId) : null + const parent = validProjectId(body.parentId) ? await projectStore.active(body.parentId) : null if (!parent) return send(res, 404, { error: 'parent project not found' }) if (parent.parentId) return send(res, 400, { error: 'a folder cannot hold folders' }) } @@ -11449,9 +11471,37 @@ async function handleChatProjectsApi(req, res, path) { return send(res, 201, { project: { ...projectSummary(project, []), files: [], memory: '' } }) } } - const m = /^\/api\/chat\/projects\/([A-Za-z0-9_-]{1,64})(\/files\/move|\/files(?:\/([A-Za-z0-9_-]{8,64}))?|\/memory(?:\/move)?|\/favicon)?$/.exec(path) + // Settings → Archive: what is put away, each archived project with its folders + // and each archived folder whose project is still in use. + if (path === '/api/chat/projects/archived') { + if (req.method !== 'GET') return send(res, 405, { error: 'method not allowed' }) + const all = await projectStore.listAll() + const threads = await threadStore.list() + const entry = (p) => { + const folders = p.parentId ? [] : all.filter((f) => f.parentId === p.id) + const ids = new Set([p.id, ...folders.map((f) => f.id)]) + return { + ...projectSummary(p, threads), + chatCount: threads.filter((t) => ids.has(t.projectId)).length, + ...(p.parentId ? { parentName: all.find((x) => x.id === p.parentId)?.name || null } : {}), + folders: folders.map((f) => ({ id: f.id, name: f.name, icon: f.icon, archivedAt: f.archivedAt, chatCount: threads.filter((t) => t.projectId === f.id).length })), + } + } + const items = all.filter((p) => p.archivedAt && !(p.parentId && all.find((x) => x.id === p.parentId)?.archivedAt)) + return send(res, 200, { projects: items.sort((a, b) => b.archivedAt - a.archivedAt).map(entry) }) + } + const m = /^\/api\/chat\/projects\/([A-Za-z0-9_-]{1,64})(\/files\/move|\/files(?:\/([A-Za-z0-9_-]{8,64}))?|\/memory(?:\/move)?|\/favicon|\/archive|\/restore)?$/.exec(path) if (!m) return false const [, id, sub, fileId] = m + // Put away whole (chat/projects.mjs): its files, memory and chats stay as they are. + if ((sub === '/archive' || sub === '/restore') && req.method === 'POST') { + try { + const project = sub === '/archive' ? await projectStore.archive(id) : await projectStore.restore(id) + return send(res, 200, { project: projectSummary(project, await threadStore.list()) }) + } catch (e) { return send(res, e.status || 500, { error: e.message }) } + } + // An archived one is read and changed only by restoring it. + if (!(await projectStore.active(id))) return send(res, 404, { error: 'project not found' }) const full = async () => { const project = await projectStore.get(id) if (!project) return null @@ -11473,30 +11523,6 @@ async function handleChatProjectsApi(req, res, path) { if ('image' in body) await setProjectImage(id, image || null) return send(res, 200, { project: await full() }) } - if (req.method === 'DELETE') { - // Its chats move rather than vanishing with it: a folder's up to its - // project, a project's (and its folders') to Home. Its files go, except - // ones a chat message still shows. - const project = await projectStore.remove(id) - if (!project) return send(res, 404, { error: 'project not found' }) - const folders = project.parentId ? [] : (await projectStore.list()).filter((p) => p.parentId === id) - for (const f of folders) await projectStore.remove(f.id) - const gone = new Set([id, ...folders.map((f) => f.id)]) - let moved = 0 - for (const t of await threadStore.list()) { - if (!gone.has(t.projectId)) continue - await threadStore.update(t.id, (x) => { if (project.parentId) x.projectId = project.parentId; else delete x.projectId }) - moved++ - } - // Tasks filed there move the same way. - for (const g of gone) { - await taskFolders.reassign(g, project.parentId || null) - // The project is already gone; a task left naming it reads as Personal, so a failure here is only logged. - try { todoService.refileFolder(g, project.parentId || null, { actor: 'http', reason: 'chat project removed' }) } catch (e) { log(`task folders: could not move tasks out of a removed project (${e.message})`) } - } - await dropUnusedUploads([project, ...folders].flatMap((p) => [...p.files.map((f) => f.id), ...(p.image ? [p.image] : [])])) - return send(res, 200, { ok: true, movedChats: moved, removedFolders: folders.length }) - } } // A folder's entries or files, moved up into its parent project. if ((sub === '/memory/move' || sub === '/files/move') && req.method === 'POST') { @@ -16720,7 +16746,7 @@ const server = http.createServer(async (req, res) => { const thread = await writeThread(id, body) if (body.needsReply === false) dismissChatPush(id) // A chat moved into a project brings its files with it. - if (thread.projectId && !thread.projectContextOff && before && before.projectId !== thread.projectId && await projectStore.get(thread.projectId)) { + if (thread.projectId && !thread.projectContextOff && before && before.projectId !== thread.projectId && await projectStore.active(thread.projectId)) { const files = [] for (const m of thread.messages) { for (const a of m.attachments || []) files.push({ ...a, source: 'chat', threadId: id }) diff --git a/chat/projects.mjs b/chat/projects.mjs index a916bb8..6934220 100644 --- a/chat/projects.mjs +++ b/chat/projects.mjs @@ -20,9 +20,16 @@ // folder's, so a side topic never leaks into the main project. The owner moves // what should be shared up by hand: memory entries (moveMemoryEntries) and files. // +// Archiving: a project or folder is never deleted. Archiving one (`archivedAt`) +// puts it away whole, with its files, memory and chats, and a project's folders +// go with it; Settings → Archive brings it back as it was. `list()` is what is in +// use (archived ones and the folders of an archived project left out), so every +// picker, the chats panel and the agents' tools pass over it; `get()` still reads +// it, so a chat inside one keeps its context if the owner opens it from search. +// // Layout: //project.json + //memory.md. The memory is a file, // not a field, because the agent edits it with its own file tools. -import { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises' +import { mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { randomUUID } from 'node:crypto' @@ -82,6 +89,7 @@ function normalizeProject(raw, id) { if (validUploadId(raw?.image)) out.image = raw.image if (typeof raw?.provider === 'string' && /^[a-z0-9_-]{1,80}$/i.test(raw.provider)) out.provider = raw.provider if (validProjectId(raw?.parentId) && raw.parentId !== id) out.parentId = raw.parentId + if (num(raw?.archivedAt)) out.archivedAt = num(raw.archivedAt) const ms = normalizeModelSettings(raw?.modelSettings) if (ms) out.modelSettings = ms return out @@ -205,7 +213,8 @@ export function createProjectStore({ dir } = {}) { return raw ? normalizeProject(raw, id) : null } - async function list() { + /** Every project and folder, archived ones included. */ + async function listAll() { let names = [] try { names = await readdir(dir) } catch { return [] } const out = [] @@ -216,6 +225,20 @@ export function createProjectStore({ dir } = {}) { return out.sort((a, b) => a.name.localeCompare(b.name)) } + /** The projects and folders in use: not archived, nor inside an archived project. */ + async function list() { + const all = await listAll() + return all.filter((p) => !archivedIn(all, p)) + } + + /** A project or folder that is in use, or null (missing or archived). */ + async function active(id) { + const p = await get(id) + if (!p || p.archivedAt) return null + if (p.parentId && (await get(p.parentId))?.archivedAt) return null + return p + } + async function create(body = {}) { const id = randomUUID().replace(/-/g, '').slice(0, 20) const now = Date.now() @@ -280,22 +303,38 @@ export function createProjectStore({ dir } = {}) { await writeFile(memoryPath(id), String(text || '').slice(0, MEMORY_MAX)) } - async function remove(id) { - const project = await get(id) - if (!project) return null - await rm(folder(id), { recursive: true, force: true }) - return project + /** Put a project (with its folders) or a folder away. Refused when it is not in use. */ + async function archive(id) { + if (!(await active(id))) throw Object.assign(new Error((await get(id)) ? 'that is already archived' : 'project not found'), { status: (await get(id)) ? 409 : 404 }) + return update(id, (p) => { p.archivedAt = Date.now() }) + } + + /** Bring an archived project or folder back. A folder whose project is archived waits for the project. */ + async function restore(id) { + const p = await get(id) + if (!p) throw Object.assign(new Error('project not found'), { status: 404 }) + if (!p.archivedAt) throw Object.assign(new Error('that is not archived'), { status: 409 }) + if (p.parentId && (await get(p.parentId))?.archivedAt) throw Object.assign(new Error('its project is archived; restore the project first'), { status: 409 }) + return update(id, (x) => { delete x.archivedAt }) } - /** Every upload id any project holds, so thread cleanup and the orphan sweep leave them be. */ + /** Every upload id any project holds (archived ones too), so thread cleanup and the orphan sweep leave them be. */ async function fileIds() { const ids = new Set() - for (const p of await list()) { + for (const p of await listAll()) { for (const f of p.files) ids.add(f.id) if (p.image) ids.add(p.image) } return ids } - return { list, get, create, patch, update, addFiles, removeFiles, readMemory, writeMemory, memoryPath, remove, fileIds } + return { list, listAll, get, active, create, patch, update, addFiles, removeFiles, readMemory, writeMemory, memoryPath, archive, restore, fileIds } +} + +/** Is this project put away: archived itself, or a folder of an archived project? */ +export function archivedIn(projects, p) { + if (!p) return false + if (p.archivedAt) return true + const parent = p.parentId ? projects.find((x) => x.id === p.parentId) : null + return !!parent?.archivedAt } diff --git a/chat/projects.test.mjs b/chat/projects.test.mjs index 45edf1d..0e6367a 100644 --- a/chat/projects.test.mjs +++ b/chat/projects.test.mjs @@ -73,8 +73,51 @@ test('memory is capped and a missing project refuses writes', async () => { await store.writeMemory(p.id, 'x'.repeat(MEMORY_MAX + 10)) assert.equal((await store.readMemory(p.id)).length, MEMORY_MAX) await assert.rejects(store.writeMemory('nope', 'hi'), /not found/) - await store.remove(p.id) - assert.equal(await store.get(p.id), null) + await rm(dir, { recursive: true, force: true }) +}) + +test('archiving puts a project away whole, with its folders, and restoring brings it back', async () => { + const dir = await tmp() + const store = createProjectStore({ dir }) + const p = await store.create({ name: 'Acme' }) + const f = await store.create({ name: 'Launch', parentId: p.id }) + const other = await store.create({ name: 'Other' }) + await store.addFiles(f.id, [{ id: 'file00000001', name: 'a.txt' }]) + await store.writeMemory(f.id, '- kept') + + await store.archive(p.id) + assert.deepEqual((await store.list()).map((x) => x.id), [other.id]) + assert.equal((await store.listAll()).length, 3) + assert.equal(await store.active(p.id), null) + assert.equal(await store.active(f.id), null, 'a folder of an archived project is put away too') + assert.ok((await store.get(p.id)).archivedAt, 'get still reads it') + assert.ok((await store.fileIds()).has('file00000001'), 'its files are not swept') + await assert.rejects(store.archive(p.id), /already archived/) + await assert.rejects(store.archive(f.id), /already archived/) + + await store.restore(p.id) + assert.deepEqual((await store.list()).map((x) => x.name), ['Acme', 'Launch', 'Other']) + assert.equal((await store.get(p.id)).archivedAt, undefined) + assert.equal(await store.readMemory(f.id), '- kept') + assert.equal((await store.get(f.id)).files.length, 1) + await assert.rejects(store.restore(p.id), /not archived/) + await rm(dir, { recursive: true, force: true }) +}) + +test('a folder archived on its own waits for its project to be restored first', async () => { + const dir = await tmp() + const store = createProjectStore({ dir }) + const p = await store.create({ name: 'Acme' }) + const f = await store.create({ name: 'Launch', parentId: p.id }) + await store.archive(f.id) + assert.deepEqual((await store.list()).map((x) => x.id), [p.id]) + await store.archive(p.id) + await assert.rejects(store.restore(f.id), /restore the project first/) + await store.restore(p.id) + assert.deepEqual((await store.list()).map((x) => x.id), [p.id], 'the folder stays archived on its own') + await store.restore(f.id) + assert.equal((await store.list()).length, 2) + await assert.rejects(store.archive('nope'), /not found/) await rm(dir, { recursive: true, force: true }) }) diff --git a/chat/settle-bridge.test.mjs b/chat/settle-bridge.test.mjs index a55871a..86a4fb5 100644 --- a/chat/settle-bridge.test.mjs +++ b/chat/settle-bridge.test.mjs @@ -94,11 +94,12 @@ const until = async (fn, ms = 15_000) => { } } +const until_ = (...a) => until(...a) const drain = async (reader) => { while (!(await reader.read()).done); } -/** Resolves once the bridge has started the reply; it holds until `release`. */ -async function startHeldReply(id, prompt) { - const r = await fetch(`${B.base}/api/chat`, { method: 'POST', headers: bearer, body: JSON.stringify({ provider: 'claude', threadId: id, text: prompt }) }) +/** Resolves once the bridge has started the reply; it holds until `release`. `extra` goes in the body. */ +async function startHeldReply(id, prompt, extra = {}) { + const r = await fetch(`${B.base}/api/chat`, { method: 'POST', headers: bearer, body: JSON.stringify({ provider: 'claude', threadId: id, text: prompt, ...extra }) }) assert.ok(r.ok, `POST /api/chat ${r.status}`) const reader = r.body.getReader() let seen = '' @@ -239,3 +240,31 @@ test('a voice turn wakes a snoozed chat; a turn with nothing he said does not', assert.deepEqual(shelved(t), {}) assert.ok(t.unsettledAt >= at) }) + +test('$snooze: a new chat snoozed as it starts stays snoozed once its reply lands', async () => { + const id = 'settle-held' + const until = Date.now() + 86_400_000 + const reply = await startHeldReply(id, 'hold-held', { snoozeUntil: until, pinned: true }) + let t = await thread(id) + assert.equal(t.snoozedUntil, until) + assert.equal(t.snoozeHeld, true) + assert.equal(t.pinned, true, '$pin: pinned from the start') + await reply.release() + t = await until_(async () => { const x = await thread(id); return x.needsReply ? x : null }) + assert.equal(t.snoozedUntil, until, 'its own reply does not wake it') + + // Snoozed again by hand, it is an ordinary snooze: the next reply wakes it. + await call('PUT', `/api/threads/${id}`, { snoozedUntil: until + 1000, snoozedAt: Date.now() }) + assert.equal((await thread(id)).snoozeHeld, undefined) +}) + +test('$snooze and $pin only start a new chat: an existing one keeps its own state', async () => { + const id = 'settle-held-existing' + const first = await startHeldReply(id, 'hold-existing') + await first.release() + const second = await startHeldReply(id, 'hold-existing-2', { snoozeUntil: Date.now() + 86_400_000, pinned: true }) + const t = await thread(id) + assert.equal(t.snoozedUntil, undefined) + assert.equal(t.pinned, undefined) + await second.release() +}) diff --git a/chat/store.mjs b/chat/store.mjs index 8e8899a..44d7981 100644 --- a/chat/store.mjs +++ b/chat/store.mjs @@ -387,7 +387,14 @@ function applyMetadata(thread, body, now) { if (num(body.doneAt)) thread.doneAt = num(body.doneAt) else delete thread.doneAt } - if (!thread.snoozedUntil) delete thread.snoozedAt + // A snooze he set as he started the chat (`$snooze`): its own reply doesn't wake it + // early. Written only by the bridge (not in METADATA_KEYS); a snooze a client sets + // or clears afterwards is an ordinary one again. + if ('snoozeHeld' in body) { + if (body.snoozeHeld === true) thread.snoozeHeld = true + else delete thread.snoozeHeld + } else if ('snoozedUntil' in body) delete thread.snoozeHeld + if (!thread.snoozedUntil) { delete thread.snoozedAt; delete thread.snoozeHeld } else if (!thread.snoozedAt) thread.snoozedAt = now if (thread.kind === 'temporary') thread.expiresAt = num(body.expiresAt) || thread.expiresAt || now else delete thread.expiresAt @@ -409,6 +416,7 @@ export function wakeOnOwnerMessage(thread, now = Date.now()) { delete thread.settledAt delete thread.snoozedUntil delete thread.snoozedAt + delete thread.snoozeHeld delete thread.doneAt } diff --git a/chat/task-folders-bridge.test.mjs b/chat/task-folders-bridge.test.mjs index 3b825ad..835afe0 100644 --- a/chat/task-folders-bridge.test.mjs +++ b/chat/task-folders-bridge.test.mjs @@ -1,8 +1,8 @@ // Run with: node --test chat/task-folders-bridge.test.mjs // // The Tasks panel's filing routes against a real bridge.mjs: a task is filed only -// under a project that exists, bad ids are refused, and deleting a folder hands -// its tasks up to its project (deleting a project unfiles them), as its chats move. +// under a project that exists, bad ids are refused, and archiving a project puts +// it away whole (its folders, chats and filings) until Settings → Archive restores it. // The bridge runs from a shadow checkout on its own port, with no scheduler. import test, { before, after } from 'node:test' @@ -84,15 +84,45 @@ test('filing needs a real project and a valid task id; null unfiles', async () = assert.equal((await call('POST', '/api/chat/task-folders', {})).status, 405) }) -test('a deleted folder hands its tasks to its project; a deleted project unfiles them', async () => { +test('an archived project is put away with its folders and chats, and comes back whole', async () => { const project = (await call('POST', '/api/chat/projects', { name: 'Client' })).body.project const folder = (await call('POST', '/api/chat/projects', { name: 'Network', parentId: project.id })).body.project await call('PUT', '/api/chat/task-folders/a', { projectId: folder.id }) - await call('PUT', '/api/chat/task-folders/b', { projectId: project.id }) - assert.equal((await call('DELETE', `/api/chat/projects/${folder.id}`)).status, 200) - assert.deepEqual((await call('GET', '/api/chat/task-folders')).body.folders, { a: project.id, b: project.id }) - assert.equal((await call('DELETE', `/api/chat/projects/${project.id}`)).status, 200) - assert.deepEqual((await call('GET', '/api/chat/task-folders')).body.folders, {}) + await call('PUT', '/api/threads/thread-in-folder', { projectId: folder.id, title: 'Cutover', messages: [{ id: 'm1', role: 'user', content: 'hi', createdAt: Date.now() }] }) + const names = async () => (await call('GET', '/api/chat/projects')).body.projects.map((p) => p.name) + const chats = async () => (await call('GET', '/api/threads?view=summary')).body.threads.map((t) => t.id) + + // Nothing deletes a project any more. + assert.equal((await call('DELETE', `/api/chat/projects/${project.id}`)).status, 405) + assert.equal((await call('POST', `/api/chat/projects/${project.id}/restore`)).status, 409) + + const archived = await call('POST', `/api/chat/projects/${project.id}/archive`) + assert.equal(archived.status, 200) + assert.ok(archived.body.project.archivedAt) + assert.equal((await call('POST', `/api/chat/projects/${folder.id}/archive`)).status, 409, 'its folder went with it') + assert.ok(!(await names()).includes('Client')) + assert.ok(!(await names()).includes('Network')) + assert.ok(!(await chats()).includes('thread-in-folder'), 'its chats are put away too') + assert.equal((await call('GET', '/api/threads/thread-in-folder')).status, 200, 'but still open by id') + assert.equal((await call('GET', `/api/chat/projects/${folder.id}`)).status, 404) + assert.equal((await call('PATCH', `/api/chat/projects/${project.id}`, { name: 'x' })).status, 404) + assert.equal((await call('PUT', '/api/chat/task-folders/c', { projectId: folder.id })).status, 404, 'nothing is filed into it') + assert.equal((await call('POST', '/api/chat/projects', { name: 'Sub', parentId: project.id })).status, 404) + assert.deepEqual((await call('GET', '/api/chat/task-folders')).body.folders.a, undefined) + + const list = (await call('GET', '/api/chat/projects/archived')).body.projects + const entry = list.find((p) => p.id === project.id) + assert.equal(entry.chatCount, 1) + assert.deepEqual(entry.folders.map((f) => f.name), ['Network']) + assert.ok(!list.some((p) => p.id === folder.id), 'a folder is listed under its archived project, not beside it') + + const restored = await call('POST', `/api/chat/projects/${project.id}/restore`) + assert.equal(restored.status, 200) + assert.equal(restored.body.project.archivedAt, undefined) + assert.ok((await names()).includes('Network')) + assert.ok((await chats()).includes('thread-in-folder')) + assert.equal((await call('GET', '/api/chat/task-folders')).body.folders.a, folder.id, 'its filings come back') + assert.ok(!(await call('GET', '/api/chat/projects/archived')).body.projects.some((p) => p.id === project.id)) }) test('a chat keeps a taskId written to it', async () => { diff --git a/chat/thread-tools.mjs b/chat/thread-tools.mjs index d2839c5..a5dd44e 100644 --- a/chat/thread-tools.mjs +++ b/chat/thread-tools.mjs @@ -24,7 +24,7 @@ const iso = (ms) => (ms ? new Date(ms).toISOString() : null) export function threadTitle(t) { if (t.title) return t.title const first = clip(t.messages?.find((m) => m.role === 'user')?.content, 49) - return first || (t.kind === 'temporary' ? 'Temporary chat' : 'New chat') + return first || (t.kind === 'temporary' ? 'Ghost chat' : 'New chat') } /** "Work", or "Work / Hiring" for a folder; null for Home. */ diff --git a/docs/chat.md b/docs/chat.md index 7d20dc0..edc0dc6 100644 --- a/docs/chat.md +++ b/docs/chat.md @@ -1590,9 +1590,21 @@ chat's conclusions reach the next. folder chat's parent memory (`readOnlyPaths`). Without it the memory write is refused and Haiku still tells the owner it saved the note. - **Removing a file** drops it from the project; the bytes go only when no chat message - still shows it. **Deleting a project** deletes its files, instructions and memory (and - its folders') and moves its chats to Home. Thread deletion and the orphan sweep leave - project files alone. + still shows it. Thread deletion and the orphan sweep leave project files alone, an + archived project's included. +- **Archiving, never deleting.** Nothing deletes a project or folder. The card's Settings → + Archive (`POST /api/chat/projects//archive`) sets `archivedAt` and puts it away whole: + its files, instructions, memory and chats stay as they are, and a project's folders go with + it. The store's `list()` leaves archived ones out (`listAll()` has them; `active(id)` is the + check every route that files or opens something into a project uses), so the chats panel, + pickers, `$`, agents' tools and task folders pass over it, and `GET /api/threads` leaves out + the chats inside it (each still opens by its id, from search). Its tasks stay filed there + and read as Personal until it is back. Settings → Archive (`GET /api/chat/projects/archived`, + `web/src/components/settings/ArchivePane.tsx`, the app's `panes/ArchivePane.tsx`) lists each + archived project with its folders, and each folder archived on its own under its project's + name; Restore (`/restore`) puts it back where it was. A folder archived on its own inside an + archived project stays archived when the project is restored, and cannot be restored before + it (409). - **A picture instead of an icon.** The card's Settings → Icon also takes an uploaded image or a website's own icon (`image`, an upload id; the bridge adds a signed `imageUrl`). "Use site icon" has the bridge read the page's ``/apple-touch-icon tags, then @@ -1620,7 +1632,7 @@ never leaks into the project. The owner moves what should be shared up by hand: `memoryEntries` in `chat/projects.mjs`, twinned in `web/src/chat/memoryEntries.ts`). Picked entries land under the same heading in the parent and leave the folder. - **Files:** pick files under the folder card's Files row → "Move up" (to the project). -- **Deleting a folder** moves its chats up to its project. +- **Archiving a folder** puts it away with its chats until Settings → Archive restores it. A chat moves between Home, projects and folders with its menu's "Move to…" (T3 Code's project selector); each card names where it lives. @@ -1656,6 +1668,13 @@ so its settle has no Undo toast; Un-settle in the sheet puts a chat back. - **Settle** (✓ on hover, the chat menu, or the leader shortcut `c s`) shelves a chat until the owner writes in it. Settling unpins it, ends its snooze, and clears "waiting on you". A toast offers Undo. A running chat can't be settled. +- **A ghost chat never sits on the Settled shelf** (a `temporary` chat: Home only, gone at + midnight). Settled any way (by hand, or done from the agent or its task and read), it is + listed nowhere (`ghostGone` in `settle.ts`, used by `shelve` and `sidebarLists`, so the app's + drawer and sheet too). Settled by hand on the web, it leaves the screen if it was open and + is deleted once its "Ghost chat … is gone" toast has passed without Undo (`settleGhost` in + `chat/store.ts`); a tab closed before then, or a settle in the app, leaves it hidden until + the bridge drops it at midnight, as every ghost chat is (`expiresAt`, `chat/store.mjs`). - **Auto-settle**: a chat with no activity for `autoSettleDays` (Settings → Chat, default 3, 0 = never) is shown as settled at its last activity. This is worked out on read and never written, so changing the setting re-sorts every list. Pinned chats, running @@ -1828,8 +1847,8 @@ are added, edited and sorted. side, `data/task-folders.json` (`chat/task-folders.mjs`, `TASK_FOLDERS_FILE`; `PUT /api/chat/task-folders/` with `{ projectId }`, where `null` stores `none`, Personal on purpose), and every row arrives from `GET /api/todos/sheet` already filed: its - own filing, else the sheet's default folder (`docs/task-sheet.md`). Deleting a folder moves - its tasks up to its project, deleting a project makes them Personal, as with its chats. + own filing, else the sheet's default folder (`docs/task-sheet.md`). Tasks and rows filed in + an archived folder keep their filing and read as Personal until it is restored. - **The task card** (`web/src/work/TaskCard.tsx`, `card.ts`), T3 Code's thread card for a task: the check circle and title, then one row per setting with a dropdown (Folder, Due, Priority, Repeat, Snooze), the description, the chats working on it with New chat, Open @@ -1906,7 +1925,7 @@ The draft moves to the new place, words and files, and opens there (the "Start i chips do the same, `moveDraft` in `web/src/chat/drafts.ts`); one already waiting there stays a row of its own (Drafts, below). While a file is still uploading or has failed, the places say so and a pick waits. The menu is only -offered before the first send (an open chat moves with Move to…), never in a temporary chat, +offered before the first send (an open chat moves with Move to…), never in a ghost chat, and reads tasks only while it is open. The composer's + menu has "Put it in a folder or task", which types the `$`. ⌘/Ctrl+Shift+O (Settings → Keyboard › Hotkeys) starts a blank chat at Home from any page, ready for this (`docs/shortcuts.md` → Hotkeys). @@ -1932,7 +1951,50 @@ words became the task, so the chat's box starts empty with the task strip above the bridge refuses leaves the words in the box. Leaving for another draft or chat while it is being added still adds it, says so, and stays where he went. Files still uploading hold it, as they hold a pick. It is offered wherever the `$` places are (a chat not started yet, -not temporary); the iPhone app has no `$` menu. +not a ghost chat); the iPhone app has no `$` menu. + +#### More `$` actions: `$ghost`, a new folder, `$opus`, `$pin` and `$snooze` + +The `$` menu's **Quick actions** are New task, **Ghost chat** and **Pin it**; a bare `$` +lists the first two between the places and the tasks. + +- **`$ghost`** (from `$gh`; also `$temp…` and `$inco…` from four letters) makes the chat a + ghost chat: not kept, gone at midnight, and gone at once when settled (Settled and + snoozed). The words and files move to the ghost chat's draft at Home, out of any project + or task it was being started in (ghost chats live outside projects), as the header's ghost + switch does for a chat at Home (`placeDraft(…, ghost)` in `useChatDrafts.ts`). A ghost + chat's composer offers no `/` or `$` menu; the header's switch turns it back. +- **A name nothing has yet** (`$tax-returns`, three letters on) ends the menu with + **New project “Tax returns”**, and, in a project or one of its folders, first **New + folder “Tax returns”** in that project (one level of folders). The name is the term as + typed with hyphens as spaces and a capital if none was typed (`nameFromTerm`). It is + offered only when no place matches and no project's name starts with the term + (`$harb` is on its way to harbor), never for a price or a word `$` keeps (task, ghost, + home, folder, project, …), and after any task the term matches, so Enter still picks the + task. Picking it makes the folder (`createProject`, not opened), then moves the draft there + as picking a place does, keeping a task it was being started for; a refusal leaves the + words in the box, and leaving for another draft meanwhile still makes it and says so. +- **`$opus`, `$sonnet`, `$codex`, `$gpt-5`…** (two letters on) lists, under **Start on a + model**, up to five models whose name or id the term starts or starts a word of, on every + account (each account's catalogue is loaded as the model picker loads it, `ensureModels`), + and an account whose name or driver it names, as " default". The account's own + row leads, then favourites; hidden models never show (`rankModels`). Picking one sets the + new chat's model as the picker would (`settingsForPick`, the draft's pick in `ChatView`), + takes the `$…` out and leaves the words where they are; the model chip shows it. A + matched model also counts as a name taken, so no "New project “Opus”". +- **`$pin`** (from `$pi`) pins the chat from its first message; **`$snooze`** (from `$sn`; + also `$later`, `$remind` from three letters) lists the snooze times (`snoozePresets`: + in an hour, three hours, this evening, tomorrow, next week) under **Send it, back later**, + and `$snooze-tom` narrows to one. Either shows as a chip above the box (× takes it back) + and goes with the first message (`pinned`, `snoozeUntil` on `POST /api/chat`, read only + for a chat the bridge hasn't seen, a snooze at most a year off). A snoozed one is sent + and answered out of sight: the composer moves on to a fresh new chat with a "Back …" + toast (Open now wakes it), the chat waits in Snoozed, and its replies don't wake it + early or push (`snoozeHeld`, set by the bridge only; `startChatTurn` and the run's final + save in `bridge.mjs`, both stores' `done`). It comes back at its time marked Woke, as any + snooze does. A snooze or wake set afterwards is an ordinary one again (`applyMetadata` + drops `snoozeHeld`), and his next message clears it. None of these move the draft, so a + file still uploading doesn't hold them. Nothing loads tasks until a chat card with a task, a task strip or the `$` menu is on screen; while one is, the store (`web/src/work/state.ts`) reads the board, the sheet feed (its own two-minute cache) diff --git a/docs/tasks.md b/docs/tasks.md index 682dbcf..efc2833 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -105,8 +105,10 @@ Tasks used to be Personal or Ventures with a venture tag. Migration 013 adds `fo named like its venture tag (`folderAdoption` in `todos/folders.mjs`); everything else is Personal. `area` and `venture_tag` stay in the database and the API for older clients and exports, and nothing draws them. The bridge refuses a `folderId` that is not an existing -chat project (`UNKNOWN_FOLDER`); a task whose project is deleted later moves to that -folder's project, or becomes Personal (`refileFolder`). Agents read and set the folder by +chat project in use (`UNKNOWN_FOLDER`; an archived one counts as gone). A task filed in a +project or folder that is archived later keeps its `folderId` and reads as Personal until +Settings → Archive restores it (projects are never deleted; `refileFolder` is left for a +caller that needs it). Agents read and set the folder by name (`totem_get_tasks`, `totem_create_task`, `totem_update_task`; `totem_get_projects` lists the folders), and a task an agent creates from a chat in a project lands in that project and is linked to the chat (`docs/chat.md` → Linked tasks). diff --git a/mobile/src/features/chat/ChatScreen.tsx b/mobile/src/features/chat/ChatScreen.tsx index 531fde0..8051104 100644 --- a/mobile/src/features/chat/ChatScreen.tsx +++ b/mobile/src/features/chat/ChatScreen.tsx @@ -532,8 +532,8 @@ export default function ChatScreen() { ) : ( - {temporary ? 'Temporary chat' : greeting(ownerName)} - {temporary ? This chat won’t be kept after midnight. : null} + {temporary ? 'Ghost chat' : greeting(ownerName)} + {temporary ? Not kept: gone at midnight, or as soon as you settle it. : null} {providerState && providerState !== 'ready' && providerState !== 'unknown' ? ( {providerById(choice.provider)?.name} is {providerState === 'missing' ? 'not installed on this machine' : providerState === 'logged-out' ? 'signed out' : 'not responding'}. Pick another account below{caps?.providers?.[choice.provider]?.fix ? `, or run ${caps.providers[choice.provider].fix}` : ''}. @@ -559,7 +559,7 @@ export default function ChatScreen() { ) - const titleText = active && !empty ? threadTitle(active) : temporary ? 'Temporary chat' : 'New chat' + const titleText = active && !empty ? threadTitle(active) : temporary ? 'Ghost chat' : 'New chat' const titleMenu = active && !empty ? threadMenu(active, shelfOf(active, Date.now(), autoSettleDays, busy, active.id !== openedSettled, !!attentionOf(active, handoffs[active.id])), busy) : null const titleEl = ( @@ -642,7 +642,7 @@ export default function ChatScreen() { newChat(temporary ? 'regular' : 'temporary')} - accessibilityLabel={temporary ? 'Turn off temporary chat' : 'Temporary chat — not kept past midnight'} + accessibilityLabel={temporary ? 'Turn off ghost chat' : 'Ghost chat — not kept past midnight'} accessibilityState={{ selected: temporary }} > @@ -708,7 +708,7 @@ export default function ChatScreen() { above={missingEl || queueEl ? <>{missingEl}{queueEl} : null} onVoice={() => openVoice({ threadId: activeId, kind })} busy={busy} - placeholder={waitingApproval ? DECLINE_PLACEHOLDER : temporary ? 'Temporary chat — gone at midnight' : project && empty ? `New chat in ${project.name}` : 'Ask Totem anything'} + placeholder={waitingApproval ? DECLINE_PLACEHOLDER : temporary ? 'Ghost chat — gone at midnight' : project && empty ? `New chat in ${project.name}` : 'Ask Totem anything'} allowCommands={!temporary} maxUploadBytes={caps?.maxUploadBytes} compacting={compactTokens != null && !keepHistory} diff --git a/mobile/src/features/chat/ModelPicker.tsx b/mobile/src/features/chat/ModelPicker.tsx index 7d78a81..b279054 100644 --- a/mobile/src/features/chat/ModelPicker.tsx +++ b/mobile/src/features/chat/ModelPicker.tsx @@ -277,7 +277,7 @@ export default function ModelPickerSheet() { {lockedTo ? ( - {`A temporary chat stays on ${providerById(lockedTo)?.name || lockedTo}. Start a regular chat to use another account.`} + {`A ghost chat stays on ${providerById(lockedTo)?.name || lockedTo}. Start a regular chat to use another account.`} ) : req.started && provider !== req.provider ? ( diff --git a/mobile/src/features/settings/paneRoutes.test.mjs b/mobile/src/features/settings/paneRoutes.test.mjs index 79efae9..488807c 100644 --- a/mobile/src/features/settings/paneRoutes.test.mjs +++ b/mobile/src/features/settings/paneRoutes.test.mjs @@ -66,6 +66,7 @@ test('every search hit the app keeps is a row its own pane draws', () => { skills: ['panes/SkillsPane.tsx'], connections: ['panes/ConnectionsPane.tsx'], tasks: ['panes/TasksPane.tsx'], + archive: ['panes/ArchivePane.tsx'], security: ['panes/SecurityPane.tsx'], logs: ['panes/ActivityPane.tsx'], } diff --git a/mobile/src/features/settings/panes.ts b/mobile/src/features/settings/panes.ts index 27891b7..0dedc33 100644 --- a/mobile/src/features/settings/panes.ts +++ b/mobile/src/features/settings/panes.ts @@ -15,6 +15,7 @@ import IconChartBar from '@tabler/icons-react-native/dist/esm/icons/IconChartBar import IconSparkles from '@tabler/icons-react-native/dist/esm/icons/IconSparkles.mjs' import IconPlugConnected from '@tabler/icons-react-native/dist/esm/icons/IconPlugConnected.mjs' import IconCircleCheck from '@tabler/icons-react-native/dist/esm/icons/IconCircleCheck.mjs' +import IconArchive from '@tabler/icons-react-native/dist/esm/icons/IconArchive.mjs' import IconShieldLock from '@tabler/icons-react-native/dist/esm/icons/IconShieldLock.mjs' import IconActivity from '@tabler/icons-react-native/dist/esm/icons/IconActivity.mjs' import type { IconType } from '../../lib/icons' @@ -31,6 +32,7 @@ import UsagePane from './panes/UsagePane' import SkillsPane from './panes/SkillsPane' import ConnectionsPane from './panes/ConnectionsPane' import TasksPane from './panes/TasksPane' +import ArchivePane from './panes/ArchivePane' import SecurityPane from './panes/SecurityPane' import ActivityPane from './panes/ActivityPane' @@ -57,6 +59,7 @@ const PANE: Record & { label?: string }> = { skills: { icon: IconSparkles, component: SkillsPane }, connections: { icon: IconPlugConnected, component: ConnectionsPane }, tasks: { icon: IconCircleCheck, component: TasksPane }, + archive: { icon: IconArchive, component: ArchivePane }, security: { icon: IconShieldLock, component: SecurityPane }, logs: { icon: IconActivity, component: ActivityPane }, } diff --git a/mobile/src/features/settings/panes/ArchivePane.tsx b/mobile/src/features/settings/panes/ArchivePane.tsx new file mode 100644 index 0000000..be55d4c --- /dev/null +++ b/mobile/src/features/settings/panes/ArchivePane.tsx @@ -0,0 +1,78 @@ +// Settings → Archive (web components/settings/ArchivePane.tsx): what was put away, +// and the way back. Only chat projects and folders for now (chat/projects.mjs +// `archivedAt`); nothing in Totem deletes one. An archived project carries its +// folders; a folder archived on its own is listed by itself, under its project's name. +import React, { useCallback, useEffect, useState } from 'react' +import { ApiError, AuthError } from '../../../lib/api' +import { listArchivedProjects } from '../../../lib/chat/api' +import { restoreProject } from '../../../lib/chat/store' +import type { ArchivedProject } from '../../../lib/chat/types' +import { pushError, pushSuccess } from '../../../lib/toast' +import { Btn } from '../../../ui/kit' +import { success, tap } from '../../../ui/haptics' +import { ProjectIcon } from '../../chat/ThreadIcon' +import { Loading, Row, Section } from '../ui' + +const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}` + +function day(ts: number) { + const d = new Date(ts) + return d.toLocaleDateString([], { month: 'short', day: 'numeric', ...(d.getFullYear() !== new Date().getFullYear() ? { year: 'numeric' } : {}) }) +} + +function archiveLine(p: ArchivedProject): string { + const parts = [p.parentId ? `Folder in ${p.parentName || 'a project'}` : 'Project'] + if (p.folders.length) parts.push(`${plural(p.folders.length, 'folder')} (${p.folders.map((f) => f.name).join(', ')})`) + parts.push(plural(p.chatCount, 'chat')) + if (p.fileCount) parts.push(plural(p.fileCount, 'file')) + parts.push(`archived ${day(p.archivedAt)}`) + return parts.join(' · ') +} + +export default function ArchivePane() { + const [items, setItems] = useState(null) + const [error, setError] = useState('') + const [busy, setBusy] = useState(null) + const load = useCallback(() => { + listArchivedProjects() + .then((r) => { setItems(r.projects); setError('') }) + .catch((e) => { if (!(e instanceof AuthError)) setError(e instanceof ApiError ? e.message : String(e)) }) + }, []) + useEffect(() => { load() }, [load]) + + async function restore(p: ArchivedProject) { + tap() + setBusy(p.id) + try { + await restoreProject(p.id) + setItems((list) => (list || []).filter((x) => x.id !== p.id)) + success() + pushSuccess(`Restored ${p.name}`) + } catch (e: any) { + if (!(e instanceof AuthError)) pushError(`Couldn't restore it: ${e.message}`) + } finally { + setBusy(null) + load() + } + } + + return ( +
+ {!items ? : !items.length ? ( + + ) : items.map((p) => ( + } + title={p.name} + description={archiveLine(p)} + control={ void restore(p)} />} + /> + ))} +
+ ) +} diff --git a/mobile/src/lib/chat/api.ts b/mobile/src/lib/chat/api.ts index d89736e..0a61dc7 100644 --- a/mobile/src/lib/chat/api.ts +++ b/mobile/src/lib/chat/api.ts @@ -3,7 +3,7 @@ import { authHeaders, AuthError, api, getJSON, peekJSON } from '../api' import { bridgeFetch, bridgeUrl } from '../connection' import { PROJECTS_GET, PROJECTS_PATH } from './projectList' -import type { ApprovalDecision, Attachment, ChatCapabilities, ChatMode, ModelSettings, Project, QueuedMessage, StreamEvent } from './types' +import type { ApprovalDecision, ArchivedProject, Attachment, ChatCapabilities, ChatMode, ModelSettings, Project, QueuedMessage, StreamEvent } from './types' export interface SendArgs { threadId: string @@ -178,7 +178,9 @@ export const peekProjects = () => peekJSON<{ projects: Project[] }>(PROJECTS_PAT export const getProject = (id: string) => api<{ project: Project }>(`/api/chat/projects/${encodeURIComponent(id)}`) export const createProjectApi = (body: Partial) => api<{ project: Project }>('/api/chat/projects', json('POST', body)) export const patchProjectApi = (id: string, body: Record) => api<{ project: Project }>(`/api/chat/projects/${encodeURIComponent(id)}`, json('PATCH', body)) -export const deleteProjectApi = (id: string) => api<{ ok: boolean; movedChats: number; removedFolders?: number }>(`/api/chat/projects/${encodeURIComponent(id)}`, json('DELETE')) +export const archiveProjectApi = (id: string) => api<{ project: Project }>(`/api/chat/projects/${encodeURIComponent(id)}/archive`, json('POST')) +export const restoreProjectApi = (id: string) => api<{ project: Project }>(`/api/chat/projects/${encodeURIComponent(id)}/restore`, json('POST')) +export const listArchivedProjects = () => api<{ projects: ArchivedProject[] }>('/api/chat/projects/archived') export const putProjectMemory = (id: string, memory: string) => api<{ memory: string }>(`/api/chat/projects/${encodeURIComponent(id)}/memory`, json('PUT', { memory })) export const addProjectFilesApi = (id: string, uploadIds: string[]) => api<{ project: Project }>(`/api/chat/projects/${encodeURIComponent(id)}/files`, json('POST', { uploadIds })) export const moveProjectMemoryApi = (id: string, entries: string[]) => api<{ moved: number; project: Project }>(`/api/chat/projects/${encodeURIComponent(id)}/memory/move`, json('POST', { entries })) diff --git a/mobile/src/lib/chat/draftsShared.ts b/mobile/src/lib/chat/draftsShared.ts index b8dfadf..d444241 100644 --- a/mobile/src/lib/chat/draftsShared.ts +++ b/mobile/src/lib/chat/draftsShared.ts @@ -181,7 +181,7 @@ export function draftRows(s: DraftState, { projects, projectId, shown, listedOnA return { key: d.key, preview: draftPreview(d), - place: project?.name || (d.temporary ? 'Temporary chat' : 'Home'), + place: project?.name || (d.temporary ? 'Ghost chat' : 'Home'), icon: d.place.kind === 'task' ? 'task' : project ? 'project' : d.temporary ? 'temporary' : 'home', ...(project ? { project } : {}), active: d.key === shown, diff --git a/mobile/src/lib/chat/settle.ts b/mobile/src/lib/chat/settle.ts index e69e451..3b4237c 100644 --- a/mobile/src/lib/chat/settle.ts +++ b/mobile/src/lib/chat/settle.ts @@ -13,6 +13,10 @@ // it is opened (opening clears the fields). A reply that finishes while the chat // is snoozed wakes it early (the bridge sets `snoozedUntil` to that moment). // +// A ghost chat (kind 'temporary': not kept, gone at midnight) never sits on the +// Settled shelf: settled, it is off every list (`ghostGone`), and Settle by hand +// deletes it once its Undo has passed (settleThread in store.ts). +// // The bridge stores the fields (chat/store.mjs) and clears them whenever he // writes in the chat (wakeOnOwnerMessage there, ownerMessageChange here); // everything else about them lives in this file. @@ -88,6 +92,9 @@ export const offersSettle = (t: ChatThread, shelf: Shelf, live = false) => */ export const keptOpenId = (activeId: string | null, openedSettled: string | null) => (activeId && activeId !== openedSettled ? activeId : null) +/** A ghost chat that has settled: listed nowhere, and deleted at midnight if not before. */ +export const ghostGone = (t: ChatThread, settled: number) => t.kind === 'temporary' && settled > 0 + /** Snoozed wins over settled, as in T3. `waiting` as for settledAt. */ export function shelfOf(t: ChatThread, now: number, autoDays: number, live = false, open = false, waiting = false): Shelf { if (isSnoozed(t, now)) return 'snoozed' @@ -102,6 +109,7 @@ export function shelve(threads: ChatThread[], now: number, autoDays: number, liv for (const t of threads) { if (isSnoozed(t, now)) { snoozed.push(t); continue } const at = settledAt(t, now, autoDays, live(t.id), t.id === openId, waiting(t)) + if (ghostGone(t, at)) continue if (at) settled.push({ t, at }) else active.push(t) } diff --git a/mobile/src/lib/chat/sidebar.ts b/mobile/src/lib/chat/sidebar.ts index 7d5392d..433bb2e 100644 --- a/mobile/src/lib/chat/sidebar.ts +++ b/mobile/src/lib/chat/sidebar.ts @@ -14,7 +14,7 @@ // (one project and its folders, or Home) narrows the list when he asks for it. // Totems' own chats are not listed; they live with their totems. import type { ChatThread, Project } from './types' -import { activeAt, isSnoozed, settledAt } from './settle' +import { activeAt, ghostGone, isSnoozed, settledAt } from './settle' /** What the list shows: every chat, the ones in no project, or one project and its folders. */ export type SidebarScope = 'all' | 'home' | string @@ -66,6 +66,7 @@ export function sidebarLists(threads: ChatThread[], o: SidebarOptions): SidebarL // Waiting on him stays in play, whatever would settle it on its own (age, a finished // task, the agent's "done"); only his own Settle shelves it (settle.ts settledAt). const at = settledAt(t, now, autoDays, live(t.id), t.id === openId, needsYou(t)) + if (ghostGone(t, at)) continue if (at) { settledOrder.set(t.id, at); out.settled.push(t); continue } if (t.pinned) out.pinned.push(t) else if (live(t.id) && !needsYou(t)) out.working.push(t) diff --git a/mobile/src/lib/chat/store.ts b/mobile/src/lib/chat/store.ts index 0bf7ff0..bec7d34 100644 --- a/mobile/src/lib/chat/store.ts +++ b/mobile/src/lib/chat/store.ts @@ -15,7 +15,7 @@ import { oneAtATime } from '../oneAtATime' import { applyEvent } from './reduce' import { sendChat, attachRun, stopChat, steerChat, decideApproval, changeQueue, getRuns, getCapabilities, probeCapabilities, listProjects, peekProjects, getProject, createProjectApi, patchProjectApi, - deleteProjectApi, putProjectMemory, addProjectFilesApi, removeProjectFilesApi, moveProjectMemoryApi, moveProjectFilesApi, type SendArgs, type StreamHandle, + archiveProjectApi, restoreProjectApi, putProjectMemory, addProjectFilesApi, removeProjectFilesApi, moveProjectMemoryApi, moveProjectFilesApi, type SendArgs, type StreamHandle, } from './api' import type { QueueAction } from './api' import { defaultSettingsFor, fromPreset, normalizeModelSettings, parseModelSpec, visibleModels, wireModel } from './models' @@ -601,39 +601,34 @@ export async function removeProjectFiles(id: string, ids: string[]) { } } -/** Delete a project (and its folders) or a folder. Chats move to Home, or a folder's up to its project; returns how many did. */ -export async function deleteProject(id: string) { +/** + * Put a project (with its folders) or a folder away (the web's archiveProject). + * Nothing is deleted: Settings → Archive brings it back with its chats. + */ +export async function archiveProject(id: string) { const parentId = projectById(id)?.parentId - const { movedChats } = await deleteProjectApi(id) + await archiveProjectApi(id) projectSync.changed() - if (parentId) { - set((s) => { - const detail = { ...s.projectDetail } - delete detail[id] - return { - projects: s.projects.filter((p) => p.id !== id), - projectDetail: detail, - projectId: s.projectId === id ? parentId : s.projectId, - threads: s.threads.map((t) => (t.projectId === id ? { ...t, projectId: parentId } : t)), - } - }) - loadProject(parentId) - loadProjects() - return movedChats - } - const gone = new Set([id, ...foldersOf(state.projects, id).map((f) => f.id)]) + const gone = new Set([id, ...(parentId ? [] : foldersOf(state.projects, id).map((f) => f.id))]) set((s) => { const detail = { ...s.projectDetail } for (const g of gone) delete detail[g] return { projects: s.projects.filter((p) => !gone.has(p.id)), projectDetail: detail, - projectId: s.projectId && gone.has(s.projectId) ? null : s.projectId, - threads: s.threads.map((t) => (t.projectId && gone.has(t.projectId) ? { ...t, projectId: undefined } : t)), + projectId: s.projectId && gone.has(s.projectId) ? (parentId || null) : s.projectId, + threads: s.threads.filter((t) => !t.projectId || !gone.has(t.projectId) || t.id === s.activeId || !!s.runs[t.id]), } }) loadProjects() - return movedChats + return gone.size +} + +/** Bring an archived project or folder back, with its chats. */ +export async function restoreProject(id: string) { + await restoreProjectApi(id) + projectSync.changed() + await Promise.all([loadProjects(), syncThreads()]) } /** Move a folder's memory entries (by text) up into its project. */ @@ -1172,7 +1167,7 @@ function handleEvent(threadId: string, e: StreamEvent) { patchAssistant(threadId, (m) => ({ ...e.message, parts: e.message.parts?.length ? e.message.parts : m.parts })) // The bridge marks it waiting on him too; this shows it without a sync. // Not after a compaction (`/compact`, context.ts): housekeeping is nothing to read. - if (e.message.status !== 'stopped') patchThread(threadId, (t) => (t.totemId || isCompactionTurn(t.messages[t.messages.findIndex((m) => m.id === e.message.id) - 1]) ? t : { ...t, needsReply: true, ...(t.snoozedUntil && t.snoozedUntil > now() ? { snoozedUntil: now() } : {}) })) + if (e.message.status !== 'stopped') patchThread(threadId, (t) => (t.totemId || isCompactionTurn(t.messages[t.messages.findIndex((m) => m.id === e.message.id) - 1]) ? t : { ...t, needsReply: true, ...(t.snoozedUntil && t.snoozedUntil > now() && !t.snoozeHeld ? { snoozedUntil: now() } : {}) })) break case 'error': patchAssistant(threadId, (m) => ({ ...m, status: 'error', error: e.text })) @@ -1551,7 +1546,7 @@ export function threadTitle(t: ChatThread | null | undefined): string { // A summary's preview holds only the last turn; the first message comes with it. const first = plainRefs(t.firstUserText || t.messages.find((m) => m.role === 'user')?.content || '').replace(/\s+/g, ' ').trim() if (first) return first.length > 48 ? `${first.slice(0, 48)}…` : first - return t.kind === 'temporary' ? 'Temporary chat' : 'New chat' + return t.kind === 'temporary' ? 'Ghost chat' : 'New chat' } /** Sidebar buckets, newest first, the way ChatGPT and T3 group history. */ diff --git a/mobile/src/lib/chat/storeDrafts.test.mjs b/mobile/src/lib/chat/storeDrafts.test.mjs index eb70a04..078b422 100644 --- a/mobile/src/lib/chat/storeDrafts.test.mjs +++ b/mobile/src/lib/chat/storeDrafts.test.mjs @@ -36,7 +36,7 @@ const SOURCES = { export const listProjects = async () => ({ projects: [] }) export const peekProjects = () => undefined export const stopChat = none, steerChat = none, decideApproval = none, changeQueue = none, getCapabilities = none, probeCapabilities = none, - getProject = none, createProjectApi = none, patchProjectApi = none, deleteProjectApi = none, putProjectMemory = none, + getProject = none, createProjectApi = none, patchProjectApi = none, archiveProjectApi = none, restoreProjectApi = none, putProjectMemory = none, addProjectFilesApi = none, removeProjectFilesApi = none, moveProjectMemoryApi = none, moveProjectFilesApi = none`, } const hooks = ` diff --git a/mobile/src/lib/chat/types.ts b/mobile/src/lib/chat/types.ts index fc2e4be..c81849c 100644 --- a/mobile/src/lib/chat/types.ts +++ b/mobile/src/lib/chat/types.ts @@ -321,6 +321,8 @@ export interface ChatThread { /** Hidden in Snoozed until then. A past time that's still set means it woke and hasn't been opened since. */ snoozedUntil?: number snoozedAt?: number + /** Snoozed as he started it (`$snooze`): its replies don't wake it early. Set by the bridge only. */ + snoozeHeld?: boolean /** The agent marked the request finished (mark_chat_done): Settle is offered, and it settles once read. Cleared by his next message. */ doneAt?: number /** @@ -380,6 +382,8 @@ export interface Project { modelSettings?: Partial /** A folder: the top-level project it sits in. */ parentId?: string + /** Put away (Settings → Archive); the lists never carry one. */ + archivedAt?: number fileCount: number chatCount: number createdAt: number @@ -389,6 +393,14 @@ export interface Project { memory?: string } +/** Settings → Archive: an archived project with its folders, or an archived folder on its own. */ +export interface ArchivedProject extends Project { + archivedAt: number + /** A folder's project, by name. */ + parentName?: string | null + folders: { id: string; name: string; icon?: string; archivedAt?: number; chatCount: number }[] +} + export interface ProviderRow { id: string driver: string diff --git a/mobile/src/lib/components/settings/searchIndex.ts b/mobile/src/lib/components/settings/searchIndex.ts index 6eca831..1d7a806 100644 --- a/mobile/src/lib/components/settings/searchIndex.ts +++ b/mobile/src/lib/components/settings/searchIndex.ts @@ -90,6 +90,9 @@ const ENTRIES: Partial> = { ['task-sheet', 'Task sheet', 'Tasks', 'spreadsheet action items sheet google drive read-only assignees'], ['task-retention', 'Retention', 'Tasks', 'archive completed finished recycle bin purge empty delete days time'], ], + archive: [ + ['archived-folders', 'Archived folders', 'Archive', 'archive restore unarchive bring back folders projects deleted removed hidden'], + ], security: [ ['approval-code', 'Approval code', 'Security', 'approve send second factor'], ['change-login', 'Change password', 'Sign-in', 'passphrase credentials'], diff --git a/mobile/src/lib/components/settings/sections.ts b/mobile/src/lib/components/settings/sections.ts index fd047e6..9d520f0 100644 --- a/mobile/src/lib/components/settings/sections.ts +++ b/mobile/src/lib/components/settings/sections.ts @@ -4,7 +4,7 @@ export const SETTINGS_GROUPS = [ { heading: null, items: ['general', 'appearance', 'chat', 'voice', 'notifications', 'shortcuts'] }, { heading: 'AI', items: ['providers', 'usage', 'skills'] }, - { heading: 'Data', items: ['connections', 'tasks'] }, + { heading: 'Data', items: ['connections', 'tasks', 'archive'] }, { heading: 'Account', items: ['security', 'logs'] }, ] as const @@ -24,6 +24,7 @@ export const SETTINGS_LABELS: Record = { skills: 'Skills', connections: 'Connections', tasks: 'Tasks', + archive: 'Archive', security: 'Security', logs: 'Activity', } diff --git a/web/src/chat/ChatHeader.tsx b/web/src/chat/ChatHeader.tsx index 62ea23e..f2e234b 100644 --- a/web/src/chat/ChatHeader.tsx +++ b/web/src/chat/ChatHeader.tsx @@ -136,7 +136,7 @@ export default function ChatHeader(p: ChatHeaderProps) { rows.push(...p.panels) if (usage) rows.push({ id: 'usage', icon: IconChartBar, label: 'AI usage', detail: usage.text, tone: usage.tone as HeaderItem['tone'], title: usage.label, into: 'usage', open: p.onManageUsage || openUsageSettings }) if (p.onKeep) rows.push({ id: 'keep', icon: IconPinned, label: 'Keep this chat', title: 'Keep this chat after midnight', into: 'menu', open: p.onKeep }) - if (p.temporary) rows.push({ id: 'temporary', icon: IconGhost2, label: 'Temporary chat', detail: p.temporary.on ? 'On' : 'Off', tone: p.temporary.on ? 'on' : '', title: p.temporary.on ? 'Turn off temporary chat' : 'Temporary chat — not kept past midnight', into: 'menu', open: p.temporary.onToggle }) + if (p.temporary) rows.push({ id: 'temporary', icon: IconGhost2, label: 'Ghost chat', detail: p.temporary.on ? 'On' : 'Off', tone: p.temporary.on ? 'on' : '', title: p.temporary.on ? 'Turn off ghost chat' : 'Ghost chat — not kept past midnight', into: 'menu', open: p.temporary.onToggle }) return (
@@ -235,7 +235,7 @@ export default function ChatHeader(p: ChatHeaderProps) { className={`vc-icon-btn ${p.temporary.on ? 'on' : ''}`} onClick={p.temporary.onToggle} aria-pressed={p.temporary.on} - title={p.temporary.on ? 'Turn off temporary chat' : 'Temporary chat — not kept past midnight'} + title={p.temporary.on ? 'Turn off ghost chat' : 'Ghost chat — not kept past midnight'} data-fold-into="menu" > diff --git a/web/src/chat/Composer.tsx b/web/src/chat/Composer.tsx index 0a73f3b..f0e8b13 100644 --- a/web/src/chat/Composer.tsx +++ b/web/src/chat/Composer.tsx @@ -15,17 +15,17 @@ import { readNewTask, type NewTaskFields } from './newTask' import NewTaskBar from './NewTaskBar' import { folderNames } from '../todos/folders' import ProjectIcon from './ProjectIcon' -import { useChat } from './store' +import { ensureModels, useChat } from './store' import { getWork, subscribeWork } from '../work/state' import { dueLabel } from '../work/groups' import { micUnavailableReason, openMic, closeMic, recordUntilStopped } from './recorder' -import type { Attachment, DraftAttachment, Project } from './types' +import type { Attachment, DraftAttachment, ModelRow, Project, ProviderRow } from './types' import type { Answering } from './QuestionsPanel' -import { TI, useDismiss } from './ui' +import { TI, ProviderLogo, useDismiss } from './ui' import { IconArrowUp, IconPlayerStopFilled, IconPlus, IconPaperclip, IconPhoto, IconMicrophone, IconWaveSine, IconSparkles, IconX, IconCheck, IconLoader2, IconCornerUpRight, IconPuzzle, IconPlaylistAdd, IconPlayerPlayFilled, - IconHome, IconChecklist, IconTable, IconFolder, IconArrowsDiagonalMinimize2, IconArrowsDiagonal, IconSquarePlus, + IconHome, IconChecklist, IconTable, IconFolder, IconFolderPlus, IconGhost2, IconPinned, IconZzz, IconArrowsDiagonalMinimize2, IconArrowsDiagonal, IconSquarePlus, } from './icons' import { formatContextTokens } from './context' import type { ChatCommand } from '../studio' @@ -119,6 +119,12 @@ export interface ComposerProps { taskId: string | null onPick: (d: Destination, text: string, caret: number) => void onNewTask?: (fields: NewTaskFields) => Promise + /** `$opus`: start on this model (the composer's model chip shows it). */ + onModel?: (d: Extract) => void + /** `$pin`, `$snooze`: how the chat starts, sent with its first message. */ + onStartOption?: (d: Extract) => void + /** Pinned by `$pin` already. */ + pinned?: boolean /** The draft on screen: a task line is that draft's, so another draft is a message again. */ draftKey?: string } @@ -149,11 +155,21 @@ const noSubscribe = () => () => {} type MenuItem = { kind: 'dest'; d: Destination } | { kind: 'cmd'; c: ChatCommand } const itemKey = (it: MenuItem) => (it.kind === 'dest' ? it.d.key : it.c.cmd) -const itemGroup = (it: MenuItem) => (it.kind === 'dest' ? (it.d.kind === 'new-task' ? 'Make a task' : it.d.kind === 'task' ? 'Start it for a task' : 'Start it in') +const NO_PROVIDERS: ProviderRow[] = [] +const NO_CATALOGS: Record = {} +const QUICK = new Set(['new-task', 'ghost', 'pin']) +/** Picks that leave the draft where it is, so a file still uploading doesn't hold them. */ +const STAYS = new Set(['new-task', 'model', 'pin', 'snooze']) +const itemGroup = (it: MenuItem) => (it.kind === 'dest' ? (QUICK.has(it.d.kind) ? 'Quick actions' : it.d.kind === 'snooze' ? 'Send it, back later' : it.d.kind === 'model' ? 'Start on a model' : it.d.kind === 'new-folder' ? 'Make a folder' : it.d.kind === 'task' ? 'Start it for a task' : 'Start it in') : it.c.kind === 'agent' ? 'Your agent skills' : 'Totem skills') -function destDesc(d: Destination, sheetName: string, here?: Project) { +function destDesc(d: Destination, sheetName: string, here?: Project, forTask = false) { if (d.kind === 'new-task') return here ? `Type it here, filed in ${here.name}, then chat about it` : 'Type it here, then start a chat for it' + if (d.kind === 'ghost') return here || forTask ? 'Not kept: moves to Home, gone at midnight' : 'Not kept: gone at midnight, or as soon as you settle it' + if (d.kind === 'new-folder') return d.parent ? `New folder in ${d.parent.name}, then start the chat in it` : 'New project, then start the chat in it' + if (d.kind === 'model') return d.note ? `${d.provider.name} · ${d.note}` : d.provider.name + if (d.kind === 'pin') return 'Pinned to the top of your chats once it starts' + if (d.kind === 'snooze') return `Sends now; stays in Snoozed until ${d.when}, even once answered` if (d.kind === 'home') return 'Chats in no project' if (d.kind === 'project') return d.parent ? `Folder in ${d.parent.name}` : 'Project' const due = d.task.dueDate ? dueLabel(d.task.dueDate, new Date()) : null @@ -164,6 +180,11 @@ function destDesc(d: Destination, sheetName: string, here?: Project) { function DestIcon({ d }: { d: Destination }) { if (d.kind === 'home') return if (d.kind === 'new-task') return + if (d.kind === 'ghost') return + if (d.kind === 'new-folder') return + if (d.kind === 'model') return + if (d.kind === 'pin') return + if (d.kind === 'snooze') return if (d.kind === 'project') return d.project.icon || d.project.imageUrl ? : return } @@ -540,8 +561,17 @@ const Composer = forwardRef(function Composer(pro // `$` in a chat not started yet: where it goes and which task it is for, before the `$` skills. const dollar = !!query && query.prefix === '$' && !!destinations const work = useSyncExternalStore(dollar ? subscribeWork : noSubscribe, getWork, getWork) + const providers = useChat((s) => s.providers) || NO_PROVIDERS + const catalogs = useChat((s) => s.models) || NO_CATALOGS + const wantModels = dollar && !!destinations?.onModel && query!.term.length >= 2 + // Every account's models, so `$opus` finds a model on any of them (the picker loads them the same way). + useEffect(() => { if (wantModels) for (const p of providers) ensureModels(p.id) }, [wantModels, providers]) + const accounts = useMemo(() => providers.map((provider) => ({ provider, models: catalogs[provider.id] || [] })), [providers, catalogs]) const places = dollar && destinations - ? rankDestinations({ projects, tasks: work.tasks, projectId: destinations.projectId, taskId: destinations.taskId }, query!.term) + ? rankDestinations({ + projects, tasks: work.tasks, projectId: destinations.projectId, taskId: destinations.taskId, + models: destinations.onModel ? accounts : [], startOptions: !!destinations.onStartOption, pinned: destinations.pinned, + }, query!.term, value.slice(query!.start + 1, query!.end)) .filter((d) => d.kind !== 'new-task' || canMakeTask) : [] const items: MenuItem[] = [...places.map((d): MenuItem => ({ kind: 'dest', d })), ...matches.map((c): MenuItem => ({ kind: 'cmd', c }))] @@ -569,10 +599,15 @@ const Composer = forwardRef(function Composer(pro function chooseItem(it: MenuItem) { if (it.kind === 'cmd') { chooseCommand(it.c); return } - if (!query || !destinations || placeHeld) return + if (!query || !destinations) return + // Only a move waits for uploads: a model, pin or snooze leaves the files where they are. + if (placeHeld && !STAYS.has(it.d.kind)) return const { value: next, caret: pos } = stripToken(value, query.start, query.end) setDismissed(null) if (it.d.kind === 'new-task') { placeCaret(next, pos); startTask(); return } + // These change how the chat starts, not where: the words stay in this draft. + if (it.d.kind === 'model') { placeCaret(next, pos); destinations.onModel?.(it.d); return } + if (it.d.kind === 'pin' || it.d.kind === 'snooze') { placeCaret(next, pos); destinations.onStartOption?.(it.d); return } destinations.onPick(it.d, next, pos) } @@ -715,14 +750,14 @@ const Composer = forwardRef(function Composer(pro return ( {group !== prev &&
{group}
} - + Archive {kind} +

Puts the {kind} away with its chats, files and memory{folderCount ? ', and its folders' : ''}. Bring it back from Settings → Archive. Tasks filed here show under Personal until then.

+
) diff --git a/web/src/chat/api.ts b/web/src/chat/api.ts index 84b8296..dd860df 100644 --- a/web/src/chat/api.ts +++ b/web/src/chat/api.ts @@ -1,7 +1,7 @@ // Chat's bridge calls. Streaming endpoints are read as Server-Sent Events over // fetch (EventSource cannot send the bearer header). import { authHeaders, AuthError, api } from '../api' -import type { ApprovalDecision, Attachment, ChatCapabilities, ModelSettings, Project, QueuedMessage, StreamEvent } from './types' +import type { ApprovalDecision, ArchivedProject, Attachment, ChatCapabilities, ModelSettings, Project, QueuedMessage, StreamEvent } from './types' export interface SendArgs { threadId: string @@ -23,6 +23,10 @@ export interface SendArgs { editMessageId?: string /** Compact the idle chat first; the message waits at the front of its queue (chat/context.mjs). */ compactFirst?: boolean + /** A new chat pinned from the start (`$pin`). */ + pinned?: boolean + /** A new chat snoozed until then from the start (`$snooze`); its reply doesn't wake it. */ + snoozeUntil?: number } export interface StreamHandle { @@ -157,7 +161,9 @@ export const getProject = (id: string) => api<{ project: Project }>(`/api/chat/p export const createProjectApi = (body: Partial) => api<{ project: Project }>('/api/chat/projects', json('POST', body)) export const patchProjectApi = (id: string, body: Record) => api<{ project: Project }>(`/api/chat/projects/${encodeURIComponent(id)}`, json('PATCH', body)) export const projectFaviconApi = (id: string, site: string) => api<{ project: Project }>(`/api/chat/projects/${encodeURIComponent(id)}/favicon`, json('POST', { site })) -export const deleteProjectApi = (id: string) => api<{ ok: boolean; movedChats: number; removedFolders?: number }>(`/api/chat/projects/${encodeURIComponent(id)}`, json('DELETE')) +export const archiveProjectApi = (id: string) => api<{ project: Project }>(`/api/chat/projects/${encodeURIComponent(id)}/archive`, json('POST')) +export const restoreProjectApi = (id: string) => api<{ project: Project }>(`/api/chat/projects/${encodeURIComponent(id)}/restore`, json('POST')) +export const listArchivedProjects = () => api<{ projects: ArchivedProject[] }>('/api/chat/projects/archived') export const putProjectMemory = (id: string, memory: string) => api<{ memory: string }>(`/api/chat/projects/${encodeURIComponent(id)}/memory`, json('PUT', { memory })) export const addProjectFilesApi = (id: string, uploadIds: string[]) => api<{ project: Project }>(`/api/chat/projects/${encodeURIComponent(id)}/files`, json('POST', { uploadIds })) export const moveProjectMemoryApi = (id: string, entries: string[]) => api<{ moved: number; project: Project }>(`/api/chat/projects/${encodeURIComponent(id)}/memory/move`, json('POST', { entries })) diff --git a/web/src/chat/chat.css b/web/src/chat/chat.css index 7189840..3a5040b 100644 --- a/web/src/chat/chat.css +++ b/web/src/chat/chat.css @@ -654,6 +654,8 @@ button.vc-ref:focus-visible { outline: 2px solid currentColor; outline-offset: 1 background: none; color: var(--vc-faint); cursor: pointer; } .vc-newtask button:hover { background: color-mix(in srgb, var(--text) 14%, transparent); color: var(--text); } +/* `$pin` / `$snooze` picked for a new chat: named above the box until it is sent. */ +.vc-start-opts { padding: 2px 4px 6px; } .vc-newtask-help { margin-left: auto; color: var(--vc-faint); } @media (pointer: coarse) { .vc-newtask-help { display: none; } } .vc-plus-wrap { position: relative; } diff --git a/web/src/chat/composerDestinations.test.tsx b/web/src/chat/composerDestinations.test.tsx index e029da7..3bd6caf 100644 --- a/web/src/chat/composerDestinations.test.tsx +++ b/web/src/chat/composerDestinations.test.tsx @@ -18,7 +18,13 @@ const work = { folders: {}, sheetName: '', loaded: true, error: '', } -vi.mock('./store', async (orig) => ({ ...(await orig()), useChat: (sel: (s: { projects: Project[] }) => unknown) => sel({ projects }) })) +const providers = [{ id: 'claude', name: 'Claude', driver: 'claude', supportsModelPicker: true }] +const models = { claude: [{ id: 'claude-opus-5-5', name: 'Claude Opus 5.5' }] } +vi.mock('./store', async (orig) => ({ + ...(await orig()), + useChat: (sel: (s: { projects: Project[]; providers: typeof providers; models: typeof models }) => unknown) => sel({ projects, providers, models }), + ensureModels: () => {}, +})) // An upload that never finishes, for the test that a pick waits for it. vi.mock('./api', async (orig) => ({ ...(await orig()), uploadFile: () => new Promise(() => {}) })) vi.mock('../work/state', async (orig) => ({ ...(await orig()), getWork: () => work, subscribeWork: () => () => {} })) @@ -27,14 +33,15 @@ const { default: Composer } = await import('./Composer') afterEach(cleanup) -function Harness({ onPick, destinations = true, onNewTask, projectId = null, onSend = () => {} }: { +function Harness({ onPick, destinations = true, onNewTask, projectId = null, onSend = () => {}, onModel, onStartOption, valueSpy }: { onPick: (d: Destination, text: string) => void; destinations?: boolean onNewTask?: (fields: NewTaskFields) => Promise; projectId?: string | null; onSend?: () => void + onModel?: (d: any) => void; onStartOption?: (d: any) => void; valueSpy?: (v: string) => void }) { const [value, setValue] = useState('') return ( - {}} busy={false} - destinations={destinations ? { projectId, taskId: null, onPick: (d, text) => onPick(d, text), onNewTask } : undefined} /> + { valueSpy?.(v); setValue(v) }} onSend={onSend} onStop={() => {}} busy={false} + destinations={destinations ? { projectId, taskId: null, onPick: (d, text) => onPick(d, text), onNewTask, onModel, onStartOption } : undefined} /> ) } @@ -92,6 +99,60 @@ describe('composer $ destinations', () => { expect(onPick).not.toHaveBeenCalled() }) + it('$ghost makes it a ghost chat, keeping the words', async () => { + const onPick = vi.fn() + render() + const box = await type('just between us $gho') + expect(screen.getAllByRole('option')[0].textContent).toContain('Ghost chat') + fireEvent.keyDown(box, { key: 'Enter' }) + expect(onPick.mock.calls[0][0]).toMatchObject({ kind: 'ghost' }) + expect(onPick.mock.calls[0][1]).toBe('just between us') + }) + + it('offers a new folder in the project, and a new project, for a name nothing has, with his capitals', async () => { + const onPick = vi.fn() + render() + await type('$NYC-trip') + const options = screen.getAllByRole('option').map((o) => o.textContent) + expect(options[0]).toContain('New folder “NYC trip”') + expect(options[0]).toContain('New folder in Work - Acme') + expect(options[1]).toContain('New project “NYC trip”') + fireEvent.mouseDown(screen.getAllByRole('option')[1]) + expect(onPick.mock.calls[0][0]).toMatchObject({ kind: 'new-folder', name: 'NYC trip' }) + expect(onPick.mock.calls[0][0].parent).toBeUndefined() + }) + + it('$opus picks the model and leaves the words in the box', async () => { + const onPick = vi.fn() + const onModel = vi.fn() + const box = await (async () => { render(); return type('plan the week $opus') })() + expect(screen.getAllByRole('option')[0].textContent).toContain('Claude Opus 5.5') + fireEvent.keyDown(box, { key: 'Enter' }) + expect(onModel.mock.calls[0][0]).toMatchObject({ kind: 'model', modelId: 'claude-opus-5-5' }) + expect(onPick).not.toHaveBeenCalled() + await waitFor(() => expect(screen.queryAllByRole('option')).toHaveLength(0)) + }) + + it('offers no models where the chat view cannot take one', async () => { + render() + await type('$opus') + expect(screen.queryAllByRole('option').map((o) => o.textContent).join()).not.toContain('Opus 5.5') + }) + + it('$pin and $snooze-tom hand the option over', async () => { + const onStartOption = vi.fn() + render() + const box = await type('$pin') + fireEvent.keyDown(box, { key: 'Enter' }) + expect(onStartOption.mock.calls[0][0]).toMatchObject({ kind: 'pin' }) + cleanup() + render() + const again = await type('ask about the lease $snooze-tom') + expect(screen.getAllByRole('option')[0].textContent).toContain('Snooze · Tomorrow') + fireEvent.keyDown(again, { key: 'Enter' }) + expect(onStartOption.mock.calls[1][0]).toMatchObject({ kind: 'snooze' }) + }) + it('offers nothing of the kind in a chat already started', async () => { render() await type('$harb') diff --git a/web/src/chat/destinations.test.ts b/web/src/chat/destinations.test.ts index 6e40d86..e240971 100644 --- a/web/src/chat/destinations.test.ts +++ b/web/src/chat/destinations.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest' -import { matchScore, placeAfter, rankDestinations, slug, stripToken } from './destinations' +import { matchScore, nameFromTerm, placeAfter, rankDestinations, slug, stripToken } from './destinations' import type { Project } from './types' import type { WorkTask } from '../work/groups' @@ -46,7 +46,7 @@ describe('rankDestinations', () => { // A bare `$` keeps to four places, so the tasks are in view under them. expect(keys(rankDestinations(ctx, ''))).toEqual([ 'p:lp', 'p:harbor', 'p:mn', 'p:wp', - 'new-task', + 'new-task', 'ghost', 't:t2', 't:t1', 't:sheet:1:2:abcd', ]) expect(keys(rankDestinations(ctx, 'r'))).toContain('p:gb') @@ -75,7 +75,7 @@ describe('rankDestinations', () => { }) it('leaves out done and snoozed tasks', () => { - expect(keys(rankDestinations(ctx, 'thing'))).toEqual([]) + expect(keys(rankDestinations(ctx, 'thing')).filter((k) => k.startsWith('t:'))).toEqual([]) }) }) @@ -116,3 +116,102 @@ describe('placeAfter', () => { expect(placeAfter(t2, { taskId: null, projectId: 'wp' }, () => 'harbor')).toEqual({ taskId: 't2', projectId: 'harbor' }) }) }) + +describe('$ghost', () => { + const ctx = { projects, tasks, projectId: null, taskId: null } + + it('leads with Ghost chat for $gh…, $temp… and $inco…, and not for shorter or other words', () => { + for (const term of ['gh', 'ghost', 'temp', 'temporary', 'inco', 'incognito']) expect(keys(rankDestinations(ctx, term))[0]).toBe('ghost') + for (const term of ['g', 'te', 'tem', 'in', 'ghosts', 'harb']) expect(keys(rankDestinations(ctx, term))).not.toContain('ghost') + }) + + it('moves the chat to Home, out of its project and task', () => { + const ghost = rankDestinations(ctx, 'ghost')[0] + expect(placeAfter(ghost, { taskId: 't1', projectId: 'harbor' }, () => 'wp')).toEqual({ taskId: null, projectId: null }) + }) +}) + +describe('new folder from a name nothing has', () => { + const ctx = { projects, tasks, projectId: null, taskId: null } + const folders = (list: ReturnType) => list.filter((d) => d.kind === 'new-folder') + + it('offers a new project at Home, last, named as typed', () => { + const list = rankDestinations(ctx, 'tax-returns', 'tax-returns') + expect(keys(list)).toEqual(['new-project']) + expect(list[0].name).toBe('Tax returns') + expect(rankDestinations(ctx, 'q4-plans', 'Q4-Plans')[0].name).toBe('Q4 Plans') + // After any task it matches, so Enter still picks the task. + expect(keys(rankDestinations(ctx, 'expense'))).toEqual(['t:t1', 'new-project']) + }) + + it('in a project or one of its folders, offers a folder in the project first', () => { + const inFolder = { ...ctx, projectId: 'harbor' } + const list = folders(rankDestinations(inFolder, 'receipts')) + expect(list.map((d) => d.key)).toEqual(['new-folder:lp', 'new-project']) + expect(list[0].kind === 'new-folder' && list[0].parent?.id).toBe('lp') + }) + + it('never for a name a place already has, a short term, a price or a word `$` keeps', () => { + expect(folders(rankDestinations(ctx, 'harb'))).toEqual([]) + expect(folders(rankDestinations({ ...ctx, projectId: 'harbor' }, 'harbor'))).toEqual([]) + expect(folders(rankDestinations(ctx, 'zz'))).toEqual([]) + expect(folders(rankDestinations(ctx, '400'))).toEqual([]) + for (const term of ['task', 'ghost', 'temporary', 'hom', 'folder', 'project']) expect(folders(rankDestinations(ctx, term))).toEqual([]) + }) + + it('moves nothing when picked: the folder is made first', () => { + const now = { taskId: 't1', projectId: null } + expect(placeAfter(rankDestinations(ctx, 'tax-returns')[0], now, () => null)).toEqual(now) + }) + + it('names keep his capitals', () => { + expect(nameFromTerm('tax-returns')).toBe('Tax returns') + expect(nameFromTerm('NYC-trip')).toBe('NYC trip') + }) +}) + +describe('$opus, $pin and $snooze', () => { + const provider = (id: string, name: string, driver: string, supportsModelPicker = true) => ({ id, name, driver, supportsModelPicker }) + const models = [ + { provider: provider('claude', 'Claude', 'claude'), models: [ + { id: 'claude-opus-5-5', name: 'Claude Opus 5.5' }, { id: 'claude-sonnet-5-5', name: 'Claude Sonnet 5.5', favorite: true }, + { id: 'claude-opus-4', name: 'Claude Opus 4', hidden: true }, + ] }, + { provider: provider('codex', 'Codex', 'codex'), models: [{ id: 'gpt-5.5-codex', name: 'GPT-5.5 Codex' }] }, + { provider: provider('cursor', 'Cursor', 'cursor', false), models: [] }, + ] + const ctx = { projects, tasks, projectId: null, taskId: null, models, startOptions: true, now: new Date(2026, 10, 25, 10, 0) } + + it('finds models by a word of their name or id, never a hidden one, and an account by its name', () => { + expect(keys(rankDestinations(ctx, 'opus'))).toEqual(['m:claude:claude-opus-5-5']) + expect(keys(rankDestinations(ctx, 'sonnet'))).toEqual(['m:claude:claude-sonnet-5-5']) + // The account itself first (its default), then its models; favourites before the rest. + expect(keys(rankDestinations(ctx, 'claude'))).toEqual(['m:claude:', 'm:claude:claude-sonnet-5-5', 'm:claude:claude-opus-5-5']) + expect(keys(rankDestinations(ctx, 'codex'))).toEqual(['m:codex:', 'm:codex:gpt-5.5-codex']) + // An account with no model list is offered as itself. + expect(keys(rankDestinations(ctx, 'cursor'))).toEqual(['m:cursor:']) + // A model's name is taken: no New project "Opus". + expect(rankDestinations(ctx, 'opus').some((d) => d.kind === 'new-folder')).toBe(false) + expect(keys(rankDestinations(ctx, 'o')).some((k) => k.startsWith('m:'))).toBe(false) + }) + + it('offers Pin it for $pi, unless it is pinned already or the chat view cannot', () => { + expect(keys(rankDestinations(ctx, 'pi'))[0]).toBe('pin') + expect(keys(rankDestinations({ ...ctx, pinned: true }, 'pin'))).not.toContain('pin') + expect(keys(rankDestinations({ ...ctx, startOptions: false }, 'pin'))).not.toContain('pin') + }) + + it('lists the snooze times for $snooze, $later and $remind, and narrows with $snooze-tom', () => { + for (const term of ['sn', 'snooze', 'later', 'rem']) expect(keys(rankDestinations(ctx, term))).toContain('snooze:tomorrow') + expect(keys(rankDestinations(ctx, 'snooze-tom'))).toEqual(['snooze:tomorrow']) + const tomorrow = rankDestinations(ctx, 'snooze-tom')[0] + expect(tomorrow.kind === 'snooze' && new Date(tomorrow.until).getDate()).toBe(26) + expect(keys(rankDestinations({ ...ctx, startOptions: false }, 'snooze'))).toEqual([]) + expect(keys(rankDestinations(ctx, 'la'))).not.toContain('snooze:tomorrow') + }) + + it('none of them move the chat', () => { + const now = { taskId: 't1', projectId: 'harbor' } + for (const term of ['opus', 'pin', 'snooze-tom']) expect(placeAfter(rankDestinations(ctx, term)[0], now, () => 'wp')).toEqual(now) + }) +}) diff --git a/web/src/chat/destinations.ts b/web/src/chat/destinations.ts index 14a89c2..e179e10 100644 --- a/web/src/chat/destinations.ts +++ b/web/src/chat/destinations.ts @@ -1,22 +1,72 @@ // Where a new chat goes, picked from the composer with `$`: `$harbor` puts the // chat being started in the harbor folder, `$expense` starts it for that task // (in the task's own folder, as "New chat for this task" does), and `$task` makes -// a new task right in the composer, then starts the chat for it. Pure, so the +// a new task right in the composer, then starts the chat for it, `$ghost` makes it +// a ghost chat (not kept: gone at midnight), and a name no place has yet +// (`$tax-returns`) offers a new folder or project by that name, `$opus` (any model +// or account name) picks the chat's model, `$pin` pins it from the start, and +// `$snooze` sends it now and keeps it out of the way until a time. Pure, so the // composer's menu and its tests read the same rules. -import type { Project } from './types' +import type { ModelRow, Project, ProviderRow } from './types' import type { WorkTask } from '../work/groups' +import { snoozePresets } from './settle' +import { visibleModels } from './models' export type Destination = | { kind: 'home'; key: string; name: string } | { kind: 'project'; key: string; name: string; project: Project; parent?: Project } | { kind: 'task'; key: string; name: string; task: WorkTask } | { kind: 'new-task'; key: 'new-task'; name: 'New task' } + | { kind: 'ghost'; key: 'ghost'; name: 'Ghost chat' } + /** A folder (in `parent`) or a top-level project, made by that name, then the chat starts in it. */ + | { kind: 'new-folder'; key: string; name: string; parent?: Project } + /** A model to start on (no `modelId`: the account's own default). */ + | { kind: 'model'; key: string; name: string; provider: ProviderRow; modelId?: string; note?: string } + | { kind: 'pin'; key: 'pin'; name: 'Pin it' } + /** Send now, and keep it in Snoozed until `until`, even once the reply lands. */ + | { kind: 'snooze'; key: string; name: string; until: number; when: string } /** What `$` takes for "make a new task": `$task`, `$new`, `$newtask`, from two letters on. */ const NEW_TASK_WORDS = ['task', 'new', 'new-task', 'newtask'] export const wantsNewTask = (term: string) => term.length >= 2 && NEW_TASK_WORDS.some((w) => w.startsWith(term)) const NEW_TASK: Destination = { kind: 'new-task', key: 'new-task', name: 'New task' } +/** What `$` takes for a ghost chat: `$gh…` for ghost, `$temp…`, `$inco…` (each word from its `min` letters). */ +const GHOST_WORDS: Array<[string, number]> = [['ghost', 2], ['temporary', 4], ['incognito', 4]] +export const wantsGhost = (term: string) => GHOST_WORDS.some(([w, min]) => term.length >= min && w.startsWith(term)) +const GHOST: Destination = { kind: 'ghost', key: 'ghost', name: 'Ghost chat' } + +/** `$pin` from `$pi`. */ +export const wantsPin = (term: string) => term.length >= 2 && 'pin'.startsWith(term) +const PIN: Destination = { kind: 'pin', key: 'pin', name: 'Pin it' } + +/** `$snooze` from `$sn`, `$later`, `$remind` from three letters; `$snooze-tom` narrows to a time. */ +const SNOOZE_WORDS: Array<[string, number]> = [['snooze', 2], ['later', 3], ['remind', 3]] +export const wantsSnooze = (term: string) => SNOOZE_WORDS.some(([w, min]) => term.length >= min && w.startsWith(term)) +function snoozeRows(term: string, now: Date): Destination[] { + const narrow = /^(?:snooze|later|remind)-(.+)$/.exec(term)?.[1] + if (!narrow && !wantsSnooze(term)) return [] + return snoozePresets(now) + .filter((p) => !narrow || matchScore(p.label, narrow) >= 0 && matchScore(p.label, narrow) <= 1) + .map((p) => ({ kind: 'snooze', key: `snooze:${p.id}`, name: p.label, until: p.until, when: p.when })) +} + +/** Models offered for one term, at most. */ +const MODELS = 5 +/** Account and model names are matched from this many letters (`$op` for Opus). */ +const MODEL_MIN = 2 + +/** Words `$` keeps for itself, so typing one never offers a folder by that name. */ +const RESERVED = [...NEW_TASK_WORDS, ...GHOST_WORDS.map(([w]) => w), ...SNOOZE_WORDS.map(([w]) => w), 'pin', 'home', 'folder', 'project', 'new-folder', 'new-project'] +/** A name is offered as a new folder from this many letters, once no place matches it. */ +const NEW_FOLDER_MIN = 3 + +/** The name a typed `$tax-returns` stands for: hyphens as spaces, a capital if he typed none. */ +export function nameFromTerm(raw: string) { + const name = raw.replace(/-+/g, ' ').trim() + return name === name.toLowerCase() ? name.charAt(0).toUpperCase() + name.slice(1) : name +} + /** A name as `$` reaches it: lower case, every run of other characters one hyphen. */ export const slug = (name: string) => name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') @@ -42,6 +92,13 @@ export interface DestinationContext { projectId: string | null /** The task it is being started for, if any. */ taskId: string | null + /** Every account and the models it lists (as the model picker has them), for `$opus`. */ + models?: ReadonlyArray<{ provider: ProviderRow; models: readonly ModelRow[] }> + /** Offer `$pin` and `$snooze` (they need a chat view that sends them). */ + startOptions?: boolean + /** It is pinned already: no `$pin`. */ + pinned?: boolean + now?: Date } const PLACES = 8 @@ -51,10 +108,13 @@ const PLACES_BARE = 4 /** * The `$` menu's places (Home, projects, folders) then tasks, best matches first. - * "New task" leads when the term asks for it (`$task`) and sits between the places - * and the tasks for a bare `$`. None for a price ("$40", "$4.99", "$1,000"): Enter should send it. + * "New task" and "Ghost chat" lead when the term asks for them (`$task`, `$ghost`) and + * sit between the places and the tasks for a bare `$`. A name that matches no place + * ends the list with "New folder … in " (in a project or folder) and "New + * project …"; `raw` is the term as typed, for the name's capitals. None for a price + * ("$40", "$4.99", "$1,000"): Enter should send it. */ -export function rankDestinations(ctx: DestinationContext, term: string): Destination[] { +export function rankDestinations(ctx: DestinationContext, term: string, raw = term): Destination[] { if (/^\d[\d.,]*$/.test(term)) return [] const t = term.toLowerCase() const byId = new Map(ctx.projects.map((p) => [p.id, p])) @@ -89,8 +149,55 @@ export function rankDestinations(ctx: DestinationContext, term: string): Destina const found = tasks.slice(0, TASKS).map(({ task }): Destination => ({ kind: 'task', key: `t:${task.ref}`, name: task.title, task })) const shown = places.slice(0, t ? PLACES : PLACES_BARE).map((x) => x.d) - if (wantsNewTask(t)) return [NEW_TASK, ...shown, ...found] - return [...shown, ...(t ? [] : [NEW_TASK]), ...found] + const lead = [ + ...(wantsNewTask(t) ? [NEW_TASK] : []), ...(wantsGhost(t) ? [GHOST] : []), + ...(ctx.startOptions && !ctx.pinned && wantsPin(t) ? [PIN] : []), + ...(ctx.startOptions ? snoozeRows(t, ctx.now ?? new Date()) : []), + ] + if (!t) return [...shown, NEW_TASK, GHOST, ...found] + const models = rankModels(ctx.models || [], t) + // Only a name nothing has yet offers a new one; the folder the chat is in counts, + // and so does a name the term is the start of ("$harb" is on its way to harbor), or a model's. + const taken = lead.length > 0 || places.length > 0 || models.length > 0 || ctx.projects.some((p) => { const s = matchScore(p.name, t); return s === 0 || s === 1 }) + return [...lead, ...shown, ...models, ...found, ...(taken ? [] : newFolders(ctx, t, raw))] +} + +/** + * `$opus`, `$gpt-5`, `$codex`: models whose name or id the term starts or starts a word of + * (favourites first), and an account named by the term, which starts on its own default. + */ +export function rankModels(accounts: NonNullable, t: string): Destination[] { + if (t.length < MODEL_MIN) return [] + // The account's own row leads its models (fav -1), then favourites, then the rest. + const close = (name: string) => { const s = matchScore(name, t); return s === 0 || s === 1 ? s : -1 } + const out: Array<{ d: Destination; s: number; fav: number; order: number }> = [] + let order = 0 + for (const { provider, models } of accounts) { + const named = close(provider.name) + const accountScore = named >= 0 ? named : close(provider.driver) + if (accountScore >= 0) out.push({ d: { kind: 'model', key: `m:${provider.id}:`, name: `${provider.name} default`, provider, note: 'The account’s default model' }, s: accountScore, fav: -1, order: order++ }) + if (!provider.supportsModelPicker) continue + for (const m of visibleModels([...models])) { + const scores = [close(m.name || m.id), close(m.id)].filter((x) => x >= 0) + if (!scores.length) continue + out.push({ d: { kind: 'model', key: `m:${provider.id}:${m.id}`, name: m.name || m.id, provider, modelId: m.id, ...(m.note ? { note: m.note } : {}) }, s: Math.min(...scores), fav: m.favorite ? 0 : 1, order: order++ }) + } + } + out.sort((a, b) => a.s - b.s || a.fav - b.fav || a.order - b.order) + return out.slice(0, MODELS).map((x) => x.d) +} + +/** "New folder “Tax returns” in Acme" (in a project or one of its folders: one level only) and "New project “Tax returns”". */ +function newFolders(ctx: DestinationContext, t: string, raw: string): Destination[] { + if (t.length < NEW_FOLDER_MIN || !/[a-z]/.test(t) || RESERVED.some((w) => w.startsWith(t))) return [] + const name = nameFromTerm(raw).slice(0, 80) + if (!name) return [] + const here = ctx.projectId ? ctx.projects.find((p) => p.id === ctx.projectId) : undefined + const root = here?.parentId ? ctx.projects.find((p) => p.id === here.parentId) : here + return [ + ...(root ? [{ kind: 'new-folder' as const, key: `new-folder:${root.id}`, name, parent: root }] : []), + { kind: 'new-folder', key: 'new-project', name }, + ] } const dueOrder = (t: WorkTask) => (t.dueDate ? Date.parse(t.dueDate.slice(0, 10)) || Infinity : Infinity) @@ -113,8 +220,11 @@ export function stripToken(value: string, start: number, end: number) { * being started for; a task takes its own folder, else stays where it is. */ export function placeAfter(d: Destination, now: { taskId: string | null; projectId: string | null }, taskHome: (ref: string) => string | null) { - // "New task" moves nothing until the task exists (the composer makes it first). - if (d.kind === 'new-task') return now + // "New task" and "New folder" move nothing until the task or folder exists (made first); + // a model, a pin or a snooze changes how it starts, not where. + if (d.kind === 'new-task' || d.kind === 'new-folder' || d.kind === 'model' || d.kind === 'pin' || d.kind === 'snooze') return now + // A ghost chat lives at Home, outside any project or task. + if (d.kind === 'ghost') return { taskId: null, projectId: null } if (d.kind === 'home') return { taskId: now.taskId, projectId: null } if (d.kind === 'project') return { taskId: now.taskId, projectId: d.project.id } return { taskId: d.task.ref, projectId: taskHome(d.task.ref) ?? now.projectId } diff --git a/web/src/chat/draftsShared.test.ts b/web/src/chat/draftsShared.test.ts index fbf3522..c560629 100644 --- a/web/src/chat/draftsShared.test.ts +++ b/web/src/chat/draftsShared.test.ts @@ -140,7 +140,7 @@ describe('the panel’s rows', () => { it('new-chat drafts only, newest first, each with its place', () => { const rows = draftRows(four().get(), { projects, projectId: null, shown: null, listedOnArrival: false }) expect(rows.map((r) => [r.key, r.preview, r.place, r.icon])).toEqual([ - ['new:d', 'gone at midnight', 'Temporary chat', 'temporary'], + ['new:d', 'gone at midnight', 'Ghost chat', 'temporary'], ['new:c', 'for a task', 'Garden', 'task'], ['new:b', '2 attachments', 'Beds', 'project'], ['new:a', 'first line', 'Home', 'home'], diff --git a/web/src/chat/draftsShared.ts b/web/src/chat/draftsShared.ts index b8dfadf..d444241 100644 --- a/web/src/chat/draftsShared.ts +++ b/web/src/chat/draftsShared.ts @@ -181,7 +181,7 @@ export function draftRows(s: DraftState, { projects, projectId, shown, listedOnA return { key: d.key, preview: draftPreview(d), - place: project?.name || (d.temporary ? 'Temporary chat' : 'Home'), + place: project?.name || (d.temporary ? 'Ghost chat' : 'Home'), icon: d.place.kind === 'task' ? 'task' : project ? 'project' : d.temporary ? 'temporary' : 'home', ...(project ? { project } : {}), active: d.key === shown, diff --git a/web/src/chat/icons.ts b/web/src/chat/icons.ts index 6fdb146..e5a8f02 100644 --- a/web/src/chat/icons.ts +++ b/web/src/chat/icons.ts @@ -139,3 +139,4 @@ export { default as IconAdjustmentsHorizontal } from '@tabler/icons-react/dist/e // Context compaction (CompactionMark.tsx, the composer's Compact chip): T3's Minimize2. export { default as IconArrowsDiagonalMinimize2 } from '@tabler/icons-react/dist/esm/icons/IconArrowsDiagonalMinimize2.mjs' export { default as IconArrowsDiagonal } from '@tabler/icons-react/dist/esm/icons/IconArrowsDiagonal.mjs' +export { default as IconArchive } from '@tabler/icons-react/dist/esm/icons/IconArchive.mjs' diff --git a/web/src/chat/settle.test.ts b/web/src/chat/settle.test.ts index 0e74421..70e37ad 100644 --- a/web/src/chat/settle.test.ts +++ b/web/src/chat/settle.test.ts @@ -118,6 +118,20 @@ describe('shelves', () => { }) +describe('ghost chats', () => { + it('are on no shelf once settled, by hand or on their own; in play they list as usual', () => { + const ghost = (id: string, extra: Partial = {}) => chat(id, { kind: 'temporary', expiresAt: NOW + HOUR_MS, ...extra }) + const { active, settled } = shelve([ + ghost('by-hand', { settledOverride: 'settled', settledAt: NOW }), + ghost('done', { doneAt: NOW - 60_000 }), + ghost('live'), + chat('kept', { settledOverride: 'settled', settledAt: NOW }), + ], NOW, 3) + expect(active.map((t) => t.id)).toEqual(['live']) + expect(settled.map((t) => t.id)).toEqual(['kept']) + }) +}) + describe('writing in a chat', () => { const written = (t: ChatThread) => ({ ...t, ...ownerMessageChange(t, NOW) }) it('brings a settled chat back to the top', () => { diff --git a/web/src/chat/settle.ts b/web/src/chat/settle.ts index e69e451..3b4237c 100644 --- a/web/src/chat/settle.ts +++ b/web/src/chat/settle.ts @@ -13,6 +13,10 @@ // it is opened (opening clears the fields). A reply that finishes while the chat // is snoozed wakes it early (the bridge sets `snoozedUntil` to that moment). // +// A ghost chat (kind 'temporary': not kept, gone at midnight) never sits on the +// Settled shelf: settled, it is off every list (`ghostGone`), and Settle by hand +// deletes it once its Undo has passed (settleThread in store.ts). +// // The bridge stores the fields (chat/store.mjs) and clears them whenever he // writes in the chat (wakeOnOwnerMessage there, ownerMessageChange here); // everything else about them lives in this file. @@ -88,6 +92,9 @@ export const offersSettle = (t: ChatThread, shelf: Shelf, live = false) => */ export const keptOpenId = (activeId: string | null, openedSettled: string | null) => (activeId && activeId !== openedSettled ? activeId : null) +/** A ghost chat that has settled: listed nowhere, and deleted at midnight if not before. */ +export const ghostGone = (t: ChatThread, settled: number) => t.kind === 'temporary' && settled > 0 + /** Snoozed wins over settled, as in T3. `waiting` as for settledAt. */ export function shelfOf(t: ChatThread, now: number, autoDays: number, live = false, open = false, waiting = false): Shelf { if (isSnoozed(t, now)) return 'snoozed' @@ -102,6 +109,7 @@ export function shelve(threads: ChatThread[], now: number, autoDays: number, liv for (const t of threads) { if (isSnoozed(t, now)) { snoozed.push(t); continue } const at = settledAt(t, now, autoDays, live(t.id), t.id === openId, waiting(t)) + if (ghostGone(t, at)) continue if (at) settled.push({ t, at }) else active.push(t) } diff --git a/web/src/chat/sidebar.test.ts b/web/src/chat/sidebar.test.ts index e6f1139..1f4c58d 100644 --- a/web/src/chat/sidebar.test.ts +++ b/web/src/chat/sidebar.test.ts @@ -12,6 +12,15 @@ const ids = (list: ChatThread[]) => list.map((t) => t.id) const base = { now: NOW, autoDays: 3, live: () => false, projects: PROJECTS } describe('the chats panel’s shelves', () => { + it('lists a settled ghost chat nowhere', () => { + const lists = sidebarLists([ + chat('ghost', { kind: 'temporary', settledOverride: 'settled', settledAt: NOW }), + chat('ghost-live', { kind: 'temporary' }), + ], base) + expect(ids(lists.inbox)).toEqual(['ghost-live']) + expect(lists.settled).toEqual([]) + }) + it('lists every chat in every project and folder in one list, latest first', () => { const lists = sidebarLists([ chat('home', { updatedAt: NOW - 3 * HOUR_MS }), diff --git a/web/src/chat/sidebar.ts b/web/src/chat/sidebar.ts index 7d5392d..433bb2e 100644 --- a/web/src/chat/sidebar.ts +++ b/web/src/chat/sidebar.ts @@ -14,7 +14,7 @@ // (one project and its folders, or Home) narrows the list when he asks for it. // Totems' own chats are not listed; they live with their totems. import type { ChatThread, Project } from './types' -import { activeAt, isSnoozed, settledAt } from './settle' +import { activeAt, ghostGone, isSnoozed, settledAt } from './settle' /** What the list shows: every chat, the ones in no project, or one project and its folders. */ export type SidebarScope = 'all' | 'home' | string @@ -66,6 +66,7 @@ export function sidebarLists(threads: ChatThread[], o: SidebarOptions): SidebarL // Waiting on him stays in play, whatever would settle it on its own (age, a finished // task, the agent's "done"); only his own Settle shelves it (settle.ts settledAt). const at = settledAt(t, now, autoDays, live(t.id), t.id === openId, needsYou(t)) + if (ghostGone(t, at)) continue if (at) { settledOrder.set(t.id, at); out.settled.push(t); continue } if (t.pinned) out.pinned.push(t) else if (live(t.id) && !needsYou(t)) out.working.push(t) diff --git a/web/src/chat/store.ts b/web/src/chat/store.ts index f831725..7b9ecf6 100644 --- a/web/src/chat/store.ts +++ b/web/src/chat/store.ts @@ -14,7 +14,7 @@ import { announceTasks, onTasksChanged } from '../todos/bus' import { applyEvent } from './reduce' import { sendChat, attachRun, stopChat, steerChat, decideApproval, changeQueue, getRuns, getCapabilities, probeCapabilities, listProjects, getProject, createProjectApi, patchProjectApi, projectFaviconApi, - deleteProjectApi, putProjectMemory, addProjectFilesApi, removeProjectFilesApi, moveProjectMemoryApi, moveProjectFilesApi, type SendArgs, type StreamHandle, + archiveProjectApi, restoreProjectApi, putProjectMemory, addProjectFilesApi, removeProjectFilesApi, moveProjectMemoryApi, moveProjectFilesApi, type SendArgs, type StreamHandle, } from './api' import type { QueueAction } from './api' import { defaultSettingsFor, fromPreset, normalizeModelSettings, parseModelSpec, visibleModels, wireModel } from './models' @@ -645,37 +645,34 @@ export async function removeProjectFiles(id: string, ids: string[]) { } } -/** Delete a project (and its folders) or a folder. Chats move to Home, or a folder's up to its project; returns how many did. */ -export async function deleteProject(id: string) { +/** + * Put a project (with its folders) or a folder away. Nothing is deleted: its files, + * memory and chats wait in Settings → Archive, and the lists leave them out until + * it is restored. A folder's page goes back to its project; a project's to Home. + */ +export async function archiveProject(id: string) { const parentId = projectById(id)?.parentId - const { movedChats } = await deleteProjectApi(id) - if (parentId) { - set((s) => { - const detail = { ...s.projectDetail } - delete detail[id] - return { - projects: s.projects.filter((p) => p.id !== id), - projectDetail: detail, - projectId: s.projectId === id ? parentId : s.projectId, - threads: s.threads.map((t) => (t.projectId === id ? { ...t, projectId: parentId } : t)), - } - }) - loadProject(parentId) - loadProjects() - return movedChats - } - const gone = new Set([id, ...foldersOf(state.projects, id).map((f) => f.id)]) + await archiveProjectApi(id) + const gone = new Set([id, ...(parentId ? [] : foldersOf(state.projects, id).map((f) => f.id))]) set((s) => { const detail = { ...s.projectDetail } for (const g of gone) delete detail[g] return { projects: s.projects.filter((p) => !gone.has(p.id)), projectDetail: detail, - projectId: s.projectId && gone.has(s.projectId) ? null : s.projectId, - threads: s.threads.map((t) => (t.projectId && gone.has(t.projectId) ? { ...t, projectId: undefined } : t)), + projectId: s.projectId && gone.has(s.projectId) ? (parentId || null) : s.projectId, + // Its chats go with it (the bridge's list leaves them out); one answering stays until it ends. + threads: s.threads.filter((t) => !t.projectId || !gone.has(t.projectId) || t.id === s.activeId || !!s.runs[t.id]), } }) - return movedChats + if (parentId) loadProject(parentId) + return gone.size +} + +/** Bring an archived project or folder back, with its chats. */ +export async function restoreProject(id: string) { + await restoreProjectApi(id) + await Promise.all([loadProjects(), syncThreads()]) } /** Move a folder's memory entries (by text) up into its project. */ @@ -722,9 +719,27 @@ export function settleThread(id: string) { if (!t || state.runs[id]) return const before = settleFieldsOf(t) writeSettle(id, settleChange(now())) + if (t.kind === 'temporary') { settleGhost(id, threadTitle(t), before); return } undoable(id, `Settled “${threadTitle(t)}”`, before) } +/** + * A ghost chat settled is gone: off every list at once (settle.ts ghostGone), off the + * screen if it was open, and deleted once the toast's Undo has passed. A tab closed + * before then leaves it settled, so hidden, until the bridge drops it at midnight. + */ +function settleGhost(id: string, title: string, before: SettleFields) { + if (state.activeId === id) set({ activeId: null }) + pushToast(`Ghost chat “${title}” is gone`, 'info', { + duration: 6000, + action: { label: 'Undo', onClick: () => writeSettle(id, before) }, + onExpire: () => { + const t = state.threads.find((x) => x.id === id) + if (t?.kind === 'temporary' && t.settledOverride === 'settled') void removeThread(id) + }, + }) +} + export function unsettleThread(id: string) { const t = state.threads.find((x) => x.id === id) if (t) writeSettle(id, unsettleChange(now())) @@ -1292,7 +1307,7 @@ function handleEvent(threadId: string, e: StreamEvent) { patchAssistant(threadId, (m) => ({ ...e.message, parts: e.message.parts?.length ? e.message.parts : m.parts })) // The bridge marks it waiting on him too; this shows it without a sync. // Not after a compaction (`/compact`, context.ts): housekeeping is nothing to read. - if (e.message.status !== 'stopped') patchThread(threadId, (t) => (t.totemId || isCompactionTurn(t.messages[t.messages.findIndex((m) => m.id === e.message.id) - 1]) ? t : { ...t, needsReply: true, ...(t.snoozedUntil && t.snoozedUntil > now() ? { snoozedUntil: now() } : {}) })) + if (e.message.status !== 'stopped') patchThread(threadId, (t) => (t.totemId || isCompactionTurn(t.messages[t.messages.findIndex((m) => m.id === e.message.id) - 1]) ? t : { ...t, needsReply: true, ...(t.snoozedUntil && t.snoozedUntil > now() && !t.snoozeHeld ? { snoozedUntil: now() } : {}) })) break case 'error': patchAssistant(threadId, (m) => ({ ...m, status: 'error', error: e.text })) @@ -1377,6 +1392,10 @@ export interface SendInput { taskId?: string /** "Compact and send" (context.ts): the chat compacts first and the message waits right behind it. */ compactFirst?: boolean + /** A new chat pinned from the start (`$pin`). */ + pinned?: boolean + /** A new chat out of the way until then (`$snooze`), even once its reply lands. */ + snoozeUntil?: number /** The bridge refused the message before starting it (not a message that never reached it, which stays as "Not sent"). */ onRefused?: () => void } @@ -1413,10 +1432,13 @@ export function send(input: SendInput): string { } const contextOff = !!projectId && !thread && !!input.projectContextOff const taskId = !thread && input.taskId ? input.taskId : undefined + const pinned = !thread && !!input.pinned + const snoozeUntil = !thread && input.snoozeUntil && input.snoozeUntil > t0 ? input.snoozeUntil : undefined if (!thread) { thread = { id: threadId, kind, provider: kind === 'regular' ? provider : undefined, modelSettings: settings, ...(projectId ? { projectId } : {}), ...(contextOff ? { projectContextOff: true } : {}), ...(taskId ? { taskId } : {}), + ...(pinned ? { pinned: true } : {}), ...(snoozeUntil ? { snoozedUntil: snoozeUntil, snoozedAt: t0, snoozeHeld: true } : {}), messages: [], createdAt: t0, updatedAt: t0, ...(kind === 'temporary' ? { expiresAt: endOfToday() } : {}), } } @@ -1433,6 +1455,8 @@ export function send(input: SendInput): string { ...(contextOff ? { projectContextOff: true } : {}), ...(taskId ? { taskId } : {}), ...(compactFirst ? { compactFirst: true } : {}), + ...(pinned ? { pinned: true } : {}), + ...(snoozeUntil ? { snoozeUntil } : {}), } const { messages: _m, needsReply: _n, keepUnread: _k, ...meta } = thread // Unsent, Retry and Discard work on what he wrote; a compact-first send carries it in its args. @@ -1653,7 +1677,7 @@ export function threadTitle(t: ChatThread | null | undefined): string { const first = plainRefs(t.firstUserText || (t.summary || t.history?.hasMore ? '' : t.messages.find((m) => m.role === 'user')?.content || '')).replace(/\s+/g, ' ').trim() || plainRefs(t.messages.find((m) => m.role === 'user')?.content || '').replace(/\s+/g, ' ').trim() if (first) return first.length > 48 ? `${first.slice(0, 48)}…` : first - return t.kind === 'temporary' ? 'Temporary chat' : 'New chat' + return t.kind === 'temporary' ? 'Ghost chat' : 'New chat' } /** Sidebar buckets, newest first, the way ChatGPT and T3 group history. */ diff --git a/web/src/chat/types.ts b/web/src/chat/types.ts index 49b4f8c..44676d1 100644 --- a/web/src/chat/types.ts +++ b/web/src/chat/types.ts @@ -322,6 +322,8 @@ export interface ChatThread { /** Hidden in Snoozed until then. A past time that's still set means it woke and hasn't been opened since. */ snoozedUntil?: number snoozedAt?: number + /** Snoozed as he started it (`$snooze`): its replies don't wake it early. Set by the bridge only. */ + snoozeHeld?: boolean /** The agent marked the request finished (mark_chat_done): Settle is offered, and it settles once read. Cleared by his next message. */ doneAt?: number /** @@ -381,6 +383,8 @@ export interface Project { modelSettings?: Partial /** A folder: the top-level project it sits in. */ parentId?: string + /** Put away (Settings → Archive); the lists never carry one. */ + archivedAt?: number fileCount: number chatCount: number createdAt: number @@ -390,6 +394,14 @@ export interface Project { memory?: string } +/** Settings → Archive: an archived project with its folders, or an archived folder on its own. */ +export interface ArchivedProject extends Project { + archivedAt: number + /** A folder's project, by name. */ + parentName?: string | null + folders: { id: string; name: string; icon?: string; archivedAt?: number; chatCount: number }[] +} + export interface ProviderRow { id: string driver: string diff --git a/web/src/chat/useChatDrafts.test.ts b/web/src/chat/useChatDrafts.test.ts index 5a96162..2780388 100644 --- a/web/src/chat/useChatDrafts.test.ts +++ b/web/src/chat/useChatDrafts.test.ts @@ -14,11 +14,13 @@ vi.mock('./store', () => ({ listAnswered: () => 0, openProject: vi.fn(), startTaskDraft: vi.fn(), + createProject: (...args: unknown[]) => createProject(...args), projectById: () => undefined, })) vi.mock('./api', () => ({ holdUploads: vi.fn(async () => ({ held: [], missing: [] })), deleteUpload: vi.fn() })) vi.mock('../toast', () => ({ pushToast: vi.fn(), pushError: vi.fn() })) const createTask = vi.fn() +const createProject = vi.fn() vi.mock('../work/state', () => ({ taskHome: () => null, createTask: (...args: unknown[]) => createTask(...args) })) const { useChatDrafts } = await import('./useChatDrafts') @@ -101,3 +103,46 @@ describe('$task: a task made in the composer', () => { expect(store.startTaskDraft).not.toHaveBeenCalled() }) }) + +describe('$ghost and a new folder, picked from the `$` menu', () => { + const withKind = (setDraftKind: (k: 'regular' | 'temporary') => void, scope?: { id: string }) => renderHook(() => useChatDrafts({ + activeId: null, active: null, scopeProject: scope as any, draftTaskId: null, draftKind: 'regular', setDraftKind, + composer: { current: null }, slot: '', visible: false, editing: false, onEditFiles: () => {}, + })).result.current + + it('$ghost moves the words to a ghost chat’s draft at Home', () => { + fake.threads = [] + fake.projects = [{ id: 'acme' }] + const set = vi.fn() + const here = drafts.keyAt({ kind: 'project', id: 'acme' }) + drafts.write(here, { text: 'x' }, { place: { kind: 'project', id: 'acme' } }) + withKind(set, { id: 'acme' }).pickDestination({ kind: 'ghost', key: 'ghost', name: 'Ghost chat' }, 'just between us', 0) + expect(set).toHaveBeenLastCalledWith('temporary') + const ghost = drafts.get().drafts[drafts.keyAt({ kind: 'home' }, true)] + expect(ghost?.text).toBe('just between us') + expect(ghost?.temporary).toBe(true) + expect(drafts.get().drafts[here]).toBeUndefined() + fake.projects = [] + }) + + it('a new folder is made, then the words move into it', async () => { + fake.threads = [] + const home = drafts.keyAt({ kind: 'home' }) + drafts.write(home, { text: 'x' }, { place: { kind: 'home' } }) + createProject.mockResolvedValueOnce({ id: 'tax', name: 'Tax returns' }) + fake.projects = [{ id: 'tax' }] + withKind(() => {}).pickDestination({ kind: 'new-folder', key: 'new-project', name: 'Tax returns' }, 'sort the 1099s', 0) + await vi.waitFor(() => expect(drafts.get().drafts[drafts.keyAt({ kind: 'project', id: 'tax' })]?.text).toBe('sort the 1099s')) + expect(createProject).toHaveBeenLastCalledWith({ name: 'Tax returns' }, { open: false }) + fake.projects = [] + }) + + it('a folder the bridge refuses leaves the words where they were', async () => { + const home = drafts.keyAt({ kind: 'home' }) + drafts.write(home, { text: 'x' }, { place: { kind: 'home' } }) + createProject.mockRejectedValueOnce(new Error('nope')) + withKind(() => {}).pickDestination({ kind: 'new-folder', key: 'new-folder:acme', name: 'Receipts', parent: { id: 'acme' } as any }, 'keep me', 0) + await vi.waitFor(() => expect(createProject).toHaveBeenLastCalledWith({ name: 'Receipts', parentId: 'acme' }, { open: false })) + expect(drafts.get().drafts[home].text).toBe('keep me') + }) +}) diff --git a/web/src/chat/useChatDrafts.ts b/web/src/chat/useChatDrafts.ts index 3b759f3..7b980f5 100644 --- a/web/src/chat/useChatDrafts.ts +++ b/web/src/chat/useChatDrafts.ts @@ -3,7 +3,7 @@ // follow-up and a discarded unsent message. import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import type React from 'react' -import { getState, openProject, startTaskDraft, useChat } from './store' +import { createProject, getState, openProject, startTaskDraft, useChat } from './store' import { draftKeyAt, placeKey } from './drafts' import { arrive, keepEdit as keepEditIn, ownedBy, placeFor, placeOfThread, returnFollowUp, returnUnsent, takeForSend as takeOut, trayOf, writeTray, @@ -13,7 +13,7 @@ import { drafts, useDraftState, useMissingUploads, setShownDraft, takeOpenedDraf import { placeAfter, type Destination } from './destinations' import { createTask, taskHome } from '../work/state' import type { NewTaskFields } from './newTask' -import { pushToast } from '../toast' +import { pushError, pushToast } from '../toast' import type { ComposerHandle, FollowUpPayload } from './Composer' import type { Attachment, ChatThread, Project } from './types' @@ -74,9 +74,10 @@ export function useChatDrafts({ activeId, active, scopeProject, draftTaskId, dra useEffect(() => { setShownDraft(visible && !activeId ? draftKey : null) }, [visible, activeId, draftKey]) // --- moving a new chat's draft (`$`, "Start in") ----------------------------- - function placeDraft(next: { taskId: string | null; projectId: string | null }) { - setDraftKind('regular') - const key = drafts.move(draftKey, placeFor(next, getState().projects)) + /** `ghost`: it becomes a ghost chat's draft, which is Home's (`next` is Home then). */ + function placeDraft(next: { taskId: string | null; projectId: string | null }, ghost = false, from = draftKey) { + setDraftKind(ghost ? 'temporary' : 'regular') + const key = drafts.move(from, placeFor(next, getState().projects), ghost) if (drafts.get().drafts[key]) { openDraft(key); return } if (next.taskId) startTaskDraft(next.taskId, next.projectId) else openProject(next.projectId) @@ -91,7 +92,28 @@ export function useChatDrafts({ activeId, active, scopeProject, draftTaskId, dra /** `$`: the words, less the `$…`, and the tray's files go to the picked place. */ const pickDestination = (d: Destination, text: string) => { drafts.write(draftKey, { text }, at) - placeDraft(placeAfter(d, { taskId: draftTaskId, projectId: scopeProject?.id ?? null }, taskHome)) + if (d.kind === 'new-folder') { void newFolder(d); return } + placeDraft(placeAfter(d, { taskId: draftTaskId, projectId: scopeProject?.id ?? null }, taskHome), d.kind === 'ghost') + requestAnimationFrame(() => composer.current?.focus()) + } + + /** + * `$tax-returns` where nothing has that name: make the folder (or project), then + * move the draft there, keeping a task it was being started for. If he moved on + * while it was being made, the folder is made and he stays where he is. + */ + async function newFolder(d: Extract) { + const key = draftKey + const taskId = draftTaskId + let project: Project + try { + project = await createProject({ name: d.name, ...(d.parent ? { parentId: d.parent.id } : {}) }, { open: false }) + } catch (e: any) { + pushError(`Couldn't make “${d.name}”: ${e?.message || e}`) + return + } + if (keyRef.current !== key) { pushToast(`Made “${project.name}”.`, 'info'); return } + placeDraft({ taskId, projectId: project.id }, false, key) requestAnimationFrame(() => composer.current?.focus()) } diff --git a/web/src/components/ChatView.tsx b/web/src/components/ChatView.tsx index f410a25..2f755f0 100644 --- a/web/src/components/ChatView.tsx +++ b/web/src/components/ChatView.tsx @@ -44,7 +44,9 @@ import { useChatPresence } from '../chat/presence' import { useViewing } from '../chat/onScreen' import { contextVersion, subscribeContext, takeContext } from '../chat/pendingContext' import { TI } from '../chat/ui' -import { IconArrowDown, IconPaperclip } from '../chat/icons' +import { IconArrowDown, IconPaperclip, IconPinned, IconX, IconZzz } from '../chat/icons' +import { settingsForPick } from '../chat/models' +import type { Destination } from '../chat/destinations' import HandoffBar from '../chat/HandoffBar' import type { Attachment, ChatMessage, ModelSettings, QueuedMessage } from '../chat/types' import '../chat/chat.css' @@ -72,6 +74,9 @@ const STARTERS: { text: string; fill?: boolean }[] = [ ] // One empty list for a chat with nothing to draw, so effects keyed on it stay put. +/** `$pin` and `$snooze` picked for a new chat's draft (`key`), sent with its first message. */ +interface StartOptions { key: string; pinned?: boolean; snooze?: { until: number; when: string } } + const NO_MESSAGES: ChatMessage[] = [] /** The Totems tab, on one totem's settings when given its id. */ @@ -124,6 +129,8 @@ export default function ChatView({ onAuthError, visible = true, onOpenMenu, pane const [draftPick, setDraftPick] = useState(null) // A new project chat can start without the project's instructions, memory and files. const [draftContextOff, setDraftContextOff] = useState(false) + // `$pin` and `$snooze` for the new chat on screen: sent with its first message. + const [startOpts, setStartOpts] = useState(null) // The project the panel is showing. A new chat here starts in it, on its default model. const scopeId = useChat((s) => s.projectId) const scopeProject = useChat((s) => s.projects.find((p) => p.id === s.projectId)) @@ -500,10 +507,23 @@ export default function ChatView({ onAuthError, visible = true, onOpenMenu, pane function onSend({ text, attachments }: { text: string; attachments: Attachment[] }) { const onRefused = takeForSend() - const id = send({ threadId: activeId, text, attachments, kind: !active && draftTaskId ? 'regular' : kind, provider: draft.provider, modelSettings: draft.modelSettings, projectId: active ? undefined : project?.id, projectContextOff: !active && !!project && draftContextOff, taskId: active ? undefined : draftTaskId || undefined, compactFirst: compactTokens != null && !keepHistory, onRefused }) + const opts = shownOpts + const id = send({ + threadId: activeId, text, attachments, kind: !active && draftTaskId ? 'regular' : kind, provider: draft.provider, modelSettings: draft.modelSettings, + projectId: active ? undefined : project?.id, projectContextOff: !active && !!project && draftContextOff, taskId: active ? undefined : draftTaskId || undefined, + compactFirst: compactTokens != null && !keepHistory, pinned: opts?.pinned, snoozeUntil: opts?.snooze?.until, onRefused, + }) setKeepHistory(false) if (id !== activeId) { setDraftPick(null) + setStartOpts(null) + // `$snooze`: it is answered out of sight, and he stays on a new chat. + if (opts?.snooze) { + const said = text.replace(/\s+/g, ' ').trim() + pushToast(`Sent${said ? ` “${said.length > 40 ? `${said.slice(0, 40)}…` : said}”` : ''}. Back ${opts.snooze.when}.`, 'info', { action: { label: 'Open now', onClick: () => { wakeThread(id); setActive(id) } } }) + requestAnimationFrame(() => composer.current?.focus()) + return + } setActive(id) } requestAnimationFrame(glideToBottom) @@ -613,7 +633,31 @@ export default function ChatView({ onAuthError, visible = true, onOpenMenu, pane displace: (text) => setInput(input.trim() ? `${input.replace(/\s+$/, '')}\n${text}` : text), }) - const destinations = { projectId: scopeProject?.id ?? null, taskId: draftTaskId, onPick: pickDestination, onNewTask: newTask, draftKey } + // Options picked with `$` belong to the draft they were picked in. + const shownOpts = !active && startOpts?.key === draftKey ? startOpts : null + const onStartOption = (d: Extract) => setStartOpts((o) => ({ + ...(o?.key === draftKey ? o : {}), key: draftKey, + ...(d.kind === 'pin' ? { pinned: true } : { snooze: { until: d.until, when: wakeDescription(d.until, Date.now()) } }), + })) + const onModel = (d: Extract) => { + const s = getState() + changeModel({ provider: d.provider.id, modelSettings: settingsForPick(d.provider, d.modelId, s.defaultProvider, s.defaultModel) }) + } + const destinations = { projectId: scopeProject?.id ?? null, taskId: draftTaskId, onPick: pickDestination, onNewTask: newTask, onModel, onStartOption, pinned: !!shownOpts?.pinned, draftKey } + const optsEl = shownOpts && (shownOpts.pinned || shownOpts.snooze) ? ( +
+ {shownOpts.pinned && ( + Pinned + + + )} + {shownOpts.snooze && ( + Back {shownOpts.snooze.when} + + + )} +
+ ) : null const missingEl = missingFiles.length > 0 && !editing ? (
@@ -647,11 +691,11 @@ export default function ChatView({ onAuthError, visible = true, onOpenMenu, pane followUp={followUp} queueEdit={editing ? { onSave: saveQueueEdit } : undefined} onResume={!busy && active?.queueHeld && queue.length && activeId ? () => { void updateQueue(activeId, { action: 'resume' }) } : undefined} - above={
{missingEl}{queueEl}
} + above={
{missingEl}{optsEl}{queueEl}
} onVoice={() => setVoice(true)} busy={busy} autoFocus={visible} - placeholder={waitingApproval ? DECLINE_PLACEHOLDER : !active && draftTaskId ? 'What should we do about it?' : temporary ? 'Temporary chat — gone at midnight' : project && empty ? `New chat in ${project.name}` : 'Ask Totem anything'} + placeholder={waitingApproval ? DECLINE_PLACEHOLDER : !active && draftTaskId ? 'What should we do about it?' : temporary ? 'Ghost chat — gone at midnight' : project && empty ? `New chat in ${project.name}` : 'Ask Totem anything'} allowCommands={!temporary} destinations={active ? undefined : destinations} maxUploadBytes={caps?.maxUploadBytes} @@ -721,7 +765,7 @@ export default function ChatView({ onAuthError, visible = true, onOpenMenu, pane totemsCrumb={!!(active?.totemId || active?.members?.length)} onTotems={goTotems} thread={active && !empty ? active : undefined} - title={!project || (active && !empty) ? (active && !empty ? threadTitle(active) : temporary ? 'Temporary chat' : 'New chat') : undefined} + title={!project || (active && !empty) ? (active && !empty ? threadTitle(active) : temporary ? 'Ghost chat' : 'New chat') : undefined} retitling={retitling} onRetitle={active && !empty ? () => regenerateTitle(active.id) : undefined} totem={active?.totemId ? { id: active.totemId, job: totemDir.get(active.totemId) } : undefined} @@ -760,8 +804,8 @@ export default function ChatView({ onAuthError, visible = true, onOpenMenu, pane ) : empty ? (
-

{temporary ? 'Temporary chat' : greeting(ownerName)}

- {temporary &&

This chat won’t be kept after midnight.

} +

{temporary ? 'Ghost chat' : greeting(ownerName)}

+ {temporary &&

Not kept: gone at midnight, or as soon as you settle it.

} {providerState && providerState !== 'ready' && providerState !== 'unknown' && (

{providerById(choice.provider)?.name} is {providerState === 'missing' ? 'not installed on this machine' : providerState === 'logged-out' ? 'signed out' : 'not responding'}. Pick another account above{caps?.providers?.[choice.provider]?.fix ? `, or run ${caps.providers[choice.provider].fix}` : ''}.

)} diff --git a/web/src/components/SettingsView.tsx b/web/src/components/SettingsView.tsx index 6fd3175..f09b012 100644 --- a/web/src/components/SettingsView.tsx +++ b/web/src/components/SettingsView.tsx @@ -11,6 +11,7 @@ import IconChartBar from '@tabler/icons-react/dist/esm/icons/IconChartBar.mjs' import IconSparkles from '@tabler/icons-react/dist/esm/icons/IconSparkles.mjs' import IconPlugConnected from '@tabler/icons-react/dist/esm/icons/IconPlugConnected.mjs' import IconCircleCheck from '@tabler/icons-react/dist/esm/icons/IconCircleCheck.mjs' +import IconArchive from '@tabler/icons-react/dist/esm/icons/IconArchive.mjs' import IconShieldLock from '@tabler/icons-react/dist/esm/icons/IconShieldLock.mjs' import IconActivity from '@tabler/icons-react/dist/esm/icons/IconActivity.mjs' import IconSearch from '@tabler/icons-react/dist/esm/icons/IconSearch.mjs' @@ -26,6 +27,7 @@ import { searchSettings, type SettingsSearchItem } from './settings/searchIndex' import GeneralPane from './settings/GeneralPane' import AppearancePane from './settings/AppearancePane' import SecurityPane from './settings/SecurityPane' +import ArchivePane from './settings/ArchivePane' import ChatSettings from './ChatSettings' import VoiceSettings from './VoiceSettings' import NotificationsSettings from './NotificationsSettings' @@ -65,6 +67,7 @@ const ICONS: Record[0]['icon']> = { skills: IconSparkles, connections: IconPlugConnected, tasks: IconCircleCheck, + archive: IconArchive, security: IconShieldLock, logs: IconActivity, } @@ -154,6 +157,7 @@ function Pane({ id, onAuthError, onDisconnect, onNavigate }: { case 'skills': return case 'connections': return case 'tasks': return + case 'archive': return case 'security': return case 'logs': return } diff --git a/web/src/components/settings/ArchivePane.tsx b/web/src/components/settings/ArchivePane.tsx new file mode 100644 index 0000000..ff09b09 --- /dev/null +++ b/web/src/components/settings/ArchivePane.tsx @@ -0,0 +1,78 @@ +import React, { useCallback, useEffect, useRef, useState } from 'react' +import { AuthError } from '../../api' +import { listArchivedProjects } from '../../chat/api' +import ProjectIcon from '../../chat/ProjectIcon' +import { restoreProject } from '../../chat/store' +import type { ArchivedProject } from '../../chat/types' +import { when } from '../../chat/ui' +import { pushError, pushSuccess } from '../../toast' +import { SettingsPage, SettingsRow, SettingsSection } from './ui' + +// Settings → Archive: what was put away, and the way back. Only chat projects and +// folders for now (chat/projects.mjs `archivedAt`); nothing in Totem deletes one. +// An archived project carries its folders; a folder archived on its own is listed +// by itself, under its project's name. + +const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}` + +export function archiveLine(p: ArchivedProject): string { + const parts = [p.parentId ? `Folder in ${p.parentName || 'a project'}` : 'Project'] + if (p.folders.length) parts.push(`${plural(p.folders.length, 'folder')} (${p.folders.map((f) => f.name).join(', ')})`) + parts.push(plural(p.chatCount, 'chat')) + if (p.fileCount) parts.push(plural(p.fileCount, 'file')) + parts.push(`archived ${when(p.archivedAt)}`) + return parts.join(' · ') +} + +export default function ArchivePane({ onAuthError }: { onAuthError: () => void }) { + const [items, setItems] = useState(null) + const [error, setError] = useState('') + const [busy, setBusy] = useState(null) + // The parent's callback changes identity on every render. + const authError = useRef(onAuthError) + authError.current = onAuthError + const load = useCallback(() => { + listArchivedProjects() + .then((r) => { setItems(r.projects); setError('') }) + .catch((e) => { if (e instanceof AuthError) authError.current(); else setError(e instanceof Error ? e.message : String(e)) }) + }, []) + useEffect(() => { load() }, [load]) + + async function restore(p: ArchivedProject) { + setBusy(p.id) + try { + await restoreProject(p.id) + setItems((list) => (list || []).filter((x) => x.id !== p.id)) + pushSuccess(`Restored ${p.name}`) + } catch (e: any) { + if (e instanceof AuthError) authError.current() + else pushError(`Couldn't restore it: ${e.message}`) + } finally { + setBusy(null) + load() + } + } + + return ( + + + {!items ? ( + + ) : !items.length ? ( + + ) : items.map((p) => ( + {p.name}} + description={archiveLine(p)} + control={} + /> + ))} + + + ) +} diff --git a/web/src/components/settings/searchIndex.ts b/web/src/components/settings/searchIndex.ts index 6eca831..1d7a806 100644 --- a/web/src/components/settings/searchIndex.ts +++ b/web/src/components/settings/searchIndex.ts @@ -90,6 +90,9 @@ const ENTRIES: Partial> = { ['task-sheet', 'Task sheet', 'Tasks', 'spreadsheet action items sheet google drive read-only assignees'], ['task-retention', 'Retention', 'Tasks', 'archive completed finished recycle bin purge empty delete days time'], ], + archive: [ + ['archived-folders', 'Archived folders', 'Archive', 'archive restore unarchive bring back folders projects deleted removed hidden'], + ], security: [ ['approval-code', 'Approval code', 'Security', 'approve send second factor'], ['change-login', 'Change password', 'Sign-in', 'passphrase credentials'], diff --git a/web/src/components/settings/sections.ts b/web/src/components/settings/sections.ts index fd047e6..9d520f0 100644 --- a/web/src/components/settings/sections.ts +++ b/web/src/components/settings/sections.ts @@ -4,7 +4,7 @@ export const SETTINGS_GROUPS = [ { heading: null, items: ['general', 'appearance', 'chat', 'voice', 'notifications', 'shortcuts'] }, { heading: 'AI', items: ['providers', 'usage', 'skills'] }, - { heading: 'Data', items: ['connections', 'tasks'] }, + { heading: 'Data', items: ['connections', 'tasks', 'archive'] }, { heading: 'Account', items: ['security', 'logs'] }, ] as const @@ -24,6 +24,7 @@ export const SETTINGS_LABELS: Record = { skills: 'Skills', connections: 'Connections', tasks: 'Tasks', + archive: 'Archive', security: 'Security', logs: 'Activity', } diff --git a/web/src/components/settings/settings.css b/web/src/components/settings/settings.css index 4242ea0..9a7165e 100644 --- a/web/src/components/settings/settings.css +++ b/web/src/components/settings/settings.css @@ -295,3 +295,8 @@ /* A skill's command badge stays on one line; the title gives way instead. */ .stg .skill-command { white-space: nowrap; flex: none; } .stg .skill-card strong, .stg .skill-card h3 { min-width: 0; overflow: hidden; text-overflow: ellipsis; } + +/* Archive: an archived project's name beside its own icon or picture. */ +.stg .stg-archive-name { display: inline-flex; align-items: center; gap: 8px; min-width: 0; } +.stg .stg-archive-name .vc-proj-icon { flex: none; color: var(--muted); } +.stg .stg-archive-name .vc-proj-img { border-radius: 4px; object-fit: cover; } diff --git a/web/src/settingsSections.test.ts b/web/src/settingsSections.test.ts index a56bbab..147caa1 100644 --- a/web/src/settingsSections.test.ts +++ b/web/src/settingsSections.test.ts @@ -61,6 +61,7 @@ describe('settings search', () => { skills: ['components/SkillsView.tsx'], connections: ['components/McpSettingsView.tsx', 'components/ClaudeToolsPanel.tsx', 'components/DataConnectionsPanel.tsx', 'sources/SourceHealthPanel.tsx'], tasks: ['components/TaskSettings.tsx'], + archive: ['components/settings/ArchivePane.tsx'], security: ['components/settings/SecurityPane.tsx'], logs: ['components/LogsView.tsx'], }