From ec7d787424873f4dc7cd2517529fd9f856c20a5b Mon Sep 17 00:00:00 2001 From: ehonis Date: Tue, 24 Nov 2026 23:45:29 -0500 Subject: [PATCH] iPhone: full-screen glass drawer, no Totems row, updates without a cold start Published from the private repository by oss-sync. - iPhone: full-screen glass drawer, no Totems row, updates without a cold start 31 files changed, 567 insertions(+), 115 deletions(-) --- AGENTS.md | 2 +- docs/chat.md | 4 +- mobile/AGENTS.md | 34 ++++- mobile/src/app/(app)/_layout.tsx | 21 ++- mobile/src/app/_layout.tsx | 9 +- mobile/src/app/chat/shelf.tsx | 2 +- mobile/src/features/chat/ChatScreen.tsx | 3 + mobile/src/features/chat/ChatsNav.tsx | 44 ++++-- mobile/src/features/chat/Composer.tsx | 4 + mobile/src/features/chat/InboxCardRow.tsx | 4 + mobile/src/features/chat/Message.tsx | 4 + mobile/src/features/chat/QuestionsPanel.tsx | 4 + mobile/src/features/chat/ShelfSheet.tsx | 9 +- mobile/src/features/chat/appDrafts.ts | 21 ++- mobile/src/features/chat/dictation.ts | 3 + mobile/src/features/chat/totemReport.ts | 5 + mobile/src/features/inbox/InboxScreen.tsx | 4 + mobile/src/features/journal/RecorderPanel.tsx | 6 +- mobile/src/features/journal/useRecorder.ts | 4 + .../src/features/overview/OverviewScreen.tsx | 17 ++- mobile/src/features/voice/VoiceScreen.tsx | 3 + mobile/src/shell/AppDrawer.tsx | 116 ++++++++++------ mobile/src/shell/Screen.tsx | 55 ++++---- mobile/src/shell/drawerKeyboard.ts | 2 +- mobile/src/shell/otaPolicy.test.mjs | 54 ++++++++ mobile/src/shell/otaPolicy.ts | 56 ++++++++ mobile/src/shell/otaUpdates.tsx | 130 ++++++++++++++++++ mobile/src/shell/quickActions.ts | 11 +- mobile/src/theme.ts | 2 - mobile/src/ui/glass.tsx | 43 ++++++ mobile/src/ui/toastFloor.ts | 6 +- 31 files changed, 567 insertions(+), 115 deletions(-) create mode 100644 mobile/src/features/chat/totemReport.ts create mode 100644 mobile/src/shell/otaPolicy.test.mjs create mode 100644 mobile/src/shell/otaPolicy.ts create mode 100644 mobile/src/shell/otaUpdates.tsx create mode 100644 mobile/src/ui/glass.tsx diff --git a/AGENTS.md b/AGENTS.md index 9923a7c..1626f0c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -78,7 +78,7 @@ open-ended work. The default provider and model come from Settings → Providers | Away spans | `away/`, `web/src/away.ts`, `web/src/components/AwayEditor.tsx`, `mobile/src/features/overview/AwaySheet.tsx` | Trips and days off in `data/away.json` (`AWAY_FILE`): inclusive local day keys, edited by the owner from the Overview's schedule card (`/api/away`). Every prompt's date block marks away days in its 14-day table and names the current and coming spans, capped at five, and always says to propose a trip found in email (`away/grounding.mjs`); the calendar draws them as a band; a queued notification whose category's `away` column is `'hold'` waits one night at a time (`heldBy: 'away'`) and goes out the first morning the owner is back, older digest copies dropped and nothing distinct lost (`away/hold.mjs` through `gate.addHold`, `notify/categories.mjs`). Agents get `totem_away_list` and `totem_away_propose` (`away__*` in the gateway): propose stages an `away` inbox item once per set of dates, only the dashboard accepts it, and there is no write tool. Agents never edit `data/away.json`; the store re-reads it when it changes on disk and drops rows that fail validation. `docs/away.md`. | | Voice journal | `journal/`, `web/src/journal/` | Record in the browser, transcribe on the box with whisper.cpp, digest into the notes repo after a grace period. `docs/journal.md`. | | Notifications | `notify/`, `web/public/sw.js` | Web Push (RFC 8291/8292 on `node:crypto`) and APNs for the native iPhone app (`notify/apns.mjs`, `APNS_*`; a chat's notification is taken back off the phone by a silent push once the chat is read anywhere, `notifier.dismiss`), a due-queue drained on the job tick, digests, feed scan, quota nudges. On an away day a queued notification whose category's `away` column is `'hold'` waits until the owner is back (`createAwayHold` in `away/hold.mjs`, registered through `gate.addHold`; a hold's `tag` stays on the entry as `heldBy`, which skips the missed-delivery cutoff and is claimed after everything never held; a repeat is suppressed when first held, by `admit(item, { reserve: false })`, not after the earlier copy's window runs out). Every push passes the dedupe gate in `notifier.deliver` (`notify/dedupe.mjs`): a key already sent inside its window (a quota fact's key is its reset window, persisted across restarts; keyless repeats only in categories with `textDedupe`) or a story already told (only items carrying `story`: canonical link, or headlines with the same lead model and version, no event kind the earlier lacks, shared details and real word overlap, within 48 h; an optional background model check for close calls, Claude or Codex only, that fails open) is counted on the first notification instead of pushed, and logged. Sends are reserved, then committed only if they reached the bell or a phone. Settings → Notifications › Duplicates; `gate.addHold(fn)` keeps a queued one waiting. Habits get no completion nudges (no "streak ends tonight"): they can be logged for past days, so the notifier drops any still queued (`isRetiredNudge`). `docs/notifications.md`. | -| Totems | `totems/`, the "Totems" block in `bridge.mjs`, `web/src/components/TotemsView.tsx`, `web/src/totems/` | On the rail after Chat since 1.1 (`TOTEMS_TAB_DEF` in `App.tsx`; its badge counts totem chats with an unread report), and from a totem chat's gear. Laid out like a project's page: a composer that hands a description to the builder, then flush rows (drafts, group chats, totems, and a folded shelf of the built-ins that are off): a row opens the totem's chat (its runs are posted there), the gear its page, whose settings are drawn with the Settings dialog's sections and rows (`web/src/totems/fields.tsx`, shared with the builder's draft); the totem's chat header has a play button that runs it now. Neither the web's chats panel nor the iPhone drawer lists totem chats; the drawer has a Totems row under Overview with the same dot. Any chat can bring totems in: `totems__list`/`totems__ask`/`totems__wait`/`totems__invite` run a totem on its own model with its memory and tools, and its answer shows under its name (`web/src/chat/totemReply.ts`); a chat with `members` is a group chat its agent hosts. On by default (`totemsInChat`, Settings → Chat). Standing agents over the job store: every job is a totem (no second scheduler). A totem's runs keep the standard job limits unless its Full access switch is on (`access: 'full'`: bypassPermissions / danger-full-access, since nothing can approve a command mid-run), and write their memory and their chat's outputs folder. Agent totems keep `data/totems//memory.md` (pasted into each run and ask, a fresh session that needs its state; only named in the totem's chat, which reads it on demand), end runs with `NOTIFY:`/`QUIET`, post runs to their chat `totem-`, and get cheapest-first model recommendations from the builder or any model from the chat picker (`modelsOnly`). The builder asks scoping questions in a chat beside the draft and revises it on each reply; an unfinished design is a draft (`totems/drafts.mjs`, `data/totem-drafts/`). A totem can wake on a watch (git branch or web page) instead of a schedule; the built-in "Deploy Totem" pulls, rebuilds and restarts the bridge when main moves. Any chat can propose a change (Accept card). Replaced Studio. `docs/totems.md`. | +| Totems | `totems/`, the "Totems" block in `bridge.mjs`, `web/src/components/TotemsView.tsx`, `web/src/totems/` | On the rail after Chat since 1.1 (`TOTEMS_TAB_DEF` in `App.tsx`; its badge counts totem chats with an unread report), and from a totem chat's gear. Laid out like a project's page: a composer that hands a description to the builder, then flush rows (drafts, group chats, totems, and a folded shelf of the built-ins that are off): a row opens the totem's chat (its runs are posted there), the gear its page, whose settings are drawn with the Settings dialog's sections and rows (`web/src/totems/fields.tsx`, shared with the builder's draft); the totem's chat header has a play button that runs it now. Neither the web's chats panel nor the iPhone drawer lists totem chats; on the iPhone the Totems page opens from the Overview's app row, not the drawer. Any chat can bring totems in: `totems__list`/`totems__ask`/`totems__wait`/`totems__invite` run a totem on its own model with its memory and tools, and its answer shows under its name (`web/src/chat/totemReply.ts`); a chat with `members` is a group chat its agent hosts. On by default (`totemsInChat`, Settings → Chat). Standing agents over the job store: every job is a totem (no second scheduler). A totem's runs keep the standard job limits unless its Full access switch is on (`access: 'full'`: bypassPermissions / danger-full-access, since nothing can approve a command mid-run), and write their memory and their chat's outputs folder. Agent totems keep `data/totems//memory.md` (pasted into each run and ask, a fresh session that needs its state; only named in the totem's chat, which reads it on demand), end runs with `NOTIFY:`/`QUIET`, post runs to their chat `totem-`, and get cheapest-first model recommendations from the builder or any model from the chat picker (`modelsOnly`). The builder asks scoping questions in a chat beside the draft and revises it on each reply; an unfinished design is a draft (`totems/drafts.mjs`, `data/totem-drafts/`). A totem can wake on a watch (git branch or web page) instead of a schedule; the built-in "Deploy Totem" pulls, rebuilds and restarts the bridge when main moves. Any chat can propose a change (Accept card). Replaced Studio. `docs/totems.md`. | | Jobs | `jobs/` | Timezone-aware schedules (`daily`, `weekly`, `interval`, `window`), watch triggers over one or more git branches or pages, checked without AI (`jobs/triggers.mjs`), and `data/jobs.json`. One 30-second tick in `bridge.mjs` runs jobs, checks watches and drains notifications. A job id Totem stopped shipping goes in the store's `retiredIds` and is dropped on read. `docs/jobs.md`. | | Skills | `skills/` | Every prompt as an editable `SKILL.md` with `{{variables}}`. Generic seeds in `skills/seeds/` are copied into `data/skills/` once. Chat cites a skill with `/name` anywhere in a message; the owner's Claude Code/Codex/Cursor skills are found read-only by `skills/agent-skills.mjs` and cited the same way. `docs/skills.md`. The `change-totem` seed is the steps for changing Totem itself from a chat; the guardrails are in code (next row), not in the skill. | | Changing Totem from a chat | `dev/change.mjs`, `change_start`/`change_finish` on each chat run's `/agent-mcp` (`changeTools` in `bridge.mjs`), `web/src/chat/ChangeCard.tsx` | "Build me a page for X" ends as a pull request card, never as edits to the checkout Totem runs from. Offered only to Full-access chat runs. `change_start` fetches `origin/main` into `refs/totem-change/base` (never moving the live `origin/main`) and makes a worktree under `CHANGE_WORKTREES_DIR` (default `~/.totem-changes`; the path is checked before anything is created, and refused inside or around the live checkout or over `AGENT_CWD`/cwd), linking `node_modules`. `change_finish` first checks every field of its record (`data/changes.json`, denied to Claude's file tools) against git and GitHub, then stages the worktree into a tree and checks it as one diff against the base, reading git's output in full (anything that would not fit is refused; at most 500 files, 5 MB of diff; diffs with `--no-ext-diff --no-textconv` and fixed prefixes): paths are case-folded and must be ASCII (macOS deploys), and it refuses data/env/secrets/`.git`/`node_modules`, package-manager and git config files, symlinks and submodules, case collisions, protected files (`auth/`, `logs/approval*`, `.github/`, the rule-enforcing files in `PROTECTED_FILES`, the flow itself), `bridge.mjs` lines in `GUARDED_LINE`, changed package `scripts`, `.gitignore` lines about `node_modules`, and any secret from Totem's credential files (`data/*-tokens.json`, `auth.json`, `ai-settings.json`, `integrations.json`, the MCP manifest's env, `BRIDGE_SECRET`) or a known token shape anywhere in a changed file's whole content (a tripwire for accidents, not a boundary). It then makes one fresh commit of that tree on the last push, runs `npm test` (retried once) and the web build with a throwaway `HOME` and no git config or tokens, refuses if they moved HEAD or wrote tracked files or the live checkout got dirty (by content hash), and pushes exactly that SHA to `totem-change/*`. Stop or a timeout kills the checks' whole process tree. It opens the PR with `gh`, saves it at once, and posts a `change-pr` card whose CI state is a snapshot at push. A merged or closed PR starts a fresh worktree, and so does a record that no longer checks out (the remote branch moved); every git call has filters and attribute files switched off, and `.git/info/attributes` is refused; `cleanup()` (boot, then every 6 h) removes those and ones abandoned 14 days. No merge path anywhere. Off unless the owner sets `CHANGE_FLOW_ENABLED=true` (`changeFlowEnabled`), and only when Totem runs from a git checkout. `docs/change-totem.md`. | diff --git a/docs/chat.md b/docs/chat.md index 437d870..059628e 100644 --- a/docs/chat.md +++ b/docs/chat.md @@ -1649,8 +1649,8 @@ search box of their own: the Search tab finds any chat, parked or not. The iPhone app draws no Snoozed or Settled shelf in its drawer, which has one scroll: they are a button each with a count (a dot when the open chat is on it) in the drawer's foot -beside Settings, for whatever the list is scoped to, and a button opens a three-quarter -sheet of those chats with a switch between the two (`mobile/src/features/chat/ShelfSheet.tsx`). The app shows no toasts but errors, +beside Settings, for whatever the list is scoped to (liquid glass on iOS 26, melted into one +shape), and a button opens a three-quarter glass sheet of those chats with a switch between the two (`mobile/src/features/chat/ShelfSheet.tsx`). The app shows no toasts but errors, 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 diff --git a/mobile/AGENTS.md b/mobile/AGENTS.md index e2090e3..47b042f 100644 --- a/mobile/AGENTS.md +++ b/mobile/AGENTS.md @@ -92,10 +92,14 @@ Use `npx expo install ` for dependencies so versions match the SDK. on the step `shell/drawerKeyboard.ts` names. The composer rides the keyboard over the drawer, so a keyboard left up covered half of it. KeyboardController resigns whatever holds the keyboard, not only the input React Native's focus tracker knows, which is all `Keyboard.dismiss()` blurs. A new way to open the drawer needs nothing more. -- `src/shell/` is the frame: `AppDrawer` (the sidebar: Search, which opens the Search page, by the wordmark; Overview, Totems - (a dot while a totem's report waits; totems' chats are not in the list), the Productivity tools as a - 4 + 3 grid the heading's chevron folds away, remembered per device, then the chats, all in one scroll; a pinned foot - with the list's Snoozed and Settled buttons, which open `features/chat/ShelfSheet.tsx`, and New chat and Settings on the right), `Screen` (top bar with the AI usage pill on the right, where the web phone bar has new chat; plus the voice/new-chat buttons), `nav.ts` (`navigateTo` takes the +- `src/shell/` is the frame: `AppDrawer` (the sidebar, the whole screen wide, with a close button in its head: Search, + which opens the Search page, by the wordmark; Overview (a dot while a totem's report waits, as on the Overview's + Totems tile), the Productivity tools as a + 4 + 3 grid the heading's chevron folds away, remembered per device, then the chats, all in one scroll; a foot floating + over the scroll's end with the list's Snoozed and Settled buttons, which open `features/chat/ShelfSheet.tsx`, and New + chat and Settings on the right; no Totems row: totems' chats are not in the list, and the Totems page opens from the + Overview's app row), `Screen` (top bar with the AI usage pill on the right, where the web phone bar has new chat; plus + the corner new-chat button; voice mode starts from the home-screen quick action, not a corner button), `nav.ts` (`navigateTo` takes the web's tab/app ids, `openChat`, `newChat`, `startVoice`), `routes.ts` (where each id lands, pure and tested by `routes.test.mjs`), `ToolIcon` (each tool's mark), `quickActions.ts` (home-screen long-press). - `src/app/` holds routes only. `(app)/` is the drawer with one screen per web tab. Pushed screens and sheets @@ -116,6 +120,28 @@ Use `npx expo install ` for dependencies so versions match the SDK. `navigateTo('todos')`, `{ tab: 'productivity', app }`, notification links (`destination.ts`) and the landing-tab preference all go through `routes.ts`. +- **Liquid glass** (`src/ui/glass.tsx`, `expo-glass-effect`, already in the build): the drawer's foot, the corner + new-chat button, the composer and the shelf sheet. `GlassButton` is a pressable glass shape with a solid `fallback` + for iOS before 26, and `GlassGroup` (a `GlassContainer`) melts shapes within `spacing` into one, so neighbouring + buttons read as one piece; keep a row of floating buttons in one group. A sheet is glass when its route uses + `glassSheet` in `src/app/_layout.tsx` (a formSheet over a clear screen, which iOS 26 draws in glass) and its content + is clear too; rows on it pass `glass` to `ThreadItem`, which is clear at rest and takes its solid fill the + frame it starts to move (its swipe progress copied on the UI thread), so the actions never show through its text. +- **Over-the-air updates arrive without a cold start** (`shell/otaUpdates.tsx`, rules in `shell/otaPolicy.ts`): + expo-updates on its own checks only at launch and applies at the next launch, and iOS keeps the app suspended for + days, so a merge once seemed not to reach the phone. Coming back to the foreground checks (at most every 10 minutes) + and fetches an update or a rollback; a fetched one is applied on a return after 30 minutes away, only on the + Overview or an open chat (`safePage`: the pages whose every input saves as it changes or holds the reload; any other + page, sheet or editor may keep edits only in memory), with no input focused (a chat excepted: its drafts are flushed + just before, `onBeforeReload`), and only if nothing lands in the 1.5 s after (a + tapped notification, a quick action calling `noteArrival`, a link that moves the page or chat). Before reloading it + notes the page and chat, and the next launch goes back there (`resumedFromUpdate`) and skips the quick action the + app was first cold-launched from, which the native module never clears. Anything else a reload would lose takes + `holdReload()` while it lasts (voice mode, dictation, a journal take or typed entry, the Overview's ask box, a queued + message or sent message being edited, an inbox card's note, unsent answers to an agent's questions, an edited + LinkedIn draft); a chat not started yet is never reloaded under. An input added to the Overview or the chat screen + that keeps unsent words only in React state takes a hold too; widening `safePage` needs the same audit of that page. A build from + before this code needs two cold starts once to pick it up. - **The drawer's chats** (`features/chat/ChatsNav.tsx`, docs/chat.md → The chats panel): the web chats panel, T3 Code's flat list. Every chat in every project and folder on one list (unsent drafts, Pinned, the chats still in play latest first, then Working), each a card with its place, its status in words and its linked task (`features/work/TaskBadge.tsx`, diff --git a/mobile/src/app/(app)/_layout.tsx b/mobile/src/app/(app)/_layout.tsx index 9cfb9e0..d2a267b 100644 --- a/mobile/src/app/(app)/_layout.tsx +++ b/mobile/src/app/(app)/_layout.tsx @@ -1,7 +1,9 @@ // The signed-in app: the push drawer around every tab (ChatGPT's layout — the -// page slides right to reveal the sidebar, and follows a finger from the edge). +// page slides right to reveal the sidebar, which fills the screen, and follows a +// finger from the edge). import React, { useEffect } from 'react' import { useWindowDimensions } from 'react-native' +import { router } from 'expo-router' import { Drawer, useDrawerProgress, type DrawerContentComponentProps } from 'expo-router/drawer' import { KeyboardController } from 'react-native-keyboard-controller' import { useAnimatedReaction } from 'react-native-reanimated' @@ -13,7 +15,8 @@ import { useQuickActions } from '../../shell/quickActions' import { usePush } from '../../shell/push' import { useAccessReauth } from '../../shell/accessReauth' import { useMorningCheckin } from '../../shell/morningCheckin' -import { navigateTo } from '../../shell/nav' +import { OtaUpdates, takeResumedFromUpdate } from '../../shell/otaUpdates' +import { navigateTo, openChat } from '../../shell/nav' import { PRODUCTIVITY_APPS, TOOL_LABELS } from '../../shell/routes' import { getSettings } from '../../lib/settings' import { colors } from '../../theme' @@ -39,17 +42,26 @@ export default function AppLayout() { // landing tab is one navigation on first mount. (A quick action, handled a tick // later, still wins.) useEffect(() => { + // Just reloaded into an update (shell/otaUpdates.tsx): back to the page and chat he was on. + const resume = takeResumedFromUpdate() + if (resume) { + if (resume.chatId) openChat(resume.chatId) + else if (resume.path !== '/') router.navigate(resume.path as any) + return + } const landing = getSettings().landingTab if (landing && landing !== 'overview') navigateTo(landing) }, []) return ( + <> + } screenOptions={{ headerShown: false, drawerType: 'slide', - // shell.css: --sh-w: min(84vw, 330px) - drawerStyle: { width: Math.min(width * 0.84, 330), backgroundColor: colors.bg2 }, + // The whole screen: the page slides off to the right (the web drawer is min(84vw, 330px)). + drawerStyle: { width, backgroundColor: colors.bg2 }, overlayColor: 'rgba(0,0,0,0.35)', swipeEnabled: true, swipeEdgeWidth: 40, @@ -70,5 +82,6 @@ export default function AppLayout() { + ) } diff --git a/mobile/src/app/_layout.tsx b/mobile/src/app/_layout.tsx index ea2d3c8..5fadc8e 100644 --- a/mobile/src/app/_layout.tsx +++ b/mobile/src/app/_layout.tsx @@ -16,6 +16,7 @@ import ToastHost from '../ui/ToastHost' import { pushedOptions } from '../features/settings/ui' import { ScreenError } from '../shell/ScreenError' import { colors } from '../theme' +import { GLASS } from '../ui/glass' SplashScreen.preventAutoHideAsync() @@ -45,6 +46,12 @@ const sheet = (detents: Detents, background: string = colors.bg2) => ({ contentStyle: { backgroundColor: background }, }) +// iOS 26 draws a sheet in liquid glass when the screen under its content is clear +// (it turns opaque at the full detent by itself). Without glass it stays a solid sheet. +const glassSheet = (detents: Detents) => (GLASS + ? { presentation: 'formSheet' as const, sheetAllowedDetents: detents, sheetGrabberVisible: true, contentStyle: { backgroundColor: 'transparent' } } + : sheet(detents)) + /** One row per route under src/app, outside the drawer and Connect. */ const ROUTES: { name: string; options: object }[] = [ // Chat (features/chat, features/voice) @@ -56,7 +63,7 @@ const ROUTES: { name: string; options: object }[] = [ { name: 'chat/select', options: sheet([0.75, 1], colors.bg) }, { name: 'chat/snooze', options: sheet([0.5]) }, // A list's Snoozed or Settled chats, opened from the drawer's foot. - { name: 'chat/shelf', options: sheet([0.75, 1]) }, + { name: 'chat/shelf', options: glassSheet([0.75, 1]) }, // The task a chat works toward: picked, changed or unlinked (features/work/LinkTaskSheet.tsx). { name: 'chat/task', options: sheet([0.75, 1]) }, // Voice takes the whole screen and stays until ended: no swipe-down to leave it live. diff --git a/mobile/src/app/chat/shelf.tsx b/mobile/src/app/chat/shelf.tsx index 6e1bb98..0cc003b 100644 --- a/mobile/src/app/chat/shelf.tsx +++ b/mobile/src/app/chat/shelf.tsx @@ -1,2 +1,2 @@ -// Sheet detents: [0.75, 1] (formSheet, grabber, corner radius 22; registered in src/app/_layout.tsx). +// Sheet detents: [0.75, 1] (glassSheet: liquid glass on iOS 26; registered in src/app/_layout.tsx). export { default } from '../../features/chat/ShelfSheet' diff --git a/mobile/src/features/chat/ChatScreen.tsx b/mobile/src/features/chat/ChatScreen.tsx index 06d01b1..531fde0 100644 --- a/mobile/src/features/chat/ChatScreen.tsx +++ b/mobile/src/features/chat/ChatScreen.tsx @@ -67,6 +67,7 @@ import { useSettings } from '../../lib/settings' import { useLanding, useLandOn, useStill } from '../../ui/landing' import { farIndex } from '../../lib/landing' import { IconArrowDown, IconEdit, IconGhost2, IconMenu, IconFolder, IconFolderOff, IconSparkles, IconChevronDown, IconSettings, IconUsersGroup, IconUserPlus } from './icons' +import { holdReload } from '../../shell/otaUpdates' function greeting(name: string) { const h = new Date().getHours() @@ -202,6 +203,8 @@ export default function ChatScreen() { // draft waits in the store meanwhile and is back in the box once the edit ends. const [queueEdit, setQueueEdit] = useState(null) const editing = !!queueEdit && queueEdit.threadId === activeId + // A queued message being edited lives only here: it holds off an over-the-air reload (shell/otaUpdates.tsx). + useEffect(() => (editing ? holdReload() : undefined), [editing]) const onEditFiles = useCallback((files: Attachment[]) => setQueueEdit((e) => (e ? { ...e, files } : e)), []) // What the composer shows: an open chat's own draft, or the new-chat draft its place shows now. const { diff --git a/mobile/src/features/chat/ChatsNav.tsx b/mobile/src/features/chat/ChatsNav.tsx index 395d37d..b650f57 100644 --- a/mobile/src/features/chat/ChatsNav.tsx +++ b/mobile/src/features/chat/ChatsNav.tsx @@ -26,7 +26,7 @@ import React, { useEffect, useMemo, useRef, useSyncExternalStore } from 'react' import { StyleSheet, View } from 'react-native' import { MenuView } from '@react-native-menu/menu' import ReanimatedSwipeable, { type SwipeableMethods } from 'react-native-gesture-handler/ReanimatedSwipeable' -import Animated, { useAnimatedStyle, useSharedValue, withRepeat, withTiming } from 'react-native-reanimated' +import Animated, { useAnimatedReaction, useAnimatedStyle, useSharedValue, withRepeat, withTiming, type SharedValue } from 'react-native-reanimated' import { useDrawerStatus } from 'expo-router/drawer' import { useChat, openProject, createProject, threadTitle } from '../../lib/chat/store' import { attentionOf, attentionBadge, attentionTitle, type Attention } from '../../lib/chat/attention' @@ -40,6 +40,7 @@ import { pushError } from '../../lib/toast' import { colors, textAlpha } from '../../theme' import { T } from '../../ui/Text' import { Press } from '../../ui/kit' +import { GlassButton, GlassGroup } from '../../ui/glass' import { impact, tap } from '../../ui/haptics' import { prompt, showActionTree } from '../../ui/menu' import { useNow } from './threadOps' @@ -88,7 +89,7 @@ function CardStatus({ t, needs, live, woke, unread, settle, now }: { t: ChatThre return {ago(activeAt(t, now), now)} } -export function ThreadItem({ t, active, live, onOpen, shelf = 'active', now, beforeDiscard, card = false, place }: { +export function ThreadItem({ t, active, live, onOpen, shelf = 'active', now, beforeDiscard, card = false, place, glass = false }: { t: ChatThread active: boolean live: boolean @@ -101,6 +102,8 @@ export function ThreadItem({ t, active, live, onOpen, shelf = 'active', now, bef card?: boolean /** The chat's project or folder for a card's first line; a null project is Home. */ place?: { project: Project | null; label: string } + /** On a glass sheet: the row is clear at rest and solid while swiped. */ + glass?: boolean }) { const retitling = useChat((s) => !!s.retitling[t.id]) const autoDays = useChat((s) => s.prefs.autoSettleDays ?? 3) @@ -116,6 +119,11 @@ export function ThreadItem({ t, active, live, onOpen, shelf = 'active', now, bef const menu = threadMenu(t, shelf, live, unsent) const run = (id: string) => { if (id === 'discard-draft') beforeDiscard?.(); menu.run(id) } const swipe = useRef(null) + // A clear row (glass) takes its solid fill the frame it starts to move, on the UI thread + // (Track below), so the actions behind it never show through its text. + const moved = useSharedValue(0) + const solid = colors.bg2 + const fill = useAnimatedStyle(() => ({ backgroundColor: moved.value > 0 ? solid : 'transparent' })) // Every swipe action is one of the menu's own ids, so both run the same code. const act = (id: string) => { swipe.current?.close(); tap(); run(id) } const settle = offersSettle(t, shelf, live) @@ -183,7 +191,7 @@ export function ThreadItem({ t, active, live, onOpen, shelf = 'active', now, bef ) : null} ) : ( - + {/* The open chat: a fill and an accent bar, so it is the first row the eye finds. */} {active ? : null} @@ -205,7 +213,7 @@ export function ThreadItem({ t, active, live, onOpen, shelf = 'active', now, bef {/* Marked done, or its task finished: Settle without a swipe. */} {settleChip} - + ) return ( // No long-press MenuView around the row: inside the drawer it swallowed the @@ -218,8 +226,9 @@ export function ThreadItem({ t, active, live, onOpen, shelf = 'active', now, bef rightThreshold={40} overshootRight={false} blocksExternalGesture={drawerPan()} - renderRightActions={() => ( + renderRightActions={(progress) => ( + {glass ? : null} {shelf === 'snoozed' ? ( act('wake')} style={card && st.swipeTall} /> ) : ( @@ -253,6 +262,12 @@ export function ThreadItem({ t, active, live, onOpen, shelf = 'active', now, bef ) } +/** Copies a swiped row's progress to its own value on the UI thread, for its fill. */ +function Track({ progress, into }: { progress: SharedValue; into: SharedValue }) { + useAnimatedReaction(() => progress.value, (v) => { into.value = v }) + return null +} + /** One action behind a swiped row (a chat's, a draft's). Without onPress it is the face of a MenuView. */ export function SwipeBtn({ label, icon, fill, ink, disabled, onPress, style }: { label: string; icon: typeof IconDots; fill: string; ink: string; disabled?: boolean; onPress?: () => void; style?: object | false @@ -285,12 +300,14 @@ export function openShelf(kind: ShelfKind, scope: string, showing = true) { router.push({ pathname: '/chat/shelf', params: { kind, scope, showing: showing ? '1' : '0' } }) } -/** One shelf as a button: what it holds and how many. */ +/** One shelf as a glass capsule (ui/glass.tsx): what it holds and how many. */ function ShelfBtn({ kind, count, scope, showing }: { kind: ShelfKind; count: number; scope: string; showing: boolean }) { const label = kind === 'snoozed' ? 'Snoozed' : 'Settled' return ( - openShelf(kind, scope, showing)} accessibilityRole="button" @@ -299,7 +316,7 @@ function ShelfBtn({ kind, count, scope, showing }: { kind: ShelfKind; count: num > {label} {count} - + ) } @@ -308,10 +325,11 @@ type ShelfCounts = { scope: string; snoozed: number; settled: number; showing: b export function ShelfButtons({ scope, snoozed, settled, showing, style }: ShelfCounts & { style?: object }) { if (!snoozed && !settled) return null return ( - + // Side by side they melt into one glass shape. + {snoozed ? : null} {settled ? : null} - + ) } @@ -520,7 +538,9 @@ const st = StyleSheet.create({ metaTime: { paddingLeft: 4, fontVariant: ['tabular-nums'] }, doneBtn: { flexDirection: 'row', alignItems: 'center', gap: 3, height: 26, marginLeft: 'auto', marginRight: 8, paddingLeft: 6, paddingRight: 8, borderRadius: 7, backgroundColor: 'rgba(63, 185, 80, 0.15)' }, shelfBtns: { flexDirection: 'row', alignItems: 'center', gap: 6, flexWrap: 'wrap' }, - shelfBtn: { flexDirection: 'row', alignItems: 'center', gap: 5, minHeight: 36, paddingVertical: 6, paddingHorizontal: 11, borderRadius: 18, backgroundColor: colors.bg3 }, + shelfBtn: { minHeight: 46, borderRadius: 23 }, + shelfSolid: { backgroundColor: colors.bg3 }, + shelfInner: { flexDirection: 'row', gap: 5, paddingVertical: 6, paddingHorizontal: 14 }, divider: { height: StyleSheet.hairlineWidth, backgroundColor: colors.line, marginVertical: 6, marginHorizontal: 12 }, scope: { flexDirection: 'row', alignItems: 'center', gap: 2, paddingTop: 4, paddingBottom: 6, paddingHorizontal: 2 }, scopeBtn: { flexDirection: 'row', alignItems: 'center', gap: 7, minHeight: 40, paddingHorizontal: 10, borderRadius: 10 }, diff --git a/mobile/src/features/chat/Composer.tsx b/mobile/src/features/chat/Composer.tsx index 96258db..c24ab50 100644 --- a/mobile/src/features/chat/Composer.tsx +++ b/mobile/src/features/chat/Composer.tsx @@ -35,6 +35,7 @@ import { IconArrowUp, IconPlayerStopFilled, IconPlus, IconMicrophone, IconWaveSine, IconX, IconCheck, IconCornerUpRight, IconPuzzle, IconPlaylistAdd, IconPlayerPlayFilled, } from './icons' +import { holdReload } from '../../shell/otaUpdates' export interface ComposerHandle { /** An upload that already exists (Search's "Add to chat"). */ @@ -259,6 +260,9 @@ const Composer = forwardRef(function Composer(pro const failed = drafts.some((d) => d.status === 'error') const ready = drafts.filter((d) => d.status === 'ready' && d.uploaded).map((d) => d.uploaded!) const unfinished = drafts.length - ready.length + // Files still uploading (or failed) live only here: they hold off an over-the-air reload (shell/otaUpdates.tsx). + const pendingFiles = unfinished > 0 + useEffect(() => (pendingFiles ? holdReload() : undefined), [pendingFiles]) const trayState = `${ready.map((a) => a.id).join(',')}|${unfinished}` const reported = useRef(trayState) useEffect(() => { diff --git a/mobile/src/features/chat/InboxCardRow.tsx b/mobile/src/features/chat/InboxCardRow.tsx index bca01c6..5fce0b2 100644 --- a/mobile/src/features/chat/InboxCardRow.tsx +++ b/mobile/src/features/chat/InboxCardRow.tsx @@ -20,6 +20,7 @@ import { success, tap } from '../../ui/haptics' import { alpha, colors } from '../../theme' import { TI, vc } from './ui' import { IconArrowBackUp, IconChevronRight, IconShield, IconShieldCheck, IconShieldX } from './icons' +import { holdReload } from '../../shell/otaUpdates' // One listing shared by every card on screen, refreshed when it is a few seconds old. let listing: { at: number; items: Promise } | null = null @@ -48,6 +49,9 @@ export default function InboxCardRow({ part, messageId }: { part: InboxPart; mes const [missing, setMissing] = useState(false) const [open, setOpen] = useState(false) const [note, setNote] = useState('') + // A note not yet sent holds off an over-the-air reload (shell/otaUpdates.tsx). + const noted = pending && note.trim().length > 0 + useEffect(() => (noted ? holdReload() : undefined), [noted]) const [busy, setBusy] = useState(false) useEffect(() => { diff --git a/mobile/src/features/chat/Message.tsx b/mobile/src/features/chat/Message.tsx index 593f620..675330d 100644 --- a/mobile/src/features/chat/Message.tsx +++ b/mobile/src/features/chat/Message.tsx @@ -50,6 +50,7 @@ import { IconAlertCircle, IconCopy, IconCheck, IconRefresh, IconFileText, IconFileTypePdf, IconClipboardText, IconBolt, IconDeviceDesktop, IconMicrophone, IconX, IconArrowForwardUp, IconWorld, IconPencil, } from './icons' +import { holdReload } from '../../shell/otaUpdates' // A pasted URL has no spaces to wrap at; iOS breaks it anywhere already, the web preview needs telling. const WRAP = Platform.OS === 'web' ? ({ wordBreak: 'break-word', overflowWrap: 'anywhere' } as any) : undefined @@ -234,6 +235,9 @@ export const UserMessage = React.memo(function UserMessage({ m, canEdit, onEdit, // The edit box is plain text: each attached file shows as [name] and keeps its reference on save. const editable = useMemo(() => editableRefs(m.content), [m.content]) const [draft, setDraft] = useState(editable.text) + // An edit not yet sent holds off an over-the-air reload (shell/otaUpdates.tsx). + const rewriting = editing && draft !== editable.text + useEffect(() => (rewriting ? holdReload() : undefined), [rewriting]) const [lightbox, setLightbox] = useState<{ uri: string; headers?: Record } | null>(null) const [copied, setCopied] = useState(false) const badge = m.mode ? MODE_BADGE[m.mode] : null diff --git a/mobile/src/features/chat/QuestionsPanel.tsx b/mobile/src/features/chat/QuestionsPanel.tsx index 7c173a5..ea2894e 100644 --- a/mobile/src/features/chat/QuestionsPanel.tsx +++ b/mobile/src/features/chat/QuestionsPanel.tsx @@ -16,6 +16,7 @@ import { success, tap } from '../../ui/haptics' import { alpha, colors } from '../../theme' import { TI, vc } from './ui' import { IconCheck, IconChevronDown, IconChevronUp, IconMessageCircleQuestion, IconX } from './icons' +import { holdReload } from '../../shell/otaUpdates' const ADVANCE_MS = 200 @@ -54,6 +55,9 @@ export function useQuestionFlow({ threadId, pending, sendText, displace }: { const last = index === questions.length - 1 const draft = q ? flow.drafts[q.id] : undefined const answered = q ? draftAnswer(q, draft).length > 0 : false + // Answers not yet sent hold off an over-the-air reload (shell/otaUpdates.tsx). + const unsent = questions.some((x) => draftAnswer(x, flow.drafts[x.id]).length > 0) + useEffect(() => (unsent ? holdReload() : undefined), [unsent]) const setDraft = useCallback((id: string, d: Draft) => setFlow((f) => ({ ...f, drafts: { ...f.drafts, [id]: d } })), []) diff --git a/mobile/src/features/chat/ShelfSheet.tsx b/mobile/src/features/chat/ShelfSheet.tsx index 2af5432..efb2261 100644 --- a/mobile/src/features/chat/ShelfSheet.tsx +++ b/mobile/src/features/chat/ShelfSheet.tsx @@ -1,4 +1,5 @@ -// Sheet detents: [0.75, 1] (formSheet, grabber, corner radius 22; registered in src/app/_layout.tsx). +// Sheet detents: [0.75, 1] (formSheet, grabber; liquid glass on iOS 26, else solid with +// corner radius 22; registered in src/app/_layout.tsx as glassSheet). // // The drawer list's parked chats: Snoozed or Settled, switched at the top, for the // scope the list shows (every chat, Home's, or one project's with its folders; one @@ -19,6 +20,7 @@ import type { ChatThread } from '../../lib/chat/types' import { colors } from '../../theme' import { T } from '../../ui/Text' import { Segmented } from '../../ui/kit' +import { GLASS } from '../../ui/glass' import { closeDrawer } from '../../shell/drawerGesture' import { openChat } from '../../shell/nav' import { useNow } from './threadOps' @@ -86,7 +88,7 @@ export default function ShelfSheet() { ref={list} data={rows} keyExtractor={(t) => t.id} - renderItem={({ item }) => router.back()} place={{ project: null, label: placeLabel(item, projects) || 'Home' }} />} + renderItem={({ item }) => router.back()} place={{ project: null, label: placeLabel(item, projects) || 'Home' }} />} onScrollToIndexFailed={({ index, averageItemLength }) => list.current?.scrollToOffset({ offset: index * averageItemLength, animated: false })} contentContainerStyle={{ paddingHorizontal: 8, paddingBottom: insets.bottom + 16 }} ListEmptyComponent={{kind === 'snoozed' ? 'Nothing snoozed here.' : 'Nothing settled here.'}} @@ -97,7 +99,8 @@ export default function ShelfSheet() { } const st = StyleSheet.create({ - sheet: { flex: 1, backgroundColor: colors.bg2 }, + // Clear over the system's glass sheet; solid without it. + sheet: { flex: 1, backgroundColor: GLASS ? 'transparent' : colors.bg2 }, head: { paddingTop: 22, paddingBottom: 12, paddingHorizontal: 20 }, note: { paddingHorizontal: 20, paddingTop: 10, paddingBottom: 6 }, empty: { paddingVertical: 28, textAlign: 'center' }, diff --git a/mobile/src/features/chat/appDrafts.ts b/mobile/src/features/chat/appDrafts.ts index 66a5e4e..266a858 100644 --- a/mobile/src/features/chat/appDrafts.ts +++ b/mobile/src/features/chat/appDrafts.ts @@ -15,9 +15,23 @@ import { getBaseUrl, subscribeConnection } from '../../lib/connection' import { pushError } from '../../lib/toast' import { taskHome } from '../work/state' import { showUndo } from '../work/undoDock' +import { onBeforeReload } from '../../shell/otaUpdates' + +// Whether the drafts reached storage, for the reload into an update (below): any read or +// write that throws counts as not saved, and the save's last step is the drafts' own write. +let wrote = false +const storage = { + getItem: (k: string) => { + try { return localStorage.getItem(k) } catch (e) { wrote = false; throw e } + }, + setItem: (k: string, v: string) => { + try { localStorage.setItem(k, v); wrote = true } catch (e) { wrote = false; throw e } + }, + removeItem: (k: string) => localStorage.removeItem(k), +} export const drafts = createAppDrafts({ - storage: localStorage, + storage, appState: AppState, bridge: getBaseUrl, onBridgeChange: (fn) => { subscribeConnection(fn) }, @@ -26,6 +40,11 @@ export const drafts = createAppDrafts({ onSaveError: () => pushError('This phone won’t save drafts right now. They stay until the app is closed.'), }) +// A reload into an update (shell/otaUpdates.tsx) saves the drafts first: a keystroke still +// waiting on the save timer would otherwise be lost. +// A failed write calls the reload off, so the words stay in memory until they can be saved. +onBeforeReload(() => { wrote = false; drafts.flush(); return wrote }) + export const useDraftState = () => useSyncExternalStore(drafts.subscribe, drafts.get, drafts.get) export const useHasDraft = (key: string) => useSyncExternalStore(drafts.subscribe, () => hasContent(drafts.get().drafts[key]), () => false) /** Something derived from the drafts, re-rendering only when it changes (not on every keystroke). */ diff --git a/mobile/src/features/chat/dictation.ts b/mobile/src/features/chat/dictation.ts index 036d44f..b1c0e04 100644 --- a/mobile/src/features/chat/dictation.ts +++ b/mobile/src/features/chat/dictation.ts @@ -8,6 +8,7 @@ import { } from 'expo-audio' import { pushError } from '../../lib/toast' import { transcribeFile } from './upload' +import { holdReload } from '../../shell/otaUpdates' export type DictationState = null | { state: 'recording' | 'transcribing'; startedAt: number; level: number } @@ -17,6 +18,8 @@ export function useDictation(onText: (text: string) => void) { const [phase, setPhase] = useState(null) const onTextRef = useRef(onText) onTextRef.current = onText + // A clip being recorded or transcribed holds off an over-the-air reload (shell/otaUpdates.tsx). + useEffect(() => (phase ? holdReload() : undefined), [phase !== null]) // eslint-disable-line react-hooks/exhaustive-deps const start = useCallback(async () => { try { diff --git a/mobile/src/features/chat/totemReport.ts b/mobile/src/features/chat/totemReport.ts new file mode 100644 index 0000000..81d25ce --- /dev/null +++ b/mobile/src/features/chat/totemReport.ts @@ -0,0 +1,5 @@ +// A totem's report waiting in its chat. Totems' chats are not in the drawer's list, so the +// drawer's Overview row and the Overview's Totems tile wear a dot for it (one test, here). +import { useChat } from '../../lib/chat/store' + +export const useTotemReportWaiting = () => useChat((s) => s.threads.some((t) => t.totemId && t.needsReply && !s.runs[t.id])) diff --git a/mobile/src/features/inbox/InboxScreen.tsx b/mobile/src/features/inbox/InboxScreen.tsx index 5d8b159..6aadd1d 100644 --- a/mobile/src/features/inbox/InboxScreen.tsx +++ b/mobile/src/features/inbox/InboxScreen.tsx @@ -23,6 +23,7 @@ import { T } from '../../ui/Text' import { Empty, IconBtn, Press, ViewHead } from '../../ui/kit' import { confirm } from '../../ui/menu' import { success, tap, warn } from '../../ui/haptics' +import { holdReload } from '../../shell/otaUpdates' // Per-kind glyph for the destination chip, so "where is this going" reads at a // glance. Unknown kinds (future sources) fall back to the generic inbox icon. @@ -61,6 +62,9 @@ export function LinkedinCard({ card }: { card: { action: string; url: string; au const [draft, setDraft] = useState(card.draft || '') const [copied, setCopied] = useState(false) useEffect(() => { setDraft(card.draft || '') }, [card.draft]) + // His edits to the draft live only here: they hold off an over-the-air reload (shell/otaUpdates.tsx). + const edited = draft !== (card.draft || '') + useEffect(() => (edited ? holdReload() : undefined), [edited]) const what = ({ like: 'Like this post', repost: 'Repost this', comment: 'Comment on this post', reply: 'Reply', connect: 'Send a connection request' } as Record)[card.action] || card.action const copy = async () => { try { diff --git a/mobile/src/features/journal/RecorderPanel.tsx b/mobile/src/features/journal/RecorderPanel.tsx index 73affa5..0bbf8f3 100644 --- a/mobile/src/features/journal/RecorderPanel.tsx +++ b/mobile/src/features/journal/RecorderPanel.tsx @@ -5,7 +5,7 @@ // // The panel owns the recorder, so the once-a-second clock re-renders this card // and not the whole list of entries under it. -import React, { useState } from 'react' +import React, { useEffect, useState } from 'react' import { Linking, StyleSheet, TextInput, View } from 'react-native' import Animated, { useAnimatedStyle, useSharedValue, withTiming } from 'react-native-reanimated' import { LinearGradient } from 'expo-linear-gradient' @@ -21,6 +21,7 @@ import { fmtClock } from '../../lib/journal/format' import { useRecorder, type RecorderResult } from './useRecorder' import Waveform from './Waveform' import { AudioBar, Spin } from './bits' +import { holdReload } from '../../shell/otaUpdates' interface RecorderPanelProps { engineReady: boolean @@ -37,6 +38,9 @@ export default function RecorderPanel({ engineReady, delayMinutes, onSave, onSav const [saving, setSaving] = useState(false) const [typing, setTyping] = useState(false) const [text, setText] = useState('') + // A typed entry not yet saved holds off an over-the-air reload (shell/otaUpdates.tsx). + const unsaved = text.trim().length > 0 + useEffect(() => (unsaved ? holdReload() : undefined), [unsaved]) const halo = useSharedValue(0) const haloStyle = useAnimatedStyle(() => ({ opacity: withTiming(live ? 1 : 0, { duration: 150 }), diff --git a/mobile/src/features/journal/useRecorder.ts b/mobile/src/features/journal/useRecorder.ts index caf3454..03c8191 100644 --- a/mobile/src/features/journal/useRecorder.ts +++ b/mobile/src/features/journal/useRecorder.ts @@ -15,6 +15,7 @@ import { } from 'expo-audio' import { activateKeepAwakeAsync, deactivateKeepAwake } from 'expo-keep-awake' import { RECORDING_MIME, deleteLocalRecording } from './upload' +import { holdReload } from '../../shell/otaUpdates' export type RecorderState = 'idle' | 'requesting' | 'recording' | 'paused' | 'stopped' | 'denied' @@ -75,6 +76,9 @@ export function useRecorder(): Recorder { const durationMs = useRef(0) const stateRef = useRef(state) stateRef.current = state + // Recording, paused, or a take not yet saved: an over-the-air reload would lose it (shell/otaUpdates.tsx). + const unsaved = state === 'recording' || state === 'paused' || state === 'stopped' + useEffect(() => (unsaved ? holdReload() : undefined), [unsaved]) const stopMeter = () => { if (meter.current) clearInterval(meter.current) diff --git a/mobile/src/features/overview/OverviewScreen.tsx b/mobile/src/features/overview/OverviewScreen.tsx index 606c725..69bedca 100644 --- a/mobile/src/features/overview/OverviewScreen.tsx +++ b/mobile/src/features/overview/OverviewScreen.tsx @@ -7,6 +7,7 @@ import { Image } from 'expo-image' import { useFocusEffect } from 'expo-router' import { Screen, FAB_CLEARANCE } from '../../shell/Screen' import { navigateTo, openChat } from '../../shell/nav' +import { holdReload } from '../../shell/otaUpdates' import { colors, alpha, fonts } from '../../theme' import { T } from '../../ui/Text' import { Badge, Press } from '../../ui/kit' @@ -40,6 +41,7 @@ import { chatAboutMenu } from '../../ui/chatAbout' import { openAway } from './AwaySheet' import RecentChats from './RecentChats' import { isWakeNetworkError } from '../../lib/wake' +import { useTotemReportWaiting } from '../chat/totemReport' type NavTarget = Parameters[0] type Tabler = React.ComponentType @@ -58,9 +60,11 @@ function TotemsGlyph({ size = 21, color }: { size?: number; color?: string }) { } // Everything Totem has, one tap away. The phone's drawer has no tabs, so this row -// is the way to every screen: Inbox, Search and Totems sit where the web lists Code -// and Brain, which the app has no screen for yet (left out rather than dead-ending). +// is the way to every screen (Totems first: the drawer has no Totems row). Inbox and +// Search sit where the web lists Code and Brain, which the app has no screen for yet (left out rather than dead-ending). const APPS: { id: string; label: string; icon: Tabler; to: NavTarget }[] = [ + // First, since the drawer has no Totems row: its dot says a totem's report is waiting. + { id: 'totems', label: 'Totems', icon: TotemsGlyph, to: 'totems' }, // Each Productivity tool opens its own page (#177), named as its top bar names it. { id: 'todos', label: 'Tasks', icon: IconChecklist, to: 'todos' }, { id: 'calendar', label: 'Calendar', icon: IconCalendarEvent, to: 'calendar' }, @@ -71,7 +75,6 @@ const APPS: { id: string; label: string; icon: Tabler; to: NavTarget }[] = [ { id: 'journal', label: 'Journal', icon: IconMicrophone2, to: 'journal' }, { id: 'inbox', label: 'Inbox', icon: IconInbox, to: 'inbox' }, { id: 'search', label: 'Search', icon: IconSearch, to: 'search' }, - { id: 'totems', label: 'Totems', icon: TotemsGlyph, to: 'totems' }, { id: 'fleet', label: 'Fleet', icon: IconServer2, to: 'fleet' }, { id: 'logs', label: 'Logs', icon: IconHistory, to: { tab: 'settings', sub: 'logs' } }, { id: 'studio', label: 'Skills', icon: IconWand, to: { tab: 'settings', sub: 'skills' } }, @@ -366,6 +369,7 @@ export default function OverviewScreen() { nextJob, requestsToday: data.assistant?.today, })) const inboxOpen: number = data.inbox?.open || 0 + const totemReports = useTotemReportWaiting() const daily = useMemo(() => { const a: any[] = data.assistant?.daily || [] @@ -453,10 +457,11 @@ export default function OverviewScreen() { {APPS.map((app) => ( - navigateTo(app.to)} style={st.app} accessibilityRole="button" accessibilityLabel={app.label}> + navigateTo(app.to)} style={st.app} accessibilityRole="button" accessibilityLabel={app.id === 'totems' && totemReports ? 'Totems, a report is waiting' : app.label}> {app.id === 'inbox' && inboxOpen ? : null} + {app.id === 'totems' && totemReports ? : null} {app.label} @@ -784,6 +789,9 @@ function RefreshButton({ spinning, onPress }: { spinning: boolean; onPress: () = // Sending starts a new chat with the text and opens it. function AskBox({ onAsk }: { onAsk: (text: string) => void }) { const [text, setText] = useState('') + // Words not yet sent hold off an over-the-air reload (shell/otaUpdates.tsx). + const unsent = text.trim().length > 0 + useEffect(() => (unsent ? holdReload() : undefined), [unsent]) const ref = useRef(null) const submit = () => { const t = text.trim() @@ -847,6 +855,7 @@ const st = StyleSheet.create({ backgroundColor: ov.surface, borderWidth: 1, borderColor: ov.line, }, appBadge: { position: 'absolute', top: -5, right: -6 }, + appDot: { position: 'absolute', top: -2, right: -2, width: 8, height: 8, borderRadius: 4, backgroundColor: colors.accent }, askInput: { flex: 1, minWidth: 0, color: colors.text, fontFamily: fonts[400], fontSize: 16, lineHeight: 22, paddingTop: 9, paddingBottom: 9, maxHeight: 140, diff --git a/mobile/src/features/voice/VoiceScreen.tsx b/mobile/src/features/voice/VoiceScreen.tsx index 4d64aa8..0047e78 100644 --- a/mobile/src/features/voice/VoiceScreen.tsx +++ b/mobile/src/features/voice/VoiceScreen.tsx @@ -25,6 +25,7 @@ import { RealtimeVoice } from './realtime' import { MicError, type RtPhase, type VoiceStatus } from './types' import { Orb, type OrbPhase } from './Orb' import { handToDictation } from './handoff' +import { holdReload } from '../../shell/otaUpdates' const RT_CAPTION: Record = { connecting: 'Connecting…', @@ -177,6 +178,8 @@ function RealtimeVoiceMode({ threadId, kind, status }: { threadId: string | null /** Voice mode: realtime when the bridge has a key (and it isn't turned off), dictation otherwise. */ export default function VoiceScreen() { useKeepAwake('totem-voice') + // A call in progress is never cut off by an over-the-air update (shell/otaUpdates.tsx). + useEffect(() => holdReload(), []) const params = useLocalSearchParams<{ threadId?: string; kind?: string }>() const threadId = params.threadId || null const kind = params.kind === 'temporary' ? 'temporary' : 'regular' diff --git a/mobile/src/shell/AppDrawer.tsx b/mobile/src/shell/AppDrawer.tsx index 79c4530..7d7b292 100644 --- a/mobile/src/shell/AppDrawer.tsx +++ b/mobile/src/shell/AppDrawer.tsx @@ -1,11 +1,13 @@ // The phone sidebar (Shell.tsx MobileDrawer): TOTEM with Search (the Search page); -// then Overview, Totems (a dot when a totem's report waits), the Productivity tools -// and the chats (one list, T3 Code's way: features/chat/ChatsNav.tsx) in one scroll; and a foot -// that stays put, with the chats' Snoozed and Settled buttons on the left and New -// chat and Settings on the right, where the thumb is (the web drawer's foot has -// Settings there too). New chat wears the corner button's light fill. -// The drawer navigator slides the page aside to reveal it, the way the ChatGPT app -// does; the scrim, a swipe or picking anything closes it. +// then Overview (a dot when a totem's report waits), the Productivity tools and the chats (one list, T3 Code's way: +// features/chat/ChatsNav.tsx) in one scroll; and a foot that floats over the scroll's +// end, with the chats' Snoozed and Settled buttons on the left and New chat and +// Settings on the right, where the thumb is (the web drawer's foot has Settings there +// too). On iOS 26 the foot is liquid glass (ui/glass.tsx): neighbouring buttons melt +// into one shape, the list slides under them, and New chat wears the corner button's +// light tint. Totems is not here: it opens from the Overview's app row. +// The drawer takes the whole screen (the page slides off to the right); the head's +// close button, a swipe back or picking anything closes it. // // On the phone Totem is a chat app first, so the web's tab rail isn't here: the other // screens open from the Overview's app row. The Productivity tools are the exception @@ -16,20 +18,21 @@ // now lives in Settings. Search opens the Search page; the chat list has no search // box of its own. import React, { useEffect, useState } from 'react' -import { Image as RNImage, LayoutAnimation, ScrollView, StyleSheet, useWindowDimensions, View } from 'react-native' +import { LayoutAnimation, ScrollView, StyleSheet, useWindowDimensions, View } from 'react-native' import { useReducedMotion } from 'react-native-reanimated' import { useSafeAreaInsets } from 'react-native-safe-area-context' import { router, usePathname } from 'expo-router' import type { DrawerContentComponentProps } from 'expo-router/drawer' -import { colors, textAlpha } from '../theme' +import { LinearGradient } from 'expo-linear-gradient' +import { alpha, colors, textAlpha } from '../theme' import { T } from '../ui/Text' import { Badge, IconBtn, Press } from '../ui/kit' +import { FAB_TINT, GLASS, GlassButton, GlassGroup } from '../ui/glass' import { Hi, Squares2X2Icon, Cog6ToothIcon, ChevronRightIcon } from '../lib/icons' import IconChevronDown from '@tabler/icons-react-native/dist/esm/icons/IconChevronDown.mjs' import IconChevronUp from '@tabler/icons-react-native/dist/esm/icons/IconChevronUp.mjs' import { useSettings } from '../lib/settings' -import { useChat } from '../lib/chat/store' -import { IconEdit, IconSearch } from '../lib/chat/icons' +import { IconEdit, IconLayoutSidebarLeftCollapse, IconSearch } from '../lib/chat/icons' import { useInboxCount } from '../lib/useInboxCount' import { useUnreadNotifications } from '../features/notifications/useUnread' import ChatsNav, { DockedShelfButtons } from '../features/chat/ChatsNav' @@ -40,6 +43,7 @@ import { newChat, openChat } from './nav' import { PRODUCTIVITY_APPS, TAB_ROUTES, TOOL_LABELS, productivityPage, productivityPath } from './routes' import { ToolIcon } from './ToolIcon' import { tap } from '../ui/haptics' +import { useTotemReportWaiting } from '../features/chat/totemReport' const FOLD_KEY = 'totem.drawer.toolsFolded' const readFolded = () => { try { return localStorage.getItem(FOLD_KEY) === '1' } catch { return false } } @@ -71,9 +75,7 @@ export default function AppDrawer({ navigation }: DrawerContentComponentProps) { const onOverview = path === '/' || path === '' const onSettings = path.startsWith('/settings') const onSearch = path.startsWith('/search') - const onTotems = path.startsWith(TAB_ROUTES.totems) - // A totem's report waiting in its chat: its chats are not in the list below, so the row says so. - const totemReports = useChat((s) => s.threads.some((t) => t.totemId && t.needsReply && !s.runs[t.id])) + const totemReports = useTotemReportWaiting() const onTool = productivityPage(path) const toolName = onToolName(path) // Highlighted on the hub, or folded away while one of its tools is open. @@ -87,6 +89,8 @@ export default function AppDrawer({ navigation }: DrawerContentComponentProps) { // A chat opened from the shelf sheet over the drawer closes the drawer too. useEffect(() => keepDrawerClose(() => navigation.closeDrawer()), [navigation]) const go = (to: string) => { tap(); router.navigate(to as any); close() } + // The list scrolls under the floating foot, so its end clears the foot's height. + const [footH, setFootH] = useState(72) const openFromDrawer = (id: string | null) => { openChat(id); close() } return ( @@ -102,18 +106,16 @@ export default function AppDrawer({ navigation }: DrawerContentComponentProps) { style={onSearch ? { backgroundColor: colors.drawerOn } : undefined} onPress={() => go(TAB_ROUTES.search)} /> + {/* No page edge is left to tap, so the head closes it; a swipe left does too. */} + - + - go(TAB_ROUTES.overview)} accessibilityRole="button"> + go(TAB_ROUTES.overview)} accessibilityRole="button" accessibilityLabel={`Overview${inboxOpen ? `, ${inboxOpen} in the inbox` : ''}${totemReports ? ", a totem's report is waiting" : ''}`}> Overview - - go(TAB_ROUTES.totems)} accessibilityRole="button" accessibilityLabel={totemReports ? 'Totems, a report is waiting' : 'Totems'}> - {/* The web rail's Totems mark, tinted like a glyph. */} - - Totems + {/* A totem's report waits: its Totems tile on the Overview has the same dot. */} {totemReports ? : null} @@ -173,23 +175,44 @@ export default function AppDrawer({ navigation }: DrawerContentComponentProps) { drafts={(projectId, homeOnly) => } /> - {/* A discarded draft's Undo, kept in sight whatever the scroll. */} - - - - { newChat(); close() }} accessibilityRole="button" accessibilityLabel="New chat" hitSlop={4}> - - - 0 ? `Settings, ${unread} unread ${unread === 1 ? 'notification' : 'notifications'}` : 'Settings'} - badge={unread > 0} - color={onSettings ? colors.text : textAlpha(72)} - style={onSettings ? { backgroundColor: colors.drawerOn } : undefined} - onPress={() => go(TAB_ROUTES.settings)} - /> + setFootH(Math.round(e.nativeEvent.layout.height))} + pointerEvents="box-none" + > + {/* The list fades out under the glass, as iOS 26's scroll edge does. */} + {GLASS ? : null} + {/* A discarded draft's Undo, kept in sight whatever the scroll. */} + + + + + { newChat(); close() }} + > + + + 0 ? `Settings, ${unread} unread ${unread === 1 ? 'notification' : 'notifications'}` : 'Settings'} + onPress={() => go(TAB_ROUTES.settings)} + > + + {unread > 0 ? : null} + + + ) @@ -199,13 +222,20 @@ const st = StyleSheet.create({ drawer: { flex: 1, backgroundColor: colors.bg2, paddingHorizontal: 8 }, head: { height: 58, flexDirection: 'row', alignItems: 'center', gap: 2 }, nav: { paddingTop: 2, paddingBottom: 6, gap: 2, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: colors.line }, - // Pinned under the scroll: the shelves on the left, Settings on the right. - foot: { flexDirection: 'row', alignItems: 'center', gap: 6, paddingTop: 8, paddingLeft: 4, borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: colors.line }, - // Screen.tsx's new-chat corner button, smaller: the one light circle in the drawer. - newChat: { width: 44, height: 44, borderRadius: 22, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.text }, + // Floating over the scroll's end: the shelves on the left, New chat and Settings on the right. + foot: { position: 'absolute', left: 8, right: 8, bottom: 0 }, + // Without glass the foot is a solid band, as before. + footSolid: { backgroundColor: colors.bg2, borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: colors.line }, + fade: { position: 'absolute', left: -8, right: -8, top: -18, bottom: 0 }, + footRow: { flexDirection: 'row', alignItems: 'center', gap: 8, paddingTop: 8, paddingLeft: 4, paddingRight: 2 }, + // Close enough to melt into one shape under glass. + pair: { flexDirection: 'row', alignItems: 'center', gap: 6 }, + // Screen.tsx's new-chat corner button, smaller. + round: { width: 46, height: 46, borderRadius: 23 }, + dot: { width: 7, height: 7, borderRadius: 4, marginRight: 6, backgroundColor: colors.accent }, + badge: { position: 'absolute', top: 9, right: 10, width: 8, height: 8, borderRadius: 4, backgroundColor: colors.accent }, item: { flexDirection: 'row', alignItems: 'center', gap: 13, minHeight: 44, paddingVertical: 6, paddingHorizontal: 12, borderRadius: 10 }, itemOn: { backgroundColor: colors.drawerOn }, - dot: { width: 7, height: 7, borderRadius: 4, marginRight: 6, backgroundColor: colors.accent }, tools: { paddingTop: 6, paddingBottom: 8, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: colors.line }, toolsHead: { flexDirection: 'row', alignItems: 'center' }, toolsOpen: { flex: 1, flexDirection: 'row', alignItems: 'center', gap: 4, minHeight: 44, paddingVertical: 6, paddingHorizontal: 12, borderRadius: 10 }, diff --git a/mobile/src/shell/Screen.tsx b/mobile/src/shell/Screen.tsx index 3f016d1..b8ff3ab 100644 --- a/mobile/src/shell/Screen.tsx +++ b/mobile/src/shell/Screen.tsx @@ -1,8 +1,10 @@ // Every screen but the chat: ChatGPT's top bar (☰, the screen's name, the AI -// usage pill), the content, and in the bottom-right corner the voice + new-chat pair -// (shell.css .sh-mbar / .sh-fab). Mirrors Shell.tsx's MobileBar and NewChatFab, -// except the bar's right slot: the web has new chat there, the app the usage pill -// (new chat is the corner button), so that glance is on every page. +// usage pill), the content, and in the bottom-right corner the new-chat button, in +// liquid glass where iOS has it (shell.css .sh-mbar / .sh-fab). Voice mode starts from +// the home-screen quick action and the chat's composer, not a second corner button. +// Mirrors Shell.tsx's MobileBar and NewChatFab, except the bar's right slot: the web +// has new chat there, the app the usage pill (new chat is the corner button), so that +// glance is on every page. import React, { useEffect, useState, useSyncExternalStore } from 'react' import { StyleSheet, View, type StyleProp, type ViewStyle } from 'react-native' import { useSafeAreaInsets } from 'react-native-safe-area-context' @@ -11,11 +13,12 @@ import { colors, textAlpha } from '../theme' import { T } from '../ui/Text' import { IconBtn, Press } from '../ui/kit' import { Hi } from '../lib/icons' -import { IconEdit, IconMenu, IconWaveSine } from '../lib/chat/icons' +import { IconEdit, IconMenu } from '../lib/chat/icons' import UsageChips from '../features/chat/UsageChips' -import { newChat, openDrawer, startVoice } from './nav' +import { newChat, openDrawer } from './nav' import { PageGlow, type GlowPage } from '../ui/PageGlow' import { impact } from '../ui/haptics' +import { FAB_TINT, GlassButton } from '../ui/glass' import { setToastFloor } from '../ui/toastFloor' import { getCacheStatus, subscribeCacheStatus } from '../lib/api' import { ago } from '../lib/chat/settle' @@ -60,15 +63,11 @@ function OfflineHint() { } const FAB_SIZE = 54 -const FAB_GAP = 14 -/** - * The voice + new-chat buttons, stacked in the bottom-right corner: one size, so - * they read as a pair; the voice one keeps its darker fill. - */ +/** The new-chat button in the bottom-right corner: tinted light glass, or the solid light circle without glass. */ export function NewChatFab({ bottomOffset = 0 }: { bottomOffset?: number }) { const insets = useSafeAreaInsets() - // Toasts at the bottom keep left of the pair. + // Toasts at the bottom keep left of it. const focused = useIsFocused() useEffect(() => { if (!focused) return @@ -77,22 +76,18 @@ export function NewChatFab({ bottomOffset = 0 }: { bottomOffset?: number }) { }, [focused]) const base = Math.max(insets.bottom, 14) + 8 + bottomOffset return ( - <> - { impact(); startVoice() }} - style={[st.fab, st.fabVoice, { bottom: base + FAB_SIZE + FAB_GAP }]} - > - - - + { impact(); newChat() }} - style={[st.fab, { bottom: base }]} > - - + + ) } @@ -121,7 +116,7 @@ export function Screen({ title, children, fab = true, glow, style }: { ) } -/** Bottom padding a scrolling screen needs so its last item clears the FABs. */ +/** Bottom padding a scrolling screen needs so its last item clears the corner button. */ export const FAB_CLEARANCE = 14 + 56 + 40 const st = StyleSheet.create({ @@ -130,12 +125,10 @@ const st = StyleSheet.create({ // shows; at a large text size the pill widens its side instead of covering the title. side: { minWidth: 76, justifyContent: 'center' }, bar: { height: 52, flexDirection: 'row', alignItems: 'center', gap: 4, paddingHorizontal: 6, backgroundColor: colors.bg, zIndex: 5 }, - fab: { - position: 'absolute', right: 16, width: FAB_SIZE, height: FAB_SIZE, borderRadius: FAB_SIZE / 2, - alignItems: 'center', justifyContent: 'center', backgroundColor: colors.text, - shadowColor: '#000', shadowOpacity: 0.5, shadowRadius: 14, shadowOffset: { width: 0, height: 10 }, zIndex: 44, - }, - fabVoice: { backgroundColor: colors.fabVoice, borderWidth: 1, borderColor: colors.fabVoiceBorder }, + fabSpot: { position: 'absolute', right: 16, zIndex: 44 }, + fab: { width: FAB_SIZE, height: FAB_SIZE, borderRadius: FAB_SIZE / 2 }, + // Glass draws its own depth; the solid circle keeps its fill and drop shadow. + fabSolid: { backgroundColor: colors.text, shadowColor: '#000', shadowOpacity: 0.5, shadowRadius: 14, shadowOffset: { width: 0, height: 10 } }, }) export { textAlpha } diff --git a/mobile/src/shell/drawerKeyboard.ts b/mobile/src/shell/drawerKeyboard.ts index 6e5d0e4..d39954c 100644 --- a/mobile/src/shell/drawerKeyboard.ts +++ b/mobile/src/shell/drawerKeyboard.ts @@ -3,7 +3,7 @@ // leave half of it out of reach. `(app)/_layout.tsx` watches the drawer's progress // (0 shut, 1 open) on the UI thread and asks this at every step. -// Below this the drawer counts as shut: a few points of a 330 pt drawer. +// Below this the drawer counts as shut: a few points of the drawer. const SHUT = 0.01 /** Whether this step is the drawer leaving shut: once per opening, never while closing. */ diff --git a/mobile/src/shell/otaPolicy.test.mjs b/mobile/src/shell/otaPolicy.test.mjs new file mode 100644 index 0000000..4972022 --- /dev/null +++ b/mobile/src/shell/otaPolicy.test.mjs @@ -0,0 +1,54 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { APPLY_AFTER_AWAY_MS, CHECK_EVERY_MS, safePage, shouldApply, shouldCheck, stillSettled } from './otaPolicy.ts' + +const LONG = 3 * 3600_000 +const base = { pending: true, awayMs: LONG, held: false, path: '/chat', typing: false } + +test('a fetched update is applied on coming back to a page after a long absence', () => { + assert.equal(shouldApply(base), true) + assert.equal(shouldApply({ ...base, path: '/', awayMs: APPLY_AFTER_AWAY_MS }), true) +}) + +test('a quick app switch never reloads the app under him', () => { + assert.equal(shouldApply({ ...base, awayMs: 5_000 }), false) + assert.equal(shouldApply({ ...base, awayMs: APPLY_AFTER_AWAY_MS - 1 }), false) +}) + +test('nothing fetched, or voice or a recording in progress, means no reload', () => { + assert.equal(shouldApply({ ...base, pending: false }), false) + assert.equal(shouldApply({ ...base, held: true }), false) +}) + +test('only the Overview and a chat: any other page, sheet or editor keeps its unsaved edits', () => { + for (const path of ['/todo/abc', '/goal/edit', '/settings/skills', '/chat/model', '/habit/new', '/journal/123', '/fleet', '/productivity/lists', '/productivity/journal', '/inbox', '/settings']) { + assert.equal(safePage(path), false, path) + assert.equal(shouldApply({ ...base, path }), false, path) + } +}) + +test('typing holds it off, except in a chat, whose draft is saved as the app leaves', () => { + assert.equal(shouldApply({ ...base, path: '/', typing: true }), false) + assert.equal(shouldApply({ ...base, path: '/chat', typing: true }), true) +}) + +test('a new chat not yet started keeps its place: no reload under it', () => { + assert.equal(shouldApply({ ...base, newChat: true }), false) + assert.equal(shouldApply({ ...base, path: '/', newChat: true }), true) +}) + +test('a push, quick action or link that lands while the return settles wins', () => { + const calm = { pathBefore: '/chat', pathNow: '/chat', chatBefore: 'a', chatNow: 'a', arrived: false } + assert.equal(stillSettled(calm), true) + assert.equal(stillSettled({ ...calm, arrived: true }), false) + assert.equal(stillSettled({ ...calm, chatNow: 'b' }), false) + assert.equal(stillSettled({ ...calm, pathNow: '/inbox' }), false) +}) + +test('checks are spaced out and never stack', () => { + const now = 1_000_000_000 + assert.equal(shouldCheck({ lastCheckAt: 0, now, busy: false }), true) + assert.equal(shouldCheck({ lastCheckAt: now - CHECK_EVERY_MS + 1, now, busy: false }), false) + assert.equal(shouldCheck({ lastCheckAt: now - CHECK_EVERY_MS, now, busy: false }), true) + assert.equal(shouldCheck({ lastCheckAt: 0, now, busy: true }), false) +}) diff --git a/mobile/src/shell/otaPolicy.ts b/mobile/src/shell/otaPolicy.ts new file mode 100644 index 0000000..ca1e9ea --- /dev/null +++ b/mobile/src/shell/otaPolicy.ts @@ -0,0 +1,56 @@ +// When the app looks for, and applies, an over-the-air update (otaUpdates.ts). Pure, so +// the rules are tested on their own (otaPolicy.test.mjs). +// +// expo-updates on its own checks only at a cold start and applies what it fetched at the +// next one. iOS keeps a suspended app for days, so a merge could take a week to show up +// ("the phone didn't get today's change"). So the app also checks as it comes back to the +// foreground, and applies a fetched update on a later return after a long absence, but +// only where a reload loses nothing: on the Overview or an open chat, the two pages whose +// every input is saved as it changes or holds the reload (never a sheet, an editor or any +// other page, whose edits may live only in memory), with nothing being typed, and only once +// the return has settled, so a notification or quick action that brought the app back +// keeps its screen. Those two are where he comes back to, so the update still lands. + +/** Away at least this long, a fetched update may be applied as he comes back. */ +export const APPLY_AFTER_AWAY_MS = 30 * 60_000 +/** At most one check for a new update this often. */ +export const CHECK_EVERY_MS = 10 * 60_000 +/** How long after coming back the app waits for a push or quick action to land. */ +export const SETTLE_MS = 1500 + +/** + * The Overview or the chat: every input there saves as it changes (the composer's draft, a + * habit's number on blur) or holds the reload while it has unsent words (holdReload), so a + * reload, and the resume after it, gives the page back as it was. Anything else may not. + */ +export function safePage(path: string) { + return path === '/' || path === '/chat' +} + +/** + * Reload into the fetched update on this return? Never while something would be lost: + * voice or a recording (`held`), a page with an editor on top, or an input being typed in + * (`typing`), except in a chat, whose composer saves its draft as the app leaves. A chat + * not started yet (`newChat`) is left alone too, since only the draft text is saved. + */ +export function shouldApply({ pending, awayMs, held, path, typing, newChat = false }: { + pending: boolean; awayMs: number; held: boolean; path: string; typing: boolean + /** A chat not started yet is on screen: where it was placed (a project, a task) lives in memory. */ + newChat?: boolean +}) { + if (!pending || held || awayMs < APPLY_AFTER_AWAY_MS) return false + if (!safePage(path) || (path === '/chat' && newChat)) return false + return !typing || path === '/chat' +} + +/** Still nothing else moving SETTLE_MS later: the same page and chat, and no push or quick action arrived. */ +export function stillSettled({ pathBefore, pathNow, chatBefore, chatNow, arrived }: { + pathBefore: string; pathNow: string; chatBefore: string | null; chatNow: string | null; arrived: boolean +}) { + return !arrived && pathBefore === pathNow && chatBefore === chatNow +} + +/** Ask the update server again? */ +export function shouldCheck({ lastCheckAt, now, busy }: { lastCheckAt: number; now: number; busy: boolean }) { + return !busy && now - lastCheckAt >= CHECK_EVERY_MS +} diff --git a/mobile/src/shell/otaUpdates.tsx b/mobile/src/shell/otaUpdates.tsx new file mode 100644 index 0000000..2a9be6f --- /dev/null +++ b/mobile/src/shell/otaUpdates.tsx @@ -0,0 +1,130 @@ +// Over-the-air updates while the app stays alive (the rules: otaPolicy.ts). Coming back to +// the foreground looks for an update (or a rollback) and fetches it in the background; a +// fetched one is applied on a later return after a long absence, only on a top-level page +// with nothing being typed, and only if nothing else arrives in the moment after (a tapped +// notification, a quick action, a link). Voice mode, dictation and an unsaved journal take +// hold it off (holdReload). Before reloading it notes the page and chat on screen, and the +// fresh launch goes back there (resumedFromUpdate) instead of the landing page, and does not +// replay the home-screen action the app was first launched from (quickActions.ts). +// A development build, or one without expo-updates, does nothing here. +import { useEffect, useRef } from 'react' +import { AppState, TextInput } from 'react-native' +import { usePathname } from 'expo-router' +import * as Updates from 'expo-updates' +import { getState as chatState } from '../lib/chat/store' +import { tappedNotificationRecently } from './push' +import { SETTLE_MS, shouldApply, shouldCheck, stillSettled } from './otaPolicy' + +const holds = new Set() + +/** Keep the app from reloading into an update until the returned release is called. */ +export function holdReload(): () => void { + const key = Symbol('hold') + holds.add(key) + return () => { holds.delete(key) } +} + +const beforeReload = new Set<() => boolean>() +/** + * Run just before reloading into an update, to save what is still waiting on a timer (the + * chat drafts). Returning false (it could not be saved) calls the reload off. + */ +export function onBeforeReload(fn: () => boolean): () => void { + beforeReload.add(fn) + return () => { beforeReload.delete(fn) } +} + +let arrivedAt = 0 +/** Something opened a screen of its own as the app came back (a quick action): no reload now. */ +export function noteArrival() { arrivedAt = Date.now() } + +// Where to pick up after a reload into an update, kept for one launch. +const RESUME_KEY = 'totem.ota.resume' +type Resume = { at: number; path: string; chatId: string | null } + +function takeResume(): Resume | null { + try { + const raw = localStorage.getItem(RESUME_KEY) + if (!raw) return null + localStorage.removeItem(RESUME_KEY) + const r = JSON.parse(raw) as Resume + return Date.now() - r.at < 120_000 ? r : null + } catch { return null } +} + +let resume: Resume | null | undefined +/** Where the reload before this launch left him; null on any other launch. Read after mount. */ +export function resumedFromUpdate(): Resume | null { + if (resume === undefined) resume = takeResume() + return resume +} + +let resumeTaken = false +/** The layout takes the resume once; a later remount (signing in again) lands as usual. */ +export function takeResumedFromUpdate(): Resume | null { + if (resumeTaken) return null + resumeTaken = true + return resumedFromUpdate() +} + +/** Mounted once in the signed-in app; draws nothing, so its re-renders stay here. */ +export function OtaUpdates() { + const { isUpdatePending, isChecking, isDownloading } = Updates.useUpdates() + const path = usePathname() + const state = useRef({ pending: false, busy: false, path: '/', leftAt: 0, lastCheckAt: Date.now() }) + state.current.pending = isUpdatePending + state.current.busy = isChecking || isDownloading + state.current.path = path + + useEffect(() => { + if (__DEV__ || !Updates.isEnabled) return + let settle: ReturnType | undefined + const check = async () => { + const s = state.current + if (!shouldCheck({ lastCheckAt: s.lastCheckAt, now: Date.now(), busy: s.busy || s.pending })) return + s.lastCheckAt = Date.now() + try { + const found = await Updates.checkForUpdateAsync() + if (found.isAvailable || found.isRollBackToEmbedded) await Updates.fetchUpdateAsync() + } catch { /* offline or the server is away: the next return tries again */ } + } + const apply = (pathBefore: string, chatBefore: string | null) => { + const s = state.current + const chatNow = chatState().activeId + if (AppState.currentState !== 'active' || holds.size) return + if (s.path !== '/chat' && TextInput.State.currentlyFocusedInput() != null) return + const arrived = tappedNotificationRecently(SETTLE_MS + 1000) || Date.now() - arrivedAt < SETTLE_MS + 1000 + if (!stillSettled({ pathBefore, pathNow: s.path, chatBefore, chatNow, arrived })) return + // Save what is waiting first; nothing saved, no reload (and no resume marker left behind). + let saved = true + beforeReload.forEach((fn) => { try { if (!fn()) saved = false } catch { saved = false } }) + if (!saved) return + try { + const resume: Resume = { at: Date.now(), path: s.path, chatId: s.path === '/chat' ? chatNow : null } + localStorage.setItem(RESUME_KEY, JSON.stringify(resume)) + } catch { /* it lands on the landing page instead */ } + Updates.reloadAsync().catch(() => { + // Stays on this bundle until the next cold start, which must not think it was a reload. + try { localStorage.removeItem(RESUME_KEY) } catch { /* expires on its own */ } + }) + } + const sub = AppState.addEventListener('change', (next) => { + const s = state.current + if (next === 'background') { s.leftAt = Date.now(); clearTimeout(settle); return } + if (next !== 'active') return + const awayMs = s.leftAt ? Date.now() - s.leftAt : 0 + s.leftAt = 0 + const typing = TextInput.State.currentlyFocusedInput() != null + const newChat = chatState().activeId == null + if (shouldApply({ pending: s.pending, awayMs, held: holds.size > 0, path: s.path, typing, newChat })) { + const pathBefore = s.path + const chatBefore = chatState().activeId + settle = setTimeout(() => apply(pathBefore, chatBefore), SETTLE_MS) + return + } + void check() + }) + return () => { sub.remove(); clearTimeout(settle) } + }, []) + return null +} diff --git a/mobile/src/shell/quickActions.ts b/mobile/src/shell/quickActions.ts index 1d53b4e..3eac926 100644 --- a/mobile/src/shell/quickActions.ts +++ b/mobile/src/shell/quickActions.ts @@ -6,6 +6,7 @@ import { Platform } from 'react-native' import { router } from 'expo-router' import * as QuickActions from 'expo-quick-actions' import { newChat, startVoice } from './nav' +import { noteArrival, resumedFromUpdate } from './otaUpdates' const ITEMS: QuickActions.Action[] = [ { id: 'new-chat', title: 'New chat', icon: 'symbol:square.and.pencil' }, @@ -15,6 +16,7 @@ const ITEMS: QuickActions.Action[] = [ ] function run(action: QuickActions.Action | null | undefined) { + if (action) noteArrival() switch (action?.id) { case 'new-chat': return newChat() case 'voice': return startVoice() @@ -23,12 +25,19 @@ function run(action: QuickActions.Action | null | undefined) { } } +// The launch's action runs once per JS launch: the layout can mount again (signing in again) +// and the native module never clears it. +let initialHandled = false + export function useQuickActions() { useEffect(() => { if (Platform.OS === 'web') return QuickActions.setItems(ITEMS).catch(() => {}) // Launched from an action: the navigator has just mounted, so defer a tick. - const initial = QuickActions.initial + // After a reload into an update, `initial` is still the action of the original cold + // launch (the native module never clears it): replaying it could open voice mode by itself. + const initial = initialHandled || resumedFromUpdate() ? null : QuickActions.initial + initialHandled = true if (initial) setTimeout(() => run(initial), 0) const sub = QuickActions.addListener(run) return () => sub.remove() diff --git a/mobile/src/theme.ts b/mobile/src/theme.ts index e3dd54f..c63248f 100644 --- a/mobile/src/theme.ts +++ b/mobile/src/theme.ts @@ -48,8 +48,6 @@ const base = { // Shell (shell.css) shades that are not tokens on the web. rail: '#0b0c10', drawerOn: '#252a37', - fabVoice: '#2a2f3c', - fabVoiceBorder: '#3a4152', // Toast fills (ToastHost.tsx): white text clears 5.4:1 on each. toastError: '#c42d4c', toastSuccess: '#1f7a34', diff --git a/mobile/src/ui/glass.tsx b/mobile/src/ui/glass.tsx new file mode 100644 index 0000000..a93dba0 --- /dev/null +++ b/mobile/src/ui/glass.tsx @@ -0,0 +1,43 @@ +// iOS 26's liquid glass for the app's floating controls: the drawer's foot, the +// corner new-chat button and the sheets opened from the drawer. Each control is its +// own glass shape; a GlassGroup lets shapes within `spacing` of each other melt +// together, the way iOS 26's toolbars do, so a row of buttons reads as one piece. +// Older iOS, Android and the web preview get the solid `fallback` style instead. +import React from 'react' +import { Platform, View, type PressableProps, type StyleProp, type ViewStyle } from 'react-native' +import { GlassContainer, GlassView, isGlassEffectAPIAvailable, isLiquidGlassAvailable } from 'expo-glass-effect' +import { Press } from './kit' + +export const GLASS = Platform.OS === 'ios' && isLiquidGlassAvailable() && isGlassEffectAPIAvailable() + +/** The light glass of the app's one primary button: New chat, in the corner and the drawer's foot. */ +export const FAB_TINT = 'rgba(230, 232, 238, 0.82)' + +/** Shapes inside melt into one another when closer than `spacing`. */ +export function GlassGroup({ spacing = 12, style, children }: { spacing?: number; style?: StyleProp; children: React.ReactNode }) { + if (!GLASS) return {children} + return {children} +} + +/** + * A pressable glass shape. `shape` is its size and corner radius, `fallback` the solid + * look without glass (a fill, a border), `tint` the glass's colour (the light new-chat + * button). The press target fills the shape, so the whole capsule takes the tap. + */ +export function GlassButton({ shape, fallback, tint, inner, children, ...press }: PressableProps & { + haptic?: boolean + shape: StyleProp + fallback?: StyleProp + tint?: string + /** The content's layout inside the shape (a row of label and count). */ + inner?: StyleProp + children: React.ReactNode +}) { + const body = {children} + if (!GLASS) return {body} + return ( + + {body} + + ) +} diff --git a/mobile/src/ui/toastFloor.ts b/mobile/src/ui/toastFloor.ts index 085f5d0..7d0b680 100644 --- a/mobile/src/ui/toastFloor.ts +++ b/mobile/src/ui/toastFloor.ts @@ -1,6 +1,6 @@ // What the toast deck has to sit above at the bottom of the screen. The open -// chat registers its dock (composer and what rides on it), the floating voice and -// new-chat buttons register themselves, each only while their screen is focused. +// chat registers its dock (composer and what rides on it), the floating new-chat +// button registers itself, each only while their screen is focused. // ToastHost adds the keyboard on top. import { useSyncExternalStore } from 'react' @@ -9,7 +9,7 @@ export type ToastFloor = { dock: number /** How much of the keyboard the dock's own bottom gap already absorbs. */ lift: number - /** The floating buttons are in the bottom-right corner. */ + /** The floating new-chat button is in the bottom-right corner. */ fab: boolean }