diff --git a/docs/mobile/DESIGN.md b/docs/mobile/DESIGN.md index 0020854f..d9d2309c 100644 --- a/docs/mobile/DESIGN.md +++ b/docs/mobile/DESIGN.md @@ -1,6 +1,6 @@ # Muster mobile app: design -Status: phases 1 to 3 built, phase 4 (several computers, offline history and the outbox, native Markdown, tablets) built (issue #326); later phases planned below. This document is the plan of record for the phone app: how a phone reaches the +Status: phases 1 to 4 built, phase 5 (the v3 design, diff review with keep and undo, Stop) built (issue #326); later phases planned below. This document is the plan of record for the phone app: how a phone reaches the person's desktop Muster from anywhere, how the traffic is protected, which stack the app uses, the screens, the phases and the threat model. The acceptance cases live in [docs/spec/clauses/23-mobile.md](../spec/clauses/23-mobile.md). @@ -341,6 +341,20 @@ column capped at 760 and a Needs-you inspector, and every orientation allowed (2 WindowManager module and is deferred. On the desktop: rows mapped once per version for all sessions and only for watched chats, `remove` ops for deleted rows, and a fixed note on replies past the 64 KB item cap (23A to 23D). +**Phase 5: the v3 design and diff review (built).** The binding v3 design: tonal surfaces, the iOS type scale (nothing under +12 pt, prose 17 on 26, code 13 on 21), capsule buttons, three springs with Reduce Motion turning them into a 150 ms crossfade, +and glass (iOS 26 Liquid Glass through expo-glass-effect, a blur below it, a tonal surface on Android) on the tab bar, the +composer and toolbars (24A). Chats are two-line rows in Active and Earlier (24B); a turn's steps fold into one capsule with a live +line and the caret, and a finished run resolves into its summary (24C); Send turns into Stop (`chat.stop`, act only) (24D, 24M); +the composer shows its chips only while focused (24E); approvals lead with their question (24F); All clear, paired and +run-finished moments (24G, 24I); search sits in its own glass circle (24H). Diff review reuses the desktop's review domain: +`changes.list` (the chat's latest turn, as the changed-files card shows it), `changes.diff` (the desktop's own hunks with their +ids, named after their function, changed words marked, highlighted on the desktop with Shiki's JavaScript engine and the +desktop's themes as [dark, light] colour pairs, in pages of 400 lines), `changes.keep` and `changes.undo` (act only, access +checked again right before the write, a stale hash writes nothing) (24J to 24L). The phone shows a review ring and swipeable +files, an inline diff with one gutter and a glass hunk toolbar, and a split diff from 600 points wide (24N to 24P). The file +viewer, git actions and the terminal come next. + **Phase 3b: needs-you everywhere.** Push relay and generic pushes; Projects (tasks, runs, Inbox) read and act; a relay mounted in Muster Server. Acceptance: an approval on the desktop produces exactly one generic push whose payload holds no chat text; tapping it opens the card; approving from the card unblocks the run; revoking removes the push id. 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/CHANGELOG.md b/packages/agent-app/CHANGELOG.md index a6b0f7f3..fd4d8460 100644 --- a/packages/agent-app/CHANGELOG.md +++ b/packages/agent-app/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to Muster Agent. Each `## ` section becomes the not - **Pair a phone (first part of the Muster mobile app).** Settings › Integrations › Phone shows a QR that pairs a phone with this computer through a relay you set; the phone and the computer talk end to end encrypted (Noise), so the relay only ever forwards ciphertext. A new phone is read only: it lists your chats, opens one and watches the turn stream, and sees what needs you. Choose Can act for it to send, steer, approve or decline one request and answer questions from the phone; approving for a whole session stays on the computer. Revoke ends its sessions at once. The pairing code works once and expires after 5 minutes, and pairing needs the system keychain (#326). - **Start work from the phone (second part of the Muster mobile app).** A phone allowed to act can start a new chat in a folder or Project with the provider and model you pick, and attach photos and files: they travel through the same encrypted session in checked pieces (up to 20 MB each) and reach the agent as images and files, as if you had attached them on the computer. On the same Wi-Fi the phone now connects to the computer directly instead of through the relay, with the same encryption and the same checks, and falls back to the relay everywhere else; Settings › Integrations › Phone shows the addresses it uses and turns this off. Pairing on a phone is also steadier: a second scan or press while one is in flight no longer hides the check code, the pair screen is easier to read, and a `muster://pair` link opens the app and starts pairing. - **A phone app that stays smooth while agents stream (third part of the Muster mobile app).** The computer now sends a phone only what changed in the open chat (the new end of a reply, a status, a new row), numbered so the phone notices a missed piece and reloads the chat; the phone's chat is a virtualized list that re-renders only the streaming row. A heartbeat notices a link that died while the phone slept and reconnects at once. Paths inside your folders reach the phone relative to the folder, and the computer caps how many requests and how large a request one phone can send. +- **Review changes and stop a turn from the phone (fifth part of the Muster mobile app).** A phone sees the files the chat’s latest turn changed and reads each diff, highlighted by this computer and sent in pages so a long file opens at once; a phone allowed to act keeps or undoes a whole file or one change and stops a running turn, with access checked again right before each write. The phone app also gets its new look: two-line chats grouped into Active and Earlier, a glass tab bar, steps folded into one capsule with a live line of what the agent is doing, Send that turns into Stop, and clearer approvals. - **Several computers, offline reading and Markdown on the phone (fourth part of the Muster mobile app).** A phone can pair with more than one computer, switch between them from the computer pill or show all of them together, and each pairing keeps its own keys. The last chats it saw open with no connection, messages written offline go out once it reconnects (approvals always wait for the computer), and a computer that revokes the phone has its saved chats wiped from it. Replies render as native Markdown with code blocks you can copy, and tablets and landscape get a sidebar, chat and inspector. On this computer, the phone link now maps a streaming reply once for every phone watching (about 16 times less work while streaming), tells the phone when a message is removed, and says where a reply too long for the phone continues. - **GitLab merge requests and Bitbucket pull requests.** A folder whose remote is on GitLab (gitlab.com, or your own GitLab once you save a token for its host) or Bitbucket Cloud now gets the same summary card rows, Git tab and PR tab as GitHub: list, create (pushing the branch first), view, comment and merge. GitLab is labelled merge request with `!` numbers; its pipeline jobs are the checks, and a failed job's log opens in the app and feeds Fix failing checks. Bitbucket build statuses (including Pipelines) are its checks; their logs open on Bitbucket for now. Sign in to GitLab with `glab auth login`, or save a token in Settings › Integrations › Git hosts; Bitbucket takes a username and app password, or an access token. Tokens are encrypted and sent only to the host they were saved for. Review threads, line comments, reviews, reviewer requests and mark-ready stay GitHub-only and say so on the other hosts (#329). - **Android phones over USB in Devices.** A phone plugged in with USB debugging on is listed under Android with its maker and model and opens like an emulator, streamed through the same helper. A phone that has not allowed USB debugging yet is listed with how to fix it (accept the prompt on the phone). Install APK… on a connected phone picks an .apk and runs `adb install -r`. Without the Android SDK, an adb on PATH or from Homebrew is enough for phones; emulators still need the SDK. Muster never turns a USB phone off or rotates it (#363). 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/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..7dc58156 --- /dev/null +++ b/packages/agent-app/tests/mobile-phase5-326.test.ts @@ -0,0 +1,253 @@ +/** #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, 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); +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, onStop?: () => void): 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 () => { 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. + 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: 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'); + 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 => { + 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); 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; + 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/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/_layout.tsx b/packages/mobile/app/_layout.tsx index b085f7d5..d360e8e6 100644 --- a/packages/mobile/app/_layout.tsx +++ b/packages/mobile/app/_layout.tsx @@ -12,11 +12,13 @@ export default function Layout() { - + - + + + diff --git a/packages/mobile/app/changes.tsx b/packages/mobile/app/changes.tsx new file mode 100644 index 00000000..7a94fe03 --- /dev/null +++ b/packages/mobile/app/changes.tsx @@ -0,0 +1,15 @@ +import {Stack, useLocalSearchParams, useRouter} from 'expo-router'; +import {useComputerConnection} from '../src/connection/ConnectionProvider'; +import {ChangesScreen} from '../src/screens/ChangesScreen'; + +/** The chat's changed files; a file opens its diff. */ +export default function Changes() { + const {chat, computer} = useLocalSearchParams<{chat: string; computer?: string}>(); + const {connection, view} = useComputerConnection(computer || undefined); + const router = useRouter(); + if (!connection || !view || !chat) return null; + return <> + + router.push({pathname: '/diff', params: {chat, computer: view.id, path}})} /> + ; +} 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/diff.tsx b/packages/mobile/app/diff.tsx new file mode 100644 index 00000000..c9daf81d --- /dev/null +++ b/packages/mobile/app/diff.tsx @@ -0,0 +1,15 @@ +import {Stack, useLocalSearchParams} from 'expo-router'; +import {useComputerConnection} from '../src/connection/ConnectionProvider'; +import {DiffScreen} from '../src/screens/DiffScreen'; +import {fileName, folderOf} from '../src/screens/ChangesScreen'; + +/** One changed file's diff: its name as the title and its folder under it. */ +export default function Diff() { + const {chat, computer, path} = useLocalSearchParams<{chat: string; computer?: string; path: string}>(); + const {connection} = useComputerConnection(computer || undefined); + if (!connection || !chat || !path) return null; + return <> + + + ; +} 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/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 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 ? ( - -