From 461f557d4ef0088e31c1c51ebcba191422fc6c6a Mon Sep 17 00:00:00 2001
From: Dhairya <127371606+Dkm0315@users.noreply.github.com>
Date: Sun, 15 Nov 2026 09:04:06 +0530
Subject: [PATCH 1/7] Mobile phase 5: spec cases 24A-24P and red desktop tests
for diff review, keep, undo and Stop (#326)
---
docs/spec/clauses/23-mobile.md | 200 +++++++++++++-
.../agent-app/src/shared/mobile/protocol.ts | 42 ++-
.../agent-app/tests/mobile-phase5-326.test.ts | 252 ++++++++++++++++++
packages/mobile/package.json | 3 +
packages/mobile/pnpm-lock.yaml | 115 ++++++++
5 files changed, 609 insertions(+), 3 deletions(-)
create mode 100644 packages/agent-app/tests/mobile-phase5-326.test.ts
diff --git a/docs/spec/clauses/23-mobile.md b/docs/spec/clauses/23-mobile.md
index cf36072b..b4d48a17 100644
--- a/docs/spec/clauses/23-mobile.md
+++ b/docs/spec/clauses/23-mobile.md
@@ -10,13 +10,15 @@ What the user can do:
- revoke a phone, or change it between read only and act, from the desktop;
- start a new chat from the phone in a folder or Project with a provider and model, and send photos and files (phase 2);
- connect straight to the desktop when both are on the same network, with the relay as the fallback (phase 2);
-- pair several computers and switch between them or see all at once, read the last known state with no connection, write messages that go out on reconnect, read replies as native Markdown, and use the app on tablets and in landscape (phase 4).
+- pair several computers and switch between them or see all at once, read the last known state with no connection, write messages that go out on reconnect, read replies as native Markdown, and use the app on tablets and in landscape (phase 4);
+- review a chat’s changed files and their diffs and keep or undo each file or change, and stop a running turn (phase 5).
Boundaries:
- The phone talks to the desktop through a relay, or directly on the same network, with end-to-end encryption (Noise IK) either way; the relay and the network see only ciphertext.
- A new phone is read-only. The phone can never raise a chat's access level or approve for a whole session.
- Pairing needs secure storage on the desktop and a one-time code that expires.
- Each computer keeps its own keys and its own cached data; the phone caches only what it was shown and wipes a computer’s cache when that computer revokes it or is unpaired. Approvals are never queued offline.
+- Keeping, undoing and stopping need act access, checked again right before the desktop runs them; the phone sees folder-relative paths only and gets diffs already highlighted, in pages.
- Production relay hosting, push notifications, Projects and dictation are later phases (see the design).
## Acceptance cases
@@ -100,6 +102,22 @@ Boundaries:
| [MUS-SPEC-23-23C](23-mobile.md#mus-spec-23-23c) | The removed item is gone from the screen, the other two stay, and chat.open is not called again. | [`a remove op takes the row off the chat screen`](../../../packages/mobile/tests/chat-stream.test.tsx) |
| [MUS-SPEC-23-23D](23-mobile.md#mus-spec-23-23d) | Every delta for the reply is an append or a status change, never the whole item. The phone’s text is the reply’s first 65,536 characters followed by a note that the rest is on the computer, and the finished status reaches the phone. | [`a reply that grows past the phone’s item cap is sent as appends and says the rest is on the computer`](../../../packages/agent-app/tests/mobile-phase3-326.test.ts) |
| [MUS-SPEC-23-23E](23-mobile.md#mus-spec-23-23e) | Sending the same chat.send again with its request id, while the turn runs and after it ends, answers with the first run id and no error, and the chat has the message once; a steer sent again with its request id answers steered and reaches the agent once. | [`a message or steer the computer already took is answered as sent when the phone sends it again`](../../../packages/agent-app/tests/mobile-phase3-326.test.ts) |
+| [MUS-SPEC-23-24A](23-mobile.md#mus-spec-23-24a) | Primary and secondary text are at least 7:1 and 4.5:1 on every surface in both palettes, the label on the filled accent is at least 4.5:1, and amber, green, red and the accent are at least 3:1 on the canvas. No type style is under 12 points, chat prose is 17 on 26, and code is 13 on 21. The snappy, gentle and bouncy springs have damping, mass and stiffness 26/0.7/330, 20/1/180 and 14/0.8/260; with Reduce Motion on, each is a 150 ms crossfade instead. | [`the v3 palettes keep text readable, the type never goes under 12 and Reduce Motion turns springs into a crossfade`](../../../packages/mobile/tests/v3-tokens.test.tsx) |
+| [MUS-SPEC-23-24B](23-mobile.md#mus-spec-23-24b) | There are no filter chips. Active lists the running and the waiting chat, Earlier the failed and the finished one; each row shows its title and one line of what it is doing (the waiting one says Needs you, the failed one Failed) with a status glyph that names its state for screen readers. After the event the chat that started running is under Active and the phone gives one selection haptic. | [`chats show as two-line rows in Active and Earlier, and a chat that starts running moves into Active with a tick`](../../../packages/mobile/tests/chats-v3.test.tsx) |
+| [MUS-SPEC-23-24C](23-mobile.md#mus-spec-23-24c) | The reasoning and tool rows are one capsule reading Working and 4 steps, not four rows; opening it lists each step. The live line under the reply names the running tool, and the reply ends with the accent caret. After the turn ends the live line is gone, the caret is gone, the capsule reads Worked with its duration and 4 steps, and a summary card says the run finished, 1 file changed, with Review; the phone gives one success haptic. | [`a turn’s steps fold into one capsule, the live line names the running step, and a finished run shows its summary`](../../../packages/mobile/tests/chat-v3.test.tsx) |
+| [MUS-SPEC-23-24D](23-mobile.md#mus-spec-23-24d) | With an empty field the composer shows Stop (with its moving ring) and no floating Working pill; pressing it calls chat.stop for the chat and gives a light haptic. With text typed it shows Steer and the hint that the message goes to the running turn. | [`while a turn runs Send becomes Stop, and Stop stops the turn on the computer with a light tap`](../../../packages/mobile/tests/chat-v3.test.tsx) |
+| [MUS-SPEC-23-24E](23-mobile.md#mus-spec-23-24e) | Before focus the composer is one row (add, field, send) with no chips. Focused, it shows the Photo, Camera and File chips above the field. Blurred with nothing typed, the chips go again. | [`the composer shows its chips only while it is focused`](../../../packages/mobile/tests/chat-v3.test.tsx) |
+| [MUS-SPEC-23-24F](23-mobile.md#mus-spec-23-24f) | The card’s title is the question Run this command?, then the command in a code well, then the reason; Approve is the one filled action and Decline is plain; one quiet line says approving for the whole chat is a desktop setting. Pressing Approve calls approval.respond with accept and settles into an Approved receipt with a success haptic. The watch-only card keeps its question and command but has no buttons and says where to answer it. | [`an approval reads as its question, the command, one line of why and one filled Approve, and a watch-only phone is told where to answer`](../../../packages/mobile/tests/approval-v3.test.tsx) |
+| [MUS-SPEC-23-24G](23-mobile.md#mus-spec-23-24g) | The header counts 1 waiting before. After the answer the screen shows All clear, the answered request as a receipt under Just answered, and exactly one success haptic for the moment. | [`answering the last request shows All clear with one success haptic`](../../../packages/mobile/tests/needs-you-v3.test.tsx) |
+| [MUS-SPEC-23-24H](23-mobile.md#mus-spec-23-24h) | Four tabs show with Chats selected and a badge of 2 on Needs you; search is a separate button. Pressing Needs you goes to that tab with a selection haptic; pressing search opens Chats with its search field. | [`the glass tab bar shows four tabs and the Needs you count, with search as its own circle`](../../../packages/mobile/tests/tabbar.test.tsx) |
+| [MUS-SPEC-23-24I](23-mobile.md#mus-spec-23-24i) | In the switcher and in Settings the watch-only computer carries an eye described as Watch only and the other carries none, and neither shows an access pill. After pairing the screen shows the paired moment: Paired with the computer’s name, that nobody in between can read what passes, and a Continue action, with a success haptic. | [`a watch-only computer carries an eye in the switcher and Settings, and pairing ends on the paired moment`](../../../packages/mobile/tests/computers-v3.test.tsx) |
+| [MUS-SPEC-23-24J](23-mobile.md#mus-spec-23-24j) | changes.list names the turn and lists both files by folder-relative path with their added and removed counts, both to review. The diff of src/store.ts has one hunk named after the function it is in, its removed line marked removed with no number, its added line marked added with its new line number, context lines around them, the changed words marked on both lines, and its code split into coloured tokens from a palette with a dark and a light colour. Nothing in either answer holds the folder’s absolute path. README.md is refused as not one of the turn’s changes. | [`a phone lists a chat’s changed files and reads a highlighted diff with function-named hunks`](../../../packages/agent-app/tests/mobile-phase5-326.test.ts) |
+| [MUS-SPEC-23-24K](23-mobile.md#mus-spec-23-24k) | Every page holds at most 400 lines and names where the next starts; the pages together hold all 5,000 lines once, in order. Each page answers in under 1,500 ms, and every ping sent meanwhile answers in under 500 ms. | [`a 5,000-line diff comes in pages without holding up the desktop`](../../../packages/agent-app/tests/mobile-phase5-326.test.ts) |
+| [MUS-SPEC-23-24L](23-mobile.md#mus-spec-23-24l) | The read-only calls are refused as read only and nothing changes on disk or in the review marks. Keep marks src/key.ts kept on the desktop and changes.list then shows it kept. Undoing the hunk puts src/store.ts back to its text before the turn byte for byte. The undo with the old hash answers stale and leaves the file as written. The undo held while the phone was revoked fails and leaves the file as it was. | [`keep and undo use the desktop’s review commands; a read-only phone, a stale hash or a revoke mid-action changes nothing`](../../../packages/agent-app/tests/mobile-phase5-326.test.ts) |
+| [MUS-SPEC-23-24M](23-mobile.md#mus-spec-23-24m) | The read-only call is refused and the turn keeps running; with act the turn stops and the chat is no longer running. | [`a phone that can act stops a running turn, and a read-only one can’t`](../../../packages/agent-app/tests/mobile-phase5-326.test.ts) |
+| [MUS-SPEC-23-24N](23-mobile.md#mus-spec-23-24n) | The ring and the header say 1 of 3 kept. Files to review show their counts and the kept one says Kept. Swiping right calls changes.keep with the whole file; swiping left calls changes.undo with the file’s hash, and each row then says Kept or Undone. Read-only shows the files and the ring but no Keep all or Undo all, and swipes do nothing. | [`the changes screen shows the review ring and files, keeps and undoes by swipe, and hides actions when read only`](../../../packages/mobile/tests/changes-screen.test.tsx) |
+| [MUS-SPEC-23-24O](23-mobile.md#mus-spec-23-24o) | Each hunk has a pill named in its function, removed lines have no number and added lines their new number, and the toolbar reads 1 of 2. Keep calls changes.keep with the focused hunk and folds it into a Kept pill; next moves to 2 of 2 and Undo calls changes.undo with that hunk. The 5,000-line file renders its first page with only a window of rows mounted and asks for the next page only as the reader nears the end, until it has all 5,000 lines. | [`the diff shows function-named hunks with one gutter, keeps and undoes from the toolbar and pages a 5,000-line file`](../../../packages/mobile/tests/diff-screen.test.tsx) |
+| [MUS-SPEC-23-24P](23-mobile.md#mus-spec-23-24p) | At 390 the diff is inline (one column). At 844 it is split: the removed line on the left with its old number and the added line on the right with its new number, in the same row. | [`landscape and tablet widths show the diff side by side`](../../../packages/mobile/tests/diff-screen.test.tsx) |
### Pairing, the device registry and access
@@ -993,3 +1011,183 @@ Boundaries:
- Environment: Node test runner; the real agent service with a fake provider, the dev relay from packages/relay on 127.0.0.1, and a Node phone built from the same MobileClient and Noise code the app uses, with Node crypto.
- Known gaps: A steer's request id is remembered while the computer's app runs; a steer sent again after a restart can reach the agent twice.
- Evidence: UNVERIFIED
+
+### v3 design (phase 5)
+
+
+#### MUS-SPEC-23-24A: The v3 colours and type keep text readable
+
+- Precondition: The dark and light palettes, the type scale and the motion presets of packages/mobile/src/theme.ts and motion.ts.
+- Action: Measure the contrast of primary and secondary text on the canvas, on a cell and on a raised cell, of the accent label on the filled accent, and of the status hues on the canvas; list every type style; ask for a spring with Reduce Motion off and on.
+- Expected result: Primary and secondary text are at least 7:1 and 4.5:1 on every surface in both palettes, the label on the filled accent is at least 4.5:1, and amber, green, red and the accent are at least 3:1 on the canvas. No type style is under 12 points, chat prose is 17 on 26, and code is 13 on 21. The snappy, gentle and bouncy springs have damping, mass and stiffness 26/0.7/330, 20/1/180 and 14/0.8/260; with Reduce Motion on, each is a 150 ms crossfade instead.
+- Test: `packages/mobile/tests/v3-tokens.test.tsx::the v3 palettes keep text readable, the type never goes under 12 and Reduce Motion turns springs into a crossfade`
+- Environment: jest (jest-expo preset) in Node with @testing-library/react-native; screens are given fake connections with the MobileClient interface.
+- Known gaps: Glass blur and saturation are drawn by the platform and checked on a device.
+- Evidence: UNVERIFIED
+
+
+#### MUS-SPEC-23-24B: Chats are two-line rows grouped into Active and Earlier
+
+- Precondition: The chats screen with a fake connection listing a running chat, a chat waiting on the person, a failed chat and a finished one.
+- Action: Render the screen; then emit a chats event in which the finished chat starts running.
+- Expected result: There are no filter chips. Active lists the running and the waiting chat, Earlier the failed and the finished one; each row shows its title and one line of what it is doing (the waiting one says Needs you, the failed one Failed) with a status glyph that names its state for screen readers. After the event the chat that started running is under Active and the phone gives one selection haptic.
+- Test: `packages/mobile/tests/chats-v3.test.tsx::chats show as two-line rows in Active and Earlier, and a chat that starts running moves into Active with a tick`
+- Environment: jest (jest-expo preset) in Node with @testing-library/react-native; screens are given fake connections with the MobileClient interface.
+- Known gaps: The large title collapsing into the bar and the 2.2 s shimmer are checked on a device.
+- Evidence: UNVERIFIED
+
+
+#### MUS-SPEC-23-24C: Tool steps fold into one capsule and the live line says what runs now
+
+- Precondition: The chat screen with a fake connection whose chat is running: a user message, a reasoning row, three tool rows (the last still running) and a streaming reply.
+- Action: Render the chat; open the capsule; then emit a delta that finishes the running tool and the chat as completed, with one changed file.
+- Expected result: The reasoning and tool rows are one capsule reading Working and 4 steps, not four rows; opening it lists each step. The live line under the reply names the running tool, and the reply ends with the accent caret. After the turn ends the live line is gone, the caret is gone, the capsule reads Worked with its duration and 4 steps, and a summary card says the run finished, 1 file changed, with Review; the phone gives one success haptic.
+- Test: `packages/mobile/tests/chat-v3.test.tsx::a turn’s steps fold into one capsule, the live line names the running step, and a finished run shows its summary`
+- Environment: jest (jest-expo preset) in Node with @testing-library/react-native; screens are given fake connections with the MobileClient interface.
+- Known gaps: The caret blink, the shimmer and the summary ripple are timed on a device.
+- Evidence: UNVERIFIED
+
+
+#### MUS-SPEC-23-24D: Send turns into Stop while a turn runs
+
+- Precondition: The chat screen with a fake connection, access act, whose chat is running.
+- Action: Read the composer with an empty field; press Stop; type a message.
+- Expected result: With an empty field the composer shows Stop (with its moving ring) and no floating Working pill; pressing it calls chat.stop for the chat and gives a light haptic. With text typed it shows Steer and the hint that the message goes to the running turn.
+- Test: `packages/mobile/tests/chat-v3.test.tsx::while a turn runs Send becomes Stop, and Stop stops the turn on the computer with a light tap`
+- Environment: jest (jest-expo preset) in Node with @testing-library/react-native; screens are given fake connections with the MobileClient interface.
+- Known gaps: The ring’s motion is checked on a device.
+- Evidence: UNVERIFIED
+
+
+#### MUS-SPEC-23-24E: The composer shows its chips only while focused
+
+- Precondition: The chat screen with a fake connection, access act, an idle chat and a picker for attachments.
+- Action: Read the composer; focus the field; blur it.
+- Expected result: Before focus the composer is one row (add, field, send) with no chips. Focused, it shows the Photo, Camera and File chips above the field. Blurred with nothing typed, the chips go again.
+- Test: `packages/mobile/tests/chat-v3.test.tsx::the composer shows its chips only while it is focused`
+- Environment: jest (jest-expo preset) in Node with @testing-library/react-native; screens are given fake connections with the MobileClient interface.
+- Known gaps: Keyboard-sticky motion is checked on a device.
+- Evidence: UNVERIFIED
+
+
+#### MUS-SPEC-23-24F: An approval reads as its question, the command and one filled action
+
+- Precondition: An approval card for the command pnpm db:reset --seed with a reason, once for a phone that can act and once for a watch-only phone.
+- Action: Render it for the acting phone and press Approve; render it for the watch-only phone.
+- Expected result: The card’s title is the question Run this command?, then the command in a code well, then the reason; Approve is the one filled action and Decline is plain; one quiet line says approving for the whole chat is a desktop setting. Pressing Approve calls approval.respond with accept and settles into an Approved receipt with a success haptic. The watch-only card keeps its question and command but has no buttons and says where to answer it.
+- Test: `packages/mobile/tests/approval-v3.test.tsx::an approval reads as its question, the command, one line of why and one filled Approve, and a watch-only phone is told where to answer`
+- Environment: jest (jest-expo preset) in Node with @testing-library/react-native; screens are given fake connections with the MobileClient interface.
+- Known gaps: Face ID before approving is the app lock of a later phase.
+- Evidence: UNVERIFIED
+
+
+#### MUS-SPEC-23-24G: Answering the last request is all clear
+
+- Precondition: Needs you with a fake connection listing one approval.
+- Action: Approve it; let the computer’s needs event say nothing waits.
+- Expected result: The header counts 1 waiting before. After the answer the screen shows All clear, the answered request as a receipt under Just answered, and exactly one success haptic for the moment.
+- Test: `packages/mobile/tests/needs-you-v3.test.tsx::answering the last request shows All clear with one success haptic`
+- Environment: jest (jest-expo preset) in Node with @testing-library/react-native; screens are given fake connections with the MobileClient interface.
+- Known gaps: The drawn check and the ring burst are timed on a device; with Reduce Motion the check is static.
+- Evidence: UNVERIFIED
+
+
+#### MUS-SPEC-23-24H: The glass tab bar keeps search in its own circle
+
+- Precondition: The tab bar with the Chats tab selected and two requests waiting.
+- Action: Render it; press Needs you; press the search circle.
+- Expected result: Four tabs show with Chats selected and a badge of 2 on Needs you; search is a separate button. Pressing Needs you goes to that tab with a selection haptic; pressing search opens Chats with its search field.
+- Test: `packages/mobile/tests/tabbar.test.tsx::the glass tab bar shows four tabs and the Needs you count, with search as its own circle`
+- Environment: jest (jest-expo preset) in Node with @testing-library/react-native; screens are given fake connections with the MobileClient interface.
+- Known gaps: The glass material (iOS 26 glass, blur below it, tonal surface on Android) is drawn natively and checked on a device.
+- Evidence: UNVERIFIED
+
+
+#### MUS-SPEC-23-24I: Computers show watch-only with an eye, and pairing ends on a moment
+
+- Precondition: Two computers, one that can act and one watch-only; the pair screen with a pairing that confirms.
+- Action: Open the computer switcher and Settings; pair.
+- Expected result: In the switcher and in Settings the watch-only computer carries an eye described as Watch only and the other carries none, and neither shows an access pill. After pairing the screen shows the paired moment: Paired with the computer’s name, that nobody in between can read what passes, and a Continue action, with a success haptic.
+- Test: `packages/mobile/tests/computers-v3.test.tsx::a watch-only computer carries an eye in the switcher and Settings, and pairing ends on the paired moment`
+- Environment: jest (jest-expo preset) in Node with @testing-library/react-native; screens are given fake connections with the MobileClient interface.
+- Known gaps: The fingerprint scramble and shield animation are checked on a device.
+- Evidence: UNVERIFIED
+
+### Diff review with keep and undo (phase 5)
+
+
+#### MUS-SPEC-23-24J: A phone reads a chat’s changed files and a highlighted diff
+
+- Precondition: A desktop with a folder that is a Git repository and a chat in it whose fake provider edits src/store.ts inside a function and adds src/key.ts during a turn; a paired read-only phone.
+- Action: Run the turn; from the phone call changes.list for the chat, changes.diff for src/store.ts, and changes.diff for README.md, which is in the folder but not changed by the turn.
+- Expected result: changes.list names the turn and lists both files by folder-relative path with their added and removed counts, both to review. The diff of src/store.ts has one hunk named after the function it is in, its removed line marked removed with no number, its added line marked added with its new line number, context lines around them, the changed words marked on both lines, and its code split into coloured tokens from a palette with a dark and a light colour. Nothing in either answer holds the folder’s absolute path. README.md is refused as not one of the turn’s changes.
+- Test: `packages/agent-app/tests/mobile-phase5-326.test.ts::a phone lists a chat’s changed files and reads a highlighted diff with function-named hunks`
+- Environment: Node test runner; the real agent service with a fake provider that edits files in a temporary Git repository during its turn, the dev relay from packages/relay on 127.0.0.1, and Node phones built from the same MobileClient and Noise code the app uses, with Node crypto.
+- Known gaps: Highlighting covers the common languages bundled with the desktop’s runtime; other files come as plain text.
+- Evidence: UNVERIFIED
+
+
+#### MUS-SPEC-23-24K: A 5,000-line diff comes in pages without holding up the desktop
+
+- Precondition: The chat of 24J whose turn also writes a new 5,000-line file.
+- Action: Read the file’s diff page by page with changes.diff; while each page is read, ping the desktop from a second session.
+- Expected result: Every page holds at most 400 lines and names where the next starts; the pages together hold all 5,000 lines once, in order. Each page answers in under 1,500 ms, and every ping sent meanwhile answers in under 500 ms.
+- Test: `packages/agent-app/tests/mobile-phase5-326.test.ts::a 5,000-line diff comes in pages without holding up the desktop`
+- Environment: Node test runner; the real agent service with a fake provider that edits files in a temporary Git repository during its turn, the dev relay from packages/relay on 127.0.0.1, and Node phones built from the same MobileClient and Noise code the app uses, with Node crypto.
+- Known gaps: Times are measured on the CI runner; the receipt in the PR lists the times measured locally.
+- Evidence: UNVERIFIED
+
+
+#### MUS-SPEC-23-24L: Keep and undo use the desktop’s review commands, and only with act
+
+- Precondition: The chat of 24J after its turn; a paired phone, first read-only; a gate that holds a request after its reads.
+- Action: While read-only, call changes.keep and changes.undo. Allow the phone to act; keep src/key.ts; undo the hunk of src/store.ts. Write src/key.ts again on disk and undo it with the hash read before. Hold an undo of src/key.ts at the gate, revoke the phone on the desktop, and release it.
+- Expected result: The read-only calls are refused as read only and nothing changes on disk or in the review marks. Keep marks src/key.ts kept on the desktop and changes.list then shows it kept. Undoing the hunk puts src/store.ts back to its text before the turn byte for byte. The undo with the old hash answers stale and leaves the file as written. The undo held while the phone was revoked fails and leaves the file as it was.
+- Test: `packages/agent-app/tests/mobile-phase5-326.test.ts::keep and undo use the desktop’s review commands; a read-only phone, a stale hash or a revoke mid-action changes nothing`
+- Environment: Node test runner; the real agent service with a fake provider that edits files in a temporary Git repository during its turn, the dev relay from packages/relay on 127.0.0.1, and Node phones built from the same MobileClient and Noise code the app uses, with Node crypto.
+- Known gaps: Undo all on the phone undoes file by file; a file renamed by the turn is undone as the desktop does it, not exercised here.
+- Evidence: UNVERIFIED
+
+
+#### MUS-SPEC-23-24M: A phone that can act stops a running turn
+
+- Precondition: A desktop chat whose fake provider runs a turn until stopped; a paired phone, first read-only.
+- Action: Call chat.stop while read-only; allow the phone to act; call chat.stop.
+- Expected result: The read-only call is refused and the turn keeps running; with act the turn stops and the chat is no longer running.
+- Test: `packages/agent-app/tests/mobile-phase5-326.test.ts::a phone that can act stops a running turn, and a read-only one can’t`
+- Environment: Node test runner; the real agent service with a fake provider, the dev relay from packages/relay on 127.0.0.1, and Node phones built from the same MobileClient and Noise code the app uses, with Node crypto.
+- Known gaps: None known.
+- Evidence: UNVERIFIED
+
+
+#### MUS-SPEC-23-24N: The changes screen keeps and undoes files
+
+- Precondition: The changes screen with a fake connection whose changes.list answers three files, one already kept; access act, then read-only.
+- Action: Render it; swipe one file right and another left; render it read-only.
+- Expected result: The ring and the header say 1 of 3 kept. Files to review show their counts and the kept one says Kept. Swiping right calls changes.keep with the whole file; swiping left calls changes.undo with the file’s hash, and each row then says Kept or Undone. Read-only shows the files and the ring but no Keep all or Undo all, and swipes do nothing.
+- Test: `packages/mobile/tests/changes-screen.test.tsx::the changes screen shows the review ring and files, keeps and undoes by swipe, and hides actions when read only`
+- Environment: jest (jest-expo preset) in Node with @testing-library/react-native; screens are given fake connections with the MobileClient interface.
+- Known gaps: Swipe feel is checked on a device.
+- Evidence: UNVERIFIED
+
+
+#### MUS-SPEC-23-24O: The diff is built for a phone and pages a 5,000-line file
+
+- Precondition: The diff screen with a fake connection whose changes.diff answers two hunks named after functions, then a 5,000-line file in pages of 400 lines.
+- Action: Render the first file; press Keep in the toolbar, then next and Undo; open the 5,000-line file and scroll to its end.
+- Expected result: Each hunk has a pill named in its function, removed lines have no number and added lines their new number, and the toolbar reads 1 of 2. Keep calls changes.keep with the focused hunk and folds it into a Kept pill; next moves to 2 of 2 and Undo calls changes.undo with that hunk. The 5,000-line file renders its first page with only a window of rows mounted and asks for the next page only as the reader nears the end, until it has all 5,000 lines.
+- Test: `packages/mobile/tests/diff-screen.test.tsx::the diff shows function-named hunks with one gutter, keeps and undoes from the toolbar and pages a 5,000-line file`
+- Environment: jest (jest-expo preset) in Node with @testing-library/react-native; screens are given fake connections with the MobileClient interface.
+- Known gaps: Scrolling frame time is measured on a device.
+- Evidence: UNVERIFIED
+
+
+#### MUS-SPEC-23-24P: Landscape and tablets show the diff side by side
+
+- Precondition: The diff screen with a fake connection answering one hunk with one removed and one added line.
+- Action: Render it 390 points wide, then 844 points wide.
+- Expected result: At 390 the diff is inline (one column). At 844 it is split: the removed line on the left with its old number and the added line on the right with its new number, in the same row.
+- Test: `packages/mobile/tests/diff-screen.test.tsx::landscape and tablet widths show the diff side by side`
+- Environment: jest (jest-expo preset) in Node with @testing-library/react-native; screens are given fake connections with the MobileClient interface.
+- Known gaps: Anchoring the focused hunk through a rotation is checked on a device.
+- Evidence: UNVERIFIED
diff --git a/packages/agent-app/src/shared/mobile/protocol.ts b/packages/agent-app/src/shared/mobile/protocol.ts
index 37fab473..5d4ef9a1 100644
--- a/packages/agent-app/src/shared/mobile/protocol.ts
+++ b/packages/agent-app/src/shared/mobile/protocol.ts
@@ -110,6 +110,34 @@ export const UPLOADS_AT_ONCE = 2;
export const MAX_SEND_ATTACHMENTS = 10;
export interface MobileAttachment { id: string; name: string; mime: string; size: number; kind: 'image' | 'file' }
+
+/** A file the chat's latest turn changed (phase 5), by its path inside the chat's folder. `state` is what the person decided:
+ * still to review, kept or undone. An undone file is listed from the review marks after it left the change list. */
+export type MobileReviewState = 'review' | 'kept' | 'undone';
+export interface MobileChange {
+ path: string; previousPath?: string; status: 'modified' | 'added' | 'deleted' | 'renamed'; adds: number; dels: number;
+ binary?: boolean; state: MobileReviewState; afterHash: string;
+}
+/** A run of code with one colour: the text and an index into the diff's `palette` (no index: the text colour). */
+export type MobileToken = [text: string, color?: number];
+/** One diff line (phase 5): added, removed or context, the hunk it belongs to, its new line number (none for a removed line),
+ * its code as coloured tokens, and the changed words as [start, end) character ranges. */
+export interface MobileDiffLine { k: 'a' | 'd' | 'c'; h: number; n?: number; old?: number; t: MobileToken[]; w?: Array<[number, number]> }
+/** A hunk: its id for keep and undo, the function it is in (or null), its first new line and its size. */
+export interface MobileHunk { id: string; fn: string | null; newStart: number; adds: number; dels: number; state: MobileReviewState }
+/** Lines one changes.diff page holds at most. */
+export const DIFF_PAGE_LINES = 400;
+export interface MobileDiffPage {
+ runId: string; path: string; status: MobileChange['status']; afterHash: string; adds: number; dels: number;
+ /** Too large or binary: no lines; open it on the computer. */
+ binary?: boolean; tooLarge?: boolean;
+ /** Token colours as [dark, light]. */
+ palette: Array<[string, string]>;
+ hunks: MobileHunk[];
+ /** Lines `from` to `from + lines.length` of `total`; `next` is where the next page starts, null at the end. */
+ lines: MobileDiffLine[]; from: number; total: number; next: number | null;
+}
+
/** Methods the phone may call. Every one is checked on the desktop against the phone's access. */
export interface MobileMethods {
/** `lan`: the desktop's current direct addresses (phase 2), so the phone's record follows network changes. */
@@ -142,11 +170,21 @@ export interface MobileMethods {
'upload.cancel': {params: {uploadId: string}; result: Record};
/** Removes a file this phone uploaded and has not sent (the person took it out of the composer). */
'upload.discard': {params: {chatId: string; attachmentId: string}; result: Record};
+ /** The chat's latest turn's changed files (phase 5); runId is null when the chat has no turn with a snapshot. */
+ 'changes.list': {params: {chatId: string}; result: {runId: string | null; files: MobileChange[]; truncated: boolean}};
+ /** One page of a changed file's diff, highlighted on the computer. `from` is a line index (0 for the first page). */
+ 'changes.diff': {params: {chatId: string; path: string; from?: number}; result: MobileDiffPage};
+ /** Keeps hunks of a file of the turn ('*' for the whole file); the computer records it as its own Keep does. */
+ 'changes.keep': {params: {chatId: string; runId: string; path: string; hunkIds: string[]}; result: {state: MobileReviewState}};
+ /** Undoes one hunk, or the whole file without a hunk id, if the file is still as the phone read it (`afterHash`). */
+ 'changes.undo': {params: {chatId: string; runId: string; path: string; afterHash: string; hunkId?: string}; result: {stale: boolean}};
+ /** Stops the chat's running turn. */
+ 'chat.stop': {params: {id: string}; result: Record};
}
export type MobileMethod = keyof MobileMethods;
-export const MOBILE_METHODS: readonly MobileMethod[] = ['hello', 'ping', 'chats.list', 'chat.open', 'chat.close', 'chat.send', 'chat.steer', 'approval.respond', 'question.respond', 'needs.list', 'chat.options', 'chat.create', 'upload.start', 'upload.chunk', 'upload.finish', 'upload.cancel', 'upload.discard'];
+export const MOBILE_METHODS: readonly MobileMethod[] = ['hello', 'ping', 'chats.list', 'chat.open', 'chat.close', 'chat.send', 'chat.steer', 'approval.respond', 'question.respond', 'needs.list', 'chat.options', 'chat.create', 'upload.start', 'upload.chunk', 'upload.finish', 'upload.cancel', 'upload.discard', 'changes.list', 'changes.diff', 'changes.keep', 'changes.undo', 'chat.stop'];
/** Methods a read-only phone may not call. chat.options is only for starting a chat, so it is acting too. */
-export const ACTING_METHODS: ReadonlySet = new Set(['chat.send', 'chat.steer', 'approval.respond', 'question.respond', 'chat.options', 'chat.create', 'upload.start', 'upload.chunk', 'upload.finish', 'upload.cancel', 'upload.discard']);
+export const ACTING_METHODS: ReadonlySet = new Set(['chat.send', 'chat.steer', 'approval.respond', 'question.respond', 'chat.options', 'chat.create', 'upload.start', 'upload.chunk', 'upload.finish', 'upload.cancel', 'upload.discard', 'changes.keep', 'changes.undo', 'chat.stop']);
export type MobileEvent =
| {type: 'chats'; chats: MobileChat[]}
diff --git a/packages/agent-app/tests/mobile-phase5-326.test.ts b/packages/agent-app/tests/mobile-phase5-326.test.ts
new file mode 100644
index 00000000..7a28979f
--- /dev/null
+++ b/packages/agent-app/tests/mobile-phase5-326.test.ts
@@ -0,0 +1,252 @@
+/** #326 phase 5: diff review with keep and undo, and Stop, from the phone. The "phone" is Node running the same MobileClient and
+ * Noise code the app runs (Node crypto), against the real agent service, a temporary Git repository and the dev relay. */
+import assert from 'node:assert/strict';
+import {test, type TestContext} from 'node:test';
+import {execFileSync} from 'node:child_process';
+import {mkdir, mkdtemp, readFile, rm, writeFile} from 'node:fs/promises';
+import {tmpdir} from 'node:os';
+import {join} from 'node:path';
+import {setTimeout as delay} from 'node:timers/promises';
+import {startRelay, type DevRelay} from '../../relay/src/relay.ts';
+import {createAgentService} from '../src/runtime/service.ts';
+import type {ProviderAdapter, ProviderInput, ProviderResult} from '../src/runtime/provider.ts';
+import {SecretStore} from '../src/runtime/secret-store.ts';
+import {mobileSeams} from '../src/runtime/domains/mobile.ts';
+import {nodeNoiseCrypto} from '../src/runtime/mobile/node-crypto.ts';
+import {connectPhone, pairPhone, MobileError, type MobileConnection, type PairedRecord} from '../src/shared/mobile/client.ts';
+import {DIFF_PAGE_LINES, type MobileDiffLine} from '../src/shared/mobile/protocol.ts';
+
+const makeBox = () => ({isEncryptionAvailable: () => true, encryptString: (value: string) => Buffer.from(`box:${value}`), decryptString: (value: Buffer) => value.toString().slice(4)});
+const socket = (url: string) => new WebSocket(url);
+const crypto = nodeNoiseCrypto();
+const git = (cwd: string, ...args: string[]) => execFileSync('git', ['-c', 'user.email=t@t', '-c', 'user.name=t', '-c', 'gc.auto=0', ...args], {cwd, stdio: 'pipe'});
+
+async function until(check: () => boolean | Promise, label: string, ms = 15_000) {
+ const end = Date.now() + ms;
+ while (Date.now() < end) { if (await check()) return; await delay(10); }
+ assert.fail(`${label} not reached`);
+}
+const rejection = async (work: Promise) => { try { await work; } catch (error) { return error as MobileError; } assert.fail('expected a rejection'); };
+
+const STORE_BEFORE = `export class Store {
+ constructor(private list: List) {}
+
+ append(id: string) {
+ const at = Date.now();
+ return this.list.push(id);
+ }
+
+ read(id: string) {
+ return this.list.get(id);
+ }
+}
+`;
+const STORE_AFTER = STORE_BEFORE.replace('return this.list.push(id);', 'return this.stream.add(id, at);');
+const KEY = 'export const streamKey = (id: string) => `session:${id}`;\n';
+
+interface Desktop { relay: DevRelay; service: ReturnType; root: string; chatId: string }
+/** A desktop with a Git folder and a chat in it whose turn runs `edit` after its review baseline is taken. */
+async function desktop(t: TestContext, edit: (root: string, input: ProviderInput) => Promise): Promise {
+ const relay = await startRelay({test: true});
+ const dataDir = await mkdtemp(join(tmpdir(), 'muster-mobile-p5-'));
+ const root = join(dataDir, 'atlas-api');
+ await mkdir(join(root, 'src'), {recursive: true});
+ git(root, 'init', '-q');
+ git(root, 'config', 'gc.auto', '0');
+ await writeFile(join(root, 'src', 'store.ts'), STORE_BEFORE);
+ await writeFile(join(root, 'README.md'), '# atlas\n');
+ git(root, 'add', '.'); git(root, 'commit', '-qm', 'init');
+ const secrets = new SecretStore(dataDir, () => makeBox());
+ mobileSeams.secrets = () => secrets;
+ mobileSeams.lanHosts = [];
+ let service!: ReturnType;
+ const provider: ProviderAdapter = {
+ info: () => [{id: 'fake', name: 'Fake', available: true, identityMasked: 'Hidden', models: [{id: 'fake-model', name: 'Fake model'}]}],
+ stop: async () => true, dispose() {}, async steer() { return true; },
+ async run(input) {
+ input.onThreadReady?.('thread-1');
+ // A real turn's first write comes after a model round trip; waiting for the baseline stands in for it.
+ await service.invoke('review.baselines' as never, {chatId: input.chat.id} as never);
+ return (await edit(root, input)) ?? {status: 'completed', finalMessage: 'done'};
+ },
+ };
+ service = createAgentService({dataDir, provider, onEvent() {}});
+ t.after(async () => {
+ await service.dispose();
+ await relay.close();
+ secrets.close();
+ for (const key of Object.keys(mobileSeams)) delete (mobileSeams as Record)[key];
+ await rm(dataDir, {recursive: true, force: true, maxRetries: 5, retryDelay: 200});
+ });
+ await service.invoke('mobile.relay.set', {url: relay.url});
+ const folder = await service.invoke('folder.add', {path: root});
+ const chat = await service.invoke('chat.create', {folderId: folder.id});
+ return {relay, service, root, chatId: chat.id};
+}
+async function pair(t: TestContext, d: Desktop): Promise<{client: MobileConnection; record: PairedRecord}> {
+ const {link} = await d.service.invoke('mobile.pair.start', {});
+ const {client, record, checkCode, confirmed} = await pairPhone({link, crypto, socket, name: 'Test phone', platform: 'android'});
+ t.after(() => client.close());
+ await d.service.invoke('mobile.pair.confirm', {checkCode});
+ await confirmed;
+ return {client, record};
+}
+async function reconnect(t: TestContext, record: PairedRecord): Promise {
+ const client = await connectPhone({record, crypto, socket});
+ t.after(() => client.close());
+ return client;
+}
+async function allowAct(d: Desktop, client: MobileConnection) {
+ const [entry] = (await d.service.invoke('mobile.status', {})).devices;
+ await d.service.invoke('mobile.devices.setAccess', {id: entry!.id, access: 'act'});
+ await until(() => client.access === 'act', 'access event');
+}
+async function runTurn(d: Desktop) {
+ await d.service.invoke('chat.send', {id: d.chatId, text: 'move the store to streams', requestId: `p5-${Date.now().toString(36)}`});
+ await until(async () => (await d.service.invoke('app.snapshot', undefined)).chats.find(chat => chat.id === d.chatId)?.status === 'completed', 'turn completed');
+}
+const editStore = async (root: string) => {
+ await writeFile(join(root, 'src', 'store.ts'), STORE_AFTER);
+ await writeFile(join(root, 'src', 'key.ts'), KEY);
+};
+const textOf = (line: MobileDiffLine) => line.t.map(([text]) => text).join('');
+
+// Spec: MUS-SPEC-23-24J (docs/spec/clauses/23-mobile.md#mus-spec-23-24j)
+test('a phone lists a chat’s changed files and reads a highlighted diff with function-named hunks', async t => {
+ const d = await desktop(t, editStore);
+ const {client} = await pair(t, d);
+ await runTurn(d);
+ const list = await client.call('changes.list', {chatId: d.chatId});
+ assert.ok(list.runId, 'the turn is named');
+ const byPath = new Map(list.files.map(file => [file.path, file]));
+ assert.deepEqual([...byPath.keys()].sort(), ['src/key.ts', 'src/store.ts']);
+ assert.deepEqual({adds: byPath.get('src/store.ts')!.adds, dels: byPath.get('src/store.ts')!.dels, state: byPath.get('src/store.ts')!.state, status: byPath.get('src/store.ts')!.status}, {adds: 1, dels: 1, state: 'review', status: 'modified'});
+ assert.deepEqual({adds: byPath.get('src/key.ts')!.adds, state: byPath.get('src/key.ts')!.state, status: byPath.get('src/key.ts')!.status}, {adds: 1, state: 'review', status: 'added'});
+
+ const page = await client.call('changes.diff', {chatId: d.chatId, path: 'src/store.ts'});
+ assert.equal(page.hunks.length, 1);
+ assert.match(page.hunks[0]!.fn ?? '', /append/, 'the hunk is named after its function');
+ assert.equal(page.next, null);
+ const removed = page.lines.filter(line => line.k === 'd'), added = page.lines.filter(line => line.k === 'a'), context = page.lines.filter(line => line.k === 'c');
+ assert.equal(removed.length, 1); assert.equal(added.length, 1);
+ assert.equal(removed[0]!.n, undefined, 'a removed line has no new line number');
+ assert.equal(added[0]!.n, 6, 'an added line carries its new line number');
+ assert.equal(textOf(removed[0]!), ' return this.list.push(id);');
+ assert.equal(textOf(added[0]!), ' return this.stream.add(id, at);');
+ assert.ok(context.length >= 2, 'context lines around the change');
+ const marked = (line: MobileDiffLine) => (line.w ?? []).map(([from, to]) => textOf(line).slice(from, to)).join('|');
+ assert.match(marked(removed[0]!), /list/, 'changed words are marked on the removed line');
+ assert.match(marked(added[0]!), /stream/, 'changed words are marked on the added line');
+ assert.doesNotMatch(marked(added[0]!), /return/, 'unchanged words are not marked');
+ const coloured = page.lines.flatMap(line => line.t).filter(([, color]) => color !== undefined);
+ assert.ok(coloured.length > 0, 'code arrives as coloured tokens');
+ for (const [, color] of coloured) { const entry = page.palette[color!]; assert.ok(entry && /^#[0-9a-f]{6}/i.test(entry[0]) && /^#[0-9a-f]{6}/i.test(entry[1]), 'each colour has a dark and a light value'); }
+ const keyword = page.lines.flatMap(line => line.t).find(([text]) => text.trim() === 'return');
+ assert.notEqual(keyword?.[1], undefined, 'a keyword is coloured');
+
+ assert.equal(JSON.stringify(list).includes(d.root), false, 'no absolute path in the list');
+ assert.equal(JSON.stringify(page).includes(d.root), false, 'no absolute path in the diff');
+ const refused = await rejection(client.call('changes.diff', {chatId: d.chatId, path: 'README.md'}));
+ assert.equal(refused.code, 'not-found');
+ const outside = await rejection(client.call('changes.diff', {chatId: d.chatId, path: '../../etc/passwd'}));
+ assert.ok(outside.code === 'not-found' || outside.code === 'bad-request');
+});
+
+// Spec: MUS-SPEC-23-24K (docs/spec/clauses/23-mobile.md#mus-spec-23-24k)
+test('a 5,000-line diff comes in pages without holding up the desktop', async t => {
+ const LINES = 5000;
+ const d = await desktop(t, async root => {
+ await editStore(root);
+ await writeFile(join(root, 'src', 'big.ts'), Array.from({length: LINES}, (_, index) => `export const value${index} = { id: ${index}, name: 'row ${index}' }; // row ${index}\n`).join(''));
+ });
+ const {client, record} = await pair(t, d);
+ const other = await reconnect(t, record);
+ await runTurn(d);
+ const lines: MobileDiffLine[] = [];
+ const pages: number[] = [], pings: number[] = [];
+ let from: number | null = 0;
+ while (from !== null) {
+ const started = performance.now();
+ let pinging = true;
+ const pinger = (async () => { while (pinging) { const at = performance.now(); await other.call('ping', {}); pings.push(performance.now() - at); await delay(20); } })();
+ const page = await client.call('changes.diff', {chatId: d.chatId, path: 'src/big.ts', from});
+ pages.push(performance.now() - started);
+ pinging = false; await pinger;
+ assert.equal(page.from, from, 'the page starts where it was asked');
+ assert.ok(page.lines.length <= DIFF_PAGE_LINES, `a page holds at most ${DIFF_PAGE_LINES} lines (${page.lines.length})`);
+ assert.equal(page.total, LINES);
+ lines.push(...page.lines);
+ from = page.next;
+ }
+ assert.equal(lines.length, LINES, 'every line once');
+ lines.forEach((line, index) => { assert.equal(line.k, 'a'); assert.equal(line.n, index + 1, 'in order'); });
+ assert.ok(Math.max(...pages) < 1500, `every page under 1,500 ms (slowest ${Math.max(...pages).toFixed(0)} ms)`);
+ assert.ok(pings.length > 0 && Math.max(...pings) < 500, `pings answered under 500 ms meanwhile (slowest ${Math.max(...pings).toFixed(0)} ms)`);
+ const receipt = process.env.MOBILE_RECEIPT_FILE;
+ if (receipt) await writeFile(receipt, JSON.stringify({case: 'MUS-SPEC-23-24K', lines: LINES, pages: pages.length, pageMs: pages.map(ms => Math.round(ms)), slowestPingMs: Math.round(Math.max(...pings)), pings: pings.length}, null, 2));
+});
+
+// Spec: MUS-SPEC-23-24L (docs/spec/clauses/23-mobile.md#mus-spec-23-24l)
+test('keep and undo use the desktop’s review commands; a read-only phone, a stale hash or a revoke mid-action changes nothing', async t => {
+ const d = await desktop(t, editStore);
+ const {client} = await pair(t, d);
+ await runTurn(d);
+ const list = await client.call('changes.list', {chatId: d.chatId});
+ const runId = list.runId!;
+ const store = list.files.find(file => file.path === 'src/store.ts')!, key = list.files.find(file => file.path === 'src/key.ts')!;
+ const marks = () => d.service.invoke('review.marks', {runId});
+ const read = (path: string) => readFile(join(d.root, path), 'utf8');
+
+ const keepRefused = await rejection(client.call('changes.keep', {chatId: d.chatId, runId, path: key.path, hunkIds: ['*']}));
+ assert.equal(keepRefused.code, 'read-only');
+ const undoRefused = await rejection(client.call('changes.undo', {chatId: d.chatId, runId, path: store.path, afterHash: store.afterHash}));
+ assert.equal(undoRefused.code, 'read-only');
+ assert.deepEqual(await marks(), [], 'nothing marked');
+ assert.equal(await read('src/store.ts'), STORE_AFTER, 'nothing undone');
+
+ await allowAct(d, client);
+ assert.deepEqual(await client.call('changes.keep', {chatId: d.chatId, runId, path: key.path, hunkIds: ['*']}), {state: 'kept'});
+ assert.ok((await marks()).some(mark => mark.path === 'src/key.ts' && mark.hunkId === '*' && mark.state === 'kept'), 'kept on the desktop');
+ assert.equal((await client.call('changes.list', {chatId: d.chatId})).files.find(file => file.path === 'src/key.ts')!.state, 'kept');
+
+ const diff = await client.call('changes.diff', {chatId: d.chatId, path: store.path});
+ assert.deepEqual(await client.call('changes.undo', {chatId: d.chatId, runId, path: store.path, afterHash: diff.afterHash, hunkId: diff.hunks[0]!.id}), {stale: false});
+ assert.equal(await read('src/store.ts'), STORE_BEFORE, 'the hunk is undone byte for byte');
+
+ await writeFile(join(d.root, 'src', 'key.ts'), `${KEY}// edited after the phone read it\n`);
+ assert.deepEqual(await client.call('changes.undo', {chatId: d.chatId, runId, path: key.path, afterHash: key.afterHash}), {stale: true});
+ assert.equal(await read('src/key.ts'), `${KEY}// edited after the phone read it\n`, 'a stale undo writes nothing');
+
+ const fresh = (await client.call('changes.list', {chatId: d.chatId})).files.find(file => file.path === 'src/key.ts')!;
+ let release!: () => void, held!: () => void;
+ const reached = new Promise(resolve => { held = resolve; });
+ mobileSeams.reviewGate = () => { held(); return new Promise(resolve => { release = resolve; }); };
+ const pending = client.call('changes.undo', {chatId: d.chatId, runId, path: key.path, afterHash: fresh.afterHash}).catch(error => error as Error);
+ await reached;
+ const [entry] = (await d.service.invoke('mobile.status', {})).devices;
+ await d.service.invoke('mobile.devices.revoke', {id: entry!.id});
+ release();
+ assert.ok((await pending) instanceof Error, 'the held undo fails');
+ await delay(100);
+ assert.equal(await read('src/key.ts'), `${KEY}// edited after the phone read it\n`, 'a revoke mid-action leaves the file');
+});
+
+// Spec: MUS-SPEC-23-24M (docs/spec/clauses/23-mobile.md#mus-spec-23-24m)
+test('a phone that can act stops a running turn, and a read-only one can’t', async t => {
+ const d = await desktop(t, async (_root, input) => {
+ // Runs until stopped (or 20 s, so a failing test never hangs the suite).
+ await new Promise(resolve => { const timer = setTimeout(resolve, 20_000); if (input.signal?.aborted) resolve(); input.signal?.addEventListener('abort', () => { clearTimeout(timer); resolve(); }); });
+ return {status: 'interrupted', finalMessage: ''};
+ });
+ const {client} = await pair(t, d);
+ await d.service.invoke('chat.send', {id: d.chatId, text: 'run until stopped', requestId: 'p5-stop'});
+ const status = async () => (await d.service.invoke('app.snapshot', undefined)).chats.find(chat => chat.id === d.chatId)?.status;
+ await until(async () => await status() === 'running', 'turn running');
+ const refused = await rejection(client.call('chat.stop', {id: d.chatId}));
+ assert.equal(refused.code, 'read-only');
+ await delay(100);
+ assert.equal(await status(), 'running', 'a read-only stop changes nothing');
+ await allowAct(d, client);
+ assert.deepEqual(await client.call('chat.stop', {id: d.chatId}), {});
+ await until(async () => await status() !== 'running' && await status() !== 'stopping', 'turn stopped');
+});
diff --git a/packages/mobile/package.json b/packages/mobile/package.json
index f4001608..dedbb931 100644
--- a/packages/mobile/package.json
+++ b/packages/mobile/package.json
@@ -16,12 +16,14 @@
"@noble/curves": "^2.4.0",
"@noble/hashes": "^2.4.0",
"expo": "~58.0.23",
+ "expo-blur": "~58.0.6",
"expo-build-properties": "~58.0.12",
"expo-camera": "~58.0.14",
"expo-clipboard": "~58.0.4",
"expo-constants": "~58.0.15",
"expo-crypto": "~58.0.7",
"expo-document-picker": "~58.0.5",
+ "expo-glass-effect": "~58.0.5",
"expo-haptics": "~58.0.8",
"expo-image-picker": "~58.0.10",
"expo-linking": "~58.0.16",
@@ -37,6 +39,7 @@
"react-native-reanimated": "4.7.1",
"react-native-safe-area-context": "~5.11.1",
"react-native-screens": "~4.30.1",
+ "react-native-svg": "15.16.0",
"react-native-worklets": "0.13.1"
},
"devDependencies": {
diff --git a/packages/mobile/pnpm-lock.yaml b/packages/mobile/pnpm-lock.yaml
index 9c414b15..e295bad1 100644
--- a/packages/mobile/pnpm-lock.yaml
+++ b/packages/mobile/pnpm-lock.yaml
@@ -23,6 +23,9 @@ importers:
expo:
specifier: ~58.0.23
version: 58.0.23(@babel/core@7.29.13)(@expo/dom-webview@58.0.2)(@expo/metro-runtime@58.0.17)(expo-router@58.0.30)(react-dom@19.3.1(react@19.3.1))(react-native-worklets@0.13.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(react-native@0.88.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(@types/react@19.2.18)(react@19.3.1))(react@19.3.1))(react-native@0.88.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(@types/react@19.2.18)(react@19.3.1))(react@19.3.1)(typescript@5.9.3)
+ expo-blur:
+ specifier: ~58.0.6
+ version: 58.0.6(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(@types/react@19.2.18)(react@19.3.1))(react@19.3.1)
expo-build-properties:
specifier: ~58.0.12
version: 58.0.12(expo@58.0.23)
@@ -41,6 +44,9 @@ importers:
expo-document-picker:
specifier: ~58.0.5
version: 58.0.5(expo@58.0.23)
+ expo-glass-effect:
+ specifier: ~58.0.5
+ version: 58.0.5(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(@types/react@19.2.18)(react@19.3.1))(react@19.3.1)
expo-haptics:
specifier: ~58.0.8
version: 58.0.8(expo@58.0.23)
@@ -86,6 +92,9 @@ importers:
react-native-screens:
specifier: ~4.30.1
version: 4.30.1(react-native@0.88.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(@types/react@19.2.18)(react@19.3.1))(react@19.3.1)
+ react-native-svg:
+ specifier: 15.16.0
+ version: 15.16.0(react-native@0.88.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(@types/react@19.2.18)(react@19.3.1))(react@19.3.1)
react-native-worklets:
specifier: 0.13.1
version: 0.13.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(react-native@0.88.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(@types/react@19.2.18)(react@19.3.1))(react@19.3.1)
@@ -1789,6 +1798,9 @@ packages:
resolution: {integrity: sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==}
engines: {node: '>=0.6'}
+ boolbase@1.0.0:
+ resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==}
+
bplist-creator@0.1.0:
resolution: {integrity: sha512-sXaHZicyEEmY86WyueLTQesbeoH/mquvarJaQNbjuOQO+7gbFcDEWqKmcWA4cOTLzFlfgvkiVxolk1k5bBIpmg==}
@@ -1962,6 +1974,17 @@ packages:
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
engines: {node: '>= 8'}
+ css-select@5.2.2:
+ resolution: {integrity: sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==}
+
+ css-tree@1.1.3:
+ resolution: {integrity: sha512-tRpdppF7TRazZrjJ6v3stzv93qxRcSsFmW6cX0Zm2NVKpxE1WV1HblnghVv9TreireHkqI/VDEsfolRF1p6y7Q==}
+ engines: {node: '>=8.0.0'}
+
+ css-what@6.2.2:
+ resolution: {integrity: sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==}
+ engines: {node: '>= 6'}
+
cssstyle@4.6.0:
resolution: {integrity: sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==}
engines: {node: '>=18'}
@@ -2039,6 +2062,19 @@ packages:
dnssd-advertise@1.1.6:
resolution: {integrity: sha512-Ndrrf6BMPalkQPd/zubL+4YghH2J9NspapQ09uDXwYbvOPkP0oaqf5CkcwJ0b50kS2O3ul6yVu+jz+RY62Cejg==}
+ dom-serializer@2.0.0:
+ resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==}
+
+ domelementtype@2.3.0:
+ resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==}
+
+ domhandler@5.0.3:
+ resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==}
+ engines: {node: '>= 4'}
+
+ domutils@3.2.2:
+ resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==}
+
eastasianwidth@0.2.0:
resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==}
@@ -2066,6 +2102,10 @@ packages:
resolution: {integrity: sha512-Ev/hIyePLZtpL98x562lvPtenrUfGr0lfaf44HFZ+hDEwso7ccV9QAZrEVLg0hxNAzygaAFxy2dYaAKKM0G06A==}
engines: {node: '>= 0.8'}
+ entities@4.5.0:
+ resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==}
+ engines: {node: '>=0.12'}
+
entities@6.0.1:
resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==}
engines: {node: '>=0.12'}
@@ -2130,6 +2170,13 @@ packages:
react: '*'
react-native: '*'
+ expo-blur@58.0.6:
+ resolution: {integrity: sha512-gjcw+pBi/15Qy9L0vD6n+KbEbutz6owvrjbYr+74kSaNgj0DEf2qJ7cEU3EJ8/f8KcZss0/7sUWWO9FtBEg+Wg==}
+ peerDependencies:
+ expo: '*'
+ react: '*'
+ react-native: '*'
+
expo-build-properties@58.0.12:
resolution: {integrity: sha512-Wrs1X1iz0kigrBBDs3qILxvXmANccvbsjpR937KqX0Qq7ON6ISk2uJyfz7Tb7/GFhDuJ6MAfW0jR+oryYdOhcg==}
peerDependencies:
@@ -2961,6 +3008,9 @@ packages:
makeerror@1.0.12:
resolution: {integrity: sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==}
+ mdn-data@2.0.14:
+ resolution: {integrity: sha512-dn6wd0uw5GsdswPFfsgMp5NSB0/aDe6fK94YJV/AJDYXL6HVLWBsxeq7js7Ad+mU2K9LAlwpk6kN2D5mwCPVow==}
+
memoize-one@5.2.1:
resolution: {integrity: sha512-zYiwtZUcYyXKo/np96AGZAckk+FWWsUdJ3cHGGmld7+AhvcWmQyGCYUh1hc4Q/pkOhb65dQR/pqCyK0cOaHz4Q==}
@@ -3199,6 +3249,9 @@ packages:
resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==}
engines: {node: '>=8'}
+ nth-check@2.1.1:
+ resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==}
+
nullthrows@1.1.1:
resolution: {integrity: sha512-2vPPEi+Z7WqML2jZYddDIfy5Dqb0r2fze2zTxNNknZaFpVHU3mFB3R+DWeJWGVx0ecvttSGlJTI+WG+8Z4cDWw==}
@@ -3445,6 +3498,12 @@ packages:
react: '*'
react-native: '*'
+ react-native-svg@15.16.0:
+ resolution: {integrity: sha512-uh8yktufYeRU3W9Omi8+SPyLF9BVN4JmLflSgc9oOcKkSKk/S5JUmmTjKZq/L8GHfQUtCvcu/W6X4xhEfBBAjQ==}
+ peerDependencies:
+ react: '*'
+ react-native: '*'
+
react-native-worklets@0.13.1:
resolution: {integrity: sha512-sX55Vx89/Y9uJmvAbAGoHXBZvCWXtYPGWPJ9Z9yl0h76mP9A10ULlSrixzGqBFLXeQMBpIpyJEhWpzXP7GG6YA==}
peerDependencies:
@@ -6111,6 +6170,8 @@ snapshots:
big-integer@1.6.52: {}
+ boolbase@1.0.0: {}
+
bplist-creator@0.1.0:
dependencies:
stream-buffers: 2.2.0
@@ -6280,6 +6341,21 @@ snapshots:
shebang-command: 2.0.0
which: 2.0.2
+ css-select@5.2.2:
+ dependencies:
+ boolbase: 1.0.0
+ css-what: 6.2.2
+ domhandler: 5.0.3
+ domutils: 3.2.2
+ nth-check: 2.1.1
+
+ css-tree@1.1.3:
+ dependencies:
+ mdn-data: 2.0.14
+ source-map: 0.6.1
+
+ css-what@6.2.2: {}
+
cssstyle@4.6.0:
dependencies:
'@asamuzakjp/css-color': 3.2.0
@@ -6326,6 +6402,24 @@ snapshots:
dnssd-advertise@1.1.6: {}
+ dom-serializer@2.0.0:
+ dependencies:
+ domelementtype: 2.3.0
+ domhandler: 5.0.3
+ entities: 4.5.0
+
+ domelementtype@2.3.0: {}
+
+ domhandler@5.0.3:
+ dependencies:
+ domelementtype: 2.3.0
+
+ domutils@3.2.2:
+ dependencies:
+ dom-serializer: 2.0.0
+ domelementtype: 2.3.0
+ domhandler: 5.0.3
+
eastasianwidth@0.2.0: {}
ee-first@1.1.1: {}
@@ -6342,6 +6436,8 @@ snapshots:
encodeurl@2.0.1: {}
+ entities@4.5.0: {}
+
entities@6.0.1: {}
environment@1.1.0: {}
@@ -6404,6 +6500,12 @@ snapshots:
- supports-color
- typescript
+ expo-blur@58.0.6(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(@types/react@19.2.18)(react@19.3.1))(react@19.3.1):
+ dependencies:
+ expo: 58.0.23(@babel/core@7.29.13)(@expo/dom-webview@58.0.2)(@expo/metro-runtime@58.0.17)(expo-router@58.0.30)(react-dom@19.3.1(react@19.3.1))(react-native-worklets@0.13.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(react-native@0.88.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(@types/react@19.2.18)(react@19.3.1))(react@19.3.1))(react-native@0.88.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(@types/react@19.2.18)(react@19.3.1))(react@19.3.1)(typescript@5.9.3)
+ react: 19.3.1
+ react-native: 0.88.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(@types/react@19.2.18)(react@19.3.1)
+
expo-build-properties@58.0.12(expo@58.0.23):
dependencies:
'@expo/schema-utils': 58.0.3
@@ -7466,6 +7568,8 @@ snapshots:
dependencies:
tmpl: 1.0.5
+ mdn-data@2.0.14: {}
+
memoize-one@5.2.1: {}
merge-stream@2.0.0: {}
@@ -7902,6 +8006,10 @@ snapshots:
dependencies:
path-key: 3.1.1
+ nth-check@2.1.1:
+ dependencies:
+ boolbase: 1.0.0
+
nullthrows@1.1.1: {}
nwsapi@2.2.28: {}
@@ -8136,6 +8244,13 @@ snapshots:
react-native: 0.88.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(@types/react@19.2.18)(react@19.3.1)
warn-once: 0.1.1
+ react-native-svg@15.16.0(react-native@0.88.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(@types/react@19.2.18)(react@19.3.1))(react@19.3.1):
+ dependencies:
+ css-select: 5.2.2
+ css-tree: 1.1.3
+ react: 19.3.1
+ react-native: 0.88.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(@types/react@19.2.18)(react@19.3.1)
+
react-native-worklets@0.13.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(react-native@0.88.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(@types/react@19.2.18)(react@19.3.1))(react@19.3.1):
dependencies:
'@babel/core': 7.29.13
From 23299836464621b5ffa0881a8ad462a03f1d9027 Mon Sep 17 00:00:00 2001
From: Dhairya <127371606+Dkm0315@users.noreply.github.com>
Date: Sun, 15 Nov 2026 14:11:28 +0530
Subject: [PATCH 2/7] Mobile phase 5: changed files, paged highlighted diffs,
keep, undo and Stop over the phone bridge (#326)
---
.../agent-app/src/runtime/domains/mobile.ts | 3 +
.../agent-app/src/runtime/mobile/bridge.ts | 115 +++++++++++++++-
packages/agent-app/src/runtime/mobile/diff.ts | 125 ++++++++++++++++++
.../agent-app/src/runtime/mobile/highlight.ts | 95 +++++++++++++
.../agent-app/tests/mobile-phase5-326.test.ts | 17 +--
5 files changed, 346 insertions(+), 9 deletions(-)
create mode 100644 packages/agent-app/src/runtime/mobile/diff.ts
create mode 100644 packages/agent-app/src/runtime/mobile/highlight.ts
diff --git a/packages/agent-app/src/runtime/domains/mobile.ts b/packages/agent-app/src/runtime/domains/mobile.ts
index c8acb5ac..42835fcc 100644
--- a/packages/agent-app/src/runtime/domains/mobile.ts
+++ b/packages/agent-app/src/runtime/domains/mobile.ts
@@ -43,6 +43,8 @@ export const mobileSeams: {secrets?: () => SecretStore | undefined; pairingTtlMs
maxRequestsInFlight?: number; requestGate?: Promise;
/** Awaited after upload.finish checked a file and before it is staged. */
stageGate?: () => Promise;
+ /** Awaited by changes.keep and changes.undo after their reads and before the access check and the write (phase 5). */
+ reviewGate?: () => Promise;
/** Told how many characters the path scrubber reads (phase 4 cost receipts). */
onScrub?: (chars: number) => void} = {};
/** Requests one phone may have in flight at once, over all its sessions; more are refused at once (phase 3). */
@@ -380,6 +382,7 @@ export function createMobileDomain(context: DomainContext): DomainModule {
scrub,
map: (item: TimelineItem) => mapper!.map(item),
...(mobileSeams.stageGate ? {beforeStage: mobileSeams.stageGate} : {}),
+ ...(mobileSeams.reviewGate ? {beforeReview: mobileSeams.reviewGate} : {}),
watch: (chatId: string | null, deltas?: boolean) => { session.watching = chatId; session.stream = chatId && deltas ? {chatId, seq: 0, sent: null, pending: []} : null; },
streamFrom: (chatId: string, items: MobileItem[]): number => {
const stream = session.stream;
diff --git a/packages/agent-app/src/runtime/mobile/bridge.ts b/packages/agent-app/src/runtime/mobile/bridge.ts
index 1322a190..04d32db4 100644
--- a/packages/agent-app/src/runtime/mobile/bridge.ts
+++ b/packages/agent-app/src/runtime/mobile/bridge.ts
@@ -4,9 +4,11 @@
*/
import type {ApprovalData, Chat, PendingQuestion, ProviderInfo, Snapshot, TimelineItem} from '../../shared/protocol.ts';
import {device} from '../../shared/device-noun.ts';
-import {ACTING_METHODS, MAX_SEND_ATTACHMENTS, MOBILE_METHODS, MOBILE_PROTOCOL_VERSION, MobileError, type MobileAccess, type MobileApproval, type MobileChat, type MobileChatStatus, type MobileItem, type MobileMethod, type MobileMethods, type MobileNeed, type MobilePlace, type MobileProvider, type MobileQuestion} from '../../shared/mobile/protocol.ts';
+import {ACTING_METHODS, MAX_SEND_ATTACHMENTS, MOBILE_METHODS, MOBILE_PROTOCOL_VERSION, MobileError, type MobileAccess, type MobileApproval, type MobileChange, type MobileChat, type MobileReviewState, type MobileChatStatus, type MobileItem, type MobileMethod, type MobileMethods, type MobileNeed, type MobilePlace, type MobileProvider, type MobileQuestion} from '../../shared/mobile/protocol.ts';
import type {DomainContext} from '../domains/types.ts';
import type {PhoneUploads} from './uploads.ts';
+import type {ReviewBaselineInfo, ReviewChange, ReviewMark} from '../../shared/domains/review-protocol.ts';
+import {buildDiff, diffPage, hunkInfo, type BuiltDiff} from './diff.ts';
const MAX_ITEM_TEXT = 64 * 1024;
const OPEN_ITEMS = 200;
@@ -164,6 +166,49 @@ export interface BridgeContext {
map?(item: TimelineItem): MobileItem;
/** Test seam: awaited after upload.finish checked the file and before it is staged. */
beforeStage?(): Promise;
+ /** Test seam: awaited after changes.keep or changes.undo read what they need and before the access check and the write. */
+ beforeReview?(): Promise;
+}
+
+// ---------------------------------------------------------------------------
+// Diff review (phase 5): the chat's latest turn, as the desktop's changed-files card shows it, through the review domain.
+
+const STATUS: Record = {added: 'added', untracked: 'added', copied: 'added', deleted: 'deleted', renamed: 'renamed'};
+const HASH = /^[0-9a-f]{40,64}$/;
+/** A turn of the chat with a snapshot: the latest by default, or the one named (it must be this chat's). */
+async function turnOf(invoke: DomainContext['invoke'], chat: Chat, runId?: string): Promise {
+ const turns = await invoke('review.baselines', {chatId: chat.id});
+ if (runId) {
+ const named = turns.find(turn => turn.runId === runId);
+ if (!named || !named.treeSha || !named.folderId) throw new MobileError('not-found', 'That turn is not one of this chat’s.');
+ return named;
+ }
+ for (let index = turns.length - 1; index >= 0; index--) {
+ const turn = turns[index]!;
+ if (!chat.folderId || !turn.folderId || turn.folderId === chat.folderId) return turn.treeSha && turn.folderId ? turn : null;
+ }
+ return null;
+}
+const keptOf = (marks: readonly ReviewMark[], path: string) => new Set(marks.filter(mark => mark.path === path && mark.state === 'kept').map(mark => mark.hunkId));
+function mobileChanges(files: ReviewChange[], marks: readonly ReviewMark[]): MobileChange[] {
+ const out = files.map((file): MobileChange => {
+ const kept = keptOf(marks, file.path).has('*');
+ return {path: file.path, ...(file.previousPath ? {previousPath: file.previousPath} : {}), status: STATUS[file.status] ?? 'modified', adds: file.adds, dels: file.dels,
+ ...(file.binary ? {binary: true} : {}), state: kept ? 'kept' : 'review', afterHash: file.afterHash};
+ });
+ // A file undone as a whole is back to its text before the turn, so Git no longer lists it: the marks still do.
+ const listed = new Set(files.map(file => file.path));
+ for (const mark of marks) if (mark.hunkId === '*' && mark.state === 'undone' && !listed.has(mark.path)) { listed.add(mark.path); out.push({path: mark.path, status: 'modified', adds: 0, dels: 0, state: 'undone', afterHash: ''}); }
+ return out;
+}
+/** Built diffs of the last few files read, by file version: paging through one file builds it once. */
+const built = new Map();
+function builtDiff(key: string, make: () => BuiltDiff | null): BuiltDiff | null {
+ if (built.has(key)) { const value = built.get(key)!; built.delete(key); built.set(key, value); return value; }
+ const value = make();
+ built.set(key, value);
+ if (built.size > 6) built.delete(built.keys().next().value!);
+ return value;
}
export async function needsList(invoke: DomainContext['invoke'], snapshot: Snapshot, scrub?: PathScrub): Promise {
@@ -320,6 +365,74 @@ export async function handle(ctx: BridgeContext, method: unknown, rawParams: unk
uploads.own(ref.id, file.chatId);
return {attachment: {id: ref.id, name: ref.name, mime: ref.mime, size: ref.size, kind: ref.kind}} satisfies MobileMethods['upload.finish']['result'];
}
+ case 'changes.list': {
+ const chat = await chatOf(id(p.chatId, 'chatId'));
+ const turn = await turnOf(ctx.invoke, chat);
+ if (!turn) return {runId: null, files: [], truncated: false} satisfies MobileMethods['changes.list']['result'];
+ const [changes, marks] = await Promise.all([ctx.invoke('review.changes', {folderId: turn.folderId!, baseline: {runId: turn.runId}}), ctx.invoke('review.marks', {runId: turn.runId})]);
+ return {runId: turn.runId, files: mobileChanges(changes.files, marks), truncated: changes.truncated} satisfies MobileMethods['changes.list']['result'];
+ }
+ case 'changes.diff': {
+ const chat = await chatOf(id(p.chatId, 'chatId')), path = text(p.path, 'path', 4096);
+ const from = p.from === undefined ? 0 : typeof p.from === 'number' && Number.isInteger(p.from) && p.from >= 0 ? p.from : -1;
+ if (from < 0) throw new MobileError('bad-request', 'Missing or invalid from.');
+ const turn = await turnOf(ctx.invoke, chat);
+ if (!turn) throw new MobileError('not-found', 'This chat has no changes to review.');
+ const baseline = {runId: turn.runId};
+ const changes = await ctx.invoke('review.changes', {folderId: turn.folderId!, baseline});
+ const change = changes.files.find(file => file.path === path);
+ if (!change) throw new MobileError('not-found', 'That file is not one of this turn’s changes.');
+ const [diff, marks] = await Promise.all([ctx.invoke('review.fileDiff', {folderId: turn.folderId!, path, baseline}), ctx.invoke('review.marks', {runId: turn.runId})]);
+ const base = {runId: turn.runId, path, status: STATUS[change.status] ?? 'modified', afterHash: diff.afterHash, adds: change.adds, dels: change.dels};
+ const empty = {palette: [], hunks: [], lines: [], from: 0, total: 0, next: null};
+ if (diff.binary || diff.image) return {...base, ...empty, binary: true} satisfies MobileMethods['changes.diff']['result'];
+ const lines = diff.truncated ? null : builtDiff(`${turn.runId}:${path}:${diff.beforeHash}:${diff.afterHash}`, () => buildDiff(path, diff.before, diff.after));
+ if (!lines) return {...base, ...empty, tooLarge: true} satisfies MobileMethods['changes.diff']['result'];
+ const page = await diffPage(lines, from);
+ return {...base, palette: page.palette, hunks: hunkInfo(lines, keptOf(marks, path)), lines: page.lines, from: Math.min(from, lines.lines.length), total: lines.lines.length, next: page.next} satisfies MobileMethods['changes.diff']['result'];
+ }
+ case 'changes.keep': {
+ const chat = await chatOf(id(p.chatId, 'chatId')), path = text(p.path, 'path', 4096);
+ const hunkIds = Array.isArray(p.hunkIds) && p.hunkIds.length && p.hunkIds.length <= 500 ? p.hunkIds.map(value => value === '*' ? '*' : id(value, 'hunk id')) : null;
+ if (!hunkIds) throw new MobileError('bad-request', 'Choose between 1 and 500 changes.');
+ const turn = await turnOf(ctx.invoke, chat, id(p.runId, 'runId'));
+ const changes = await ctx.invoke('review.changes', {folderId: turn!.folderId!, baseline: {runId: turn!.runId}});
+ if (!changes.files.some(file => file.path === path)) throw new MobileError('not-found', 'That file is not one of this turn’s changes.');
+ // Keeping the last hunk still to review keeps the whole file, as the desktop's file view does.
+ let all = hunkIds.includes('*');
+ if (!all) {
+ const diff = await ctx.invoke('review.fileDiff', {folderId: turn!.folderId!, path, baseline: {runId: turn!.runId}});
+ const lines = diff.binary || diff.truncated ? null : buildDiff(path, diff.before, diff.after);
+ const kept = keptOf(await ctx.invoke('review.marks', {runId: turn!.runId}), path);
+ all = Boolean(lines && lines.hunks.every(hunk => kept.has(hunk.id) || hunkIds.includes(hunk.id)));
+ }
+ await ctx.beforeReview?.();
+ recheck();
+ const marks = await ctx.invoke('review.keep', {runId: turn!.runId, path, hunkIds: all && !hunkIds.includes('*') ? [...hunkIds, '*'] : hunkIds});
+ const state: MobileReviewState = keptOf(marks, path).has('*') ? 'kept' : 'review';
+ return {state} satisfies MobileMethods['changes.keep']['result'];
+ }
+ case 'changes.undo': {
+ const chat = await chatOf(id(p.chatId, 'chatId')), path = text(p.path, 'path', 4096);
+ if (typeof p.afterHash !== 'string' || !HASH.test(p.afterHash)) throw new MobileError('bad-request', 'Read the file again and retry.');
+ const hunkId = p.hunkId === undefined ? undefined : id(p.hunkId, 'hunk id');
+ const turn = await turnOf(ctx.invoke, chat, id(p.runId, 'runId'));
+ const baseline = {runId: turn!.runId}, folderId = turn!.folderId!;
+ const changes = await ctx.invoke('review.changes', {folderId, baseline});
+ if (!changes.files.some(file => file.path === path)) throw new MobileError('not-found', 'That file is not one of this turn’s changes.');
+ await ctx.beforeReview?.();
+ recheck();
+ const result = hunkId
+ ? await ctx.invoke('review.undoHunk', {folderId, path, baseline, hunkId, expectedAfterHash: p.afterHash})
+ : await ctx.invoke('review.undoFile', {folderId, path, baseline, expectedAfterHash: p.afterHash});
+ return {stale: result.stale} satisfies MobileMethods['changes.undo']['result'];
+ }
+ case 'chat.stop': {
+ const chatId = id(p.id); await chatOf(chatId);
+ recheck();
+ await ctx.invoke('chat.stop', {id: chatId});
+ return {} satisfies MobileMethods['chat.stop']['result'];
+ }
case 'needs.list': return {needs: await needsList(ctx.invoke, await ctx.snapshot(), ctx.scrub)} satisfies MobileMethods['needs.list']['result'];
}
} catch (error) {
diff --git a/packages/agent-app/src/runtime/mobile/diff.ts b/packages/agent-app/src/runtime/mobile/diff.ts
new file mode 100644
index 00000000..be83bb8b
--- /dev/null
+++ b/packages/agent-app/src/runtime/mobile/diff.ts
@@ -0,0 +1,125 @@
+/**
+ * A changed file's diff as the phone shows it (#326 phase 5): the desktop's own review hunks (the ids Keep and Undo act on),
+ * each named after the function it is in, with three lines of context, the changed words of paired lines, and one line number
+ * (the new one). Lines are built once per file version and sent a page at a time; only the page being sent is highlighted.
+ */
+import {diffWordsWithSpace} from 'diff';
+import {computeHunks, splitLines, type ReviewHunk} from '../../shared/review-hunks.ts';
+import {DIFF_PAGE_LINES, type MobileDiffLine, type MobileHunk, type MobileReviewState} from '../../shared/mobile/protocol.ts';
+import {highlightLines, languageOf, Palette} from './highlight.ts';
+
+const CONTEXT = 3;
+/** Paired lines longer than this, or hunks with more lines on a side, get no word marks. */
+const WORD_LINE_MAX = 500, WORD_PAIRS_MAX = 20;
+/** A diff line before it is highlighted. */
+export interface PlainLine { k: 'a' | 'd' | 'c'; h: number; n?: number; old?: number; text: string; w?: Array<[number, number]> }
+export interface BuiltDiff { hunks: ReviewHunk[]; names: Array; lines: PlainLine[]; language: string | null }
+
+const strip = (line: string) => line.replace(/\r?\n$/, '');
+
+const DECLARATIONS: RegExp[] = [
+ /^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)\s*[<(]/,
+ /^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([A-Za-z_]\w*)/,
+ /^\s*(?:async\s+)?def\s+([A-Za-z_]\w*)\s*\(/,
+ /^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)\s*\(/,
+ /^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*(?:async\s+)?(?:function\b|\([^)]*\)\s*(?::[^=]+)?=>|[A-Za-z_$][\w$]*\s*=>)/,
+ /^\s*(?:(?:public|private|protected|internal|static|async|override|readonly|abstract|final|get|set|suspend|open)\s+)*(?:[\w<>[\],.?]+\s+)?([A-Za-z_$][\w$]*)\s*\([^;]*\)\s*(?::\s*[^{;=]+)?(?:throws [\w., ]+)?\s*\{\s*$/,
+];
+const TYPES = /^\s*(?:export\s+)?(?:default\s+)?(?:(?:abstract|public|private|final|data|sealed)\s+)*(?:class|interface|struct|enum|impl|trait|protocol|extension|object)\s+([A-Za-z_$][\w$]*)/;
+const NOT_NAMES = new Set(['if', 'for', 'while', 'switch', 'catch', 'with', 'return', 'else', 'do', 'try', 'function', 'elif', 'when']);
+const indent = (line: string) => line.length - line.trimStart().length;
+
+/** The function (or else the type) a hunk is in: the nearest line above it, less indented, that declares one. */
+export function enclosingName(after: string[], hunk: ReviewHunk): string | null {
+ const first = hunk.added.length ? strip(hunk.added[0]!) : strip(after[hunk.newStart - 1] ?? '');
+ const own = declared(first);
+ if (own) return own;
+ let depth = first.trim() ? indent(first) : Number.POSITIVE_INFINITY;
+ for (let at = hunk.newStart - 2; at >= 0 && at >= hunk.newStart - 400; at--) {
+ const line = strip(after[at]!);
+ if (!line.trim() || indent(line) >= depth) continue;
+ const name = declared(line);
+ if (name) return name;
+ depth = Math.min(depth, indent(line));
+ if (depth === 0) break;
+ }
+ return null;
+}
+function declared(line: string): string | null {
+ for (const pattern of DECLARATIONS) { const name = pattern.exec(line)?.[1]; if (name && !NOT_NAMES.has(name)) return `${name}()`; }
+ return TYPES.exec(line)?.[1] ?? null;
+}
+
+/** Changed-word ranges of a removed line and the added line paired with it. */
+function words(before: string, after: string): [Array<[number, number]>, Array<[number, number]>] | null {
+ if (before.length > WORD_LINE_MAX || after.length > WORD_LINE_MAX) return null;
+ const left: Array<[number, number]> = [], right: Array<[number, number]> = [];
+ let a = 0, b = 0;
+ const push = (list: Array<[number, number]>, from: number, to: number) => {
+ const last = list[list.length - 1];
+ if (last && last[1] >= from) last[1] = to; else list.push([from, to]);
+ };
+ for (const part of diffWordsWithSpace(before, after)) {
+ if (part.removed) { if (part.value.trim()) push(left, a, a + part.value.length); a += part.value.length; }
+ else if (part.added) { if (part.value.trim()) push(right, b, b + part.value.length); b += part.value.length; }
+ else { a += part.value.length; b += part.value.length; }
+ }
+ // A line that changed throughout reads better without marks.
+ const covered = (list: Array<[number, number]>, size: number) => list.reduce((sum, [from, to]) => sum + to - from, 0) >= size * 0.8;
+ if (covered(left, before.trim().length) && covered(right, after.trim().length)) return [[], []];
+ return [left, right];
+}
+
+function wholeFile(before: string, after: string): ReviewHunk {
+ const removed = splitLines(before), added = splitLines(after);
+ return {id: '*', oldStart: 1, oldLines: removed.length, newStart: 1, newLines: added.length, removed, added};
+}
+
+/** All of a file's diff lines, or null when it is too large or too different to diff. */
+export function buildDiff(path: string, before: string, after: string): BuiltDiff | null {
+ // A whole new (or deleted) file past the line diff's budget is one hunk; it is kept or undone as the whole file ('*').
+ const hunks = computeHunks(before, after) ?? (!before || !after ? [wholeFile(before, after)] : null);
+ if (!hunks) return null;
+ const next = splitLines(after);
+ const lines: PlainLine[] = [];
+ let shown = 0;
+ hunks.forEach((hunk, h) => {
+ const start = hunk.newStart - 1;
+ for (let at = Math.max(shown, start - CONTEXT); at < start; at++) lines.push({k: 'c', h, n: at + 1, old: at + 1 + hunk.oldStart - hunk.newStart, text: strip(next[at]!)});
+ const pairs = hunk.removed.length <= WORD_PAIRS_MAX && hunk.added.length <= WORD_PAIRS_MAX ? Math.min(hunk.removed.length, hunk.added.length) : 0;
+ const marks = Array.from({length: pairs}, (_, index) => words(strip(hunk.removed[index]!), strip(hunk.added[index]!)));
+ hunk.removed.forEach((line, index) => { const w = marks[index]?.[0]; lines.push({k: 'd', h, old: hunk.oldStart + index, text: strip(line), ...(w?.length ? {w} : {})}); });
+ hunk.added.forEach((line, index) => { const w = marks[index]?.[1]; lines.push({k: 'a', h, n: hunk.newStart + index, text: strip(line), ...(w?.length ? {w} : {})}); });
+ const end = start + hunk.newLines, limit = Math.min(next.length, end + CONTEXT, (hunks[h + 1]?.newStart ?? Number.POSITIVE_INFINITY) - 1);
+ for (let at = end; at < limit; at++) lines.push({k: 'c', h, n: at + 1, old: at + 1 + hunk.oldStart + hunk.oldLines - hunk.newStart - hunk.newLines, text: strip(next[at]!)});
+ shown = Math.max(shown, limit);
+ });
+ return {hunks, names: hunks.map(hunk => enclosingName(next, hunk)), lines, language: languageOf(path)};
+}
+
+/** Hunk summaries for the phone, with each hunk's Keep state. */
+export function hunkInfo(diff: BuiltDiff, kept: ReadonlySet): MobileHunk[] {
+ return diff.hunks.map((hunk, index): MobileHunk => {
+ const state: MobileReviewState = kept.has('*') || kept.has(hunk.id) ? 'kept' : 'review';
+ return {id: hunk.id, fn: diff.names[index] ?? null, newStart: hunk.newStart, adds: hunk.added.length, dels: hunk.removed.length, state};
+ });
+}
+
+/** One page of lines from `from`, highlighted: runs of the same side are highlighted together. */
+export async function diffPage(diff: BuiltDiff, from: number): Promise<{lines: MobileDiffLine[]; palette: Array<[string, string]>; next: number | null}> {
+ const start = Math.max(0, Math.min(from, diff.lines.length));
+ const slice = diff.lines.slice(start, start + DIFF_PAGE_LINES);
+ const palette = new Palette();
+ const out: MobileDiffLine[] = [];
+ for (let at = 0; at < slice.length;) {
+ const side = slice[at]!.k === 'd';
+ let end = at;
+ while (end < slice.length && (slice[end]!.k === 'd') === side && slice[end]!.h === slice[at]!.h) end++;
+ const run = slice.slice(at, end);
+ const tokens = await highlightLines(run.map(line => line.text), diff.language, palette);
+ run.forEach((line, index) => out.push({k: line.k, h: line.h, ...(line.n ? {n: line.n} : {}), ...(line.old ? {old: line.old} : {}), t: tokens[index] ?? [], ...(line.w ? {w: line.w} : {})}));
+ at = end;
+ }
+ const next = start + slice.length;
+ return {lines: out, palette: palette.entries, next: next < diff.lines.length ? next : null};
+}
diff --git a/packages/agent-app/src/runtime/mobile/highlight.ts b/packages/agent-app/src/runtime/mobile/highlight.ts
new file mode 100644
index 00000000..a38e6c86
--- /dev/null
+++ b/packages/agent-app/src/runtime/mobile/highlight.ts
@@ -0,0 +1,95 @@
+/**
+ * Syntax colours for the phone's diffs (#326 phase 5). The phone does no parsing: the desktop splits each line into coloured
+ * tokens with Shiki, using the desktop's own dark and light themes, and sends each colour as a [dark, light] pair. Shiki runs
+ * with its JavaScript regex engine (no WebAssembly in the runtime worker) and a fixed set of common grammars; other files come
+ * as plain text. Lines are highlighted a page at a time, so a long file never blocks the runtime for long.
+ */
+import type {HighlighterCore} from 'shiki/core';
+import type {MobileToken} from '../../shared/mobile/protocol.ts';
+
+/** File extensions to the grammars bundled for the phone. */
+const EXTENSIONS: Record = {
+ ts: 'typescript', mts: 'typescript', cts: 'typescript', tsx: 'tsx', js: 'javascript', mjs: 'javascript', cjs: 'javascript', jsx: 'jsx',
+ json: 'json', jsonc: 'json', css: 'css', scss: 'css', md: 'markdown', markdown: 'markdown', py: 'python', pyi: 'python',
+ sh: 'shellscript', bash: 'shellscript', zsh: 'shellscript', go: 'go', rs: 'rust', yml: 'yaml', yaml: 'yaml', swift: 'swift',
+ kt: 'kotlin', kts: 'kotlin', java: 'java', sql: 'sql', toml: 'toml',
+};
+const GRAMMARS: Record Promise<{default: unknown}>> = {
+ typescript: () => import('@shikijs/langs/typescript'), tsx: () => import('@shikijs/langs/tsx'),
+ javascript: () => import('@shikijs/langs/javascript'), jsx: () => import('@shikijs/langs/jsx'),
+ json: () => import('@shikijs/langs/json'), css: () => import('@shikijs/langs/css'), markdown: () => import('@shikijs/langs/markdown'),
+ python: () => import('@shikijs/langs/python'), shellscript: () => import('@shikijs/langs/shellscript'), go: () => import('@shikijs/langs/go'),
+ rust: () => import('@shikijs/langs/rust'), yaml: () => import('@shikijs/langs/yaml'), swift: () => import('@shikijs/langs/swift'),
+ kotlin: () => import('@shikijs/langs/kotlin'), java: () => import('@shikijs/langs/java'), sql: () => import('@shikijs/langs/sql'),
+ toml: () => import('@shikijs/langs/toml'),
+};
+/** Longer lines go as plain text: highlighting a minified line costs much and helps little on a phone. */
+const MAX_LINE = 1000;
+
+export const languageOf = (path: string): string | null => {
+ const name = path.split('/').pop() ?? '';
+ const extension = name.includes('.') ? name.split('.').pop()!.toLowerCase() : '';
+ return EXTENSIONS[extension] ?? null;
+};
+
+let highlighter: Promise | null = null;
+const loaded = new Map>();
+async function core(): Promise {
+ highlighter ??= (async () => {
+ const [{createHighlighterCore}, {createJavaScriptRegexEngine}, dark, light] = await Promise.all([
+ import('shiki/core'), import('shiki/engine/javascript'), import('@shikijs/themes/dark-plus'), import('@shikijs/themes/light-plus'),
+ ]);
+ return createHighlighterCore({engine: createJavaScriptRegexEngine({forgiving: true}), themes: [dark.default, light.default], langs: []});
+ })();
+ return highlighter;
+}
+async function ready(language: string): Promise {
+ const load = GRAMMARS[language];
+ if (!load) return null;
+ const instance = await core();
+ let done = loaded.get(language);
+ if (!done) { done = load().then(module => instance.loadLanguage(module.default as never)).then(() => true, () => false); loaded.set(language, done); }
+ return (await done) ? instance : null;
+}
+
+/** Collects token colours into the page's palette, as [dark, light] pairs. */
+export class Palette {
+ readonly entries: Array<[string, string]> = [];
+ private readonly index = new Map();
+ of(dark: string, light: string): number {
+ const key = `${dark}|${light}`;
+ let at = this.index.get(key);
+ if (at === undefined) { at = this.entries.length; this.entries.push([dark, light]); this.index.set(key, at); }
+ return at;
+ }
+}
+/** The themes' plain text colours: such tokens go without a colour, so the phone uses its own text colour. */
+const PLAIN = new Set(['#D4D4D4|#000000', '#D4D4D4|#000000FF', '#d4d4d4|#000000']);
+
+/**
+ * Tokens for a run of consecutive lines of one side of a file (they are highlighted together, so a string or comment that spans
+ * lines keeps its colour). Returns one token list per line; without a grammar each line is one plain token.
+ */
+export async function highlightLines(lines: string[], language: string | null, palette: Palette): Promise {
+ const plain = () => lines.map((line): MobileToken[] => line ? [[line]] : []);
+ if (!language || !lines.length) return plain();
+ const instance = await ready(language).catch(() => null);
+ if (!instance) return plain();
+ const safe = lines.map(line => line.length > MAX_LINE ? '' : line);
+ let rows;
+ try { rows = instance.codeToTokens(safe.join('\n'), {lang: language, themes: {light: 'light-plus', dark: 'dark-plus'}}).tokens; } catch { return plain(); }
+ return lines.map((line, index): MobileToken[] => {
+ if (line.length > MAX_LINE) return [[line]];
+ const out: MobileToken[] = [];
+ for (const token of rows[index] ?? []) {
+ if (!token.content) continue;
+ const style = (token.htmlStyle ?? {}) as Record;
+ const light = style.color ?? token.color, dark = style['--shiki-dark'];
+ const color = light && dark && !PLAIN.has(`${dark}|${light}`) ? palette.of(dark, light) : undefined;
+ const last = out[out.length - 1];
+ if (last && last[1] === color) last[0] += token.content;
+ else out.push(color === undefined ? [token.content] : [token.content, color]);
+ }
+ return out.length || !line ? out : [[line]];
+ });
+}
diff --git a/packages/agent-app/tests/mobile-phase5-326.test.ts b/packages/agent-app/tests/mobile-phase5-326.test.ts
index 7a28979f..7dc58156 100644
--- a/packages/agent-app/tests/mobile-phase5-326.test.ts
+++ b/packages/agent-app/tests/mobile-phase5-326.test.ts
@@ -14,7 +14,7 @@ import {SecretStore} from '../src/runtime/secret-store.ts';
import {mobileSeams} from '../src/runtime/domains/mobile.ts';
import {nodeNoiseCrypto} from '../src/runtime/mobile/node-crypto.ts';
import {connectPhone, pairPhone, MobileError, type MobileConnection, type PairedRecord} from '../src/shared/mobile/client.ts';
-import {DIFF_PAGE_LINES, type MobileDiffLine} from '../src/shared/mobile/protocol.ts';
+import {DIFF_PAGE_LINES, type MobileDiffLine, type MobileDiffPage} from '../src/shared/mobile/protocol.ts';
const makeBox = () => ({isEncryptionAvailable: () => true, encryptString: (value: string) => Buffer.from(`box:${value}`), decryptString: (value: Buffer) => value.toString().slice(4)});
const socket = (url: string) => new WebSocket(url);
@@ -46,7 +46,7 @@ const KEY = 'export const streamKey = (id: string) => `session:${id}`;\n';
interface Desktop { relay: DevRelay; service: ReturnType; root: string; chatId: string }
/** A desktop with a Git folder and a chat in it whose turn runs `edit` after its review baseline is taken. */
-async function desktop(t: TestContext, edit: (root: string, input: ProviderInput) => Promise): Promise {
+async function desktop(t: TestContext, edit: (root: string, input: ProviderInput) => Promise, onStop?: () => void): Promise {
const relay = await startRelay({test: true});
const dataDir = await mkdtemp(join(tmpdir(), 'muster-mobile-p5-'));
const root = join(dataDir, 'atlas-api');
@@ -62,7 +62,7 @@ async function desktop(t: TestContext, edit: (root: string, input: ProviderInput
let service!: ReturnType;
const provider: ProviderAdapter = {
info: () => [{id: 'fake', name: 'Fake', available: true, identityMasked: 'Hidden', models: [{id: 'fake-model', name: 'Fake model'}]}],
- stop: async () => true, dispose() {}, async steer() { return true; },
+ stop: async () => { onStop?.(); return true; }, dispose() {}, async steer() { return true; },
async run(input) {
input.onThreadReady?.('thread-1');
// A real turn's first write comes after a model round trip; waiting for the baseline stands in for it.
@@ -169,7 +169,7 @@ test('a 5,000-line diff comes in pages without holding up the desktop', async t
const started = performance.now();
let pinging = true;
const pinger = (async () => { while (pinging) { const at = performance.now(); await other.call('ping', {}); pings.push(performance.now() - at); await delay(20); } })();
- const page = await client.call('changes.diff', {chatId: d.chatId, path: 'src/big.ts', from});
+ const page: MobileDiffPage = await client.call('changes.diff', {chatId: d.chatId, path: 'src/big.ts', from});
pages.push(performance.now() - started);
pinging = false; await pinger;
assert.equal(page.from, from, 'the page starts where it was asked');
@@ -233,11 +233,12 @@ test('keep and undo use the desktop’s review commands; a read-only phone, a st
// Spec: MUS-SPEC-23-24M (docs/spec/clauses/23-mobile.md#mus-spec-23-24m)
test('a phone that can act stops a running turn, and a read-only one can’t', async t => {
- const d = await desktop(t, async (_root, input) => {
+ let stopped!: () => void;
+ const d = await desktop(t, async () => {
// Runs until stopped (or 20 s, so a failing test never hangs the suite).
- await new Promise(resolve => { const timer = setTimeout(resolve, 20_000); if (input.signal?.aborted) resolve(); input.signal?.addEventListener('abort', () => { clearTimeout(timer); resolve(); }); });
- return {status: 'interrupted', finalMessage: ''};
- });
+ await new Promise(resolve => { const timer = setTimeout(resolve, 20_000); stopped = () => { clearTimeout(timer); resolve(); }; });
+ return {status: 'completed', finalMessage: ''};
+ }, () => stopped?.());
const {client} = await pair(t, d);
await d.service.invoke('chat.send', {id: d.chatId, text: 'run until stopped', requestId: 'p5-stop'});
const status = async () => (await d.service.invoke('app.snapshot', undefined)).chats.find(chat => chat.id === d.chatId)?.status;
From 552559af54687cd4474a7cdb46d9bccd90bc2656 Mon Sep 17 00:00:00 2001
From: Dhairya <127371606+Dkm0315@users.noreply.github.com>
Date: Sun, 15 Nov 2026 14:14:04 +0530
Subject: [PATCH 3/7] Mobile phase 5: red tests for the v3 restyle (24A-24I)
(#326)
---
packages/mobile/tests/approval-v3.test.tsx | 32 ++++++++
packages/mobile/tests/chat-v3.test.tsx | 83 +++++++++++++++++++++
packages/mobile/tests/chats-v3.test.tsx | 35 +++++++++
packages/mobile/tests/computers-v3.test.tsx | 38 ++++++++++
packages/mobile/tests/needs-you-v3.test.tsx | 21 ++++++
packages/mobile/tests/tabbar.test.tsx | 32 ++++++++
packages/mobile/tests/v3-tokens.test.tsx | 41 ++++++++++
7 files changed, 282 insertions(+)
create mode 100644 packages/mobile/tests/approval-v3.test.tsx
create mode 100644 packages/mobile/tests/chat-v3.test.tsx
create mode 100644 packages/mobile/tests/chats-v3.test.tsx
create mode 100644 packages/mobile/tests/computers-v3.test.tsx
create mode 100644 packages/mobile/tests/needs-you-v3.test.tsx
create mode 100644 packages/mobile/tests/tabbar.test.tsx
create mode 100644 packages/mobile/tests/v3-tokens.test.tsx
diff --git a/packages/mobile/tests/approval-v3.test.tsx b/packages/mobile/tests/approval-v3.test.tsx
new file mode 100644
index 00000000..a9ceb16a
--- /dev/null
+++ b/packages/mobile/tests/approval-v3.test.tsx
@@ -0,0 +1,32 @@
+import {fireEvent, render, screen, waitFor} from '@testing-library/react-native';
+import * as Haptics from 'expo-haptics';
+import {ApprovalCard} from '../src/components/ApprovalCard';
+import {fakeConnection} from './fake-connection';
+
+const approval = {kind: 'command' as const, command: 'pnpm db:reset --seed', reason: 'Resets the local test database, then runs the spec ten times.'};
+
+// Spec: MUS-SPEC-23-24F (docs/spec/clauses/23-mobile.md#mus-spec-23-24f)
+test('an approval reads as its question, the command, one line of why and one filled Approve, and a watch-only phone is told where to answer', async () => {
+ const connection = fakeConnection({'approval.respond': {}});
+ const first = await render();
+ expect(screen.getByText('Run this command?')).toBeTruthy();
+ expect(screen.getByText('pnpm db:reset --seed')).toBeTruthy();
+ expect(screen.getByText(approval.reason)).toBeTruthy();
+ expect(screen.getByText('Approving for the whole chat is a desktop setting')).toBeTruthy();
+ expect(screen.getByRole('button', {name: 'Decline'})).toBeTruthy();
+ expect(screen.getAllByTestId('filled-action')).toHaveLength(1);
+ (Haptics.notificationAsync as jest.Mock).mockClear();
+ await fireEvent.press(screen.getByRole('button', {name: 'Approve'}));
+ await waitFor(() => expect(screen.getByText(/^Approved/)).toBeTruthy());
+ expect(connection.calls).toContainEqual({method: 'approval.respond', params: {itemId: 'a1', decision: 'accept'}});
+ expect(Haptics.notificationAsync).toHaveBeenCalledWith('success');
+ expect(screen.queryByRole('button', {name: 'Approve'})).toBeNull();
+ await first.unmount();
+
+ await render();
+ expect(screen.getByText('Run this command?')).toBeTruthy();
+ expect(screen.getByText('pnpm db:reset --seed')).toBeTruthy();
+ expect(screen.queryByRole('button', {name: 'Approve'})).toBeNull();
+ expect(screen.queryByRole('button', {name: 'Decline'})).toBeNull();
+ expect(screen.getByText(/Answer this on Studio Mac/)).toBeTruthy();
+});
diff --git a/packages/mobile/tests/chat-v3.test.tsx b/packages/mobile/tests/chat-v3.test.tsx
new file mode 100644
index 00000000..87f83eb6
--- /dev/null
+++ b/packages/mobile/tests/chat-v3.test.tsx
@@ -0,0 +1,83 @@
+import {act, fireEvent, render, screen, waitFor} from '@testing-library/react-native';
+import * as Haptics from 'expo-haptics';
+import {ChatScreen} from '../src/screens/ChatScreen';
+import type {MobileChat, MobileItem} from '../src/shared';
+import {fakeConnection, layOutRows, layOutTimeline} from './fake-connection';
+
+const chat = (status: MobileChat['status']): MobileChat => ({id: 'c1', title: 'Migrate session store', status, updatedAt: '2026-11-15T10:04:00.000Z', place: 'atlas-api', needsYou: 0});
+const at = (second: number) => new Date(Date.UTC(2026, 10, 15, 10, 0, second)).toISOString();
+const items: MobileItem[] = [
+ {id: 'u1', kind: 'user', text: 'Move the store to Streams', createdAt: at(0)},
+ {id: 'r1', kind: 'reasoning', text: 'Reading the store', createdAt: at(2)},
+ {id: 't1', kind: 'tool', text: 'Read src/session/store.ts', status: 'completed', createdAt: at(10)},
+ {id: 't2', kind: 'tool', text: 'Edited src/session/store.ts', status: 'completed', createdAt: at(60)},
+ {id: 't3', kind: 'tool', text: 'Running the session tests', status: 'inProgress', createdAt: at(134)},
+ {id: 'm1', kind: 'assistant', text: 'Appends now go through XADD', createdAt: at(135)},
+];
+const open = (status: MobileChat['status'], list = items) => ({chat: chat(status), items: list, revision: 1, seq: 1});
+const press = (label: string | RegExp) => fireEvent.press(screen.getByRole('button', {name: label}));
+
+// Spec: MUS-SPEC-23-24C (docs/spec/clauses/23-mobile.md#mus-spec-23-24c)
+test('a turn’s steps fold into one capsule, the live line names the running step, and a finished run shows its summary', async () => {
+ const connection = fakeConnection({'chat.open': open('running'), 'changes.list': {runId: 'run-1', files: [{path: 'src/session/store.ts', status: 'modified', adds: 3, dels: 1, state: 'review', afterHash: 'a'.repeat(40)}], truncated: false}});
+ await render();
+ await layOutTimeline();
+ await layOutRows();
+ expect(await screen.findByText('Appends now go through XADD')).toBeTruthy();
+ expect(screen.getByRole('button', {name: /^Working, 4 steps/})).toBeTruthy();
+ expect(screen.queryByText('Read src/session/store.ts')).toBeNull();
+ expect(screen.getByTestId('now-line')).toHaveTextContent('Running the session tests');
+ expect(screen.getByTestId('caret')).toBeTruthy();
+ await press(/^Working, 4 steps/);
+ await layOutRows();
+ expect(screen.getByText('Read src/session/store.ts')).toBeTruthy();
+ expect(screen.getByText('Edited src/session/store.ts')).toBeTruthy();
+
+ (Haptics.notificationAsync as jest.Mock).mockClear();
+ await act(async () => {
+ connection.emit({type: 'delta', chatId: 'c1', seq: 2, ops: [{id: 't3', status: 'completed'}]});
+ connection.emit({type: 'chats', chats: [chat('completed')]});
+ });
+ await layOutRows();
+ await waitFor(() => expect(screen.getByText('Run finished')).toBeTruthy());
+ expect(screen.queryByTestId('now-line')).toBeNull();
+ expect(screen.queryByTestId('caret')).toBeNull();
+ expect(screen.getByRole('button', {name: /^Worked 2m 14s, 4 steps/})).toBeTruthy();
+ expect(screen.getByText('1 file changed')).toBeTruthy();
+ expect(screen.getByRole('button', {name: 'Review'})).toBeTruthy();
+ expect((Haptics.notificationAsync as jest.Mock).mock.calls.filter(([kind]) => kind === 'success')).toHaveLength(1);
+});
+
+// Spec: MUS-SPEC-23-24D (docs/spec/clauses/23-mobile.md#mus-spec-23-24d)
+test('while a turn runs Send becomes Stop, and Stop stops the turn on the computer with a light tap', async () => {
+ const connection = fakeConnection({'chat.open': open('running'), 'chat.stop': {}, 'changes.list': {runId: null, files: [], truncated: false}});
+ await render();
+ await layOutTimeline();
+ await screen.findByText('Migrate session store');
+ expect(screen.queryByText(/Working ·/)).toBeNull();
+ expect(screen.queryByRole('button', {name: 'Send'})).toBeNull();
+ (Haptics.impactAsync as jest.Mock).mockClear();
+ await press('Stop');
+ await act(async () => undefined);
+ expect(connection.calls).toContainEqual({method: 'chat.stop', params: {id: 'c1'}});
+ expect(Haptics.impactAsync).toHaveBeenCalledWith('light');
+ await fireEvent.changeText(screen.getByTestId('composer-input'), 'also keep the old keys');
+ expect(screen.getByRole('button', {name: 'Steer'})).toBeTruthy();
+ expect(screen.queryByRole('button', {name: 'Stop'})).toBeNull();
+ expect(screen.getByText(/goes to the running turn/i)).toBeTruthy();
+});
+
+// Spec: MUS-SPEC-23-24E (docs/spec/clauses/23-mobile.md#mus-spec-23-24e)
+test('the composer shows its chips only while it is focused', async () => {
+ const connection = fakeConnection({'chat.open': open('completed', items.slice(0, 1)), 'changes.list': {runId: null, files: [], truncated: false}});
+ await render( null} />);
+ await layOutTimeline();
+ await screen.findByText('Migrate session store');
+ expect(screen.getByRole('button', {name: 'Attach'})).toBeTruthy();
+ expect(screen.getByRole('button', {name: 'Send'})).toBeTruthy();
+ for (const chip of ['Photo', 'Camera', 'File']) expect(screen.queryByRole('button', {name: chip})).toBeNull();
+ await fireEvent(screen.getByTestId('composer-input'), 'focus');
+ for (const chip of ['Photo', 'Camera', 'File']) expect(screen.getByRole('button', {name: chip})).toBeTruthy();
+ await fireEvent(screen.getByTestId('composer-input'), 'blur');
+ for (const chip of ['Photo', 'Camera', 'File']) expect(screen.queryByRole('button', {name: chip})).toBeNull();
+});
diff --git a/packages/mobile/tests/chats-v3.test.tsx b/packages/mobile/tests/chats-v3.test.tsx
new file mode 100644
index 00000000..c47ad23b
--- /dev/null
+++ b/packages/mobile/tests/chats-v3.test.tsx
@@ -0,0 +1,35 @@
+import {act, render, screen} from '@testing-library/react-native';
+import * as Haptics from 'expo-haptics';
+import {ChatsScreen} from '../src/screens/ChatsScreen';
+import type {MobileChat} from '../src/shared';
+import {fakeConnection, layOutTimeline} from './fake-connection';
+
+const minutes = (n: number) => new Date(Date.now() - n * 60_000).toISOString();
+const chats: MobileChat[] = [
+ {id: 'run', title: 'Migrate session store to Streams', status: 'running', updatedAt: minutes(0), place: 'atlas-api', needsYou: 0},
+ {id: 'wait', title: 'Fix flaky checkout test', status: 'waiting', updatedAt: minutes(2), place: 'atlas-web', needsYou: 1},
+ {id: 'fail', title: 'Nightly ETL out of memory', status: 'failed', updatedAt: minutes(180), place: null, needsYou: 0},
+ {id: 'done', title: 'Bump React Native to 0.88', status: 'completed', updatedAt: minutes(60), place: 'atlas-api', needsYou: 0},
+];
+/** The section headers and rows in screen order, as a reader would meet them. */
+const outline = () => screen.getByTestId('chats-list').queryAll(node => typeof node.type === 'string' && (node.props.accessibilityRole === 'header' || node.props.testID?.startsWith?.('chat-row-')))
+ .map(node => node.props.accessibilityRole === 'header' ? `# ${node.props.accessibilityLabel}` : node.props.testID.slice('chat-row-'.length));
+
+// Spec: MUS-SPEC-23-24B (docs/spec/clauses/23-mobile.md#mus-spec-23-24b)
+test('chats show as two-line rows in Active and Earlier, and a chat that starts running moves into Active with a tick', async () => {
+ const connection = fakeConnection({'chats.list': {chats}});
+ await render( undefined} />);
+ await layOutTimeline('chats-list');
+ await screen.findByText('Migrate session store to Streams');
+ expect(screen.queryAllByRole('tab')).toHaveLength(0);
+ expect(outline()).toEqual(['# Active', 'run', 'wait', '# Earlier', 'done', 'fail']);
+ expect(screen.getByLabelText(/^Fix flaky checkout test, Needs you/)).toBeTruthy();
+ expect(screen.getByLabelText(/^Nightly ETL out of memory, Failed/)).toBeTruthy();
+ expect(screen.getByLabelText(/^Migrate session store to Streams, Running/)).toBeTruthy();
+ expect(screen.getByText('Needs you')).toBeTruthy();
+ (Haptics.selectionAsync as jest.Mock).mockClear();
+ await act(async () => { connection.emit({type: 'chats', chats: chats.map(chat => chat.id === 'done' ? {...chat, status: 'running', updatedAt: minutes(0)} : chat)}); });
+ await layOutTimeline('chats-list');
+ expect(outline().slice(0, 4)).toEqual(['# Active', 'done', 'run', 'wait']);
+ expect(Haptics.selectionAsync).toHaveBeenCalledTimes(1);
+});
diff --git a/packages/mobile/tests/computers-v3.test.tsx b/packages/mobile/tests/computers-v3.test.tsx
new file mode 100644
index 00000000..2f719bd3
--- /dev/null
+++ b/packages/mobile/tests/computers-v3.test.tsx
@@ -0,0 +1,38 @@
+import {act, render, screen} from '@testing-library/react-native';
+import * as Haptics from 'expo-haptics';
+import {ComputerSwitcher} from '../src/components/ComputerSwitcher';
+import {SettingsScreen} from '../src/screens/SettingsScreen';
+import {PairScreen} from '../src/screens/PairScreen';
+import type {ComputerView} from '../src/connection/computers';
+import {createPairingStore, memorySecureStore} from '../src/connection/store';
+import {formatPairingLink, type PairedRecord, type PairingLink} from '../src/shared';
+import {fakeConnection} from './fake-connection';
+
+const views: ComputerView[] = [
+ {id: 'studio', name: 'Studio Mac', path: 'lan', access: 'act', connection: fakeConnection({})},
+ {id: 'linux', name: 'Linux workstation', path: 'relay', access: 'read-only', connection: fakeConnection({}, 'read-only')},
+];
+const link: PairingLink = {relayUrl: 'wss://relay.example.com', route: 'a'.repeat(32), desktopKey: 'k'.repeat(43), code: 'c'.repeat(43), desktopName: 'Studio Mac'};
+const record: PairedRecord = {relayUrl: link.relayUrl, route: link.route, desktopKey: link.desktopKey, desktopName: 'Studio Mac', deviceId: 'device-1', publicKey: 'p'.repeat(43), privateKey: 's'.repeat(43)};
+
+// Spec: MUS-SPEC-23-24I (docs/spec/clauses/23-mobile.md#mus-spec-23-24i)
+test('a watch-only computer carries an eye in the switcher and Settings, and pairing ends on the paired moment', async () => {
+ const switcher = await render( undefined} onShowAll={() => undefined} onPair={() => undefined} onClose={() => undefined} />);
+ expect(screen.getAllByLabelText('Watch only')).toHaveLength(1);
+ expect(screen.queryByText('Can act')).toBeNull();
+ expect(screen.queryByText('Read only')).toBeNull();
+ await switcher.unmount();
+ const settings = await render( undefined} onUnpair={() => undefined} />);
+ expect(screen.getAllByLabelText('Watch only')).toHaveLength(1);
+ expect(screen.queryByText('Can act')).toBeNull();
+ await settings.unmount();
+
+ (Haptics.notificationAsync as jest.Mock).mockClear();
+ const onPaired = jest.fn();
+ await render( ({record, checkCode: '123456', confirmed: Promise.resolve()})} store={createPairingStore(memorySecureStore())} initialLink={formatPairingLink(link)} onPaired={onPaired} />);
+ expect(await screen.findByText('Paired with Studio Mac')).toBeTruthy();
+ expect(screen.getByText(/nobody in between/i)).toBeTruthy();
+ expect(screen.getByRole('button', {name: 'Continue'})).toBeTruthy();
+ await act(async () => undefined);
+ expect(Haptics.notificationAsync).toHaveBeenCalledWith('success');
+});
diff --git a/packages/mobile/tests/needs-you-v3.test.tsx b/packages/mobile/tests/needs-you-v3.test.tsx
new file mode 100644
index 00000000..a7d6f6a9
--- /dev/null
+++ b/packages/mobile/tests/needs-you-v3.test.tsx
@@ -0,0 +1,21 @@
+import {act, fireEvent, render, screen} from '@testing-library/react-native';
+import * as Haptics from 'expo-haptics';
+import {NeedsYouScreen} from '../src/screens/NeedsYouScreen';
+import type {MobileNeed} from '../src/shared';
+import {fakeConnection} from './fake-connection';
+
+const need: MobileNeed = {chatId: 'c1', chatTitle: 'Fix flaky checkout test', itemId: 'a1', kind: 'approval', summary: 'pnpm db:reset', createdAt: new Date().toISOString(), approval: {kind: 'command', command: 'pnpm db:reset'}};
+
+// Spec: MUS-SPEC-23-24G (docs/spec/clauses/23-mobile.md#mus-spec-23-24g)
+test('answering the last request shows All clear with one success haptic', async () => {
+ const connection = fakeConnection({'needs.list': {needs: [need]}, 'approval.respond': {}});
+ await render();
+ expect(await screen.findByText('1 waiting')).toBeTruthy();
+ (Haptics.notificationAsync as jest.Mock).mockClear();
+ await fireEvent.press(screen.getByRole('button', {name: 'Approve'}));
+ await act(async () => { connection.emit({type: 'needs', needs: []}); });
+ expect(await screen.findByText('All clear')).toBeTruthy();
+ expect(screen.getByText('Just answered')).toBeTruthy();
+ expect(screen.getByText('Approved pnpm db:reset')).toBeTruthy();
+ expect((Haptics.notificationAsync as jest.Mock).mock.calls.filter(([kind]) => kind === 'success')).toHaveLength(1);
+});
diff --git a/packages/mobile/tests/tabbar.test.tsx b/packages/mobile/tests/tabbar.test.tsx
new file mode 100644
index 00000000..cf0acd2c
--- /dev/null
+++ b/packages/mobile/tests/tabbar.test.tsx
@@ -0,0 +1,32 @@
+import {fireEvent, render, screen} from '@testing-library/react-native';
+import * as Haptics from 'expo-haptics';
+import {GlassTabBar} from '../src/components/GlassTabBar';
+import {ChatsScreen} from '../src/screens/ChatsScreen';
+import type {MobileChat} from '../src/shared';
+import {fakeConnection, layOutTimeline} from './fake-connection';
+
+// Spec: MUS-SPEC-23-24H (docs/spec/clauses/23-mobile.md#mus-spec-23-24h)
+test('the glass tab bar shows four tabs and the Needs you count, with search as its own circle', async () => {
+ const onTab = jest.fn(), onSearch = jest.fn();
+ await render();
+ expect(screen.getAllByRole('tab').map(tab => tab.props.accessibilityLabel)).toEqual(['Chats', 'Needs you, 2 waiting', 'Projects', 'Settings']);
+ expect(screen.getByRole('tab', {name: 'Chats'}).props.accessibilityState).toMatchObject({selected: true});
+ expect(screen.getByText('2')).toBeTruthy();
+ (Haptics.selectionAsync as jest.Mock).mockClear();
+ await fireEvent.press(screen.getByRole('tab', {name: /^Needs you/}));
+ expect(onTab).toHaveBeenCalledWith('needs-you');
+ expect(Haptics.selectionAsync).toHaveBeenCalledTimes(1);
+ const search = screen.getByRole('button', {name: 'Search'});
+ expect(screen.getAllByRole('tab')).not.toContain(search);
+ await fireEvent.press(search);
+ expect(onSearch).toHaveBeenCalled();
+
+ const at = new Date().toISOString();
+ const chats: MobileChat[] = [{id: 'a', title: 'Migrate session store', status: 'idle', updatedAt: at, place: null, needsYou: 0}, {id: 'b', title: 'Dark mode', status: 'idle', updatedAt: at, place: null, needsYou: 0}];
+ await render( undefined} />);
+ await layOutTimeline('chats-list');
+ await fireEvent.changeText(screen.getByPlaceholderText('Search chats'), 'dark');
+ await layOutTimeline('chats-list');
+ expect(screen.getByText('Dark mode')).toBeTruthy();
+ expect(screen.queryByText('Migrate session store')).toBeNull();
+});
diff --git a/packages/mobile/tests/v3-tokens.test.tsx b/packages/mobile/tests/v3-tokens.test.tsx
new file mode 100644
index 00000000..5e9cd6d1
--- /dev/null
+++ b/packages/mobile/tests/v3-tokens.test.tsx
@@ -0,0 +1,41 @@
+import {palettes, type} from '../src/theme';
+import {springs, springFor, CROSSFADE_MS} from '../src/motion';
+
+/** WCAG relative luminance of a #rrggbb colour, with an rgba() colour laid over `under`. */
+function rgb(color: string, under = '#000000'): [number, number, number] {
+ const rgba = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\)$/.exec(color);
+ if (rgba) { const base = rgb(under); const a = Number(rgba[4]); return [0, 1, 2].map(i => Number(rgba[i + 1]) * a + base[i]! * (1 - a)) as [number, number, number]; }
+ const hex = color.replace('#', '');
+ return [0, 2, 4].map(i => parseInt(hex.slice(i, i + 2), 16)) as [number, number, number];
+}
+const luminance = ([r, g, b]: [number, number, number]) => [r, g, b].map(v => { const c = v / 255; return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; }).reduce((sum, c, i) => sum + c * [0.2126, 0.7152, 0.0722][i]!, 0);
+const contrast = (fg: string, bg: string) => { const [a, b] = [luminance(rgb(fg, bg)), luminance(rgb(bg))]; return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05); };
+
+// Spec: MUS-SPEC-23-24A (docs/spec/clauses/23-mobile.md#mus-spec-23-24a)
+test('the v3 palettes keep text readable, the type never goes under 12 and Reduce Motion turns springs into a crossfade', () => {
+ expect(palettes.dark.background).toBe('#0e0e0e');
+ expect(palettes.dark.surface).toBe('#1a1a1c');
+ expect(palettes.dark.raised).toBe('#242426');
+ expect(palettes.dark.fill).toBe('#2e2e31');
+ expect(palettes.dark.bubble).toBe('#2a2c30');
+ expect(palettes.light.background).toBe('#f2f2f7');
+ expect(palettes.light.surface).toBe('#ffffff');
+ for (const c of [palettes.dark, palettes.light]) {
+ for (const surface of [c.background, c.surface, c.raised]) {
+ expect(contrast(c.text, surface)).toBeGreaterThanOrEqual(7);
+ expect(contrast(c.muted, surface)).toBeGreaterThanOrEqual(4.5);
+ }
+ expect(contrast(c.onAccent, c.accentFill)).toBeGreaterThanOrEqual(4.5);
+ for (const hue of [c.accent, c.warning, c.success, c.danger]) expect(contrast(hue, c.background)).toBeGreaterThanOrEqual(3);
+ }
+ for (const style of Object.values(type)) expect(style.fontSize).toBeGreaterThanOrEqual(12);
+ expect([type.prose.fontSize, type.prose.lineHeight]).toEqual([17, 26]);
+ expect([type.code.fontSize, type.code.lineHeight]).toEqual([13, 21]);
+ expect([type.largeTitle.fontSize, type.largeTitle.lineHeight]).toEqual([34, 41]);
+ expect(springs.snappy).toMatchObject({damping: 26, mass: 0.7, stiffness: 330});
+ expect(springs.gentle).toMatchObject({damping: 20, mass: 1, stiffness: 180});
+ expect(springs.bouncy).toMatchObject({damping: 14, mass: 0.8, stiffness: 260});
+ expect(springFor('gentle', false)).toEqual({kind: 'spring', config: springs.gentle});
+ expect(springFor('bouncy', true)).toEqual({kind: 'fade', duration: CROSSFADE_MS});
+ expect(CROSSFADE_MS).toBe(150);
+});
From 4339d03d36e8d442d4200d2ba3d5f36ddce2f578 Mon Sep 17 00:00:00 2001
From: Dhairya <127371606+Dkm0315@users.noreply.github.com>
Date: Sun, 15 Nov 2026 21:40:00 +0530
Subject: [PATCH 4/7] Mobile phase 5: the v3 restyle - tokens, glass tab bar,
two-line chats, work capsule, live line, Stop, approval anatomy, moments
(#326)
---
packages/mobile/app/(tabs)/_layout.tsx | 44 ++---
packages/mobile/app/(tabs)/index.tsx | 28 +--
packages/mobile/app/(tabs)/projects.tsx | 21 ++-
packages/mobile/app/chat/[id].tsx | 47 +++--
packages/mobile/app/pair.tsx | 2 +-
.../mobile/src/components/ApprovalCard.tsx | 90 ++++++---
packages/mobile/src/components/Button.tsx | 43 +++--
.../mobile/src/components/ChatTimeline.tsx | 110 +++++++++--
.../mobile/src/components/ComputerPill.tsx | 26 +--
.../src/components/ComputerSwitcher.tsx | 63 ++++---
.../src/components/ConnectionBanner.tsx | 39 ++--
.../mobile/src/components/GlassTabBar.tsx | 58 ++++++
packages/mobile/src/components/Icon.tsx | 63 +++++++
packages/mobile/src/components/Markdown.tsx | 16 +-
packages/mobile/src/components/QrScanner.tsx | 6 +-
.../mobile/src/components/QuestionCard.tsx | 69 +++++--
.../mobile/src/components/TimelineRow.tsx | 32 ++--
.../mobile/src/components/WorkCapsule.tsx | 74 ++++++++
packages/mobile/src/components/v3.tsx | 150 +++++++++++++++
packages/mobile/src/haptics.ts | 16 +-
packages/mobile/src/motion.ts | 27 ++-
packages/mobile/src/screens/ChatScreen.tsx | 158 +++++++++++-----
packages/mobile/src/screens/ChatsHome.tsx | 69 +++++--
packages/mobile/src/screens/ChatsScreen.tsx | 172 ++++++++++++------
packages/mobile/src/screens/Moments.tsx | 133 ++++++++++++++
.../mobile/src/screens/NeedsYouScreen.tsx | 74 ++++++--
packages/mobile/src/screens/NewChatScreen.tsx | 83 +++++----
packages/mobile/src/screens/PairScreen.tsx | 55 ++++--
.../mobile/src/screens/SettingsScreen.tsx | 93 +++++++---
packages/mobile/src/screens/TabletShell.tsx | 18 +-
packages/mobile/src/theme.ts | 78 +++++---
packages/mobile/src/timeline/useTimeline.ts | 13 +-
packages/mobile/tests/approval-card.test.tsx | 2 +-
packages/mobile/tests/chat-screen.test.tsx | 13 +-
packages/mobile/tests/chat-stream.test.tsx | 3 +-
packages/mobile/tests/chat-v3.test.tsx | 6 +-
.../mobile/tests/chat-virtualized.test.tsx | 7 +-
packages/mobile/tests/chats-screen.test.tsx | 6 +-
packages/mobile/tests/chats-v3.test.tsx | 5 +-
packages/mobile/tests/computers.test.tsx | 4 +-
packages/mobile/tests/offline.test.tsx | 4 +-
packages/mobile/tests/setup.ts | 1 +
packages/mobile/tests/theme.test.tsx | 8 +-
43 files changed, 1510 insertions(+), 519 deletions(-)
create mode 100644 packages/mobile/src/components/GlassTabBar.tsx
create mode 100644 packages/mobile/src/components/Icon.tsx
create mode 100644 packages/mobile/src/components/WorkCapsule.tsx
create mode 100644 packages/mobile/src/components/v3.tsx
create mode 100644 packages/mobile/src/screens/Moments.tsx
diff --git a/packages/mobile/app/(tabs)/_layout.tsx b/packages/mobile/app/(tabs)/_layout.tsx
index abbfcc6d..c36341c8 100644
--- a/packages/mobile/app/(tabs)/_layout.tsx
+++ b/packages/mobile/app/(tabs)/_layout.tsx
@@ -1,39 +1,27 @@
-/** The four tabs of the approved design: Chats, Needs you (with a live badge), Projects and Settings. */
-import {Tabs} from 'expo-router';
-import {StyleSheet, Text, View} from 'react-native';
+/** The four tabs of the v3 design (Chats, Needs you with its count, Projects, Settings) in the glass tab bar, with search as
+ * its own circle: it opens Chats with its search field. Each tab draws its own large title, so the tabs have no header. */
+import {router, Tabs} from 'expo-router';
import {useLink} from '../../src/connection/ConnectionProvider';
import {useNeedsCount} from '../../src/hooks';
-import {themed, type, useTheme} from '../../src/theme';
-
-function TabMark({focused, badge}: {focused: boolean; badge?: number}) {
- const styles = useStyles();
- return (
-
- {badge ? {badge > 99 ? '99+' : badge} : null}
-
- );
-}
+import {GlassTabBar, type TabName} from '../../src/components/GlassTabBar';
+import {useTheme} from '../../src/theme';
export default function TabsLayout() {
const c = useTheme();
const {selected} = useLink();
const needs = useNeedsCount(selected?.connection ?? null);
return (
-
- }} />
- }} />
- }} />
- }} />
+ (
+ { const route = state.routes.find(entry => entry.name === name); if (route) navigateToTab(route.key); }}
+ onSearch={() => router.navigate({pathname: '/', params: {search: String(Date.now())}})} />
+ )}
+ screenOptions={{headerShown: false, sceneStyle: {backgroundColor: c.background}, animation: 'fade'}}>
+
+
+
+
);
}
-const useStyles = themed(c => StyleSheet.create({
- mark: {width: 18, height: 18, borderRadius: 5, backgroundColor: c.scheme === 'light' ? 'rgba(0,0,0,0.08)' : 'rgba(255,255,255,0.08)'},
- markOn: {backgroundColor: c.scheme === 'light' ? 'rgba(59,106,147,0.3)' : 'rgba(145,171,194,0.3)'},
- badge: {position: 'absolute', top: -5, right: -10, minWidth: 16, paddingHorizontal: 4, borderRadius: 8, overflow: 'hidden', backgroundColor: c.danger, color: '#ffffff', fontSize: 10, lineHeight: 14, fontWeight: '700', textAlign: 'center'},
-}));
diff --git a/packages/mobile/app/(tabs)/index.tsx b/packages/mobile/app/(tabs)/index.tsx
index 8b1f0314..13a344b2 100644
--- a/packages/mobile/app/(tabs)/index.tsx
+++ b/packages/mobile/app/(tabs)/index.tsx
@@ -1,30 +1,22 @@
-import {Redirect, Tabs, useRouter} from 'expo-router';
-import {Pressable, StyleSheet, Text, useWindowDimensions, View} from 'react-native';
+import {Redirect, useLocalSearchParams, useRouter} from 'expo-router';
+import {useWindowDimensions, View} from 'react-native';
import {useLink} from '../../src/connection/ConnectionProvider';
import {TabletShell} from '../../src/screens/TabletShell';
-import {space, themed, touch} from '../../src/theme';
+import {useTheme} from '../../src/theme';
export default function Index() {
const link = useLink();
const router = useRouter();
- const styles = useStyles();
+ const c = useTheme();
const {width} = useWindowDimensions();
- if (link.phase === 'loading') return ;
+ // The tab bar's search circle opens Chats with its search field.
+ const {search} = useLocalSearchParams<{search?: string}>();
+ if (link.phase === 'loading') return ;
if (!link.computers.length) return ;
const live = link.selected && (link.selected.path === 'lan' || link.selected.path === 'relay');
- const add = live ? () => (
- router.push('/new-chat')} style={styles.add}>+
- ) : undefined;
return (
- <>
-
- router.push('/pair')} onOpen={(id, computer) => router.push({pathname: '/chat/[id]', params: {id, computer}})} />
- >
+ router.push('/new-chat')} : {})}
+ onPair={() => router.push('/pair')} onOpen={(id, computer) => router.push({pathname: '/chat/[id]', params: {id, computer}})} />
);
}
-const useStyles = themed(c => StyleSheet.create({
- center: {flex: 1, backgroundColor: c.background},
- add: {width: touch, height: touch, alignItems: 'center', justifyContent: 'center', marginRight: space.s},
- addLabel: {color: c.strong, fontSize: 20},
-}));
diff --git a/packages/mobile/app/(tabs)/projects.tsx b/packages/mobile/app/(tabs)/projects.tsx
index 98e28642..d093677d 100644
--- a/packages/mobile/app/(tabs)/projects.tsx
+++ b/packages/mobile/app/(tabs)/projects.tsx
@@ -1,18 +1,25 @@
import {StyleSheet, Text, View} from 'react-native';
+import {LargeTitle} from '../../src/screens/ChatsHome';
+import {EmptyArt} from '../../src/screens/Moments';
import {space, themed, type} from '../../src/theme';
-/** Projects (tasks, runs and Inbox) arrive in a later phase of #326; the tab is in place so the navigation does not move. */
+/** Projects (tasks, runs and the Inbox) arrive in a later phase of #326; the tab is in place so the navigation does not move. */
export default function Projects() {
const styles = useStyles();
return (
-
- Projects are coming
- Tasks, runs and the Inbox from your computer will show here in a later update.
+
+
+
+
+ Projects are coming
+ Tasks, runs and the Inbox from your computer will show here in a later update.
+
);
}
const useStyles = themed(c => StyleSheet.create({
- center: {flex: 1, alignItems: 'center', justifyContent: 'center', padding: space.xl, gap: space.s, backgroundColor: c.background},
- title: {color: c.strong, ...type.headline, fontWeight: '600'},
- body: {color: c.muted, ...type.footnote, textAlign: 'center'},
+ screen: {flex: 1, backgroundColor: c.background},
+ center: {flex: 1, alignItems: 'center', justifyContent: 'center', padding: space.xl, gap: space.s, paddingBottom: 120},
+ title: {color: c.text, ...type.title2, marginTop: space.l},
+ body: {color: c.muted, ...type.body, lineHeight: 24, textAlign: 'center'},
}));
diff --git a/packages/mobile/app/chat/[id].tsx b/packages/mobile/app/chat/[id].tsx
index 14ab4982..0fd8e384 100644
--- a/packages/mobile/app/chat/[id].tsx
+++ b/packages/mobile/app/chat/[id].tsx
@@ -1,27 +1,42 @@
-import {Stack, useLocalSearchParams} from 'expo-router';
-import {Text, View} from 'react-native';
+import {Stack, useLocalSearchParams, useRouter} from 'expo-router';
+import {Pressable, StyleSheet, Text, View} from 'react-native';
import {useComputerConnection} from '../../src/connection/ConnectionProvider';
import {ChatScreen} from '../../src/screens/ChatScreen';
import {pickAttachment} from '../../src/connection/pickers';
-import {themed, type} from '../../src/theme';
+import {Icon} from '../../src/components/Icon';
+import {Glass} from '../../src/components/v3';
+import {size, themed, type, useTheme} from '../../src/theme';
-/** One header bar: the stack's own, with the chat's title and its folder or Project and computer under it. */
+/** One header bar (v3): the chat's title with its folder or Project under it, and Changes as a glass button with its count. */
export default function Chat() {
const {id, computer} = useLocalSearchParams<{id: string; computer?: string}>();
const {view, connection} = useComputerConnection(computer || undefined);
- const styles = useStyles();
+ const router = useRouter();
+ const styles = useStyles(), c = useTheme();
if (!connection || !view || !id) return null;
- return (
- (
-
- {chat?.title ?? ''}
- {[chat?.place, view.name].filter(Boolean).join(' · ')}
-
- )}} />
+ const review = () => router.push({pathname: '/changes', params: {chat: id, computer: view.id}});
+ return (
+ (
+
+ {chat?.title ?? ''}
+ {[chat?.place, view.name].filter(Boolean).join(' · ')}
+
+ ),
+ headerRight: changes ? () => (
+
+
+ {changes}
+
+
+ ) : undefined,
+ }} />
)} />;
}
-const useStyles = themed(c => ({
- title: {alignItems: 'center' as const, maxWidth: 240},
- name: {color: c.strong, ...type.footnote, fontWeight: '600' as const},
- place: {color: c.faint, ...type.caption},
+const useStyles = themed(c => StyleSheet.create({
+ title: {alignItems: 'center', maxWidth: 220},
+ name: {color: c.text, ...type.headline},
+ place: {color: c.muted, ...type.footnote},
+ changes: {flexDirection: 'row', alignItems: 'center', gap: 6, height: size.glassCircle, paddingHorizontal: 14},
+ count: {color: c.text, ...type.headline},
}));
diff --git a/packages/mobile/app/pair.tsx b/packages/mobile/app/pair.tsx
index 1dacc8ec..055979ca 100644
--- a/packages/mobile/app/pair.tsx
+++ b/packages/mobile/app/pair.tsx
@@ -10,5 +10,5 @@ export default function Pair() {
const {pair, store, paired} = useLink();
const router = useRouter();
const initialLink = pairingLinkFromParams(useLocalSearchParams());
- return } onPaired={record => { paired(record); router.replace('/'); }} />;
+ return } onPaired={paired} onDone={() => router.replace('/')} />;
}
diff --git a/packages/mobile/src/components/ApprovalCard.tsx b/packages/mobile/src/components/ApprovalCard.tsx
index 12695873..0268c099 100644
--- a/packages/mobile/src/components/ApprovalCard.tsx
+++ b/packages/mobile/src/components/ApprovalCard.tsx
@@ -4,10 +4,12 @@ import {useRef, useState} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import Animated from 'react-native-reanimated';
import type {MobileApproval, MobileConnection} from '../shared';
-import {errorText, READ_ONLY_NOTE} from '../hooks';
+import {errorText} from '../hooks';
import {haptics} from '../haptics';
import {rowLayout} from '../motion';
-import {font, space, themed, type} from '../theme';
+import {radius, size, space, themed, type, useTheme} from '../theme';
+import {ago} from '../time';
+import {Icon} from './Icon';
import {Button} from './Button';
export type Decision = 'accept' | 'decline';
@@ -33,41 +35,75 @@ export function useApprovalResponse(connection: MobileConnection, itemId: string
/** Approvals are never queued offline: they wait for the computer. */
export const offlineNote = (computer: string): string => `${computer} is offline. You can answer this when ${computer} is back.`;
-/** `response`: pass one when something else (a swipe) answers this card too; otherwise the card has its own. `heading` names the
+const QUESTION: Record = {command: 'Run this command?', fileChange: 'Change these files?', mcp: 'Use this tool?'};
+
+/** An approval in the v3 anatomy (MUS-SPEC-23-24F): the question is the title next to an amber hand, then the command in a
+ * code well, one line of why, and Approve as the one filled action (Decline is plain). Answered, it folds into a receipt.
+ * A watch-only phone keeps the question and command but is told where to answer instead of being shown buttons.
+ * `response`: pass one when something else (a swipe) answers this card too; otherwise the card has its own. `heading` names the
* chat in Needs you. */
-export function ApprovalCard({connection, itemId, approval, status, canAct, fallback, response, heading, offline}: {connection: MobileConnection; itemId: string; approval?: MobileApproval; status?: string; canAct: boolean; fallback: string; response?: ApprovalResponse; heading?: string; offline?: string}) {
- const styles = useStyles();
+export function ApprovalCard({connection, itemId, approval, status, canAct, fallback, response, heading, offline, createdAt}: {connection: MobileConnection; itemId: string; approval?: MobileApproval; status?: string; canAct: boolean; fallback: string; response?: ApprovalResponse; heading?: string; offline?: string; createdAt?: string}) {
+ const styles = useStyles(), c = useTheme();
const own = useApprovalResponse(connection, itemId);
const {sending, answered, error, respond} = response ?? own;
const settled = answered ? (answered === 'accept' ? 'approved' : 'declined') : status && status !== 'pending' ? status : null;
- const title = approval?.kind === 'fileChange' ? 'Change files' : approval?.kind === 'mcp' ? 'Use a tool' : 'Run a command';
+ const what = approval?.command ?? (approval?.tool ? `${approval.server ? `${approval.server} › ` : ''}${approval.tool}` : approval?.files?.length ? approval.files.join(', ') : fallback);
+ if (settled) {
+ const approved = settled === 'approved' || settled === 'approved-session' || settled === 'accepted' || settled === 'completed';
+ const word = approved ? 'Approved' : settled === 'declined' ? 'Declined' : settled;
+ return (
+
+
+ {word}{` · ${what}`}
+
+ );
+ }
+ const meta = [heading ?? 'Needs your approval', createdAt ? agoWords(createdAt) : null].filter(Boolean).join(' · ');
+ const code = approval?.command ? approval.command.split('\n') : approval?.tool ? [what] : approval?.files?.length ? approval.files : [];
return (
- {settled ? title : heading ? `Approval · ${heading}` : 'Approval needed'}
- {approval?.command ? {approval.command} : null}
- {approval?.tool ? {approval.server ? `${approval.server} › ` : ''}{approval.tool} : null}
- {approval?.files?.length ? {approval.files.join('\n')} : null}
- {!approval?.command && !approval?.tool && !approval?.files?.length ? {fallback} : null}
- {approval?.reason && !settled ? {approval.reason} : null}
- {settled ? {settled === 'approved' || settled === 'approved-session' ? 'Approved' : settled === 'declined' ? 'Declined' : settled}
- : offline ? {offlineNote(offline)} : canAct ? (
-
-
-
+
+
+
+ {QUESTION[approval?.kind ?? 'command']}
+ {meta}
+
+
+ {code.length ? {code.map((line, index) => (
+ {approval?.kind === 'command' ? $ : null}{line}
+ ))} : {fallback}}
+ {approval?.reason ? {approval.reason} : null}
+ {offline ? {offlineNote(offline)} : canAct ? (
+ <>
+
+
- ) : {READ_ONLY_NOTE}}
+ Approving for the whole chat is a desktop setting
+ >
+ ) : {`Watch only. Answer this on ${connection.desktopName}, or let this phone act in Settings › Integrations › Phone there.`}}
{error ? {error} : null}
);
}
+const agoWords = (iso: string) => { const at = ago(iso); return at === 'now' ? 'just now' : `${at} ago`; };
const useStyles = themed(c => StyleSheet.create({
- card: {backgroundColor: c.surface, borderRadius: 12, borderWidth: 1, borderColor: c.border, padding: space.m, gap: space.s},
- title: {color: c.warning, ...type.label, fontWeight: '600'},
- titleDone: {color: c.muted},
- code: {color: c.text, fontFamily: font.mono, ...type.label},
- body: {color: c.text, ...type.body},
- muted: {color: c.muted, ...type.label},
- error: {color: c.danger, ...type.label},
- row: {flexDirection: 'row', gap: space.s, marginTop: space.xs},
- grow: {flex: 1},
+ card: {backgroundColor: c.surface, borderRadius: radius.card, padding: space.l, gap: 14},
+ head: {flexDirection: 'row', gap: space.m, alignItems: 'flex-start'},
+ tile: {width: size.glyph, height: size.glyph, borderRadius: size.glyph / 2, backgroundColor: c.warningTint, alignItems: 'center', justifyContent: 'center'},
+ headText: {flex: 1, gap: 2},
+ title: {color: c.text, ...type.headline},
+ meta: {color: c.muted, ...type.footnote},
+ well: {backgroundColor: c.code, borderRadius: radius.well, paddingHorizontal: space.l, paddingVertical: space.m, gap: 2},
+ codeLine: {flexDirection: 'row', gap: space.s},
+ prompt: {color: c.faint, ...type.codeBlock},
+ code: {flex: 1, color: c.text, ...type.codeBlock},
+ why: {color: c.muted, ...type.subhead},
+ actions: {flexDirection: 'row', gap: space.m},
+ quiet: {color: c.faint, ...type.footnote, textAlign: 'center'},
+ note: {color: c.muted, ...type.subhead},
+ error: {color: c.danger, ...type.footnote},
+ receipt: {flexDirection: 'row', alignItems: 'center', gap: space.s, backgroundColor: c.surface, borderRadius: 22, height: 44, paddingHorizontal: 14, alignSelf: 'flex-start', maxWidth: '100%'},
+ receiptText: {color: c.muted, ...type.subhead, flexShrink: 1},
+ receiptWord: {color: c.text, fontWeight: '600'},
}));
diff --git a/packages/mobile/src/components/Button.tsx b/packages/mobile/src/components/Button.tsx
index 5e761303..670524d7 100644
--- a/packages/mobile/src/components/Button.tsx
+++ b/packages/mobile/src/components/Button.tsx
@@ -1,23 +1,36 @@
-import {Pressable, StyleSheet, Text} from 'react-native';
-import {space, themed, touch, type} from '../theme';
+import {ActivityIndicator, Pressable, StyleSheet, Text, View} from 'react-native';
+import {radius, size, space, themed, type, useTheme} from '../theme';
+import {Icon, type IconName} from './Icon';
-/** A labelled button at least 44 points tall. `busy` shows it working and ignores presses (no double sends). */
-export function Button({label, onPress, kind = 'secondary', disabled = false, busy = false}: {label: string; onPress(): void; kind?: 'primary' | 'secondary' | 'danger'; disabled?: boolean; busy?: boolean}) {
- const styles = useStyles();
+export type ButtonKind = 'primary' | 'secondary' | 'tint' | 'plain' | 'danger';
+/** A v3 capsule: 50 tall (36 with `small`). Primary is the one filled action on a screen or card; plain and danger are text
+ * only. `busy` shows a spinner and ignores presses (no double sends). */
+export function Button({label, onPress, kind = 'secondary', disabled = false, busy = false, small = false, icon, grow = false}: {label: string; onPress(): void; kind?: ButtonKind; disabled?: boolean; busy?: boolean; small?: boolean; icon?: IconName; grow?: boolean}) {
+ const styles = useStyles(), c = useTheme();
const off = disabled || busy;
+ const fg = kind === 'primary' ? c.onAccent : kind === 'tint' || kind === 'plain' ? c.accent : kind === 'danger' ? c.danger : c.text;
return (
- [styles.base, kind === 'primary' && styles.primary, kind === 'danger' && styles.danger, (pressed || off) && styles.dim]}>
- {label}
+ [styles.base, small && styles.small, styles[kind], grow && styles.grow, (pressed || off) && styles.dim]}>
+
+ {busy ? : icon ? : null}
+ {label}
+
);
}
const useStyles = themed(c => StyleSheet.create({
- base: {minHeight: touch, justifyContent: 'center', paddingHorizontal: space.l, borderRadius: 10, backgroundColor: c.raised, borderWidth: 1, borderColor: c.control, alignItems: 'center'},
- primary: {backgroundColor: c.accentFill, borderColor: c.accentFill},
- danger: {borderColor: c.danger},
- dim: {opacity: 0.6},
- label: {color: c.strong, ...type.footnote, fontWeight: '500'},
- onAccent: {color: c.onAccent},
- strong: {fontWeight: '600'},
+ base: {height: size.primary, borderRadius: radius.capsule, paddingHorizontal: space.margin, alignItems: 'center', justifyContent: 'center'},
+ small: {height: size.small, borderRadius: radius.small, paddingHorizontal: 14},
+ grow: {flex: 1},
+ primary: {backgroundColor: c.accentFill},
+ secondary: {backgroundColor: c.fill},
+ tint: {backgroundColor: c.accentTint},
+ plain: {backgroundColor: 'transparent'},
+ danger: {backgroundColor: 'transparent'},
+ dim: {opacity: 0.55},
+ row: {flexDirection: 'row', alignItems: 'center', gap: space.s},
+ label: {...type.headline},
+ labelSmall: {...type.subhead, fontWeight: '600'},
}));
diff --git a/packages/mobile/src/components/ChatTimeline.tsx b/packages/mobile/src/components/ChatTimeline.tsx
index 3a6c62c9..7b6cddf3 100644
--- a/packages/mobile/src/components/ChatTimeline.tsx
+++ b/packages/mobile/src/components/ChatTimeline.tsx
@@ -2,49 +2,87 @@
* The chat's virtualized list (MUS-SPEC-23-16A). It mounts only the rows near the screen, opens at the newest message, and
* stays at the end while the reader is there. A reader who scrolled up is left where they are, and a "New" pill offers the
* way back. The list knows only ids; each row follows its own item, so swapping the list library touches this file only.
+ *
+ * v3 (MUS-SPEC-23-24C): a turn's consecutive tool steps and thinking fold into one work capsule; while the turn runs, the live
+ * line under the newest row says what the agent is doing now and the streaming reply ends with the caret; when it ends, the
+ * live line resolves into the run's summary.
*/
-import {useCallback, useEffect, useRef, useState} from 'react';
+import {useCallback, useEffect, useMemo, useRef, useState, type ReactElement} from 'react';
import {Pressable, StyleSheet, Text, useWindowDimensions, View, type NativeScrollEvent, type NativeSyntheticEvent} from 'react-native';
import Animated from 'react-native-reanimated';
import {KeyboardAwareLegendList} from '@legendapp/list/keyboard';
import type {LegendListRef} from '@legendapp/list/react-native';
-import type {MobileConnection} from '../shared';
+import type {MobileConnection, MobileItem} from '../shared';
import type {TimelineStore} from '../timeline/store';
-import {useTimelineIds} from '../timeline/useTimeline';
+import {useTimelineIds, useTimelineItems} from '../timeline/useTimeline';
import {floatEnter, floatExit} from '../motion';
import {haptics} from '../haptics';
import {space, themed, touch, type} from '../theme';
import {TimelineRow} from './TimelineRow';
+import {stepRunning, WorkCapsule} from './WorkCapsule';
+import {Glass, Shimmer, StatusGlyph} from './v3';
/** How close to the end (points) still counts as "reading the newest". */
export const NEAR_END = 120;
+const STEP = new Set(['tool', 'reasoning']);
+const WORK = 'work:';
-export function ChatTimeline({store, connection, canAct, offline}: {store: TimelineStore; connection: MobileConnection; canAct: boolean; /** The computer's name while it is offline: cards wait for it. */ offline?: string}) {
+/** Rows of the list: an item's id, or a work group keyed by its first step, with the turn's start for its duration. */
+interface Group { ids: string[]; since: string | null }
+function grouping(store: TimelineStore, ids: readonly string[]): {rows: string[]; groups: Map} {
+ const rows: string[] = [], groups = new Map();
+ let current: Group | null = null, since: string | null = null;
+ for (const id of ids) {
+ const item = store.getItem(id);
+ if (item?.kind === 'user') since = item.createdAt;
+ if (item && STEP.has(item.kind)) {
+ if (!current) { current = {ids: [], since}; groups.set(WORK + id, current); rows.push(WORK + id); }
+ current.ids.push(id);
+ } else { current = null; rows.push(id); }
+ }
+ return {rows, groups};
+}
+/** What the agent is doing now, in plain words. */
+function nowStep(store: TimelineStore, ids: readonly string[]): string {
+ for (let index = ids.length - 1; index >= 0 && index >= ids.length - 40; index--) {
+ const item = store.getItem(ids[index]!);
+ if (item && stepRunning(item)) return item.text.split('\n')[0]!;
+ }
+ const last = ids.length ? store.getItem(ids[ids.length - 1]!) : undefined;
+ return last?.kind === 'reasoning' ? 'Thinking' : last?.kind === 'assistant' ? 'Writing' : 'Working';
+}
+
+export function ChatTimeline({store, connection, canAct, offline, running = false, footer}: {store: TimelineStore; connection: MobileConnection; canAct: boolean; /** The computer's name while it is offline: cards wait for it. */ offline?: string; /** A turn is running: show the live line and the caret. */ running?: boolean; /** Below the newest row when no turn runs (the run's summary). */ footer?: ReactElement | null}) {
const styles = useStyles();
const ids = useTimelineIds(store);
+ const {rows, groups} = useMemo(() => grouping(store, ids), [store, ids]);
+ const lastId = ids[ids.length - 1];
+ const liveId = running && lastId && store.getItem(lastId)?.kind === 'assistant' ? lastId : null;
// The window's size stands in until the list is measured, so the newest rows paint in the first frame.
const window = useWindowDimensions();
const list = useRef(null);
- const near = useRef(true), seen = useRef(ids.length);
+ const near = useRef(true), seen = useRef(rows.length);
const [unseen, setUnseen] = useState(false);
useEffect(() => {
- if (ids.length > seen.current && !near.current) setUnseen(true);
- seen.current = ids.length;
- }, [ids.length]);
+ if (rows.length > seen.current && !near.current) setUnseen(true);
+ seen.current = rows.length;
+ }, [rows.length]);
const onScroll = useCallback((event: NativeSyntheticEvent) => {
const {contentOffset, contentSize, layoutMeasurement} = event.nativeEvent;
near.current = contentSize.height - contentOffset.y - layoutMeasurement.height < NEAR_END;
if (near.current) setUnseen(false);
}, []);
const toEnd = () => { haptics.select(); setUnseen(false); near.current = true; void list.current?.scrollToEnd({animated: true}); };
+ const live = running && !offline ? : null;
return (
id}
- getItemType={id => store.getItem(id)?.kind ?? 'assistant'}
+ getItemType={id => id.startsWith(WORK) ? 'work' : store.getItem(id)?.kind ?? 'assistant'}
estimatedItemSize={56}
estimatedListSize={{width: window.width, height: window.height}}
recycleItems={false}
@@ -55,23 +93,59 @@ export function ChatTimeline({store, connection, canAct, offline}: {store: Timel
onScroll={onScroll}
scrollEventThrottle={32}
contentContainerStyle={styles.content}
- renderItem={({item: id}) => }
+ ListFooterComponent={live ?? footer ?? null}
+ renderItem={({item: id}) => {id.startsWith(WORK)
+ ?
+ : }}
/>
{unseen ? (
-
- New ↓
-
+
+
+ New ↓
+
+
) : null}
);
}
+
+/** The live line: a running glyph and the step in plain words, shimmering. */
+function LiveLine({store, ids}: {store: TimelineStore; ids: readonly string[]}) {
+ const styles = useStyles();
+ // Follows the newest rows, so the line moves on when a step finishes.
+ useTimelineItems(store, ids.slice(-40));
+ const step = nowStep(store, ids);
+ return (
+
+
+
+
+ );
+}
+
+/** The duration of the newest work group, for the run's summary. */
+export function lastWorkSpan(store: TimelineStore): number | null {
+ const ids = store.getIds();
+ let since: string | null = null, first: MobileItem | undefined, last: MobileItem | undefined;
+ for (const id of ids) {
+ const item = store.getItem(id);
+ if (!item) continue;
+ if (item.kind === 'user') { since = item.createdAt; first = undefined; last = undefined; }
+ else if (STEP.has(item.kind)) { first ??= item; last = item; }
+ }
+ const start = since ?? first?.createdAt;
+ return start && last ? Date.parse(last.createdAt) - Date.parse(start) : null;
+}
+
const useStyles = themed(c => StyleSheet.create({
wrap: {flex: 1},
- content: {paddingHorizontal: space.l, paddingVertical: space.m},
- row: {paddingVertical: space.xs},
+ content: {paddingHorizontal: space.margin, paddingVertical: space.m},
+ row: {paddingVertical: 7},
+ live: {flexDirection: 'row', alignItems: 'center', gap: 10, paddingVertical: space.s},
+ liveText: {...type.subhead, fontWeight: '500', flexShrink: 1},
pillWrap: {position: 'absolute', bottom: space.m, alignSelf: 'center'},
- pill: {minHeight: touch - 8, paddingHorizontal: space.l, justifyContent: 'center', borderRadius: 18, backgroundColor: c.accentFill},
- pillText: {color: c.onAccent, ...type.label, fontWeight: '600'},
+ pill: {minHeight: touch - 8, paddingHorizontal: space.l, justifyContent: 'center'},
+ pillText: {color: c.text, ...type.subhead, fontWeight: '600'},
}));
diff --git a/packages/mobile/src/components/ComputerPill.tsx b/packages/mobile/src/components/ComputerPill.tsx
index 725acbbd..e11081d3 100644
--- a/packages/mobile/src/components/ComputerPill.tsx
+++ b/packages/mobile/src/components/ComputerPill.tsx
@@ -1,11 +1,14 @@
-/** The computer pill, top left on every main screen (#326 phase 4): a dot, the computer's name and how the phone reaches it
- * (LAN, Relay, Reconnecting, Offline). Tapping it opens the computer switcher. */
+/** The computer line under every large title (v3): a dot, the computer's name with a chevron, and how it is connected in plain
+ * words. Tapping it opens the computer switcher. The dot and words never flash for blips under 3 seconds (phase 4). */
import {Pressable, StyleSheet, Text, View} from 'react-native';
import type {LinkPath} from '../connection/link';
import {space, themed, type, useTheme, type Palette} from '../theme';
+import {Icon} from './Icon';
export const pathLabel = (path: LinkPath): string => ({connecting: 'Connecting', lan: 'LAN', relay: 'Relay', reconnecting: 'Reconnecting', offline: 'Offline', revoked: 'Revoked'})[path];
-export const pathColor = (c: Palette, path: LinkPath): string => path === 'lan' ? c.success : path === 'relay' ? c.accent : path === 'offline' ? c.control : path === 'revoked' ? c.danger : c.warning;
+/** The words under the title: Connected, Reconnecting…, Offline. */
+export const pathWords = (path: LinkPath): string => ({connecting: 'Connecting…', lan: 'Connected', relay: 'Connected', reconnecting: 'Reconnecting…', offline: 'Offline', revoked: 'Removed on the computer'})[path];
+export const pathColor = (c: Palette, path: LinkPath): string => path === 'lan' || path === 'relay' ? c.success : path === 'offline' ? c.faint : path === 'revoked' ? c.danger : c.warning;
export function StatusDot({path, size = 7}: {path: LinkPath; size?: number}) {
const c = useTheme();
@@ -13,21 +16,20 @@ export function StatusDot({path, size = 7}: {path: LinkPath; size?: number}) {
}
export function ComputerPill({name, path, onPress, label}: {name: string; path: LinkPath; onPress?(): void; label?: string}) {
- const styles = useStyles();
+ const styles = useStyles(), c = useTheme();
const how = label ?? pathLabel(path);
return (
- [styles.pill, pressed && styles.pressed]}>
+ [styles.line, pressed && styles.pressed]}>
{name}
- {how}
- {onPress ? ⌄ : null}
+ {onPress ? : null}
+ {label ? `${label} computers` : pathWords(path)}
);
}
const useStyles = themed(c => StyleSheet.create({
- pill: {flexDirection: 'row', alignItems: 'center', gap: 6, alignSelf: 'flex-start', minHeight: 32, maxWidth: 260, paddingHorizontal: space.m, borderRadius: 16, backgroundColor: c.surface, borderWidth: StyleSheet.hairlineWidth, borderColor: c.border},
- pressed: {backgroundColor: c.raised},
- name: {color: c.text, ...type.label, fontWeight: '600', flexShrink: 1},
- path: {color: c.faint, ...type.micro},
- chevron: {color: c.faint, ...type.micro, marginTop: -4},
+ line: {flexDirection: 'row', alignItems: 'center', gap: 6, alignSelf: 'flex-start', minHeight: 28, maxWidth: '100%'},
+ pressed: {opacity: 0.6},
+ name: {color: c.text, ...type.subhead, fontWeight: '600', flexShrink: 1},
+ path: {color: c.muted, ...type.subhead, marginLeft: space.xs},
}));
diff --git a/packages/mobile/src/components/ComputerSwitcher.tsx b/packages/mobile/src/components/ComputerSwitcher.tsx
index 8e459239..a84f0d52 100644
--- a/packages/mobile/src/components/ComputerSwitcher.tsx
+++ b/packages/mobile/src/components/ComputerSwitcher.tsx
@@ -1,11 +1,13 @@
-/** The computer switcher sheet (#326 phase 4): each paired computer with how it is connected and what this phone may do
- * there, Pair another computer, and Show all computers together. A pick gives a selection haptic and closes the sheet. */
+/** The computer switcher sheet (v3): each paired computer on two plain lines (how it is connected, and how to reach it), an eye
+ * on a watch-only one instead of an access pill, Pair another computer, and Show all computers together. A pick gives a
+ * selection haptic and closes the sheet. */
import {Modal, Pressable, StyleSheet, Switch, Text, View} from 'react-native';
import type {ComputerView} from '../connection/computers';
import {haptics} from '../haptics';
import {ago} from '../time';
-import {space, themed, touch, type, useTheme} from '../theme';
+import {radius, size, space, themed, touch, type, useTheme} from '../theme';
import {StatusDot} from './ComputerPill';
+import {Icon} from './Icon';
export function computerStatus(view: ComputerView, now = Date.now()): string {
switch (view.path) {
@@ -18,6 +20,12 @@ export function computerStatus(view: ComputerView, now = Date.now()): string {
}
}
+/** The eye a watch-only computer carries. */
+export function WatchOnly() {
+ const c = useTheme();
+ return ;
+}
+
export function ComputerSwitcher({visible, computers, selectedId, showAll, onSelect, onShowAll, onPair, onClose}: {visible: boolean; computers: ComputerView[]; selectedId: string | null; showAll: boolean; onSelect(id: string): void; onShowAll(on: boolean): void; onPair(): void; onClose(): void}) {
const styles = useStyles(), c = useTheme();
return (
@@ -27,61 +35,56 @@ export function ComputerSwitcher({visible, computers, selectedId, showAll, onSel
Computers
- ✕
+
{computers.map((view, index) => (
{ haptics.select(); onSelect(view.id); onClose(); }} style={({pressed}) => [styles.row, index > 0 && styles.divider, (pressed || view.id === selectedId) && styles.rowOn]}>
- ▭
+ onPress={() => { haptics.select(); onSelect(view.id); onClose(); }} style={({pressed}) => [styles.row, index > 0 && styles.divider, pressed && styles.rowOn]}>
+
{view.name}
- {view.access ? {view.access === 'act' ? 'Can act' : 'Read only'} : null}
+ {view.access === 'read-only' ? : null}
{computerStatus(view)}
- {view.id === selectedId && !showAll ? ✓ : null}
+ {view.id === selectedId && !showAll ? : null}
))}
{ onClose(); onPair(); }} style={styles.row}>
- Pair another computer
+ Pair another computer
Show all computers together
- { haptics.select(); onShowAll(on); }} trackColor={{true: c.accentFill, false: c.raised}} />
+ { haptics.select(); onShowAll(on); }} trackColor={{true: c.success, false: c.fill}} />
- Each computer has its own encrypted link and its own access level.
+ Each computer has its own encrypted link and its own access.
);
}
const useStyles = themed(c => StyleSheet.create({
- scrim: {flex: 1, backgroundColor: 'rgba(0,0,0,0.45)'},
- sheet: {backgroundColor: c.menu, borderTopLeftRadius: 20, borderTopRightRadius: 20, paddingHorizontal: space.l, paddingBottom: space.xl + space.l, gap: space.m},
- grabber: {alignSelf: 'center', width: 36, height: 5, borderRadius: 3, backgroundColor: c.control, marginTop: space.s},
+ scrim: {flex: 1, backgroundColor: c.scrim},
+ sheet: {backgroundColor: c.menu, borderTopLeftRadius: radius.sheet, borderTopRightRadius: radius.sheet, paddingHorizontal: space.card, paddingBottom: 40, gap: space.l},
+ grabber: {alignSelf: 'center', width: 36, height: 5, borderRadius: 3, backgroundColor: c.fill, marginTop: space.s},
head: {flexDirection: 'row', alignItems: 'center', justifyContent: 'center', minHeight: touch},
- title: {color: c.strong, ...type.headline, fontWeight: '600'},
- close: {position: 'absolute', right: 0, width: 30, height: 30, borderRadius: 15, backgroundColor: c.raised, alignItems: 'center', justifyContent: 'center'},
- closeText: {color: c.muted, ...type.label},
- group: {backgroundColor: c.surface, borderRadius: 14, overflow: 'hidden'},
- row: {flexDirection: 'row', alignItems: 'center', gap: space.m, minHeight: touch + 8, paddingHorizontal: space.m, paddingVertical: space.s},
+ title: {color: c.text, ...type.headline},
+ close: {position: 'absolute', right: 0, width: 32, height: 32, borderRadius: 16, backgroundColor: c.fill, alignItems: 'center', justifyContent: 'center'},
+ group: {backgroundColor: c.surface, borderRadius: radius.group, overflow: 'hidden'},
+ row: {flexDirection: 'row', alignItems: 'center', gap: 14, minHeight: 66, paddingHorizontal: space.l, paddingVertical: 11},
rowOn: {backgroundColor: c.raised},
divider: {borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: c.border},
- icon: {width: 36, height: 36, borderRadius: 9, backgroundColor: c.raised, alignItems: 'center', justifyContent: 'center'},
- iconText: {color: c.muted, fontSize: 18},
- iconDot: {position: 'absolute', right: -2, bottom: -2, padding: 2, borderRadius: 6, backgroundColor: c.surface},
+ icon: {width: size.glyph, height: size.glyph, borderRadius: 10, backgroundColor: c.fill, alignItems: 'center', justifyContent: 'center'},
+ iconDot: {position: 'absolute', right: -3, bottom: -3, padding: 2, borderRadius: 7, backgroundColor: c.surface},
body: {flex: 1, gap: 2},
line: {flexDirection: 'row', alignItems: 'center', gap: space.s},
- name: {color: c.strong, ...type.footnote, fontWeight: '600', flexShrink: 1},
- chip: {color: c.muted, backgroundColor: c.raised, ...type.micro, paddingHorizontal: 6, paddingVertical: 1, borderRadius: 6, overflow: 'hidden'},
- chipAct: {color: c.accent},
- status: {color: c.faint, ...type.caption},
- check: {color: c.accent, ...type.headline},
- action: {color: c.accent, ...type.footnote, fontWeight: '500'},
- label: {flex: 1, color: c.text, ...type.footnote},
- note: {color: c.faint, ...type.caption, paddingHorizontal: space.xs},
+ name: {color: c.text, ...type.body, fontWeight: '500', flexShrink: 1},
+ status: {color: c.muted, ...type.subhead},
+ action: {color: c.accent, ...type.body},
+ label: {flex: 1, color: c.text, ...type.body},
+ note: {color: c.muted, ...type.footnote, paddingHorizontal: space.xs},
}));
diff --git a/packages/mobile/src/components/ConnectionBanner.tsx b/packages/mobile/src/components/ConnectionBanner.tsx
index 20b6ec95..963b4a8a 100644
--- a/packages/mobile/src/components/ConnectionBanner.tsx
+++ b/packages/mobile/src/components/ConnectionBanner.tsx
@@ -1,32 +1,35 @@
-/** The calm banner over a computer's chats while it can't be reached (#326 phase 4): Offline with the last update time and
- * Retry, or Reconnecting while the link comes back. What is on screen is the last known state. */
-import {Pressable, StyleSheet, Text, View} from 'react-native';
+/** The calm glass banner over a computer's chats while it can't be reached (v3): "Studio Mac is offline", when what is shown
+ * was true, and Retry; or Reconnecting while the link comes back. What is on screen is the last known state. */
+import {StyleSheet, Text, View} from 'react-native';
import Animated from 'react-native-reanimated';
import type {LinkPath} from '../connection/link';
import {clock} from '../time';
import {floatEnter} from '../motion';
-import {space, themed, touch, type} from '../theme';
+import {radius, space, themed, type, useTheme} from '../theme';
+import {Button} from './Button';
+import {Icon} from './Icon';
+import {Glass} from './v3';
export function ConnectionBanner({name, path, lastSync, onRetry}: {name: string; path: LinkPath; lastSync: number | null; onRetry(): void}) {
- const styles = useStyles();
+ const styles = useStyles(), c = useTheme();
const offline = path === 'offline' || path === 'revoked';
return (
-
- {offline ? '☁︎' : '↻'}
-
- {offline ? `Offline${lastSync ? ` · last update ${clock(lastSync)}` : ''}` : `Reconnecting to ${name}…`}
- {offline ? `Showing what ${name} sent last. The agent may have moved on since then.` : 'What you write waits in the outbox and goes out when it is back.'}
-
- {offline ? Retry : null}
+
+
+
+
+ {offline ? `${name} is offline` : `Reconnecting to ${name}…`}
+ {offline ? (lastSync ? `Showing what it sent at ${clock(lastSync)}` : 'Showing what it sent last') : 'What you write waits in the outbox and goes out when it is back.'}
+
+ {offline ? : null}
+
);
}
const useStyles = themed(c => StyleSheet.create({
- banner: {flexDirection: 'row', alignItems: 'center', gap: space.m, marginHorizontal: space.m, marginVertical: space.s, padding: space.m, borderRadius: 14, backgroundColor: c.surface, borderWidth: StyleSheet.hairlineWidth, borderColor: c.border},
- icon: {color: c.muted, fontSize: 16},
+ wrap: {marginHorizontal: space.card, marginVertical: space.s},
+ banner: {flexDirection: 'row', alignItems: 'center', gap: 14, paddingVertical: 14, paddingLeft: space.l, paddingRight: space.m},
body: {flex: 1, gap: 2},
- title: {color: c.strong, ...type.label, fontWeight: '600'},
- sub: {color: c.faint, ...type.caption},
- retry: {minHeight: touch - 12, paddingHorizontal: space.m, justifyContent: 'center', borderRadius: 16, backgroundColor: c.raised},
- retryText: {color: c.strong, ...type.label, fontWeight: '600'},
+ title: {color: c.text, ...type.headline},
+ sub: {color: c.muted, ...type.footnote},
}));
diff --git a/packages/mobile/src/components/GlassTabBar.tsx b/packages/mobile/src/components/GlassTabBar.tsx
new file mode 100644
index 00000000..37e39e26
--- /dev/null
+++ b/packages/mobile/src/components/GlassTabBar.tsx
@@ -0,0 +1,58 @@
+/** The v3 tab bar: one glass capsule with the four tabs (the selected one on a lighter pill, Needs you with its count), and
+ * search as its own glass circle beside it. It floats over the content with a scroll-edge fade below the lists. */
+import {Pressable, StyleSheet, Text, View} from 'react-native';
+import {useSafeAreaInsets} from 'react-native-safe-area-context';
+import {haptics} from '../haptics';
+import {size, space, themed, useTheme} from '../theme';
+import {Icon, type IconName} from './Icon';
+import {EdgeFade, Glass} from './v3';
+
+export type TabName = 'index' | 'needs-you' | 'projects' | 'settings';
+const TABS: Array<[TabName, string, IconName]> = [['index', 'Chats', 'chats'], ['needs-you', 'Needs you', 'needs'], ['projects', 'Projects', 'projects'], ['settings', 'Settings', 'gear']];
+/** Room lists leave at their end so the last row clears the floating bar. */
+export const TAB_BAR_SPACE = size.tabBar + 40;
+
+export function GlassTabBar({active, needs, onTab, onSearch}: {active: TabName; needs: number; onTab(name: TabName): void; onSearch(): void}) {
+ const styles = useStyles(), c = useTheme();
+ const insets = useSafeAreaInsets();
+ return (
+
+
+
+
+
+ {TABS.map(([name, label, icon]) => {
+ const on = name === active, count = name === 'needs-you' ? needs : 0;
+ return (
+ { if (!on) { haptics.select(); onTab(name); } }} style={[styles.tab, on && styles.tabOn]}>
+
+ {label}
+ {count ? {count > 99 ? '99+' : count} : null}
+
+ );
+ })}
+
+
+
+ { haptics.select(); onSearch(); }} style={styles.searchHit}>
+
+
+
+
+
+ );
+}
+const useStyles = themed(c => StyleSheet.create({
+ wrap: {position: 'absolute', left: 0, right: 0, bottom: 0},
+ row: {flexDirection: 'row', gap: 10, marginHorizontal: space.margin, zIndex: 6},
+ bar: {flex: 1, height: size.tabBar},
+ tabs: {flex: 1, flexDirection: 'row', padding: 4},
+ tab: {flex: 1, borderRadius: 27, alignItems: 'center', justifyContent: 'center', gap: 2},
+ tabOn: {backgroundColor: c.glassSelected},
+ label: {fontSize: 12, lineHeight: 14, fontWeight: '600'},
+ badge: {position: 'absolute', top: 3, left: '56%', minWidth: 18, height: 18, borderRadius: 9, paddingHorizontal: 5, backgroundColor: c.badge, alignItems: 'center', justifyContent: 'center'},
+ badgeText: {color: '#ffffff', fontSize: 12, lineHeight: 14, fontWeight: '700'},
+ search: {width: size.tabBar, height: size.tabBar},
+ searchHit: {flex: 1, alignItems: 'center', justifyContent: 'center'},
+}));
diff --git a/packages/mobile/src/components/Icon.tsx b/packages/mobile/src/components/Icon.tsx
new file mode 100644
index 00000000..4419c59a
--- /dev/null
+++ b/packages/mobile/src/components/Icon.tsx
@@ -0,0 +1,63 @@
+/** Icons from the v3 design (24 × 24, 2 pt strokes, round caps), drawn with react-native-svg. */
+import {Circle, Path, Rect, Svg} from 'react-native-svg';
+
+type Shape = ['path', string, boolean] | ['circle', number, number, number, boolean] | ['rect', number, number, number, number, number];
+const ICONS = {
+ chevL: [['path', 'm15 18-6-6 6-6', false]],
+ chevR: [['path', 'm9 18 6-6-6-6', false]],
+ chevD: [['path', 'm6 9 6 6 6-6', false]],
+ chevU: [['path', 'm6 15 6-6 6 6', false]],
+ plus: [['path', 'M12 5v14M5 12h14', false]],
+ compose: [['path', 'M11 4H6a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5', false], ['path', 'M17.6 3.6a2 2 0 0 1 2.8 2.8L12 14.8l-3.6.8.8-3.6Z', false]],
+ search: [['circle', 11, 11, 7, false], ['path', 'm20 20-3.6-3.6', false]],
+ more: [['circle', 5.5, 12, 1.3, true], ['circle', 12, 12, 1.3, true], ['circle', 18.5, 12, 1.3, true]],
+ chats: [['path', 'M20.5 11.5a8.5 8.5 0 0 1-12.3 7.6L3.5 20.5l1.4-4.4A8.5 8.5 0 1 1 20.5 11.5Z', false]],
+ needs: [['path', 'M4 13.5 6.3 5.6A2 2 0 0 1 8.2 4h7.6a2 2 0 0 1 1.9 1.6L20 13.5V18a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2Z', false], ['path', 'M4 13.5h4.5l1.2 2.5h4.6l1.2-2.5H20', false]],
+ projects: [['rect', 3.5, 3.5, 7, 8, 2], ['rect', 13.5, 3.5, 7, 5, 2], ['rect', 13.5, 11.5, 7, 9, 2], ['rect', 3.5, 14.5, 7, 6, 2]],
+ gear: [['circle', 12, 12, 3, false], ['path', 'M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1Z', false]],
+ mic: [['rect', 9, 3, 6, 11, 3], ['path', 'M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21', false]],
+ up: [['path', 'M12 19V5M5.5 11.5 12 5l6.5 6.5', false]],
+ stop: [['rect', 6.5, 6.5, 11, 11, 2.5]],
+ clip: [['path', 'm20.5 11.5-8.4 8.4a5.3 5.3 0 0 1-7.5-7.5l8.4-8.4a3.5 3.5 0 0 1 5 5l-8.4 8.4a1.8 1.8 0 0 1-2.5-2.5l7.8-7.8', false]],
+ camera: [['path', 'M3.5 8.5a2 2 0 0 1 2-2h2.2l1.6-2h5.4l1.6 2h2.2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-13a2 2 0 0 1-2-2Z', false], ['circle', 12, 13, 3.5, false]],
+ check: [['path', 'M20 6.5 9.5 17 4 11.5', false]],
+ x: [['path', 'M18 6 6 18M6 6l12 12', false]],
+ branch: [['circle', 6, 5.5, 2.2, false], ['circle', 6, 18.5, 2.2, false], ['circle', 18, 7.5, 2.2, false], ['path', 'M6 7.7v8.6M18 9.7c0 4-3 5.3-6 5.3H8.2', false]],
+ term: [['rect', 3, 4, 18, 16, 3], ['path', 'm7.5 9.5 3 2.5-3 2.5M12.5 15h4', false]],
+ file: [['path', 'M14 3.5H7a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8.5Z', false], ['path', 'M14 3.5v5h5', false]],
+ folder: [['path', 'M3.5 7.5a2 2 0 0 1 2-2h3.8l2 2h7.2a2 2 0 0 1 2 2v7.5a2 2 0 0 1-2 2h-13a2 2 0 0 1-2-2Z', false]],
+ diff: [['path', 'M8 4v10M3 9h10M14 20h7', false], ['path', 'M16 4h3a2 2 0 0 1 2 2v7', false]],
+ laptop: [['rect', 4.5, 5, 15, 10.5, 1.6], ['path', 'M2.5 19h19', false]],
+ desktop: [['rect', 3, 4, 18, 12, 2], ['path', 'M9 20h6M12 16v4', false]],
+ lock: [['rect', 5, 10.5, 14, 10, 2.5], ['path', 'M8 10.5V7.5a4 4 0 0 1 8 0v3', false]],
+ shield: [['path', 'M12 3 4.5 6v5.5c0 4.7 3.2 8.2 7.5 9.5 4.3-1.3 7.5-4.8 7.5-9.5V6Z', false], ['path', 'm8.8 12 2.2 2.2 4.3-4.4', false]],
+ cloud: [['path', 'M7 18.5a4.5 4.5 0 0 1-.6-9 6 6 0 0 1 11.5 1.6 3.8 3.8 0 0 1-.6 7.4Z', false]],
+ undo: [['path', 'M9 14.5 4 9.5l5-5', false], ['path', 'M4 9.5h10.5a5.5 5.5 0 0 1 0 11H11', false]],
+ refresh: [['path', 'M20.5 12a8.5 8.5 0 1 1-2.6-6.1L20.5 8.5', false], ['path', 'M20.5 3.5v5h-5', false]],
+ eye: [['path', 'M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12Z', false], ['circle', 12, 12, 3, false]],
+ hand: [['path', 'M8 13V6a1.5 1.5 0 0 1 3 0v5M11 11V4.5a1.5 1.5 0 0 1 3 0V11M14 11V6a1.5 1.5 0 0 1 3 0v8a7 7 0 0 1-7 7 6.5 6.5 0 0 1-5.4-2.9l-2.4-3.8a1.5 1.5 0 0 1 2.5-1.6L8 15', false]],
+ alert: [['path', 'M10.3 4 2.6 17.5A2 2 0 0 0 4.3 20.5h15.4a2 2 0 0 0 1.7-3L13.7 4a2 2 0 0 0-3.4 0Z', false], ['path', 'M12 9.5v4M12 17h.01', false]],
+ clock: [['circle', 12, 12, 8.5, false], ['path', 'M12 7.5V12l3 2', false]],
+ image: [['rect', 3.5, 4.5, 17, 15, 3], ['circle', 9, 10, 1.8, false], ['path', 'm20.5 15.5-4.8-4.8-9.2 8.8', false]],
+ sidebar: [['rect', 3, 4, 18, 16, 3], ['path', 'M9.5 4v16', false]],
+ split: [['rect', 3, 4, 18, 16, 3], ['path', 'M12 4v16', false]],
+ list: [['path', 'M9 6h12M9 12h12M9 18h12M4 6h.01M4 12h.01M4 18h.01', false]],
+ copy: [['rect', 8.5, 8.5, 12, 12, 2.5], ['path', 'M15.5 8.5V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v7.5a2 2 0 0 0 2 2h2.5', false]],
+ sparkle: [['path', 'M12 3.5 13.9 9l5.6 2-5.6 2L12 18.5 10.1 13l-5.6-2 5.6-2Z', false]],
+ phone: [['rect', 6.5, 2.5, 11, 19, 2.5], ['path', 'M11 18.5h2', false]],
+ wifi: [['path', 'M2.5 9a14 14 0 0 1 19 0M5.5 12.5a9.5 9.5 0 0 1 13 0M8.7 16a5 5 0 0 1 6.6 0', false], ['circle', 12, 19.3, 1, true]],
+ trash: [['path', 'M4 6.5h16M9.5 6.5V4.5h5v2M6 6.5l1 13a1.5 1.5 0 0 0 1.5 1.5h7a1.5 1.5 0 0 0 1.5-1.5l1-13', false]],
+ qr: [['rect', 3.5, 3.5, 7, 7, 1.5], ['rect', 13.5, 3.5, 7, 7, 1.5], ['rect', 3.5, 13.5, 7, 7, 1.5], ['path', 'M13.5 13.5h3v3M20.5 13.5v7h-7', false]],
+ wrap: [['path', 'M3.5 6h17M3.5 12h14a3 3 0 0 1 0 6h-4M3.5 18h6', false], ['path', 'm15.5 16 -2 2 2 2', false]],
+} satisfies Record;
+export type IconName = keyof typeof ICONS;
+
+export function Icon({name, size = 24, color, stroke = 2}: {name: IconName; size?: number; color: string; stroke?: number}) {
+ return (
+
+ );
+}
diff --git a/packages/mobile/src/components/Markdown.tsx b/packages/mobile/src/components/Markdown.tsx
index 50a19914..742e2c19 100644
--- a/packages/mobile/src/components/Markdown.tsx
+++ b/packages/mobile/src/components/Markdown.tsx
@@ -8,7 +8,7 @@ import * as Clipboard from 'expo-clipboard';
import {splitBlocks, sameBlock, type Block} from '../markdown/blocks';
import {haptics} from '../haptics';
import {reportRender} from '../perf';
-import {font, space, themed, touch, type, useTheme, type Palette} from '../theme';
+import {font, radius, space, themed, touch, type, useTheme, type Palette} from '../theme';
/** Cards keep this height before anything renders, so text below never jumps. */
export const CARD_HEIGHT = 180;
@@ -16,9 +16,9 @@ const CARD_TITLE = {diagram: 'Diagram', chart: 'Chart'} as const;
type Card = Extract;
const markdownStyle = (c: Palette) => ({
- paragraph: {color: c.text, fontSize: type.body.fontSize, lineHeight: type.body.lineHeight},
+ paragraph: {color: c.text, fontSize: type.prose.fontSize, lineHeight: type.prose.lineHeight},
h1: {color: c.strong, fontSize: 22}, h2: {color: c.strong, fontSize: 19}, h3: {color: c.strong, fontSize: 17},
- link: {color: c.accent}, code: {color: c.text, backgroundColor: c.raised, fontFamily: font.mono},
+ link: {color: c.accent}, code: {color: c.text, backgroundColor: c.inline, fontFamily: font.mono},
blockquote: {color: c.muted, borderColor: c.control},
});
@@ -27,7 +27,7 @@ function CodeBlock({lang, code}: {lang: string; code: string}) {
const [copied, setCopied] = useState(false);
const timer = useRef | undefined>(undefined);
const copy = () => {
- void Clipboard.setStringAsync(code); haptics.tap(); setCopied(true);
+ void Clipboard.setStringAsync(code); haptics.light(); setCopied(true);
clearTimeout(timer.current); timer.current = setTimeout(() => setCopied(false), 1200);
};
const lines = code.split('\n');
@@ -90,15 +90,15 @@ export const Markdown = memo(function Markdown({text}: {text: string}) {
const useStyles = themed(c => StyleSheet.create({
blocks: {gap: space.s},
prose: {flexShrink: 1},
- code: {backgroundColor: c.surface, borderRadius: 10, borderWidth: StyleSheet.hairlineWidth, borderColor: c.border, overflow: 'hidden'},
+ code: {backgroundColor: c.code, borderRadius: radius.well, overflow: 'hidden'},
codeHead: {flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingHorizontal: space.m, paddingTop: space.s},
lang: {color: c.faint, ...type.caption, fontFamily: font.mono},
copy: {color: c.muted, ...type.caption, fontWeight: '600'},
codeBody: {padding: space.m},
codeLine: {flexDirection: 'row', gap: space.m},
- number: {color: c.faint, ...type.label, fontFamily: font.mono, minWidth: 18, textAlign: 'right'},
- codeText: {color: c.text, ...type.label, fontFamily: font.mono},
- card: {height: CARD_HEIGHT, backgroundColor: c.surface, borderRadius: 12, borderWidth: StyleSheet.hairlineWidth, borderColor: c.border, overflow: 'hidden', gap: space.s},
+ number: {color: c.faint, ...type.caption, lineHeight: 21, fontFamily: font.mono, minWidth: 18, textAlign: 'right'},
+ codeText: {color: c.text, ...type.codeBlock},
+ card: {height: CARD_HEIGHT, backgroundColor: c.surface, borderRadius: radius.card, overflow: 'hidden', gap: space.s},
cardSource: {color: c.faint, ...type.caption, fontFamily: font.mono, paddingHorizontal: space.m},
full: {flex: 1, backgroundColor: c.background, paddingTop: space.xl + space.l, gap: space.s},
fullHead: {flexDirection: 'row', alignItems: 'center', justifyContent: 'center', minHeight: touch, paddingHorizontal: space.l},
diff --git a/packages/mobile/src/components/QrScanner.tsx b/packages/mobile/src/components/QrScanner.tsx
index f74744d0..169ad88b 100644
--- a/packages/mobile/src/components/QrScanner.tsx
+++ b/packages/mobile/src/components/QrScanner.tsx
@@ -3,10 +3,10 @@ import {useRef} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import {CameraView, useCameraPermissions} from 'expo-camera';
import {Button} from './Button';
-import {space, themed, useTheme} from '../theme';
+import {space, themed, type} from '../theme';
export function QrScanner({onScan}: {onScan(text: string): void}) {
- const styles = useStyles(), colors = useTheme();
+ const styles = useStyles();
const [permission, request] = useCameraPermissions();
const done = useRef(false);
if (!permission) return null;
@@ -21,5 +21,5 @@ export function QrScanner({onScan}: {onScan(text: string): void}) {
}
const useStyles = themed(colors => StyleSheet.create({
ask: {flex: 1, alignItems: 'center', justifyContent: 'center', gap: space.m, padding: space.l},
- muted: {color: colors.text, textAlign: 'center'},
+ muted: {color: colors.text, ...type.callout, textAlign: 'center'},
}));
diff --git a/packages/mobile/src/components/QuestionCard.tsx b/packages/mobile/src/components/QuestionCard.tsx
index bfb78a16..68520dc2 100644
--- a/packages/mobile/src/components/QuestionCard.tsx
+++ b/packages/mobile/src/components/QuestionCard.tsx
@@ -1,9 +1,11 @@
/** A provider question, answered in place. One single-choice question answers on tap; otherwise pick, then Send answers. */
import {useState} from 'react';
-import {StyleSheet, Text, TextInput, View} from 'react-native';
+import {Pressable, StyleSheet, Text, TextInput, View} from 'react-native';
import type {MobileConnection, MobileQuestion} from '../shared';
import {errorText, READ_ONLY_NOTE} from '../hooks';
-import {font, radius, space, themed, useTheme} from '../theme';
+import {radius, size, space, themed, type, useTheme} from '../theme';
+import {haptics} from '../haptics';
+import {Icon} from './Icon';
import {Button} from './Button';
export function QuestionCard({connection, itemId, questions, status, canAct, note = READ_ONLY_NOTE}: {connection: MobileConnection; itemId: string; questions: MobileQuestion[]; status?: string; canAct: boolean; /** Why it can't be answered here. */ note?: string}) {
@@ -13,7 +15,7 @@ export function QuestionCard({connection, itemId, questions, status, canAct, not
const [error, setError] = useState(null);
const pending = !status || status === 'pending';
const instant = questions.length === 1 && !questions[0]!.multiSelect;
- const send = (answers: Record) => { setError(null); connection.call('question.respond', {itemId, answers}).catch(failure => setError(errorText(failure))); };
+ const send = (answers: Record) => { setError(null); connection.call('question.respond', {itemId, answers}).then(() => haptics.success(), failure => setError(errorText(failure))); };
const choose = (question: MobileQuestion, label: string) => {
if (instant) return send({[question.id]: [label]});
setPicked(current => {
@@ -25,17 +27,37 @@ export function QuestionCard({connection, itemId, questions, status, canAct, not
const ready = questions.every(question => (picked[question.id]?.length ?? 0) > 0 || Boolean(custom[question.id]?.trim()));
return (
- {questions.map(question => (
+ {questions.map((question, index) => (
- {question.header ? {question.header} : null}
- {question.question}
+
+
+
+ {question.question}
+
+ {question.header ? {question.header} : null}
+ {questions.length > 1 ? {questions.map((_, dot) => )} : null}
+
+
+
{question.secret ? Answer this one on your computer: it asks for a secret.
: pending && canAct ? (
<>
- {question.options.map(option => choose(question, option.label)} />)}
+ {question.options.map(option => {
+ const on = Boolean(picked[question.id]?.includes(option.label));
+ return (
+ { haptics.select(); choose(question, option.label); }} style={({pressed}) => [styles.option, pressed && styles.pressed]}>
+
+ {option.label}
+ {option.description ? {option.description} : null}
+
+ {on ? : null}
+
+ );
+ })}
- {question.allowCustomAnswer && !instant ? setCustom(current => ({...current, [question.id]: text}))} /> : null}
+ {question.allowCustomAnswer && !instant ? setCustom(current => ({...current, [question.id]: text}))} /> : null}
>
) : null}
@@ -47,12 +69,27 @@ export function QuestionCard({connection, itemId, questions, status, canAct, not
);
}
const useStyles = themed(colors => StyleSheet.create({
- card: {backgroundColor: colors.surface, borderRadius: radius.m, borderWidth: 1, borderColor: colors.accent, padding: space.m, gap: space.m},
- question: {gap: space.s},
- header: {color: colors.muted, fontSize: font.small, textTransform: 'uppercase'},
- body: {color: colors.text, fontSize: font.body},
- muted: {color: colors.muted, fontSize: font.small},
- error: {color: colors.danger, fontSize: font.small},
- options: {flexDirection: 'row', flexWrap: 'wrap', gap: space.s},
- input: {borderWidth: 1, borderColor: colors.border, borderRadius: radius.s, color: colors.text, padding: space.s},
+ card: {backgroundColor: colors.surface, borderRadius: radius.card, padding: space.l, gap: space.l},
+ question: {gap: 14},
+ head: {flexDirection: 'row', gap: space.m, alignItems: 'flex-start'},
+ tile: {width: size.glyph, height: size.glyph, borderRadius: size.glyph / 2, backgroundColor: colors.accentTint, alignItems: 'center', justifyContent: 'center'},
+ headText: {flex: 1, gap: 2},
+ title: {color: colors.text, ...type.headline},
+ metaRow: {flexDirection: 'row', alignItems: 'center', gap: space.s},
+ meta: {color: colors.muted, ...type.footnote},
+ dots: {flexDirection: 'row', gap: 4},
+ dot: {width: 6, height: 6, borderRadius: 3, backgroundColor: colors.fill},
+ dotOn: {backgroundColor: colors.accent},
+ options: {gap: space.s},
+ option: {flexDirection: 'row', alignItems: 'center', gap: space.m, minHeight: 50, borderRadius: radius.capsule, backgroundColor: colors.fill, paddingHorizontal: 18, paddingVertical: 10},
+ pressed: {opacity: 0.7},
+ optionText: {flex: 1, gap: 2},
+ optionLabel: {color: colors.text, ...type.body, fontWeight: '500'},
+ optionWhy: {color: colors.muted, ...type.footnote},
+ radio: {width: 22, height: 22, borderRadius: 11, borderWidth: 2, borderColor: colors.control, alignItems: 'center', justifyContent: 'center'},
+ radioOn: {borderColor: colors.accent},
+ radioDot: {width: 10, height: 10, borderRadius: 5, backgroundColor: colors.accent},
+ muted: {color: colors.muted, ...type.subhead},
+ error: {color: colors.danger, ...type.footnote},
+ input: {borderWidth: 1, borderColor: colors.control, borderRadius: radius.well, color: colors.text, paddingHorizontal: space.l, height: 46, ...type.body},
}));
diff --git a/packages/mobile/src/components/TimelineRow.tsx b/packages/mobile/src/components/TimelineRow.tsx
index a633b3ca..b29185cb 100644
--- a/packages/mobile/src/components/TimelineRow.tsx
+++ b/packages/mobile/src/components/TimelineRow.tsx
@@ -1,42 +1,34 @@
/** One timeline row. It follows only its own item in the store, so a streaming token re-renders this row and no other
- * (MUS-SPEC-23-16A). Replies render as native Markdown; tool calls are one dim line; approvals and questions are cards. */
+ * (MUS-SPEC-23-16A). Replies render as native Markdown at 17 on 26, the streaming one ending with the accent caret; the
+ * person's messages are bubbles; approvals and questions are cards. Tool steps fold into a WorkCapsule instead. */
import {memo} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import type {MobileConnection} from '../shared';
import type {TimelineStore} from '../timeline/store';
import {useTimelineItem} from '../timeline/useTimeline';
import {reportRender} from '../perf';
-import {font, radius, space, themed, type} from '../theme';
+import {space, themed, type} from '../theme';
import {ApprovalCard, offlineNote} from './ApprovalCard';
import {QuestionCard} from './QuestionCard';
import {Markdown} from './Markdown';
+import {Caret} from './v3';
-export const TimelineRow = memo(function TimelineRow({store, id, connection, canAct, offline}: {store: TimelineStore; id: string; connection: MobileConnection; canAct: boolean; offline?: string}) {
+export const TimelineRow = memo(function TimelineRow({store, id, connection, canAct, offline, live = false}: {store: TimelineStore; id: string; connection: MobileConnection; canAct: boolean; offline?: string; /** The reply streaming now: it ends with the caret. */ live?: boolean}) {
const item = useTimelineItem(store, id);
const styles = useStyles();
reportRender('timeline-row', id);
if (!item) return null;
- if (item.kind === 'approval') return ;
+ if (item.kind === 'approval') return ;
if (item.kind === 'question') return ;
if (item.kind === 'user') return {item.text};
- if (item.kind === 'tool') return (
-
-
- {item.text}{item.status && item.status !== 'completed' ? ` · ${item.status}` : ''}
-
- );
+ if (item.kind === 'tool' || item.kind === 'reasoning') return {item.text};
if (item.kind === 'notice') return {item.text};
- if (item.kind === 'reasoning') return {item.text};
- return ;
+ return {live ? : null};
});
const useStyles = themed(c => StyleSheet.create({
- user: {alignSelf: 'flex-end', maxWidth: '85%', backgroundColor: c.bubble, borderRadius: 18, borderBottomRightRadius: radius.s, paddingVertical: space.s, paddingHorizontal: space.m, marginVertical: space.xs},
- userText: {color: c.strong, ...type.body},
+ user: {alignSelf: 'flex-end', maxWidth: '84%', backgroundColor: c.bubble, borderRadius: 22, paddingVertical: 11, paddingHorizontal: space.l, marginVertical: space.xs},
+ userText: {color: c.text, fontSize: 17, lineHeight: 23},
assistant: {paddingVertical: space.xs},
- tool: {flexDirection: 'row', alignItems: 'center', gap: space.s, paddingVertical: 2},
- toolMark: {width: 12, height: 12, borderRadius: 3, backgroundColor: c.raised, borderWidth: StyleSheet.hairlineWidth, borderColor: c.control},
- toolFailed: {backgroundColor: c.danger},
- toolText: {flex: 1, color: c.muted, fontFamily: font.mono, ...type.caption},
- notice: {color: c.faint, ...type.label, fontStyle: 'italic'},
- reasoning: {color: c.faint, ...type.label},
+ step: {color: c.muted, ...type.subhead},
+ notice: {color: c.muted, ...type.footnote, textAlign: 'center'},
}));
diff --git a/packages/mobile/src/components/WorkCapsule.tsx b/packages/mobile/src/components/WorkCapsule.tsx
new file mode 100644
index 00000000..4bb13bc0
--- /dev/null
+++ b/packages/mobile/src/components/WorkCapsule.tsx
@@ -0,0 +1,74 @@
+/** A turn's tool steps and thinking folded into one capsule (v3): "Working · N steps" while a step runs, "Worked 2m 14s ·
+ * N steps" after. Tapping it opens the steps, each a plain sentence with its status. */
+import {memo, useState} from 'react';
+import {Pressable, StyleSheet, Text, View} from 'react-native';
+import Animated from 'react-native-reanimated';
+import type {MobileItem} from '../shared';
+import type {TimelineStore} from '../timeline/store';
+import {useTimelineItems} from '../timeline/useTimeline';
+import {haptics} from '../haptics';
+import {rowLayout} from '../motion';
+import {reportRender} from '../perf';
+import {radius, space, themed, type, useTheme} from '../theme';
+import {Icon, type IconName} from './Icon';
+import {Spinner} from './v3';
+
+const FINISHED = new Set(['completed', 'failed', 'declined', 'cancelled', 'interrupted']);
+/** A step still running: a tool whose status is set and not finished. */
+export const stepRunning = (item: MobileItem): boolean => item.kind === 'tool' && Boolean(item.status) && !FINISHED.has(item.status!);
+/** "2m 14s", "45s", "1h 3m". */
+export function took(ms: number): string {
+ const seconds = Math.max(0, Math.round(ms / 1000));
+ if (seconds < 60) return `${seconds}s`;
+ const minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return `${minutes}m ${String(seconds % 60).padStart(2, '0')}s`;
+ return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
+}
+const stepIcon = (item: MobileItem): IconName => item.kind === 'reasoning' ? 'sparkle' : /^(edit|wrote|write|creat|patch|apply)/i.test(item.text) ? 'diff' : /^(run|ran|exec|\$)/i.test(item.text) ? 'term' : 'file';
+
+export const WorkCapsule = memo(function WorkCapsule({store, id, ids, since, running}: {store: TimelineStore; id: string; ids: readonly string[]; since: string | null; running: boolean}) {
+ const styles = useStyles(), c = useTheme();
+ const items = useTimelineItems(store, ids);
+ const [open, setOpen] = useState(false);
+ reportRender('timeline-row', id);
+ const working = running && items.some(stepRunning);
+ const last = items[items.length - 1];
+ const start = since ?? items[0]?.createdAt;
+ const span = start && last ? Date.parse(last.createdAt) - Date.parse(start) : 0;
+ const label = working ? 'Working' : span >= 1000 ? `Worked ${took(span)}` : 'Worked';
+ const steps = items.length === 1 ? '1 step' : `${items.length} steps`;
+ const failed = items.some(item => item.status === 'failed');
+ return (
+
+ { haptics.select(); setOpen(value => !value); }} style={styles.capsule}>
+ {working ? : }
+ {label}
+ {steps}
+
+
+ {open ?
+ {items.map(item => (
+
+
+
+ {item.kind === 'reasoning' ? 'Thinking' : item.text}
+ {item.kind === 'reasoning' ? {item.text} : item.status && item.status !== 'completed' ? {stepRunning(item) ? 'Running' : item.status} : null}
+
+
+ ))}
+ : null}
+
+ );
+});
+const useStyles = themed(c => StyleSheet.create({
+ wrap: {alignSelf: 'flex-start', maxWidth: '100%', backgroundColor: c.surface, borderRadius: 22},
+ open: {alignSelf: 'stretch', borderRadius: radius.card},
+ capsule: {flexDirection: 'row', alignItems: 'center', gap: 10, height: 44, paddingLeft: space.m, paddingRight: 14},
+ label: {color: c.text, ...type.subhead, fontWeight: '500'},
+ steps: {color: c.muted, ...type.subhead},
+ list: {paddingHorizontal: space.l, paddingBottom: space.m, gap: space.m},
+ step: {flexDirection: 'row', gap: space.m, alignItems: 'flex-start'},
+ stepBody: {flex: 1, gap: 2},
+ stepText: {color: c.text, ...type.subhead},
+ detail: {color: c.muted, ...type.footnote},
+}));
diff --git a/packages/mobile/src/components/v3.tsx b/packages/mobile/src/components/v3.tsx
new file mode 100644
index 00000000..56b5e72b
--- /dev/null
+++ b/packages/mobile/src/components/v3.tsx
@@ -0,0 +1,150 @@
+/** The v3 building blocks: the glass material, scroll-edge fades, status glyphs, the review ring, the streaming caret and the
+ * live line's shimmer. Every loop stops under Reduce Motion. */
+import {useEffect, type ReactNode} from 'react';
+import {Platform, StyleSheet, View, type StyleProp, type TextStyle, type ViewStyle} from 'react-native';
+import {BlurView} from 'expo-blur';
+import {GlassView, isLiquidGlassAvailable} from 'expo-glass-effect';
+import Animated, {cancelAnimation, Easing, useAnimatedStyle, useSharedValue, withRepeat, withSequence, withTiming} from 'react-native-reanimated';
+import {Circle, Defs, LinearGradient, Rect, Stop, Svg} from 'react-native-svg';
+import type {MobileChatStatus} from '../shared';
+import {CARET_BLINK_MS, SHIMMER_MS, useReduceMotion} from '../motion';
+import {useTheme, type Palette} from '../theme';
+import {Icon, type IconName} from './Icon';
+
+const liquidGlass = (() => { try { return Platform.OS === 'ios' && isLiquidGlassAvailable(); } catch { return false; } })();
+
+/** Glass: iOS 26 Liquid Glass, else a blur under the v3 glass tint with its top-edge highlight; on Android a tonal surface. */
+export function Glass({style, radius, children, testID}: {style?: StyleProp; radius: number; children?: ReactNode; testID?: string}) {
+ const c = useTheme();
+ if (liquidGlass) return {children};
+ const edge = {borderRadius: radius, borderWidth: StyleSheet.hairlineWidth, borderColor: c.glassEdge, borderTopColor: c.glassHighlight};
+ if (Platform.OS === 'ios') return (
+
+
+ {children}
+
+ );
+ return {children};
+}
+
+/** The 120 pt fade from the canvas under a nav bar (top) or a tab bar or toolbar (bottom). */
+export function EdgeFade({edge, height = 120}: {edge: 'top' | 'bottom'; height?: number}) {
+ const c = useTheme();
+ const id = `fade-${edge}`;
+ return (
+
+
+
+ );
+}
+
+export type GlyphKind = 'running' | 'waiting' | 'question' | 'failed' | 'done' | 'idle' | 'queued';
+/** The words a glyph stands for, for screen readers and the colour-coded lead of a chat row. */
+export const GLYPH_WORD: Record = {running: 'Running', waiting: 'Needs you', question: 'Asks a question', failed: 'Failed', done: 'Done', idle: 'Idle', queued: 'Was running'};
+export const glyphOf = (status: MobileChatStatus, offline = false): GlyphKind =>
+ offline && (status === 'running' || status === 'stopping') ? 'queued'
+ : status === 'running' || status === 'stopping' ? 'running' : status === 'waiting' ? 'waiting' : status === 'failed' ? 'failed' : status === 'completed' ? 'done' : 'idle';
+export const glyphColor = (c: Palette, kind: GlyphKind): string =>
+ kind === 'running' || kind === 'question' ? c.accent : kind === 'waiting' ? c.warning : kind === 'failed' ? c.danger : kind === 'done' ? c.success : kind === 'queued' ? c.muted : c.faint;
+const GLYPH_ICON: Partial> = {waiting: 'hand', question: 'chats', failed: 'alert', done: 'check', queued: 'clock'};
+
+/** A status glyph: a tile tinted in the state's hue with a shape that differs per state (running ring, amber hand, accent
+ * bubble, red triangle, green check, dashed idle ring, clock for queued). */
+export function StatusGlyph({kind, size = 36}: {kind: GlyphKind; size?: number}) {
+ const c = useTheme();
+ const color = glyphColor(c, kind);
+ const label = GLYPH_WORD[kind];
+ if (kind === 'running') return ;
+ if (kind === 'idle') {
+ const r = size / 2 - 2;
+ return ;
+ }
+ const tint = kind === 'waiting' ? c.warningTint : kind === 'failed' ? c.dangerTint : kind === 'done' ? c.successTint : kind === 'queued' ? c.fill : c.accentTint;
+ return (
+
+
+
+ );
+}
+
+/** A ring with a turning arc (the running glyph, and the ring around Stop). */
+export function Spinner({size, color, tint, track, stroke = 2.6}: {size: number; color: string; tint?: string; track?: string; stroke?: number}) {
+ const reduce = useReduceMotion();
+ const turn = useSharedValue(0);
+ useEffect(() => {
+ if (reduce) return;
+ turn.value = withRepeat(withTiming(360, {duration: 1100, easing: Easing.linear}), -1, false);
+ return () => cancelAnimation(turn);
+ }, [reduce]);
+ const spin = useAnimatedStyle(() => ({transform: [{rotate: `${turn.value}deg`}]}));
+ const r = size / 2 - stroke, length = 2 * Math.PI * r;
+ return (
+
+
+
+
+
+
+ );
+}
+
+/** The review ring: how much of something is done (0 to 1). */
+export function ProgressRing({value, size = 32, label}: {value: number; size?: number; label?: string}) {
+ const c = useTheme();
+ const r = size / 2 - 3, length = 2 * Math.PI * r, done = Math.max(0, Math.min(1, value));
+ return (
+
+
+
+ );
+}
+
+/** The streaming caret: 9 pt in the accent with a 12 pt glow, blinking every 1.1 s (steady under Reduce Motion). */
+export function Caret() {
+ const c = useTheme();
+ const reduce = useReduceMotion();
+ const shown = useSharedValue(1);
+ useEffect(() => {
+ if (reduce) return;
+ shown.value = withRepeat(withSequence(withTiming(1, {duration: CARET_BLINK_MS / 2}), withTiming(0, {duration: 0}), withTiming(0, {duration: CARET_BLINK_MS / 2}), withTiming(1, {duration: 0})), -1, false);
+ return () => cancelAnimation(shown);
+ }, [reduce]);
+ const blink = useAnimatedStyle(() => ({opacity: shown.value}));
+ return ;
+}
+
+/** The live line's text: it brightens and dims once every 2.2 s, a single text so readers meet it once (still under Reduce
+ * Motion). */
+export function Shimmer({text, style}: {text: string; style: StyleProp}) {
+ const c = useTheme();
+ const reduce = useReduceMotion();
+ const lit = useSharedValue(0);
+ useEffect(() => {
+ if (reduce) return;
+ lit.value = withRepeat(withSequence(withTiming(1, {duration: SHIMMER_MS / 2, easing: Easing.inOut(Easing.quad)}), withTiming(0, {duration: SHIMMER_MS / 2, easing: Easing.inOut(Easing.quad)})), -1, false);
+ return () => cancelAnimation(lit);
+ }, [reduce]);
+ const glow = useAnimatedStyle(() => ({opacity: 0.72 + lit.value * 0.28}));
+ return {text};
+}
+
+const styles = StyleSheet.create({
+ fade: {position: 'absolute', left: 0, right: 0, zIndex: 5},
+});
diff --git a/packages/mobile/src/haptics.ts b/packages/mobile/src/haptics.ts
index 50cf5056..c8273fd4 100644
--- a/packages/mobile/src/haptics.ts
+++ b/packages/mobile/src/haptics.ts
@@ -1,14 +1,20 @@
-/** Haptics on key actions: a tap on send, success on approve, warning on decline, and a light texture while a reply streams
- * (at most once every 320 ms, and never for a reply that was already streaming when the chat opened). */
+/** Haptics (v3): selection for chips, swipe thresholds and stream ticks (at most every 320 ms, and never for a reply that was
+ * already streaming when the chat opened); light for send, copy, Stop and undo; medium for start, pair and lift; success for
+ * approve, answer, commit, all clear and a finished run; warning for decline, failure and locked. */
import * as Haptics from 'expo-haptics';
const quiet = (work: Promise | undefined) => { void Promise.resolve(work).catch(() => undefined); };
export const STREAM_TICK_MS = 320;
-let lastTick = 0;
+/** A moment that follows an answer (all clear) gives no second success inside this window. */
+export const MOMENT_WINDOW_MS = 1500;
+let lastTick = 0, lastSuccess = 0;
export const haptics = {
- tap: () => quiet(Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light)),
select: () => quiet(Haptics.selectionAsync()),
- success: () => quiet(Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success)),
+ light: () => quiet(Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light)),
+ medium: () => quiet(Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium)),
+ success: () => { lastSuccess = Date.now(); quiet(Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success)); },
+ /** Success for a moment, unless an answer just gave one. */
+ moment: () => { if (Date.now() - lastSuccess > MOMENT_WINDOW_MS) haptics.success(); },
warning: () => quiet(Haptics.notificationAsync(Haptics.NotificationFeedbackType.Warning)),
streamTick(now = Date.now()) { if (now - lastTick < STREAM_TICK_MS) return; lastTick = now; quiet(Haptics.selectionAsync()); },
};
diff --git a/packages/mobile/src/motion.ts b/packages/mobile/src/motion.ts
index 53cddff9..c2458294 100644
--- a/packages/mobile/src/motion.ts
+++ b/packages/mobile/src/motion.ts
@@ -1,11 +1,30 @@
-/** One feel for every animation: durations and the swipe spring, all honouring the system's Reduce Motion setting. */
-import {Easing, FadeIn, FadeOut, LinearTransition, ReduceMotion} from 'react-native-reanimated';
+/** One feel for every animation (v3): three springs, shared durations, and Reduce Motion, under which springs become a 150 ms
+ * crossfade and nothing shimmers or blinks. */
+import {Easing, FadeIn, FadeOut, LinearTransition, ReduceMotion, useReducedMotion} from 'react-native-reanimated';
export const duration = {adjust: 120, exit: 150, enter: 200, layout: 180, pane: 260, rowIn: 140, rowOut: 100, floatIn: 180, floatOut: 120} as const;
-export const spring = {damping: 26, mass: 0.7, stiffness: 330, overshootClamping: true, reduceMotion: ReduceMotion.System} as const;
+/** snappy: controls and swipes; gentle: cards, sheets and capsules; bouncy: moments only (all clear, paired, run finished). */
+export const springs = {
+ snappy: {damping: 26, mass: 0.7, stiffness: 330},
+ gentle: {damping: 20, mass: 1, stiffness: 180},
+ bouncy: {damping: 14, mass: 0.8, stiffness: 260},
+} as const;
+export type SpringName = keyof typeof springs;
+export const CROSSFADE_MS = 150;
+/** The live line's shimmer sweep and the streaming caret's blink. */
+export const SHIMMER_MS = 2200;
+export const CARET_BLINK_MS = 1100;
+/** The swipe spring (snappy, never overshooting a row's rest position). */
+export const spring = {...springs.snappy, overshootClamping: true, reduceMotion: ReduceMotion.System} as const;
+/** What an animation should do: spring with a preset, or (Reduce Motion) crossfade. */
+export function springFor(name: SpringName, reduce: boolean): {kind: 'spring'; config: typeof springs[SpringName]} | {kind: 'fade'; duration: number} {
+ return reduce ? {kind: 'fade', duration: CROSSFADE_MS} : {kind: 'spring', config: springs[name]};
+}
+/** Reduce Motion from the system, for components that run their own loops. */
+export const useReduceMotion = (): boolean => useReducedMotion() ?? false;
export const paneEasing = Easing.inOut(Easing.cubic);
/** Layout animations for rows and floating controls (no-ops when Reduce Motion is on). */
-export const rowLayout = LinearTransition.duration(duration.layout).reduceMotion(ReduceMotion.System);
+export const rowLayout = LinearTransition.springify().damping(springs.gentle.damping).mass(springs.gentle.mass).stiffness(springs.gentle.stiffness).reduceMotion(ReduceMotion.System);
export const rowEnter = FadeIn.duration(duration.rowIn).reduceMotion(ReduceMotion.System);
export const rowExit = FadeOut.duration(duration.rowOut).reduceMotion(ReduceMotion.System);
export const floatEnter = FadeIn.duration(duration.floatIn).reduceMotion(ReduceMotion.System);
diff --git a/packages/mobile/src/screens/ChatScreen.tsx b/packages/mobile/src/screens/ChatScreen.tsx
index 418031a8..cd27a122 100644
--- a/packages/mobile/src/screens/ChatScreen.tsx
+++ b/packages/mobile/src/screens/ChatScreen.tsx
@@ -1,7 +1,12 @@
-/** One chat: its timeline streaming live in a virtualized list, approval and question cards in place, and the composer (Send
- * when idle, Steer while a turn runs, the same rule as the desktop's follow-up mode). The composer rides the keyboard.
- * With the computer offline it shows the cached chat under a banner; messages go to the outbox and approvals wait. */
-import {useState, type ReactNode} from 'react';
+/** One chat: its timeline streaming live in a virtualized list, approval and question cards in place, and the composer. The
+ * composer rides the keyboard. With the computer offline it shows the cached chat under a banner; messages go to the
+ * outbox and approvals wait.
+ *
+ * v3: the composer is one glass row (add, field, send). Its chips (Photo, Camera, File) show only while it is focused
+ * (MUS-SPEC-23-24E). While a turn runs, Send turns into Stop wrapped in a moving ring; with text typed it is Steer, and a
+ * hint says the message goes to the running turn (24D). When a turn ends while the chat is open, its live line resolves into
+ * the run's summary with a success haptic (24C). */
+import {useEffect, useRef, useState, type ReactNode} from 'react';
import {Pressable, StyleSheet, Text, TextInput, View} from 'react-native';
import {KeyboardStickyView} from 'react-native-keyboard-controller';
import {sha256} from '@noble/hashes/sha2.js';
@@ -13,18 +18,36 @@ import {ConnectionBanner} from '../components/ConnectionBanner';
import type {LinkPath} from '../connection/link';
import {haptics} from '../haptics';
import {Button} from '../components/Button';
-import {ChatTimeline} from '../components/ChatTimeline';
-import {space, themed, touch, type, useTheme} from '../theme';
+import {Icon} from '../components/Icon';
+import {ChatTimeline, lastWorkSpan} from '../components/ChatTimeline';
+import {took} from '../components/WorkCapsule';
+import {Glass, Spinner} from '../components/v3';
+import {RunFinished} from './Moments';
+import {space, themed, type, useTheme} from '../theme';
const BUSY = new Set(['running', 'stopping', 'waiting']);
+const RUNNING = new Set(['running', 'stopping']);
/** A file in the composer: uploading (with how much has arrived) or ready to send. */
interface Draft { key: string; name: string; size: number; sent: number; attachment: MobileAttachment | null }
-const SOURCES: Array<[AttachSource, string]> = [['photo', 'Photo'], ['camera', 'Camera'], ['file', 'File']];
+const SOURCES: Array<[AttachSource, string, 'image' | 'camera' | 'file']> = [['photo', 'Photo', 'image'], ['camera', 'Camera', 'camera'], ['file', 'File', 'file']];
+
+/** How many files the chat's latest turn changed (0 when none, or the computer can't say). */
+export function useChangeCount(connection: MobileConnection, chatId: string, stamp: string | undefined): number {
+ const [count, setCount] = useState(0);
+ useEffect(() => {
+ if (offlineOf(connection)) return;
+ let live = true;
+ connection.call('changes.list', {chatId}).then(result => { if (live) setCount((result.files ?? []).filter(file => file.state !== "undone").length); }, () => undefined);
+ return () => { live = false; };
+ }, [connection, chatId, stamp]);
+ return count;
+}
/** `header`: how the chat's title is shown. A stack route passes one that sets its native header (one bar, no second header
- * in the body); a tablet pane or a test leaves it out and the title shows at the top of the screen. */
-export function ChatScreen({connection, chatId, pickAttachment, header, path}: {connection: MobileConnection; chatId: string; pickAttachment?: PickAttachment; header?: (chat: MobileChat | null) => ReactNode; path?: LinkPath}) {
+ * in the body); a tablet pane or a test leaves it out and the title shows at the top of the screen. `onReview` opens the
+ * turn's changes. */
+export function ChatScreen({connection, chatId, pickAttachment, header, path, onReview}: {connection: MobileConnection; chatId: string; pickAttachment?: PickAttachment; header?: (chat: MobileChat | null, changes: number) => ReactNode; path?: LinkPath; onReview?(): void}) {
const {chat, store, error} = useChat(connection, chatId);
const styles = useStyles(), c = useTheme();
const access = useAccess(connection);
@@ -34,12 +57,29 @@ export function ChatScreen({connection, chatId, pickAttachment, header, path}: {
const [draft, setDraft] = useState('');
const [sendError, setSendError] = useState(null);
const [files, setFiles] = useState([]);
- const [menu, setMenu] = useState(false);
+ const [focused, setFocused] = useState(false);
+ const [stopping, setStopping] = useState(false);
+ const running = Boolean(chat && RUNNING.has(chat.status)) && !offline;
const steering = Boolean(chat && BUSY.has(chat.status)) && !offline;
+ const changes = useChangeCount(connection, chatId, chat ? `${chat.status}:${RUNNING.has(chat.status)}` : undefined);
+ // A turn that ends while the chat is open resolves into its summary, once, with a success haptic.
+ const [finished, setFinished] = useState<{took: string | null} | null>(null);
+ const was = useRef(null);
+ useEffect(() => {
+ if (!chat) return;
+ const before = was.current;
+ was.current = chat.status;
+ if (RUNNING.has(chat.status)) { setFinished(null); setStopping(false); return; }
+ if (before && RUNNING.has(before) && (chat.status === 'completed' || chat.status === 'failed' || chat.status === 'interrupted')) {
+ const span = lastWorkSpan(store);
+ setFinished({took: span && span >= 1000 ? took(span) : null});
+ if (chat.status === 'completed') haptics.success(); else haptics.warning();
+ }
+ }, [chat?.status]);
const uploading = files.some(file => !file.attachment);
const update = (key: string, change: Partial) => setFiles(current => current.map(file => file.key === key ? {...file, ...change} : file));
const attach = async (source: AttachSource) => {
- setMenu(false); setSendError(null);
+ haptics.select(); setSendError(null);
if (!pickAttachment) return;
const key = requestId();
try {
@@ -54,6 +94,11 @@ export function ChatScreen({connection, chatId, pickAttachment, header, path}: {
setFiles(current => current.filter(entry => entry.key !== file.key));
if (file.attachment) void connection.call('upload.discard', {chatId, attachmentId: file.attachment.id}).catch(() => undefined);
};
+ const stop = async () => {
+ if (stopping) return;
+ haptics.light(); setStopping(true); setSendError(null);
+ try { await connection.call('chat.stop', {id: chatId}); } catch (failure) { setStopping(false); setSendError(errorText(failure)); }
+ };
const submit = async () => {
const text = draft.trim();
if (!text || !canAct || uploading) return;
@@ -62,13 +107,13 @@ export function ChatScreen({connection, chatId, pickAttachment, header, path}: {
if (offline) {
// Offline: the message waits in the outbox and goes out, once, when the computer is back.
const scope = cacheScopeOf(connection)!;
- setDraft(''); setSendError(null); haptics.tap();
+ setDraft(''); setSendError(null); haptics.light();
scope.cache.enqueue(scope.computerId, chatId, text);
return;
}
const attached = files;
setDraft(''); setFiles([]); setSendError(null);
- haptics.tap();
+ haptics.light();
try {
if (steering) {
const result = await connection.call('chat.steer', {id: chatId, text, requestId: requestId()});
@@ -76,9 +121,12 @@ export function ChatScreen({connection, chatId, pickAttachment, header, path}: {
} else await connection.call('chat.send', {id: chatId, text, requestId: requestId(), ...(attached.length ? {attachmentIds: attached.map(file => file.attachment!.id)} : {})});
} catch (failure) { setDraft(text); setFiles(attached); setSendError(errorText(failure)); }
};
+ const typed = Boolean(draft.trim());
+ const showStop = running && !typed && canAct;
+ const chips = Boolean(pickAttachment) && !offline && canAct && focused;
return (
- {header ? header(chat) : (
+ {header ? header(chat, changes) : (
{chat?.title ?? ''}
{chat?.place ? {chat.place} : null}
@@ -86,56 +134,74 @@ export function ChatScreen({connection, chatId, pickAttachment, header, path}: {
)}
{offline ? : null}
{error ? {error} : null}
-
+ : null} />
{queued.length ?
{queued.map(entry =>
{entry.text}
- {entry.error ? `Not sent: ${entry.error}` : 'Waiting to send'}
+ {entry.error ? `Not sent: ${entry.error}` : 'Waiting to send'}
)}
: null}
{sendError ? {sendError} : null}
- {!canAct ? {READ_ONLY_NOTE} : null}
{files.length ?
{files.map(file =>
{file.name}
{file.attachment ? null : {`${Math.floor(file.sent * 100 / Math.max(1, file.size))}%`}}
- remove(file)}>×
+ remove(file)}>
)}
: null}
{steering && files.length ? Photos and files go with your next message, once this turn ends. : null}
- {menu ? {SOURCES.map(([source, label]) => void attach(source)} />)} : null}
-
- {pickAttachment && !offline ? setMenu(open => !open)} hitSlop={6} style={[styles.attach, !canAct && styles.dim]}>
- +
- : null}
-
- 0)} onPress={() => void submit()} />
-
+ {steering && typed && canAct ? Steer: this goes to the running turn. : null}
+ {chips ? {SOURCES.map(([source, label, icon]) => void attach(source)} />)} : null}
+ {!canAct ? (
+ {READ_ONLY_NOTE}
+ ) : (
+
+ {pickAttachment && !offline ? setFocused(on => !on)} hitSlop={6} style={styles.add}>
+
+ : null}
+ setFocused(true)} onBlur={() => setFocused(false)} multiline />
+ {showStop ? (
+ void stop()} style={styles.stop}>
+
+
+
+ ) : (
+ 0)} onPress={() => void submit()}
+ style={[styles.circle, {backgroundColor: typed ? c.accentFill : c.fill}]}>
+
+
+ )}
+
+ )}
);
}
const useStyles = themed(c => StyleSheet.create({
screen: {flex: 1, backgroundColor: c.background},
- header: {paddingHorizontal: space.l, paddingVertical: space.m, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: c.border},
- title: {color: c.strong, ...type.headline, fontWeight: '600'},
- muted: {color: c.muted, ...type.label},
- error: {color: c.danger, ...type.label, paddingHorizontal: space.l, paddingTop: space.xs},
- note: {color: c.muted, ...type.label, paddingHorizontal: space.l, paddingTop: space.s},
- composer: {flexDirection: 'row', alignItems: 'flex-end', gap: space.s, marginHorizontal: space.s, marginTop: space.s, marginBottom: space.m, padding: space.s, backgroundColor: c.surface, borderWidth: 1, borderColor: c.border, borderRadius: 20},
- files: {flexDirection: 'row', flexWrap: 'wrap', gap: space.s, paddingHorizontal: space.m, paddingTop: space.s},
- file: {flexDirection: 'row', alignItems: 'center', gap: space.s, maxWidth: '100%', borderWidth: 1, borderColor: c.control, borderRadius: 8, paddingHorizontal: space.s, paddingVertical: 2},
- fileName: {color: c.text, ...type.label, flexShrink: 1},
- remove: {color: c.text, ...type.body, paddingHorizontal: space.xs},
- menu: {flexDirection: 'row', gap: space.s, paddingHorizontal: space.m, paddingTop: space.s},
- attach: {width: touch - 8, height: touch - 8, borderRadius: 18, borderWidth: 1, borderColor: c.control, alignItems: 'center', justifyContent: 'center'},
- attachLabel: {color: c.text, fontSize: 20, lineHeight: 22},
- dim: {opacity: 0.5},
- queue: {alignItems: 'flex-end', gap: space.s, paddingHorizontal: space.l, paddingTop: space.s},
- queued: {maxWidth: '85%', borderRadius: 18, borderBottomRightRadius: 6, borderWidth: 1, borderStyle: 'dashed', borderColor: c.control, paddingVertical: space.s, paddingHorizontal: space.m, gap: 2},
- queuedText: {color: c.text, ...type.body},
- queuedNote: {color: c.faint, ...type.micro, textAlign: 'right'},
- queuedError: {color: c.danger, ...type.micro, textAlign: 'right'},
- input: {flex: 1, minHeight: touch - 8, maxHeight: 140, color: c.text, paddingHorizontal: space.s, paddingVertical: space.s, ...type.body},
+ header: {paddingHorizontal: space.margin, paddingVertical: space.m},
+ title: {color: c.text, ...type.headline},
+ muted: {color: c.muted, ...type.footnote},
+ error: {color: c.danger, ...type.footnote, paddingHorizontal: space.margin, paddingTop: space.xs},
+ note: {color: c.muted, ...type.footnote, paddingHorizontal: space.margin + 4, paddingTop: space.s},
+ composer: {flexDirection: 'row', alignItems: 'flex-end', gap: 6, marginHorizontal: space.card, marginTop: space.s, marginBottom: space.m, padding: 6, minHeight: 52},
+ readOnly: {flexDirection: 'row', alignItems: 'center', gap: space.m, marginHorizontal: space.card, marginTop: space.s, marginBottom: space.m, paddingHorizontal: space.l, paddingVertical: 14},
+ readOnlyText: {flex: 1, color: c.muted, ...type.subhead},
+ add: {width: 40, height: 40, borderRadius: 20, backgroundColor: c.fill, alignItems: 'center', justifyContent: 'center'},
+ circle: {width: 40, height: 40, borderRadius: 20, alignItems: 'center', justifyContent: 'center'},
+ stop: {width: 48, height: 48, margin: -4, alignItems: 'center', justifyContent: 'center'},
+ input: {flex: 1, minHeight: 40, maxHeight: 140, color: c.text, paddingHorizontal: 4, paddingTop: 9, paddingBottom: 9, ...type.body},
+ chips: {flexDirection: 'row', gap: space.s, paddingHorizontal: space.card, paddingTop: space.s},
+ files: {flexDirection: 'row', flexWrap: 'wrap', gap: space.s, paddingHorizontal: space.card, paddingTop: space.s},
+ file: {flexDirection: 'row', alignItems: 'center', gap: space.s, maxWidth: '100%', borderRadius: 18, backgroundColor: c.surface, paddingHorizontal: space.m, height: 36},
+ fileName: {color: c.text, ...type.subhead, flexShrink: 1},
+ queue: {alignItems: 'flex-end', gap: space.s, paddingHorizontal: space.margin, paddingTop: space.s},
+ queued: {maxWidth: '84%', borderRadius: 22, backgroundColor: c.bubble, opacity: 0.6, paddingVertical: 11, paddingHorizontal: space.l, gap: 4},
+ queuedText: {color: c.text, fontSize: 17, lineHeight: 23},
+ queuedNote: {flexDirection: 'row', alignItems: 'center', gap: 4, alignSelf: 'flex-end'},
+ queuedWait: {color: c.muted, ...type.caption},
+ queuedError: {color: c.danger, ...type.caption},
}));
diff --git a/packages/mobile/src/screens/ChatsHome.tsx b/packages/mobile/src/screens/ChatsHome.tsx
index 11e103da..923f654b 100644
--- a/packages/mobile/src/screens/ChatsHome.tsx
+++ b/packages/mobile/src/screens/ChatsHome.tsx
@@ -1,13 +1,17 @@
-/** The Chats tab (#326 phase 4): the computer pill over the chat list of the chosen computer, or of every computer when
- * Show all computers together is on; the pill opens the computer switcher. */
-import {useState} from 'react';
-import {StyleSheet, Text, View} from 'react-native';
+/** The Chats tab (v3): the large title with the computer line under it (it opens the computer switcher) and New chat in a
+ * glass capsule, over the chat list of the chosen computer, or of every computer when Show all computers together is on. */
+import {useState, type ReactElement} from 'react';
+import {Pressable, StyleSheet, Text, View} from 'react-native';
+import {useSafeAreaInsets} from 'react-native-safe-area-context';
import type {ComputerView} from '../connection/computers';
import {ComputerPill} from '../components/ComputerPill';
import {ComputerSwitcher} from '../components/ComputerSwitcher';
import {Button} from '../components/Button';
-import {space, themed, type} from '../theme';
+import {Icon} from '../components/Icon';
+import {EdgeFade, Glass} from '../components/v3';
+import {size, space, themed, type, useTheme} from '../theme';
import {ChatsScreen, type ChatSource} from './ChatsScreen';
+import {EmptyArt} from './Moments';
export interface ComputersProps {
computers: ComputerView[]; selectedId: string | null; showAll: boolean;
@@ -15,7 +19,7 @@ export interface ComputersProps {
}
const sourceOf = (view: ComputerView): ChatSource | null => view.connection ? {id: view.id, name: view.name, connection: view.connection, path: view.path} : null;
-/** The pill for the chosen computer (or "All computers"), with its switcher; for any screen's header. */
+/** The computer line for the chosen computer (or "All computers"), with its switcher; for any screen's large title. */
export function ComputerHeader({computers, selectedId, showAll, onSelect, onShowAll, onPair}: ComputersProps) {
const [open, setOpen] = useState(false);
const selected = computers.find(view => view.id === selectedId) ?? computers[0];
@@ -31,26 +35,59 @@ export function ComputerHeader({computers, selectedId, showAll, onSelect, onShow
);
}
-export function ChatsHome(props: ComputersProps & {onOpen(chatId: string, computerId: string): void}) {
+/** A large title (34 pt) with an optional second line and glass buttons at the top right. */
+export function LargeTitle({title, children, actions}: {title: string; children?: ReactElement | null; actions?: Array<{icon: 'compose' | 'more' | 'search'; label: string; onPress(): void}>}) {
+ const styles = useStyles(), c = useTheme();
+ const insets = useSafeAreaInsets();
+ return (
+
+
+ {actions?.length ?
+ {actions.map(action => )}
+ : null}
+
+ {title}
+ {children ? {children} : null}
+
+ );
+}
+
+export function ChatsHome(props: ComputersProps & {onOpen(chatId: string, computerId: string): void; onNew?(): void; searching?: boolean}) {
const styles = useStyles();
- const {computers, selectedId, showAll, onPair, onOpen} = props;
+ const {computers, selectedId, showAll, onPair, onOpen, onNew, searching} = props;
const selected = computers.find(view => view.id === selectedId) ?? computers[0];
const sources = (showAll ? computers : selected ? [selected] : []).map(sourceOf).filter((source): source is ChatSource => source !== null);
+ const header = ;
return (
-
- {sources.length ? : (
-
- {selected?.path === 'revoked' ? `This phone is no longer paired with ${selected.name}.` : 'No computer to show yet.'}
-
+ {sources.length ?
+
+ Start your first chat
+ {`It runs on ${selected?.name ?? 'your computer'}. Chats you start on the computer appear here live.`}
+ {onNew ? : null}
+ } /> : (
+
+ {header}
+
+ {selected?.path === 'revoked' ? `This phone is no longer paired with ${selected.name}.` : 'No computer to show yet.'}
+
+
)}
+
);
}
const useStyles = themed(c => StyleSheet.create({
screen: {flex: 1, backgroundColor: c.background},
- header: {paddingHorizontal: space.l, paddingTop: space.s, paddingBottom: space.s},
- center: {flex: 1, alignItems: 'center', justifyContent: 'center', gap: space.m, padding: space.l},
- text: {color: c.text, ...type.body, textAlign: 'center'},
+ top: {paddingHorizontal: space.margin, paddingBottom: space.s},
+ bar: {minHeight: size.glassCircle, flexDirection: 'row', justifyContent: 'flex-end'},
+ capsule: {flexDirection: 'row', height: size.glassCircle, paddingHorizontal: 4},
+ action: {width: 40, height: size.glassCircle, alignItems: 'center', justifyContent: 'center'},
+ title: {color: c.text, ...type.largeTitle, letterSpacing: 0.37},
+ sub: {marginTop: 2},
+ center: {flex: 1, alignItems: 'center', justifyContent: 'center', gap: space.m, padding: space.xl, paddingTop: 48},
+ emptyTitle: {color: c.text, ...type.title2, marginTop: space.l},
+ text: {color: c.muted, ...type.body, lineHeight: 24, textAlign: 'center'},
}));
diff --git a/packages/mobile/src/screens/ChatsScreen.tsx b/packages/mobile/src/screens/ChatsScreen.tsx
index fb4ca84a..ac3a234c 100644
--- a/packages/mobile/src/screens/ChatsScreen.tsx
+++ b/packages/mobile/src/screens/ChatsScreen.tsx
@@ -1,9 +1,10 @@
-/** The computer's chats, newest first, in the approved layout: a status dot, the title, the place and what it is doing, and
- * a count of what waits on the person. Filters for running chats and chats that need you. Updates live. With several
- * computers shown together each row names its computer; a computer that can't be reached shows its cached chats under a
- * calm banner, a running chat reading "Was running" (#326 phase 4). */
-import {memo, useEffect, useMemo, useState} from 'react';
-import {Pressable, RefreshControl, StyleSheet, Text, View} from 'react-native';
+/** The computer's chats in the v3 layout (MUS-SPEC-23-24B): two-line rows (what the chat is, and what it is doing now) with a
+ * 36 pt status glyph, grouped into Active (running or waiting on the person) and Earlier. No filter chips: search lives in the
+ * tab bar. A chat that starts running moves into Active with a selection tick. With several computers shown together each
+ * row names its computer; a computer that can't be reached shows its cached chats under a calm banner, a running chat
+ * reading "Was running" (#326 phase 4). */
+import {memo, useEffect, useMemo, useRef, useState, type ReactElement} from 'react';
+import {Pressable, RefreshControl, StyleSheet, Text, TextInput, View} from 'react-native';
import {LegendList} from '@legendapp/list/react-native';
import type {MobileChat, MobileConnection} from '../shared';
import {errorText} from '../hooks';
@@ -12,46 +13,61 @@ import {ago} from '../time';
import {offlineOf} from '../offline/connection';
import {ConnectionBanner} from '../components/ConnectionBanner';
import type {LinkPath} from '../connection/link';
-import {space, themed, touch, type, useTheme, type Palette} from '../theme';
-
-type Filter = 'all' | 'running' | 'needs';
-const FILTERS: Array<[Filter, string]> = [['all', 'All'], ['running', 'Running'], ['needs', 'Needs you']];
-const RUNNING = new Set(['running', 'stopping']);
+import {Icon} from '../components/Icon';
+import {GLYPH_WORD, glyphColor, glyphOf, Shimmer, StatusGlyph} from '../components/v3';
+import {TAB_BAR_SPACE} from '../components/GlassTabBar';
+import {size, space, themed, type, useTheme} from '../theme';
export {ago};
-const doing = (chat: MobileChat, offline = false): string => {
+const ACTIVE = new Set(['running', 'stopping', 'waiting']);
+const isActive = (chat: MobileChat) => ACTIVE.has(chat.status) || chat.needsYou > 0;
+/** What a chat is doing now, in plain words (the lead word is coloured for a chat that needs the person or failed). */
+function doing(chat: MobileChat, offline: boolean): {lead?: string; text: string} {
switch (chat.status) {
- case 'running': return offline ? 'Was running' : `Working ${ago(chat.updatedAt)}`;
- case 'stopping': return 'Stopping';
- case 'waiting': return 'Waiting for you';
- case 'failed': return `Failed · ${ago(chat.updatedAt)}`;
- case 'interrupted': return `Stopped · ${ago(chat.updatedAt)}`;
- case 'completed': return `Done · ${ago(chat.updatedAt)}`;
- default: return ago(chat.updatedAt);
+ case 'running': return {text: offline ? 'Was running' : 'Working'};
+ case 'stopping': return {text: 'Stopping'};
+ case 'waiting': return {lead: 'Needs you', text: ''};
+ case 'failed': return {lead: 'Failed', text: ''};
+ case 'interrupted': return {text: 'Stopped'};
+ case 'completed': return {text: 'Done'};
+ default: return {text: ''};
}
-};
-const dotColor = (c: Palette, status: MobileChat['status']): string =>
- status === 'running' ? c.accent : status === 'waiting' || status === 'stopping' ? c.warning : status === 'completed' ? c.success : status === 'failed' ? c.danger : c.control;
+}
/** One computer's chats, as the screen gets them. `path` is how the phone reaches it (for the banner). */
export interface ChatSource { id: string; name: string; connection: MobileConnection; path?: LinkPath }
interface Row { key: string; chat: MobileChat; computerId: string; computer: string | null; offline: boolean }
+type Entry = {header: string} | Row;
const ChatRow = memo(function ChatRow({row, onOpen}: {row: Row; onOpen(chatId: string, computerId: string): void}) {
const styles = useStyles(), c = useTheme();
- const {chat} = row, what = doing(chat, row.offline);
+ const {chat} = row, kind = glyphOf(chat.status, row.offline), what = doing(chat, row.offline);
+ const rest = [row.computer, chat.place, what.text].filter(Boolean).join(' · ');
+ const line = what.lead ? [what.lead, rest].filter(Boolean).join(' · ') : rest;
return (
- onOpen(chat.id, row.computerId)} style={({pressed}) => [styles.row, pressed && styles.pressed]}>
-
+ onOpen(chat.id, row.computerId)} style={({pressed}) => [styles.row, pressed && styles.pressed]}>
+
- {chat.title}
- {[row.computer, chat.place, what].filter(Boolean).join(' · ')}
+
+ {chat.title}
+ {ago(chat.updatedAt)}
+
+ {kind === 'running' ?
+ :
+ {what.lead ? {what.lead} : null}
+ {what.lead && rest ? ' · ' : ''}{rest}
+ }
- {chat.needsYou ? {chat.needsYou} : null}
);
});
+function Header({label}: {label: string}) {
+ const styles = useStyles();
+ return {label};
+}
+
const tags = new WeakMap();
let lastTag = 0;
/** Changes when a source is added, removed or gets a new connection (a reconnect, or going offline). */
@@ -75,57 +91,93 @@ function useChatsFrom(sources: ChatSource[]) {
return {lists: ready ? lists : null, error, refresh: () => Promise.all(sources.map(load))};
}
-export function ChatsScreen({connection, sources: given, onOpen}: {connection?: MobileConnection; sources?: ChatSource[]; onOpen(chatId: string, computerId: string): void}) {
+/** `header`: the screen's large title, scrolled with the list. `searching`: show the search field (from the tab bar). */
+export function ChatsScreen({connection, sources: given, onOpen, header, searching = false, empty}: {connection?: MobileConnection; sources?: ChatSource[]; onOpen(chatId: string, computerId: string): void; header?: ReactElement; searching?: boolean; empty?: ReactElement}) {
const styles = useStyles(), c = useTheme();
const sources = given ?? (connection ? [{id: '', name: connection.desktopName, connection}] : []);
const {lists, error, refresh} = useChatsFrom(sources);
- const [filter, setFilter] = useState('all');
const [refreshing, setRefreshing] = useState(false);
+ const [query, setQuery] = useState('');
const several = sources.length > 1;
const rows = useMemo(() => !lists ? null : sources.flatMap(source => (lists[source.id] ?? []).map((chat): Row => ({key: `${source.id}:${chat.id}`, chat, computerId: source.id, computer: several ? source.name : null, offline: Boolean(offlineOf(source.connection))})))
.sort((a, b) => b.chat.updatedAt.localeCompare(a.chat.updatedAt)), [lists, several, sourcesKey(sources)]);
- const shown = useMemo(() => (rows ?? []).filter(({chat}) => filter === 'all' || (filter === 'running' ? RUNNING.has(chat.status) : chat.needsYou > 0)), [rows, filter]);
+ // A row moving into Active gives one selection tick (not on the first load).
+ const active = useRef | null>(null);
+ useEffect(() => {
+ if (!rows) return;
+ const now = new Set(rows.filter(row => isActive(row.chat)).map(row => row.key));
+ if (active.current && [...now].some(key => !active.current!.has(key))) haptics.select();
+ active.current = now;
+ }, [rows]);
+ const entries = useMemo((): Entry[] => {
+ const needle = searching ? query.trim().toLowerCase() : '';
+ const shown = (rows ?? []).filter(row => !needle || row.chat.title.toLowerCase().includes(needle) || (row.chat.place ?? '').toLowerCase().includes(needle));
+ const now = shown.filter(row => isActive(row.chat)), earlier = shown.filter(row => !isActive(row.chat));
+ return [...(now.length ? [{header: 'Active'}, ...now] : []), ...(earlier.length ? [{header: 'Earlier'}, ...earlier] : [])];
+ }, [rows, query, searching]);
const pull = () => { setRefreshing(true); void refresh().finally(() => setRefreshing(false)); };
- return (
-
+ const top = (
+
+ {header}
+ {searching ?
+
+
+ : null}
{sources.map(source => { const offline = offlineOf(source.connection); return offline ? : null; })}
-
- {FILTERS.map(([value, label]) => (
- { haptics.select(); setFilter(value); }} style={[styles.segment, filter === value && styles.segmentOn]}>
- {label}
-
- ))}
-
{error ? {error} : null}
+
+ );
+ return (
+
row.key}
- estimatedItemSize={62}
+ data={entries}
+ keyExtractor={entry => 'header' in entry ? `h:${entry.header}` : entry.key}
+ getItemType={entry => 'header' in entry ? 'header' : 'row'}
+ estimatedItemSize={size.chatRow}
recycleItems={false}
+ ListHeaderComponent={top}
+ contentContainerStyle={styles.content}
refreshControl={}
- ListEmptyComponent={rows ? {filter === 'all' ? `No chats on ${several ? 'your computers' : sources[0]?.name ?? 'your computer'} yet.` : 'Nothing here right now.'} : Loading…}
- renderItem={({item: row}) => }
+ ListEmptyComponent={rows ? (query ? No chats match “{query}”. : empty ?? {`No chats on ${several ? 'your computers' : sources[0]?.name ?? 'your computer'} yet.`}) : }
+ renderItem={({item: entry}) => 'header' in entry ? : }
/>
);
}
+
+/** Loading: skeletons the shape of the two-line row, so nothing jumps when the list lands. */
+function Skeleton() {
+ const styles = useStyles();
+ return (
+
+ {Array.from({length: 6}, (_, index) => (
+
+
+
+
+ ))}
+
+ );
+}
+
const useStyles = themed(c => StyleSheet.create({
screen: {flex: 1, backgroundColor: c.background},
- segments: {flexDirection: 'row', marginHorizontal: space.m, marginBottom: space.s, padding: 2, borderRadius: 9, backgroundColor: c.surface},
- segment: {flex: 1, minHeight: 32, alignItems: 'center', justifyContent: 'center', borderRadius: 7},
- segmentOn: {backgroundColor: c.scheme === 'light' ? c.raised : 'rgba(255,255,255,0.1)'},
- segmentText: {color: c.muted, ...type.label},
- segmentTextOn: {color: c.strong, fontWeight: '600'},
- row: {flexDirection: 'row', alignItems: 'center', gap: space.m, minHeight: Math.max(touch, 60), paddingVertical: space.s, paddingHorizontal: space.l, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: c.border},
+ content: {paddingBottom: TAB_BAR_SPACE},
+ header: {paddingHorizontal: space.margin, paddingTop: space.l, paddingBottom: space.s},
+ headerText: {color: c.muted, ...type.footnote, fontWeight: '500'},
+ row: {flexDirection: 'row', gap: space.m, minHeight: size.chatRow, paddingTop: space.m, paddingBottom: space.m, paddingLeft: space.l, paddingRight: space.margin},
pressed: {backgroundColor: c.surface},
- dot: {width: 8, height: 8, borderRadius: 4},
- dotRunning: {shadowColor: c.accent, shadowOpacity: 0.6, shadowRadius: 3},
- body: {flex: 1, gap: 2},
- title: {color: c.strong, ...type.footnote, fontWeight: '600'},
- sub: {color: c.faint, ...type.caption},
- failed: {color: c.danger},
- pill: {color: c.warning, backgroundColor: c.scheme === 'light' ? 'rgba(160,120,0,0.12)' : 'rgba(224,168,79,0.18)', ...type.caption, fontWeight: '600', paddingHorizontal: space.s, borderRadius: 6, overflow: 'hidden'},
- empty: {color: c.muted, ...type.footnote, padding: space.l, textAlign: 'center'},
- error: {color: c.danger, ...type.label, paddingHorizontal: space.l},
+ lead: {width: size.glyph, height: 44, alignItems: 'center', justifyContent: 'center'},
+ body: {flex: 1, minWidth: 0, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: c.border, paddingBottom: space.s},
+ top: {flexDirection: 'row', alignItems: 'baseline', gap: space.s},
+ title: {flex: 1, color: c.text, ...type.headline},
+ time: {color: c.muted, ...type.subhead},
+ preview: {color: c.muted, ...type.subhead, marginTop: 3},
+ search: {flexDirection: 'row', alignItems: 'center', gap: space.s, marginHorizontal: space.l, marginBottom: space.s, paddingHorizontal: space.m, height: 40, borderRadius: 20, backgroundColor: c.fill},
+ searchInput: {flex: 1, color: c.text, ...type.body, paddingVertical: 0},
+ empty: {color: c.muted, ...type.callout, padding: space.margin, textAlign: 'center'},
+ error: {color: c.danger, ...type.footnote, paddingHorizontal: space.margin},
+ skeletonDot: {borderRadius: size.glyph / 2, backgroundColor: c.surface, width: size.glyph, height: size.glyph},
+ bar: {height: 13, borderRadius: 6, backgroundColor: c.surface},
}));
diff --git a/packages/mobile/src/screens/Moments.tsx b/packages/mobile/src/screens/Moments.tsx
new file mode 100644
index 00000000..b687b054
--- /dev/null
+++ b/packages/mobile/src/screens/Moments.tsx
@@ -0,0 +1,133 @@
+/** The v3 moments: all clear, paired and a run finishing, plus the lit empty-state art. Each animates once with the bouncy
+ * spring and gives its haptic once; under Reduce Motion they show still. */
+import {useEffect} from 'react';
+import {StyleSheet, Text, View} from 'react-native';
+import Animated, {useAnimatedStyle, useSharedValue, withDelay, withSpring, withTiming} from 'react-native-reanimated';
+import {Circle, Defs, Path, RadialGradient, Rect, Stop, Svg} from 'react-native-svg';
+import {haptics} from '../haptics';
+import {springs, useReduceMotion} from '../motion';
+import {radius, space, themed, type, useTheme} from '../theme';
+import {Button} from '../components/Button';
+import {Icon, type IconName} from '../components/Icon';
+
+/** Rings that scale out once from 0.6 with the bouncy spring, around a filled disc with a glyph. */
+function Burst({icon, color, size = 180}: {icon: IconName; color: string; size?: number}) {
+ const reduce = useReduceMotion();
+ const grow = useSharedValue(reduce ? 1 : 0.6);
+ useEffect(() => { if (!reduce) grow.value = withSpring(1, springs.bouncy); }, [reduce]);
+ const rings = useAnimatedStyle(() => ({transform: [{scale: grow.value}], opacity: Math.min(1, grow.value)}));
+ const half = size / 2;
+ return (
+
+
+
+
+
+
+
+
+ );
+}
+
+/** Answering the last thing that waited (MUS-SPEC-23-24G): the burst, All clear, and what was just answered. */
+export function AllClear({answered, celebrate}: {answered: string[]; celebrate: boolean}) {
+ const styles = useStyles(), c = useTheme();
+ useEffect(() => { if (celebrate) haptics.moment(); }, [celebrate]);
+ return (
+
+ {celebrate ? : }
+ All clear
+ Agents keep working. You’ll hear from them when they need you.
+ {answered.length ?
+ Just answered
+ {answered.map((line, index) => (
+ 0 && styles.divider]}>{line}
+ ))}
+ : null}
+
+ );
+}
+
+/** Pairing worked (MUS-SPEC-23-24I): a shield, who can read what passes, and one next step. */
+export function PairedMoment({name, onContinue}: {name: string; onContinue(): void}) {
+ const styles = useStyles(), c = useTheme();
+ useEffect(() => { haptics.success(); }, []);
+ return (
+
+
+ {`Paired with ${name}`}
+ {`Only this phone and ${name} can read what passes between them. The relay carries it, but nobody in between can read it.`}
+ It starts watch-only. To send, steer and answer from here, choose Can act for this phone on the computer.
+
+
+ );
+}
+
+/** The live line resolving into a summary when a turn ends (MUS-SPEC-23-24C). */
+export function RunFinished({took, files, onReview}: {took: string | null; files: number; onReview?(): void}) {
+ const styles = useStyles(), c = useTheme();
+ const reduce = useReduceMotion();
+ const pulse = useSharedValue(reduce ? 0 : 1);
+ useEffect(() => { if (!reduce) pulse.value = withDelay(80, withTiming(0, {duration: 600})); }, [reduce]);
+ const ring = useAnimatedStyle(() => ({opacity: pulse.value * 0.6, transform: [{scale: 1 + (1 - pulse.value) * 0.8}]}));
+ return (
+
+
+
+
+
+
+ Run finished
+
+ {took ? {`${took} · `} : null}
+ {files === 1 ? '1 file changed' : files ? `${files} files changed` : 'No files changed'}
+
+
+ {files && onReview ? : null}
+
+ );
+}
+
+/** The lit illustration for empty screens. */
+export function EmptyArt() {
+ const c = useTheme();
+ return (
+
+ );
+}
+
+const useStyles = themed(c => StyleSheet.create({
+ moment: {alignItems: 'center', paddingHorizontal: space.margin, paddingTop: space.xl, gap: space.s},
+ still: {width: 80, height: 80, borderRadius: 40, backgroundColor: c.successTint, alignItems: 'center', justifyContent: 'center', marginBottom: space.m},
+ title: {color: c.text, ...type.title1, textAlign: 'center'},
+ body: {color: c.muted, ...type.body, lineHeight: 24, textAlign: 'center'},
+ note: {color: c.muted, ...type.footnote, textAlign: 'center', marginTop: space.s},
+ action: {alignSelf: 'stretch', marginTop: space.xl},
+ receipts: {alignSelf: 'stretch', marginTop: space.xl},
+ section: {color: c.muted, ...type.footnote, fontWeight: '500', paddingHorizontal: space.xs, paddingBottom: space.s},
+ group: {backgroundColor: c.surface, borderRadius: radius.group, overflow: 'hidden'},
+ receipt: {flexDirection: 'row', alignItems: 'center', gap: space.m, minHeight: 52, paddingHorizontal: space.l},
+ divider: {borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: c.border},
+ receiptText: {flex: 1, color: c.text, ...type.callout},
+ finished: {flexDirection: 'row', alignItems: 'center', gap: 14, backgroundColor: c.surface, borderRadius: radius.card, padding: space.l, marginTop: space.s},
+ tile: {width: 40, height: 40, borderRadius: 12, backgroundColor: c.successTint, alignItems: 'center', justifyContent: 'center'},
+ pulse: {position: 'absolute', width: 40, height: 40, borderRadius: 12, borderWidth: 2},
+ finishedBody: {flex: 1, gap: 2},
+ finishedTitle: {color: c.text, ...type.headline},
+ finishedSub: {color: c.muted, ...type.footnote},
+ subRow: {flexDirection: 'row', flexWrap: 'wrap'},
+}));
diff --git a/packages/mobile/src/screens/NeedsYouScreen.tsx b/packages/mobile/src/screens/NeedsYouScreen.tsx
index 784a5545..e3ad1895 100644
--- a/packages/mobile/src/screens/NeedsYouScreen.tsx
+++ b/packages/mobile/src/screens/NeedsYouScreen.tsx
@@ -1,9 +1,13 @@
/** Everything waiting on the person across chats; approvals and questions are answered right here. A phone that can act
* swipes an approval right to approve it or left to decline it. With several computers shown together each one has its
* own section; a computer that is offline shows what it last asked for, to answer once it is back (#326 phase 4). */
+import {useEffect, useRef, useState} from 'react';
import {ScrollView, StyleSheet, Text, View} from 'react-native';
import type {MobileConnection, MobileNeed} from '../shared';
import {useAccess, useNeeds} from '../hooks';
+import {TAB_BAR_SPACE} from '../components/GlassTabBar';
+import {LargeTitle} from './ChatsHome';
+import {AllClear} from './Moments';
import {offlineOf} from '../offline/connection';
import {ApprovalCard, offlineNote, useApprovalResponse} from '../components/ApprovalCard';
import {QuestionCard} from '../components/QuestionCard';
@@ -12,9 +16,18 @@ import {space, themed, type} from '../theme';
export interface NeedsSource { id: string; name: string; connection: MobileConnection }
-function ApprovalRow({connection, need, canAct, offline}: {connection: MobileConnection; need: MobileNeed; canAct: boolean; offline?: string}) {
+/** What the person answered here, for the receipts under All clear. */
+type Answered = (line: string) => void;
+
+function ApprovalRow({connection, need, canAct, offline, onAnswered}: {connection: MobileConnection; need: MobileNeed; canAct: boolean; offline?: string; onAnswered: Answered}) {
const response = useApprovalResponse(connection, need.itemId);
- const card = ;
+ const told = useRef(false);
+ useEffect(() => {
+ if (!response.answered || told.current) return;
+ told.current = true;
+ onAnswered(`${response.answered === 'accept' ? 'Approved' : 'Declined'} ${need.approval?.command ?? need.summary}`);
+ }, [response.answered]);
+ const card = ;
if (!canAct || offline || response.answered) return card;
return (
response.respond('accept')} onLeft={() => response.respond('decline')}>
@@ -23,20 +36,20 @@ function ApprovalRow({connection, need, canAct, offline}: {connection: MobileCon
);
}
-function NeedsSection({source, heading, onOpen}: {source: NeedsSource; heading: boolean; onOpen?(chatId: string, computerId: string): void}) {
+function NeedsSection({source, heading, needs, error, onOpen, onAnswered}: {source: NeedsSource; heading: boolean; needs: MobileNeed[] | null; error: string | null; onOpen?(chatId: string, computerId: string): void; onAnswered: Answered}) {
const styles = useStyles();
const {connection} = source;
- const {needs, error} = useNeeds(connection);
const canAct = useAccess(connection) === 'act';
const offline = offlineOf(connection) ? source.name : undefined;
+ if (!needs?.length && !error && !heading) return null;
return (
{heading ? {source.name}{offline ? ' · offline' : ''} : null}
{error ? {error} : null}
- {needs && !needs.length ? {heading ? 'Nothing waiting.' : 'All clear. Nothing needs you right now.'} : null}
+ {heading && needs && !needs.length ? Nothing waiting. : null}
{(needs ?? []).map(need => (
- {need.kind === 'approval' ? : (
+ {need.kind === 'approval' ? : (
<>
onOpen(need.chatId, source.id) : undefined} accessibilityRole={onOpen ? 'link' : undefined}>{need.chatTitle}
@@ -48,25 +61,48 @@ function NeedsSection({source, heading, onOpen}: {source: NeedsSource; heading:
);
}
+/** Every source's needs, live. */
+function useAllNeeds(sources: NeedsSource[]) {
+ return sources.map(source => ({source, ...useNeeds(source.connection)}));
+}
+function Sources({sources, children}: {sources: NeedsSource[]; children(all: ReturnType): React.ReactNode}) {
+ return <>{children(useAllNeeds(sources))}>;
+}
+
+/** Needs you (v3): one queue for every computer under a large title that counts what waits, one decision per card. Answering
+ * the last one shows the All clear moment with what was just answered (MUS-SPEC-23-24G). */
export function NeedsYouScreen({connection, sources: given, onOpen}: {connection?: MobileConnection; sources?: NeedsSource[]; onOpen?(chatId: string, computerId: string): void}) {
const styles = useStyles();
const sources = given ?? (connection ? [{id: '', name: connection.desktopName, connection}] : []);
+ const [answered, setAnswered] = useState([]);
+ const onAnswered: Answered = line => setAnswered(current => [line, ...current].slice(0, 5));
+ // The hooks run per source; the source list only changes with the computers, so it is keyed on their ids.
return (
-
- {/* The feed is short (what waits right now), so a plain scroll view; the chat and chat lists are virtualized. */}
-
- {sources.map(source => 1} {...(onOpen ? {onOpen} : {})} />)}
-
-
+ source.id).join(',')} sources={sources}>{all => {
+ const loaded = all.every(entry => entry.needs);
+ const waiting = all.reduce((sum, entry) => sum + (entry.needs?.length ?? 0), 0);
+ return (
+
+ {!loaded ? 'Loading…' : waiting ? `${waiting} waiting` : 'Nothing waiting'}{sources.length > 1 ? · all computers : null}
+
+ {all.map(({source, needs, error}) => 1 && Boolean(needs?.length)} needs={needs} error={error} onAnswered={onAnswered} {...(onOpen ? {onOpen} : {})} />)}
+
+ {loaded && !waiting ? 0} /> : null}
+
+ );
+ }}
);
}
const useStyles = themed(c => StyleSheet.create({
screen: {flex: 1, backgroundColor: c.background},
- content: {padding: space.m},
- section: {paddingBottom: space.s},
- computer: {color: c.muted, ...type.caption, fontWeight: '600', textTransform: 'uppercase', paddingVertical: space.s},
- entry: {gap: space.xs, paddingBottom: space.m},
- chat: {color: c.accent, ...type.label, fontWeight: '600'},
- muted: {color: c.muted, ...type.body, padding: space.l, textAlign: 'center'},
- error: {color: c.danger, ...type.label, padding: space.l},
+ content: {paddingBottom: TAB_BAR_SPACE},
+ count: {color: c.text, ...type.subhead, fontWeight: '600'},
+ countSub: {color: c.muted, fontWeight: '400'},
+ cards: {paddingHorizontal: space.card, gap: 14},
+ section: {gap: 14},
+ computer: {color: c.muted, ...type.footnote, fontWeight: '500', paddingHorizontal: space.xs, paddingTop: space.s},
+ entry: {gap: space.xs},
+ chat: {color: c.accent, ...type.footnote, fontWeight: '600', paddingHorizontal: space.xs},
+ muted: {color: c.muted, ...type.subhead, paddingHorizontal: space.xs},
+ error: {color: c.danger, ...type.footnote, padding: space.l},
}));
diff --git a/packages/mobile/src/screens/NewChatScreen.tsx b/packages/mobile/src/screens/NewChatScreen.tsx
index 901db1de..c9970a3c 100644
--- a/packages/mobile/src/screens/NewChatScreen.tsx
+++ b/packages/mobile/src/screens/NewChatScreen.tsx
@@ -1,20 +1,26 @@
/** New chat: pick a folder or Project from the computer's list, a provider and one of its models, then start the chat on the
* computer and open it. Needs act access; the computer checks again. */
import {useEffect, useState} from 'react';
-import {Pressable, ScrollView, StyleSheet, Text, View} from 'react-native';
+import {Pressable, ScrollView, StyleSheet, Text, TextInput, View} from 'react-native';
import type {MobileConnection, MobileMethods, MobilePlace} from '../shared';
-import {errorText, READ_ONLY_NOTE, useAccess} from '../hooks';
+import {errorText, READ_ONLY_NOTE, requestId, useAccess} from '../hooks';
+import {haptics} from '../haptics';
+import {Icon} from '../components/Icon';
import {Button} from '../components/Button';
-import {font, radius, space, themed, useTheme} from '../theme';
+import {radius, space, themed, type, useTheme} from '../theme';
type Options = MobileMethods['chat.options']['result'];
-function Choice({label, detail, selected, onPress}: {label: string; detail?: string; selected: boolean; onPress(): void}) {
- const styles = useStyles();
+/** One row of a grouped list with a check on the chosen one. */
+function Choice({label, detail, selected, onPress, first}: {label: string; detail?: string; selected: boolean; onPress(): void; first: boolean}) {
+ const styles = useStyles(), c = useTheme();
return (
-
- {label}
- {detail ? {detail} : null}
+ { haptics.select(); onPress(); }} style={({pressed}) => [styles.choice, !first && styles.divider, pressed && styles.pressed]}>
+
+ {label}
+ {detail ? {detail} : null}
+
+ {selected ? : null}
);
}
@@ -27,6 +33,7 @@ export function NewChatScreen({connection, onCreated}: {connection: MobileConnec
const [providerId, setProviderId] = useState(null);
const [model, setModel] = useState(null);
const [busy, setBusy] = useState(false);
+ const [task, setTask] = useState('');
const [error, setError] = useState(null);
useEffect(() => {
if (access !== 'act') return;
@@ -45,40 +52,52 @@ export function NewChatScreen({connection, onCreated}: {connection: MobileConnec
const provider = options?.providers.find(entry => entry.id === providerId) ?? null;
const start = async () => {
if (!providerId || !model || busy) return;
+ haptics.medium();
setBusy(true); setError(null);
try {
const {chat} = await connection.call('chat.create', {...(place?.kind === 'folder' ? {folderId: place.id} : place?.kind === 'project' ? {projectId: place.id} : {}), providerId, model});
+ // The task goes as the chat's first message.
+ if (task.trim()) await connection.call('chat.send', {id: chat.id, text: task.trim(), requestId: requestId()});
onCreated(chat.id);
} catch (failure) { setError(errorText(failure)); } finally { setBusy(false); }
};
return (
-
- {!options && !error ? Loading… : null}
- {options ? <>
- Where
- {options.places.length ? options.places.map(entry => setPlace(entry)} />)
- : No folders or Projects on {connection.desktopName}; the chat starts without one.}
- Provider
- {options.providers.length ? options.providers.map(entry => { setProviderId(entry.id); setModel(entry.models[0]?.id ?? null); }} />)
- : No provider is ready on {connection.desktopName}. Connect one in Muster on your computer.}
- {provider ? <>
- Model
- {provider.models.map(entry => setModel(entry.id)} />)}
+
+
+
+ {!options && !error ? Loading… : null}
+ {options ? <>
+ Where
+ {options.places.length ? {options.places.map((entry, index) => setPlace(entry)} />)}
+ : No folders or Projects on {connection.desktopName}; the chat starts without one.}
+ Agent
+ {options.providers.length ? {options.providers.map((entry, index) => { setProviderId(entry.id); setModel(entry.models[0]?.id ?? null); }} />)}
+ : No provider is ready on {connection.desktopName}. Connect one in Muster on your computer.}
+ {provider ? <>
+ Model
+ {provider.models.map((entry, index) => setModel(entry.id)} />)}
+ > : null}
> : null}
- void start()} />
- > : null}
- {error ? {error} : null}
-
+ {error ? {error} : null}
+
+ {options ? void start()} /> : null}
+
);
}
const useStyles = themed(colors => StyleSheet.create({
screen: {flex: 1, backgroundColor: colors.background},
- content: {padding: space.l, gap: space.s},
- label: {color: colors.muted, fontSize: font.small, marginTop: space.m},
- choice: {borderWidth: 1, borderColor: colors.border, borderRadius: radius.m, paddingVertical: space.s, paddingHorizontal: space.m, gap: 2},
- selected: {borderColor: colors.accent, backgroundColor: colors.surface},
- choiceLabel: {color: colors.text, fontSize: font.body},
- muted: {color: colors.muted, fontSize: font.small},
- note: {color: colors.muted, fontSize: font.small, padding: space.l},
- error: {color: colors.danger, fontSize: font.small},
+ content: {padding: space.card, gap: space.s, paddingBottom: space.xl},
+ task: {minHeight: 96, backgroundColor: colors.surface, borderRadius: radius.card, padding: space.l, color: colors.text, ...type.body, textAlignVertical: 'top'},
+ label: {color: colors.muted, ...type.footnote, fontWeight: '500', paddingHorizontal: space.l, marginTop: space.l},
+ group: {backgroundColor: colors.surface, borderRadius: radius.group, overflow: 'hidden'},
+ choice: {flexDirection: 'row', alignItems: 'center', gap: space.m, minHeight: 52, paddingHorizontal: space.l, paddingVertical: 10},
+ divider: {borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: colors.border},
+ pressed: {backgroundColor: colors.raised},
+ choiceBody: {flex: 1, gap: 2},
+ choiceLabel: {color: colors.text, ...type.body},
+ detail: {color: colors.muted, ...type.subhead},
+ muted: {color: colors.muted, ...type.subhead, paddingHorizontal: space.l},
+ note: {color: colors.muted, ...type.subhead, padding: space.margin},
+ error: {color: colors.danger, ...type.footnote, paddingHorizontal: space.l},
+ bottom: {padding: space.card, paddingBottom: space.xl},
}));
diff --git a/packages/mobile/src/screens/PairScreen.tsx b/packages/mobile/src/screens/PairScreen.tsx
index 22d31062..a25d919d 100644
--- a/packages/mobile/src/screens/PairScreen.tsx
+++ b/packages/mobile/src/screens/PairScreen.tsx
@@ -2,25 +2,29 @@
* link. One attempt at a time: while one is in flight (the desktop may already be waiting on its check code) the scanner is
* hidden and Pair does nothing, so a second attempt can't fail with "code already used" over the code the person needs. */
import {useEffect, useRef, useState, type ReactNode} from 'react';
-import {StyleSheet, Text, TextInput, View} from 'react-native';
+import {ScrollView, StyleSheet, Text, TextInput, View} from 'react-native';
import {groupCheckCode, MobileError, NOT_A_PAIRING_LINK, parsePairingLink, type PairedRecord, type PairingLink} from '../shared';
import type {PairingStore} from '../connection/store';
import {Button} from '../components/Button';
import {errorText} from '../hooks';
-import {font, radius, space, themed, useTheme} from '../theme';
+import {font, radius, space, themed, type, useTheme} from '../theme';
+import {Icon} from '../components/Icon';
+import {PairedMoment} from './Moments';
export interface PairScreenProps {
/** Runs the pairing handshake; `confirmed` settles when the desktop adds the phone after the owner compared check codes. */
pairWith(link: PairingLink): Promise<{record: PairedRecord; checkCode: string; confirmed: Promise}>;
store: PairingStore;
onPaired?(record: PairedRecord): void;
+ /** Continue on the paired moment. */
+ onDone?(): void;
/** The camera scanner (not rendered in tests); it calls back with the scanned text. */
scanner?: (onScan: (text: string) => void) => ReactNode;
/** A link the app was opened with (muster://pair?…): filled in and paired at once. */
initialLink?: string;
}
-export function PairScreen({pairWith, store, onPaired, scanner, initialLink}: PairScreenProps) {
+export function PairScreen({pairWith, store, onPaired, onDone, scanner, initialLink}: PairScreenProps) {
const styles = useStyles(), colors = useTheme();
const [text, setText] = useState(initialLink ?? '');
const [busy, setBusy] = useState(false);
@@ -46,32 +50,43 @@ export function PairScreen({pairWith, store, onPaired, scanner, initialLink}: Pa
} catch (failure) { setError(errorText(failure)); } finally { inFlight.current = false; setBusy(false); }
};
useEffect(() => { if (initialLink) void pair(initialLink); }, [initialLink]);
+ if (paired) return onDone?.()} />;
return (
-
- Pair with your computer
- On your computer, open Muster › Settings › Integrations › Phone and press Pair a phone. Scan the code, or paste its link.
- {scanner && !busy && !paired ? {scanner(value => { if (inFlight.current) return; setText(value); void pair(value); })} : null}
+
+ Pair with your computer
+
+
+ On your computer, open Muster › Settings › Integrations › Phone and press Pair a phone. Scan the code, or paste its link. The link is end-to-end encrypted.
+
+ {scanner && !busy ? {scanner(value => { if (inFlight.current) return; setText(value); void pair(value); })} : null}
void pair(text)} />
{checkCode ?
- Check code
- {groupCheckCode(checkCode)}
+ Check code
+ {groupCheckCode(checkCode).split('').map((digit, index) => digit === ' ' ? : {digit})}
+ {groupCheckCode(checkCode)}
Make sure your computer shows the same code, then confirm it on your computer with Add phone. If the codes differ, reject it there.
: null}
{error && !checkCode ? {error} : null}
- {paired ? {`Paired with ${paired}`} : null}
A new phone can read your chats. To send, steer or answer from it, choose Can act for it on your computer.
-
+
);
}
const useStyles = themed(colors => StyleSheet.create({
- screen: {flex: 1, backgroundColor: colors.background, padding: space.l, gap: space.m},
- title: {color: colors.text, fontSize: 22, fontWeight: '700'},
- muted: {color: colors.muted, fontSize: font.small, lineHeight: 18},
- scanner: {height: 260, borderRadius: radius.m, overflow: 'hidden', backgroundColor: colors.surface},
- input: {borderWidth: 1, borderColor: colors.control, borderRadius: radius.s, color: colors.text, padding: space.m, fontSize: font.body},
- check: {borderWidth: 1, borderColor: colors.border, borderRadius: radius.m, padding: space.m, gap: space.s, alignItems: 'center'},
- code: {color: colors.text, fontSize: 32, fontWeight: '700', letterSpacing: 4, fontVariant: ['tabular-nums']},
- error: {color: colors.danger, fontSize: font.small},
- success: {color: colors.success, fontSize: font.body},
+ screen: {flex: 1, backgroundColor: colors.background},
+ content: {padding: space.margin, gap: space.l, paddingBottom: 48},
+ title: {color: colors.text, ...type.title1},
+ card: {flexDirection: 'row', gap: 14, alignItems: 'flex-start', backgroundColor: colors.surface, borderRadius: radius.card, padding: space.l},
+ cardText: {flex: 1, color: colors.text, ...type.subhead},
+ muted: {color: colors.muted, ...type.footnote},
+ scanner: {height: 280, borderRadius: radius.card, overflow: 'hidden', backgroundColor: colors.surface},
+ input: {borderWidth: 1, borderColor: colors.control, borderRadius: radius.well, color: colors.text, paddingHorizontal: space.l, height: 50, ...type.body},
+ check: {backgroundColor: colors.surface, borderRadius: radius.card, padding: space.l, gap: space.m, alignItems: 'center'},
+ checkTitle: {color: colors.text, ...type.headline},
+ boxes: {flexDirection: 'row', gap: 6},
+ box: {width: 40, height: 52, borderRadius: 12, backgroundColor: colors.fill, alignItems: 'center', justifyContent: 'center'},
+ gap: {width: 10},
+ digit: {color: colors.text, fontSize: 28, lineHeight: 34, fontWeight: '700', fontFamily: font.mono},
+ hidden: {position: 'absolute', opacity: 0, height: 1},
+ error: {color: colors.danger, ...type.subhead},
}));
diff --git a/packages/mobile/src/screens/SettingsScreen.tsx b/packages/mobile/src/screens/SettingsScreen.tsx
index a4f02fb3..c5b09641 100644
--- a/packages/mobile/src/screens/SettingsScreen.tsx
+++ b/packages/mobile/src/screens/SettingsScreen.tsx
@@ -1,35 +1,80 @@
-/** This phone's computers (#326 phase 4): each with how it is connected and what this phone may do there, and Unpair, which
- * forgets that computer's keys and everything cached from it on this phone. Pair another computer adds one. */
-import {StyleSheet, Text, View} from 'react-native';
+/** Settings in the iOS anatomy (v3): this phone as the hero row, then its computers (an eye on a watch-only one; tap one for
+ * what it allows and Unpair), then Pair another computer. Unpairing asks first and forgets that computer's keys and
+ * everything cached from it on this phone. */
+import {useState} from 'react';
+import {Alert, Platform, Pressable, ScrollView, StyleSheet, Text, View} from 'react-native';
import type {ComputerView} from '../connection/computers';
-import {Button} from '../components/Button';
import {StatusDot} from '../components/ComputerPill';
-import {computerStatus} from '../components/ComputerSwitcher';
-import {space, themed, type} from '../theme';
+import {computerStatus, WatchOnly} from '../components/ComputerSwitcher';
+import {Icon} from '../components/Icon';
+import {TAB_BAR_SPACE} from '../components/GlassTabBar';
+import {haptics} from '../haptics';
+import {radius, size, space, themed, type, useTheme} from '../theme';
+import {LargeTitle} from './ChatsHome';
export function SettingsScreen({computers, onUnpair, onPair}: {computers: ComputerView[]; onUnpair(id: string): void; onPair(): void}) {
- const styles = useStyles();
+ const styles = useStyles(), c = useTheme();
+ const [open, setOpen] = useState(null);
+ const unpair = (view: ComputerView) => {
+ haptics.warning();
+ Alert.alert(`Unpair ${view.name}?`, 'This phone forgets its keys and the chats it saved from it.', [{text: 'Cancel', style: 'cancel'}, {text: 'Unpair', style: 'destructive', onPress: () => onUnpair(view.id)}]);
+ };
return (
-
- Computers
- {computers.map(view => (
-
- {view.name}
- {computerStatus(view)}
- {view.access ? {view.access === 'act' ? 'This phone can read, send, steer and answer' : 'This phone can read only'} : null}
- onUnpair(view.id)} />
+
+
+
+
+
+ This phone{`${Platform.OS === 'ios' ? 'iPhone' : 'Android'} · ${computers.length === 1 ? '1 computer' : `${computers.length} computers`}`}
- ))}
-
- Change what this phone can do on a computer, or revoke it, in Settings › Integrations › Phone on that computer. Unpairing here forgets its keys and the chats this phone saved from it.
-
+
+ Computers
+
+ {computers.map((view, index) => (
+
+ { haptics.select(); setOpen(current => current === view.id ? null : view.id); }}
+ style={({pressed}) => [styles.row, index > 0 && styles.divider, pressed && styles.pressed]}>
+
+
+ {view.name}{view.access === 'read-only' ? : null}
+ {computerStatus(view)}
+
+
+
+ {open === view.id ?
+ {view.access === 'act' ? 'This phone can read, send, steer and answer here.' : view.access === 'read-only' ? 'Watch only: this phone can read. To send, steer and answer, choose Can act for it in Settings › Integrations › Phone on the computer.' : 'Connecting…'}
+ unpair(view)} style={styles.unpair}>{`Unpair ${view.name}`}
+ : null}
+
+ ))}
+ 0 && styles.divider]}>
+
+ Pair another computer
+
+
+ Change what this phone can do on a computer, or revoke it, in Settings › Integrations › Phone on that computer.
+
);
}
const useStyles = themed(c => StyleSheet.create({
- screen: {flex: 1, backgroundColor: c.background, padding: space.l, gap: space.m},
- label: {color: c.muted, ...type.caption, fontWeight: '600', textTransform: 'uppercase'},
- card: {backgroundColor: c.surface, borderRadius: 14, padding: space.m, gap: space.s},
+ screen: {flex: 1, backgroundColor: c.background},
+ content: {paddingBottom: TAB_BAR_SPACE},
+ group: {marginHorizontal: space.card, backgroundColor: c.surface, borderRadius: radius.group, overflow: 'hidden'},
+ section: {color: c.muted, ...type.footnote, fontWeight: '500', paddingHorizontal: space.margin + 12, paddingTop: space.xl, paddingBottom: space.s},
+ row: {flexDirection: 'row', alignItems: 'center', gap: 14, minHeight: 52, paddingHorizontal: space.l, paddingVertical: 10},
+ hero: {minHeight: 76},
+ pressed: {backgroundColor: c.raised},
+ divider: {borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: c.border},
+ tile: {width: 32, height: 32, borderRadius: 8, backgroundColor: c.fill, alignItems: 'center', justifyContent: 'center'},
+ heroTile: {width: 52, height: 52, borderRadius: 14, backgroundColor: c.accentFill},
+ body: {flex: 1, gap: 2},
line: {flexDirection: 'row', alignItems: 'center', gap: space.s},
- name: {color: c.strong, ...type.footnote, fontWeight: '600'},
- muted: {color: c.muted, ...type.label},
+ heroTitle: {color: c.text, ...type.title3},
+ name: {color: c.text, ...type.body, flexShrink: 1},
+ sub: {color: c.muted, ...type.subhead, flexShrink: 1},
+ detail: {paddingHorizontal: space.l, paddingLeft: space.l + 32 + 14, paddingBottom: space.m, gap: space.s},
+ unpair: {minHeight: size.small, justifyContent: 'center'},
+ danger: {color: c.danger, ...type.body},
+ action: {color: c.accent, ...type.body},
+ footer: {color: c.muted, ...type.footnote, paddingHorizontal: space.margin + 12, paddingTop: space.s},
}));
diff --git a/packages/mobile/src/screens/TabletShell.tsx b/packages/mobile/src/screens/TabletShell.tsx
index a9bd49f5..c955c4dd 100644
--- a/packages/mobile/src/screens/TabletShell.tsx
+++ b/packages/mobile/src/screens/TabletShell.tsx
@@ -5,13 +5,14 @@ import {useState} from 'react';
import {Pressable, StyleSheet, Text, View} from 'react-native';
import {CHAT_COLUMN_MAX, INSPECTOR_WIDTH, SIDEBAR_WIDTH, widthClass} from '../layout';
import {haptics} from '../haptics';
-import {space, themed, touch, type} from '../theme';
+import {radius, space, themed, touch, type, useTheme} from '../theme';
+import {Icon} from '../components/Icon';
import {ChatsHome, type ComputersProps} from './ChatsHome';
import {ChatScreen} from './ChatScreen';
import {NeedsYouScreen} from './NeedsYouScreen';
-export function TabletShell(props: ComputersProps & {width: number; onOpen?(chatId: string, computerId: string): void}) {
- const styles = useStyles();
+export function TabletShell(props: ComputersProps & {width: number; onOpen?(chatId: string, computerId: string): void; onNew?(): void; searching?: boolean}) {
+ const styles = useStyles(), c = useTheme();
const {width, computers, selectedId, showAll, onOpen} = props;
const [open, setOpen] = useState<{chatId: string; computerId: string} | null>(null);
const [sidebar, setSidebar] = useState(true);
@@ -25,7 +26,7 @@ export function TabletShell(props: ComputersProps & {width: number; onOpen?(chat
{sidebar ? setOpen({chatId, computerId})} /> : null}
- {sidebar ? '⟨' : '☰'}
+
{open && current?.connection ?
@@ -33,7 +34,6 @@ export function TabletShell(props: ComputersProps & {width: number; onOpen?(chat
{size === 'expanded' ?
- Needs you
({id: view.id, name: view.name, connection: view.connection!}))} onOpen={(chatId, computerId) => setOpen({chatId, computerId})} />
: null}
@@ -41,13 +41,11 @@ export function TabletShell(props: ComputersProps & {width: number; onOpen?(chat
}
const useStyles = themed(c => StyleSheet.create({
row: {flex: 1, flexDirection: 'row', backgroundColor: c.background},
- sidebar: {width: SIDEBAR_WIDTH, borderRightWidth: StyleSheet.hairlineWidth, borderRightColor: c.border},
+ sidebar: {width: SIDEBAR_WIDTH, margin: space.s, marginRight: 0, borderRadius: radius.card, overflow: 'hidden', backgroundColor: c.surface},
center: {flex: 1},
toolbar: {flexDirection: 'row', paddingHorizontal: space.s, minHeight: touch, alignItems: 'center'},
tool: {width: touch, height: touch, alignItems: 'center', justifyContent: 'center'},
- toolText: {color: c.muted, ...type.headline},
column: {flex: 1, width: '100%', maxWidth: CHAT_COLUMN_MAX, alignSelf: 'center'},
- empty: {color: c.faint, ...type.body, textAlign: 'center', marginTop: space.xl},
- inspector: {width: INSPECTOR_WIDTH, borderLeftWidth: StyleSheet.hairlineWidth, borderLeftColor: c.border},
- heading: {color: c.muted, ...type.caption, fontWeight: '600', textTransform: 'uppercase', padding: space.m, paddingBottom: 0},
+ empty: {color: c.muted, ...type.body, textAlign: 'center', marginTop: space.xl},
+ inspector: {width: INSPECTOR_WIDTH, margin: space.s, marginLeft: 0, borderRadius: radius.card, overflow: 'hidden', backgroundColor: c.surface},
}));
diff --git a/packages/mobile/src/theme.ts b/packages/mobile/src/theme.ts
index ffbdc1d8..1181aef3 100644
--- a/packages/mobile/src/theme.ts
+++ b/packages/mobile/src/theme.ts
@@ -1,40 +1,76 @@
-/** Colours and spacing from the desktop app's design tokens (packages/agent-app/src/renderer/styles.css), in the approved
- * mobile concept's layout. The app follows the phone's light or dark setting (`useTheme`). Translucent desktop tokens are
- * flattened onto their background, so contrast can be checked: body text and `muted` are at least 7:1, `faint` at least
- * 4.5:1, labels on `accentFill` at least 4.5:1 and `control` (button and field edges) at least 3:1 (MUS-SPEC-23-14B). */
+/** The v3 design tokens (#326 phase 5; ~/.muster-work design v3, binding): tonal surfaces instead of outlines, the iOS type
+ * scale, 20 pt text margins and 16 pt card margins, capsule buttons and the glass material. The app follows the phone's light
+ * or dark setting (`useTheme`). Primary text is at least 7:1 on every surface, secondary at least 4.5:1, and `faint`
+ * (tertiary) is for decoration only (MUS-SPEC-23-24A). */
import {Platform, useColorScheme} from 'react-native';
export interface Palette {
scheme: 'dark' | 'light';
- background: string; surface: string; raised: string; menu: string; bubble: string; border: string; control: string;
+ /** The canvas, a grouped cell, a raised cell (inside a cell, sheets), a control fill, a menu and the user's bubble. */
+ background: string; surface: string; raised: string; fill: string; menu: string; bubble: string;
+ /** Code wells and inline code. */
+ code: string; inline: string;
+ /** Separators, inside cells only. */
+ border: string;
+ /** Edges of fields and controls that need 3:1. */
+ control: string;
text: string; strong: string; muted: string; faint: string;
accent: string; accentFill: string; onAccent: string; danger: string; success: string; warning: string;
- /** Diff and status tints behind added and removed lines. */
- addBg: string; delBg: string;
+ /** 16 % tints behind status glyphs and tinted buttons, and 26 % for emphasis. */
+ accentTint: string; accentTint2: string; successTint: string; warningTint: string; dangerTint: string;
+ /** Diff lines and their changed words. */
+ addBg: string; delBg: string; addWord: string; delWord: string;
+ /** The glass material: fill, the specular top edge, the hairline and the selected-tab fill. */
+ glass: string; glassHighlight: string; glassEdge: string; glassSelected: string;
+ /** The badge on the Needs you tab. */
+ badge: string;
+ scrim: string;
}
export const palettes: Record<'dark' | 'light', Palette> = {
dark: {
- scheme: 'dark', background: '#0e0e0e', surface: '#161616', raised: '#1c1c1c', menu: '#1c1c1c', bubble: '#262626', border: '#1f1f1f', control: '#6b6b6b',
- text: '#e8e8e8', strong: '#ffffff', muted: '#ababab', faint: '#8c8c8c',
- accent: '#91abc2', accentFill: '#91abc2', onAccent: '#0e0e0e', danger: '#e5735f', success: '#5bb98c', warning: '#e0a84f',
- addBg: 'rgba(91,185,140,0.12)', delBg: 'rgba(229,115,95,0.12)',
+ scheme: 'dark', background: '#0e0e0e', surface: '#1a1a1c', raised: '#242426', fill: '#2e2e31', menu: '#1f1f21', bubble: '#2a2c30',
+ code: '#141416', inline: 'rgba(255,255,255,0.08)', border: 'rgba(255,255,255,0.09)', control: '#6b6b70',
+ text: '#f2f2f3', strong: '#ffffff', muted: '#a7a7ad', faint: '#7e7e85',
+ accent: '#91abc2', accentFill: '#91abc2', onAccent: '#0b1118', danger: '#e5735f', success: '#5bb98c', warning: '#e0a84f',
+ accentTint: 'rgba(145,171,194,0.16)', accentTint2: 'rgba(145,171,194,0.26)', successTint: 'rgba(91,185,140,0.16)', warningTint: 'rgba(224,168,79,0.16)', dangerTint: 'rgba(229,115,95,0.16)',
+ addBg: 'rgba(91,185,140,0.13)', delBg: 'rgba(229,115,95,0.13)', addWord: 'rgba(91,185,140,0.34)', delWord: 'rgba(229,115,95,0.34)',
+ glass: 'rgba(38,38,42,0.52)', glassHighlight: 'rgba(255,255,255,0.16)', glassEdge: 'rgba(255,255,255,0.10)', glassSelected: 'rgba(255,255,255,0.14)',
+ badge: '#d48a00', scrim: 'rgba(0,0,0,0.52)',
},
light: {
- scheme: 'light', background: '#fbfbfb', surface: '#ffffff', raised: '#f2f2f4', menu: '#ffffff', bubble: '#ececef', border: '#e4e4e4', control: '#8a8a8e',
- text: '#1d1d1f', strong: '#000000', muted: '#575759', faint: '#6e6e70',
- accent: '#3b6a93', accentFill: '#3b6a93', onAccent: '#ffffff', danger: '#c4314b', success: '#2f8a18', warning: '#a07800',
- addBg: 'rgba(44,122,79,0.10)', delBg: 'rgba(196,49,75,0.09)',
+ scheme: 'light', background: '#f2f2f7', surface: '#ffffff', raised: '#ececf0', fill: '#e3e3e8', menu: '#ffffff', bubble: '#e4e6ea',
+ code: '#f6f6f8', inline: 'rgba(0,0,0,0.06)', border: 'rgba(60,60,67,0.13)', control: '#8a8a8e',
+ text: '#111113', strong: '#000000', muted: '#5c5c63', faint: '#7d7d85',
+ accent: '#3b6a93', accentFill: '#3b6a93', onAccent: '#ffffff', danger: '#c4314b', success: '#2f8a5a', warning: '#a46a00',
+ accentTint: 'rgba(59,106,147,0.11)', accentTint2: 'rgba(59,106,147,0.2)', successTint: 'rgba(47,138,90,0.12)', warningTint: 'rgba(196,132,0,0.13)', dangerTint: 'rgba(196,49,75,0.1)',
+ addBg: 'rgba(47,138,90,0.10)', delBg: 'rgba(196,49,75,0.09)', addWord: 'rgba(47,138,90,0.26)', delWord: 'rgba(196,49,75,0.24)',
+ glass: 'rgba(255,255,255,0.62)', glassHighlight: 'rgba(255,255,255,0.9)', glassEdge: 'rgba(0,0,0,0.06)', glassSelected: 'rgba(0,0,0,0.07)',
+ badge: '#d48a00', scrim: 'rgba(0,0,0,0.25)',
},
};
/** The dark palette, for code that runs outside React (tests, the status bar default). Screens use `useTheme`. */
export const colors = palettes.dark;
-export const space = {xs: 4, s: 8, m: 12, l: 16, xl: 24};
-export const radius = {s: 6, m: 10, l: 16};
-export const font = {body: 15, small: 13, tiny: 11, title: 17, large: 22, mono: Platform.OS === 'ios' ? 'Menlo' : 'monospace'};
-/** The type scale (size / line height). */
+/** Spacing. Text sits 20 pt from the screen edge (`margin`), cards 16 (`card`). */
+export const space = {xs: 4, s: 8, m: 12, l: 16, xl: 24, margin: 20, card: 16} as const;
+/** Shapes: a cell group 26, a card 24, a sheet 38, capsule buttons 25 (50 tall) and 18 (36 tall), a code well 16. */
+export const radius = {s: 6, m: 10, well: 16, card: 24, group: 26, sheet: 38, capsule: 25, small: 18} as const;
+export const size = {primary: 50, small: 36, glassCircle: 44, chatRow: 72, glyph: 36, tabBar: 62} as const;
+export const font = {mono: Platform.OS === 'ios' ? 'Menlo' : 'monospace'};
+/** The type scale (size / line height). Nothing is under 12. */
export const type = {
- micro: {fontSize: 11, lineHeight: 14}, caption: {fontSize: 12, lineHeight: 16}, label: {fontSize: 13, lineHeight: 17}, footnote: {fontSize: 14, lineHeight: 19},
- body: {fontSize: 16, lineHeight: 23}, headline: {fontSize: 18, lineHeight: 23}, title: {fontSize: 21, lineHeight: 28}, largeTitle: {fontSize: 26, lineHeight: 32},
+ largeTitle: {fontSize: 34, lineHeight: 41, fontWeight: '700'},
+ title1: {fontSize: 28, lineHeight: 34, fontWeight: '700'},
+ title2: {fontSize: 22, lineHeight: 28, fontWeight: '700'},
+ title3: {fontSize: 20, lineHeight: 25, fontWeight: '600'},
+ headline: {fontSize: 17, lineHeight: 22, fontWeight: '600'},
+ body: {fontSize: 17, lineHeight: 22},
+ prose: {fontSize: 17, lineHeight: 26},
+ callout: {fontSize: 16, lineHeight: 21},
+ subhead: {fontSize: 15, lineHeight: 20},
+ footnote: {fontSize: 13, lineHeight: 18},
+ caption: {fontSize: 12, lineHeight: 16},
+ code: {fontSize: 13, lineHeight: 21, fontFamily: font.mono},
+ codeBlock: {fontSize: 14, lineHeight: 21, fontFamily: font.mono},
} as const;
/** The smallest comfortable touch target (iOS 44 pt; Android rounds to 48 dp with hitSlop). */
export const touch = 44;
diff --git a/packages/mobile/src/timeline/useTimeline.ts b/packages/mobile/src/timeline/useTimeline.ts
index bbf5267f..c35ad20b 100644
--- a/packages/mobile/src/timeline/useTimeline.ts
+++ b/packages/mobile/src/timeline/useTimeline.ts
@@ -1,5 +1,5 @@
/** React bindings for the timeline store: the list follows the ids, each row follows only its own item. */
-import {useSyncExternalStore} from 'react';
+import {useCallback, useMemo, useSyncExternalStore} from 'react';
import type {MobileItem} from '../shared';
import type {TimelineStore} from './store';
@@ -7,3 +7,14 @@ export const useTimelineIds = (store: TimelineStore): readonly string[] => useSy
export function useTimelineItem(store: TimelineStore, id: string): MobileItem | undefined {
return useSyncExternalStore(listener => store.subscribeItem(id, listener), () => store.getItem(id));
}
+/** Several items, followed together (a work capsule's steps): a new array only when one of them changed. */
+export function useTimelineItems(store: TimelineStore, ids: readonly string[]): MobileItem[] {
+ const key = ids.join('\n');
+ const cache = useMemo(() => ({items: [] as MobileItem[]}), [key]);
+ const subscribe = useCallback((listener: () => void) => { const offs = ids.map(id => store.subscribeItem(id, listener)); return () => { for (const off of offs) off(); }; }, [store, key]);
+ return useSyncExternalStore(subscribe, () => {
+ const now = ids.map(id => store.getItem(id)).filter((item): item is MobileItem => Boolean(item));
+ if (now.length !== cache.items.length || now.some((item, index) => item !== cache.items[index])) cache.items = now;
+ return cache.items;
+ });
+}
diff --git a/packages/mobile/tests/approval-card.test.tsx b/packages/mobile/tests/approval-card.test.tsx
index 6b700790..ac490104 100644
--- a/packages/mobile/tests/approval-card.test.tsx
+++ b/packages/mobile/tests/approval-card.test.tsx
@@ -12,7 +12,7 @@ test('approve is sent once, settles to Approved with a haptic, and a failure bri
let release: () => void = () => undefined;
const connection = fakeConnection({'approval.respond': () => new Promise